lib.FileContext: Limit accessible addresses
Allow to attach a default path filter to a FileContext, given in the constructor as default_path_filter, or in the URI query as "path-filter". Passing False as default_path_filter will make the FileContext ignore any path-filter in the query. The filter is created lazily on first use through PathFilter.create(), so a string spec is loaded from the lib.pf module like any other filter. Every path based action evaluates the filter before it is carried out. An IGNORE verdict is logged and the action is skipped: reads and stats raise FileNotFoundError, writes, unlinks, erases, renames, and mkdirs are no-ops, and readdir() drops the filtered entries. An ABORT verdict raises PermissionError. Every path-driven method also takes a flag parameter, "filtered", defaulting to True, so a caller that must work regardless of the context's filter can opt out of the check. Add a unit test that exercises the verdicts, the filtered bypass, and the distribution probe on a Local context. Signed-off-by: Jan Lindemann <jan@janware.com> Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0
This commit is contained in:
parent
013636fa38
commit
c2c8db2737
5 changed files with 247 additions and 12 deletions
|
|
@ -61,7 +61,7 @@ class Distro(abc.ABC):
|
|||
async def read_os_release_str(cls, ec: ExecContext) -> str:
|
||||
release_file = '/etc/os-release'
|
||||
try:
|
||||
result = await ec.get(release_file, throw = True)
|
||||
result = await ec.get(release_file, throw = True, filtered = False)
|
||||
return result.stdout_str
|
||||
except Exception as e:
|
||||
log(
|
||||
|
|
|
|||
|
|
@ -1,18 +1,21 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import os
|
||||
|
||||
from enum import Enum, auto
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING, Any, Iterable, override
|
||||
from typing import TYPE_CHECKING, Any, Iterable, Literal, override
|
||||
|
||||
from .base import Result
|
||||
from .file_types import FT_DIR, FT_REG
|
||||
from .log import DEBUG, ERR, log
|
||||
from .log import DEBUG, ERR, get_caller_pos, log
|
||||
from .PathFilter import PathFilter, Verdict
|
||||
from .ProcFilter import ProcPipeline
|
||||
from .Uri import Uri
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .base import Result, StatResult
|
||||
from .base import StatResult
|
||||
from .file_types import FileType
|
||||
from .ProcFilter import ProcFilter
|
||||
|
||||
|
|
@ -30,6 +33,7 @@ class FileContext(abc.ABC):
|
|||
chroot: bool = False,
|
||||
in_pipe: ProcPipeline | None = None,
|
||||
out_pipe: ProcPipeline | None = None,
|
||||
default_path_filter: str | PathFilter | None | Literal[False] = None,
|
||||
):
|
||||
self.__uri = Uri.pimp(uri)
|
||||
self.__chroot = chroot
|
||||
|
|
@ -39,6 +43,10 @@ class FileContext(abc.ABC):
|
|||
self.__in_pipe = in_pipe
|
||||
self.__out_pipe = out_pipe
|
||||
self.__open_count = 0
|
||||
self.__default_path_filter: str | PathFilter | Literal[
|
||||
False] | None = default_path_filter
|
||||
self.__path_filter: PathFilter | Literal[
|
||||
False] | None = False if default_path_filter is False else None
|
||||
if verbose_default not in [True, False]:
|
||||
raise ValueError(
|
||||
'Tried to instantiate FileContext with verbose_default '
|
||||
|
|
@ -116,6 +124,49 @@ class FileContext(abc.ABC):
|
|||
def chroot(self) -> bool:
|
||||
return self.__chroot
|
||||
|
||||
@property
|
||||
def path_filter(self) -> PathFilter | None:
|
||||
|
||||
def __create_path_filter(
|
||||
candidate: str | None | PathFilter | Literal[False]
|
||||
) -> PathFilter | Literal[False]:
|
||||
if candidate is None or candidate is False:
|
||||
return False
|
||||
if isinstance(candidate, PathFilter):
|
||||
return candidate
|
||||
return PathFilter.create(spec = candidate, file_context = self)
|
||||
|
||||
if self.__path_filter is None:
|
||||
query = self.__uri.query_dict if self.__uri.query_dict else {}
|
||||
candidate: str | PathFilter | Literal[False] | None = \
|
||||
query.get('path-filter')
|
||||
if candidate is None:
|
||||
candidate = self.__default_path_filter
|
||||
self.__path_filter = __create_path_filter(candidate)
|
||||
return self.__path_filter or None
|
||||
|
||||
@path_filter.setter
|
||||
def path_filter(self, value: str | PathFilter | None | Literal[False]) -> None:
|
||||
self.__path_filter = None
|
||||
self.__default_path_filter = value
|
||||
|
||||
async def check_filtered(
|
||||
self,
|
||||
path: str,
|
||||
mode: int = os.F_OK,
|
||||
action: str = '',
|
||||
caller: tuple[str, str, int] | None = None,
|
||||
) -> Verdict:
|
||||
path_filter = self.path_filter
|
||||
if path_filter is None:
|
||||
return Verdict.ALLOW
|
||||
return await path_filter.run(
|
||||
path,
|
||||
mode = mode,
|
||||
msg = f'[{self.log_name}] {action}("{path}") is filtered',
|
||||
caller = caller or get_caller_pos(),
|
||||
)
|
||||
|
||||
@property
|
||||
def username(self) -> str | None:
|
||||
return self.__uri.username
|
||||
|
|
@ -145,7 +196,11 @@ class FileContext(abc.ABC):
|
|||
throw: bool = True,
|
||||
verbose: bool | None = None,
|
||||
title: str | None = None,
|
||||
filtered: bool = True,
|
||||
) -> Result:
|
||||
if filtered and await self.check_filtered(path, mode = os.R_OK,
|
||||
action = 'get') == Verdict.IGNORE:
|
||||
raise FileNotFoundError(path)
|
||||
ret = await self._get(
|
||||
self._chroot(path),
|
||||
wd = wd,
|
||||
|
|
@ -184,7 +239,11 @@ class FileContext(abc.ABC):
|
|||
mode: int | None = None,
|
||||
atomic: bool = False,
|
||||
ftype: FileType = FT_REG,
|
||||
filtered: bool = True,
|
||||
) -> Result:
|
||||
if filtered and await self.check_filtered(path, mode = os.W_OK,
|
||||
action = 'put') == Verdict.IGNORE:
|
||||
return Result()
|
||||
mode_str = None if mode is None else oct(mode).replace('0o', '0')
|
||||
if self.__out_pipe is not None:
|
||||
content = (await self.__out_pipe.run(content)).stdout
|
||||
|
|
@ -207,7 +266,10 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: unlink("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def unlink(self, path: str) -> None:
|
||||
async def unlink(self, path: str, filtered: bool = True) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
path, mode = os.W_OK, action = 'unlink') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._unlink(self._chroot(path))
|
||||
|
||||
async def _erase(self, path: str) -> None:
|
||||
|
|
@ -215,7 +277,10 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: erase("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def erase(self, path: str) -> None:
|
||||
async def erase(self, path: str, filtered: bool = True) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
path, mode = os.W_OK, action = 'erase') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._erase(self._chroot(path))
|
||||
|
||||
async def _rename(self, src: str, dst: str) -> None:
|
||||
|
|
@ -223,15 +288,28 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: rename("{src}" -> "{dst}") is not implemented'
|
||||
)
|
||||
|
||||
async def rename(self, src: str, dst: str) -> None:
|
||||
return await self._rename(src, dst)
|
||||
async def rename(self, src: str, dst: str, filtered: bool = True) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
src, mode = os.R_OK, action = 'rename') == Verdict.IGNORE:
|
||||
return
|
||||
if filtered and await self.check_filtered(
|
||||
dst, mode = os.W_OK, action = 'rename') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._rename(self._chroot(src), self._chroot(dst))
|
||||
|
||||
async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None:
|
||||
raise NotImplementedError(f'{self.log_name}: mkdir({path}) is not implemented')
|
||||
|
||||
async def mkdir(
|
||||
self, path: str, mode: int = 0o777, ftype: FileType = FT_DIR
|
||||
self,
|
||||
path: str,
|
||||
mode: int = 0o777,
|
||||
ftype: FileType = FT_DIR,
|
||||
filtered: bool = True,
|
||||
) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
path, mode = os.W_OK, action = 'mkdir') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._mkdir(self._chroot(path), mode, ftype)
|
||||
|
||||
async def _mktemp(self, tmpl: str, directory: bool) -> str:
|
||||
|
|
@ -269,9 +347,17 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: lstat("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def stat(self, path: str, follow_symlinks: bool = True) -> StatResult:
|
||||
async def stat(
|
||||
self,
|
||||
path: str,
|
||||
follow_symlinks: bool = True,
|
||||
filtered: bool = True
|
||||
) -> StatResult:
|
||||
if not isinstance(path, str):
|
||||
raise TypeError(f'path must be str, got {type(path).__name__}')
|
||||
if filtered and await self.check_filtered(path, mode = os.F_OK,
|
||||
action = 'stat') == Verdict.IGNORE:
|
||||
raise FileNotFoundError(path)
|
||||
return await self._stat(self._chroot(path), follow_symlinks)
|
||||
|
||||
async def _file_exists(self, path: str) -> bool:
|
||||
|
|
@ -341,8 +427,16 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: readdir("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def readdir(self, path: str) -> Iterable[str]:
|
||||
return await self._readdir(self._chroot(path))
|
||||
async def readdir(self, path: str, filtered: bool = True) -> Iterable[str]:
|
||||
base = path.rstrip('/')
|
||||
ret: list[str] = []
|
||||
for entry in await self._readdir(self._chroot(path)):
|
||||
full = f'{base}/{entry}' if base else entry
|
||||
if filtered and await self.check_filtered(
|
||||
full, mode = os.R_OK, action = 'readdir') == Verdict.IGNORE:
|
||||
continue
|
||||
ret.append(entry)
|
||||
return ret
|
||||
|
||||
@classmethod
|
||||
def create(cls, uri: str | Uri, *args: Any, **kwargs: Any) -> 'FileContext':
|
||||
|
|
|
|||
|
|
@ -141,6 +141,7 @@ class Base(FileContext):
|
|||
mode: int | None = None,
|
||||
atomic: bool = False,
|
||||
ftype: FileType = FT_REG,
|
||||
filtered: bool = True,
|
||||
) -> Result:
|
||||
# -- A put that changes nothing is a no-op: the pre-read is
|
||||
# fallback-aware, so a value already represented, below
|
||||
|
|
@ -171,6 +172,7 @@ class Base(FileContext):
|
|||
mode,
|
||||
atomic,
|
||||
ftype,
|
||||
filtered,
|
||||
)
|
||||
|
||||
def _put_is_noop(self, existing: bytes, content: bytes, ftype: FileType) -> bool:
|
||||
|
|
|
|||
8
test/unit/python/jw/pkg/lib/FileContext/Makefile
Normal file
8
test/unit/python/jw/pkg/lib/FileContext/Makefile
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
TOPDIR = ../../../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-run.mk
|
||||
|
||||
all:
|
||||
|
||||
test: run
|
||||
131
test/unit/python/jw/pkg/lib/FileContext/test.py
Normal file
131
test/unit/python/jw/pkg/lib/FileContext/test.py
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import asyncio
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from typing import Any, override
|
||||
|
||||
from jw.pkg.lib.Distro import Distro
|
||||
from jw.pkg.lib.ec.Local import Local
|
||||
from jw.pkg.lib.PathFilter import DenyAction, PathFilter
|
||||
|
||||
class BlockedFilter(PathFilter):
|
||||
|
||||
def __init__(self, *, spec: str, blocked: str, **kwargs: Any) -> None:
|
||||
super().__init__(spec = spec, **kwargs)
|
||||
self.__blocked = blocked
|
||||
|
||||
@override
|
||||
async def _access(self, path: str, mode: int = os.F_OK) -> bool:
|
||||
return not (path == self.__blocked or path.startswith(self.__blocked + '/'))
|
||||
|
||||
class AllIgnoreFilter(PathFilter):
|
||||
|
||||
def __init__(self, *, spec: str, **kwargs: Any) -> None:
|
||||
super().__init__(spec = spec, **kwargs)
|
||||
|
||||
@override
|
||||
async def _access(self, path: str, mode: int = os.F_OK) -> bool:
|
||||
return False
|
||||
|
||||
class AbortingFilter(PathFilter):
|
||||
|
||||
def __init__(self, *, spec: str, abort: str, **kwargs: Any) -> None:
|
||||
super().__init__(spec = spec, deny_action = DenyAction.ABORT, **kwargs)
|
||||
self.__abort = abort
|
||||
|
||||
@override
|
||||
async def _access(self, path: str, mode: int = os.F_OK) -> bool:
|
||||
return not (path == self.__abort or path.startswith(self.__abort + '/'))
|
||||
|
||||
async def run_tests() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for name in ('a/x', 'b/y'):
|
||||
p = os.path.join(tmp, name)
|
||||
os.makedirs(os.path.dirname(p), exist_ok = True)
|
||||
with open(p, 'w') as f:
|
||||
f.write('v\n')
|
||||
|
||||
fc = Local(
|
||||
f'local://{tmp}',
|
||||
chroot = True,
|
||||
default_path_filter = BlockedFilter(spec = 'test:b', blocked = 'b')
|
||||
)
|
||||
assert isinstance(fc.path_filter, BlockedFilter)
|
||||
|
||||
# -- An unfiltered address passes through
|
||||
assert (await fc.get('a/x')).stdout == b'v\n'
|
||||
|
||||
# -- A filtered address is not visible to reads
|
||||
try:
|
||||
await fc.get('b/y')
|
||||
raise AssertionError('filtered get() should not pass')
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
try:
|
||||
await fc.stat('b/y')
|
||||
raise AssertionError('filtered stat() should not pass')
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
# -- A filtered write is a no-op, an unfiltered one lands
|
||||
await fc.put('b/z', b'v\n')
|
||||
assert not os.path.exists(os.path.join(tmp, 'b', 'z'))
|
||||
await fc.put('a/z', b'v\n')
|
||||
assert os.path.exists(os.path.join(tmp, 'a', 'z'))
|
||||
|
||||
# -- A filtered unlink leaves the file in place
|
||||
await fc.unlink('b/y')
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'y'))
|
||||
await fc.unlink('a/z')
|
||||
assert not os.path.exists(os.path.join(tmp, 'a', 'z'))
|
||||
|
||||
# -- A filtered rename is a no-op, in either direction
|
||||
await fc.rename('b/y', 'a/moved')
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'y'))
|
||||
assert not os.path.exists(os.path.join(tmp, 'a', 'moved'))
|
||||
await fc.rename('a/x', 'a/moved')
|
||||
assert os.path.exists(os.path.join(tmp, 'a', 'moved'))
|
||||
|
||||
# -- A filtered mkdir and erase are no-ops
|
||||
await fc.mkdir('b/d')
|
||||
assert not os.path.exists(os.path.join(tmp, 'b', 'd'))
|
||||
await fc.erase('b/y')
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'y'))
|
||||
|
||||
# -- readdir() drops the filtered entries
|
||||
assert set(await fc.readdir('')) == {'a'}
|
||||
assert set(await fc.readdir('a')) == {'moved'}
|
||||
|
||||
# -- filtered=False bypasses the filter
|
||||
assert (await fc.get('b/y', filtered = False)).stdout == b'v\n'
|
||||
assert (await fc.stat('b/y', filtered = False)) is not None
|
||||
await fc.put('b/w', b'v\n', filtered = False)
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'w'))
|
||||
|
||||
# -- An aborting verdict denies the operation outright
|
||||
ac = Local(
|
||||
f'local://{tmp}',
|
||||
chroot = True,
|
||||
default_path_filter = AbortingFilter(spec = 'test:b', abort = 'b')
|
||||
)
|
||||
try:
|
||||
await ac.get('b/y')
|
||||
raise AssertionError('aborted get() should not pass')
|
||||
except PermissionError:
|
||||
pass
|
||||
|
||||
# -- Without a filter, everything is visible
|
||||
plain = Local(f'local://{tmp}', chroot = True)
|
||||
assert set(await plain.readdir('')) == {'a', 'b'}
|
||||
|
||||
# -- The distribution probe reads /etc/os-release even on a
|
||||
# context whose filter ignores every path
|
||||
if os.path.exists('/etc/os-release'):
|
||||
ec = Local(
|
||||
'local', default_path_filter = AllIgnoreFilter(spec = 'test:all')
|
||||
)
|
||||
with open('/etc/os-release') as f:
|
||||
expected = f.read()
|
||||
assert await Distro.read_os_release_str(ec) == expected
|
||||
|
||||
asyncio.run(run_tests())
|
||||
Loading…
Reference in a new issue