okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
4.0 KiB100 linesraw
1"""POSIX 'owner-only' checks that repair what is ours and explain what is not.
2
3Strata keeps its private state in folders (0700) and files (0600) of the user. The checks used to refuse as soon as a mode had drifted
4(a `chmod -R`, an rsync, a restored backup) or the owner was not the current user (one `sudo strata ...` leaves root-owned folders behind).
5Now:
6
7* the folder or file is ours and only the mode bits are wrong: the mode is put back (0700 / 0600) and the command goes on;
8* the filesystem cannot hold modes at all (a Windows drive seen from WSL, vfat, some network shares): one note, then it goes on;
9* another account owns it (root after sudo): the check still refuses, because that is the real boundary, but the message names the
10  cause and the exact command that fixes it.
11
12Windows has no mode bits; its own check lives in `private_files` and is not touched here.
13"""
14
15from __future__ import annotations
16
17import os
18import stat
19import sys
20from pathlib import Path
21
22POSIX = os.name == "posix"
23_NOTED: set[str] = set()
24
25
26def owner_only_wrong(path: str | os.PathLike, details: os.stat_result) -> bool:
27    """True when `path` (whose lstat or fstat is `details`) is not private to this user and could not be made so.
28
29    Replaces `details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077`. Never follows a link and never touches
30    a file that another account owns.
31    """
32    if not POSIX:
33        return False
34    if details.st_uid != os.getuid():
35        return True
36    if not stat.S_IMODE(details.st_mode) & 0o077:
37        return False
38    if stat.S_ISLNK(details.st_mode):
39        return True
40    want = 0o700 if stat.S_ISDIR(details.st_mode) else 0o600
41    try:
42        os.chmod(path, want)                              # not a link (checked above), so this is the file itself
43        after = os.lstat(path)
44    except (OSError, NotImplementedError):
45        after = None
46    if after is not None and after.st_uid == os.getuid() and not stat.S_IMODE(after.st_mode) & 0o077:
47        return False
48    # The mode did not stick although the owner is right: the filesystem has no real modes. Say it once and carry on.
49    folder = str(path if stat.S_ISDIR(details.st_mode) else Path(path).parent)
50    if folder not in _NOTED:
51        _NOTED.add(folder)
52        print(f"strata: {folder} is on a drive that cannot keep files private to your account (a Windows drive seen from Linux, "
53              "a USB stick or a network share). Strata goes on; keep your data on the Linux disk to make it private.", file=sys.stderr)
54    return False
55
56
57def _owner_name(uid: int) -> str:
58    try:
59        import pwd
60        return pwd.getpwuid(uid).pw_name
61    except (ImportError, KeyError):
62        return f"user {uid}"
63
64
65def fix_target(path: str | os.PathLike) -> Path:
66    """The highest folder above `path` (below the home folder) that another account owns: one `chown` there fixes the whole tree."""
67    target = Path(path)
68    home = Path.home()
69    uid = os.getuid()
70    best = target
71    current = target
72    for _ in range(6):
73        parent = current.parent
74        if parent == current or parent == home or parent == Path(parent.anchor):
75            break
76        try:
77            if parent.lstat().st_uid == uid:
78                break
79        except OSError:
80            break
81        best = parent
82        current = parent
83    return best
84
85
86def owner_only_text(text: str, path: str | os.PathLike) -> str:
87    """The message for a refused check. `text` is the old sentence ("recipe directory must be owner-only"); when another account owns
88    `path` it becomes a sentence with the cause and the exact command, otherwise it is returned unchanged."""
89    if not POSIX:
90        return text
91    try:
92        owner = os.lstat(path).st_uid
93    except OSError:
94        return text
95    if owner == os.getuid():
96        return text
97    subject = text.split(" must ")[0].split(" is not ")[0].strip()
98    target = fix_target(path)
99    return (f"{subject} belongs to {_owner_name(owner)}, not to you (usually from running Strata once with sudo). "
100            f"Run this once, then try again: sudo chown -R \"$USER\" {target}")