Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(wordpress): durable per-site PHP limit writes + wire the PHP tab (#24)

Juan Denisaaf99212cb3c
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index de7d0e21..03a5d654 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -389,6 +389,8 @@ def get_php(app_id):
return jsonify({'error': 'Access denied'}), 403
info = WordPressService.get_php_info(app.root_path)
info['available_versions'] = WordPressService.get_available_php_versions()
+ # The directives the limits panel may edit (#24 write side).
+ info['editable_limits'] = list(WordPressService.get_php_limit_spec().keys())
return jsonify({'php': info}), 200
@@ -410,6 +412,25 @@ def set_php(app_id):
return jsonify(result), 200 if result.get('success') else 400
+@wordpress_bp.route('/sites/<int:app_id>/php/limits', methods=['POST'])
+@jwt_required()
+@admin_required
+def set_php_limits(app_id):
+ """Durably set per-site PHP ini limits (#24): writes a conf.d drop-in,
+ bind-mounts it, and reloads the container. Body: {limits: {key: value, ...}}."""
+ app = _resolve_app(app_id)
+ data = request.get_json() or {}
+ if not app:
+ return jsonify({'error': 'Application not found'}), 404
+ if app.app_type not in ('wordpress', 'docker'):
+ return jsonify({'error': 'Application is not a WordPress site'}), 400
+ limits = data.get('limits')
+ if not isinstance(limits, dict) or not limits:
+ return jsonify({'error': 'limits object is required'}), 400
+ result = WordPressService.set_php_limits(app.root_path, limits)
+ return jsonify(result), 200 if result.get('success') else 400
+
+
def _site_status_target(wp_site):
"""Best-effort public URL for a managed site's status-page component.
Prefers a primary domain (https when SSL), falls back to the local port.
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 902ee8e0..232cff0f 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -285,6 +285,121 @@ define('WP_AUTO_UPDATE_CORE', 'minor');
except Exception as e:
return {'success': False, 'error': str(e)}
+ # --- Per-site PHP ini limits (#24 write side) -------------------------------
+ # The official wordpress:*-apache image is Apache + mod_php and scans
+ # /usr/local/etc/php/conf.d for *.ini drop-ins. We persist a host-side ini and
+ # BIND-MOUNT it into conf.d so it survives container recreate — a plain
+ # `docker exec` write would be lost on the next `compose up`. Every directive is
+ # whitelisted + regex-validated because the value is written as a raw php.ini line.
+ PHP_LIMIT_SPEC = {
+ 'memory_limit': r'^(-1|\d{1,5}[KMGkmg]?)$',
+ 'upload_max_filesize': r'^\d{1,5}[KMGkmg]?$',
+ 'post_max_size': r'^\d{1,5}[KMGkmg]?$',
+ 'max_execution_time': r'^\d{1,5}$',
+ 'max_input_time': r'^-?\d{1,5}$',
+ 'max_input_vars': r'^\d{1,6}$',
+ }
+ PHP_CONF_DIR = 'php-conf'
+ PHP_CONF_FILE = 'zz-serverkit.ini'
+ PHP_CONF_CONTAINER = '/usr/local/etc/php/conf.d/zz-serverkit.ini'
+
+ @classmethod
+ def get_php_limit_spec(cls) -> Dict:
+ """The editable php.ini directives (key -> validation regex) the limits
+ panel may set. Exposed so the frontend renders exactly the safe set."""
+ return dict(cls.PHP_LIMIT_SPEC)
+
+ @staticmethod
+ def _read_php_ini(ini_path: str) -> Dict:
+ """Parse a simple `key = value` ini into a dict (comments/blank lines skipped).
+ Never raises — a missing/garbled file just yields {}."""
+ out = {}
+ if os.path.exists(ini_path):
+ try:
+ with open(ini_path, 'r') as f:
+ for line in f:
+ line = line.strip()
+ if not line or line.startswith(';') or '=' not in line:
+ continue
+ k, v = line.split('=', 1)
+ out[k.strip()] = v.strip()
+ except Exception:
+ pass
+ return out
+
+ @classmethod
+ def set_php_limits(cls, path: str, limits: Dict) -> Dict:
+ """Durably set per-site PHP ini limits for a Docker WP site.
+
+ Writes a host-side conf.d drop-in, bind-mounts it into the container's
+ php conf.d (so it survives recreate), then reloads: a newly-added mount is
+ applied via `compose up -d` (recreates the app container); a content-only
+ change restarts the `wordpress` service so mod_php re-reads php.ini.
+ Partial updates merge with any previously-set directives.
+ """
+ import re as _re
+ import yaml
+ from app.services.docker_service import DockerService
+
+ compose_file = os.path.join(path, 'docker-compose.yml')
+ if not os.path.exists(compose_file):
+ return {'success': False, 'error': 'Not a Docker-stack site (no docker-compose.yml)'}
+
+ # 1) Validate + sanitize against the whitelist (values become raw ini lines).
+ clean = {}
+ for k, v in (limits or {}).items():
+ if k not in cls.PHP_LIMIT_SPEC:
+ return {'success': False, 'error': f'Unknown PHP limit: {k}'}
+ val = str(v).strip()
+ # fullmatch (not match) so a value like "256M\nevil = 1" can never
+ # smuggle an extra ini directive past the `$` anchor into the file.
+ if not _re.fullmatch(cls.PHP_LIMIT_SPEC[k], val):
+ return {'success': False, 'error': f'Invalid value for {k}: {val}'}
+ clean[k] = val
+ if not clean:
+ return {'success': False, 'error': 'No valid limits provided'}
+
+ try:
+ # 2) Write the host ini FIRST — a single-file bind-mount needs the
+ # source to exist before `compose up`, else Docker makes a dir.
+ conf_dir = os.path.join(path, cls.PHP_CONF_DIR)
+ os.makedirs(conf_dir, exist_ok=True)
+ ini_path = os.path.join(conf_dir, cls.PHP_CONF_FILE)
+ merged = cls._read_php_ini(ini_path)
+ merged.update(clean)
+ body = ['; Managed by ServerKit (#24) — per-site PHP limits. Do not edit by hand.']
+ body += [f'{k} = {v}' for k, v in merged.items()]
+ with open(ini_path, 'w') as f:
+ f.write('\n'.join(body) + '\n')
+
+ # 3) Ensure the wordpress service bind-mounts the ini into conf.d.
+ with open(compose_file, 'r') as f:
+ compose = yaml.safe_load(f) or {}
+ wp = (compose.get('services') or {}).get('wordpress')
+ if not isinstance(wp, dict):
+ return {'success': False, 'error': 'wordpress service not found in compose file'}
+ mount = f'./{cls.PHP_CONF_DIR}/{cls.PHP_CONF_FILE}:{cls.PHP_CONF_CONTAINER}:ro'
+ vols = wp.get('volumes') or []
+ mount_added = mount not in vols
+ if mount_added:
+ vols.append(mount)
+ wp['volumes'] = vols
+ with open(compose_file, 'w') as f:
+ yaml.dump(compose, f, default_flow_style=False, sort_keys=False)
+
+ # 4) Apply: recreate if the mount is new, else restart so php.ini reloads.
+ if mount_added:
+ res = DockerService.compose_up(path, detach=True, build=False)
+ else:
+ res = DockerService.compose_restart(path, service='wordpress')
+ if not res.get('success'):
+ return {'success': False, 'error': res.get('error') or 'Failed to apply PHP limits'}
+ cls._wait_for_wp_ready(path)
+ return {'success': True, 'message': 'PHP limits updated', 'limits': merged,
+ 'applied': cls.get_php_info(path).get('limits', {})}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
@classmethod
def is_multisite(cls, path: str) -> bool:
"""Return True if the WordPress install at ``path`` is a multisite network.
diff --git a/backend/tests/test_wp_php_limits.py b/backend/tests/test_wp_php_limits.py
new file mode 100644
index 00000000..1fe8050b
--- /dev/null
+++ b/backend/tests/test_wp_php_limits.py
@@ -0,0 +1,105 @@
+"""Tests for #24 per-site PHP limit writes — validation + durable conf.d ini /
+bind-mount. The Docker apply step is mocked (no Docker on the dev/CI host); the
+file-rendering, compose-mutation, merge, and injection-rejection logic is real."""
+import os
+import yaml
+
+
+def _compose_site(tmp_path):
+ """A minimal Docker-stack WP site dir with a docker-compose.yml."""
+ (tmp_path / 'docker-compose.yml').write_text(
+ "services:\n"
+ " wordpress:\n"
+ " image: wordpress:6.4-apache\n"
+ " volumes:\n"
+ " - wordpress_html:/var/www/html\n"
+ )
+ return str(tmp_path)
+
+
+def _mock_docker(monkeypatch):
+ from app.services.wordpress_service import WordPressService
+ from app.services.docker_service import DockerService
+ monkeypatch.setattr(DockerService, 'compose_up', lambda *a, **k: {'success': True})
+ monkeypatch.setattr(DockerService, 'compose_restart', lambda *a, **k: {'success': True})
+ monkeypatch.setattr(WordPressService, '_wait_for_wp_ready', staticmethod(lambda p: None))
+ monkeypatch.setattr(WordPressService, 'get_php_info', staticmethod(lambda p: {'limits': {}}))
+
+
+# ---- validation / injection rejection (no Docker needed) -------------------
+
+def test_rejects_unknown_directive(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ res = WordPressService.set_php_limits(_compose_site(tmp_path), {'evil_directive': '1'})
+ assert res['success'] is False and 'Unknown PHP limit' in res['error']
+
+
+def test_rejects_injection_value(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ # A newline-smuggled extra directive must not pass validation.
+ res = WordPressService.set_php_limits(_compose_site(tmp_path),
+ {'memory_limit': '256M\nevil = 1'})
+ assert res['success'] is False and 'Invalid value' in res['error']
+ # ...and nothing was written.
+ assert not os.path.exists(os.path.join(_compose_site(tmp_path), 'php-conf', 'zz-serverkit.ini'))
+
+
+def test_rejects_non_stack_site(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ res = WordPressService.set_php_limits(str(tmp_path), {'memory_limit': '256M'})
+ assert res['success'] is False and 'Not a Docker-stack site' in res['error']
+
+
+# ---- durable write + bind-mount (Docker mocked) ----------------------------
+
+def test_writes_ini_and_injects_single_file_mount(tmp_path, monkeypatch):
+ from app.services.wordpress_service import WordPressService
+ _mock_docker(monkeypatch)
+ path = _compose_site(tmp_path)
+
+ res = WordPressService.set_php_limits(path, {'memory_limit': '512M', 'max_execution_time': '120'})
+ assert res['success'] is True
+
+ ini = os.path.join(path, 'php-conf', 'zz-serverkit.ini')
+ content = open(ini).read()
+ assert 'memory_limit = 512M' in content
+ assert 'max_execution_time = 120' in content
+
+ vols = yaml.safe_load(open(os.path.join(path, 'docker-compose.yml')))['services']['wordpress']['volumes']
+ assert any('php-conf/zz-serverkit.ini:/usr/local/etc/php/conf.d/zz-serverkit.ini' in v for v in vols)
+
+
+def test_partial_update_merges_and_mount_not_duplicated(tmp_path, monkeypatch):
+ from app.services.wordpress_service import WordPressService
+ _mock_docker(monkeypatch)
+ path = _compose_site(tmp_path)
+
+ WordPressService.set_php_limits(path, {'memory_limit': '256M'})
+ res = WordPressService.set_php_limits(path, {'upload_max_filesize': '64M'})
+ assert res['success'] is True
+ # The second (partial) update keeps the first directive.
+ assert res['limits']['memory_limit'] == '256M'
+ assert res['limits']['upload_max_filesize'] == '64M'
+
+ # The single-file mount is added once, not duplicated on the second call.
+ vols = yaml.safe_load(open(os.path.join(path, 'docker-compose.yml')))['services']['wordpress']['volumes']
+ assert len([v for v in vols if 'zz-serverkit.ini' in v]) == 1
+
+
+def test_accepts_unlimited_and_size_suffixes(tmp_path, monkeypatch):
+ from app.services.wordpress_service import WordPressService
+ _mock_docker(monkeypatch)
+ path = _compose_site(tmp_path)
+ res = WordPressService.set_php_limits(path, {'memory_limit': '-1', 'max_input_time': '-1',
+ 'upload_max_filesize': '2G', 'max_input_vars': '5000'})
+ assert res['success'] is True
+ assert res['limits']['memory_limit'] == '-1'
+
+
+# ---- ini parsing -----------------------------------------------------------
+
+def test_read_php_ini_skips_comments_and_garbage(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ p = tmp_path / 'x.ini'
+ p.write_text('; a comment\nmemory_limit = 128M\n\nno equals here\nmax_input_vars = 2000\n')
+ assert WordPressService._read_php_ini(str(p)) == {'memory_limit': '128M', 'max_input_vars': '2000'}
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index ad0ec4ab..7cdddc34 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -223,11 +223,12 @@ The headline value of a managed platform, and the most net-new — but it leans
- **Reuse:** `wp_cli`, `wordpress.yaml` compose template, `flush_cache`.
- **Done when:** Object cache is enabled and reports a hit ratio.
-### #24 — Per-site PHP version & limits panel `[M]` 🟡 — ✅ Done (read panel: live version + limits via wp eval; version switch via image tag + recreate. Arbitrary limit-WRITE deferred — needs a conf.d ini + compose bind-mount for durability)
+### #24 — Per-site PHP version & limits panel `[M]` 🟡 — ✅ Done (read panel: live version + limits via wp eval; version switch via image tag + recreate; **arbitrary limit-WRITE now durable via a conf.d ini + compose bind-mount**)
- **Today:** The full PHP-FPM API (`getPHPVersions`/`setDefaultPHPVersion`/`installPHPVersion`/`createPHPPool`/`getPHPPools`/`restartPHPFPM` in `services/system.js`) has **zero** frontend consumers; `php_version` on `Application` is write-once with no update route, and pools are decoupled from the WP model.
- **Do:** A per-site PHP panel (version + `memory_limit`/upload size/`max_execution_time`/workers) bound to the WP environment + an update-pool/change-version route.
- **Reuse:** `php_service`, `system.js`.
- **Done when:** A site's PHP version and limits are editable per environment.
+- **Landed (limit-WRITE):** the deferred write side now ships, Docker-correct for the `wordpress:*-apache` (Apache + mod_php) model. New `WordPressService.set_php_limits(path, limits)` whitelists + **`re.fullmatch`-validates** each directive (`memory_limit`, `upload_max_filesize`, `post_max_size`, `max_execution_time`, `max_input_time`, `max_input_vars`) — fullmatch (not match) so a value like `"256M\nevil = 1"` can't smuggle a second ini line past the `$` anchor — then writes a host-side `php-conf/zz-serverkit.ini` and **bind-mounts that single file into `/usr/local/etc/php/conf.d/`** so it survives container recreate (a plain `docker exec` write would be lost on the next `compose up`). The host file is written **before** the mount is added (a single-file bind-mount needs its source to pre-exist, else Docker makes a directory); a newly-added mount applies via `compose up -d` (recreate), a content-only change via `compose_restart('wordpress')` so mod_php re-reads `php.ini`. Partial updates **merge** with the existing drop-in (no directive is dropped), and the mount is injected once (idempotent). Route `POST /sites/<id>/php/limits` (`@admin_required`), client `setPhpLimits`, and an **Edit PHP Limits** panel added to the PHP tab (per-directive inputs seeded from live values, partial-diff save). **Also fixed a latent #24 bug:** the `PhpTab` component (the read panel + version switch) was built but **never wired into `WordPressDetail`** — no tab button, no render branch — so the entire PHP panel was invisible; added `'php'` to `VALID_TABS` + a PHP tab + the render branch, so the read panel *and* the new limits editor actually render. Verified: backend `py_compile`, **7 new pytest tests** (unknown-directive + injection-value rejection, non-stack-site guard, ini-write + single-file-mount injection, partial-merge + no-duplicate-mount, unlimited/size-suffix acceptance, ini parsing), full suite **200 passed / 12 skipped**, frontend lint-clean (the `PhpTab`-unused warning is now gone) + production build. Not runtime-exercised on a real Docker host (Windows dev).
### #25 — Per-site traffic / error / cache analytics `[L]` ❌ — ✅ Done (Docker-correct: on-demand apache access-log analytics; PHP-fatals / response-time / cache-ratio deferred)
- **Today:** All metrics are host/agent-keyed; API analytics covers only ServerKit's own API. No per-site visits/bandwidth/5xx/404/PHP-fatal.
diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx
index b8dd4a9e..8eff71de 100644
--- a/frontend/src/pages/WordPressDetail.jsx
+++ b/frontend/src/pages/WordPressDetail.jsx
@@ -76,7 +76,7 @@ const DetailPageSkeleton = () => (
</div>
);
-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security', 'updates', 'reports'];
+const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security', 'updates', 'php', 'reports'];
// Environment-type → dot tint for the header environment switcher.
const ENV_DOT_COLORS = {
@@ -493,6 +493,12 @@ const WordPressDetail = () => {
>
<RefreshCw size={14} /> Updates
</div>
+ <div
+ className={`app-detail-tab ${activeTab === 'php' ? 'active' : ''}`}
+ onClick={() => setActiveTab('php')}
+ >
+ <Settings size={14} /> PHP
+ </div>
<div
className={`app-detail-tab ${activeTab === 'reports' ? 'active' : ''}`}
onClick={() => setActiveTab('reports')}
@@ -562,6 +568,7 @@ const WordPressDetail = () => {
{activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}
{activeTab === 'security' && <SecurityTab siteId={site.id} />}
{activeTab === 'updates' && <UpdatesTab siteId={site.id} />}
+ {activeTab === 'php' && <PhpTab siteId={site.id} />}
{activeTab === 'reports' && <ReportsTab siteId={site.id} />}
</ErrorBoundary>
</div>
@@ -569,19 +576,38 @@ const WordPressDetail = () => {
);
};
+// Friendly labels for the editable php.ini directives (#24 limits panel).
+const PHP_LIMIT_LABELS = {
+ memory_limit: 'Memory Limit',
+ upload_max_filesize: 'Upload Max Filesize',
+ post_max_size: 'Post Max Size',
+ max_execution_time: 'Max Execution Time',
+ max_input_time: 'Max Input Time',
+ max_input_vars: 'Max Input Vars',
+};
+
// PHP Tab — live PHP version + ini limits for the Docker (apache/mod_php) site.
// Version is the image tag; switching recreates the container (volumes persist).
+// Limits are written as a durable conf.d drop-in (bind-mounted), editable below.
const PhpTab = ({ siteId }) => {
const toast = useToast();
const [php, setPhp] = useState(null);
const [loading, setLoading] = useState(true);
const [switching, setSwitching] = useState(false);
+ const [form, setForm] = useState({});
+ const [saving, setSaving] = useState(false);
const load = React.useCallback(async () => {
setLoading(true);
try {
const data = await wordpressApi.getPhpInfo(siteId);
- setPhp(data.php || data);
+ const info = data.php || data;
+ setPhp(info);
+ // Seed the edit form from live values for the editable directives.
+ const lim = info?.limits || {};
+ const seed = {};
+ (info?.editable_limits || []).forEach(k => { seed[k] = lim[k] || ''; });
+ setForm(seed);
} catch (err) {
toast.error(err.message || 'Failed to load PHP info');
} finally {
@@ -607,11 +633,35 @@ const PhpTab = ({ siteId }) => {
}
}
+ async function handleSaveLimits() {
+ // Send only the directives that changed from the live value (partial update).
+ const live = php?.limits || {};
+ const changed = {};
+ Object.entries(form).forEach(([k, v]) => {
+ const val = (v ?? '').toString().trim();
+ if (val && val !== (live[k] || '')) changed[k] = val;
+ });
+ if (Object.keys(changed).length === 0) { toast.info('No changes to save'); return; }
+ if (!window.confirm('Apply these PHP limits? The container reloads (brief downtime; database and files are preserved).')) return;
+ setSaving(true);
+ try {
+ const res = await wordpressApi.setPhpLimits(siteId, changed);
+ if (res.success === false) { toast.error(res.error || 'Failed to update PHP limits'); return; }
+ toast.success(res.message || 'PHP limits updated');
+ await load();
+ } catch (err) {
+ toast.error(err.message || 'Failed to update PHP limits');
+ } finally {
+ setSaving(false);
+ }
+ }
+
if (loading) return <div className="tab-loading"><p className="hint">Loading PHP info...</p></div>;
const limits = php?.limits || {};
const current = php?.php_version || 'Unknown';
const versions = php?.available_versions || [];
+ const editableKeys = php?.editable_limits || [];
return (
<div className="app-overview-grid">
@@ -663,6 +713,25 @@ const PhpTab = ({ siteId }) => {
</div>
</div>
)}
+
+ {editableKeys.length > 0 && (
+ <div className="app-panel">
+ <div className="app-panel-header">Edit PHP Limits</div>
+ <div className="app-panel-body">
+ <p className="hint">Saved as a durable conf.d drop-in bind-mounted into the container, so limits survive a container recreate. Saving reloads the container (brief downtime).</p>
+ {editableKeys.map(k => (
+ <div className="form-group" key={k}>
+ <Label>{PHP_LIMIT_LABELS[k] || k}</Label>
+ <Input value={form[k] ?? ''} placeholder={limits[k] || ''} disabled={saving}
+ onChange={e => setForm(f => ({ ...f, [k]: e.target.value }))} />
+ </div>
+ ))}
+ <div className="app-detail-actions">
+ <Button size="sm" onClick={handleSaveLimits} disabled={saving}>{saving ? 'Saving…' : 'Save limits'}</Button>
+ </div>
+ </div>
+ </div>
+ )}
</div>
</div>
);
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
index 705c68bf..d9cd8e08 100644
--- a/frontend/src/services/wordpress.js
+++ b/frontend/src/services/wordpress.js
@@ -175,6 +175,12 @@ const wordpressApi = {
body: { version }
}),
+ // Durably set per-site PHP ini limits (conf.d drop-in + bind-mount; #24).
+ setPhpLimits: (siteId, limits) => api.request(`${BASE_PATH}/${siteId}/php/limits`, {
+ method: 'POST',
+ body: { limits }
+ }),
+
// Update plugins. Pass an array of slugs to update specific ones, omit for all.
updatePlugins: (siteId, plugins) => api.request(`${BASE_PATH}/${siteId}/plugins/update`, {
method: 'POST',