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
3 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:
|
||||
|
|
|
|||
Loading…
Reference in a new issue