TL;DR
- One number, four rules.
EACCES(errno 13) is the kernel’s answer when the object’s own bits deny the class that applies, when an ancestor directory has no x, when the object belongs to another account and its other-class bits are clear, or when what is missing is a privilege rather than a bit. Of 38 calls, 21 answered 13, and the twelve rows in Section 5 carry that number five times, from those four rules. - The class is chosen before a bit is read. Owner if the effective uid matches, group if any group id does, otherwise other – and only that class’s three bits count. This account is uid 1000 with 0 supplementary groups and a umask of 0022, so the group class is the one branch this page could not exercise; it says so instead of asserting it.
- x on every directory in the path is the bit people forget. A 0444 directory refused a read of a 0644 file inside it and refused a
statof that file too, while a 0111 directory let the same open through – the file’s own mode never changed. - Deletion is a directory permission. A 0444 file was removed without complaint from a 0755 directory, and a 0644 file survived in a 0555 one. The walk behind this page reports that path in 23.58 µs and agreed with the kernel on 17 of 17 in-scope calls.
Fix It First: Twelve Changes, Matched to What You Saw
| What you saw | What refused, in the kernel’s terms | Change this |
|---|---|---|
PermissionError: [Errno 13] Permission denied on a file the service owns | The file’s own bits deny the class that applies: a 0400 file opened for write answered 13 | Give the class the bit it needs, not the class you assume: chmod u+w when the owner asks, chmod g+w when the group does |
| The file is 0644 and exists, and the open still fails | A directory in the path lacks x, so the walk stops before the file is reached: a 0444 directory refused a 0644 file inside it | Walk the path yourself and fix the first component: namei -l, or permwhy.explain(path, Want.READ).first |
| A container’s service cannot write its own working directory | The volume is owned by another uid, so the service falls in the other class and the 0755 bits grant it no write (13 in the matrix) | chown -R the mount to the runtime uid, or mount it with that uid; check with stat -c '%u:%g %a %n' before blaming the application |
unlink of a read-only file is refused | The directory holding the name lacks w: a 0644 file in a 0555 directory answered 13 | Give the directory w (and x), not the file |
shutil.rmtree stops on a file nobody can write | rmtree needs w+x on each directory it empties; the file’s own bits are irrelevant (13 on this host) | Clear the directory bits first, or remove the tree from a process that owns it |
ls lists a directory but ls -l fails | Listing needs r, and each entry’s stat needs x: a 0333 directory listed nothing (13) and a 0444 directory answered 13 to stat | Add x to read metadata, r to read names |
A write to /proc/sys/... or /sys/... is refused although the file looks writable at 0644 | 0644 gives the other class no w, and the file belongs to root, so a service user is refused by the mode before any handler runs: 13 here, and whether the interface would also refuse is not separated by this arm | Write through the tool that owns the interface (sysctl, the subsystem’s own knob); if a uid-0 process is still refused, the handler is the refusal |
chmod fails with EPERM (1), not 13 | Only the owner may set a mode: procfs answered 1 to a non-owner | Run as the owner, or change ownership first; no mode makes chmod succeed |
create fails in a directory whose mode looks writable | The mount is read-only, which is checked before the bits: /usr here answered 30 | Check /proc/mounts for ro before editing any mode |
| Two processes, one directory, and only one of them can delete | The directory holding the name has the last word, and the sticky bit narrows it further; the one arm here that touched /tmp answered 13 from the parent directory’s bits, before the sticky bit was read at all | Delete from the owning uid, or move the file’s work into a directory that directory’s owner controls |
| A script fails with 13, and the same script fails with 8 when made executable | 13 is the missing x bit and 8 is ENOEXEC, a format the kernel cannot run: 13 and 8 | Run a script through its interpreter, or give it a shebang and x |
bind to port 80 is denied to a service user | Ports below the privileged boundary need a capability this process does not have: 13 here | Bind above the boundary and forward, or grant the capability deliberately |
One name in that table is not a package to install: permwhy.explain is the code this page prints in its appendix – permwhy/model.py for the bits and permwhy/walk.py for the walk – so the call runs from a copy of that tree, laid out as the appendix shows, and no pip install provides it.
Before Anything Else: One strace
One command shows the call that failed instead of the message that reached the log: strace -Z -f -e trace=%file and then the command that failed. -Z keeps only the calls that returned an error; -z, one letter down, is its opposite and keeps only the ones that succeeded. Both arrived in strace 5.2 as aliases of -e status=, the spelling to reach for when a build’s letters are in doubt. %file keeps the calls that take a path, and the failing line is the kernel’s own account: openat(AT_FDCWD, "/srv/app/upload", O_WRONLY|O_CREAT, 0666) = -1 EACCES (Permission denied).
The number on the right is the one this page is about, and the flags beside the path are the access the process asked for, which a log line drops. EROFS (30) on the same call would say the mount refused before any bit was read, ENOENT (2) that the path never existed. What the line cannot say is which component of the path refused, because the kernel reports the path the call passed and not the step it stopped at – the gap Section 6 fills.
d=$(mktemp -d); printf 'payload\n' > "$d/file"; chmod 0444 "$d"
command -v strace >/dev/null && echo "strace: $(strace -V | head -n 1)" || echo "strace: not installed"
strace -Z -f -e trace=%file python3 -c 'import sys; open(sys.argv[1])' "$d/file" 2>&1 | tail -n 2
chmod 0755 "$d"; rm -rf "$d"
On this host the block stops at its second line: strace is not installed, and the binary unpacked from the Debian package for the attempt is refused ptrace by the container’s seccomp profile. That binary’s --help still settles the two letters, which is where the command above comes from; Section 6 carries the version and the errno, and says which part of a trace is quoted rather than captured.
1. The Denial Itself
open(2) writes one sentence for four conditions: the requested access is not allowed, or search permission is denied for a directory in the path prefix, or the file did not exist and the parent cannot be written, or the file is being executed and is not executable. All four become the same three words in a log. That compression is why Permission denied is the least useful line in an incident: it is equally true of a file whose own bits refuse, of a directory three levels above it, and of a mount that was never writable.
The matrix behind this page is 38 calls, each made 5 times on Python 3.12.16 against kernel 6.12.118-guest-1.1 as uid 1000. Every repeat of every call answered identically, so the table below states rules, not samples. 21 of those calls answered errno 13 and 9 succeeded; the rest carry EPERM (1), EROFS (30) and the other errnos Section 5 lists – 9 distinct numbers in all.
| The call | The object and its mode | Class | Answered |
|---|---|---|---|
open(O_RDONLY) | file 0000 | owner | 13 |
open(O_WRONLY) | file 0400 | owner | 13 |
execve | script 0600 | owner | 13 |
open(O_RDONLY) on a 0644 file | directory 0444 above it | owner | 13 |
open(O_RDONLY) | /etc/ssl/private, mode 0700 root | other | 13 |
open(O_WRONLY) | /usr/bin/true, mode 0755 root | other | 13 |
chmod | procfs file, mode 0644 root | other | 1 |
open(O_CREAT) | /usr/bin, a read-only mount | other | 30 |
The shape that falls out is short. There are bits on the object, there is x on every directory the path passes through, there is ownership – which a chmod checks instead of any bit, and answers EPERM rather than EACCES – and there are refusals that are not modes at all: a read-only mount, a privileged port, and an interface that can refuse after the mode. Sections 2 to 5 take those in turn, each with the arms that measured it and the claims left to the manual; Section 6 turns the rules into a prediction; Sections 7 to 9 price it, wrap it for Python, and print the package.
2. Who You Are to the Kernel
Before a single mode bit is read, the kernel decides which third of the mode word belongs to your process. It compares three ids: the effective uid against the file’s owner, then the effective gid and every supplementary group against the file’s group, and if none match, the process is other. On this host the account is uid 1000, gid 1000, with 0 supplementary groups and a umask of 0022, which is why the files it creates arrive as 0644 and the directories as 0755.
| The call | Object, mode, owner | Class that applied | Answered |
|---|---|---|---|
open(O_RDONLY) | file 0400, this account | owner | 0 |
open(O_RDONLY) | file 0200, this account | owner | 13 |
execve | script 0600, this account | owner | 13 |
open(O_RDONLY) | /etc/ssl/private, 0700 root | other | 13 |
open(O_WRONLY) | /usr/bin/true, 0755 root | other | 13 |
connect to a unix socket | socket 0500, this account | owner | 13 |
The order matters more than the arithmetic, and one mode shows it. A directory at 0077 – group and other wide open, the owner triplet cleared – refused a 0644 file inside it to the account that owned the directory (13), and refused a stat of the same file (13); the same directory at 0777 answered the same open with 0. Ownership picks which three bits are read, so a mode that clears only the owner triplet locks out the owner and would let a stranger in. The file alone can do the same: with every directory above it at 0755 and the file itself at 0077, a read of it was refused (13). Both repair the same way – put the owner triplet back rather than widen anything – but they are different objects: with the directory at 0700 and the 0644 file inside it untouched, the open and the stat of that file both succeeded (0 and 0).
The group class needs a second identity and a file owned by it; this account has 0 supplementary groups and cannot change a file’s group, so every group claim below is the documented rule, not a measurement. Root’s bypass needs CAP_DAC_OVERRIDE – the effective mask here is 0000000000000000, and the account is not root – so a root process reading a 0000 file is quoted from the manual, and Section 9 prints the module applying that rule to an identity whose euid is 0 on the same basis. No ACL was set on any arm below and setfacl is absent, so none was in play. Any of these can turn a prediction of allowed into a refusal after the nine bits said yes, which is why Section 6 calls its answer a prediction.
id -u; id -g; umask; stat -c '%A %a %u:%g %n' /etc/ssl/private /usr/bin/true /usr/bin
cat /etc/ssl/private 2>&1 | tail -n 1
The block prints the identity the kernel will use, the mode of an object this account cannot open, and the same refusal an application sees, in one screen. The stat lines are checked against Python’s own view in the harness, and the two agree; the refused read reports Permission denied.
3. The Directory Bit Nobody Checks
The x bit on a directory is called search permission, and it is asked for separately from anything about the file. Every component of the path the kernel walks must grant it to the process’s class, including the last directory before the file. Take x away from a directory that holds a perfectly ordinary 0644 file and nothing inside it can be opened, stat’ed or executed; the file’s mode is not consulted at all, because the walk never arrives.
Two arms make the point without any ambiguity. A 0444 directory – readable, not searchable – answered 13 to an open(O_RDONLY) of a 0644 file inside it, and the same directory answered 13 to a stat of that file. With the directory at 0111 – searchable, not readable – the same open answered 0: the file is reachable by name, and nothing about its contents is listable.
Listing and searching are the other way round. A 0333 directory, writable and searchable, refused to list its entries (13); a 0111 directory refused as well (13); a 0555 directory listed them (0). Reading names needs r. Reading metadata needs x on every directory above the entry, which is why ls can print names where ls -l prints question marks.
| Directory mode | What was asked of it | Answered |
|---|---|---|
0111 | chdir into it | 0 |
0444 | chdir into it | 13 |
0333 | list its entries | 13 |
0111 | list its entries | 13 |
0555 | list its entries | 0 |
0444 | open the 0644 file inside | 13 |
0111 | open the 0644 file inside | 0 |
0444 | stat the 0644 file inside | 13 |
A symbolic link is the third place this bites. The link itself carries 0777 and the kernel ignores it entirely; what counts is the directory holding the link and the mode of the target. A link that points at a 0644 file from inside a 0000 directory answered 13, which reads like a permission problem on the target and is a permission problem on the link’s directory. The lesson for a deployment is short: when a path is refused and the file looks right, print the mode of every component, not the last one. That is what the walk in Section 6 does, and it is why the walk reports a component rather than a bit.
4. Delete Is a Directory Permission
Creating, renaming and deleting are operations on a name, and names live in directories. Each of the three needs w and x on the directory that holds the name; the mode of the file itself does not enter the decision. Two arms show it from both sides: a 0444 file was unlinked without complaint from a 0755 directory (0), and a 0644 file survived in a 0555 directory (13). The same rule covers mkdir (13) and a rename out of a locked directory (13).
| Operation | Directory mode | Answered |
|---|---|---|
| create a file | 0555 | 13 |
| create a file | 0755 | 0 |
| unlink a 0444 file | 0755 | 0 |
| unlink a 0644 file | 0555 | 13 |
mkdir | 0555 | 13 |
| rename a file out | 0555 | 13 |
d=$(mktemp -d)
printf 'payload\n' > "$d/file"
chmod 0444 "$d/file"
rm "$d/file" && echo "removed a 0444 file: yes"
printf 'payload\n' > "$d/file"
chmod 0555 "$d"
python3 -c "import sys; open(sys.argv[1], 'w')" "$d/new" 2>&1 | tail -n 1
chmod 0755 "$d"
python3 -c "import sys; open(sys.argv[1], 'w').close(); print('write after chmod: ok')" "$d/new"
rm -rf "$d"
Copied as printed, that block removes a read-only file, is refused a create in the directory that held it, then creates the file once the directory is opened up. Rerun here, all three lines came back: the removal printed its confirmation, the create was refused with Permission denied, and the write after the chmod printed its own line. The file’s mode changes once, at the top, where the point is that it does not matter.
The sticky bit is the one addition to this rule, and this page did not isolate it. /tmp is mode 1777, owned by root, and a rename of that directory by this account answered 13; but the name lives in /, which is 0755 root, so that refusal came from the parent’s bits before the sticky bit was ever read, and the arm is silent on the sticky rule itself. The rule is therefore quoted: with the sticky bit set, a name may be changed only by the name’s owner, the directory’s owner, or a process with the capability to override both. The tests reach it with a hand-made identity, which is the only way on a one-account host: a stranger is refused a file in someone else’s 1777 directory, and its owner is not.
5. What Looks Like Permission and Is Not
Once Permission denied is in a log, the first question is whether the kernel was refusing on a mode at all. 12 rows follow: 5 answer 13, from 4 rules (a root-owned file meets the same rule twice), and the other 7 answer a number no mode can move. Telling the two groups apart is most of the work.
| Number | What it is | The arm that answered it |
|---|---|---|
13 | the object’s own bits deny the class that applies | read a 0400 file for write: 13 |
13 | an ancestor directory has no x | open a 0644 file through a 0444 directory: 13 |
13 | the other-class bits are clear | write a 0755 root file as uid 1000: 13 |
13 | no w for the class, on a root-owned 0644 file, before any handler runs | write a 0644 procfs file: 13 |
13 | a privilege, not a mode, is missing | bind port 80: 13 |
1 | ownership, which no mode fixes | chmod a root file as uid 1000: 1 |
30 | the mount is read-only | create in the read-only /usr: 30 |
2 | the name does not exist | open a name that was never there: 2 |
17 | the name already exists | O_CREAT|O_EXCL on an occupied name: 17 |
21 | the name is a directory, opened for write | open a directory O_WRONLY: 21 |
20 | a component is a file, not a directory | open a name below a file: 20 |
8 | the file is executable but not runnable | execve a text file with x set: 8 |
The EROFS row is the one that changes how a reader should order their checks. /usr on this host is a read-only overlay – its mount options begin ro – so a create there answered 30 before the ownership question was ever asked, and a chmod of a root-owned file under it answered the same number rather than the EPERM it answers on a writable filesystem. That pair fixes the first two steps: the mount, then ownership. A runbook that starts with chmod starts in the wrong place. What it does not fix is where an interface handler sits: the procfs arm met a 0644 file whose other-class bits already deny the write, so its 13 is the mode’s answer, and a handler that would also refuse is quoted from the manual, not measured here.
Two more names belong in the list but not in this table, because no arm reached them: ELOOP (40) for a symlink chain that never resolves, and ENAMETOOLONG (36) for a component over the filesystem’s limit. Both are documented rules, not measurements here – the claim this page is most careful not to make.
6. The Walk: Naming the Component
The trace at the top of the page names the call and repeats the path that call passed; the component the kernel stopped at is not in it. The kernel has the answer and does not share it: the number covers the walk, the class and the bit at once, and no amount of reading the errno recovers which component stopped it. A program can recover it, because every component is stat-able, and the decision the kernel made is a function of modes and ids that are all visible from outside. That function is the whole of the package this page prints, and it is small enough to read in one sitting.
The trace at the top is the one thing here taken from a tool’s documentation rather than from a command run on this host. strace is not installed – a search of PATH finds it absent – and a binary unpacked from the Debian package reports strace -- version 6.13 and then fails its own ptrace check with test_ptrace_get_syscall_info: PTRACE_TRACEME: Operation not permitted (errno 1): the container’s seccomp profile does not allow ptrace. What the binary does settle is the flags: its --help prints -z, --successful-only and -Z, --failed-only, and it accepts -Z as well as -e status=failed before it reaches the refusal. The shape of a trace line is therefore quoted from the tool, and every other figure on this page came from a call the host made.
The first half is the class and the bits: pick the third of the mode word that belongs to the process, and map the operation onto the bits it needs. A directory needs r for its names and w+x to change them, while a file needs the single bit its call asks for. Nothing here is a guess about the kernel: it is the same table the manual prints, written once so a program can compare against it – with one exception, the root identity’s documented bypass, which Section 9 returns to.
"""Read one file's nine mode bits the way the kernel reads them for one process.
The kernel never asks "is this file writable". It asks which of three identity classes the
process falls into - the file's owner, one of the file's group, or neither - and then applies
that class's three bits. This module is that decision, written out, so a program can say which
bit denied it before it tries.
"""
from __future__ import annotations
import enum
class Want(enum.Enum):
"""The thing the caller is about to do, in the kernel's terms rather than Python's."""
READ = "read"
WRITE = "write"
EXEC = "execute"
LIST = "list a directory"
CREATE = "create a name"
DELETE = "delete a name"
class AccessClass(enum.Enum):
"""Which third of the mode word applies: the owner bits, the group bits, or the rest."""
OWNER = "owner"
GROUP = "group"
OTHER = "other"
FILE_BITS: dict[Want, tuple[bool, bool, bool]] = {
Want.READ: (True, False, False),
Want.WRITE: (False, True, False),
Want.EXEC: (False, False, True),
}
DIR_BITS: dict[Want, tuple[bool, bool, bool]] = {
Want.READ: (True, False, False),
Want.WRITE: (False, True, True),
Want.EXEC: (False, False, True),
Want.LIST: (True, False, False),
Want.CREATE: (False, True, True),
Want.DELETE: (False, True, True),
}
def granted(mode: int, klass: AccessClass) -> tuple[bool, bool, bool]:
"""The (read, write, execute) bits that apply to ``klass``."""
shift = {AccessClass.OWNER: 6, AccessClass.GROUP: 3, AccessClass.OTHER: 0}[klass]
return (bool(mode & (4 << shift)), bool(mode & (2 << shift)), bool(mode & (1 << shift)))
def permits(mode: int, klass: AccessClass, want: Want, is_dir: bool, *,
root: bool = False) -> bool:
"""True when every bit ``want`` needs is set for ``klass`` on this object.
``root`` switches to the documented ``CAP_DAC_OVERRIDE`` rule a process with euid 0
holds: no bit is needed to read, write or search, while execute still needs one x bit
somewhere, which is how the kernel grants it (a directory is always searchable).
"""
table = DIR_BITS if is_dir else FILE_BITS
needed = table[want]
if root:
if not needed[2]:
return True
return is_dir or any(granted(mode, each)[2] for each in AccessClass)
have = granted(mode, klass)
return all(bit or not need for bit, need in zip(have, needed))
def describe(mode: int, klass: AccessClass) -> str:
"""'rwx', 'r-x' or '---' for the class that applies, as ls would print that third."""
read, write, execute = granted(mode, klass)
return "".join(("r" if read else "-", "w" if write else "-", "x" if execute else "-"))
The second half is the walk itself: every directory in the path, in order, each one asked for search permission, and the last directory asked for write as well when the operation changes a name. The first component that refuses is the answer, and it is reported with the mode it met, the class that lacked the bit, and the bit it wanted, so a log line can carry all three.
"""Walk a path the way the kernel does, and name the first component that will stop it.
``errno 13`` says a permission was missing. It never says which one. The answer lives in the
stat of every component the path passes through: each ancestor directory needs its x bit for the
walk, and the object at the end needs the bits its operation asks for. This module reports them
in path order, so the first entry is the one worth fixing.
What this model does not see, by construction: ACLs, SELinux and AppArmor labels, the immutable
attribute, a read-only mount and an NFS ``root_squash``. Those are checked by the kernel after
these nine bits, so a verdict of ``allowed`` here is not a promise that the call succeeds. A
root identity is answered by the documented ``CAP_DAC_OVERRIDE`` rule instead of a bit, and the
path is canonicalised with ``os.path.normpath`` first, so a ``..`` component is collapsed
lexically rather than resolved the way the kernel resolves it.
"""
from __future__ import annotations
import dataclasses
import os
import stat
from .model import AccessClass, Identity, NAME_OPERATIONS, Want, describe, permits
@dataclasses.dataclass(frozen=True)
class Blocker:
"""One component that refuses, with the bit it wanted and the class that lacked it."""
component: str
reason: str
mode: int
klass: AccessClass
needs: str
def line(self) -> str:
"""A single sentence a log line or an incident note can carry."""
return f"{self.component}: {self.reason} (mode {self.mode:04o}, {self.needs})"
@dataclasses.dataclass
class Result:
"""What the walk found: every refusal in path order, and a verdict that names the kind."""
path: str
want: Want
verdict: str
blockers: list[Blocker]
@property
def first(self) -> Blocker | None:
return self.blockers[0] if self.blockers else None
def __bool__(self) -> bool:
return self.verdict == "allowed"
def _prefixes(directory: str) -> list[str]:
"""'/a/b/c' -> ['/a', '/a/b', '/a/b/c'], the directories a walk passes through."""
parts = [part for part in directory.split(os.sep) if part]
out: list[str] = []
current = os.sep
for part in parts:
current = os.path.join(current, part)
out.append(current)
return out
def _check_directory(path: str, who: Identity, needs_write: bool,
blockers: list[Blocker]) -> str | None:
"""One ancestor: it must be a directory that grants x, and w too when a name changes.
Returns the verdict to report when this component stops the walk, or None when it passes.
"""
try:
info = os.stat(path)
except FileNotFoundError:
blockers.append(Blocker(path, "no such directory", 0, AccessClass.OTHER, "exists"))
return "blocked"
except PermissionError:
blockers.append(Blocker(path, "cannot be stat'ed", 0, AccessClass.OTHER, "search"))
return "blocked"
except OSError as exc: # ELOOP, ENAMETOOLONG: the walk ends here
blockers.append(Blocker(path, f"the walk stops: {exc.strerror}", 0,
AccessClass.OTHER, "a resolvable path"))
return "unreadable"
if not stat.S_ISDIR(info.st_mode):
blockers.append(Blocker(path, "is not a directory", stat.S_IMODE(info.st_mode),
AccessClass.OTHER, "directory"))
return "blocked"
klass = who.as_class(info.st_uid, info.st_gid)
mode = stat.S_IMODE(info.st_mode)
if not permits(mode, klass, Want.EXEC, True, root=who.is_root):
blockers.append(Blocker(path, "no search permission", mode, klass, "x"))
return "blocked"
if needs_write and not permits(mode, klass, Want.CREATE, True, root=who.is_root):
blockers.append(Blocker(path, "no write permission on the directory", mode, klass, "w+x"))
return "blocked"
return None
def explain(path: str, want: Want = Want.READ, *, identity: Identity | None = None) -> Result:
"""Return every component between the root and ``path`` that refuses ``want``."""
who = identity or Identity.current()
target = os.path.normpath(os.path.abspath(path))
name_operation = want in NAME_OPERATIONS
# A name that is about to be created or removed lives in the directory above it, so the
# walk ends there and that last directory carries the write requirement.
directory = os.path.dirname(target)
chain = _prefixes(directory)
blockers: list[Blocker] = []
for index, component in enumerate(chain):
last = index == len(chain) - 1
status = _check_directory(component, who, needs_write=name_operation and last,
blockers=blockers)
if status:
return Result(target, want, status, blockers)
if name_operation:
if want is Want.DELETE:
_sticky_note(target, who, blockers)
return Result(target, want, "blocked" if blockers else "allowed", blockers)
try:
info = os.stat(target)
except FileNotFoundError:
return Result(target, want, "missing",
[Blocker(target, "no such file", 0, AccessClass.OTHER, "exists")])
except PermissionError:
return Result(target, want, "blocked",
[Blocker(target, "cannot be stat'ed", 0, AccessClass.OTHER, "search")])
except OSError as exc: # a symlink loop, or a name too long to resolve
return Result(target, want, "unreadable",
[Blocker(target, f"cannot be stat'ed: {exc.strerror}", 0,
AccessClass.OTHER, "a resolvable path")])
mode = stat.S_IMODE(info.st_mode)
is_dir = stat.S_ISDIR(info.st_mode)
klass = who.as_class(info.st_uid, info.st_gid)
if want is Want.LIST and not is_dir:
blockers.append(Blocker(target, "is not a directory", mode, klass, "directory"))
elif not permits(mode, klass, want, is_dir, root=who.is_root):
blockers.append(Blocker(target, f"mode denies {want.value} to the {klass.value} class",
mode, klass, _needs(want, is_dir)))
return Result(target, want, "blocked" if blockers else "allowed", blockers)
def _needs(want: Want, is_dir: bool) -> str:
from .model import DIR_BITS, FILE_BITS
table = DIR_BITS if is_dir else FILE_BITS
read, write, execute = table[want]
return "".join(bit for bit, need in (("r", read), ("w", write), ("x", execute)) if need)
def _sticky_note(target: str, who: Identity, blockers: list[Blocker]) -> None:
"""A sticky directory lets the file's owner delete it, and nobody else."""
parent = os.path.dirname(target)
try:
directory = os.stat(parent)
victim = os.lstat(target) # unlink removes the name, so the name's owner is the test
except OSError:
return
if who.is_root or not directory.st_mode & stat.S_ISVTX:
return
if who.euid not in (directory.st_uid, victim.st_uid):
blockers.append(Blocker(parent, "sticky directory, and the caller owns neither it nor "
"the name",
stat.S_IMODE(directory.st_mode), AccessClass.OTHER, "ownership"))
def can(path: str, want: Want = Want.READ, *, identity: Identity | None = None) -> bool:
"""True when nothing in the walk refuses. A prediction, not a guarantee."""
return explain(path, want, identity=identity).verdict == "allowed"
def report(path: str, want: Want = Want.READ) -> str:
"""One line for a log: the verdict, and the first refusal when there is one."""
result = explain(path, want)
if result.first is None:
return f"{path}: {want.value} expected to succeed ({result.verdict})"
return f"{path}: {want.value} will fail at {result.first.line()} -> {result.verdict}"
__all__ = ["Blocker", "Result", "explain", "can", "report", "describe"]
| Components closed | Kernel answered | The walk named | First in path order |
|---|---|---|---|
| nothing | 0 | nothing | n/a |
c1 | 13 | c1 | yes |
c2 | 13 | c2 | yes |
c3 | 13 | c3 | yes |
c1 and c3 | 13 | c1 | yes |
c2, and the file at 0000 | 13 | c2 | yes |
| the file at 0000 | 13 | payload.bin | yes |
The fifth row is the reason the walk exists. With two components closed, the kernel answers one number, and a reader who opened the second component first would spend their time on the wrong directory. The walk reports the first in path order, which is the one that has to be fixed first: until it grants search permission, nothing behind it can even be reached. The sixth row shows the same ordering against a file-level refusal – the closed directory is named, not the 0000 file, because the file is never reached.
Against the kernel, the walk is a prediction, and it was checked as one: 17 of 17 in-scope arms agreed. The other 3 arms are kept in the record as outside its claim: a text file with x set answered ENOEXEC (8) because the format was wrong, a missing name answered ENOENT (2), and O_CREAT|O_EXCL on an occupied name answered EEXIST (17). None of them is a permission verdict, and counting them would inflate the agreement.
7. What a Refusal Costs
A refusal is not slow. The kernel checks the walk and returns before any I/O, so a refused open on this host took 1.7 µs (1.6–2.2 µs) against 1.3 µs (1.3–1.6 µs) for the same call that succeeded. The difference is small enough that a service which retries a refused call burns almost exactly the CPU a successful one would, and the failure surfaces as load rather than as an error rate.
A quarter of a second of retrying, with nothing else in the loop, made 151,052 attempts and succeeded 0 times. The bits do not change because a process asks again; they change when something else changes them, which is the only reason a retry is ever meaningful. A backoff does not make a refused open succeed – it spreads out the certainty.
| What was timed | Median per call | Range over the repeats |
|---|---|---|
open(O_RDONLY) on a 0000 file, refused | 1.74 µs | 1.64–2.19 |
open(O_RDONLY) on a 0444 file, allowed | 1.32 µs | 1.29–1.61 |
stat of a 0444 file | 1.40 µs | 1.39–1.42 |
os.access(R_OK) on the 0000 file | 0.79 µs | 0.77–1.00 |
explain, 4 directories deep | 23.58 µs | 22.45–29.85 |
explain, 13 directories deep | 66.72 µs | 64.73–75.96 |
| one attempt in the retry loop | 1.66 µs | 1.65–1.66 |
The walk is not free, and it should not be: it stats every component instead of letting the kernel do it once. On the short path it costs about 16.8× a single stat, and on the deep path about 2.8× the short one, because those 9 more components are 9 more stats. That is the right price for a tool used on an error path, and the wrong price for a hot loop – which is why the recommendation is to call it where a refusal is being turned into a message, not before every write.
8. Python’s Surface
Python turns the number into a class, and the class carries three attributes worth reading before anything else: errno, strerror and filename. On this host the refused open of /etc/ssl/private raised [Errno 13] Permission denied: '/etc/ssl/private', and the object is an OSError rather than a FileNotFoundError. Catching OSError and branching on errno remains the only portable shape; catching PermissionError is fine when the call is yours.
The helper most code reaches for is os.access, and here it agreed with the call it predicts on all 6 rows. That agreement is only for the owner class, on this kernel, with no ACLs: the manual is explicit that the check uses the real ids while the call uses the effective ones, which matters the moment a setuid helper is involved, and it is a check-then-act either way. What it has going for it is price: 0.79 µs against 1.74 µs for the refused open itself.
| File mode | R_OK | W_OK | X_OK | open read | open write |
|---|---|---|---|---|---|
0000 | no | no | no | 13 | 13 |
0200 | no | yes | no | 13 | 0 |
0400 | yes | no | no | 0 | 13 |
0600 | yes | yes | no | 0 | 0 |
0644 | yes | yes | no | 0 | 0 |
0755 | yes | yes | yes | 0 | 0 |
os.access next to the call it predicts, on files this account owns. The two columns on the right are errno values: 0 is the open that succeeded.The same discipline applies to the other three numbers in this family, because Python maps each to its own exception. O_CREAT|O_EXCL on an occupied name is FileExistsError (17), a missing parent is FileNotFoundError (2), and the two calls that walk directories – Path.write_text on a 0444 file and Path.unlink in a 0555 directory – are both PermissionError (13 and 13). A handler that catches PermissionError and prints the message has already lost the file name; the exception has it, and so does the walk.
"""Turn one PermissionError into a line an incident note can keep.
The error path of most services looks like ``except PermissionError: log.warning("permission
denied")``, which tells the next reader nothing: not the class, not the bit, not the component.
``diagnose`` asks permwhy about the file the exception named and prints the walk's first refusal.
The exception carries the number, the message and the name, and never the operation that was
refused, so the caller has to say what it was trying to do. A helper that assumed a write would
misread every read: on a 0200 file the read is refused and the write is allowed, and the walk
asked about the write answers that the bits are fine.
"""
from __future__ import annotations
from permwhy import Want, explain
def diagnose(error: PermissionError, want: Want) -> str:
"""One sentence: the path, the component that refuses, and the bit it wanted.
``want`` is required rather than defaulted, because the exception does not record it: a
refused read, a refused write and a refused execute raise the same class with the same
number, and the walk can only answer the question it is asked.
"""
path = str(error.filename or "")
if not path:
return f"errno {error.errno}: {error.strerror}, and no file name was attached"
result = explain(path, want)
if result.first is None:
return (f"{path}: refused with errno {error.errno}, and every mode bit allows "
f"{want.value} - the refusal came from an ACL, a capability, a read-only mount "
f"or a security label, none of which this model reads")
return f"{path}: refused at {result.first.line()}"
The operation is a parameter rather than a default, and that is the part worth copying: PermissionError never says which call was refused, so a helper that assumed a write would ask the walk the wrong question and report that every bit is fine. Handed the operation the caller attempted, the same function is one walk and one log line, and the next reader knows whether to chmod a file, fix an ancestor, or stop looking at modes altogether. When every mode allows the operation and the call was still refused, it says exactly that – the case where another chmod would be wasted work.
9. The Module
permwhy is 3 files and 315 lines: the bit arithmetic, the walk, and the report helpers. It has 4 test files and 623 lines of tests, all passing (91 tests), and it depends on nothing outside the standard library. The public surface is deliberately small.
| Call | What it answers | Cost here |
|---|---|---|
explain(path, want) | every component that refuses, in path order, with mode, class and needed bit | 23.58 µs on 4 directories |
can(path, want) | the same verdict as a bool | one walk |
report(path, want) | a one-line verdict for a log | one walk |
Identity.current() | the three ids the kernel will compare | three calls |
Want | read, write, execute, list, create, delete | an enum |
AccessClass | owner, group, other | an enum |
What the module refuses to claim matters as much as what it says. It reads nine bits and three ids, never an ACL, a mount option, a security label, or the stat of a component already unreachable. One rule comes from documentation rather than measurement – the CAP_DAC_OVERRIDE a uid-0 identity holds, which grants read, write and search with no bit set and execute only where some x bit is set – and the tests reach that branch with a hand-made root identity, because this account is not root. Two edges are named in its docstring: the path is canonicalised with os.path.normpath first, so a .. component collapses lexically where the kernel would enter it and ask for x; and a name operation predicts bits only, never whether the name is taken. A verdict of allowed is therefore a prediction about those nine bits, and Section 6 measured how often it holds.
"""The walk: real trees, real modes, and the component it names."""
from __future__ import annotations
import os
import pathlib
from permwhy import AccessClass, Identity, Want, explain
def make(path: pathlib.Path, mode: int, data: bytes = b"payload\n") -> pathlib.Path:
path.write_bytes(data)
os.chmod(path, mode)
return path
def test_a_foreign_identity_falls_to_the_other_class(shared):
target = make(shared / "payload.bin", 0o644)
stranger = Identity(4321, 4321, frozenset({4321}))
blocked = explain(str(target), Want.WRITE, identity=stranger)
assert blocked.verdict == "blocked"
assert blocked.first.klass is AccessClass.OTHER
allowed = explain(str(target), Want.READ, identity=stranger)
assert allowed.verdict == "allowed"
def test_a_group_member_uses_the_group_bits(shared):
target = make(shared / "payload.bin", 0o440)
info = os.stat(target)
member = Identity(4321, info.st_gid, frozenset({info.st_gid}))
assert explain(str(target), Want.READ, identity=member).verdict == "allowed"
assert explain(str(target), Want.WRITE, identity=member).verdict == "blocked"
The two tests above are the ones most worth reading: they build the other class explicitly, by handing the walk an identity that is not the process’s, which is the only way to test those branches without a second account on the host; the same device reaches the group class and a root identity. The example prints four cases and lets the kernel answer each one beside the walk’s verdict; it exits 0 and its lines are the shape of the output an operator would see. tests/test_example.py keeps the error path honest the same way: it raises a real refused read, hands it to diagnose as a read, and fails if the line claims that every bit is fine.
10. Deploy Notes and the Appendix
The reason this page exists is the container that cannot write its own directory. The volume is created by root, the service runs as uid 1000, and the class that applies is other – the same arms this page measured on /usr/bin/true and /etc/ssl/private. Naming the class is what turns Permission denied into a change: either the mount is given to the runtime uid, or the service is given the uid the mount already has. Widening only the owner triplet – chmod u+rwx – does nothing for a process that is not the owner; 0777 would open the other class instead, which is a different decision than the one this deploy needs.
Where each platform’s default lands
- Docker, copy into the image.
COPYwrites as root unless--chownsays otherwise, so aUSER appafterwards runs as other in its ownWORKDIR. The arm that matches is the 0755 directory that refused a write to this account: same class, same answer. - Kubernetes, a volume from a PVC. The mount arrives with whatever ownership the volume plugin gives it;
securityContext.fsGroupand aninitContainerthat chowns are the two deliberate ways to move the class. Without either, the app is other and the group bits are the only ones it can use. - A read-only root filesystem. The refusal arrives as
EROFS(30), before ownership is asked – measured here on/usr, whose mount options beginro. No chmod in the image can fix it. - NFS with
root_squash. The documented behaviour is that root’s uid is mapped to an unprivileged one, so a file written by root on the server is other on the client. This page did not measure an NFS mount, and says so. - A shared directory with the sticky bit. Deletion is the file owner’s, not the writer’s, which is why a deployment that writes into
/tmpas one uid cannot clean up after another.
The appendix prints the package, its tests, the two examples and the probe harness in full. Nothing in it needs a second host to rerun: every path it touches is under /tmp or is a system file named in the arm, and the figures in the tables carry the repeat count they were taken at.
Questions This Page Answers
Why does chmod 0777 not fix Permission denied on my own file?
Because 0777 sets all three classes, so on a writable mount the mode is no longer what refuses and the next chmod cannot help. Look outside it, in the order the kernel does: a directory above without x – a 0444 directory refused a 0644 file inside it here – then a read-only mount, which answers 30 before any bit is read, then ownership, where chmod itself answers 1 because the file belongs to another account, and finally the rules that are not modes at all: an ACL, an immutable attribute, a security label. Section 2 has the opposite slip too: a directory left at 0077 locks out the owner who owns it, and the same directory at 0700 let both the open and the stat through.
The file is 0644 and I own it, so why is the open refused?
The file is never reached. One of the directories in the path lacks x, and the walk stops there – a 0444 directory refused a read of a 0644 file inside it on this host. Print the mode of every component with namei -l, or ask permwhy.explain for the first component that refuses.
Why can I delete a read-only file but not a writable one?
Deletion is an operation on the directory. A 0444 file was unlinked from a 0755 directory here, and a 0644 file was refused in a 0555 one; the file’s own bits never enter the decision. The sticky bit adds one exception, for the file’s owner and the directory’s owner.
Why does ls work while ls -l reports errors?
Listing names needs r on the directory; printing each entry’s details needs x, because each line is a stat of a component. A 0333 directory listed nothing here, and a 0444 directory refused the stat of a file inside it.
Is os.access safe to gate a write on?
It answers about the nine bits for the owner class, and here it agreed with the real call on every row. It is still a check before an act: the manual notes it uses the real ids rather than the effective ones, and a mode can change between the check and the call. Use it to produce a message, not to decide.
Why does a chmod fail with errno 1 instead of 13?
Because ownership, not a mode, is what failed. EPERM (1) means the effective uid does not match the file’s owner; procfs answered exactly that here. No mode on the file can make chmod succeed for a non-owner.
I fixed the mode and the create still fails with errno 30. What now?
The mount is read-only, and that check comes first. /usr on this host is a read-only overlay: a create there answered 30, and even a chmod of a root-owned file under it answered 30 rather than 1. Look at /proc/mounts before editing any mode.
Should the service retry a refused open?
Only if something outside it is being changed. A retry loop made over a hundred thousand attempts in a quarter of a second here and succeeded none of them, because the bits do not change by being asked again. Retry after a deployment step that fixes the class or the component, and log the walk’s first refusal so that step is the right one.
Why does a script fail with 13 and then with 8?
13 is the missing x bit: the kernel will not execute a file it is not allowed to execute. 8 is ENOEXEC: x is granted and the format is not something the kernel can run, usually a missing shebang. Run the script through its interpreter, or give it a shebang and x.
Does the module work on the filesystems I deploy on?
It reads nine bits and three ids, which every POSIX filesystem exposes. It deliberately does not model ACLs, capabilities, mount options, security labels or NFS squashing, so a prediction of allowed is about the mode bits alone; when the call is refused anyway, those are the places left to look.
What is the fastest way to find the component in production?
Call explain where the exception is caught, and log its first blocker: that line carries the component, the mode and the class, which is everything an incident note needs. It costs about a dozen stats per call, so an error path can afford it and a hot loop cannot.
Why does the page say the group class was not measured?
Because the host had one account in one group and no file owned by that group. Every group claim here is the documented rule. The tests build a group identity by hand to keep that branch honest, and Section 2 states the limit rather than hiding it.
The two runbooks either side of this one
- ENOSPC errno 28: full blocks, full inodes, and deleted files that are still open – the refusal that looks like a permission error in a deploy log and is a full filesystem instead.
- EXDEV errno 18: a rename across devices, and the staged copy that survives it – the other error a deploy meets when it writes a temporary file in the wrong directory.
Going further
- Zero-Crash Python – one measured failure per issue, with its probe. Free.
- Runbook checklists on Gumroad – these tables as an incident-doc checklist.
Appendix: Every File the Page Carries
The package, its tests, the two examples and the probe helper, printed verbatim and folded, at the paths they sat in when the records below were written:
post41/
|-- examples/
| |-- catch_eacces.py
| `-- explain_demo.py
|-- permwhy/
| |-- __init__.py
| |-- model.py
| |-- walk.py
| `-- tests/
| |-- conftest.py
| |-- test_example.py
| |-- test_model.py
| `-- test_walk.py
`-- sandbox/
`-- probelib.py
That layout is the one the code assumes. tests/test_example.py is two directories below the tree root, so it reaches the example next door as parents[2] / "examples"; unzip every fold below into these paths, run pytest permwhy/tests from post41/, and the suite passes against the copy rather than against this page. The numbered probes that wrote the records are not folded here; each figure carries the size and repeat count it was taken at, so they can be rebuilt from the tables.
The public names, and the version this page measured permwhy/__init__.py
"""permwhy: say which bit will deny a call, before the call is made.
The kernel answers ``EACCES`` with one number and no component. ``explain`` walks the path and
names the first component that refuses, the class that lacked the bit, and the mode it met.
"""
from .model import AccessClass, Identity, Want, describe, granted, permits, symbolic
from .walk import Blocker, Result, can, explain, report
__all__ = ["AccessClass", "Identity", "Want", "Blocker", "Result", "can", "explain", "report",
"describe", "granted", "permits", "symbolic"]
__version__ = "1.0.0"
The nine bits, read the way the kernel reads them permwhy/model.py
"""Read one file's nine mode bits the way the kernel reads them for one process.
The kernel never asks "is this file writable". It asks which of three identity classes the
process falls into - the file's owner, one of the file's group, or neither - and then applies
that class's three bits. This module is that decision, written out, so a program can say which
bit denied it before it tries.
"""
from __future__ import annotations
import dataclasses
import enum
import os
class Want(enum.Enum):
"""The thing the caller is about to do, in the kernel's terms rather than Python's."""
READ = "read"
WRITE = "write"
EXEC = "execute"
LIST = "list a directory"
CREATE = "create a name"
DELETE = "delete a name"
class AccessClass(enum.Enum):
"""Which third of the mode word applies: the owner bits, the group bits, or the rest."""
OWNER = "owner"
GROUP = "group"
OTHER = "other"
#: The bits each want needs, as (read, write, execute) on the object it is asked of.
FILE_BITS: dict[Want, tuple[bool, bool, bool]] = {
Want.READ: (True, False, False),
Want.WRITE: (False, True, False),
Want.EXEC: (False, False, True),
}
#: A directory separates reading its entries (r) from changing them (w) and from walking
#: through it (x). Only the operations that change a name need both w and x.
DIR_BITS: dict[Want, tuple[bool, bool, bool]] = {
Want.READ: (True, False, False),
Want.WRITE: (False, True, True),
Want.EXEC: (False, False, True),
Want.LIST: (True, False, False),
Want.CREATE: (False, True, True),
Want.DELETE: (False, True, True),
}
#: The operations that change a name live in the directory that holds it, not in the file.
NAME_OPERATIONS = frozenset({Want.CREATE, Want.DELETE})
@dataclasses.dataclass(frozen=True)
class Identity:
"""The three ids the kernel compares a file's ownership against."""
euid: int
egid: int
groups: frozenset[int]
@classmethod
def current(cls) -> "Identity":
return cls(os.geteuid(), os.getegid(), frozenset(os.getgroups()))
@property
def is_root(self) -> bool:
"""True for euid 0, which changes the rule rather than a bit."""
return self.euid == 0
def as_class(self, owner: int, group: int) -> AccessClass:
"""Owner first, then any group, then every process left over."""
if self.euid == owner:
return AccessClass.OWNER
if self.egid == group or group in self.groups:
return AccessClass.GROUP
return AccessClass.OTHER
def granted(mode: int, klass: AccessClass) -> tuple[bool, bool, bool]:
"""The (read, write, execute) bits that apply to ``klass``."""
shift = {AccessClass.OWNER: 6, AccessClass.GROUP: 3, AccessClass.OTHER: 0}[klass]
return (bool(mode & (4 << shift)), bool(mode & (2 << shift)), bool(mode & (1 << shift)))
def permits(mode: int, klass: AccessClass, want: Want, is_dir: bool, *,
root: bool = False) -> bool:
"""True when every bit ``want`` needs is set for ``klass`` on this object.
``root`` switches to the documented ``CAP_DAC_OVERRIDE`` rule a process with euid 0
holds: no bit is needed to read, write or search, while execute still needs one x bit
somewhere, which is how the kernel grants it (a directory is always searchable).
"""
table = DIR_BITS if is_dir else FILE_BITS
needed = table[want]
if root:
if not needed[2]:
return True
return is_dir or any(granted(mode, each)[2] for each in AccessClass)
have = granted(mode, klass)
return all(bit or not need for bit, need in zip(have, needed))
def describe(mode: int, klass: AccessClass) -> str:
"""'rwx', 'r-x' or '---' for the class that applies, as ls would print that third."""
read, write, execute = granted(mode, klass)
return "".join(("r" if read else "-", "w" if write else "-", "x" if execute else "-"))
def symbolic(mode: int) -> str:
"""The whole mode as ls prints it, for a blocker a reader can compare with their own shell."""
out = ""
for klass in (AccessClass.OWNER, AccessClass.GROUP, AccessClass.OTHER):
out += describe(mode, klass)
return out
__all__ = ["Want", "AccessClass", "Identity", "FILE_BITS", "DIR_BITS", "NAME_OPERATIONS",
"granted", "permits", "describe", "symbolic"]
The one line that lets the tests import the package permwhy/tests/conftest.py
"""Make ``import permwhy`` work whichever directory pytest is started from."""
from __future__ import annotations
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
The bit arithmetic, without a filesystem permwhy/tests/test_model.py
"""The bit arithmetic, without touching the file system."""
from __future__ import annotations
import os
import stat
import pytest
from permwhy import AccessClass, Identity, Want, describe, granted, permits, symbolic
from permwhy.model import DIR_BITS, FILE_BITS, NAME_OPERATIONS
def test_granted_reads_the_owner_triplet():
assert granted(0o640, AccessClass.OWNER) == (True, True, False)
def test_granted_reads_the_group_triplet():
assert granted(0o640, AccessClass.GROUP) == (True, False, False)
def test_granted_reads_the_other_triplet():
assert granted(0o640, AccessClass.OTHER) == (False, False, False)
def test_granted_on_zero_is_nothing():
assert granted(0o000, AccessClass.OWNER) == (False, False, False)
def test_granted_counts_only_the_low_nine_bits():
assert granted(0o104644, AccessClass.OWNER) == (True, True, False)
def test_access_class_owner_wins_over_group():
who = Identity(1000, 1000, frozenset({1000}))
assert who.as_class(1000, 1000) is AccessClass.OWNER
def test_access_class_group_by_primary_gid():
who = Identity(1000, 50, frozenset({50}))
assert who.as_class(0, 50) is AccessClass.GROUP
def test_access_class_group_by_supplementary():
who = Identity(1000, 1000, frozenset({1000, 44}))
assert who.as_class(0, 44) is AccessClass.GROUP
def test_access_class_falls_through_to_other():
who = Identity(1000, 1000, frozenset({1000}))
assert who.as_class(0, 0) is AccessClass.OTHER
def test_access_class_ignores_a_group_the_process_is_not_in():
who = Identity(1000, 1000, frozenset({1000}))
assert who.as_class(0, 44) is AccessClass.OTHER
def test_identity_current_matches_the_process():
who = Identity.current()
assert who.euid == os.geteuid()
assert who.egid == os.getegid()
def test_file_bits_need_one_bit_each():
assert FILE_BITS[Want.READ] == (True, False, False)
assert FILE_BITS[Want.WRITE] == (False, True, False)
assert FILE_BITS[Want.EXEC] == (False, False, True)
def test_directory_create_needs_write_and_search():
assert DIR_BITS[Want.CREATE] == (False, True, True)
def test_directory_list_needs_only_read():
assert DIR_BITS[Want.LIST] == (True, False, False)
def test_directory_execute_needs_only_search():
assert DIR_BITS[Want.EXEC] == (False, False, True)
def test_name_operations_are_the_two_that_change_a_name():
assert NAME_OPERATIONS == frozenset({Want.CREATE, Want.DELETE})
@pytest.mark.parametrize("mode,want,expected", [
(0o400, Want.READ, True),
(0o400, Want.WRITE, False),
(0o200, Want.WRITE, True),
(0o200, Want.READ, False),
(0o100, Want.EXEC, True),
(0o600, Want.EXEC, False),
(0o000, Want.READ, False),
])
def test_permits_on_a_file(mode, want, expected):
assert permits(mode, AccessClass.OWNER, want, is_dir=False) is expected
@pytest.mark.parametrize("mode,want,expected", [
(0o555, Want.CREATE, False),
(0o755, Want.CREATE, True),
(0o733, Want.CREATE, True),
(0o333, Want.LIST, False),
(0o755, Want.LIST, True),
(0o111, Want.EXEC, True),
(0o444, Want.EXEC, False),
])
def test_permits_on_a_directory(mode, want, expected):
assert permits(mode, AccessClass.OWNER, want, is_dir=True) is expected
def test_permits_uses_the_class_it_is_given():
assert permits(0o700, AccessClass.OWNER, Want.READ, is_dir=False) is True
assert permits(0o700, AccessClass.OTHER, Want.READ, is_dir=False) is False
def test_is_root_is_true_only_for_euid_zero():
assert Identity(0, 0, frozenset({0})).is_root is True
assert Identity(1000, 1000, frozenset({1000})).is_root is False
def test_root_needs_no_bit_to_read_or_write():
assert permits(0o000, AccessClass.OTHER, Want.READ, is_dir=False, root=True) is True
assert permits(0o000, AccessClass.OTHER, Want.WRITE, is_dir=False, root=True) is True
def test_root_still_needs_one_x_bit_to_execute():
assert permits(0o644, AccessClass.OTHER, Want.EXEC, is_dir=False, root=True) is False
assert permits(0o744, AccessClass.OTHER, Want.EXEC, is_dir=False, root=True) is True
def test_root_searches_any_directory():
assert permits(0o000, AccessClass.OTHER, Want.EXEC, is_dir=True, root=True) is True
assert permits(0o444, AccessClass.OTHER, Want.CREATE, is_dir=True, root=True) is True
def test_root_is_opt_in_and_changes_nothing_by_default():
assert permits(0o000, AccessClass.OTHER, Want.READ, is_dir=False) is False
def test_describe_shows_the_class_triplet():
assert describe(0o640, AccessClass.OWNER) == "rw-"
assert describe(0o640, AccessClass.GROUP) == "r--"
assert describe(0o640, AccessClass.OTHER) == "---"
def test_symbolic_reads_like_ls():
assert symbolic(0o755) == "rwxr-xr-x"
assert symbolic(0o600) == "rw-------"
@pytest.mark.parametrize("path", ["/usr/bin/true", "/usr/bin", "/etc/ssl/private", __file__])
def test_symbolic_matches_the_platforms_own_formatter(path):
"""Ours against CPython's ls-style formatter, on four objects that already exist."""
info = os.stat(path)
assert symbolic(stat.S_IMODE(info.st_mode)) == stat.filemode(info.st_mode)[1:]
def test_symbolic_matches_the_formatter_on_modes_a_umask_never_makes(tmp_path):
"""The modes of the incident: owner cleared, group and other open, and the repair."""
for mode in (0o000, 0o077, 0o070, 0o700, 0o777, 0o640):
target = tmp_path / f"mode-{mode:04o}"
target.write_text("payload\n")
os.chmod(target, mode)
info = os.stat(target)
assert symbolic(stat.S_IMODE(info.st_mode)) == stat.filemode(info.st_mode)[1:]
def test_symbolic_does_not_model_setuid_or_the_sticky_bit(tmp_path):
"""A limit pinned by a test: the special bits are outside the nine this module reads."""
target = tmp_path / "sticky"
target.write_text("payload\n")
os.chmod(target, 0o1777)
info = os.stat(target)
assert symbolic(stat.S_IMODE(info.st_mode)) == "rwxrwxrwx"
assert stat.filemode(info.st_mode)[-1] == "t"
def test_symbolic_is_three_describe_calls():
mode = 0o754
assert symbolic(mode) == "".join(describe(mode, klass) for klass in AccessClass)
The walk, against real trees and real modes permwhy/tests/test_walk.py
"""The walk: real trees, real modes, and the component it names."""
from __future__ import annotations
import os
import pathlib
import shutil
import tempfile
import pytest
from permwhy import AccessClass, Identity, Want, can, explain, report
from permwhy.walk import Blocker, Result
@pytest.fixture()
def shared():
"""A directory under /tmp that a stranger can walk into, so an arm can test the other class."""
path = pathlib.Path(tempfile.mkdtemp(dir="/tmp"))
os.chmod(path, 0o755)
yield path
for base, dirs, files in os.walk(path):
for name in dirs:
os.chmod(os.path.join(base, name), 0o755)
for name in files:
entry = os.path.join(base, name)
if not os.path.islink(entry): # a link has no mode of its own to restore
os.chmod(entry, 0o644)
shutil.rmtree(path)
def make(path: pathlib.Path, mode: int, data: bytes = b"payload\n") -> pathlib.Path:
path.write_bytes(data)
os.chmod(path, mode)
return path
def chain(root: pathlib.Path, depth: int = 3) -> pathlib.Path:
current = root
for level in range(1, depth + 1):
current = current / f"c{level}"
current.mkdir()
os.chmod(current, 0o755)
return current
def test_allowed_read_reports_no_blocker(tmp_path):
target = make(tmp_path / "payload.bin", 0o644)
result = explain(str(target), Want.READ)
assert result.verdict == "allowed"
assert result.blockers == []
assert bool(result) is True
def test_a_0000_file_blocks_its_own_read(tmp_path):
target = make(tmp_path / "payload.bin", 0o000)
result = explain(str(target), Want.READ)
assert result.verdict == "blocked"
assert result.first.component == str(target)
assert result.first.needs == "r"
assert result.first.klass is AccessClass.OWNER
def test_a_0400_file_blocks_write(tmp_path):
target = make(tmp_path / "payload.bin", 0o400)
result = explain(str(target), Want.WRITE)
assert result.verdict == "blocked"
assert result.first.needs == "w"
def test_a_0200_file_allows_write(tmp_path):
target = make(tmp_path / "payload.bin", 0o200)
assert explain(str(target), Want.WRITE).verdict == "allowed"
def test_an_ancestor_without_x_blocks_first(tmp_path):
inside = chain(tmp_path)
target = make(inside / "payload.bin", 0o644)
os.chmod(tmp_path / "c1", 0o644)
result = explain(str(target), Want.READ)
assert result.verdict == "blocked"
assert result.first.component == str(tmp_path / "c1")
assert result.first.reason == "no search permission"
def test_a_0444_ancestor_blocks_even_a_readable_file(tmp_path):
inside = chain(tmp_path, depth=2)
target = make(inside / "payload.bin", 0o644)
os.chmod(inside, 0o444)
assert explain(str(target), Want.READ).verdict == "blocked"
def test_an_0111_ancestor_still_allows_the_file(tmp_path):
inside = chain(tmp_path, depth=2)
target = make(inside / "payload.bin", 0o644)
os.chmod(inside, 0o111)
result = explain(str(target), Want.READ)
assert result.verdict == "allowed", result.blockers
def test_create_needs_the_directory_to_be_writable(tmp_path):
directory = chain(tmp_path, depth=1)
os.chmod(directory, 0o555)
result = explain(str(directory / "new.bin"), Want.CREATE)
assert result.verdict == "blocked"
assert result.first.component == str(directory)
assert result.first.needs == "w+x"
def test_create_in_a_writable_directory_is_allowed(tmp_path):
directory = chain(tmp_path, depth=1)
assert explain(str(directory / "new.bin"), Want.CREATE).verdict == "allowed"
def test_delete_of_a_read_only_file_is_allowed(tmp_path):
target = make(tmp_path / "payload.bin", 0o444)
assert explain(str(target), Want.DELETE).verdict == "allowed"
def test_delete_in_a_read_only_directory_is_blocked(tmp_path):
directory = chain(tmp_path, depth=1)
target = make(directory / "payload.bin", 0o644)
os.chmod(directory, 0o555)
result = explain(str(target), Want.DELETE)
assert result.verdict == "blocked"
assert result.first.component == str(directory)
def test_list_needs_only_read(tmp_path):
directory = chain(tmp_path, depth=1)
os.chmod(directory, 0o333)
assert explain(str(directory), Want.LIST).verdict == "blocked"
os.chmod(directory, 0o444)
assert explain(str(directory), Want.LIST).verdict == "allowed"
def test_a_missing_target_is_not_a_permission_verdict(tmp_path):
result = explain(str(tmp_path / "never.bin"), Want.READ)
assert result.verdict == "missing"
assert result.first.reason == "no such file"
def test_a_file_in_the_middle_of_the_path_is_named(tmp_path):
middle = make(tmp_path / "plain.bin", 0o644)
result = explain(str(middle / "below.bin"), Want.READ)
assert result.verdict == "blocked"
assert result.first.reason == "is not a directory"
def test_a_symlink_through_a_locked_directory_is_blocked(tmp_path):
real = make(tmp_path / "real.bin", 0o644)
pen = tmp_path / "pen"
pen.mkdir()
os.symlink(real, pen / "shortcut")
os.chmod(pen, 0o000)
result = explain(str(pen / "shortcut"), Want.READ)
assert result.verdict == "blocked"
assert result.first.component == str(pen)
def test_a_symlink_does_not_carry_its_own_bits(tmp_path):
real = make(tmp_path / "real.bin", 0o000)
link = tmp_path / "link.bin"
os.symlink(real, link)
assert explain(str(link), Want.READ).verdict == "blocked"
def test_a_foreign_identity_falls_to_the_other_class(shared):
target = make(shared / "payload.bin", 0o644)
stranger = Identity(4321, 4321, frozenset({4321}))
blocked = explain(str(target), Want.WRITE, identity=stranger)
assert blocked.verdict == "blocked"
assert blocked.first.klass is AccessClass.OTHER
allowed = explain(str(target), Want.READ, identity=stranger)
assert allowed.verdict == "allowed"
def test_a_group_member_uses_the_group_bits(shared):
target = make(shared / "payload.bin", 0o440)
info = os.stat(target)
member = Identity(4321, info.st_gid, frozenset({info.st_gid}))
assert explain(str(target), Want.READ, identity=member).verdict == "allowed"
assert explain(str(target), Want.WRITE, identity=member).verdict == "blocked"
def test_a_deep_path_is_walked_to_the_end(tmp_path):
inside = chain(tmp_path, depth=6)
target = make(inside / "payload.bin", 0o644)
assert explain(str(target), Want.READ).verdict == "allowed"
def test_sticky_directory_lets_the_owner_delete(tmp_path):
directory = tmp_path / "shared"
directory.mkdir()
os.chmod(directory, 0o1777)
target = make(directory / "mine.bin", 0o644)
assert explain(str(target), Want.DELETE).verdict == "allowed"
def test_sticky_directory_blocks_a_stranger(shared):
directory = shared / "shared"
directory.mkdir()
os.chmod(directory, 0o1777)
target = make(directory / "mine.bin", 0o644)
stranger = Identity(4321, 4321, frozenset({4321}))
result = explain(str(target), Want.DELETE, identity=stranger)
assert result.verdict == "blocked"
assert result.first.needs == "ownership"
def test_blocker_line_carries_the_mode_and_the_bit():
blocker = Blocker("/tmp/x", "no search permission", 0o644, AccessClass.OWNER, "x")
assert blocker.line() == "/tmp/x: no search permission (mode 0644, x)"
def test_result_first_is_none_when_allowed(tmp_path):
target = make(tmp_path / "payload.bin", 0o644)
assert explain(str(target)).first is None
def test_result_is_false_when_blocked(tmp_path):
target = make(tmp_path / "payload.bin", 0o000)
assert bool(explain(str(target))) is False
def test_can_matches_the_verdict(tmp_path):
target = make(tmp_path / "payload.bin", 0o444)
assert can(str(target), Want.READ) is True
assert can(str(target), Want.WRITE) is False
def test_report_names_the_component(tmp_path):
target = make(tmp_path / "payload.bin", 0o000)
text = report(str(target), Want.READ)
assert "will fail at" in text and "no search permission" not in text
def test_report_says_expected_to_succeed(tmp_path):
target = make(tmp_path / "payload.bin", 0o644)
assert "expected to succeed" in report(str(target), Want.READ)
def test_a_relative_path_is_made_absolute(tmp_path, monkeypatch):
target = make(tmp_path / "payload.bin", 0o644)
monkeypatch.chdir(tmp_path)
result = explain("payload.bin", Want.READ)
assert result.path == str(target)
def test_a_trailing_slash_is_normalised(tmp_path):
directory = chain(tmp_path, depth=1)
result = explain(str(directory) + "/", Want.LIST)
assert result.path == str(directory)
def test_result_keeps_the_want(tmp_path):
target = make(tmp_path / "payload.bin", 0o644)
result: Result = explain(str(target), Want.EXEC)
assert result.want is Want.EXEC
def test_a_symlink_loop_is_reported_not_raised(tmp_path):
loop = tmp_path / "loop"
os.symlink(loop, loop)
result = explain(str(loop / "payload.bin"), Want.READ)
assert result.verdict == "unreadable"
assert result.first.component == str(loop)
assert "Too many levels" in result.first.reason
def test_a_symlink_loop_as_the_target_is_reported_too(tmp_path):
loop = tmp_path / "loop"
os.symlink(loop, loop)
assert explain(str(loop), Want.READ).verdict == "unreadable"
def test_list_on_a_file_names_the_kind(tmp_path):
target = make(tmp_path / "payload.bin", 0o644)
result = explain(str(target), Want.LIST)
assert result.verdict == "blocked"
assert result.first.reason == "is not a directory"
assert result.first.needs == "directory"
def test_an_empty_path_is_the_working_directory(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
result = explain("", Want.READ)
assert result.path == str(tmp_path)
assert result.verdict == "allowed"
def test_a_dot_prefix_is_the_same_path(tmp_path, monkeypatch):
target = make(tmp_path / "payload.bin", 0o644)
monkeypatch.chdir(tmp_path)
assert explain("./payload.bin", Want.READ).path == str(target)
def test_a_parent_component_is_collapsed_lexically(tmp_path):
"""A ``..`` is removed before the walk, which is not what the kernel does.
The kernel enters ``locked`` and is refused search permission there; the walk never sees
it, because normpath has already turned the path into the sibling. This test pins that
difference so a later change has to be deliberate.
"""
locked = tmp_path / "locked"
locked.mkdir()
other = tmp_path / "other"
other.mkdir()
make(other / "payload.bin", 0o644)
os.chmod(locked, 0o000)
through = str(locked / ".." / "other" / "payload.bin")
assert explain(through, Want.READ).verdict == "allowed"
if os.geteuid() != 0:
with pytest.raises(PermissionError):
os.close(os.open(through, os.O_RDONLY))
def test_a_root_identity_reads_a_0000_file(tmp_path):
target = make(tmp_path / "payload.bin", 0o000)
root = Identity(0, 0, frozenset({0}))
assert explain(str(target), Want.READ, identity=root).verdict == "allowed"
def test_a_root_identity_still_needs_an_x_bit_to_execute(tmp_path):
target = make(tmp_path / "payload.bin", 0o644)
root = Identity(0, 0, frozenset({0}))
assert explain(str(target), Want.EXEC, identity=root).verdict == "blocked"
os.chmod(target, 0o644 | 0o100)
assert explain(str(target), Want.EXEC, identity=root).verdict == "allowed"
def test_a_root_identity_may_delete_from_a_sticky_directory(tmp_path):
directory = tmp_path / "shared"
directory.mkdir()
os.chmod(directory, 0o1777)
target = make(directory / "mine.bin", 0o644)
root = Identity(0, 0, frozenset({0}))
assert explain(str(target), Want.DELETE, identity=root).verdict == "allowed"
def test_a_dangling_symlink_belongs_to_its_own_owner(shared):
"""unlink removes the name, so a sticky directory tests the link's owner, not the target's."""
directory = shared / "sticky"
directory.mkdir()
os.chmod(directory, 0o1777)
link = directory / "gone.bin"
os.symlink(directory / "never-there.bin", link)
stranger = Identity(4321, 4321, frozenset({4321}))
assert explain(str(link), Want.DELETE, identity=stranger).verdict == "blocked"
assert explain(str(link), Want.DELETE).verdict == "allowed"
The error path: the operation is named, never assumed permwhy/tests/test_example.py
"""The error-path helper: the operation is named by its caller, never assumed.
``examples/catch_eacces.py`` is not part of the package, so it is imported here by path. The
tests pin the reason ``diagnose`` takes ``want`` without a default: a read and a write raise the
same exception, and the walk asked about the wrong one reports that the bits are fine.
"""
from __future__ import annotations
import importlib.util
import pathlib
import types
import pytest
from permwhy import Want
EXAMPLE = pathlib.Path(__file__).resolve().parents[2] / "examples" / "catch_eacces.py"
@pytest.fixture(scope="module")
def catch() -> types.ModuleType:
"""Load the example module from its file, the way an operator would keep it in a tree."""
spec = importlib.util.spec_from_file_location("catch_eacces", EXAMPLE)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def refused_read(target: pathlib.Path) -> PermissionError:
"""The error the kernel raises for a read of a 0200 file this account owns."""
target.write_text("x")
target.chmod(0o200)
with pytest.raises(PermissionError) as raised:
target.read_text()
return raised.value
def test_a_read_refusal_is_diagnosed_as_a_read(catch, tmp_path):
error = refused_read(tmp_path / "report.txt")
line = catch.diagnose(error, Want.READ)
assert "refused at" in line
assert "mode 0200" in line
assert "denies read" in line
assert "every mode bit allows" not in line
def test_the_same_error_asked_about_a_write_would_have_been_misread(catch, tmp_path):
"""The misdiagnosis the removed default produced, pinned as a difference."""
error = refused_read(tmp_path / "report.txt")
line = catch.diagnose(error, Want.WRITE)
assert "every mode bit allows write" in line
assert "ACL" in line
def test_the_operation_is_required(catch, tmp_path):
error = refused_read(tmp_path / "report.txt")
with pytest.raises(TypeError):
catch.diagnose(error)
def test_a_write_refusal_names_the_file_and_its_mode(catch, tmp_path):
target = tmp_path / "report.txt"
target.write_text("x")
target.chmod(0o444)
with pytest.raises(PermissionError) as raised:
target.write_text("y")
line = catch.diagnose(raised.value, Want.WRITE)
assert str(target) in line
assert "mode 0444" in line
def test_a_refusal_with_every_bit_allowing_names_the_layer_above(catch, tmp_path):
"""A mode cannot explain this one, and the line says where to look instead."""
target = tmp_path / "readable.txt"
target.write_text("x")
error = PermissionError(13, "Permission denied", str(target))
line = catch.diagnose(error, Want.READ)
assert "every mode bit allows read" in line
assert "read-only mount" in line
def test_an_error_without_a_name_says_so(catch):
error = PermissionError(13, "Permission denied")
line = catch.diagnose(error, Want.READ)
assert "no file name was attached" in line
Four cases, answered twice: by the walk and by the kernel examples/explain_demo.py
#!/usr/bin/env python3
"""Print the walk's verdict for a small tree, then let the kernel answer the same questions.
Run from the tree root: ``python3 examples/explain_demo.py``. It builds four trees under
/tmp/p41/demo, asks permwhy about each, and makes the same call so the two answers sit on
consecutive lines.
"""
from __future__ import annotations
import os
import pathlib
import shutil
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from permwhy import Want, explain # noqa: E402
ROOT = pathlib.Path("/tmp/p41/demo")
def build() -> list[tuple[str, pathlib.Path, int, int, Want]]:
"""(label, target, dir mode, file mode, want) for four cases worth printing."""
if ROOT.exists():
for base, dirs, files in os.walk(ROOT):
for name in files:
os.chmod(os.path.join(base, name), 0o644)
for name in dirs:
os.chmod(os.path.join(base, name), 0o755)
shutil.rmtree(ROOT)
ROOT.mkdir(parents=True)
cases = []
for label, dir_mode, file_mode, want in (("readable", 0o755, 0o644, Want.READ),
("locked_file", 0o755, 0o000, Want.READ),
("locked_directory", 0o555, 0o644, Want.CREATE),
("read_only_file", 0o755, 0o444, Want.WRITE)):
directory = ROOT / label
directory.mkdir()
target = directory / "payload.bin"
target.write_bytes(b"payload\n")
os.chmod(target, file_mode)
os.chmod(directory, dir_mode)
cases.append((label, directory / "payload.bin", dir_mode, file_mode, want))
return cases
def attempt(path: pathlib.Path, want: Want) -> str:
try:
if want is Want.READ:
os.close(os.open(path, os.O_RDONLY))
elif want is Want.WRITE:
os.close(os.open(path, os.O_WRONLY))
elif want is Want.CREATE:
fd = os.open(path.parent / "created.bin", os.O_CREAT | os.O_WRONLY, 0o644)
os.close(fd)
os.unlink(path.parent / "created.bin")
return "0"
except OSError as exc:
return f"{exc.errno} {exc.strerror}"
def main() -> None:
for label, target, dir_mode, file_mode, want in build():
result = explain(str(target), want)
first = result.first.line() if result.first else "nothing refuses"
print(f"{label:17s} dir {dir_mode:04o} file {file_mode:04o} want {want.value:7s} "
f"| permwhy: {result.verdict:8s} {first}")
print(f"{'':17s} | kernel: errno {attempt(target, want)}")
if __name__ == "__main__":
main()
One PermissionError turned into a line worth keeping examples/catch_eacces.py
#!/usr/bin/env python3
"""Turn one PermissionError into a line an incident note can keep.
The error path of most services looks like ``except PermissionError: log.warning("permission
denied")``, which tells the next reader nothing: not the class, not the bit, not the component.
``diagnose`` asks permwhy about the file the exception named and prints the walk's first refusal.
The exception carries the number, the message and the name, and never the operation that was
refused, so the caller has to say what it was trying to do. A helper that assumed a write would
misread every read: on a 0200 file the read is refused and the write is allowed, and the walk
asked about the write answers that the bits are fine.
"""
from __future__ import annotations
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from permwhy import Want, explain # noqa: E402
def diagnose(error: PermissionError, want: Want) -> str:
"""One sentence: the path, the component that refuses, and the bit it wanted.
``want`` is required rather than defaulted, because the exception does not record it: a
refused read, a refused write and a refused execute raise the same class with the same
number, and the walk can only answer the question it is asked.
"""
path = str(error.filename or "")
if not path:
return f"errno {error.errno}: {error.strerror}, and no file name was attached"
result = explain(path, want)
if result.first is None:
return (f"{path}: refused with errno {error.errno}, and every mode bit allows "
f"{want.value} - the refusal came from an ACL, a capability, a read-only mount "
f"or a security label, none of which this model reads")
return f"{path}: refused at {result.first.line()}"
def main() -> None:
directory = pathlib.Path("/tmp/p41/catch")
directory.mkdir(parents=True, exist_ok=True)
target = directory / "report.txt"
target.write_text("ok\n")
target.chmod(0o444)
try:
target.write_text("again\n")
except PermissionError as error:
print("errno", error.errno, "|", error.strerror)
print(diagnose(error, Want.WRITE))
if __name__ == "__main__":
main()
The plumbing every probe wrote its record through sandbox/probelib.py
"""Shared plumbing for the probes that write article 41's measurement records.
Every probe writes one ``results/NN_name.json`` in the same shape: the conditions it ran under,
one ``arms`` list where each arm holds the five runs it made and a summary of the numbers they
produced. A figure the article prints is read back out of that file, so nothing has to be
remembered between a probe and the page.
"""
from __future__ import annotations
import errno
import json
import os
import pathlib
import shutil
import statistics
import time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent
RESULTS = ROOT / "results"
SCRATCH = pathlib.Path("/tmp/p41")
REPEATS = 5
def summary(values: list[float]) -> dict:
"""The median of the repeats and the range they fell in, as every table prints them."""
ordered = sorted(float(value) for value in values)
return {"median": statistics.median(ordered), "min": ordered[0], "max": ordered[-1],
"runs": len(ordered)}
def stats(runs: list[dict]) -> dict:
"""Summarise each numeric key of a run dict that appears in every run."""
keys = set(runs[0])
for run in runs[1:]:
keys &= set(run)
out: dict[str, dict] = {}
for key in sorted(keys):
if key in ("ok", "errno", "strerror"):
continue
sample = [run[key] for run in runs]
if all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in sample):
out[key] = summary(sample)
for key in ("ok", "errno"):
if key in keys:
out[key] = summary([int(run[key] if run[key] is not None else -1) for run in runs])
return out
def arm(label: str, runs: list[dict], **extra) -> dict:
record = {"label": label, "runs": runs, "summary": stats(runs)}
record.update(extra)
return record
def timed(fn, repeats: int = REPEATS) -> list[dict]:
"""Call ``fn`` repeats times, keeping whatever numeric record it returns."""
runs: list[dict] = []
for _ in range(repeats):
started = time.perf_counter_ns()
result = fn()
result.setdefault("ms", (time.perf_counter_ns() - started) / 1e6)
runs.append(result)
return runs
def attempt(call) -> dict:
"""Run one syscall-shaped call and record the errno it answered with, never raising."""
started = time.perf_counter_ns()
try:
call()
return {"errno": 0, "strerror": "ok", "ms": (time.perf_counter_ns() - started) / 1e6}
except OSError as exc:
return {"errno": int(exc.errno or 0), "strerror": exc.strerror,
"ms": (time.perf_counter_ns() - started) / 1e6}
def errno_name(code: int) -> str:
try:
return errno.errorcode.get(code, str(code))
except KeyError: # pragma: no cover
return str(code)
def fresh(path: pathlib.Path) -> pathlib.Path:
"""A directory of our own, emptied even if an earlier run left it unwritable."""
if path.exists():
unlock(path)
shutil.rmtree(path)
path.mkdir(parents=True)
return path
def unlock(path: pathlib.Path) -> None:
"""Give every file and directory under ``path`` the bits rmtree needs to remove it."""
for root, dirs, files in os.walk(path):
for name in dirs:
try:
os.chmod(os.path.join(root, name), 0o755)
except OSError:
pass
for name in files:
try:
os.chmod(os.path.join(root, name), 0o644)
except OSError:
pass
try:
os.chmod(path, 0o755)
except OSError:
pass
def write(prefix: str, document: dict) -> pathlib.Path:
RESULTS.mkdir(parents=True, exist_ok=True)
path = RESULTS / f"{prefix}.json"
document.setdefault("written", time.strftime("%Y-%m-%dT%H:%M:%S%z"))
path.write_text(json.dumps(document, indent=1, sort_keys=True) + "\n", encoding="utf-8")
print("wrote", path, flush=True)
return path
def host() -> dict:
"""The one host these figures were taken on, printed at the top of the page."""
return {
"uid": os.getuid(),
"gid": os.getgid(),
"groups": os.getgroups(),
"umask": os.umask(0o022),
"python": ".".join(str(part) for part in os.sys.version_info[:3]),
"kernel": os.uname().release,
"cap_effective": _capability_line(),
}
def _capability_line() -> str:
"""The process's effective capability mask, so the page can say root's bypass was not tested."""
try:
for line in pathlib.Path("/proc/self/status").read_text().splitlines():
if line.startswith("CapEff:"):
return line.split(":", 1)[1].strip()
except OSError:
pass
return "unknown"
def device(path: str) -> dict:
info = os.stat(path)
return {"major": os.major(info.st_dev), "minor": os.minor(info.st_dev),
"mode": oct(info.st_mode & 0o7777)}
def mode_of(path: str) -> str:
return oct(os.stat(path).st_mode & 0o7777)
