From: Daan De Meyer Date: Sun, 31 Mar 2024 17:21:05 +0000 (+0200) Subject: Introduce INVOKING_USER.chown() X-Git-Tag: v23~41^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=a7e2a874aaf2ab0de2963a2de32c1b9cdcb750c0;p=thirdparty%2Fmkosi.git Introduce INVOKING_USER.chown() --- diff --git a/mkosi/__init__.py b/mkosi/__init__.py index 8a520d2f1..67493ad01 100644 --- a/mkosi/__init__.py +++ b/mkosi/__init__.py @@ -77,7 +77,6 @@ from mkosi.util import ( format_rlimit, make_executable, one_zero, - parents_below, read_env_file, round_up, scopedenv, @@ -4225,15 +4224,7 @@ def run_build(args: Args, config: Config, *, resources: Path) -> None: continue p.mkdir(parents=True, exist_ok=True) - - # If we created the directory in a parent directory owned by the invoking user, make sure the directories we - # just created are owned by the invoking user as well. - if ( - INVOKING_USER.is_regular_user() and - (q := next((parent for parent in p.parents if parent.stat().st_uid == INVOKING_USER.uid), None)) - ): - for parent in parents_below(p, q): - os.chown(parent, INVOKING_USER.uid, INVOKING_USER.gid) + INVOKING_USER.chown(p) # Discard setuid/setgid bits as these are inherited and can leak into the image. if config.build_dir: diff --git a/mkosi/user.py b/mkosi/user.py index 2864eee25..6afbb13ad 100644 --- a/mkosi/user.py +++ b/mkosi/user.py @@ -12,7 +12,7 @@ from pathlib import Path from mkosi.log import die from mkosi.run import run, spawn -from mkosi.util import flock +from mkosi.util import flock, parents_below SUBRANGE = 65536 @@ -85,6 +85,19 @@ class INVOKING_USER: if cls.is_regular_user() and any(p.stat().st_uid == cls.uid for p in path.parents) and path.exists(): run(["chown", "--recursive", f"{INVOKING_USER.uid}:{INVOKING_USER.gid}", path]) + @classmethod + def chown(cls, path: Path) -> None: + # If we created a file/directory in a parent directory owned by the invoking user, make sure the path and any + # parent directories are owned by the invoking user as well. + if ( + cls.is_regular_user() and + (q := next((parent for parent in path.parents if parent.stat().st_uid == cls.uid), None)) + ): + os.chown(path, INVOKING_USER.uid, INVOKING_USER.gid) + + for parent in parents_below(path, q): + os.chown(parent, INVOKING_USER.uid, INVOKING_USER.gid) + def read_subrange(path: Path) -> int: uid = str(os.getuid())