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): sharing UI for per-site ACL grants (#33)

Juan Denis4dca43b6b06e
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index 1bc3e04f..89d92337 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**; remaining: ACL sharing UI, broad operate-endpoint 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); remaining: broad operate-endpoint grant adoption, 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`. *(Deferred: a **Sharing UI** (next), and 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. *(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.)*
### #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 8d3b4669..9a5ec5a6 100644
--- a/frontend/src/pages/Workspaces.jsx
+++ b/frontend/src/pages/Workspaces.jsx
@@ -24,6 +24,8 @@ const Workspaces = () => {
const [showResourcesModal, setShowResourcesModal] = useState(null);
const [apps, setApps] = useState([]);
const [servers, setServers] = useState([]);
+ const [sharingApp, setSharingApp] = useState(null);
+ const [grants, setGrants] = useState([]);
const [form, setForm] = useState({ name: '', description: '', max_servers: 0, max_users: 0, primary_color: '#6366f1' });
const loadWorkspaces = useCallback(async () => {
@@ -144,6 +146,51 @@ const Workspaces = () => {
}
};
+ // Per-app sharing (#33 per-site ACL) — inline sub-view of the Resources modal.
+ const loadSharing = async (appObj) => {
+ try {
+ const [gData, uData] = await Promise.all([
+ api.getAppGrants(appObj.id),
+ api.getUsers().catch(() => ({ users: [] })),
+ ]);
+ setGrants(gData.grants || []);
+ setAllUsers(uData.users || []);
+ setSharingApp(appObj);
+ } catch (err) {
+ toast.error('Failed to load sharing');
+ }
+ };
+
+ const refreshGrants = async (appId) => {
+ const gData = await api.getAppGrants(appId);
+ setGrants(gData.grants || []);
+ };
+
+ const handleGrant = async (userId) => {
+ try {
+ await api.grantAppAccess(sharingApp.id, userId);
+ toast.success('Access granted');
+ await refreshGrants(sharingApp.id);
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ const handleRevoke = async (grantId) => {
+ try {
+ await api.revokeAppAccess(sharingApp.id, grantId);
+ toast.success('Access revoked');
+ await refreshGrants(sharingApp.id);
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ const closeResources = () => {
+ setShowResourcesModal(null);
+ setSharingApp(null);
+ };
+
if (loading) return <Spinner />;
return (
@@ -293,54 +340,90 @@ const Workspaces = () => {
const srvIn = servers.filter(s => s.workspace_id === showResourcesModal);
const srvOut = servers.filter(s => s.workspace_id !== showResourcesModal);
return (
- <div className="modal-overlay" onClick={() => setShowResourcesModal(null)}>
+ <div className="modal-overlay" onClick={closeResources}>
<div className="modal" onClick={e => e.stopPropagation()}>
- <div className="modal-header">
- <h2>Workspace Resources</h2>
- <button className="modal-close" onClick={() => setShowResourcesModal(null)}>&times;</button>
- </div>
- <div className="modal-body">
- <h4>Applications</h4>
- <div className="members-list">
- {appsIn.length === 0 && <p className="form-hint">No applications in this workspace yet.</p>}
- {appsIn.map(a => (
- <div key={a.id} className="member-row">
- <div><strong>{a.name}</strong> <Badge variant="outline" className="ml-2">{a.app_type}</Badge></div>
- <Button size="sm" variant="destructive" onClick={() => handleMoveApp(a.id, null)}>Remove</Button>
+ {sharingApp ? (
+ <>
+ <div className="modal-header">
+ <h2>Sharing: {sharingApp.name}</h2>
+ <button className="modal-close" onClick={closeResources}>&times;</button>
+ </div>
+ <div className="modal-body">
+ <Button size="sm" variant="outline" onClick={() => setSharingApp(null)}>&larr; Back</Button>
+ <p className="form-hint">Grant a user access to this application (and its WordPress site, databases, and domains) without transferring ownership.</p>
+ <div className="members-list">
+ {grants.length === 0 && <p className="form-hint">Not shared with anyone yet.</p>}
+ {grants.map(g => (
+ <div key={g.id} className="member-row">
+ <div><strong>{g.username || g.email}</strong> <Badge variant="outline" className="ml-2">{g.role}</Badge></div>
+ <Button size="sm" variant="destructive" onClick={() => handleRevoke(g.id)}>Revoke</Button>
+ </div>
+ ))}
+ </div>
+ <hr />
+ <h4>Grant Access</h4>
+ <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)}>
+ <span>{u.username || u.email}</span>
+ </div>
+ ))}
</div>
- ))}
- </div>
- {appsOut.length > 0 && (
- <div className="server-select-list">
- {appsOut.map(a => (
- <div key={a.id} className="server-select-item" onClick={() => handleMoveApp(a.id, showResourcesModal)}>
- <span>{a.name}</span>
- <Badge variant="outline" className="ml-2">{a.app_type}</Badge>
- </div>
- ))}
</div>
- )}
- <hr />
- <h4>Servers</h4>
- <div className="members-list">
- {srvIn.length === 0 && <p className="form-hint">No servers in this workspace yet.</p>}
- {srvIn.map(s => (
- <div key={s.id} className="member-row">
- <div><strong>{s.name}</strong></div>
- <Button size="sm" variant="destructive" onClick={() => handleMoveServer(s.id, null)}>Remove</Button>
+ </>
+ ) : (
+ <>
+ <div className="modal-header">
+ <h2>Workspace Resources</h2>
+ <button className="modal-close" onClick={closeResources}>&times;</button>
+ </div>
+ <div className="modal-body">
+ <h4>Applications</h4>
+ <div className="members-list">
+ {appsIn.length === 0 && <p className="form-hint">No applications in this workspace yet.</p>}
+ {appsIn.map(a => (
+ <div key={a.id} className="member-row">
+ <div><strong>{a.name}</strong> <Badge variant="outline" className="ml-2">{a.app_type}</Badge></div>
+ <div className="workspace-row-actions">
+ <Button size="sm" variant="outline" onClick={() => loadSharing(a)}>Share</Button>
+ <Button size="sm" variant="destructive" onClick={() => handleMoveApp(a.id, null)}>Remove</Button>
+ </div>
+ </div>
+ ))}
</div>
- ))}
- </div>
- {srvOut.length > 0 && (
- <div className="server-select-list">
- {srvOut.map(s => (
- <div key={s.id} className="server-select-item" onClick={() => handleMoveServer(s.id, showResourcesModal)}>
- <span>{s.name}</span>
+ {appsOut.length > 0 && (
+ <div className="server-select-list">
+ {appsOut.map(a => (
+ <div key={a.id} className="server-select-item" onClick={() => handleMoveApp(a.id, showResourcesModal)}>
+ <span>{a.name}</span>
+ <Badge variant="outline" className="ml-2">{a.app_type}</Badge>
+ </div>
+ ))}
+ </div>
+ )}
+ <hr />
+ <h4>Servers</h4>
+ <div className="members-list">
+ {srvIn.length === 0 && <p className="form-hint">No servers in this workspace yet.</p>}
+ {srvIn.map(s => (
+ <div key={s.id} className="member-row">
+ <div><strong>{s.name}</strong></div>
+ <Button size="sm" variant="destructive" onClick={() => handleMoveServer(s.id, null)}>Remove</Button>
+ </div>
+ ))}
+ </div>
+ {srvOut.length > 0 && (
+ <div className="server-select-list">
+ {srvOut.map(s => (
+ <div key={s.id} className="server-select-item" onClick={() => handleMoveServer(s.id, showResourcesModal)}>
+ <span>{s.name}</span>
+ </div>
+ ))}
</div>
- ))}
+ )}
</div>
- )}
- </div>
+ </>
+ )}
</div>
</div>
);
diff --git a/frontend/src/services/api/apps.js b/frontend/src/services/api/apps.js
index a186373a..0988acd1 100644
--- a/frontend/src/services/api/apps.js
+++ b/frontend/src/services/api/apps.js
@@ -18,6 +18,19 @@ export async function setAppWorkspace(appId, workspaceId) {
});
}
+// Per-resource access grants (#33 per-site ACL): share an app with a user.
+export async function getAppGrants(appId) {
+ return this.request(`/apps/${appId}/grants`);
+}
+
+export async function grantAppAccess(appId, userId, role) {
+ return this.request(`/apps/${appId}/grants`, { method: 'POST', body: { user_id: userId, role } });
+}
+
+export async function revokeAppAccess(appId, grantId) {
+ return this.request(`/apps/${appId}/grants/${grantId}`, { method: 'DELETE' });
+}
+
export async function getApp(id) {
return this.request(`/apps/${id}`);
}
diff --git a/frontend/src/styles/pages/_workspaces.scss b/frontend/src/styles/pages/_workspaces.scss
index a2f9202f..62ef9a5b 100644
--- a/frontend/src/styles/pages/_workspaces.scss
+++ b/frontend/src/styles/pages/_workspaces.scss
@@ -115,3 +115,10 @@
background: transparent;
cursor: pointer;
}
+
+// Per-app row actions (Share + Remove) in the workspace Resources modal (#33).
+.workspace-row-actions {
+ display: flex;
+ gap: $spacing-sm;
+ flex-shrink: 0;
+}