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): viewer/editor grant roles + operate-endpoint access (#33)

Juan Denis2d83440040ab
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index 43ac1bbf..32cad79c 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -93,7 +93,7 @@ def link_apps(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
data = request.get_json()
@@ -114,7 +114,7 @@ def link_apps(app_id):
if not target_app:
return jsonify({'error': 'Target application not found'}), 404
- if user.role != 'admin' and target_app.user_id != current_user_id:
+ if not _can_edit_app(user, target_app):
return jsonify({'error': 'Access denied to target application'}), 403
if app.app_type != target_app.app_type:
@@ -192,7 +192,7 @@ def get_linked_apps(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_access_app(user, app):
return jsonify({'error': 'Access denied'}), 403
linked_apps = []
@@ -239,7 +239,7 @@ def unlink_apps(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
if not app.linked_app_id:
@@ -276,7 +276,7 @@ def update_environment(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
data = request.get_json()
@@ -368,7 +368,7 @@ def set_app_workspace(app_id):
def _can_access_app(user, app):
- """True if the user owns the app, is admin, or was granted access (#33 ACL).
+ """Read access (#33 ACL): owner, admin, or ANY grant (viewer or editor).
Uses user.id (int) — get_jwt_identity() is the stringified token id."""
if user.is_admin or app.user_id == user.id:
return True
@@ -376,6 +376,15 @@ def _can_access_app(user, app):
return ResourceGrantService.user_has_grant(user.id, 'application', app.id)
+def _can_edit_app(user, app):
+ """Write/operate access (#33 ACL): owner, admin, or an EDITOR grant. A viewer
+ grant confers read access only."""
+ if user.is_admin or app.user_id == user.id:
+ return True
+ from app.services.resource_grant_service import ResourceGrantService
+ return ResourceGrantService.grant_role(user.id, 'application', app.id) == 'editor'
+
+
@apps_bp.route('/<int:app_id>', methods=['GET'])
@jwt_required()
def get_app(app_id):
@@ -429,9 +438,11 @@ def grant_app_access(app_id):
return jsonify({'error': 'User not found'}), 404
if grantee.id == app.user_id:
return jsonify({'error': 'The owner already has access'}), 400
+ role = data.get('role') or 'editor'
+ if role not in ('viewer', 'editor'):
+ return jsonify({'error': "role must be 'viewer' or 'editor'"}), 400
grant = ResourceGrantService.grant(user_id=grantee.id, resource_type='application',
- resource_id=app.id, granted_by=user.id,
- role=data.get('role') or 'editor')
+ resource_id=app.id, granted_by=user.id, role=role)
return jsonify({'grant': grant.to_dict()}), 201
@@ -673,7 +684,7 @@ def update_app(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
data = request.get_json()
@@ -714,7 +725,7 @@ def delete_app(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not user.is_admin and app.user_id != user.id:
return jsonify({'error': 'Access denied'}), 403
cleanup_results = {
@@ -769,7 +780,7 @@ def start_app(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
# Handle Docker apps
@@ -805,7 +816,7 @@ def stop_app(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
# Handle Docker apps
@@ -840,7 +851,7 @@ def restart_app(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_edit_app(user, app):
return jsonify({'error': 'Access denied'}), 403
# Handle Docker apps
@@ -876,7 +887,7 @@ def get_app_logs(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_access_app(user, app):
return jsonify({'error': 'Access denied'}), 403
lines = request.args.get('lines', 100, type=int)
@@ -931,7 +942,7 @@ def get_container_logs(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_access_app(user, app):
return jsonify({'error': 'Access denied'}), 403
# Parse query parameters
@@ -1036,7 +1047,7 @@ def get_app_containers(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_access_app(user, app):
return jsonify({'error': 'Access denied'}), 403
containers = DockerService.get_all_app_containers(app)
@@ -1059,7 +1070,7 @@ def get_app_status(app_id):
if not app:
return jsonify({'error': 'Application not found'}), 404
- if user.role != 'admin' and app.user_id != current_user_id:
+ if not _can_access_app(user, app):
return jsonify({'error': 'Access denied'}), 403
if app.app_type == 'docker' and app.root_path:
diff --git a/backend/app/services/resource_grant_service.py b/backend/app/services/resource_grant_service.py
index 516c21d1..72722a94 100644
--- a/backend/app/services/resource_grant_service.py
+++ b/backend/app/services/resource_grant_service.py
@@ -29,6 +29,16 @@ class ResourceGrantService:
user_id=user_id, resource_type=resource_type, resource_id=resource_id
).first() is not None
+ @staticmethod
+ def grant_role(user_id, resource_type, resource_id):
+ """The role of this user's grant on the resource ('viewer'/'editor'), or
+ None if there is no grant."""
+ from app.models.workspace import ResourceGrant
+ row = ResourceGrant.query.filter_by(
+ user_id=user_id, resource_type=resource_type, resource_id=resource_id
+ ).first()
+ return row.role if row else None
+
@staticmethod
def list_for_resource(resource_type, resource_id):
from app.models.workspace import ResourceGrant
diff --git a/backend/tests/test_resource_grants.py b/backend/tests/test_resource_grants.py
index 2a91e03b..a996e672 100644
--- a/backend/tests/test_resource_grants.py
+++ b/backend/tests/test_resource_grants.py
@@ -99,6 +99,70 @@ def test_grant_is_idempotent(app, client):
assert ResourceGrant.query.filter_by(resource_type='application', resource_id=a.id, user_id=grantee.id).count() == 1
+def test_viewer_grant_is_read_only(app, client):
+ from app import db
+ from app.models import Application
+ from app.services.resource_grant_service import ResourceGrantService
+
+ owner = _mk_user(db, 'v_owner')
+ viewer = _mk_user(db, 'v_viewer')
+ a = Application(name='v-app', app_type='php', user_id=owner.id, root_path='/srv/v')
+ db.session.add(a)
+ db.session.commit()
+ ResourceGrantService.grant(user_id=viewer.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='viewer')
+
+ # A viewer can read the app and its linked list...
+ assert client.get(f'/api/v1/apps/{a.id}', headers=_token(viewer.id)).status_code == 200
+ assert client.get(f'/api/v1/apps/{a.id}/linked', headers=_token(viewer.id)).status_code == 200
+ # ...but operating it (editor-only) is denied.
+ assert client.post(f'/api/v1/apps/{a.id}/start', headers=_token(viewer.id)).status_code == 403
+
+
+def test_editor_grant_can_operate(app, client):
+ from app import db
+ from app.models import Application
+ from app.services.resource_grant_service import ResourceGrantService
+
+ owner = _mk_user(db, 'e_owner')
+ editor = _mk_user(db, 'e_editor')
+ a = Application(name='e-app', app_type='php', user_id=owner.id, root_path='/srv/e')
+ db.session.add(a)
+ db.session.commit()
+ ResourceGrantService.grant(user_id=editor.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='editor')
+
+ # An editor passes the operate access gate (the start action itself may fail
+ # without Docker, but it must NOT be a 403 access denial).
+ assert client.post(f'/api/v1/apps/{a.id}/start', headers=_token(editor.id)).status_code != 403
+ # ...but delete stays owner-only — even an editor cannot delete the app.
+ assert client.delete(f'/api/v1/apps/{a.id}', headers=_token(editor.id)).status_code == 403
+
+
+def test_grant_role_validation_and_default(app, client):
+ from app import db
+ from app.models import Application
+
+ owner = _mk_user(db, 'rv_owner')
+ g1 = _mk_user(db, 'rv_g1')
+ g2 = _mk_user(db, 'rv_g2')
+ a = Application(name='rv-app', app_type='php', user_id=owner.id)
+ db.session.add(a)
+ db.session.commit()
+
+ # Default role is editor.
+ r = client.post(f'/api/v1/apps/{a.id}/grants', json={'user_id': g1.id}, headers=_token(owner.id))
+ assert r.status_code == 201 and r.get_json()['grant']['role'] == 'editor'
+
+ # Explicit viewer is honored.
+ r = client.post(f'/api/v1/apps/{a.id}/grants', json={'user_id': g2.id, 'role': 'viewer'}, headers=_token(owner.id))
+ assert r.status_code == 201 and r.get_json()['grant']['role'] == 'viewer'
+
+ # An unknown role is rejected.
+ r = client.post(f'/api/v1/apps/{a.id}/grants', json={'user_id': g2.id, 'role': 'superuser'}, headers=_token(owner.id))
+ assert r.status_code == 400
+
+
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 89d92337..0159f8b9 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); remaining: broad operate-endpoint grant adoption, workspace↔User role reconciliation)
+### #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: grant-awareness for env-vars/databases/domains blueprints, workspace↔User role reconciliation)
- **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. *(Deferred: broadening grant-access to the generic app **operate** endpoints — start/stop/update — which stay owner-or-admin for now; delete stays owner-only by design.)*
+- **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. *(Still owner-only / not-yet-grant-aware: the separate env-vars / databases / domains endpoints in other blueprints — a follow-up sweep.)*
### #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).
diff --git a/frontend/src/pages/Workspaces.jsx b/frontend/src/pages/Workspaces.jsx
index 9a5ec5a6..36ed775f 100644
--- a/frontend/src/pages/Workspaces.jsx
+++ b/frontend/src/pages/Workspaces.jsx
@@ -26,6 +26,7 @@ const Workspaces = () => {
const [servers, setServers] = useState([]);
const [sharingApp, setSharingApp] = useState(null);
const [grants, setGrants] = useState([]);
+ const [grantRole, setGrantRole] = useState('editor');
const [form, setForm] = useState({ name: '', description: '', max_servers: 0, max_users: 0, primary_color: '#6366f1' });
const loadWorkspaces = useCallback(async () => {
@@ -168,7 +169,7 @@ const Workspaces = () => {
const handleGrant = async (userId) => {
try {
- await api.grantAppAccess(sharingApp.id, userId);
+ await api.grantAppAccess(sharingApp.id, userId, grantRole);
toast.success('Access granted');
await refreshGrants(sharingApp.id);
} catch (err) {
@@ -362,6 +363,13 @@ const Workspaces = () => {
</div>
<hr />
<h4>Grant Access</h4>
+ <div className="form-group">
+ <label>Role for new grants</label>
+ <select value={grantRole} onChange={e => setGrantRole(e.target.value)}>
+ <option value="editor">Editor (view + operate)</option>
+ <option value="viewer">Viewer (read-only)</option>
+ </select>
+ </div>
<div className="server-select-list">
{allUsers.filter(u => u.id !== sharingApp.user_id && !grants.find(g => g.user_id === u.id)).map(u => (
<div key={u.id} className="server-select-item" onClick={() => handleGrant(u.id)}>