Subfolder permissions: own access for a folder inside a share (F-DIR-9)
A subfolder (e.g. Family/Finances) can get its own list of users and groups
with Read or Read & write; nobody else gets in. Users can be set to No access
to keep them out of a listed group. The share's own access still applies.
How it works:
- POSIX ACLs on the subfolder and everything inside, with the same entries as
default ACL so new files inherit them. The kernel enforces them, so SMB, NFS
and local access behave the same (ADR-10).
- The subfolder is given to root (group kept), so whoever created it doesn't
keep owner rights to it.
- The share's create mask / directory mask get group rw / rwx when missing
(journaled smb.conf change, shown in the review). Samba's default 0744
becomes the ACL mask of new files and capped every named user at read:
reproduced with Samba 4.22 on CT 151; "inherit acls = yes" did not help.
- ACLs are written in the kernel's xattr format by internal/adapters/aclfs
(bytes checked against what setfacl stores). The walk uses an os.Root,
skips symlinks, and opens each item with openat + O_NOFOLLOW from its
parent: a share user swapping in a symlink can't redirect the root process.
setfacl -R isn't used because it works on paths. os.Root.OpenFile followed a
symlink despite O_NOFOLLOW (found by a test), hence the explicit openat.
- The ACLs on disk are the source of truth and are read back on every load;
hand changes are listed per subfolder. The app settings only list which
subfolders have rules.
- Removing a rule gives the tree what the folder above gives (its default
ACL, else its permission bits).
- Refused: personal folders, guest shares (force user), storage without ACLs
(greyed out with the reason and a "Why?" link to the limitation), rules
inside or above another rule (v1), more than 32 entries.
- The ACL change is recorded in the history (audit, not undoable; the review
says so); the smb.conf part is undoable as usual.
API: GET/PUT/DELETE /api/v1/shares/{name}/subfolders (PUT/DELETE with
?dry_run=1). UI: "Subfolders with their own access" card on the share page.
Tested: unit tests from acl(5)/kernel bytes (domain/acl 98%), service tests on
real ACLs in a temp dir (92%), adapter (85%), API via the harness, 16 mutants
all caught; e2e on CT 151 (desktop + phone); smbclient checks on CT 151 (ZFS
with ACLs; no-ACL dataset refused) and VM 152 (XFS, ext4; virtiofs refused).
Total coverage 76.8% (minimum raised to 76.0).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f9c30b458b
commit
8dabb0bd16
35 files changed
+3166
-28
No files matched your search
+5
-2
@@ -1,8 +1,8 @@
|
||||
# Minimum test coverage in %, checked by scripts/coverage-check.sh in CI.
|
||||
# Raise a number when coverage went up (CI prints the new value); never lower it
|
||||
# without a reason in the commit message.
|
||||
total 75.0
|
||||
internal/server 82.0
|
||||
total 76.0
|
||||
internal/server 83.0
|
||||
internal/auth 93.0
|
||||
internal/domain/share 89.0
|
||||
internal/rootfs 83.0
|
||||
@@ -10,3 +10,6 @@ internal/adapters/osfs 79.0
|
||||
internal/format/smbconf 77.0
|
||||
internal/format/exports 97.0
|
||||
internal/app/accounts 78.0
|
||||
internal/domain/acl 98.0
|
||||
internal/app/subfolders 92.0
|
||||
internal/adapters/aclfs 85.0
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"sharestead/internal/adapters/aclfs"
|
||||
"sharestead/internal/adapters/configstore"
|
||||
"sharestead/internal/adapters/execrun"
|
||||
"sharestead/internal/adapters/osfs"
|
||||
@@ -34,6 +35,7 @@ import (
|
||||
svcs "sharestead/internal/app/services"
|
||||
"sharestead/internal/app/settings"
|
||||
"sharestead/internal/app/shares"
|
||||
"sharestead/internal/app/subfolders"
|
||||
"sharestead/internal/app/updates"
|
||||
"sharestead/internal/auth"
|
||||
"sharestead/internal/domain/account"
|
||||
@@ -197,6 +199,8 @@ func run(listen, dataDir, adminGroup string, log *slog.Logger) error {
|
||||
Updates: updatesSvc,
|
||||
Capabilities: capabilitiesSvc,
|
||||
Limitations: limitationsSvc,
|
||||
Subfolders: &subfolders.Service{Shares: editor, Tree: aclfs.FS{}, Names: aclfs.Names{}, Settings: appSettings,
|
||||
Storage: func(ctx context.Context) (capabilities.Report, error) { return capabilitiesSvc.Storage(ctx, false) }},
|
||||
Diagnostics: &diagnostics.Service{
|
||||
Run: run, Version: version.String(), Commands: diagnostics.DefaultCommands,
|
||||
Files: []string{paths.SMBConf, paths.Exports, "/etc/nfs.conf", dlnaConf, "/etc/os-release",
|
||||
|
||||
@@ -166,6 +166,19 @@ The app never changes filesystem properties of the host (e.g. ZFS `acltype`); it
|
||||
|
||||
**Both modes are first-class.** Mode A is not an error: Sharestead is complete for share-level access. Features that need mode B (subfolder access, F-DIR-9; read-only on disk for NFS/FTP) are shown **greyed out with the reason** (what is missing and where it would change, no commands; F-MON-11), never hidden silently. When a folder switches from A to B (re-check), existing shares keep working; the disk check offers to add the matching ACLs.
|
||||
|
||||
**Subfolder permissions (F-DIR-9), built 2026-11-30:**
|
||||
|
||||
| Part | Design |
|
||||
|---|---|
|
||||
| On disk | POSIX ACLs on the subfolder and everything inside: each listed user/group gets `rwx` (Read & write) or `r-x` (Read), files without `x` unless already executable; users can get `---` (No access) to override a listed group (named user entries win in acl(5)); owning group and others `---`; folders also get the same entries as default ACL, so new files inherit them. The subfolder itself is given to root (group kept), so whoever created it doesn't keep owner rights |
|
||||
| Samba | no `inherit acls`; instead the share's `create mask` / `directory mask` get group `rw` / `rwx` (journaled smb.conf change, shown in the review). Reason: the group bits of Samba's create mode become the ACL mask, and the default 0744 capped every named user at read (tested, Samba 4.22) |
|
||||
| Writing | `internal/adapters/aclfs` writes the kernel's xattr format itself (`system.posix_acl_access/default`, bytes checked against setfacl's), walking the tree through an `os.Root`, skipping symlinks and opening each item with `O_NOFOLLOW` — a share user swapping in a symlink can't redirect the root process. No `setfacl -R` (path-based, follows swapped directories) |
|
||||
| Source of truth | the ACLs on disk, read back on every page load; hand changes are listed per subfolder ("Changed outside Sharestead"). The app settings only list which subfolders have rules (`subfolders`: share → paths) |
|
||||
| Removing | the subfolder tree gets what the folder above gives: its default ACL if it has one, else its permission bits |
|
||||
| Refused | personal folders, guest shares (`force user`), folders without ACLs (greyed out, *Why?* → limitation `acl-off:<folder>`), rules inside or above another rule (v1), more than 32 entries |
|
||||
| History | the smb.conf change is undoable as usual; the ACL change is recorded (audit), not undoable — the review says so |
|
||||
| Known limits | owners keep owner rights to their own files inside (they can also change those files' permissions); a program that `chmod`s a file (e.g. macOS over SMB with Unix permissions) can narrow its mask — saving the rule again repairs it; "Everyone else" is always *No access* in v1 |
|
||||
|
||||
- When a share's existing parameters can't be shown in this model (e.g. complex `%`-macros), the access screen switches to **"Custom — edit in Advanced"** instead of guessing.
|
||||
- The **disk check** compares share access with owner/mode/ACLs and offers a one-click fix ("Make the folder writable for group *family*").
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ All text/background pairs were checked to ≥ 4.5:1 (2026-11-29).
|
||||
| `.btn` (`primary`, `danger`, `sm`), `.linkish` | actions | one primary button per form; links look like links (underlined) |
|
||||
| `table.responsive` | lists | becomes cards on phones (`data-label` per cell) |
|
||||
| `SortHeader` | sortable list columns | WAI-ARIA sortable table: button in the `<th>`, `aria-sort` only on the sorted column; on phones a "Sort by" row of chips. Empty values sort last |
|
||||
| `SubfolderCard` | subfolders with their own access, on the share page (F-DIR-9) | list with pills per user/group + "everyone else · no access"; folder picker inside the share; LevelPicker (No access only for users); review shows item count and smb.conf diff; not possible: greyed with reason and *Why?* |
|
||||
| `LimitationCard` | a limitation (F-MON-11) on the Problems page | info colour, not warning; what isn't available, why, what would change it (no commands); *Understood* / *Show again* |
|
||||
| `Pager` | long lists | 50 rows per page; "51–100 of 312", Previous, page numbers (first, last, two around the current), Next; `aria-current="page"` |
|
||||
| list + detail pages | every object type (shares, users, groups) | list: `PageHeader` with search + "+ New …", table with linked names, sortable columns, `Pager`; detail `#/<type>/<name>`: one card per topic, delete in a `.danger-zone` with `ConfirmByName` |
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Sharestead works in the **basic case** on any supported system. Some features need more from
|
||||
the system (or from the Proxmox host). Sharestead checks this itself: the *System* page shows,
|
||||
per storage folder, what works, and features that can't work are **greyed out with the reason
|
||||
and the command to enable them**.
|
||||
and what would have to change**.
|
||||
|
||||
## Always needed
|
||||
|
||||
@@ -56,6 +56,20 @@ mounted into a Proxmox container).
|
||||
|
||||
Existing files keep their permissions; Sharestead offers to add matching ACLs to existing shares.
|
||||
|
||||
## Subfolder permissions: what to know
|
||||
|
||||
Set on the share page → *Subfolders with their own access*. Only the users and groups listed get
|
||||
into the subfolder; the share's own access still applies on top.
|
||||
|
||||
| Topic | Behaviour |
|
||||
|---|---|
|
||||
| Protocols | enforced by the filesystem, so the same for SMB, NFS and anything on the server |
|
||||
| Existing files | get the new permissions when the rule is saved (can take a while for many files) |
|
||||
| The share's create masks | Sharestead gives new files group read & write (`create mask`, `directory mask`), shown in the review; without it, people with *Read & write* couldn't change each other's new files |
|
||||
| Owners | whoever owns a file inside keeps owner rights to it |
|
||||
| Programs that change permissions | (e.g. a Mac with Unix permissions over SMB, `chmod` on the server) can narrow a single file; saving the rule again repairs it |
|
||||
| Not possible | personal folders, guest shares, a rule inside or above another rule |
|
||||
|
||||
## Protocols don't all enforce the same rules
|
||||
|
||||
Access is set **once per share** and applies to every protocol. But protocols differ:
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
// Package aclfs reads and sets POSIX ACLs on folder trees. It runs as root
|
||||
// inside folders that users can write to, so every step stays inside the
|
||||
// folder: the tree is opened as an os.Root, symlinks are skipped, and each
|
||||
// item is opened with O_NOFOLLOW before its ACL is written through the open
|
||||
// file, so a symlink swapped in during the walk can't redirect a change.
|
||||
package aclfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"sharestead/internal/domain/acl"
|
||||
)
|
||||
|
||||
// ErrNotSupported is returned when the filesystem has no POSIX ACLs.
|
||||
var ErrNotSupported = errors.New("this filesystem doesn't support POSIX ACLs")
|
||||
|
||||
// ErrNotDir is returned when the folder is missing or not a real folder.
|
||||
var ErrNotDir = errors.New("not a folder")
|
||||
|
||||
// State is a folder's owner, mode and ACLs. Access is built from the mode
|
||||
// when the folder has no ACL of its own; Default is nil without one.
|
||||
type State struct {
|
||||
UID, GID uint32
|
||||
Mode uint32
|
||||
Access acl.ACL
|
||||
Default acl.ACL
|
||||
}
|
||||
|
||||
// Report says what Apply did.
|
||||
type Report struct {
|
||||
Items int // folders and files changed
|
||||
Failed int // items that couldn't be changed
|
||||
FirstError string // the first of those errors
|
||||
}
|
||||
|
||||
// FS works on the real filesystem.
|
||||
type FS struct{}
|
||||
|
||||
// openTree opens base/rel as a root; rel must be a real folder (no symlink).
|
||||
func openTree(base, rel string) (*os.Root, error) {
|
||||
root, err := os.OpenRoot(base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
st, err := root.Lstat(rel)
|
||||
if errors.Is(err, fs.ErrNotExist) || (err == nil && !st.IsDir()) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrNotDir, rel)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return root.OpenRoot(rel)
|
||||
}
|
||||
|
||||
// Read returns the state of the folder base/rel.
|
||||
func (FS) Read(base, rel string) (State, error) {
|
||||
tree, err := openTree(base, rel)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
defer tree.Close()
|
||||
f, err := tree.OpenFile(".", os.O_RDONLY|syscall.O_DIRECTORY, 0)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
defer f.Close()
|
||||
return readFile(f)
|
||||
}
|
||||
|
||||
func readFile(f *os.File) (State, error) {
|
||||
var st unix.Stat_t
|
||||
var s State
|
||||
err := control(f, func(fd int) error {
|
||||
if err := unix.Fstat(fd, &st); err != nil {
|
||||
return err
|
||||
}
|
||||
s = State{UID: st.Uid, GID: st.Gid, Mode: st.Mode}
|
||||
var err error
|
||||
if s.Access, err = getACL(fd, acl.XattrAccess); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Access == nil {
|
||||
s.Access = acl.FromMode(st.Mode)
|
||||
}
|
||||
if st.Mode&unix.S_IFMT == unix.S_IFDIR {
|
||||
s.Default, err = getACL(fd, acl.XattrDefault)
|
||||
}
|
||||
return err
|
||||
})
|
||||
return s, err
|
||||
}
|
||||
|
||||
func getACL(fd int, name string) (acl.ACL, error) {
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
n, err := unix.Fgetxattr(fd, name, buf)
|
||||
switch {
|
||||
case errors.Is(err, unix.ENODATA):
|
||||
return nil, nil
|
||||
case errors.Is(err, unix.ERANGE):
|
||||
buf = make([]byte, 2*len(buf))
|
||||
continue
|
||||
case unsupported(err):
|
||||
return nil, nil // no ACLs: the mode bits are all there is
|
||||
case err != nil:
|
||||
return nil, err
|
||||
}
|
||||
return acl.Decode(buf[:n])
|
||||
}
|
||||
}
|
||||
|
||||
func unsupported(err error) bool {
|
||||
return errors.Is(err, unix.EOPNOTSUPP) || errors.Is(err, unix.ENOTSUP)
|
||||
}
|
||||
|
||||
// control runs fn with the file's descriptor (keeps the file non-blocking).
|
||||
func control(f *os.File, fn func(fd int) error) error {
|
||||
rc, err := f.SyscallConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var inner error
|
||||
if err := rc.Control(func(fd uintptr) { inner = fn(int(fd)) }); err != nil {
|
||||
return err
|
||||
}
|
||||
return inner
|
||||
}
|
||||
|
||||
// Count returns the number of folders and files in base/rel (the folder
|
||||
// included), stopping at limit; more reports that there are more.
|
||||
func (FS) Count(ctx context.Context, base, rel string, limit int) (n int, more bool, err error) {
|
||||
tree, err := openTree(base, rel)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
defer tree.Close()
|
||||
stop := errors.New("stop")
|
||||
err = fs.WalkDir(tree.FS(), ".", func(p string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil //nolint:nilerr // unreadable items are counted by Apply as failed
|
||||
}
|
||||
if !changeable(d) {
|
||||
return nil
|
||||
}
|
||||
if n >= limit {
|
||||
more = true
|
||||
return stop
|
||||
}
|
||||
n++
|
||||
return ctx.Err()
|
||||
})
|
||||
if errors.Is(err, stop) {
|
||||
err = nil
|
||||
}
|
||||
return n, more, err
|
||||
}
|
||||
|
||||
// changeable reports items whose ACL is set: folders and regular files.
|
||||
// Symlinks have no ACL of their own; devices, pipes and sockets are left as
|
||||
// they are.
|
||||
func changeable(d fs.DirEntry) bool { return d.IsDir() || d.Type().IsRegular() }
|
||||
|
||||
// Apply gives base/rel and everything in it the ACLs of t: folders get
|
||||
// t.ForDir, files t.ForFile. With ownerRoot the folder itself is given to
|
||||
// root first (its group stays), so whoever created it doesn't keep owner
|
||||
// rights to it. It continues past items it can't change and reports them;
|
||||
// it stops at once when the filesystem has no ACLs.
|
||||
func (FS) Apply(ctx context.Context, base, rel string, t acl.Template, ownerRoot bool) (Report, error) {
|
||||
tree, err := openTree(base, rel)
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
defer tree.Close()
|
||||
var r Report
|
||||
dirAccess, dirDefault := t.ForDir()
|
||||
walkErr := fs.WalkDir(tree.FS(), ".", func(p string, d fs.DirEntry, err error) error {
|
||||
if cerr := ctx.Err(); cerr != nil {
|
||||
return cerr
|
||||
}
|
||||
if err != nil {
|
||||
r.fail(p, err)
|
||||
return nil
|
||||
}
|
||||
if !changeable(d) {
|
||||
return nil
|
||||
}
|
||||
err = applyOne(tree, p, p == "." && ownerRoot, dirAccess, dirDefault, t)
|
||||
if errors.Is(err, ErrNotSupported) {
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
r.fail(p, err)
|
||||
return nil
|
||||
}
|
||||
r.Items++
|
||||
return nil
|
||||
})
|
||||
return r, walkErr
|
||||
}
|
||||
|
||||
func (r *Report) fail(p string, err error) {
|
||||
if r.Failed == 0 {
|
||||
r.FirstError = p + ": " + err.Error()
|
||||
}
|
||||
r.Failed++
|
||||
}
|
||||
|
||||
func applyOne(tree *os.Root, p string, chown bool, dirAccess, dirDefault acl.ACL, t acl.Template) error {
|
||||
f, err := openNoFollow(tree, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
return control(f, func(fd int) error {
|
||||
var st unix.Stat_t
|
||||
if err := unix.Fstat(fd, &st); err != nil {
|
||||
return err
|
||||
}
|
||||
isDir := st.Mode&unix.S_IFMT == unix.S_IFDIR
|
||||
if !isDir && st.Mode&unix.S_IFMT != unix.S_IFREG {
|
||||
return nil // replaced by something else during the walk
|
||||
}
|
||||
if chown {
|
||||
if err := unix.Fchown(fd, 0, -1); err != nil {
|
||||
return fmt.Errorf("giving the folder to root: %w", err)
|
||||
}
|
||||
}
|
||||
access := t.ForFile(st.Mode)
|
||||
if isDir {
|
||||
access = dirAccess
|
||||
}
|
||||
if err := setACL(fd, acl.XattrAccess, access); err != nil {
|
||||
return err
|
||||
}
|
||||
if !isDir {
|
||||
return nil
|
||||
}
|
||||
if dirDefault == nil {
|
||||
if err := unix.Fremovexattr(fd, acl.XattrDefault); err != nil && !errors.Is(err, unix.ENODATA) && !unsupported(err) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return setACL(fd, acl.XattrDefault, dirDefault)
|
||||
})
|
||||
}
|
||||
|
||||
// openNoFollow opens p inside tree without following a symlink in its last
|
||||
// part: the parent is opened through the root (which keeps every step
|
||||
// inside it), the item itself with openat and O_NOFOLLOW.
|
||||
func openNoFollow(tree *os.Root, p string) (*os.File, error) {
|
||||
if p == "." {
|
||||
return tree.OpenFile(".", os.O_RDONLY|syscall.O_DIRECTORY, 0)
|
||||
}
|
||||
parent, err := tree.OpenFile(path.Dir(p), os.O_RDONLY|syscall.O_DIRECTORY, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer parent.Close()
|
||||
var fd int
|
||||
err = control(parent, func(pfd int) error {
|
||||
var err error
|
||||
fd, err = unix.Openat(pfd, path.Base(p), unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return os.NewFile(uintptr(fd), p), nil
|
||||
}
|
||||
|
||||
func setACL(fd int, name string, a acl.ACL) error {
|
||||
b, err := a.Encode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = unix.Fsetxattr(fd, name, b, 0)
|
||||
if unsupported(err) {
|
||||
return ErrNotSupported
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package aclfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"sharestead/internal/domain/acl"
|
||||
)
|
||||
|
||||
// tree builds share/Finances with a file, a program, a subfolder, a pipe
|
||||
// and a symlink pointing outside the share. Tests skip when the
|
||||
// filesystem of the temp dir has no ACLs.
|
||||
func tree(t *testing.T) (base, outside string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
base = filepath.Join(dir, "share")
|
||||
outside = filepath.Join(dir, "outside.txt")
|
||||
must := func(err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
must(os.MkdirAll(filepath.Join(base, "Finances", "2026"), 0o770))
|
||||
must(os.WriteFile(filepath.Join(base, "Finances", "tax.pdf"), []byte("x"), 0o660))
|
||||
must(os.WriteFile(filepath.Join(base, "Finances", "2026", "run.sh"), []byte("x"), 0o770))
|
||||
must(os.WriteFile(outside, []byte("secret"), 0o600))
|
||||
must(os.Symlink(outside, filepath.Join(base, "Finances", "link")))
|
||||
must(unix.Mkfifo(filepath.Join(base, "Finances", "pipe"), 0o660))
|
||||
probe := acl.ACL{{Tag: acl.UserObj, Perm: acl.RWX}, {Tag: acl.User, ID: 0, Perm: acl.RX}, {Tag: acl.GroupObj}, {Tag: acl.Other}}
|
||||
b, _ := probe.Encode()
|
||||
if err := unix.Setxattr(base, acl.XattrAccess, b, 0); err != nil {
|
||||
t.Skipf("no POSIX ACLs in %s: %v", dir, err)
|
||||
}
|
||||
must(unix.Removexattr(base, acl.XattrAccess))
|
||||
for _, d := range []string{base, filepath.Join(base, "Finances"), filepath.Join(base, "Finances", "2026")} {
|
||||
must(os.Chmod(d, 0o770)) // independent of the umask
|
||||
}
|
||||
must(os.Chmod(filepath.Join(base, "Finances", "tax.pdf"), 0o660))
|
||||
must(os.Chmod(filepath.Join(base, "Finances", "2026", "run.sh"), 0o770))
|
||||
return base, outside
|
||||
}
|
||||
|
||||
var rule = acl.Template{Owner: acl.RWX, Users: map[uint32]acl.Perm{4242: acl.RWX, 4243: acl.RX}, Default: true}
|
||||
|
||||
func readAt(t *testing.T, p string, name string) acl.ACL {
|
||||
t.Helper()
|
||||
buf := make([]byte, 512)
|
||||
n, err := unix.Getxattr(p, name, buf)
|
||||
if errors.Is(err, unix.ENODATA) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(p, err)
|
||||
}
|
||||
a, err := acl.Decode(buf[:n])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestApplySetsTheTreeAndSkipsSymlinks(t *testing.T) {
|
||||
base, outside := tree(t)
|
||||
r, err := FS{}.Apply(context.Background(), base, "Finances", rule, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Finances, 2026, tax.pdf, run.sh — not the pipe, not the symlink.
|
||||
if r.Items != 4 || r.Failed != 0 {
|
||||
t.Errorf("report = %+v, want 4 items", r)
|
||||
}
|
||||
fin := filepath.Join(base, "Finances")
|
||||
if p, _ := readAt(t, fin, acl.XattrAccess).Get(acl.User, 4242); p != acl.RWX {
|
||||
t.Errorf("Finances user 4242 = %v", p)
|
||||
}
|
||||
if p, _ := readAt(t, filepath.Join(fin, "2026"), acl.XattrDefault).Get(acl.User, 4243); p != acl.RX {
|
||||
t.Errorf("2026 default for 4243 = %v, want r-x (inherited by new files)", p)
|
||||
}
|
||||
tax := readAt(t, filepath.Join(fin, "tax.pdf"), acl.XattrAccess)
|
||||
if p, _ := tax.Get(acl.User, 4242); p != acl.Read|acl.Write {
|
||||
t.Errorf("tax.pdf user 4242 = %v, want rw-", p)
|
||||
}
|
||||
if p, _ := readAt(t, filepath.Join(fin, "2026", "run.sh"), acl.XattrAccess).Get(acl.User, 4243); p != acl.RX {
|
||||
t.Errorf("run.sh user 4243 = %v, want r-x (programs stay runnable)", p)
|
||||
}
|
||||
// The kernel keeps the mode in step: the group bits show the mask, and
|
||||
// the owning group and others got nothing.
|
||||
st, _ := os.Stat(filepath.Join(fin, "tax.pdf"))
|
||||
if st.Mode().Perm() != 0o660 {
|
||||
t.Errorf("tax.pdf mode = %v, want 0660 (owner rw, mask rw, other none)", st.Mode().Perm())
|
||||
}
|
||||
if got := readAt(t, outside, acl.XattrAccess); got != nil {
|
||||
t.Errorf("the symlink target outside the share got an ACL: %v", got)
|
||||
}
|
||||
if st, _ := os.Stat(outside); st.Mode().Perm() != 0o600 {
|
||||
t.Errorf("outside file mode changed to %v", st.Mode().Perm())
|
||||
}
|
||||
if got := readAt(t, base, acl.XattrAccess); got != nil {
|
||||
t.Errorf("the share folder itself got an ACL: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadReturnsWhatApplySet(t *testing.T) {
|
||||
base, _ := tree(t)
|
||||
before, err := FS{}.Read(base, "Finances")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before.Access.Extended() || before.Default != nil {
|
||||
t.Errorf("before = %+v, want only the mode", before)
|
||||
}
|
||||
if p, _ := before.Access.Get(acl.GroupObj, 0); p != acl.RWX {
|
||||
t.Errorf("before group = %v, want rwx from mode 0770", p)
|
||||
}
|
||||
if _, err := (FS{}).Apply(context.Background(), base, "Finances", rule, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := FS{}.Read(base, "Finances")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.UID != uint32(os.Getuid()) || s.Mode&unix.S_IFDIR == 0 {
|
||||
t.Errorf("state = %+v", s)
|
||||
}
|
||||
if p, _ := s.Access.Get(acl.User, 4242); p != acl.RWX {
|
||||
t.Errorf("access 4242 = %v", p)
|
||||
}
|
||||
if p, _ := s.Default.Get(acl.User, 4243); p != acl.RX {
|
||||
t.Errorf("default 4243 = %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyInheritRemovesTheRule(t *testing.T) {
|
||||
base, _ := tree(t)
|
||||
ctx := context.Background()
|
||||
if _, err := (FS{}).Apply(ctx, base, "Finances", rule, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Back to what the share folder (0770, no ACL) gives.
|
||||
if _, err := (FS{}).Apply(ctx, base, "Finances", acl.Inherit(0o40770, nil), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fin := filepath.Join(base, "Finances")
|
||||
for _, p := range []string{fin, filepath.Join(fin, "2026")} {
|
||||
if a := readAt(t, p, acl.XattrAccess); a != nil {
|
||||
t.Errorf("%s still has an access ACL %v", p, a)
|
||||
}
|
||||
if a := readAt(t, p, acl.XattrDefault); a != nil {
|
||||
t.Errorf("%s still has a default ACL %v", p, a)
|
||||
}
|
||||
if st, _ := os.Stat(p); st.Mode().Perm() != 0o770 {
|
||||
t.Errorf("%s mode = %v, want 0770", p, st.Mode().Perm())
|
||||
}
|
||||
}
|
||||
if st, _ := os.Stat(filepath.Join(fin, "tax.pdf")); st.Mode().Perm() != 0o660 {
|
||||
t.Errorf("tax.pdf mode = %v, want 0660", st.Mode().Perm())
|
||||
}
|
||||
if st, _ := os.Stat(filepath.Join(fin, "2026", "run.sh")); st.Mode().Perm() != 0o770 {
|
||||
t.Errorf("run.sh mode = %v, want 0770", st.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCount(t *testing.T) {
|
||||
base, _ := tree(t)
|
||||
ctx := context.Background()
|
||||
n, more, err := FS{}.Count(ctx, base, "Finances", 100)
|
||||
if err != nil || n != 4 || more {
|
||||
t.Errorf("Count = %d %v %v, want 4 (folders and files only)", n, more, err)
|
||||
}
|
||||
n, more, err = FS{}.Count(ctx, base, "Finances", 2)
|
||||
if err != nil || n != 2 || !more {
|
||||
t.Errorf("Count limit 2 = %d %v %v", n, more, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefusesSymlinksAndMissingFolders(t *testing.T) {
|
||||
base, _ := tree(t)
|
||||
if err := os.Symlink(filepath.Dir(base), filepath.Join(base, "up")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
for _, rel := range []string{"up", "Finances/link", "nope", "Finances/tax.pdf"} {
|
||||
if _, err := (FS{}).Apply(ctx, base, rel, rule, false); !errors.Is(err, ErrNotDir) {
|
||||
t.Errorf("Apply %s: %v, want ErrNotDir", rel, err)
|
||||
}
|
||||
if _, err := (FS{}).Read(base, rel); !errors.Is(err, ErrNotDir) {
|
||||
t.Errorf("Read %s: %v, want ErrNotDir", rel, err)
|
||||
}
|
||||
if _, _, err := (FS{}).Count(ctx, base, rel, 10); !errors.Is(err, ErrNotDir) {
|
||||
t.Errorf("Count %s: %v, want ErrNotDir", rel, err)
|
||||
}
|
||||
}
|
||||
if _, err := (FS{}).Apply(ctx, base, "../x", rule, false); err == nil {
|
||||
t.Error("a path leaving the share must fail")
|
||||
}
|
||||
if _, err := (FS{}).Read(filepath.Join(base, "missing"), "x"); err == nil {
|
||||
t.Error("a missing share folder must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyStopsWhenCancelled(t *testing.T) {
|
||||
base, _ := tree(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := (FS{}).Apply(ctx, base, "Finances", rule, false); !errors.Is(err, context.Canceled) {
|
||||
t.Errorf("err = %v, want canceled", err)
|
||||
}
|
||||
if a := readAt(t, filepath.Join(base, "Finances"), acl.XattrAccess); a != nil {
|
||||
t.Errorf("changed after cancel: %v", a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyGivesTheFolderToRoot(t *testing.T) {
|
||||
if os.Getuid() != 0 {
|
||||
t.Skip("needs root (run with unshare -r)")
|
||||
}
|
||||
base, _ := tree(t)
|
||||
fin := filepath.Join(base, "Finances")
|
||||
if err := os.Chown(fin, 1234, 1234); err != nil {
|
||||
t.Skipf("can't chown here: %v", err)
|
||||
}
|
||||
if _, err := (FS{}).Apply(context.Background(), base, "Finances", rule, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, _ := FS{}.Read(base, "Finances")
|
||||
if s.UID != 0 || s.GID != 1234 {
|
||||
t.Errorf("owner %d:%d, want 0:1234 (group kept)", s.UID, s.GID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyFailsWithoutACLSupport(t *testing.T) {
|
||||
// /proc has no ACLs; opening it as a tree and writing fails cleanly.
|
||||
if _, err := (FS{}).Apply(context.Background(), "/proc/self", "fdinfo", rule, false); err == nil {
|
||||
t.Error("want an error on /proc")
|
||||
}
|
||||
}
|
||||
|
||||
// A symlink swapped in after the walk listed a real file: writing the ACL
|
||||
// must fail on the link instead of following it out of the share.
|
||||
func TestApplyOneDoesNotFollowASwappedInSymlink(t *testing.T) {
|
||||
base, outside := tree(t)
|
||||
tr, err := os.OpenRoot(filepath.Join(base, "Finances"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tr.Close()
|
||||
// The link points at a file inside the tree, so os.Root alone would allow it.
|
||||
if err := os.Symlink("tax.pdf", filepath.Join(base, "Finances", "swapped")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
access, def := rule.ForDir()
|
||||
if err := applyOne(tr, "swapped", false, access, def, rule); err == nil {
|
||||
t.Error("applyOne followed a symlink")
|
||||
}
|
||||
if got := readAt(t, filepath.Join(base, "Finances", "tax.pdf"), acl.XattrAccess); got != nil {
|
||||
t.Errorf("the link's target got an ACL: %v", got)
|
||||
}
|
||||
if got := readAt(t, outside, acl.XattrAccess); got != nil {
|
||||
t.Errorf("outside file got an ACL: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package aclfs
|
||||
|
||||
import (
|
||||
"os/user"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Names looks users and groups up in the system's account database.
|
||||
type Names struct{}
|
||||
|
||||
// UserID returns the uid of a user.
|
||||
func (Names) UserID(name string) (uint32, error) {
|
||||
u, err := user.Lookup(name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
id, err := strconv.ParseUint(u.Uid, 10, 32)
|
||||
return uint32(id), err
|
||||
}
|
||||
|
||||
// GroupID returns the gid of a group.
|
||||
func (Names) GroupID(name string) (uint32, error) {
|
||||
g, err := user.LookupGroup(name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
id, err := strconv.ParseUint(g.Gid, 10, 32)
|
||||
return uint32(id), err
|
||||
}
|
||||
|
||||
// UserName returns the name of a uid ("" if unknown).
|
||||
func (Names) UserName(id uint32) string {
|
||||
u, err := user.LookupId(strconv.FormatUint(uint64(id), 10))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return u.Username
|
||||
}
|
||||
|
||||
// GroupName returns the name of a gid ("" if unknown).
|
||||
func (Names) GroupName(id uint32) string {
|
||||
g, err := user.LookupGroupId(strconv.FormatUint(uint64(id), 10))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return g.Name
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package aclfs
|
||||
|
||||
import "testing"
|
||||
|
||||
// root (uid 0, gid 0) exists on every Linux system.
|
||||
func TestNames(t *testing.T) {
|
||||
n := Names{}
|
||||
if id, err := n.UserID("root"); err != nil || id != 0 {
|
||||
t.Errorf("UserID(root) = %d, %v", id, err)
|
||||
}
|
||||
if id, err := n.GroupID("root"); err != nil || id != 0 {
|
||||
t.Errorf("GroupID(root) = %d, %v", id, err)
|
||||
}
|
||||
if n.UserName(0) != "root" || n.GroupName(0) != "root" {
|
||||
t.Errorf("names of 0: %q %q", n.UserName(0), n.GroupName(0))
|
||||
}
|
||||
if _, err := n.UserID("no-such-user-sst"); err == nil {
|
||||
t.Error("unknown user: want an error")
|
||||
}
|
||||
if _, err := n.GroupID("no-such-group-sst"); err == nil {
|
||||
t.Error("unknown group: want an error")
|
||||
}
|
||||
if n.UserName(4000000000) != "" || n.GroupName(4000000000) != "" {
|
||||
t.Error("unknown IDs must give \"\"")
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,19 @@ func fingerprint(p health.Problem) string {
|
||||
// noUnixPermissions are filesystems without Linux owners and permissions.
|
||||
var noUnixPermissions = map[string]bool{"vfat": true, "msdos": true, "exfat": true, "ntfs": true, "ntfs3": true, "fuseblk": true}
|
||||
|
||||
// FolderID returns the ID of the limitation that keeps subfolder
|
||||
// permissions from working in a storage folder ("" when they work or the
|
||||
// check couldn't tell).
|
||||
func FolderID(f capabilities.Folder) string {
|
||||
switch {
|
||||
case noUnixPermissions[f.FSType]:
|
||||
return IDNoUnixPerms + idSep + f.Path
|
||||
case f.ACL == capabilities.ACLNo:
|
||||
return IDACLOff + idSep + f.Path
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Service) current(ctx context.Context) []health.Problem {
|
||||
var out []health.Problem
|
||||
container := ""
|
||||
@@ -108,7 +121,7 @@ func (s *Service) current(ctx context.Context) []health.Problem {
|
||||
facts := []string{"filesystem " + f.FSType, "source " + f.Source}
|
||||
if noUnixPermissions[f.FSType] {
|
||||
out = append(out, health.Problem{
|
||||
ID: IDNoUnixPerms + idSep + f.Path, Severity: health.Info,
|
||||
ID: FolderID(f), Severity: health.Info,
|
||||
Title: f.Path + " has no Linux owners or permissions",
|
||||
Affected: []string{"Access per user can't be enforced on disk here; only the share rules in Samba apply", "Subfolder permissions aren't available"},
|
||||
Cause: "The filesystem " + f.FSType + " doesn't store Linux owners, permissions or ACLs.",
|
||||
@@ -119,7 +132,7 @@ func (s *Service) current(ctx context.Context) []health.Problem {
|
||||
}
|
||||
if f.ACL == capabilities.ACLNo {
|
||||
out = append(out, health.Problem{
|
||||
ID: IDACLOff + idSep + f.Path, Severity: health.Info,
|
||||
ID: FolderID(f), Severity: health.Info,
|
||||
Title: "Subfolder permissions aren’t available in " + f.Path,
|
||||
Affected: []string{"Shares in " + f.Path + " get access per share only; subfolders can’t have their own access"},
|
||||
Cause: f.Reason,
|
||||
|
||||
@@ -20,6 +20,10 @@ type Settings struct {
|
||||
// Acknowledged holds the limitations an admin marked as understood:
|
||||
// limitation ID → fingerprint of its facts when acknowledged.
|
||||
Acknowledged map[string]string `json:"acknowledged,omitempty"`
|
||||
// Subfolders lists the subfolders with their own access per share
|
||||
// (share name → paths relative to the share folder). Their access
|
||||
// itself lives on disk as ACLs.
|
||||
Subfolders map[string][]string `json:"subfolders,omitempty"`
|
||||
}
|
||||
|
||||
// HomeByDefaultOn reports whether new users get a personal folder by
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package shares
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"sharestead/internal/app/changes"
|
||||
"sharestead/internal/domain/share"
|
||||
)
|
||||
|
||||
// FolderInfo is what subfolder permissions need to know about a share.
|
||||
type FolderInfo struct {
|
||||
Path string
|
||||
SMB bool // has a Samba section
|
||||
Homes bool // Samba [homes]
|
||||
ForceUser string // every SMB connection acts as this account
|
||||
}
|
||||
|
||||
// Folder returns a share's folder and the Samba settings that decide
|
||||
// whether subfolder permissions can work in it.
|
||||
func (e *Editor) Folder(name string) (FolderInfo, error) {
|
||||
p, err := e.pathOf(name)
|
||||
if err != nil {
|
||||
return FolderInfo{}, err
|
||||
}
|
||||
f, _, err := e.readSMB()
|
||||
if err != nil {
|
||||
return FolderInfo{}, err
|
||||
}
|
||||
info := FolderInfo{Path: p}
|
||||
if f.HasSection(name) {
|
||||
info.SMB = true
|
||||
info.Homes = strings.EqualFold(name, "homes")
|
||||
info.ForceUser = share.ForceUser(f, name)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// ACLMasks makes Samba create files in the share with group permissions,
|
||||
// so subfolder ACLs keep working for files created later
|
||||
// (share.ACLMasks). An empty result means nothing had to change.
|
||||
func (e *Editor) ACLMasks(ctx context.Context, actor, name string, base Base, dryRun bool) (Result, error) {
|
||||
f, ver, err := e.readSMB()
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if !f.HasSection(name) {
|
||||
return Result{}, nil
|
||||
}
|
||||
changed, err := share.ACLMasks(f, name)
|
||||
if err != nil || !changed {
|
||||
return Result{}, err
|
||||
}
|
||||
return e.finish(ctx, actor, pending{
|
||||
writes: []changes.Write{{Path: e.Paths.SMBConf, Content: f.Bytes(), Version: ver}},
|
||||
summary: fmt.Sprintf("Share %s: new files keep group permissions (for subfolder permissions)", name),
|
||||
}, base, dryRun)
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
// Package subfolders is the use case "different access for a subfolder
|
||||
// inside a share" (F-DIR-9). Access is written as POSIX ACLs on the
|
||||
// subfolder and everything in it (ADR-10), so the kernel enforces it for
|
||||
// every protocol. The ACLs on disk are the source of truth; Sharestead only
|
||||
// remembers which subfolders have rules, to find them again.
|
||||
package subfolders
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"sharestead/internal/adapters/aclfs"
|
||||
"sharestead/internal/app/capabilities"
|
||||
"sharestead/internal/app/limitations"
|
||||
"sharestead/internal/app/settings"
|
||||
"sharestead/internal/app/shares"
|
||||
"sharestead/internal/domain/acl"
|
||||
"sharestead/internal/domain/share"
|
||||
)
|
||||
|
||||
// Errors (besides share.ErrInvalid, share.ErrUnsupported, share.ErrCustom,
|
||||
// shares.ErrNotFound and changes.ErrConflict).
|
||||
var (
|
||||
ErrNoACL = errors.New("subfolder permissions aren't available here")
|
||||
ErrRuleNotFound = errors.New("this subfolder has no own access")
|
||||
)
|
||||
|
||||
// MaxEntries is the most users and groups one subfolder can list.
|
||||
const MaxEntries = 32
|
||||
|
||||
// countLimit is how far the preview counts items.
|
||||
const countLimit = 1_000_000
|
||||
|
||||
// Entry is one user's or group's access to a subfolder.
|
||||
type Entry struct {
|
||||
Principal share.Principal `json:"principal"`
|
||||
Level share.Level `json:"level"`
|
||||
}
|
||||
|
||||
// Rule is a subfolder with its own access, as found on disk.
|
||||
type Rule struct {
|
||||
Path string `json:"path"` // relative to the share folder
|
||||
Entries []Entry `json:"entries"`
|
||||
// Custom lists what on disk differs from what Sharestead sets, in
|
||||
// plain words (changed by hand or by a program).
|
||||
Custom []string `json:"custom,omitempty"`
|
||||
Missing bool `json:"missing,omitempty"` // the folder is gone
|
||||
}
|
||||
|
||||
// Availability says whether subfolder permissions work for a share.
|
||||
type Availability struct {
|
||||
Available bool `json:"available"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
// Limitation is the ID of the matching entry on the Problems page.
|
||||
Limitation string `json:"limitation,omitempty"`
|
||||
}
|
||||
|
||||
// Info is a share's subfolder rules and whether new ones are possible.
|
||||
type Info struct {
|
||||
Availability
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
|
||||
// Result of a change: a preview (dry run) or what was done.
|
||||
type Result struct {
|
||||
shares.Result
|
||||
Items int `json:"items"` // folders and files (to be) changed
|
||||
More bool `json:"more,omitempty"` // more than Items (preview stops counting)
|
||||
Failed int `json:"failed,omitempty"`
|
||||
FirstError string `json:"first_error,omitempty"`
|
||||
Summary string `json:"summary"`
|
||||
}
|
||||
|
||||
// Shares is the part of the share editor this needs.
|
||||
type Shares interface {
|
||||
Folder(name string) (shares.FolderInfo, error)
|
||||
ACLMasks(ctx context.Context, actor, name string, base shares.Base, dryRun bool) (shares.Result, error)
|
||||
}
|
||||
|
||||
// Tree reads and sets ACLs on folder trees (adapter).
|
||||
type Tree interface {
|
||||
Read(base, rel string) (aclfs.State, error)
|
||||
Apply(ctx context.Context, base, rel string, t acl.Template, ownerRoot bool) (aclfs.Report, error)
|
||||
Count(ctx context.Context, base, rel string, limit int) (int, bool, error)
|
||||
}
|
||||
|
||||
// Names maps user and group names to IDs and back (adapter). The reverse
|
||||
// lookups return "" for unknown IDs.
|
||||
type Names interface {
|
||||
UserID(name string) (uint32, error)
|
||||
GroupID(name string) (uint32, error)
|
||||
UserName(id uint32) string
|
||||
GroupName(id uint32) string
|
||||
}
|
||||
|
||||
// Settings stores which subfolders have rules.
|
||||
type Settings interface {
|
||||
Get() (settings.Settings, error)
|
||||
Update(change func(*settings.Settings)) (settings.Settings, error)
|
||||
}
|
||||
|
||||
// Service manages subfolder rules.
|
||||
type Service struct {
|
||||
Shares Shares
|
||||
Tree Tree
|
||||
Names Names
|
||||
Settings Settings
|
||||
// Storage returns the storage folders and whether they have ACLs.
|
||||
Storage func(ctx context.Context) (capabilities.Report, error)
|
||||
// Timeout bounds applying a rule to a large tree (default 30 min).
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// share returns the folder of a share and whether rules are possible there.
|
||||
func (s *Service) share(ctx context.Context, name string) (shares.FolderInfo, Availability, error) {
|
||||
info, err := s.Shares.Folder(name)
|
||||
if err != nil {
|
||||
return info, Availability{}, err
|
||||
}
|
||||
switch {
|
||||
case info.Homes:
|
||||
return info, Availability{Reason: "Each personal folder belongs to its user; subfolder permissions are for shared folders."}, nil
|
||||
case info.ForceUser != "":
|
||||
return info, Availability{Reason: "Everyone in this share acts as the account " + info.ForceUser + " (guest share), so the system can’t tell people apart in its subfolders."}, nil
|
||||
}
|
||||
return info, s.support(ctx, info.Path), nil
|
||||
}
|
||||
|
||||
// support finds the storage folder that holds p and whether it has ACLs.
|
||||
func (s *Service) support(ctx context.Context, p string) Availability {
|
||||
if s.Storage == nil {
|
||||
return Availability{Available: true}
|
||||
}
|
||||
rep, err := s.Storage(ctx)
|
||||
if err != nil {
|
||||
return Availability{Reason: "The storage check failed: " + err.Error()}
|
||||
}
|
||||
var best *capabilities.Folder
|
||||
for i, f := range rep.Folders {
|
||||
if (p == f.Path || strings.HasPrefix(p, strings.TrimSuffix(f.Path, "/")+"/")) && (best == nil || len(f.Path) > len(best.Path)) {
|
||||
best = &rep.Folders[i]
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case best == nil:
|
||||
return Availability{Reason: "The share’s folder isn’t in a storage folder Sharestead checks (below /srv, /mnt, /media or /data)."}
|
||||
case best.ACL == capabilities.ACLYes:
|
||||
return Availability{Available: true}
|
||||
case best.ACL == capabilities.ACLUnknown:
|
||||
return Availability{Reason: "It isn’t known whether " + best.Path + " supports POSIX ACLs: " + best.Reason, Limitation: limitations.FolderID(*best)}
|
||||
}
|
||||
reason := best.Reason
|
||||
if reason == "" {
|
||||
reason = best.Path + " has no POSIX ACLs."
|
||||
}
|
||||
return Availability{Reason: reason, Limitation: limitations.FolderID(*best)}
|
||||
}
|
||||
|
||||
// List returns the rules of a share.
|
||||
func (s *Service) List(ctx context.Context, name string) (Info, error) {
|
||||
info, avail, err := s.share(ctx, name)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
out := Info{Availability: avail, Rules: []Rule{}}
|
||||
paths, err := s.paths(name)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
for _, rel := range paths {
|
||||
st, err := s.Tree.Read(info.Path, rel)
|
||||
switch {
|
||||
case errors.Is(err, aclfs.ErrNotDir):
|
||||
out.Rules = append(out.Rules, Rule{Path: rel, Entries: []Entry{}, Missing: true})
|
||||
case err != nil:
|
||||
out.Rules = append(out.Rules, Rule{Path: rel, Entries: []Entry{}, Custom: []string{"Couldn’t read the permissions: " + err.Error()}})
|
||||
default:
|
||||
out.Rules = append(out.Rules, s.describe(rel, st))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Service) paths(name string) ([]string, error) {
|
||||
st, err := s.Settings.Get()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := slices.Clone(st.Subfolders[name])
|
||||
sort.Strings(p)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// describe turns the ACLs of a rule's folder back into levels.
|
||||
func (s *Service) describe(rel string, st aclfs.State) Rule {
|
||||
r := Rule{Path: rel, Entries: []Entry{}}
|
||||
for _, e := range st.Access.Named() {
|
||||
p := Entry{Principal: share.Principal{Kind: share.KindUser, Name: s.Names.UserName(e.ID)}}
|
||||
if e.Tag == acl.Group {
|
||||
p.Principal = share.Principal{Kind: share.KindGroup, Name: s.Names.GroupName(e.ID)}
|
||||
}
|
||||
if p.Principal.Name == "" {
|
||||
p.Principal.Name = "#" + strconv.FormatUint(uint64(e.ID), 10)
|
||||
r.Custom = append(r.Custom, fmt.Sprintf("The %s with ID %d no longer exists.", p.Principal.Kind, e.ID))
|
||||
}
|
||||
eff := st.Access.Effective(e)
|
||||
switch eff {
|
||||
case acl.RWX:
|
||||
p.Level = share.LevelWrite
|
||||
case acl.RX:
|
||||
p.Level = share.LevelRead
|
||||
case 0:
|
||||
p.Level = share.LevelNone
|
||||
default:
|
||||
p.Level = share.LevelRead
|
||||
if eff&acl.Write != 0 {
|
||||
p.Level = share.LevelWrite
|
||||
}
|
||||
if eff&acl.Read == 0 {
|
||||
p.Level = share.LevelNone
|
||||
}
|
||||
r.Custom = append(r.Custom, fmt.Sprintf("%s has %s, which is neither Read nor Read & write.", p.Principal.Name, eff))
|
||||
}
|
||||
r.Entries = append(r.Entries, p)
|
||||
}
|
||||
sortEntries(r.Entries)
|
||||
if g, _ := st.Access.Get(acl.GroupObj, 0); st.Access.Effective(acl.Entry{Tag: acl.GroupObj, Perm: g}) != 0 {
|
||||
name := nameOr(s.Names.GroupName(st.GID), st.GID)
|
||||
r.Custom = append(r.Custom, fmt.Sprintf("The folder’s group %s also has access (%s).", name, st.Access.Effective(acl.Entry{Tag: acl.GroupObj, Perm: g})))
|
||||
}
|
||||
if o, _ := st.Access.Get(acl.Other, 0); o != 0 {
|
||||
r.Custom = append(r.Custom, fmt.Sprintf("Everyone else also has access (%s).", o))
|
||||
}
|
||||
if st.UID != 0 {
|
||||
r.Custom = append(r.Custom, "The folder belongs to "+nameOr(s.Names.UserName(st.UID), st.UID)+", who keeps owner rights to it.")
|
||||
}
|
||||
if st.Default == nil {
|
||||
r.Custom = append(r.Custom, "New files and folders don’t inherit these permissions.")
|
||||
} else if !sameNamed(st.Access, st.Default) {
|
||||
r.Custom = append(r.Custom, "New files and folders get different permissions than the folder.")
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func nameOr(name string, id uint32) string {
|
||||
if name == "" {
|
||||
return "ID " + strconv.FormatUint(uint64(id), 10)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func sameNamed(a, b acl.ACL) bool {
|
||||
an, bn := a.Named(), b.Named()
|
||||
if len(an) != len(bn) {
|
||||
return false
|
||||
}
|
||||
for _, e := range an {
|
||||
p, ok := b.Get(e.Tag, e.ID)
|
||||
if !ok || b.Effective(acl.Entry{Tag: e.Tag, ID: e.ID, Perm: p}) != a.Effective(e) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sortEntries(es []Entry) {
|
||||
sort.SliceStable(es, func(i, j int) bool {
|
||||
if es[i].Principal.Kind != es[j].Principal.Kind {
|
||||
return es[i].Principal.Kind == share.KindGroup
|
||||
}
|
||||
return es[i].Principal.Name < es[j].Principal.Name
|
||||
})
|
||||
}
|
||||
|
||||
// cleanRel validates a subfolder path relative to the share folder.
|
||||
func cleanRel(rel string) (string, error) {
|
||||
rel = strings.Trim(strings.TrimSpace(rel), "/")
|
||||
if rel == "" || strings.ContainsAny(rel, "\x00\n\r") {
|
||||
return "", fmt.Errorf("%w: choose a subfolder inside the share", share.ErrInvalid)
|
||||
}
|
||||
for _, seg := range strings.Split(rel, "/") {
|
||||
if seg == ".." || seg == "." {
|
||||
return "", fmt.Errorf("%w: %q — use a path inside the share, without “.” or “..”", share.ErrInvalid, rel)
|
||||
}
|
||||
}
|
||||
return path.Clean(rel), nil
|
||||
}
|
||||
|
||||
// template builds the ACL template of a rule: the listed users and groups
|
||||
// get their level, the owner (root after applying) full access, the owning
|
||||
// group and everyone else nothing.
|
||||
func (s *Service) template(entries []Entry) (acl.Template, error) {
|
||||
t := acl.Template{Owner: acl.RWX, Users: map[uint32]acl.Perm{}, Groups: map[uint32]acl.Perm{}, Default: true}
|
||||
if len(entries) > MaxEntries {
|
||||
return t, fmt.Errorf("%w: at most %d users and groups per subfolder — use a group", share.ErrInvalid, MaxEntries)
|
||||
}
|
||||
seen := map[share.Principal]bool{}
|
||||
someone := false
|
||||
for _, e := range entries {
|
||||
if seen[e.Principal] {
|
||||
return t, fmt.Errorf("%w: %s is listed twice", share.ErrInvalid, e.Principal.Name)
|
||||
}
|
||||
seen[e.Principal] = true
|
||||
var perm acl.Perm
|
||||
switch e.Level {
|
||||
case share.LevelWrite:
|
||||
perm, someone = acl.RWX, true
|
||||
case share.LevelRead:
|
||||
perm, someone = acl.RX, true
|
||||
case share.LevelNone:
|
||||
default:
|
||||
return t, fmt.Errorf("%w: level %q", share.ErrInvalid, e.Level)
|
||||
}
|
||||
switch e.Principal.Kind {
|
||||
case share.KindUser:
|
||||
id, err := s.Names.UserID(e.Principal.Name)
|
||||
if err != nil {
|
||||
return t, fmt.Errorf("%w: unknown user %q", share.ErrInvalid, e.Principal.Name)
|
||||
}
|
||||
t.Users[id] = perm
|
||||
case share.KindGroup:
|
||||
if e.Level == share.LevelNone {
|
||||
return t, fmt.Errorf("%w: group %s set to No access — anyone not listed has no access anyway; to keep one member out of a listed group, add that user with No access", share.ErrInvalid, e.Principal.Name)
|
||||
}
|
||||
id, err := s.Names.GroupID(e.Principal.Name)
|
||||
if err != nil {
|
||||
return t, fmt.Errorf("%w: unknown group %q", share.ErrInvalid, e.Principal.Name)
|
||||
}
|
||||
t.Groups[id] = perm
|
||||
default:
|
||||
return t, fmt.Errorf("%w: subfolder access is set for users and groups", share.ErrInvalid)
|
||||
}
|
||||
}
|
||||
if !someone {
|
||||
return t, fmt.Errorf("%w: give at least one user or group Read or Read & write", share.ErrInvalid)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func summary(name, rel string, entries []Entry) string {
|
||||
sorted := slices.Clone(entries)
|
||||
sortEntries(sorted)
|
||||
var parts []string
|
||||
for _, e := range sorted {
|
||||
lvl := map[share.Level]string{share.LevelWrite: "read & write", share.LevelRead: "read", share.LevelNone: "no access"}[e.Level]
|
||||
parts = append(parts, e.Principal.Name+" "+lvl)
|
||||
}
|
||||
return fmt.Sprintf("Share %s: subfolder %s — %s, nobody else", name, rel, strings.Join(parts, ", "))
|
||||
}
|
||||
|
||||
// Set gives a subfolder its own access (or changes it) and applies it to
|
||||
// everything inside. Everyone not listed has no access to the subfolder;
|
||||
// the share's own access still applies on top.
|
||||
func (s *Service) Set(ctx context.Context, actor, name, rel string, entries []Entry, base shares.Base, dryRun bool) (Result, error) {
|
||||
info, avail, err := s.share(ctx, name)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if info.Homes || info.ForceUser != "" {
|
||||
return Result{}, fmt.Errorf("%w: %s", share.ErrUnsupported, avail.Reason)
|
||||
}
|
||||
if !avail.Available {
|
||||
return Result{}, fmt.Errorf("%w: %s", ErrNoACL, avail.Reason)
|
||||
}
|
||||
if rel, err = cleanRel(rel); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
paths, err := s.paths(name)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
for _, p := range paths {
|
||||
if p != rel && (strings.HasPrefix(rel, p+"/") || strings.HasPrefix(p, rel+"/")) {
|
||||
return Result{}, fmt.Errorf("%w: %s already has its own access — a subfolder can’t have rules inside or above another one; change that one instead", share.ErrUnsupported, p)
|
||||
}
|
||||
}
|
||||
tpl, err := s.template(entries)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
n, more, err := s.Tree.Count(ctx, info.Path, rel, countLimit)
|
||||
if err != nil {
|
||||
return Result{}, folderErr(rel, err)
|
||||
}
|
||||
res := Result{Items: n, More: more, Summary: summary(name, rel, entries)}
|
||||
masks, err := s.Shares.ACLMasks(ctx, actor, name, base, dryRun)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
res.Result = masks
|
||||
if dryRun {
|
||||
return res, nil
|
||||
}
|
||||
if _, err := s.Settings.Update(func(st *settings.Settings) {
|
||||
if st.Subfolders == nil {
|
||||
st.Subfolders = map[string][]string{}
|
||||
}
|
||||
if !slices.Contains(st.Subfolders[name], rel) {
|
||||
st.Subfolders[name] = append(st.Subfolders[name], rel)
|
||||
}
|
||||
}); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
rep, err := s.apply(ctx, info.Path, rel, tpl, true)
|
||||
res.Items, res.More, res.Failed, res.FirstError = rep.Items, false, rep.Failed, rep.FirstError
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (s *Service) apply(ctx context.Context, base, rel string, t acl.Template, ownerRoot bool) (aclfs.Report, error) {
|
||||
timeout := s.Timeout
|
||||
if timeout == 0 {
|
||||
timeout = 30 * time.Minute
|
||||
}
|
||||
// A half-applied tree is worse than a slow request: leaving the page
|
||||
// doesn't stop it.
|
||||
actx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout)
|
||||
defer cancel()
|
||||
rep, err := s.Tree.Apply(actx, base, rel, t, ownerRoot)
|
||||
if errors.Is(err, aclfs.ErrNotSupported) {
|
||||
return rep, fmt.Errorf("%w: the filesystem refused POSIX ACLs — check again on the System page", ErrNoACL)
|
||||
}
|
||||
return rep, err
|
||||
}
|
||||
|
||||
func folderErr(rel string, err error) error {
|
||||
if errors.Is(err, aclfs.ErrNotDir) {
|
||||
return fmt.Errorf("%w: %s isn’t a folder in this share (or is a link)", share.ErrInvalid, rel)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove takes a subfolder's own access away: it and everything inside get
|
||||
// what the folder above gives again (its default ACL, else its permission
|
||||
// bits).
|
||||
func (s *Service) Remove(ctx context.Context, name, rel string, dryRun bool) (Result, error) {
|
||||
info, err := s.Shares.Folder(name)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if rel, err = cleanRel(rel); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
paths, err := s.paths(name)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if !slices.Contains(paths, rel) {
|
||||
return Result{}, fmt.Errorf("%w: %s", ErrRuleNotFound, rel)
|
||||
}
|
||||
res := Result{Summary: fmt.Sprintf("Share %s: subfolder %s has the share’s access again", name, rel)}
|
||||
forget := func() error {
|
||||
_, err := s.Settings.Update(func(st *settings.Settings) {
|
||||
st.Subfolders[name] = slices.DeleteFunc(st.Subfolders[name], func(p string) bool { return p == rel })
|
||||
if len(st.Subfolders[name]) == 0 {
|
||||
delete(st.Subfolders, name)
|
||||
}
|
||||
})
|
||||
return err
|
||||
}
|
||||
n, more, err := s.Tree.Count(ctx, info.Path, rel, countLimit)
|
||||
if errors.Is(err, aclfs.ErrNotDir) {
|
||||
// The folder is gone: only the entry is left to remove.
|
||||
res.Summary = fmt.Sprintf("Share %s: rule for the missing subfolder %s removed", name, rel)
|
||||
if dryRun {
|
||||
return res, nil
|
||||
}
|
||||
return res, forget()
|
||||
}
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
res.Items, res.More = n, more
|
||||
parent, err := s.Tree.Read(info.Path, path.Dir(rel))
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if dryRun {
|
||||
return res, nil
|
||||
}
|
||||
rep, err := s.apply(ctx, info.Path, rel, acl.Inherit(parent.Mode, parent.Default), false)
|
||||
res.Items, res.More, res.Failed, res.FirstError = rep.Items, false, rep.Failed, rep.FirstError
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
return res, forget()
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
package subfolders
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"sharestead/internal/adapters/aclfs"
|
||||
"sharestead/internal/app/capabilities"
|
||||
"sharestead/internal/app/settings"
|
||||
"sharestead/internal/app/shares"
|
||||
"sharestead/internal/domain/acl"
|
||||
"sharestead/internal/domain/share"
|
||||
)
|
||||
|
||||
// realTree is the real adapter; giving the folder to root needs root, so
|
||||
// that request is only recorded when the test runs as a normal user.
|
||||
type realTree struct {
|
||||
aclfs.FS
|
||||
ownerRoot []bool
|
||||
}
|
||||
|
||||
func (t *realTree) Apply(ctx context.Context, base, rel string, tpl acl.Template, ownerRoot bool) (aclfs.Report, error) {
|
||||
t.ownerRoot = append(t.ownerRoot, ownerRoot)
|
||||
return t.FS.Apply(ctx, base, rel, tpl, ownerRoot && os.Getuid() == 0)
|
||||
}
|
||||
|
||||
type names struct{}
|
||||
|
||||
var uids = map[string]uint32{"alex": 1004, "sam": 1005, "kim": 1006}
|
||||
var gids = map[string]uint32{"family": 1005, "parents": 2000}
|
||||
|
||||
func (names) UserID(n string) (uint32, error) {
|
||||
if id, ok := uids[n]; ok {
|
||||
return id, nil
|
||||
}
|
||||
return 0, fmt.Errorf("user: unknown user %s", n)
|
||||
}
|
||||
func (names) GroupID(n string) (uint32, error) {
|
||||
if id, ok := gids[n]; ok {
|
||||
return id, nil
|
||||
}
|
||||
return 0, fmt.Errorf("group: unknown group %s", n)
|
||||
}
|
||||
func (names) UserName(id uint32) string {
|
||||
for n, i := range uids {
|
||||
if i == id {
|
||||
return n
|
||||
}
|
||||
}
|
||||
if id == uint32(os.Getuid()) {
|
||||
return "me"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func (names) GroupName(id uint32) string {
|
||||
for n, i := range gids {
|
||||
if i == id {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type fakeShares struct {
|
||||
infos map[string]shares.FolderInfo
|
||||
masks []bool // dryRun of each ACLMasks call
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeShares) Folder(name string) (shares.FolderInfo, error) {
|
||||
i, ok := f.infos[name]
|
||||
if !ok {
|
||||
return i, fmt.Errorf("%w: %q", shares.ErrNotFound, name)
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
func (f *fakeShares) ACLMasks(_ context.Context, _, _ string, _ shares.Base, dryRun bool) (shares.Result, error) {
|
||||
f.masks = append(f.masks, dryRun)
|
||||
return shares.Result{Versions: map[string]string{"/etc/samba/smb.conf": "v1"}}, f.err
|
||||
}
|
||||
|
||||
type memFiles struct {
|
||||
mu sync.Mutex
|
||||
m map[string][]byte
|
||||
}
|
||||
|
||||
func (m *memFiles) ReadFile(p string) ([]byte, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
b, ok := m.m[p]
|
||||
if !ok {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
func (m *memFiles) WriteFile(p string, b []byte) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.m[p] = b
|
||||
return nil
|
||||
}
|
||||
|
||||
type world struct {
|
||||
svc *Service
|
||||
shares *fakeShares
|
||||
tree *realTree
|
||||
family string // folder of the share "Family"
|
||||
report capabilities.Report
|
||||
}
|
||||
|
||||
// newWorld: share Family (/…/family, ACLs yes) with Finances, Photos and
|
||||
// Photos/2026; Noacl in a folder without ACLs; Public is a guest share.
|
||||
func newWorld(t *testing.T) *world {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
family := filepath.Join(dir, "storage", "family")
|
||||
for _, d := range []string{"Finances/2026", "Photos/2026"} {
|
||||
if err := os.MkdirAll(filepath.Join(family, d), 0o770); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, d := range []string{family, filepath.Join(family, "Finances"), filepath.Join(family, "Finances", "2026"), filepath.Join(family, "Photos")} {
|
||||
if err := os.Chmod(d, 0o770); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(family, "Finances", "tax.pdf"), []byte("x"), 0o660); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe, _ := acl.ACL{{Tag: acl.UserObj, Perm: acl.RWX}, {Tag: acl.User, ID: 1, Perm: acl.RX}, {Tag: acl.GroupObj}, {Tag: acl.Other}}.Encode()
|
||||
if err := unix.Setxattr(family, acl.XattrAccess, probe, 0); err != nil {
|
||||
t.Skipf("no POSIX ACLs in the temp dir: %v", err)
|
||||
}
|
||||
_ = unix.Removexattr(family, acl.XattrAccess)
|
||||
_ = os.Chmod(family, 0o770)
|
||||
w := &world{
|
||||
family: family,
|
||||
shares: &fakeShares{infos: map[string]shares.FolderInfo{
|
||||
"Family": {Path: family, SMB: true},
|
||||
"Noacl": {Path: filepath.Join(dir, "noacl", "x"), SMB: true},
|
||||
"Public": {Path: family, SMB: true, ForceUser: "nobody"},
|
||||
"homes": {Path: filepath.Join(dir, "storage", "homes", "%S"), SMB: true, Homes: true},
|
||||
"Away": {Path: "/elsewhere/away", SMB: true},
|
||||
}},
|
||||
tree: &realTree{},
|
||||
report: capabilities.Report{Folders: []capabilities.Folder{
|
||||
{Path: filepath.Join(dir, "storage"), FSType: "tmpfs", ACL: capabilities.ACLYes},
|
||||
{Path: filepath.Join(dir, "noacl"), FSType: "zfs", ACL: capabilities.ACLNo, Reason: "This filesystem (zfs) has POSIX ACLs switched off."},
|
||||
}},
|
||||
}
|
||||
w.svc = &Service{
|
||||
Shares: w.shares,
|
||||
Tree: w.tree,
|
||||
Names: names{},
|
||||
Settings: &settings.Store{Files: &memFiles{m: map[string][]byte{}}, Path: "/settings.json"},
|
||||
Storage: func(context.Context) (capabilities.Report, error) { return w.report, nil },
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func user(n string, l share.Level) Entry {
|
||||
return Entry{Principal: share.Principal{Kind: share.KindUser, Name: n}, Level: l}
|
||||
}
|
||||
func group(n string, l share.Level) Entry {
|
||||
return Entry{Principal: share.Principal{Kind: share.KindGroup, Name: n}, Level: l}
|
||||
}
|
||||
|
||||
func access(t *testing.T, p string) acl.ACL {
|
||||
t.Helper()
|
||||
buf := make([]byte, 512)
|
||||
n, err := unix.Getxattr(p, acl.XattrAccess, buf)
|
||||
if errors.Is(err, unix.ENODATA) {
|
||||
return nil // only the mode bits
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", p, err)
|
||||
}
|
||||
a, err := acl.Decode(buf[:n])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
var ctx = context.Background()
|
||||
|
||||
// F-DIR-9: "Family/Finances only for alex" — set, read back, applied to
|
||||
// everything inside, the share made ready for new files.
|
||||
func TestSetRuleAndListIt(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
entries := []Entry{user("alex", share.LevelWrite), user("kim", share.LevelRead), group("parents", share.LevelWrite), user("sam", share.LevelNone)}
|
||||
|
||||
prev, err := w.svc.Set(ctx, "admin", "Family", "/Finances/", entries, nil, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prev.Items != 3 || prev.More || prev.Versions == nil {
|
||||
t.Errorf("preview = %+v, want 3 items (Finances, 2026, tax.pdf) and the smb.conf preview", prev)
|
||||
}
|
||||
if !strings.Contains(prev.Summary, "Finances") || !strings.Contains(prev.Summary, "alex read & write") || !strings.Contains(prev.Summary, "nobody else") {
|
||||
t.Errorf("summary = %q", prev.Summary)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(w.family, "Finances")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(access(t, filepath.Join(w.family, "Finances")).Named()) != 0 {
|
||||
t.Fatal("a preview must not change anything on disk")
|
||||
}
|
||||
if info, _ := w.svc.List(ctx, "Family"); len(info.Rules) != 0 {
|
||||
t.Fatal("a preview must not remember the rule")
|
||||
}
|
||||
|
||||
res, err := w.svc.Set(ctx, "admin", "Family", "Finances", entries, map[string]string{"/etc/samba/smb.conf": "v1"}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Items != 3 || res.Failed != 0 {
|
||||
t.Errorf("result = %+v", res)
|
||||
}
|
||||
if fmt.Sprint(w.shares.masks) != "[true false]" {
|
||||
t.Errorf("smb.conf masks calls (dry run) = %v, want a preview and then the change", w.shares.masks)
|
||||
}
|
||||
if fmt.Sprint(w.tree.ownerRoot) != "[true]" {
|
||||
t.Errorf("the folder must be given to root, so its creator doesn't keep owner rights: %v", w.tree.ownerRoot)
|
||||
}
|
||||
tax := access(t, filepath.Join(w.family, "Finances", "tax.pdf"))
|
||||
for _, c := range []struct {
|
||||
tag acl.Tag
|
||||
id uint32
|
||||
want acl.Perm
|
||||
}{{acl.User, 1004, acl.Read | acl.Write}, {acl.User, 1006, acl.Read}, {acl.User, 1005, 0}, {acl.Group, 2000, acl.Read | acl.Write}, {acl.GroupObj, 0, 0}, {acl.Other, 0, 0}} {
|
||||
if p, ok := tax.Get(c.tag, c.id); !ok || tax.Effective(acl.Entry{Tag: c.tag, ID: c.id, Perm: p}) != c.want {
|
||||
t.Errorf("tax.pdf %v %d = %v (%v), want %v", c.tag, c.id, p, ok, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
info, err := w.svc.List(ctx, "Family")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !info.Available || len(info.Rules) != 1 {
|
||||
t.Fatalf("info = %+v", info)
|
||||
}
|
||||
r := info.Rules[0]
|
||||
want := []Entry{group("parents", share.LevelWrite), user("alex", share.LevelWrite), user("kim", share.LevelRead), user("sam", share.LevelNone)}
|
||||
if r.Path != "Finances" || fmt.Sprint(r.Entries) != fmt.Sprint(want) {
|
||||
t.Errorf("rule = %+v\nwant entries %v", r, want)
|
||||
}
|
||||
// Run as a normal user the folder stays ours; as root it is root's.
|
||||
for _, c := range r.Custom {
|
||||
if !strings.Contains(c, "keeps owner rights") || os.Getuid() == 0 {
|
||||
t.Errorf("unexpected note: %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangeRuleReplacesEntries(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Finances", []Entry{user("alex", share.LevelWrite), user("kim", share.LevelRead)}, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Finances", []Entry{user("alex", share.LevelRead)}, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := access(t, filepath.Join(w.family, "Finances"))
|
||||
if _, ok := a.Get(acl.User, 1006); ok {
|
||||
t.Error("kim was removed from the rule but still has an entry")
|
||||
}
|
||||
if p, _ := a.Get(acl.User, 1004); p != acl.RX {
|
||||
t.Errorf("alex = %v, want r-x", p)
|
||||
}
|
||||
info, _ := w.svc.List(ctx, "Family")
|
||||
if len(info.Rules) != 1 {
|
||||
t.Errorf("rules = %+v, want one (changed, not added twice)", info.Rules)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveRuleRestoresTheShareAccess(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
fin := filepath.Join(w.family, "Finances")
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Finances", []Entry{user("alex", share.LevelWrite)}, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prev, err := w.svc.Remove(ctx, "Family", "Finances", true)
|
||||
if err != nil || prev.Items != 3 {
|
||||
t.Fatalf("preview = %+v, %v", prev, err)
|
||||
}
|
||||
if !access(t, fin).Extended() {
|
||||
t.Fatal("the preview removed the rule")
|
||||
}
|
||||
if _, err := w.svc.Remove(ctx, "Family", "Finances", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The share folder is 0770 without ACLs: the subfolder is that again.
|
||||
for p, want := range map[string]os.FileMode{fin: 0o770, filepath.Join(fin, "2026"): 0o770, filepath.Join(fin, "tax.pdf"): 0o660} {
|
||||
st, _ := os.Stat(p)
|
||||
if st.Mode().Perm() != want {
|
||||
t.Errorf("%s mode = %v, want %v", p, st.Mode().Perm(), want)
|
||||
}
|
||||
buf := make([]byte, 64)
|
||||
if _, err := unix.Getxattr(p, acl.XattrAccess, buf); !errors.Is(err, unix.ENODATA) {
|
||||
t.Errorf("%s still has an ACL (%v)", p, err)
|
||||
}
|
||||
}
|
||||
if info, _ := w.svc.List(ctx, "Family"); len(info.Rules) != 0 {
|
||||
t.Errorf("rules = %+v", info.Rules)
|
||||
}
|
||||
if _, err := w.svc.Remove(ctx, "Family", "Finances", false); !errors.Is(err, ErrRuleNotFound) {
|
||||
t.Errorf("second remove: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingFolder(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Photos", []Entry{user("alex", share.LevelRead)}, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(w.family, "Photos")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, _ := w.svc.List(ctx, "Family")
|
||||
if len(info.Rules) != 1 || !info.Rules[0].Missing {
|
||||
t.Fatalf("rules = %+v, want Photos marked missing", info.Rules)
|
||||
}
|
||||
if r, err := w.svc.Remove(ctx, "Family", "Photos", true); err != nil || !strings.Contains(r.Summary, "missing") {
|
||||
t.Errorf("preview = %+v, %v", r, err)
|
||||
}
|
||||
if _, err := w.svc.Remove(ctx, "Family", "Photos", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info, _ := w.svc.List(ctx, "Family"); len(info.Rules) != 0 {
|
||||
t.Errorf("rules = %+v", info.Rules)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefusals(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Photos/2026", []Entry{user("alex", share.LevelRead)}, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alex := []Entry{user("alex", share.LevelWrite)}
|
||||
many := make([]Entry, MaxEntries+1)
|
||||
for i := range many {
|
||||
many[i] = user(fmt.Sprintf("u%d", i), share.LevelRead)
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
share, rel string
|
||||
entries []Entry
|
||||
want error
|
||||
}{
|
||||
"unknown share": {"Nope", "Finances", alex, shares.ErrNotFound},
|
||||
"personal folders": {"homes", "x", alex, share.ErrUnsupported},
|
||||
"guest share": {"Public", "Finances", alex, share.ErrUnsupported},
|
||||
"no ACLs": {"Noacl", "x", alex, ErrNoACL},
|
||||
"not checked": {"Away", "x", alex, ErrNoACL},
|
||||
"share root": {"Family", "/", alex, share.ErrInvalid},
|
||||
"dot dot": {"Family", "Finances/../..", alex, share.ErrInvalid},
|
||||
"dot": {"Family", "./Finances", alex, share.ErrInvalid},
|
||||
"missing folder": {"Family", "Nope", alex, share.ErrInvalid},
|
||||
"a file": {"Family", "Finances/tax.pdf", alex, share.ErrInvalid},
|
||||
"above a rule": {"Family", "Photos", alex, share.ErrUnsupported},
|
||||
"nobody": {"Family", "Finances", []Entry{user("alex", share.LevelNone)}, share.ErrInvalid},
|
||||
"empty": {"Family", "Finances", nil, share.ErrInvalid},
|
||||
"twice": {"Family", "Finances", []Entry{user("alex", share.LevelRead), user("alex", share.LevelWrite)}, share.ErrInvalid},
|
||||
"group no access": {"Family", "Finances", []Entry{user("alex", share.LevelRead), group("family", share.LevelNone)}, share.ErrInvalid},
|
||||
"unknown user": {"Family", "Finances", []Entry{user("bob", share.LevelRead)}, share.ErrInvalid},
|
||||
"unknown group": {"Family", "Finances", []Entry{group("kids", share.LevelRead)}, share.ErrInvalid},
|
||||
"everyone": {"Family", "Finances", []Entry{{Principal: share.Principal{Kind: share.KindOthers}, Level: share.LevelRead}}, share.ErrInvalid},
|
||||
"bad level": {"Family", "Finances", []Entry{user("alex", "admin")}, share.ErrInvalid},
|
||||
"too many": {"Family", "Finances", many, share.ErrInvalid},
|
||||
} {
|
||||
if _, err := w.svc.Set(ctx, "admin", c.share, c.rel, c.entries, nil, true); !errors.Is(err, c.want) {
|
||||
t.Errorf("%s: err = %v, want %v", name, err, c.want)
|
||||
}
|
||||
}
|
||||
if fmt.Sprint(w.shares.masks) != "[false]" {
|
||||
t.Errorf("a refused change must not touch smb.conf: %v", w.shares.masks)
|
||||
}
|
||||
// Below a rule is refused too.
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Photos/2026/deeper", alex, nil, true); err == nil {
|
||||
t.Error("below a rule: want an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAvailability(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
for name, c := range map[string]struct {
|
||||
share string
|
||||
available bool
|
||||
reason, lim string
|
||||
}{
|
||||
"ACLs": {"Family", true, "", ""},
|
||||
"no ACLs": {"Noacl", false, "switched off", "acl-off:"},
|
||||
"guest share": {"Public", false, "acts as the account nobody", ""},
|
||||
"personal folders": {"homes", false, "belongs to its user", ""},
|
||||
"outside storage": {"Away", false, "isn’t in a storage folder", ""},
|
||||
} {
|
||||
info, err := w.svc.List(ctx, c.share)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if info.Available != c.available || !strings.Contains(info.Reason, c.reason) || !strings.HasPrefix(info.Limitation, c.lim) || (c.lim == "" && info.Limitation != "") {
|
||||
t.Errorf("%s: %+v", name, info.Availability)
|
||||
}
|
||||
if info.Rules == nil {
|
||||
t.Errorf("%s: rules must be [] for the API, not null", name)
|
||||
}
|
||||
}
|
||||
// Unknown: the check failed; the reason says so.
|
||||
w.report.Folders[0].ACL, w.report.Folders[0].Reason = capabilities.ACLUnknown, "The test failed: boom"
|
||||
if info, _ := w.svc.List(ctx, "Family"); info.Available || !strings.Contains(info.Reason, "boom") {
|
||||
t.Errorf("unknown: %+v", info.Availability)
|
||||
}
|
||||
w.svc.Storage = func(context.Context) (capabilities.Report, error) {
|
||||
return capabilities.Report{}, errors.New("mountinfo unreadable")
|
||||
}
|
||||
if info, _ := w.svc.List(ctx, "Family"); info.Available || !strings.Contains(info.Reason, "mountinfo unreadable") {
|
||||
t.Errorf("storage error: %+v", info.Availability)
|
||||
}
|
||||
w.svc.Storage = nil
|
||||
if info, _ := w.svc.List(ctx, "Family"); !info.Available {
|
||||
t.Errorf("without a storage check: %+v", info.Availability)
|
||||
}
|
||||
}
|
||||
|
||||
// What was changed on disk by hand shows up instead of being hidden.
|
||||
func TestListShowsHandChanges(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
fin := filepath.Join(w.family, "Finances")
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Finances", []Entry{user("alex", share.LevelWrite)}, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hand := acl.ACL{
|
||||
{Tag: acl.UserObj, Perm: acl.RWX}, {Tag: acl.User, ID: 1004, Perm: acl.Read}, {Tag: acl.User, ID: 4711, Perm: acl.RWX},
|
||||
{Tag: acl.GroupObj, Perm: acl.RX}, {Tag: acl.Other, Perm: acl.Read},
|
||||
}
|
||||
b, _ := hand.Encode()
|
||||
if err := unix.Setxattr(fin, acl.XattrAccess, b, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := unix.Removexattr(fin, acl.XattrDefault); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, _ := w.svc.List(ctx, "Family")
|
||||
notes := strings.Join(info.Rules[0].Custom, "\n")
|
||||
for _, want := range []string{"alex has r--", "ID 4711 no longer exists", "group", "Everyone else also has access (r--)", "don’t inherit"} {
|
||||
if !strings.Contains(notes, want) {
|
||||
t.Errorf("notes miss %q:\n%s", want, notes)
|
||||
}
|
||||
}
|
||||
if fmt.Sprint(info.Rules[0].Entries) != fmt.Sprint([]Entry{user("#4711", share.LevelWrite), user("alex", share.LevelRead)}) {
|
||||
t.Errorf("entries = %v", info.Rules[0].Entries)
|
||||
}
|
||||
// A default ACL that differs from the folder's own.
|
||||
def := acl.ACL{{Tag: acl.UserObj, Perm: acl.RWX}, {Tag: acl.User, ID: 1004, Perm: acl.RWX}, {Tag: acl.GroupObj}, {Tag: acl.Other}}
|
||||
b, _ = def.Encode()
|
||||
if err := unix.Setxattr(fin, acl.XattrDefault, b, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, _ = w.svc.List(ctx, "Family")
|
||||
if !strings.Contains(strings.Join(info.Rules[0].Custom, "\n"), "different permissions") {
|
||||
t.Errorf("notes = %v", info.Rules[0].Custom)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSmbConfErrorStopsBeforeDisk(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
w.shares.err = fmt.Errorf("%w: create mask = %%U", share.ErrCustom)
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Finances", []Entry{user("alex", share.LevelWrite)}, nil, false); !errors.Is(err, share.ErrCustom) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
if access(t, filepath.Join(w.family, "Finances")).Extended() || len(w.tree.ownerRoot) != 0 {
|
||||
t.Error("ACLs were set although smb.conf couldn't be prepared")
|
||||
}
|
||||
}
|
||||
|
||||
type unsupportedTree struct{ realTree }
|
||||
|
||||
func (unsupportedTree) Apply(context.Context, string, string, acl.Template, bool) (aclfs.Report, error) {
|
||||
return aclfs.Report{}, aclfs.ErrNotSupported
|
||||
}
|
||||
|
||||
func TestFilesystemRefusesACLs(t *testing.T) {
|
||||
w := newWorld(t)
|
||||
w.svc.Tree = unsupportedTree{}
|
||||
if _, err := w.svc.Set(ctx, "admin", "Family", "Finances", []Entry{user("alex", share.LevelWrite)}, nil, false); !errors.Is(err, ErrNoACL) {
|
||||
t.Errorf("err = %v, want ErrNoACL", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// Package acl models POSIX ACLs (acl(5)) as Sharestead uses them for
|
||||
// subfolder permissions (F-DIR-9): the kernel's extended-attribute format,
|
||||
// templates that say what a folder tree should get, and the translation
|
||||
// between ACL entries and the access levels of the UI.
|
||||
package acl
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Extended attributes that hold the ACLs.
|
||||
const (
|
||||
XattrAccess = "system.posix_acl_access"
|
||||
XattrDefault = "system.posix_acl_default"
|
||||
)
|
||||
|
||||
// Perm is a set of permissions: 4 read, 2 write, 1 execute/search.
|
||||
type Perm uint16
|
||||
|
||||
// Permission bits.
|
||||
const (
|
||||
Read Perm = 4
|
||||
Write Perm = 2
|
||||
Exec Perm = 1
|
||||
RWX = Read | Write | Exec
|
||||
RX = Read | Exec
|
||||
)
|
||||
|
||||
func (p Perm) String() string {
|
||||
b := []byte("---")
|
||||
if p&Read != 0 {
|
||||
b[0] = 'r'
|
||||
}
|
||||
if p&Write != 0 {
|
||||
b[1] = 'w'
|
||||
}
|
||||
if p&Exec != 0 {
|
||||
b[2] = 'x'
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Tag is the kind of an entry (values as in the kernel's xattr format).
|
||||
type Tag uint16
|
||||
|
||||
// Entry kinds.
|
||||
const (
|
||||
UserObj Tag = 0x01 // the owner
|
||||
User Tag = 0x02 // a named user
|
||||
GroupObj Tag = 0x04 // the owning group
|
||||
Group Tag = 0x08 // a named group
|
||||
Mask Tag = 0x10 // upper bound for named entries and the owning group
|
||||
Other Tag = 0x20 // everyone else
|
||||
)
|
||||
|
||||
const undefinedID = 0xFFFFFFFF
|
||||
const version = 2
|
||||
|
||||
// Entry is one line of an ACL. ID is the uid or gid of named entries.
|
||||
type Entry struct {
|
||||
Tag Tag
|
||||
ID uint32
|
||||
Perm Perm
|
||||
}
|
||||
|
||||
// ACL is a list of entries.
|
||||
type ACL []Entry
|
||||
|
||||
// ErrFormat is returned for data that isn't a valid ACL.
|
||||
var ErrFormat = errors.New("not a valid POSIX ACL")
|
||||
|
||||
// Get returns the permissions of the first entry with tag and id (id is
|
||||
// ignored for the non-named kinds).
|
||||
func (a ACL) Get(tag Tag, id uint32) (Perm, bool) {
|
||||
for _, e := range a {
|
||||
if e.Tag == tag && (e.ID == id || (tag != User && tag != Group)) {
|
||||
return e.Perm, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Named returns the entries for named users and groups.
|
||||
func (a ACL) Named() []Entry {
|
||||
var out []Entry
|
||||
for _, e := range a {
|
||||
if e.Tag == User || e.Tag == Group {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Extended reports whether the ACL says more than the mode bits can.
|
||||
func (a ACL) Extended() bool { return len(a.Named()) > 0 }
|
||||
|
||||
// Effective returns what an entry of the group class (named users, owning
|
||||
// group, named groups) really grants: its permissions limited by the mask.
|
||||
func (a ACL) Effective(e Entry) Perm {
|
||||
if e.Tag == UserObj || e.Tag == Other || e.Tag == Mask {
|
||||
return e.Perm
|
||||
}
|
||||
if m, ok := a.Get(Mask, 0); ok {
|
||||
return e.Perm & m
|
||||
}
|
||||
return e.Perm
|
||||
}
|
||||
|
||||
// Encode returns the ACL in the kernel's extended-attribute format. Entries
|
||||
// are sorted as the kernel requires; a mask is added when named entries
|
||||
// need one and none is given.
|
||||
func (a ACL) Encode() ([]byte, error) {
|
||||
if err := a.Valid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sorted := slices.Clone(a)
|
||||
if sorted.Extended() {
|
||||
if _, ok := sorted.Get(Mask, 0); !ok {
|
||||
sorted = append(sorted, Entry{Tag: Mask, Perm: sorted.groupClass()})
|
||||
}
|
||||
}
|
||||
sort.SliceStable(sorted, func(i, j int) bool {
|
||||
if sorted[i].Tag != sorted[j].Tag {
|
||||
return sorted[i].Tag < sorted[j].Tag
|
||||
}
|
||||
return sorted[i].ID < sorted[j].ID
|
||||
})
|
||||
b := make([]byte, 4, 4+8*len(sorted))
|
||||
binary.LittleEndian.PutUint32(b, version)
|
||||
for _, e := range sorted {
|
||||
id := e.ID
|
||||
if e.Tag != User && e.Tag != Group {
|
||||
id = undefinedID
|
||||
}
|
||||
b = binary.LittleEndian.AppendUint16(b, uint16(e.Tag))
|
||||
b = binary.LittleEndian.AppendUint16(b, uint16(e.Perm&RWX))
|
||||
b = binary.LittleEndian.AppendUint32(b, id)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// groupClass is the union of the named entries and the owning group: the
|
||||
// smallest mask that doesn't take anything away.
|
||||
func (a ACL) groupClass() Perm {
|
||||
var p Perm
|
||||
for _, e := range a {
|
||||
if e.Tag == User || e.Tag == Group || e.Tag == GroupObj {
|
||||
p |= e.Perm
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Valid checks the rules of acl(5): exactly one owner, owning group and
|
||||
// other entry, no duplicate named entries, at most one mask, permissions
|
||||
// only rwx.
|
||||
func (a ACL) Valid() error {
|
||||
count := map[Tag]int{}
|
||||
seen := map[Entry]bool{}
|
||||
for _, e := range a {
|
||||
switch e.Tag {
|
||||
case UserObj, GroupObj, Other, Mask:
|
||||
count[e.Tag]++
|
||||
case User, Group:
|
||||
k := Entry{Tag: e.Tag, ID: e.ID}
|
||||
if seen[k] {
|
||||
return fmt.Errorf("%w: two entries for the same %s", ErrFormat, kindName(e.Tag))
|
||||
}
|
||||
seen[k] = true
|
||||
default:
|
||||
return fmt.Errorf("%w: unknown entry kind %#x", ErrFormat, uint16(e.Tag))
|
||||
}
|
||||
if e.Perm&^RWX != 0 {
|
||||
return fmt.Errorf("%w: permissions %#o", ErrFormat, uint16(e.Perm))
|
||||
}
|
||||
}
|
||||
for _, t := range []Tag{UserObj, GroupObj, Other} {
|
||||
if count[t] != 1 {
|
||||
return fmt.Errorf("%w: needs exactly one %s entry", ErrFormat, kindName(t))
|
||||
}
|
||||
}
|
||||
if count[Mask] > 1 {
|
||||
return fmt.Errorf("%w: more than one mask", ErrFormat)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func kindName(t Tag) string {
|
||||
switch t {
|
||||
case UserObj:
|
||||
return "owner"
|
||||
case User:
|
||||
return "user"
|
||||
case GroupObj:
|
||||
return "owning group"
|
||||
case Group:
|
||||
return "group"
|
||||
case Other:
|
||||
return "other"
|
||||
}
|
||||
return "mask"
|
||||
}
|
||||
|
||||
// Decode reads an ACL in the kernel's extended-attribute format.
|
||||
func Decode(b []byte) (ACL, error) {
|
||||
if len(b) < 4 || (len(b)-4)%8 != 0 {
|
||||
return nil, fmt.Errorf("%w: %d bytes", ErrFormat, len(b))
|
||||
}
|
||||
if v := binary.LittleEndian.Uint32(b); v != version {
|
||||
return nil, fmt.Errorf("%w: version %d", ErrFormat, v)
|
||||
}
|
||||
var a ACL
|
||||
for i := 4; i < len(b); i += 8 {
|
||||
e := Entry{
|
||||
Tag: Tag(binary.LittleEndian.Uint16(b[i:])),
|
||||
Perm: Perm(binary.LittleEndian.Uint16(b[i+2:])),
|
||||
ID: binary.LittleEndian.Uint32(b[i+4:]),
|
||||
}
|
||||
if e.Tag != User && e.Tag != Group {
|
||||
e.ID = 0
|
||||
}
|
||||
a = append(a, e)
|
||||
}
|
||||
if err := a.Valid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// FromMode returns the ACL equivalent to the permission bits of a mode.
|
||||
func FromMode(mode uint32) ACL {
|
||||
return ACL{
|
||||
{Tag: UserObj, Perm: Perm(mode>>6) & RWX},
|
||||
{Tag: GroupObj, Perm: Perm(mode>>3) & RWX},
|
||||
{Tag: Other, Perm: Perm(mode) & RWX},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package acl
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Bytes the Linux kernel stored for ACLs set with setfacl (read back with
|
||||
// getfattr -e hex on Debian 13): the format is fixed by the kernel, so these
|
||||
// are the oracle for Encode and Decode.
|
||||
const (
|
||||
// u::rwx, u:1004:rwx, u:1006:r-x, g::---, m::rwx, o::---
|
||||
kernelUsers = "0200000001000700ffffffff02000700ec03000002000500ee03000004000000ffffffff10000700ffffffff20000000ffffffff"
|
||||
// u::rwx, u:1005:---, g::---, g:1005:rwx, m::rwx, o::---
|
||||
kernelGroup = "0200000001000700ffffffff02000000ed03000004000000ffffffff08000700ed03000010000700ffffffff20000000ffffffff"
|
||||
)
|
||||
|
||||
func mustHex(t *testing.T, s string) []byte {
|
||||
t.Helper()
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestEncodeMatchesKernel(t *testing.T) {
|
||||
// Given in any order and without a mask: Encode sorts and adds the
|
||||
// mask like setfacl does.
|
||||
users := ACL{
|
||||
{Tag: Other},
|
||||
{Tag: User, ID: 1006, Perm: RX},
|
||||
{Tag: GroupObj},
|
||||
{Tag: User, ID: 1004, Perm: RWX},
|
||||
{Tag: UserObj, Perm: RWX},
|
||||
}
|
||||
group := ACL{
|
||||
{Tag: UserObj, Perm: RWX}, {Tag: User, ID: 1005}, {Tag: GroupObj},
|
||||
{Tag: Group, ID: 1005, Perm: RWX}, {Tag: Mask, Perm: RWX}, {Tag: Other},
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
a ACL
|
||||
want string
|
||||
}{"users": {users, kernelUsers}, "group": {group, kernelGroup}} {
|
||||
got, err := c.a.Encode()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if hex.EncodeToString(got) != c.want {
|
||||
t.Errorf("%s:\n got %x\nwant %s", name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeKernelBytes(t *testing.T) {
|
||||
a, err := Decode(mustHex(t, kernelGroup))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, ok := a.Get(Group, 1005); !ok || p != RWX {
|
||||
t.Errorf("group 1005 = %v %v, want rwx", p, ok)
|
||||
}
|
||||
if p, ok := a.Get(User, 1005); !ok || p != 0 {
|
||||
t.Errorf("user 1005 = %v %v, want --- (present)", p, ok)
|
||||
}
|
||||
if _, ok := a.Get(User, 1004); ok {
|
||||
t.Error("user 1004 isn't in the ACL")
|
||||
}
|
||||
if m, _ := a.Get(Mask, 0); m != RWX {
|
||||
t.Errorf("mask = %v", m)
|
||||
}
|
||||
if !a.Extended() || len(a.Named()) != 2 {
|
||||
t.Errorf("named = %v", a.Named())
|
||||
}
|
||||
// Round trip
|
||||
b, err := a.Encode()
|
||||
if err != nil || hex.EncodeToString(b) != kernelGroup {
|
||||
t.Errorf("round trip = %x, %v", b, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRejectsBrokenData(t *testing.T) {
|
||||
for name, s := range map[string]string{
|
||||
"empty": "",
|
||||
"short entry": "02000000010007",
|
||||
"version 1": "01000000" + kernelUsers[8:],
|
||||
"no other": "0200000001000700ffffffff04000000ffffffff",
|
||||
"two owners": "0200000001000700ffffffff01000700ffffffff04000000ffffffff20000000ffffffff",
|
||||
"unknown tag": "0200000001000700ffffffff04000000ffffffff20000000ffffffff40000000ffffffff",
|
||||
"perm too wide": "0200000001000f00ffffffff04000000ffffffff20000000ffffffff",
|
||||
"same user": "0200000001000700ffffffff02000700ec03000002000500ec03000004000000ffffffff10000700ffffffff20000000ffffffff",
|
||||
"two masks": "0200000001000700ffffffff04000000ffffffff10000700ffffffff10000700ffffffff20000000ffffffff",
|
||||
} {
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
t.Fatal(name, err)
|
||||
}
|
||||
if _, err := Decode(b); !errors.Is(err, ErrFormat) {
|
||||
t.Errorf("%s: err = %v, want ErrFormat", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeRejectsInvalid(t *testing.T) {
|
||||
if _, err := (ACL{{Tag: UserObj}, {Tag: Other}}).Encode(); !errors.Is(err, ErrFormat) {
|
||||
t.Errorf("missing owning group: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEffectiveIsLimitedByMask(t *testing.T) {
|
||||
a := ACL{{Tag: UserObj, Perm: RWX}, {Tag: User, ID: 7, Perm: RWX}, {Tag: GroupObj, Perm: RWX}, {Tag: Mask, Perm: Read}, {Tag: Other, Perm: RWX}}
|
||||
for _, c := range []struct {
|
||||
e Entry
|
||||
want Perm
|
||||
}{
|
||||
{Entry{Tag: User, ID: 7, Perm: RWX}, Read},
|
||||
{Entry{Tag: GroupObj, Perm: RWX}, Read},
|
||||
{Entry{Tag: UserObj, Perm: RWX}, RWX}, // the owner isn't masked
|
||||
{Entry{Tag: Other, Perm: RWX}, RWX}, // nor are others
|
||||
} {
|
||||
if got := a.Effective(c.e); got != c.want {
|
||||
t.Errorf("%v: %v, want %v", c.e, got, c.want)
|
||||
}
|
||||
}
|
||||
noMask := FromMode(0o750)
|
||||
if got := noMask.Effective(Entry{Tag: GroupObj, Perm: RX}); got != RX {
|
||||
t.Errorf("without mask: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromMode(t *testing.T) {
|
||||
a := FromMode(0o40751)
|
||||
want := map[Tag]Perm{UserObj: RWX, GroupObj: RX, Other: Exec}
|
||||
for tag, p := range want {
|
||||
if got, _ := a.Get(tag, 0); got != p {
|
||||
t.Errorf("%v = %v, want %v", tag, got, p)
|
||||
}
|
||||
}
|
||||
if a.Extended() {
|
||||
t.Error("a mode has no named entries")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermString(t *testing.T) {
|
||||
for p, want := range map[Perm]string{0: "---", RWX: "rwx", RX: "r-x", Read | Write: "rw-", Write: "-w-"} {
|
||||
if p.String() != want {
|
||||
t.Errorf("%d = %q, want %q", p, p.String(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaskCoversTheOwningGroup(t *testing.T) {
|
||||
// acl(5): the mask is the upper bound of the whole group class, so a
|
||||
// computed mask must not cut down the owning group.
|
||||
b, err := ACL{{Tag: UserObj, Perm: RWX}, {Tag: User, ID: 5, Perm: RX}, {Tag: GroupObj, Perm: RWX}, {Tag: Other}}.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, _ := Decode(b)
|
||||
if m, _ := a.Get(Mask, 0); m != RWX {
|
||||
t.Errorf("mask = %v, want rwx", m)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package acl
|
||||
|
||||
import "sort"
|
||||
|
||||
// Template says what every folder and file in a tree gets. Permissions are
|
||||
// written for folders; files get them without execute, unless the file is
|
||||
// already executable (like setfacl's "X").
|
||||
type Template struct {
|
||||
Owner, Group, Other Perm
|
||||
Users, Groups map[uint32]Perm
|
||||
// Default: folders also get the template as default ACL, so new files
|
||||
// and folders inherit it.
|
||||
Default bool
|
||||
}
|
||||
|
||||
// named returns the named entries, sorted.
|
||||
func (t Template) named(file, executable bool) ACL {
|
||||
var out ACL
|
||||
add := func(tag Tag, m map[uint32]Perm) {
|
||||
ids := make([]uint32, 0, len(m))
|
||||
for id := range m {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||
for _, id := range ids {
|
||||
out = append(out, Entry{Tag: tag, ID: id, Perm: forObject(m[id], file, executable)})
|
||||
}
|
||||
}
|
||||
add(User, t.Users)
|
||||
add(Group, t.Groups)
|
||||
return out
|
||||
}
|
||||
|
||||
func forObject(p Perm, file, executable bool) Perm {
|
||||
if file && !executable {
|
||||
return p &^ Exec
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// ForDir returns the access ACL of a folder and its default ACL (nil when
|
||||
// the template has none).
|
||||
func (t Template) ForDir() (access, def ACL) {
|
||||
access = append(ACL{{Tag: UserObj, Perm: t.Owner}, {Tag: GroupObj, Perm: t.Group}, {Tag: Other, Perm: t.Other}}, t.named(false, false)...)
|
||||
if t.Default {
|
||||
def = access
|
||||
}
|
||||
return access, def
|
||||
}
|
||||
|
||||
// ForFile returns the access ACL of a file with the given mode: the owner
|
||||
// keeps the permissions they have; the rest comes from the template.
|
||||
func (t Template) ForFile(mode uint32) ACL {
|
||||
exe := mode&0o111 != 0
|
||||
return append(ACL{
|
||||
{Tag: UserObj, Perm: Perm(mode>>6) & RWX},
|
||||
{Tag: GroupObj, Perm: forObject(t.Group, true, exe)},
|
||||
{Tag: Other, Perm: forObject(t.Other, true, exe)},
|
||||
}, t.named(true, exe)...)
|
||||
}
|
||||
|
||||
// Inherit returns what a folder gets from its parent when it has no rules
|
||||
// of its own: the parent's default ACL if it has one, else the parent's
|
||||
// permission bits (without inheritance).
|
||||
func Inherit(parentMode uint32, parentDefault ACL) Template {
|
||||
if len(parentDefault) == 0 {
|
||||
a := FromMode(parentMode)
|
||||
return Template{Owner: perm(a, UserObj), Group: perm(a, GroupObj), Other: perm(a, Other)}
|
||||
}
|
||||
t := Template{Owner: perm(parentDefault, UserObj), Group: parentDefault.Effective(Entry{Tag: GroupObj, Perm: perm(parentDefault, GroupObj)}), Other: perm(parentDefault, Other), Default: true}
|
||||
for _, e := range parentDefault.Named() {
|
||||
m := &t.Users
|
||||
if e.Tag == Group {
|
||||
m = &t.Groups
|
||||
}
|
||||
if *m == nil {
|
||||
*m = map[uint32]Perm{}
|
||||
}
|
||||
(*m)[e.ID] = parentDefault.Effective(e)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func perm(a ACL, tag Tag) Perm {
|
||||
p, _ := a.Get(tag, 0)
|
||||
return p
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package acl
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Finances: alex (1004) read & write, kim (1006) read, the parents group
|
||||
// (2000) read & write; nobody else.
|
||||
var finances = Template{
|
||||
Owner: RWX, Users: map[uint32]Perm{1004: RWX, 1006: RX}, Groups: map[uint32]Perm{2000: RWX}, Default: true,
|
||||
}
|
||||
|
||||
func TestTemplateForDir(t *testing.T) {
|
||||
access, def := finances.ForDir()
|
||||
want := ACL{
|
||||
{Tag: UserObj, Perm: RWX}, {Tag: GroupObj}, {Tag: Other},
|
||||
{Tag: User, ID: 1004, Perm: RWX}, {Tag: User, ID: 1006, Perm: RX}, {Tag: Group, ID: 2000, Perm: RWX},
|
||||
}
|
||||
if !slices.Equal(access, want) {
|
||||
t.Errorf("access = %v\nwant %v", access, want)
|
||||
}
|
||||
if !slices.Equal(def, want) {
|
||||
t.Errorf("default = %v, want the same as access so new files inherit it", def)
|
||||
}
|
||||
noInherit := Template{Owner: RWX, Group: RX}
|
||||
if _, def := noInherit.ForDir(); def != nil {
|
||||
t.Errorf("default = %v, want none", def)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemplateForFile(t *testing.T) {
|
||||
// A normal file: read & write without execute; the owner keeps rw-.
|
||||
plain := finances.ForFile(0o100640)
|
||||
wantPlain := ACL{
|
||||
{Tag: UserObj, Perm: Read | Write}, {Tag: GroupObj}, {Tag: Other},
|
||||
{Tag: User, ID: 1004, Perm: Read | Write}, {Tag: User, ID: 1006, Perm: Read}, {Tag: Group, ID: 2000, Perm: Read | Write},
|
||||
}
|
||||
if !slices.Equal(plain, wantPlain) {
|
||||
t.Errorf("plain file = %v\nwant %v", plain, wantPlain)
|
||||
}
|
||||
// An executable file stays executable for whoever may read it.
|
||||
exe := finances.ForFile(0o100750)
|
||||
if p, _ := exe.Get(User, 1006); p != RX {
|
||||
t.Errorf("kim on a program = %v, want r-x", p)
|
||||
}
|
||||
if p, _ := exe.Get(UserObj, 0); p != RWX {
|
||||
t.Errorf("owner of a program = %v, want rwx (kept)", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeAddsMaskFromTemplate(t *testing.T) {
|
||||
// A Read-only entry next to nothing else must keep the mask at r-x,
|
||||
// not wider: otherwise a later chmod could open more than intended.
|
||||
tpl := Template{Owner: RWX, Users: map[uint32]Perm{5: RX}}
|
||||
access, _ := tpl.ForDir()
|
||||
b, err := access.Encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, err := Decode(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m, _ := a.Get(Mask, 0); m != RX {
|
||||
t.Errorf("mask = %v, want r-x", m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInheritFromParentMode(t *testing.T) {
|
||||
// A share folder root:sst-family 0770 without ACLs: a subfolder whose
|
||||
// rule is removed gets the same bits back, without inheritance.
|
||||
got := Inherit(0o40770, nil)
|
||||
want := Template{Owner: RWX, Group: RWX}
|
||||
if got.Owner != want.Owner || got.Group != want.Group || got.Other != 0 || got.Default || len(got.Users)+len(got.Groups) != 0 {
|
||||
t.Errorf("Inherit = %+v, want %+v", got, want)
|
||||
}
|
||||
// Files then get the group's rw back.
|
||||
f := got.ForFile(0o100600)
|
||||
if p, _ := f.Get(GroupObj, 0); p != Read|Write {
|
||||
t.Errorf("file group = %v, want rw-", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInheritFromParentDefaultACL(t *testing.T) {
|
||||
// The parent has its own default ACL: the subfolder inherits exactly
|
||||
// what a new folder there would get, mask applied.
|
||||
parentDef := ACL{
|
||||
{Tag: UserObj, Perm: RWX}, {Tag: User, ID: 9, Perm: RWX}, {Tag: GroupObj, Perm: RWX},
|
||||
{Tag: Group, ID: 3, Perm: RX}, {Tag: Mask, Perm: RX}, {Tag: Other},
|
||||
}
|
||||
got := Inherit(0o40770, parentDef)
|
||||
if !got.Default || got.Owner != RWX || got.Group != RX || got.Other != 0 {
|
||||
t.Errorf("base = %+v", got)
|
||||
}
|
||||
if got.Users[9] != RX || got.Groups[3] != RX {
|
||||
t.Errorf("named = %v %v, want limited by the mask (r-x)", got.Users, got.Groups)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package share
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"sharestead/internal/format/smbconf"
|
||||
)
|
||||
|
||||
// ACLMasks makes the share's create masks keep the group permissions, and
|
||||
// reports whether it changed anything. Samba creates files with a mode
|
||||
// limited by "create mask" (default 0744) and folders by "directory mask"
|
||||
// (default 0755); in a folder with an ACL the group bits of that mode
|
||||
// become the ACL's mask, which caps every named user and group. Without
|
||||
// group rw/rwx a user with Read & write on a subfolder couldn't change
|
||||
// files someone else creates there (tested with Samba 4.22). Only group
|
||||
// bits are added; owner and other bits stay as they are.
|
||||
func ACLMasks(f *smbconf.File, sec string) (bool, error) {
|
||||
if !f.HasSection(sec) || strings.EqualFold(sec, smbconf.GlobalSection) {
|
||||
return false, fmt.Errorf("%w: share %q not found", ErrInvalid, sec)
|
||||
}
|
||||
changed := false
|
||||
for _, m := range []struct {
|
||||
key, synonym string
|
||||
def, need uint64
|
||||
}{
|
||||
{"create mask", "create mode", 0o744, 0o060},
|
||||
{"directory mask", "directory mode", 0o755, 0o070},
|
||||
} {
|
||||
cur := m.def
|
||||
if v, name, ok := lookup(f, sec, m.key, m.synonym); ok {
|
||||
n, err := strconv.ParseUint(strings.TrimSpace(v), 8, 32)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%w: %s = %q isn't an octal mode", ErrCustom, name, v)
|
||||
}
|
||||
cur = n
|
||||
}
|
||||
if cur&m.need == m.need {
|
||||
continue
|
||||
}
|
||||
f.Delete(sec, m.synonym)
|
||||
if err := f.Set(sec, m.key, fmt.Sprintf("%04o", cur|m.need)); err != nil {
|
||||
return false, err
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// ForceUser returns the account every connection to the share acts as
|
||||
// ("force user"), or "".
|
||||
func ForceUser(f *smbconf.File, sec string) string {
|
||||
v, _ := get(f, sec, "force user")
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package share
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"sharestead/internal/format/smbconf"
|
||||
)
|
||||
|
||||
func TestACLMasks(t *testing.T) {
|
||||
for name, c := range map[string]struct {
|
||||
conf, wantCreate, wantDir string
|
||||
changed bool
|
||||
}{
|
||||
// smb.conf(5): create mask defaults to 0744, directory mask to 0755.
|
||||
"samba defaults": {"[S]\npath = /srv/s\n", "0764", "0775", true},
|
||||
"sharestead share": {"[S]\ncreate mask = 0660\ndirectory mask = 0770\n", "0660", "0770", false},
|
||||
"synonym replaced": {"[S]\ncreate mode = 0700\ndirectory mode = 0700\n", "0760", "0770", true},
|
||||
"global value": {"[global]\ncreate mask = 0600\n[S]\npath = /srv/s\n", "0660", "0775", true},
|
||||
"other bits kept": {"[S]\ncreate mask = 0604\ndirectory mask = 0777\n", "0664", "0777", true},
|
||||
"own value wins globals": {"[global]\ncreate mask = 0600\n[S]\ncreate mask = 0770\n", "0770", "0775", true},
|
||||
} {
|
||||
f := smbconf.Parse([]byte(c.conf))
|
||||
changed, err := ACLMasks(f, "S")
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if changed != c.changed {
|
||||
t.Errorf("%s: changed = %v", name, changed)
|
||||
}
|
||||
if v, _ := get(f, "S", "create mask", "create mode"); v != c.wantCreate {
|
||||
t.Errorf("%s: create mask = %s, want %s", name, v, c.wantCreate)
|
||||
}
|
||||
if v, _ := get(f, "S", "directory mask", "directory mode"); v != c.wantDir {
|
||||
t.Errorf("%s: directory mask = %s, want %s", name, v, c.wantDir)
|
||||
}
|
||||
if strings.Contains(string(f.Bytes()), "mode =") && c.changed && name == "synonym replaced" {
|
||||
t.Errorf("%s: synonym left:\n%s", name, f.Bytes())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestACLMasksRefuses(t *testing.T) {
|
||||
f := smbconf.Parse([]byte("[S]\ncreate mask = %U\n"))
|
||||
if _, err := ACLMasks(f, "S"); !errors.Is(err, ErrCustom) {
|
||||
t.Errorf("macro: %v, want ErrCustom", err)
|
||||
}
|
||||
for _, sec := range []string{"global", "Missing"} {
|
||||
if _, err := ACLMasks(f, sec); !errors.Is(err, ErrInvalid) {
|
||||
t.Errorf("%s: %v, want ErrInvalid", sec, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForceUser(t *testing.T) {
|
||||
f := smbconf.Parse([]byte("[global]\nforce user = nobody\n[A]\npath=/a\n[B]\nforce user = \" media \"\n"))
|
||||
if got := ForceUser(f, "A"); got != "nobody" {
|
||||
t.Errorf("A = %q (global applies)", got)
|
||||
}
|
||||
if got := ForceUser(smbconf.Parse([]byte("[C]\npath=/c\n")), "C"); got != "" {
|
||||
t.Errorf("C = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
svcs "sharestead/internal/app/services"
|
||||
"sharestead/internal/app/settings"
|
||||
"sharestead/internal/app/shares"
|
||||
"sharestead/internal/app/subfolders"
|
||||
"sharestead/internal/app/updates"
|
||||
"sharestead/internal/auth"
|
||||
)
|
||||
@@ -67,6 +68,7 @@ type api struct {
|
||||
capabilities *capabilities.Service
|
||||
diagnostics *diagnostics.Service
|
||||
limitations *limitations.Service
|
||||
subfolders *subfolders.Service
|
||||
homes *homes.Service
|
||||
settings *settings.Store
|
||||
passkeys *passkeys.Service
|
||||
|
||||
+21
-17
@@ -14,6 +14,7 @@ import (
|
||||
apphealth "sharestead/internal/app/health"
|
||||
"sharestead/internal/app/passkeys"
|
||||
"sharestead/internal/app/quotas"
|
||||
"sharestead/internal/app/subfolders"
|
||||
"sharestead/internal/app/updates"
|
||||
"sharestead/internal/domain/quota"
|
||||
"sharestead/internal/domain/share"
|
||||
@@ -44,23 +45,26 @@ var dryRunParam = queryParam{Name: "dry_run", Description: "1: only preview the
|
||||
|
||||
// apiDocs describes every route: summary, request and response types.
|
||||
var apiDocs = map[string]opDoc{
|
||||
"POST /api/v1/auth/login": {Tag: "Auth", Summary: "Log in", Description: "Checks user name and password (PAM). Admins get the admin UI; other users their own page if self-service is on. Sets the session cookie. Repeated failures are delayed (429).", Request: loginRequest{}, Response: sessionInfo{}},
|
||||
"POST /api/v1/auth/logout": {Tag: "Auth", Summary: "Log out"},
|
||||
"GET /api/v1/auth/session": {Tag: "Auth", Summary: "Current session", Response: sessionInfo{}},
|
||||
"GET /api/v1/auth/status": {Tag: "Auth", Summary: "Whether this browser is logged in", Description: "Always 200, so a login page can ask without an error.", Response: authStatus{}},
|
||||
"POST /api/v1/auth/confirm": {Tag: "Auth", Summary: "Confirm the password again", Description: "Needed before dangerous actions when the password wasn't entered in the last minutes (they answer 403 confirm_password).", Request: confirmRequest{}},
|
||||
"GET /api/v1/me": {Tag: "Self-service", Summary: "My account", Description: "The logged-in user's shares (with the level and why), storage and limits. Nothing about other users.", Response: myAccount{}},
|
||||
"PUT /api/v1/me/password": {Tag: "Self-service", Summary: "Change my password", Description: "Needs the current password. Sets it for Samba and Linux at once.", Request: setMyPasswordRequest{}},
|
||||
"GET /api/v1/shares": {Tag: "Shares", Summary: "List shares", Description: "All shares from smb.conf and the NFS export tables, with access, disk usage and problems.", Response: sharesList{}},
|
||||
"POST /api/v1/shares": {Tag: "Shares", Summary: "Create a share", Description: "Optionally creates the folder with its own group. Writes smb.conf and/or an export table.", Request: createShareRequest{}, Response: editResponse{}, Edit: true, Errors: map[int]string{422: "This combination of access settings can’t be expressed in Samba; the detail says what to change"}},
|
||||
"PUT /api/v1/shares/{name}/access": {Tag: "Shares", Summary: "Change who may do what", Request: setShareAccessRequest{}, Response: editResponse{}, Edit: true, Errors: map[int]string{422: "This combination of access settings can’t be expressed in Samba; the detail says what to change"}},
|
||||
"PUT /api/v1/shares/{name}/nfs": {Tag: "Shares", Summary: "Change NFS access", Description: "An empty client list stops NFS for this share.", Request: setShareNFSRequest{}, Response: editResponse{}, Edit: true},
|
||||
"PUT /api/v1/shares/{name}/options": {Tag: "Shares", Summary: "Change share options", Request: setShareOptionsRequest{}, Response: editResponse{}, Edit: true},
|
||||
"DELETE /api/v1/shares/{name}": {Tag: "Shares", Summary: "Remove a share", Description: "Stops sharing; the folder and files stay.", Request: deleteShareRequest{}, Response: editResponse{}, Edit: true},
|
||||
"GET /api/v1/settings/samba": {Tag: "Settings", Summary: "Server-wide Samba settings", Response: share.GlobalValues{}},
|
||||
"PUT /api/v1/settings/samba": {Tag: "Settings", Summary: "Change server-wide Samba settings", Request: setSambaSettingsRequest{}, Response: editResponse{}, Edit: true},
|
||||
"GET /api/v1/settings/app": {Tag: "Settings", Summary: "Sharestead's own settings", Response: appSettings{}},
|
||||
"PUT /api/v1/settings/app": {Tag: "Settings", Summary: "Change Sharestead's own settings", Description: "Switching self-service off ends all user sessions.", Request: setAppSettingsRequest{}, Response: appSettingsChanged{}},
|
||||
"POST /api/v1/auth/login": {Tag: "Auth", Summary: "Log in", Description: "Checks user name and password (PAM). Admins get the admin UI; other users their own page if self-service is on. Sets the session cookie. Repeated failures are delayed (429).", Request: loginRequest{}, Response: sessionInfo{}},
|
||||
"POST /api/v1/auth/logout": {Tag: "Auth", Summary: "Log out"},
|
||||
"GET /api/v1/auth/session": {Tag: "Auth", Summary: "Current session", Response: sessionInfo{}},
|
||||
"GET /api/v1/auth/status": {Tag: "Auth", Summary: "Whether this browser is logged in", Description: "Always 200, so a login page can ask without an error.", Response: authStatus{}},
|
||||
"POST /api/v1/auth/confirm": {Tag: "Auth", Summary: "Confirm the password again", Description: "Needed before dangerous actions when the password wasn't entered in the last minutes (they answer 403 confirm_password).", Request: confirmRequest{}},
|
||||
"GET /api/v1/me": {Tag: "Self-service", Summary: "My account", Description: "The logged-in user's shares (with the level and why), storage and limits. Nothing about other users.", Response: myAccount{}},
|
||||
"PUT /api/v1/me/password": {Tag: "Self-service", Summary: "Change my password", Description: "Needs the current password. Sets it for Samba and Linux at once.", Request: setMyPasswordRequest{}},
|
||||
"GET /api/v1/shares": {Tag: "Shares", Summary: "List shares", Description: "All shares from smb.conf and the NFS export tables, with access, disk usage and problems.", Response: sharesList{}},
|
||||
"POST /api/v1/shares": {Tag: "Shares", Summary: "Create a share", Description: "Optionally creates the folder with its own group. Writes smb.conf and/or an export table.", Request: createShareRequest{}, Response: editResponse{}, Edit: true, Errors: map[int]string{422: "This combination of access settings can’t be expressed in Samba; the detail says what to change"}},
|
||||
"PUT /api/v1/shares/{name}/access": {Tag: "Shares", Summary: "Change who may do what", Request: setShareAccessRequest{}, Response: editResponse{}, Edit: true, Errors: map[int]string{422: "This combination of access settings can’t be expressed in Samba; the detail says what to change"}},
|
||||
"PUT /api/v1/shares/{name}/nfs": {Tag: "Shares", Summary: "Change NFS access", Description: "An empty client list stops NFS for this share.", Request: setShareNFSRequest{}, Response: editResponse{}, Edit: true},
|
||||
"PUT /api/v1/shares/{name}/options": {Tag: "Shares", Summary: "Change share options", Request: setShareOptionsRequest{}, Response: editResponse{}, Edit: true},
|
||||
"GET /api/v1/shares/{name}/subfolders": {Tag: "Shares", Summary: "Subfolders with their own access", Description: "Whether subfolder permissions are possible for this share (POSIX ACLs in its storage folder; not for personal folders or guest shares) and the subfolders that have them, read back from the ACLs on disk. Differences made by hand are listed per subfolder.", Response: subfolders.Info{}, Errors: map[int]string{404: "Share not found"}},
|
||||
"PUT /api/v1/shares/{name}/subfolders": {Tag: "Shares", Summary: "Give a subfolder its own access", Description: "Sets POSIX ACLs on the subfolder and everything inside: the listed users and groups get their level, nobody else gets in. New files inherit it. The share's own access still applies on top. Users can be set to No access to keep them out of a listed group. The subfolder is given to root, so whoever created it doesn't keep owner rights to it; owners keep their rights to their own files inside. When needed, the share's create masks get group permissions (shown as an smb.conf change).", Request: setSubfolderRequest{}, Response: subfolderResponse{}, Edit: true, Errors: map[int]string{404: "Share not found", 409: "Subfolder permissions aren't available here (acl_unavailable) or the configuration changed", 422: "Not possible in this share or at this place (personal folders, guest shares, inside or above another subfolder with its own access)"}},
|
||||
"DELETE /api/v1/shares/{name}/subfolders": {Tag: "Shares", Summary: "Remove a subfolder's own access", Description: "The subfolder and everything inside get what the folder above gives again.", Request: removeSubfolderRequest{}, Response: subfolderResponse{}, Edit: true, Errors: map[int]string{404: "Share or subfolder rule not found"}},
|
||||
"DELETE /api/v1/shares/{name}": {Tag: "Shares", Summary: "Remove a share", Description: "Stops sharing; the folder and files stay.", Request: deleteShareRequest{}, Response: editResponse{}, Edit: true},
|
||||
"GET /api/v1/settings/samba": {Tag: "Settings", Summary: "Server-wide Samba settings", Response: share.GlobalValues{}},
|
||||
"PUT /api/v1/settings/samba": {Tag: "Settings", Summary: "Change server-wide Samba settings", Request: setSambaSettingsRequest{}, Response: editResponse{}, Edit: true},
|
||||
"GET /api/v1/settings/app": {Tag: "Settings", Summary: "Sharestead's own settings", Response: appSettings{}},
|
||||
"PUT /api/v1/settings/app": {Tag: "Settings", Summary: "Change Sharestead's own settings", Description: "Switching self-service off ends all user sessions.", Request: setAppSettingsRequest{}, Response: appSettingsChanged{}},
|
||||
"GET /api/v1/changes": {Tag: "Changes", Summary: "Change history", Description: "Every change made here or by hand in a managed file, newest first, with the lines changed. Filtered and paged on the server.", Response: changesList{}, Query: []queryParam{
|
||||
{Name: "q", Description: "text in the summary, the actor or a file path (case-insensitive)"},
|
||||
{Name: "kind", Description: "config: can be undone; hand: made outside Sharestead; audit: recorded only", Schema: map[string]any{"type": "string", "enum": []string{"all", "config", "hand", "audit"}, "default": "all"}},
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
svcs "sharestead/internal/app/services"
|
||||
"sharestead/internal/app/settings"
|
||||
"sharestead/internal/app/shares"
|
||||
"sharestead/internal/app/subfolders"
|
||||
"sharestead/internal/app/updates"
|
||||
"sharestead/internal/auth"
|
||||
"sharestead/internal/version"
|
||||
@@ -62,12 +63,14 @@ type Deps struct {
|
||||
Diagnostics *diagnostics.Service
|
||||
// Limitations lists missing requirements Sharestead handles (F-MON-11).
|
||||
Limitations *limitations.Service
|
||||
// Subfolders sets different access for subfolders inside shares (F-DIR-9).
|
||||
Subfolders *subfolders.Service
|
||||
}
|
||||
|
||||
// New creates a server listening on addr with the given certificate.
|
||||
func New(addr string, cert tls.Certificate, d Deps, log *slog.Logger) *Server {
|
||||
mux := http.NewServeMux()
|
||||
a := &api{mux: mux, auth: d.Auth, shares: d.Shares, accounts: d.Accounts, editor: d.Editor, store: d.Store, folders: d.Folders, services: d.Services, health: d.Health, quotas: d.Quotas, updates: d.Updates, homes: d.Homes, settings: d.Settings, passkeys: d.Passkeys, dlna: d.DLNA, capabilities: d.Capabilities, diagnostics: d.Diagnostics, limitations: d.Limitations, log: log}
|
||||
a := &api{mux: mux, auth: d.Auth, shares: d.Shares, accounts: d.Accounts, editor: d.Editor, store: d.Store, folders: d.Folders, services: d.Services, health: d.Health, quotas: d.Quotas, updates: d.Updates, homes: d.Homes, settings: d.Settings, passkeys: d.Passkeys, dlna: d.DLNA, capabilities: d.Capabilities, diagnostics: d.Diagnostics, limitations: d.Limitations, subfolders: d.Subfolders, log: log}
|
||||
a.handle("POST", "/api/v1/auth/login", ScopePublic, a.login)
|
||||
a.handle("POST", "/api/v1/auth/logout", ScopeSession, a.logout)
|
||||
a.handle("GET", "/api/v1/auth/session", ScopeSession, a.currentSession)
|
||||
@@ -84,6 +87,7 @@ func New(addr string, cert tls.Certificate, d Deps, log *slog.Logger) *Server {
|
||||
a.registerStorage()
|
||||
a.registerDiagnostics()
|
||||
a.registerLimitations()
|
||||
a.registerSubfolders()
|
||||
a.registerHomes()
|
||||
a.registerMe()
|
||||
a.registerSettings()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"sharestead/internal/app/shares"
|
||||
"sharestead/internal/app/subfolders"
|
||||
)
|
||||
|
||||
func (a *api) registerSubfolders() {
|
||||
a.handle("GET", "/api/v1/shares/{name}/subfolders", ScopeAdmin, a.listSubfolders)
|
||||
a.handle("PUT", "/api/v1/shares/{name}/subfolders", ScopeAdmin, a.setSubfolder)
|
||||
a.handle("DELETE", "/api/v1/shares/{name}/subfolders", ScopeAdmin, a.removeSubfolder)
|
||||
}
|
||||
|
||||
// subfolderResponse is a preview or the result of a subfolder change: the
|
||||
// config files it touches (Samba's create masks, if they must change) and
|
||||
// how many folders and files get new permissions.
|
||||
type subfolderResponse struct {
|
||||
editResponse
|
||||
Items int `json:"items"` // folders and files (to be) changed
|
||||
More bool `json:"more,omitempty"` // the preview stopped counting at Items
|
||||
Failed int `json:"failed,omitempty"`
|
||||
FirstError string `json:"first_error,omitempty"`
|
||||
Summary string `json:"summary"`
|
||||
}
|
||||
|
||||
func toSubfolderResponse(r subfolders.Result) subfolderResponse {
|
||||
return subfolderResponse{editResponse: toResponse(r.Result), Items: r.Items, More: r.More, Failed: r.Failed, FirstError: r.FirstError, Summary: r.Summary}
|
||||
}
|
||||
|
||||
func subfolderProblem(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, subfolders.ErrNoACL):
|
||||
problem(w, http.StatusConflict, "acl_unavailable", "Subfolder permissions aren’t available here", strings.TrimPrefix(err.Error(), subfolders.ErrNoACL.Error()+": "), nil)
|
||||
case errors.Is(err, subfolders.ErrRuleNotFound):
|
||||
problem(w, http.StatusNotFound, "not_found", "This subfolder has no own access", err.Error()+" — reload the page.", nil)
|
||||
default:
|
||||
editProblem(w, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *api) listSubfolders(w http.ResponseWriter, r *http.Request) {
|
||||
info, err := a.subfolders.List(r.Context(), r.PathValue("name"))
|
||||
if err != nil {
|
||||
subfolderProblem(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, info)
|
||||
}
|
||||
|
||||
// setSubfolderRequest is the body of setSubfolder.
|
||||
type setSubfolderRequest struct {
|
||||
Path string `json:"path"` // relative to the share folder, e.g. Finances
|
||||
Entries []subfolders.Entry `json:"entries"`
|
||||
Base shares.Base `json:"base"`
|
||||
}
|
||||
|
||||
func (a *api) setSubfolder(w http.ResponseWriter, r *http.Request) {
|
||||
var in setSubfolderRequest
|
||||
if !decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
res, err := a.subfolders.Set(r.Context(), sessionFrom(r).User, name, in.Path, in.Entries, in.Base, dryRun(r))
|
||||
a.subfolderDone(w, r, "set subfolder access", name+"/"+in.Path, res, err)
|
||||
}
|
||||
|
||||
// removeSubfolderRequest is the body of removeSubfolder.
|
||||
type removeSubfolderRequest struct {
|
||||
Path string `json:"path"` // relative to the share folder
|
||||
}
|
||||
|
||||
func (a *api) removeSubfolder(w http.ResponseWriter, r *http.Request) {
|
||||
var in removeSubfolderRequest
|
||||
if !decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
res, err := a.subfolders.Remove(r.Context(), name, in.Path, dryRun(r))
|
||||
a.subfolderDone(w, r, "remove subfolder access", name+"/"+in.Path, res, err)
|
||||
}
|
||||
|
||||
func (a *api) subfolderDone(w http.ResponseWriter, r *http.Request, action, target string, res subfolders.Result, err error) {
|
||||
if !dryRun(r) {
|
||||
a.audit(r, action, target, err)
|
||||
if res.Summary != "" && (err == nil || res.Items > 0) {
|
||||
a.record(r, res.Summary, nil)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
subfolderProblem(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toSubfolderResponse(res))
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"sharestead/internal/adapters/aclfs"
|
||||
"sharestead/internal/app/capabilities"
|
||||
"sharestead/internal/app/settings"
|
||||
"sharestead/internal/app/subfolders"
|
||||
"sharestead/internal/domain/acl"
|
||||
)
|
||||
|
||||
type testNames map[string]uint32
|
||||
|
||||
func (n testNames) UserID(name string) (uint32, error) {
|
||||
if id, ok := n["u:"+name]; ok {
|
||||
return id, nil
|
||||
}
|
||||
return 0, fmt.Errorf("unknown user %s", name)
|
||||
}
|
||||
func (n testNames) GroupID(name string) (uint32, error) {
|
||||
if id, ok := n["g:"+name]; ok {
|
||||
return id, nil
|
||||
}
|
||||
return 0, fmt.Errorf("unknown group %s", name)
|
||||
}
|
||||
func (n testNames) find(prefix string, id uint32) string {
|
||||
for k, v := range n {
|
||||
if v == id && strings.HasPrefix(k, prefix) {
|
||||
return strings.TrimPrefix(k, prefix)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func (n testNames) UserName(id uint32) string { return n.find("u:", id) }
|
||||
func (n testNames) GroupName(id uint32) string { return n.find("g:", id) }
|
||||
|
||||
// rootless applies ACLs without giving folders to root (needs root).
|
||||
type rootless struct{ aclfs.FS }
|
||||
|
||||
func (r rootless) Apply(ctx context.Context, base, rel string, t acl.Template, _ bool) (aclfs.Report, error) {
|
||||
return r.FS.Apply(ctx, base, rel, t, false)
|
||||
}
|
||||
|
||||
// subfolderWorld: the harness world with the real subfolder service on
|
||||
// the temp dir. aclOK decides what the storage check reports for it.
|
||||
func subfolderWorld(t *testing.T, aclOK bool) *world {
|
||||
t.Helper()
|
||||
var w *world
|
||||
state := capabilities.ACLYes
|
||||
if !aclOK {
|
||||
state = capabilities.ACLNo
|
||||
}
|
||||
w = newWorld(t, func(d *Deps) {
|
||||
d.Subfolders = &subfolders.Service{
|
||||
Shares: d.Editor, Tree: rootless{}, Settings: &settings.Store{Files: memSettings{}, Path: "/s.json"},
|
||||
Names: testNames{"u:alex": 1004, "u:kim": 1006, "g:parents": 2000},
|
||||
Storage: func(context.Context) (capabilities.Report, error) {
|
||||
return capabilities.Report{Folders: []capabilities.Folder{{Path: filepath.Dir(filepath.Join(d.Editor.AllowedRoots[0], "x")), FSType: "zfs", ACL: state, Reason: "This filesystem (zfs) has POSIX ACLs switched off."}}}, nil
|
||||
},
|
||||
}
|
||||
})
|
||||
fin := filepath.Join(w.root, "family", "Finances")
|
||||
if err := os.MkdirAll(fin, 0o770); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(fin, "tax.pdf"), []byte("x"), 0o660); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe, _ := acl.ACL{{Tag: acl.UserObj, Perm: acl.RWX}, {Tag: acl.User, ID: 1, Perm: acl.RX}, {Tag: acl.GroupObj}, {Tag: acl.Other}}.Encode()
|
||||
if err := unix.Setxattr(fin, acl.XattrAccess, probe, 0); err != nil {
|
||||
t.Skipf("no POSIX ACLs in the temp dir: %v", err)
|
||||
}
|
||||
_ = unix.Removexattr(fin, acl.XattrAccess)
|
||||
return w
|
||||
}
|
||||
|
||||
var finances = map[string]any{"path": "Finances", "entries": []map[string]any{
|
||||
{"principal": map[string]any{"kind": "user", "name": "alex"}, "level": "write"},
|
||||
{"principal": map[string]any{"kind": "group", "name": "parents"}, "level": "read"},
|
||||
}}
|
||||
|
||||
// F-DIR-9 through the API: review (smb.conf diff and item count), apply,
|
||||
// read back, history, remove.
|
||||
func TestSubfolderAccessThroughTheAPI(t *testing.T) {
|
||||
w := subfolderWorld(t, true)
|
||||
if r := w.call("GET", "/api/v1/shares/Family/subfolders", nil); r.Code != 200 || !strings.Contains(r.Body, `"available":true`) || !strings.Contains(r.Body, `"rules":[]`) {
|
||||
t.Fatalf("list: %d %s", r.Code, r.Body)
|
||||
}
|
||||
r := w.call("PUT", "/api/v1/shares/Family/subfolders?dry_run=1", finances)
|
||||
var prev struct {
|
||||
Files []struct {
|
||||
Path string
|
||||
Diff []struct{ Op, Text string }
|
||||
}
|
||||
Versions map[string]string
|
||||
Items int
|
||||
Summary string
|
||||
}
|
||||
r.json(t, &prev)
|
||||
if r.Code != 200 || prev.Items != 2 || len(prev.Files) != 1 || prev.Files[0].Path != w.smbConf {
|
||||
t.Fatalf("preview: %d %s", r.Code, r.Body)
|
||||
}
|
||||
if !strings.Contains(r.Body, "create mask = 0764") || !strings.Contains(r.Body, "directory mask = 0775") {
|
||||
t.Errorf("the preview must show the create masks Samba needs:\n%s", r.Body)
|
||||
}
|
||||
if strings.Contains(w.read(w.smbConf), "create mask") {
|
||||
t.Fatal("a preview changed smb.conf")
|
||||
}
|
||||
|
||||
body := map[string]any{"path": finances["path"], "entries": finances["entries"], "base": prev.Versions}
|
||||
r = w.call("PUT", "/api/v1/shares/Family/subfolders", body)
|
||||
if r.Code != 200 || !strings.Contains(r.Body, `"items":2`) || !strings.Contains(r.Body, `"entry"`) {
|
||||
t.Fatalf("apply: %d %s", r.Code, r.Body)
|
||||
}
|
||||
conf := w.read(w.smbConf)
|
||||
if !strings.Contains(conf, "create mask = 0764") || !strings.Contains(conf, "x:unknown parameter = kept") || !strings.Contains(conf, "# family files") {
|
||||
t.Errorf("smb.conf after apply (hand edits must stay):\n%s", conf)
|
||||
}
|
||||
r = w.call("GET", "/api/v1/shares/Family/subfolders", nil)
|
||||
if !strings.Contains(r.Body, `"path":"Finances"`) || !strings.Contains(r.Body, `{"principal":{"kind":"group","name":"parents"},"level":"read"}`) || !strings.Contains(r.Body, `{"principal":{"kind":"user","name":"alex"},"level":"write"}`) {
|
||||
t.Errorf("list after apply: %s", r.Body)
|
||||
}
|
||||
hist := w.call("GET", "/api/v1/changes?limit=50", nil).Body
|
||||
if !strings.Contains(hist, "subfolder Finances") || !strings.Contains(hist, "new files keep group permissions") {
|
||||
t.Errorf("history misses the subfolder change or the smb.conf change:\n%s", hist)
|
||||
}
|
||||
|
||||
// The same rule again: nothing more for smb.conf.
|
||||
r = w.call("PUT", "/api/v1/shares/Family/subfolders?dry_run=1", finances)
|
||||
if r.Code != 200 || strings.Contains(r.Body, `"files"`) {
|
||||
t.Errorf("second preview should only touch the disk: %s", r.Body)
|
||||
}
|
||||
if r := w.call("PUT", "/api/v1/shares/Family/subfolders", body); r.Code != 200 {
|
||||
t.Errorf("same rule again: %d %s", r.Code, r.Body)
|
||||
}
|
||||
w.write(w.smbConf, w.read(w.smbConf)+"\n[Other]\npath = /srv/other\n")
|
||||
// A hand edit of smb.conf in between doesn't block it: this change
|
||||
// writes nothing to smb.conf any more, so its base doesn't matter.
|
||||
if r := w.call("PUT", "/api/v1/shares/Family/subfolders", body); r.Code != 200 {
|
||||
t.Errorf("hand edit in between: %d %s", r.Code, r.Body)
|
||||
}
|
||||
|
||||
if r := w.call("DELETE", "/api/v1/shares/Family/subfolders?dry_run=1", map[string]any{"path": "Finances"}); r.Code != 200 || !strings.Contains(r.Body, `"items":2`) {
|
||||
t.Errorf("remove preview: %d %s", r.Code, r.Body)
|
||||
}
|
||||
if r := w.call("DELETE", "/api/v1/shares/Family/subfolders", map[string]any{"path": "Finances"}); r.Code != 200 {
|
||||
t.Errorf("remove: %d %s", r.Code, r.Body)
|
||||
}
|
||||
if r := w.call("GET", "/api/v1/shares/Family/subfolders", nil); !strings.Contains(r.Body, `"rules":[]`) {
|
||||
t.Errorf("after remove: %s", r.Body)
|
||||
}
|
||||
if r := w.call("DELETE", "/api/v1/shares/Family/subfolders", map[string]any{"path": "Finances"}); r.Code != 404 {
|
||||
t.Errorf("remove again: %d %s", r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubfolderAPIErrors(t *testing.T) {
|
||||
w := subfolderWorld(t, true)
|
||||
w.write(w.smbConf, w.read(w.smbConf)+"\n[Guests]\npath = "+w.root+"/family\nforce user = nobody\nguest ok = yes\n")
|
||||
bad := func(entries ...map[string]any) map[string]any {
|
||||
return map[string]any{"path": "Finances", "entries": entries}
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
method, path string
|
||||
body any
|
||||
code int
|
||||
problem string
|
||||
}{
|
||||
"unknown share": {"GET", "/api/v1/shares/Nope/subfolders", nil, 404, "not_found"},
|
||||
"set unknown": {"PUT", "/api/v1/shares/Nope/subfolders?dry_run=1", finances, 404, "not_found"},
|
||||
"guest share": {"PUT", "/api/v1/shares/Guests/subfolders?dry_run=1", finances, 422, "unsupported"},
|
||||
"not a folder": {"PUT", "/api/v1/shares/Family/subfolders?dry_run=1", map[string]any{"path": "Finances/tax.pdf", "entries": finances["entries"]}, 400, "invalid_input"},
|
||||
"leaves share": {"PUT", "/api/v1/shares/Family/subfolders?dry_run=1", map[string]any{"path": "../etc", "entries": finances["entries"]}, 400, "invalid_input"},
|
||||
"nobody": {"PUT", "/api/v1/shares/Family/subfolders?dry_run=1", bad(map[string]any{"principal": map[string]any{"kind": "user", "name": "alex"}, "level": "none"}), 400, "invalid_input"},
|
||||
"unknown user": {"PUT", "/api/v1/shares/Family/subfolders?dry_run=1", bad(map[string]any{"principal": map[string]any{"kind": "user", "name": "eve"}, "level": "read"}), 400, "invalid_input"},
|
||||
"no rule": {"DELETE", "/api/v1/shares/Family/subfolders", map[string]any{"path": "Finances"}, 404, "not_found"},
|
||||
"remove bad path": {"DELETE", "/api/v1/shares/Family/subfolders", map[string]any{"path": ".."}, 400, "invalid_input"},
|
||||
"broken JSON": {"PUT", "/api/v1/shares/Family/subfolders", "{", 400, ""},
|
||||
} {
|
||||
r := w.call(c.method, c.path, c.body)
|
||||
if r.Code != c.code || (c.problem != "" && r.problemCode() != c.problem) {
|
||||
t.Errorf("%s: %d %s, want %d %s", name, r.Code, r.Body, c.code, c.problem)
|
||||
}
|
||||
}
|
||||
if r := w.call("GET", "/api/v1/shares/Guests/subfolders", nil); r.Code != 200 || !strings.Contains(r.Body, `"available":false`) || !strings.Contains(r.Body, "guest share") {
|
||||
t.Errorf("guest share list: %s", r.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubfolderWithoutACLs(t *testing.T) {
|
||||
w := subfolderWorld(t, false)
|
||||
r := w.call("GET", "/api/v1/shares/Family/subfolders", nil)
|
||||
if r.Code != 200 || !strings.Contains(r.Body, `"available":false`) || !strings.Contains(r.Body, `"limitation":"acl-off:`) {
|
||||
t.Errorf("list: %d %s", r.Code, r.Body)
|
||||
}
|
||||
r = w.call("PUT", "/api/v1/shares/Family/subfolders?dry_run=1", finances)
|
||||
if r.Code != 409 || r.problemCode() != "acl_unavailable" || !strings.Contains(r.Body, "switched off") {
|
||||
t.Errorf("set: %d %s", r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ chown kim /srv/sst-test/homes/kim/kim-data.bin
|
||||
# The Family share holds 2 MB, for the share limit test.
|
||||
head -c 2000000 /dev/urandom > /srv/sst-test/family/family-data.bin
|
||||
chown alex /srv/sst-test/family/family-data.bin
|
||||
# A subfolder for the subfolder permissions test.
|
||||
install -d -m 0770 -g family /srv/sst-test/family/Finances
|
||||
# ZFS reports a new file's size only once it is written out (a few seconds);
|
||||
# wait for it, so Sharestead's first measurement sees the 2 MB.
|
||||
sync
|
||||
|
||||
@@ -770,6 +770,56 @@ test('share page says what each protocol checks and what not', async ({ page })
|
||||
}
|
||||
});
|
||||
|
||||
test('subfolder permissions: pick a folder, review, applied and listed, removed again (F-DIR-9)', async ({ page, isMobile }, info) => {
|
||||
const errors = watchConsole(page, true);
|
||||
await login(page);
|
||||
// A guest share can't tell people apart: greyed out with the reason.
|
||||
await page.goto('/#/shares/Public');
|
||||
const card = page.locator('section.card', { has: page.getByRole('heading', { name: 'Subfolders with their own access' }) });
|
||||
await expect(card.getByRole('button', { name: 'Add subfolder…' })).toBeDisabled();
|
||||
await expect(card).toContainText('guest share');
|
||||
await expect(card.getByRole('link', { name: 'Why? What does it affect?' })).toBeVisible();
|
||||
|
||||
await page.goto('/#/shares/Family');
|
||||
const add = card.getByRole('button', { name: 'Add subfolder…' });
|
||||
await expect(add).toBeVisible();
|
||||
if (await add.isDisabled()) { // no POSIX ACLs where Family lives: the reason links to the limitation
|
||||
await expect(card.getByText('not available')).toBeVisible();
|
||||
await expect(card.getByRole('link', { name: 'Why? What does it affect?' })).toHaveAttribute('href', /problems\?show=|help\?term=acl/);
|
||||
test.skip(true, 'no POSIX ACLs for Family on this system');
|
||||
}
|
||||
for (const left of await card.getByRole('button', { name: /^Remove own access of / }).all()) { // from an earlier run
|
||||
await left.click();
|
||||
await card.getByRole('button', { name: 'Remove own access' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('applied');
|
||||
}
|
||||
await add.click();
|
||||
const kids = card.locator('ul.kids button');
|
||||
await expect(kids.first()).toBeVisible();
|
||||
const folder = (await card.locator('ul.kids button', { hasText: 'Finances' }).count()) ? 'Finances' : ((await kids.first().textContent()) ?? '').replace('📁', '').trim();
|
||||
await card.locator('ul.kids button', { hasText: folder }).first().click();
|
||||
await expect(card.getByText(`Family/${folder}`, { exact: true })).toBeVisible();
|
||||
await card.getByLabel('Add user or group').selectOption('user:alex');
|
||||
await card.getByRole('button', { name: 'Add', exact: true }).click();
|
||||
await card.getByLabel('alex: Read & write').check({ force: true });
|
||||
await expect(card.getByText('Everyone else')).toBeVisible();
|
||||
await card.getByRole('button', { name: 'Review changes' }).click();
|
||||
await expect(card.getByText(/Sets the permissions of \d/)).toBeVisible();
|
||||
await expect(card.getByText('alex read & write, nobody else')).toBeVisible();
|
||||
await page.screenshot({ path: `e2e-results/screens/${info.project.name}-subfolder-review.png`, fullPage: true, caret: 'initial', animations: 'disabled' });
|
||||
await card.getByRole('button', { name: 'Apply' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('applied to');
|
||||
const rule = card.locator('ul.rules li', { hasText: folder });
|
||||
await expect(rule).toContainText('alex · read & write');
|
||||
await expect(rule).toContainText('everyone else · no access');
|
||||
await card.getByRole('button', { name: `Remove own access of ${folder}` }).click();
|
||||
await expect(card.getByText(/back to what the folder above gives/)).toBeVisible();
|
||||
await card.getByRole('button', { name: 'Remove own access' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('share’s access again');
|
||||
await expect(card.locator('ul.rules li', { hasText: folder })).toHaveCount(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('system: storage folders show whether subfolder permissions (ACLs) are possible', async ({ page, isMobile }) => {
|
||||
const errors = watchConsole(page, true);
|
||||
await login(page);
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
// Shows what a change will do to the config files before it's applied.
|
||||
import type { EditResponse } from '../lib/types';
|
||||
import Diff from './Diff.svelte';
|
||||
let { preview, busy = false, onapply, oncancel, label = 'Apply' }:
|
||||
{ preview: EditResponse; busy?: boolean; onapply: () => void; oncancel: () => void; label?: string } = $props();
|
||||
// disk: the change also sets permissions on disk, which the change
|
||||
// history records but can't undo; it says how to go back instead.
|
||||
let { preview, busy = false, onapply, oncancel, label = 'Apply', disk = '' }:
|
||||
{ preview: EditResponse; busy?: boolean; onapply: () => void; oncancel: () => void; label?: string; disk?: string } = $props();
|
||||
// What applying does, per kind of file (Samba reloads, DLNA restarts).
|
||||
const paths = $derived((preview.files ?? []).map((f) => f.path));
|
||||
const samba = $derived(paths.some((p) => p.includes('/samba/')));
|
||||
@@ -12,7 +14,7 @@
|
||||
|
||||
<section class="card review" aria-label="Review change">
|
||||
<h2>Review change</h2>
|
||||
<p class="muted small">Nothing is changed until you apply.{#if samba} Samba checked the new configuration; clients stay connected.{/if} Every change can be undone on the Changes page.</p>
|
||||
<p class="muted small">Nothing is changed until you apply.{#if samba} Samba checked the new configuration; clients stay connected.{/if}{#if disk}{' '}{disk}{:else}{' '}Every change can be undone on the Changes page.{/if}</p>
|
||||
{#if dlna}<p class="small warnline">DLNA restarts when you apply: TVs and media players lose the connection for a moment.</p>{/if}
|
||||
{#each preview.files ?? [] as f (f.path)}<Diff file={f} />{/each}
|
||||
<div class="row end">
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
<script lang="ts">
|
||||
// Subfolders with their own access (F-DIR-9): POSIX ACLs on a subfolder
|
||||
// and everything inside. Not possible: greyed out with the reason and a
|
||||
// "Why?" link to the limitation (F-MON-11).
|
||||
import { untrack } from 'svelte';
|
||||
import { api } from '../lib/api';
|
||||
import type { Accounts, Level, Problem, Share, SubfolderEntry, SubfolderInfo, SubfolderResponse } from '../lib/types';
|
||||
import { toProblem } from '../lib/errors';
|
||||
import { whyHref } from '../lib/limitations';
|
||||
import { childPath, entriesProblem, levelWords, parentPath, sortEntries } from '../lib/subfolders';
|
||||
import Banner from './Banner.svelte';
|
||||
import HelpIcon from './HelpIcon.svelte';
|
||||
import LevelPicker from './LevelPicker.svelte';
|
||||
import Notice from './Notice.svelte';
|
||||
import Review from './Review.svelte';
|
||||
|
||||
let { share, accounts }: { share: Share; accounts: Accounts } = $props();
|
||||
|
||||
let info = $state<SubfolderInfo | null>(null);
|
||||
let loadProblem = $state<Problem | null>(null);
|
||||
type Mode = { kind: 'view' } | { kind: 'edit'; isNew: boolean } | { kind: 'remove'; path: string };
|
||||
let mode = $state<Mode>({ kind: 'view' });
|
||||
let pick = $state('');
|
||||
let entries = $state<SubfolderEntry[]>([]);
|
||||
let children = $state<string[] | null>(null);
|
||||
let addWho = $state('');
|
||||
let preview = $state<SubfolderResponse | null>(null);
|
||||
let problem = $state<Problem | null>(null);
|
||||
let ok = $state('');
|
||||
let warn = $state('');
|
||||
let busy = $state(false);
|
||||
|
||||
async function load() {
|
||||
const name = share.name;
|
||||
try {
|
||||
const got = await api.subfolders(name);
|
||||
if (name === share.name) { info = got; loadProblem = null; }
|
||||
} catch (err) { loadProblem = toProblem(err); }
|
||||
}
|
||||
// The page stays mounted when moving from one share to another.
|
||||
$effect(() => {
|
||||
void share.name;
|
||||
untrack(() => { info = null; mode = { kind: 'view' }; preview = null; problem = null; ok = ''; warn = ''; load(); });
|
||||
});
|
||||
|
||||
const ruled = $derived(new Set((info?.rules ?? []).map((r) => r.path)));
|
||||
|
||||
async function browse(rel: string) {
|
||||
pick = rel; children = null;
|
||||
try {
|
||||
const l = await api.folder(share.path + (rel ? '/' + rel : ''));
|
||||
children = l.entries.filter((e) => e.dir && !e.name.startsWith('.')).map((e) => e.name).sort((a, b) => a.localeCompare(b));
|
||||
} catch (err) { children = []; problem = toProblem(err); }
|
||||
}
|
||||
|
||||
function reset() { preview = null; problem = null; ok = ''; warn = ''; }
|
||||
function startNew() {
|
||||
reset(); entries = []; mode = { kind: 'edit', isNew: true }; browse('');
|
||||
}
|
||||
function startEdit(path: string, current: SubfolderEntry[]) {
|
||||
reset(); pick = path; entries = current.map((e) => ({ principal: { ...e.principal }, level: e.level })); mode = { kind: 'edit', isNew: false };
|
||||
}
|
||||
function startRemove(path: string) { reset(); mode = { kind: 'remove', path }; review(); }
|
||||
function cancel() { mode = { kind: 'view' }; preview = null; problem = null; }
|
||||
|
||||
const candidates = $derived([
|
||||
...accounts.groups.filter((g) => !g.system).map((g) => ({ kind: 'group' as const, name: g.name })),
|
||||
...accounts.users.map((u) => ({ kind: 'user' as const, name: u.name })),
|
||||
].filter((c) => !entries.some((e) => e.principal.kind === c.kind && e.principal.name === c.name)));
|
||||
|
||||
function add() {
|
||||
const [kind, name] = addWho.split(':') as ['user' | 'group', string];
|
||||
if (!name) return;
|
||||
entries = sortEntries([...entries, { principal: { kind, name }, level: 'read' as Level }]);
|
||||
addWho = '';
|
||||
}
|
||||
|
||||
const inputProblem = $derived(mode.kind === 'edit' ? (pick === '' ? 'Choose a subfolder.' : entriesProblem(entries)) : '');
|
||||
|
||||
async function review() {
|
||||
busy = true; problem = null;
|
||||
try {
|
||||
const run = (dry: boolean, base?: Record<string, string>) =>
|
||||
mode.kind === 'remove' ? api.removeSubfolder(share.name, mode.path, dry) : api.setSubfolder(share.name, pick, $state.snapshot(entries), dry, base);
|
||||
if (!preview) {
|
||||
preview = await run(true);
|
||||
} else {
|
||||
const res = await run(false, preview.versions);
|
||||
ok = res.summary + ' — applied to ' + res.items + (res.items === 1 ? ' item.' : ' folders and files.');
|
||||
warn = res.failed ? `${res.failed} item(s) couldn’t be changed, e.g. ${res.first_error}` : '';
|
||||
mode = { kind: 'view' }; preview = null;
|
||||
await load();
|
||||
}
|
||||
} catch (err) {
|
||||
problem = toProblem(err);
|
||||
if (mode.kind === 'remove' && !preview) mode = { kind: 'view' };
|
||||
} finally { busy = false; }
|
||||
}
|
||||
const count = (r: SubfolderResponse) => (r.more ? 'more than ' : '') + r.items.toLocaleString() + (r.items === 1 ? ' item' : ' folders and files');
|
||||
</script>
|
||||
|
||||
<section class="card" aria-labelledby="sub-title">
|
||||
<div class="row between">
|
||||
<h2 id="sub-title">Subfolders with their own access<HelpIcon term="acl" /></h2>
|
||||
{#if mode.kind === 'view' && info}<button class="btn sm" onclick={startNew} disabled={!info.available}>Add subfolder…</button>{/if}
|
||||
</div>
|
||||
<Notice problem={loadProblem} />
|
||||
{#if info === null}
|
||||
{#if !loadProblem}<p class="muted small">Checking…</p>{/if}
|
||||
{:else}
|
||||
{#if !info.available}
|
||||
<div class="off">
|
||||
<p class="small"><span class="pill">not available</span> {info.reason}</p>
|
||||
<p class="facts">Access is the same in every subfolder of this share.
|
||||
<a href={info.limitation ? whyHref(info.limitation) : '#/help?term=acl'}>Why? What does it affect?</a></p>
|
||||
</div>
|
||||
{:else if info.rules.length === 0 && mode.kind === 'view'}
|
||||
<p class="muted small">None: the share’s access applies in every subfolder. A subfolder can get its own, e.g. <i>Finances</i> only for the parents.</p>
|
||||
{/if}
|
||||
|
||||
{#if info.rules.length}
|
||||
<ul class="rules">
|
||||
{#each info.rules as r (r.path)}
|
||||
<li>
|
||||
<div class="row between wrap">
|
||||
<span class="mono path">📁 {r.path}</span>
|
||||
{#if mode.kind === 'view'}
|
||||
<span class="row">
|
||||
{#if !r.missing && info.available}<button class="btn sm" onclick={() => startEdit(r.path, r.entries)} aria-label={'Edit access of ' + r.path}>Edit</button>{/if}
|
||||
<button class="btn sm" onclick={() => startRemove(r.path)} aria-label={'Remove own access of ' + r.path}>Remove</button>
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if r.missing}
|
||||
<span class="pill bad">folder is gone</span> <span class="small muted">Removing the rule only removes it from this list.</span>
|
||||
{:else}
|
||||
<div class="pills">
|
||||
{#each r.entries as e (e.principal.kind + ':' + e.principal.name)}
|
||||
<span class="pill" class:acc={e.level === 'write'} class:ok={e.level === 'read'}>{e.principal.kind === 'group' ? '👥' : '👤'} {e.principal.name} · {levelWords(e.level)}</span>
|
||||
{/each}
|
||||
<span class="pill">✱ everyone else · no access</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if r.custom?.length}
|
||||
<Banner kind="warn" compact>Changed outside Sharestead:{#each r.custom as c (c)}<br />• {c}{/each}<br /><span class="small">Save the rule again to set it as shown.</span></Banner>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if mode.kind === 'edit'}
|
||||
<fieldset class="editor" disabled={!!preview}>
|
||||
<legend class="sr-only">Subfolder and access</legend>
|
||||
{#if mode.isNew}
|
||||
<p class="f" id="pick-label">Folder</p>
|
||||
<div class="picker" role="group" aria-labelledby="pick-label">
|
||||
<div class="row wrap">
|
||||
<span class="mono"><b>{share.name}/{pick}</b>{#if pick === ''} <span class="muted">— choose below</span>{/if}</span>
|
||||
{#if pick !== ''}<button class="btn sm" onclick={() => browse(parentPath(pick))}>↑ Up</button>{/if}
|
||||
</div>
|
||||
{#if children === null}
|
||||
<p class="muted small">Loading folders…</p>
|
||||
{:else if children.length === 0}
|
||||
<p class="muted small">No subfolders here{pick === '' ? ' — create one on the Folders page first' : ''}.</p>
|
||||
{:else}
|
||||
<ul class="kids">
|
||||
{#each children as c (c)}
|
||||
{@const p = childPath(pick, c)}
|
||||
<li><button class="linkish" onclick={() => browse(p)} disabled={ruled.has(p)}>📁 {c}</button>{#if ruled.has(p)} <span class="muted small">has its own access</span>{/if}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="small">Folder: <b class="mono">{share.name}/{pick}</b></p>
|
||||
{/if}
|
||||
|
||||
<table class="levels">
|
||||
<tbody>
|
||||
{#each entries as e, i (e.principal.kind + ':' + e.principal.name)}
|
||||
<tr>
|
||||
<td>{e.principal.kind === 'group' ? '👥' : '👤'} <b>{e.principal.name}</b> <span class="muted small">{e.principal.kind}</span>
|
||||
<button class="linkish" aria-label={'Remove ' + e.principal.name} onclick={() => (entries = entries.filter((_, j) => j !== i))}>remove</button></td>
|
||||
<td class="right"><LevelPicker bind:value={entries[i]!.level} label={e.principal.name ?? ''} allowNone={e.principal.kind === 'user'} /></td>
|
||||
</tr>
|
||||
{/each}
|
||||
<tr><td>✱ <b>Everyone else</b></td><td class="right"><span class="pill">No access</span></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="row add">
|
||||
<label class="sr-only" for="sub-add">Add user or group</label>
|
||||
<select id="sub-add" class="t" bind:value={addWho}>
|
||||
<option value="">+ Add user or group…</option>
|
||||
{#each candidates as c (c.kind + c.name)}<option value={c.kind + ':' + c.name}>{c.kind === 'group' ? '👥 ' : '👤 '}{c.name}</option>{/each}
|
||||
</select>
|
||||
<button class="btn sm" onclick={add} disabled={!addWho}>Add</button>
|
||||
</div>
|
||||
<p class="facts">Only the people listed get in; the share’s access still applies on top. Set a user to <i>No access</i> to keep them out of a listed group. Owners keep their rights to their own files inside.</p>
|
||||
{#if inputProblem && entries.length}<p class="small warnline" role="status">{inputProblem}</p>{/if}
|
||||
</fieldset>
|
||||
{/if}
|
||||
|
||||
{#if mode.kind !== 'view'}
|
||||
<Notice {problem} />
|
||||
{#if preview}
|
||||
<p class="small mt">{preview.summary}. Sets the permissions of {count(preview)}{mode.kind === 'remove' ? ' back to what the folder above gives' : ''}.</p>
|
||||
<Review {preview} {busy} label={mode.kind === 'remove' ? 'Remove own access' : 'Apply'} onapply={review} oncancel={() => (preview = null)}
|
||||
disk={'Permissions on disk are listed in the change history but can’t be undone there: ' + (mode.kind === 'remove' ? 'to go back, give the subfolder its own access again.' : 'to go back, change or remove the subfolder’s own access.')} />
|
||||
{:else if mode.kind === 'edit'}
|
||||
<div class="row end"><button class="btn" onclick={cancel}>Cancel</button><button class="btn primary" onclick={review} disabled={busy || !!inputProblem}>Review changes</button></div>
|
||||
{:else}
|
||||
<div class="row end"><button class="btn" onclick={cancel}>Cancel</button></div>
|
||||
{/if}
|
||||
{/if}
|
||||
{#if mode.kind === 'view'}<Notice {ok} />{#if warn}<Banner kind="warn" compact>{warn}</Banner>{/if}{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.off { opacity: .75; }
|
||||
.rules { list-style: none; margin: 8px 0 0; padding: 0; }
|
||||
.rules li { padding: 10px 0; border-top: 1px solid var(--line); }
|
||||
.path { font-weight: 600; overflow-wrap: anywhere; }
|
||||
.pills { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
|
||||
.editor { margin: 10px 0 0; padding: 6px 0 0; border: 0; border-top: 1px solid var(--line); min-width: 0; }
|
||||
.editor:disabled { opacity: .7; }
|
||||
.picker { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; margin-bottom: 10px; }
|
||||
.kids { list-style: none; margin: 6px 0 0; padding: 0; columns: 2 180px; }
|
||||
.kids li { padding: 2px 0; }
|
||||
.add { margin-top: 10px; } .add select { max-width: 320px; }
|
||||
.end { justify-content: flex-end; margin-top: 12px; }
|
||||
.right { text-align: right; }
|
||||
.mt { margin-top: 12px; }
|
||||
.warnline { color: var(--warn); }
|
||||
@media (max-width: 700px) {
|
||||
.levels tr { display: grid; gap: 6px; padding: 8px 0; border-bottom: 1px solid var(--line); }
|
||||
.levels td { border: 0; padding: 0; }
|
||||
.levels td.right { text-align: left; }
|
||||
}
|
||||
</style>
|
||||
+6
-1
@@ -1,4 +1,4 @@
|
||||
import type { DLNAStatus, MediaDir, PasskeyInfo, Me, HomesStatus, UpdateStatus, FolderCapabilities, StorageReport, HealthProblem, Client, ServiceStatus, FolderEntry, FolderListing, FolderStats, AccessSpec, Accounts, ChangeFilter, ChangesPage, EditResponse, RestoreResponse, NFSClient, Problem, SambaSettings, SessionInfo, Share, ShareOptions } from './types';
|
||||
import type { DLNAStatus, MediaDir, PasskeyInfo, Me, HomesStatus, UpdateStatus, FolderCapabilities, StorageReport, HealthProblem, Client, ServiceStatus, FolderEntry, FolderListing, FolderStats, AccessSpec, Accounts, ChangeFilter, ChangesPage, EditResponse, RestoreResponse, NFSClient, Problem, SambaSettings, SessionInfo, Share, ShareOptions, SubfolderEntry, SubfolderInfo, SubfolderResponse } from './types';
|
||||
|
||||
/** An API call that failed. Carries the server's problem details. */
|
||||
export class ApiError extends Error {
|
||||
@@ -131,6 +131,11 @@ export const api = {
|
||||
createGroup: (name: string, members: string[]) => request<void>('POST', '/api/v1/groups', { name, members }),
|
||||
setMembers: (name: string, members: string[]) => request<void>('PUT', '/api/v1/groups/' + encodeURIComponent(name) + '/members', { members }),
|
||||
updates: (fresh = false) => request<UpdateStatus>('GET', '/api/v1/updates' + (fresh ? '?fresh=1' : '')),
|
||||
subfolders: (name: string) => request<SubfolderInfo>('GET', '/api/v1/shares/' + encodeURIComponent(name) + '/subfolders'),
|
||||
setSubfolder: (name: string, path: string, entries: SubfolderEntry[], dry: boolean, base?: Record<string, string>) =>
|
||||
request<SubfolderResponse>('PUT', '/api/v1/shares/' + encodeURIComponent(name) + '/subfolders' + (dry ? '?dry_run=1' : ''), { path, entries, base }),
|
||||
removeSubfolder: (name: string, path: string, dry: boolean) =>
|
||||
request<SubfolderResponse>('DELETE', '/api/v1/shares/' + encodeURIComponent(name) + '/subfolders' + (dry ? '?dry_run=1' : ''), { path }),
|
||||
setShareLimit: (name: string, limit: number) => request<void>('PUT', '/api/v1/shares/' + encodeURIComponent(name) + '/limit', { limit }),
|
||||
folderCapabilities: (fresh = false) => request<FolderCapabilities>('GET', '/api/v1/folders/capabilities' + (fresh ? '?fresh=1' : '')),
|
||||
homes: () => request<{ homes: HomesStatus; default_limit: number }>('GET', '/api/v1/homes'),
|
||||
|
||||
@@ -24,7 +24,7 @@ export const glossary: Record<string, Entry> = {
|
||||
available: { title: 'Share switched on', body: 'Off keeps all settings, but nobody can open the share until you switch it on again.', tech: 'available = no' },
|
||||
hideDot: { title: 'Hide dot files', body: 'Files whose name starts with a dot (settings files from Mac and Linux) are hidden on Windows. They still exist.', tech: 'hide dot files' },
|
||||
uid: { title: 'User ID (UID)', body: 'The number Linux uses to know who owns a file. NFS sends the number from the PC, so a person needs the same UID on their PC and on the NAS.', tech: 'id -u · /etc/passwd' },
|
||||
acl: { title: 'Subfolder permissions', body: 'Lets a folder inside a share have its own access, e.g. Family/Finances only for alex. It needs POSIX ACLs on the storage folder; without them, access is set per share, which is enough for most homes.', tech: 'POSIX ACLs on the folder · Samba: inherit acls' },
|
||||
acl: { title: 'Subfolder permissions', body: 'Lets a folder inside a share have its own access, e.g. Family/Finances only for alex. It needs POSIX ACLs on the storage folder; without them, access is set per share, which is enough for most homes.', tech: 'POSIX ACLs (access + default) on the subfolder and everything inside; the subfolder belongs to root · Samba create masks keep group rw' },
|
||||
posixAcl: { title: 'ACL (POSIX ACL)', body: 'An access list on a file or folder: besides owner, one group and everyone else, it can give more users and groups their own rights. The filesystem must support it and have it switched on (ext4, XFS and btrfs usually do; ZFS when enabled); Windows shows ACLs on the Security tab. Off: each folder has just owner, group and others.', tech: 'getfacl / setfacl · acl, posixacl' },
|
||||
shareGroup: { title: 'Share group', body: 'A folder created together with a share gets its own group, so files stay usable for everyone with access, whoever created them.', tech: 'force group = sst-<name> · mode 0770' },
|
||||
changes: { title: 'Changes and undo', body: 'Every change Sharestead makes, and every hand edit of a managed config file, is recorded with the exact lines. Undo writes the old lines back, unless later changes touched them.', tech: 'journal in /var/lib/sharestead' },
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { childPath, entriesProblem, levelWords, parentPath, sortEntries } from './subfolders';
|
||||
import type { SubfolderEntry } from './types';
|
||||
|
||||
const u = (name: string, level: SubfolderEntry['level']): SubfolderEntry => ({ principal: { kind: 'user', name }, level });
|
||||
const g = (name: string, level: SubfolderEntry['level']): SubfolderEntry => ({ principal: { kind: 'group', name }, level });
|
||||
|
||||
describe('subfolder paths', () => {
|
||||
it('joins and splits relative paths', () => {
|
||||
expect(childPath('', 'Finances')).toBe('Finances');
|
||||
expect(childPath('Finances/', '2026')).toBe('Finances/2026');
|
||||
expect(childPath('/Photos', 'x')).toBe('Photos/x');
|
||||
expect(parentPath('Finances/2026')).toBe('Finances');
|
||||
expect(parentPath('Finances')).toBe('');
|
||||
expect(parentPath('')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('entriesProblem (same rules as the API)', () => {
|
||||
it('needs someone with access', () => {
|
||||
expect(entriesProblem([])).toMatch(/at least one/);
|
||||
expect(entriesProblem([u('alex', 'none')])).toMatch(/at least one/);
|
||||
expect(entriesProblem([u('alex', 'read')])).toBe('');
|
||||
expect(entriesProblem([g('parents', 'write'), u('sam', 'none')])).toBe('');
|
||||
});
|
||||
it('refuses No access for a group, and says how to keep one member out', () => {
|
||||
expect(entriesProblem([u('alex', 'write'), g('family', 'none')])).toMatch(/family.*add that user with No access/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('levelWords and sortEntries', () => {
|
||||
it('words each level', () => {
|
||||
expect([levelWords('write'), levelWords('read'), levelWords('none')]).toEqual(['read & write', 'read', 'no access']);
|
||||
});
|
||||
it('lists groups first, then users, by name', () => {
|
||||
expect(sortEntries([u('kim', 'read'), g('parents', 'write'), u('alex', 'write'), g('kids', 'read')]).map((e) => e.principal.name)).toEqual(['kids', 'parents', 'alex', 'kim']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// Subfolder permissions (F-DIR-9): helpers for the share page's card.
|
||||
import type { Level, SubfolderEntry } from './types';
|
||||
|
||||
/** Joins a subfolder path (relative to the share folder) and a child name. */
|
||||
export function childPath(rel: string, name: string): string {
|
||||
const base = rel.replace(/^\/+|\/+$/g, '');
|
||||
return base ? base + '/' + name : name;
|
||||
}
|
||||
|
||||
/** The parent of a relative subfolder path ('' = the share folder). */
|
||||
export function parentPath(rel: string): string {
|
||||
const parts = rel.replace(/^\/+|\/+$/g, '').split('/');
|
||||
parts.pop();
|
||||
return parts.join('/');
|
||||
}
|
||||
|
||||
/** What's wrong with a list of entries, in the words the backend uses ('' = fine). */
|
||||
export function entriesProblem(entries: SubfolderEntry[]): string {
|
||||
if (!entries.some((e) => e.level === 'read' || e.level === 'write')) return 'Give at least one user or group Read or Read & write.';
|
||||
const g = entries.find((e) => e.principal.kind === 'group' && e.level === 'none');
|
||||
if (g) return `Group ${g.principal.name}: No access isn’t needed — anyone not listed has no access. To keep one member out, add that user with No access.`;
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Short words for a level, as in the share's pills. */
|
||||
export const levelWords = (l: Level) => (l === 'write' ? 'read & write' : l === 'read' ? 'read' : 'no access');
|
||||
|
||||
/** Groups first, then users, each by name (as the backend lists them). */
|
||||
export function sortEntries(entries: SubfolderEntry[]): SubfolderEntry[] {
|
||||
return [...entries].sort((a, b) => (a.principal.kind === b.principal.kind ? (a.principal.name ?? '').localeCompare(b.principal.name ?? '') : a.principal.kind === 'group' ? -1 : 1));
|
||||
}
|
||||
@@ -30,6 +30,10 @@ export interface Accounts { users: User[]; groups: Group[]; admin_group: string
|
||||
export interface DiffOp { kind: number; text: string } // 32 ' ' same, 45 '-' removed, 43 '+' added, 126 '~' skipped
|
||||
export interface FilePreview { path: string; diff: DiffOp[]; warnings?: string[] }
|
||||
export interface EditResponse { files?: FilePreview[]; versions?: Record<string, string>; entry?: { id: string; summary: string } }
|
||||
export interface SubfolderEntry { principal: Principal; level: Level }
|
||||
export interface SubfolderRule { path: string; entries: SubfolderEntry[]; custom?: string[]; missing?: boolean }
|
||||
export interface SubfolderInfo { available: boolean; reason?: string; limitation?: string; rules: SubfolderRule[] }
|
||||
export interface SubfolderResponse extends EditResponse { items: number; more?: boolean; failed?: number; first_error?: string; summary: string }
|
||||
export interface RestoreResponse extends EditResponse { skipped?: string[] }
|
||||
export interface AccessSpec { guests: Level; everyone: Level; named: Access[] }
|
||||
export interface Change { id: string; time: string; actor: string; summary: string; kind?: string; undo_of?: string; undone_by?: string; files: FilePreview[] }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import ProtocolChecks from '../components/ProtocolChecks.svelte';
|
||||
import ShareLimitCard from '../components/ShareLimitCard.svelte';
|
||||
import SubfolderCard from '../components/SubfolderCard.svelte';
|
||||
import { protocolChecks } from '../lib/protocols';
|
||||
import { services as svcState } from '../lib/services-state.svelte';
|
||||
import { onMount as onMountSvc } from 'svelte';
|
||||
@@ -185,6 +186,10 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if share.path && !share.homes}
|
||||
<div class="mt"><SubfolderCard {share} {accounts} /></div>
|
||||
{/if}
|
||||
|
||||
<div class="grid g2 mt">
|
||||
<div class="card">
|
||||
<h2>Available via</h2>
|
||||
|
||||
Reference in new issue
Block a user