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
131 lines
4.6 KiB
Python
131 lines
4.6 KiB
Python
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())
|