Enforce website storage quotas on ext4 web nodes #33

Merged
parkel merged 3 commits from feature/website-storage-quotas into main 2026-11-21 14:20:21 +01:00
2 changed files with 214 additions and 0 deletions
Showing only changes of commit fe12a5d658 - Show all commits

No files matched your search

+64
View File
@@ -12,6 +12,7 @@ from .node_requests import serve_apply_request
MANIFEST_VERSION = 1
MAX_STORAGE_BYTES = 2**63 - 1
MAX_STORAGE_LIMIT_MIB = 2**31 - 1
CONFIGURATIONS = {
"apache": "apache-vhost.conf",
"php-fpm": "php-fpm-pool.conf",
@@ -84,6 +85,29 @@ class WebStorageRequest:
return {"operation": "measure_storage", "site": self.site.manifest()}
@dataclass(frozen=True)
class WebQuotaRequest:
site: WebSite
limit_mib: int | None
def __post_init__(self):
if self.limit_mib is not None and (
type(self.limit_mib) is not int
or not 1 <= self.limit_mib <= MAX_STORAGE_LIMIT_MIB
):
raise ValueError(
f"Use a website storage limit between 1 and "
f"{MAX_STORAGE_LIMIT_MIB} MiB."
)
def manifest(self):
return {
"operation": "set_storage_limit",
"site": self.site.manifest(),
"limit_mib": self.limit_mib,
}
def parse_web_request(data):
if (
isinstance(data, dict)
@@ -91,6 +115,14 @@ def parse_web_request(data):
and data["operation"] == "measure_storage"
):
return WebStorageRequest(WebSite.from_manifest(data["site"]))
if (
isinstance(data, dict)
and data.keys() == {"operation", "site", "limit_mib"}
and data["operation"] == "set_storage_limit"
):
return WebQuotaRequest(
WebSite.from_manifest(data["site"]), data["limit_mib"]
)
return WebSite.from_manifest(data)
@@ -100,6 +132,12 @@ def apply_web_request(request):
return {"used_bytes": measure_website_storage(request.site)}
if isinstance(request, WebQuotaRequest):
from .web_node_quota import apply_website_limit
apply_website_limit(request)
return None
from .web_node_apply import apply_site
apply_site(request)
@@ -130,6 +168,22 @@ def main(argv=None):
"storage-usage", help="Measure the allocated space in a document root."
)
usage.add_argument("manifest", type=Path)
quota = commands.add_parser(
"storage-limit", help="Inspect the website user's filesystem quota."
)
quota.add_argument("manifest", type=Path)
set_quota = commands.add_parser(
"set-storage-limit", help="Apply a hard storage limit to a website."
)
set_quota.add_argument("manifest", type=Path)
limit = set_quota.add_mutually_exclusive_group(required=True)
limit.add_argument("--limit-mib", type=int)
limit.add_argument(
"--unlimited",
dest="limit_mib",
action="store_const",
const=None,
)
https = commands.add_parser(
"enable-https",
help="Enable HTTPS with an existing Certbot certificate.",
@@ -226,6 +280,16 @@ def main(argv=None):
"used_bytes": measure_website_storage(site)
}
print(json.dumps(report, indent=2))
elif args.command == "storage-limit":
from .web_node_quota import website_limit_status
print(json.dumps(website_limit_status(site), indent=2))
elif args.command == "set-storage-limit":
from .web_node_quota import apply_website_limit
request = WebQuotaRequest(site, args.limit_mib)
report = apply_website_limit(request)
print(json.dumps(report, indent=2))
elif args.command == "enable-https":
from .web_node_tls import enable_https
+150
View File
@@ -0,0 +1,150 @@
import ctypes
import fcntl
import json
import os
import stat
import subprocess
from pathlib import Path
from . import web_node_apply as web
# Linux sys/quota.h user quota commands and the block-limits field mask.
GET_QUOTA = 0x800007 << 8
SET_QUOTA = 0x800008 << 8
BLOCK_LIMITS = 1
QUOTA_BLOCK_BYTES = 1024
class UserQuota(ctypes.Structure):
_fields_ = [
("block_hard_limit", ctypes.c_uint64),
("block_soft_limit", ctypes.c_uint64),
("used_bytes", ctypes.c_uint64),
("inode_hard_limit", ctypes.c_uint64),
("inode_soft_limit", ctypes.c_uint64),
("used_inodes", ctypes.c_uint64),
("block_expiry", ctypes.c_uint64),
("inode_expiry", ctypes.c_uint64),
("valid", ctypes.c_uint32),
]
def website_limit_status(site):
if os.geteuid() != 0:
raise ValueError("Run storage-limit as root on the web node.")
with web.locked_web_node(fcntl.LOCK_SH):
public, uid, _ = web.site_storage(site)
quota = read_user_quota(quota_device(public), uid)
return quota_report(site, quota)
def apply_website_limit(request):
if os.geteuid() != 0:
raise ValueError("Run set-storage-limit as root on the web node.")
site = request.site
hard_limit = (request.limit_mib or 0) * 1024
with web.locked_web_node(fcntl.LOCK_EX):
public, uid, _ = web.site_storage(site)
device = quota_device(public)
quota = read_user_quota(device, uid)
if quota.block_hard_limit != hard_limit or quota.block_soft_limit:
new_limits = UserQuota(
block_hard_limit=hard_limit, valid=BLOCK_LIMITS
)
quota_control(SET_QUOTA, device, uid, new_limits)
quota = read_user_quota(device, uid)
if quota.block_hard_limit != hard_limit or quota.block_soft_limit:
raise ValueError(
"Linux did not apply the requested website storage limit."
)
return quota_report(site, quota)
def quota_report(site, quota):
return site.manifest() | {
"limit_bytes": (quota.block_hard_limit * QUOTA_BLOCK_BYTES) or None,
"used_bytes": quota.used_bytes,
}
def quota_device(public):
root = web.WEB_ROOT
problem = f"Mount a dedicated ext4 volume with usrquota at {root}."
try:
result = subprocess.run(
[
"/usr/bin/findmnt",
"--json",
"--submounts",
"--mountpoint",
str(root),
"--output",
"TARGET,SOURCE,FSTYPE,FSROOT,FS-OPTIONS",
],
capture_output=True,
check=True,
text=True,
env={"PATH": "/usr/bin:/bin", "LC_ALL": "C"},
timeout=5,
)
(volume,) = json.loads(result.stdout)["filesystems"]
if (
volume["target"] != str(root)
or volume["fstype"] != "ext4"
or volume["fsroot"] != "/"
or "usrquota" not in volume["fs-options"].split(",")
):
raise ValueError
device = Path(volume["source"])
if not device.is_absolute():
raise ValueError
info = device.stat()
if (
not stat.S_ISBLK(info.st_mode)
or info.st_rdev != public.stat().st_dev
or info.st_rdev == root.parent.stat().st_dev
):
raise ValueError
except (
KeyError,
OSError,
TypeError,
ValueError,
subprocess.SubprocessError,
):
raise ValueError(problem) from None
for child in volume.get("children", ()):
target = Path(child["target"])
if target.is_relative_to(public) or public.is_relative_to(target):
raise ValueError(
"Remove nested mounts from this document root "
"before applying a quota."
)
return device
def read_user_quota(device, uid):
quota = UserQuota()
quota_control(GET_QUOTA, device, uid, quota)
if not quota.valid & BLOCK_LIMITS:
raise ValueError(
"Linux did not report the website user's quota limits."
)
return quota
def quota_control(command, device, uid, quota):
quotactl = ctypes.CDLL(None, use_errno=True).quotactl
quotactl.argtypes = (
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_uint,
ctypes.POINTER(UserQuota),
)
quotactl.restype = ctypes.c_int
if quotactl(command, os.fsencode(device), uid, ctypes.byref(quota)) != 0:
reason = os.strerror(ctypes.get_errno())
raise ValueError(
f"Linux could not access the website user's quota. {reason}."
)