File size: 1,366 Bytes
fbf3c28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | from pathlib import Path
ALLOWED_ROOTS = [
"/data/adaptai",
]
PROTECTED_PATHS = [
"/",
"/bin",
"/sbin",
"/usr",
"/etc",
"/lib",
"/lib64",
"/boot",
"/sys",
"/proc",
"/dev",
"/root",
]
# Normalize and dedupe
PROTECTED_PATHS = sorted(set([str(Path(p).resolve()) for p in PROTECTED_PATHS]))
ALLOWED_ROOTS = sorted(set([str(Path(p).resolve()) for p in ALLOWED_ROOTS]))
def _real(p: str) -> str:
try:
return str(Path(p).resolve())
except Exception:
return p
def is_allowed_path(path: str) -> bool:
rp = _real(path)
# Allowed if under any allowlisted root
for root in ALLOWED_ROOTS:
if rp == root or rp.startswith(root + "/"):
return True
return False
def is_protected_path(path: str) -> bool:
rp = _real(path)
for prot in PROTECTED_PATHS:
if rp == prot or rp.startswith(prot + "/"):
return True
return False
def guard_write_path(path: str) -> tuple[bool, str]:
"""
Returns (ok, msg). ok=False when path is protected or not under allowed roots.
"""
rp = _real(path)
if is_protected_path(rp) and not is_allowed_path(rp):
return False, f"write blocked: protected path {rp}"
if not is_allowed_path(rp):
return False, f"write blocked: outside allowed roots {rp}"
return True, rp
|