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(workspaces): make python.py grant-aware — every app blueprint now covered (#33)

Juan Denis6f70eb9ad161
diff --git a/backend/app/api/python.py b/backend/app/api/python.py
index bfe155ba..571f44fa 100644
--- a/backend/app/api/python.py
+++ b/backend/app/api/python.py
@@ -22,14 +22,18 @@ def admin_required(fn):
def get_app_or_404(app_id, current_user_id):
- """Get application and verify access."""
+ """Get application and verify read access. Read endpoints rely on this gate;
+ mutating endpoints additionally carry @admin_required, so honoring per-resource
+ grants here (#33) safely opens only the read GETs to grantees. Uses can_access_app
+ (user.id), which also fixes the int-vs-str identity comparison."""
+ from app.services.resource_grant_service import ResourceGrantService
user = User.query.get(current_user_id)
app = Application.query.get(app_id)
if not app:
return None, ({'error': 'Application not found'}, 404)
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not ResourceGrantService.can_access_app(user, app):
return None, ({'error': 'Access denied'}, 403)
if app.app_type not in ['flask', 'django']:
diff --git a/backend/tests/test_resource_grants.py b/backend/tests/test_resource_grants.py
index b5daa280..dc0080e3 100644
--- a/backend/tests/test_resource_grants.py
+++ b/backend/tests/test_resource_grants.py
@@ -186,6 +186,28 @@ def test_grant_extends_to_other_app_blueprints(app, client):
assert client.get(url, headers=_token(grantee.id)).status_code == 200
+def test_grant_opens_python_read_gate(app, client):
+ """python.py's get_app_or_404 (the shared read gate) honors grants; its mutating
+ endpoints are independently @admin_required, so a grant only opens the reads."""
+ from app import db
+ from app.models import Application
+ from app.services.resource_grant_service import ResourceGrantService
+
+ owner = _mk_user(db, 'py_owner')
+ grantee = _mk_user(db, 'py_grantee')
+ stranger = _mk_user(db, 'py_stranger')
+ a = Application(name='py-app', app_type='flask', user_id=owner.id, root_path='/srv/py')
+ db.session.add(a)
+ db.session.commit()
+
+ url = f'/api/v1/python/apps/{a.id}/packages' # GET, read (no @admin_required)
+ assert client.get(url, headers=_token(stranger.id)).status_code == 403 # gate denies
+ ResourceGrantService.grant(user_id=grantee.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='viewer')
+ # The grantee passes the read gate (the read itself may be empty, but not a 403).
+ assert client.get(url, headers=_token(grantee.id)).status_code != 403
+
+
def test_grant_enables_wordpress_per_site_routes(app, client):
from app import db
from app.models import Application, WordPressSite
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index 0a341630..dbe17443 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -291,7 +291,7 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c
- **Done when:** Each site exposes scoped SFTP credentials.
- **Assessment / why deferred:** The roadmap's host-sshd-chroot approach doesn't fit the Docker model — a managed site's files live in the `wordpress_html` **named volume**, not a host path, so a host-level chroot would target the wrong place. The **Docker-correct** design is a per-site **SFTP sidecar container** (e.g. `atmoz/sftp`) mounting `wordpress_html`, injected into the compose stack exactly like #23's redis (`_ensure_*_in_stack` + additive `compose up -d`), with a generated credential surfaced once and a new mapped port (via the template's port-allocation). That is genuinely implementable on the proven pattern — but it (a) opens a **publicly-exposed, security-sensitive file-access surface** that should be firewalled and that I cannot runtime-verify from the dev host, and (b) consumes a port + a container per site. Shipping security-sensitive infra blind violates the quality bar, so this is deferred for a focused pass on a real Docker host (where the sidecar, chroot perms, and firewall can be exercised). No code shipped.
-### #33 — Agency scale (workspaces, RBAC, white-label, reports) `[XL]` 🟡 — 🟡 In progress (✅ reports · workspace_id foundation · selector · brand color · resource reassignment · WP-hub scoping · **per-site ACL** (backend + sharing UI + viewer/editor roles + operate access); remaining: workspace↔User role reconciliation, python.py helper split, workspace scoping for databases/domains)
+### #33 — Agency scale (workspaces, RBAC, white-label, reports) `[XL]` 🟡 — 🟡 In progress (✅ reports · workspace_id foundation · selector · brand color · resource reassignment · WP-hub scoping · **per-site ACL** (backend + sharing UI + viewer/editor roles + operate access); remaining: workspace↔User role reconciliation, workspace scoping for databases/domains)
- **Today:** No `workspace_id` FK on `Application`/`WordPressSite`/`Server`; permissions are global with no per-site ACL; white-label lives in `localStorage` and never reads `Workspace.logo_url`/`primary_color`.
- **Do:** Add `workspace_id` FKs + per-site ACL rows + environment-tier RBAC in promote/sync/bulk endpoints; server-side branding scoped to workspace; monthly client reports aggregating uptime/updates/backups/security.
- **Reuse:** `workspace_service`, `permission_service`, `audit_service`.
@@ -303,7 +303,7 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c
- **Landed (workspace-scoped brand color):** the visible payoff — selecting a client workspace now recolors the whole panel to that client's brand. A workspace's `primary_color` (already on the model; now editable via a color picker added to the Workspaces create modal) is mirrored by the `WorkspaceSwitcher` into a `workspace_accent` localStorage key, and `ThemeContext` applies it via the existing `applyAccentToDOM` with **precedence over the user's personal accent** (`workspace_accent || accentColor`) — recoloring the logo gradient, buttons, and highlights. Deterministic (no effect-ordering races) because switching reloads and the value is read once on mount; cleared on logout and on a stale selection; reverts to the user accent on "All workspaces". Default color is the app accent, so a workspace is unbranded unless a custom color is chosen. Verified: frontend lint-clean (no new warnings) + production build. *(Deferred: per-workspace logo swap in the sidebar brand — the accent recolor is the high-impact piece and the default logo already recolors with the accent.)*
- **Landed (resource reassignment):** completes the organizing loop — existing resources were stuck wherever the backfill put them (Default); now they can be moved into client workspaces. New endpoints `PUT /apps/<id>/workspace` (owner-or-admin on the app) and `PUT /servers/<id>/workspace` (developer+), both requiring the **target** be a workspace the caller can access (member or admin); a null target moves a resource back to Default. UI: an **Apps** management modal on each Workspaces card (mirrors the Members modal) listing the workspace's apps with move-in/move-out — it fetches with `allWorkspaces` (an empty `X-Workspace-Id` header) so it can see apps in other workspaces to move them in, sidestepping the ambient scope. **Fixed a real bug** caught by tests: the ownership check compared `app.user_id` to the *stringified* `get_jwt_identity()` (int≠str → spurious 403); now uses `user.id`. Verified: backend `py_compile`, **2 new endpoint tests** (ownership + target-membership + null→Default + role gates), full suite **122 passed**, frontend lint-clean + production build. The management modal now handles **both apps and servers** (a "Resources" modal on each Workspaces card), each with move-in/move-out; servers fetch with the same `allWorkspaces` header bypass.
- **Landed (WordPress hub workspace scoping):** the active-workspace switcher now also filters the **WordPress sites hub**, not just apps/servers (it was the inconsistent gap). WP sites carry no `workspace_id` of their own, so `WordPressService.get_sites(workspace_id=…)` scopes **join-based** through the site's parent `Application.workspace_id`; `list_sites` resolves the active workspace and passes it. The hub is global today, so with no workspace context behavior is unchanged (additive, narrow-only). **No frontend change** — the WP hub already fetches through the header-injecting `api.request`, so it auto-scopes on the ambient `X-Workspace-Id`. Verified: backend `py_compile`, a new API test (global vs workspace-scoped), full suite **123 passed**. *(Follow-on for broad adoption: databases/domains are murkier — server-level vs app-child — and need their own analysis before scoping.)*
-- **Landed (per-site ACL — backend):** per-resource **sharing** — an owner/admin can grant a specific user access to a specific application (transitively its WordPress site / DB / domains) without that user owning it (access-level; per-grant view/edit roles reserved for later via a `role` column). New `ResourceGrant` model (Alembic **016**, unique per user×resource) + `ResourceGrantService` (grant/revoke/list/`user_has_grant`/`granted_ids`). **Enforcement at the cleanest seams:** `WorkspaceService.scope_query` gained `grant_resource_type` so granted apps appear in the apps list (own **OR** granted, then workspace-narrowed); `get_app` and — crucially — the WordPress `_owner_or_admin_app` helper became grant-aware, so **one change opens every WP per-site route** to a grantee. Grant-management API on `apps.py` (`GET/POST/DELETE /apps/<id>/grants`, owner-or-admin; can't grant to the owner; revoke is resource-scoped so you can't revoke another app's grant by id). Also uses `user.id` (int) not the stringified `get_jwt_identity()`. Verified: **4 new ACL tests** (visibility via list, get_app, WP route access, management perms + idempotency + revoke), full suite **127 passed**, end-to-end `alembic upgrade` to `016`. **Sharing UI (shipped):** a per-app **Share** action in the Workspaces "Resources" modal opens an inline sub-view (grant a user → access list with revoke; the owner and existing grantees are filtered out of the add-list); client methods `getAppGrants`/`grantAppAccess`/`revokeAppAccess`. Verified: frontend lint-clean + build. **Viewer/editor roles + operate access (shipped):** grants now carry a real **role** — `editor` (view + operate) or `viewer` (read-only) — and the generic app **operate** endpoints became grant-aware. Two helpers split it: `_can_access_app` (owner/admin/**any** grant) gates reads (`get_app`, `/linked`, `/logs`, `/container-logs`, `/containers`, `/status`), `_can_edit_app` (owner/admin/**editor** grant) gates mutations (`/link`, `/unlink`, `/environment`, `PUT`, `/start`, `/stop`, `/restart`); `ResourceGrantService.grant_role` backs the split. **Delete stays owner-or-admin** (an editor can't delete — tested). The grant POST validates `role ∈ {viewer, editor}` (default editor); the Sharing UI gained a role selector. The same sweep **fixed the latent int-vs-str ownership bug** across ~14 app endpoints (they compared `app.user_id` to the stringified `get_jwt_identity()` — now `user.id`). Verified: **3 more ACL tests** (viewer read-only + can't-operate, editor operates + can't-delete, role validation/default), full suite **130 passed**, frontend lint-clean + build. **Cross-blueprint sweep (shipped):** the per-resource grant now extends to every app-related blueprint, not just apps.py + WordPress. The two access helpers were promoted to a shared seam (`ResourceGrantService.can_access_app` / `can_edit_app`; `apps.py` delegates), and **33 ownership checks across 6 blueprints** were made grant-aware, categorized read-vs-mutate (via a parallel mapping workflow): `builds.py` (12), `domains.py` (7, incl. SSL enable/disable/renew + domain CRUD = editor), `deploy.py` (6), `private_urls.py` (5), `templates.py` (2), `databases.py` (1). Reads → any grant; mutates → editor grant. The sweep also **fixed the same latent int-vs-str ownership bug** in all 33 (now `user.id`). Verified: a cross-blueprint integration test (grantee reaches `builds` deployments; stranger 403), full suite **131 passed**. *(Deferred: `python.py`'s single `get_app_or_404` helper gates read+mutate+delete together — needs per-method splitting before it's safe to make grant-aware.)*
+- **Landed (per-site ACL — backend):** per-resource **sharing** — an owner/admin can grant a specific user access to a specific application (transitively its WordPress site / DB / domains) without that user owning it (access-level; per-grant view/edit roles reserved for later via a `role` column). New `ResourceGrant` model (Alembic **016**, unique per user×resource) + `ResourceGrantService` (grant/revoke/list/`user_has_grant`/`granted_ids`). **Enforcement at the cleanest seams:** `WorkspaceService.scope_query` gained `grant_resource_type` so granted apps appear in the apps list (own **OR** granted, then workspace-narrowed); `get_app` and — crucially — the WordPress `_owner_or_admin_app` helper became grant-aware, so **one change opens every WP per-site route** to a grantee. Grant-management API on `apps.py` (`GET/POST/DELETE /apps/<id>/grants`, owner-or-admin; can't grant to the owner; revoke is resource-scoped so you can't revoke another app's grant by id). Also uses `user.id` (int) not the stringified `get_jwt_identity()`. Verified: **4 new ACL tests** (visibility via list, get_app, WP route access, management perms + idempotency + revoke), full suite **127 passed**, end-to-end `alembic upgrade` to `016`. **Sharing UI (shipped):** a per-app **Share** action in the Workspaces "Resources" modal opens an inline sub-view (grant a user → access list with revoke; the owner and existing grantees are filtered out of the add-list); client methods `getAppGrants`/`grantAppAccess`/`revokeAppAccess`. Verified: frontend lint-clean + build. **Viewer/editor roles + operate access (shipped):** grants now carry a real **role** — `editor` (view + operate) or `viewer` (read-only) — and the generic app **operate** endpoints became grant-aware. Two helpers split it: `_can_access_app` (owner/admin/**any** grant) gates reads (`get_app`, `/linked`, `/logs`, `/container-logs`, `/containers`, `/status`), `_can_edit_app` (owner/admin/**editor** grant) gates mutations (`/link`, `/unlink`, `/environment`, `PUT`, `/start`, `/stop`, `/restart`); `ResourceGrantService.grant_role` backs the split. **Delete stays owner-or-admin** (an editor can't delete — tested). The grant POST validates `role ∈ {viewer, editor}` (default editor); the Sharing UI gained a role selector. The same sweep **fixed the latent int-vs-str ownership bug** across ~14 app endpoints (they compared `app.user_id` to the stringified `get_jwt_identity()` — now `user.id`). Verified: **3 more ACL tests** (viewer read-only + can't-operate, editor operates + can't-delete, role validation/default), full suite **130 passed**, frontend lint-clean + build. **Cross-blueprint sweep (shipped):** the per-resource grant now extends to every app-related blueprint, not just apps.py + WordPress. The two access helpers were promoted to a shared seam (`ResourceGrantService.can_access_app` / `can_edit_app`; `apps.py` delegates), and **33 ownership checks across 6 blueprints** were made grant-aware, categorized read-vs-mutate (via a parallel mapping workflow): `builds.py` (12), `domains.py` (7, incl. SSL enable/disable/renew + domain CRUD = editor), `deploy.py` (6), `private_urls.py` (5), `templates.py` (2), `databases.py` (1). Reads → any grant; mutates → editor grant. The sweep also **fixed the same latent int-vs-str ownership bug** in all 33 (now `user.id`). Verified: a cross-blueprint integration test (grantee reaches `builds` deployments; stranger 403), full suite **131 passed**. **`python.py` (shipped):** re-reading showed every mutating endpoint there is independently `@admin_required` (runs before the shared `get_app_or_404` gate), so the gate only governs the 4 read GETs — pointing it at `can_access_app` safely opens those to grantees while the admin-only mutations are untouched. No per-method split needed. With this, **every app-related blueprint is grant-aware.** Verified: a python read-gate test (stranger 403, grantee passes), full suite **132 passed**.
### #34 — Horizontal scaling `[XL]` ❌ — ⏸️ Deferred (XL + blocked on the same per-site reverse-proxy/upstream layer as #21)
- **Today:** `nginx_advanced_service` has load-balancing primitives (round-robin/least-conn/IP-hash) but WP containers are stateful (local uploads, no shared object cache).