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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(search): unified entity omnisearch endpoint for the palette
Juan Denis2dfe0d7d5454
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0d01b81c..9b33772e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,19 @@ awaiting a stable release:### Added+- **Command palette is now an everything-search (F1 / Ctrl+Shift+P / Ctrl+K)** —+ the palette went from a page-jumper to omnisearch. Type to search across pages,+ individual **settings** (the actual card, e.g. "Require two-factor for all+ members" or "SMTP", not just the tab), runnable **actions** (`>` prefix — New+ Service, Add Server, Toggle theme, Sign out…), live **entities** (services,+ servers, domains, databases, WordPress sites, cron jobs, extensions, vaults —+ via a new authz-aware `GET /api/v1/search`), and **docs** (`?` prefix). Results+ rank by match quality plus your own usage (per-user frecency), an empty query+ shows Recently used, and pressing Enter on a settings result lands you on the+ exact card — scrolled into view and briefly highlighted. VS Code's F1 and+ Ctrl/Cmd+Shift+P now open it alongside the original Ctrl/Cmd+K. Results are+ filtered by the same admin + workspace-nav rules as the sidebar, so a member's+ palette never surfaces admin-only pages, settings, or actions.- **One-click GitHub setup (GitHub App manifest flow)** — connecting GitHub nolonger means hand-registering an OAuth app and pasting a client id + secret.An admin clicks **Set up in one click** in Settings → Connections; ServerKitdiff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 061cf85f..a26b270f 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -449,6 +449,10 @@ def create_app(config_name=None):from app.api.plugins import plugins_bpapp.register_blueprint(plugins_bp, url_prefix='/api/v1/plugins')+ # Register blueprints - Unified entity omnisearch+ from app.api.search import search_bp+ app.register_blueprint(search_bp, url_prefix='/api/v1/search')+# Register blueprints - Modules (core-vertical toggles)from app.api.modules import modules_bpapp.register_blueprint(modules_bp, url_prefix='/api/v1/modules')diff --git a/backend/app/api/search.py b/backend/app/api/search.pynew file mode 100644index 00000000..e2b03fc9--- /dev/null+++ b/backend/app/api/search.py@@ -0,0 +1,28 @@+"""Unified entity omnisearch API (plan 41, Phase 4).++A single authz-aware endpoint the command palette calls to search across the+core entity types (services, servers, domains, databases, WordPress sites, cron+jobs, extensions, vaults). Business logic lives in SearchService; this blueprint+just validates the term, resolves the user, and shapes the JSON.+"""+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.models.user import User+from app.services.search_service import SearchService++search_bp = Blueprint('search', __name__)+++@search_bp.route('', methods=['GET'])+@jwt_required()+def search():+ """Search entities by name. ?q=<term> (>= 2 chars). Returns {'results': [...]}."""+ q = request.args.get('q', '').strip()+ if len(q) < 2:+ return jsonify({'results': []}), 200++ user = User.query.get(get_jwt_identity())+ workspace = request.headers.get('X-Workspace-Id') or request.args.get('workspace_id')+ rows = SearchService.search(user, q, workspace)+ return jsonify({'results': rows}), 200diff --git a/backend/app/services/search_service.py b/backend/app/services/search_service.pynew file mode 100644index 00000000..6c54e15f--- /dev/null+++ b/backend/app/services/search_service.py@@ -0,0 +1,234 @@+"""Unified entity omnisearch (plan 41, Phase 4).++Fans a short search term out across the panel's core entity types and returns a+flat list of lightweight, deep-linkable rows. Each entity type reuses its+domain's existing access helpers so a member never sees resources they can't+already reach elsewhere — the search endpoint invents no new ACL.++Design rules:+ - Case-insensitive substring match (SQL ILIKE / Python `in` on lowered text).+ - Per-type cap of ``PER_TYPE_CAP`` rows so one noisy type can't drown the rest.+ - Every entity block is isolated in its own try/except: one failing type+ (missing table, migration skew, service error) degrades to "no rows of that+ type" instead of 500-ing the whole search.+"""+import logging++logger = logging.getLogger(__name__)++PER_TYPE_CAP = 5+++class SearchService:+ """Stateless authz-aware entity search."""++ @staticmethod+ def search(user, term, workspace_header=None):+ """Return a flat list of match rows across the core entity types.++ Rows: {'type', 'label', 'sublabel', 'path'}. `term` is expected to be+ already trimmed and >= 2 chars by the route; we still guard here so the+ service is safe to call directly.+ """+ if user is None:+ return []+ term = (term or '').strip()+ if len(term) < 2:+ return []++ from app.services.workspace_service import WorkspaceService+ ws_id = WorkspaceService.resolve_workspace_id(user, workspace_header)++ like = f'%{term}%'+ needle = term.lower()+ rows = []++ # Resolve the set of application ids this user can see once — several+ # entity types (domains, WordPress sites) inherit access from their+ # parent application rather than carrying their own owner column.+ accessible_app_ids = None # None => "not computed / failed"; [] => none++ # --- service / app ---+ try:+ from app.models.application import Application+ q = WorkspaceService.scope_query(+ Application.query, Application, user,+ workspace_id=ws_id, owner_attr='user_id',+ grant_resource_type='application',+ )+ accessible_app_ids = [a.id for a in q.with_entities(Application.id).all()]++ apps = (q.filter(Application.name.ilike(like))+ .order_by(Application.name)+ .limit(PER_TYPE_CAP).all())+ for a in apps:+ rows.append({+ 'type': 'service',+ 'label': a.name,+ 'sublabel': a.app_type or '',+ 'path': f'/services/{a.id}',+ })+ except Exception:+ logger.exception('search: service/app fan-out failed')++ # --- server ---+ try:+ from app.models.server import Server+ q = WorkspaceService.scope_query(+ Server.query, Server, user, workspace_id=ws_id, owner_attr=None,+ )+ from app import db+ servers = (q.filter(db.or_(+ Server.name.ilike(like),+ Server.hostname.ilike(like),+ Server.ip_address.ilike(like),+ ))+ .order_by(Server.name)+ .limit(PER_TYPE_CAP).all())+ for s in servers:+ rows.append({+ 'type': 'server',+ 'label': s.name or s.hostname or '',+ 'sublabel': s.ip_address or s.hostname or '',+ 'path': f'/servers/{s.id}',+ })+ except Exception:+ logger.exception('search: server fan-out failed')++ # --- domain (inherits access from parent Application) ---+ try:+ if accessible_app_ids:+ from app.models.domain import Domain+ domains = (Domain.query+ .filter(Domain.application_id.in_(accessible_app_ids),+ Domain.name.ilike(like))+ .order_by(Domain.name)+ .limit(PER_TYPE_CAP).all())+ for d in domains:+ rows.append({+ 'type': 'domain',+ 'label': d.name,+ 'sublabel': '',+ 'path': '/domains',+ })+ except Exception:+ logger.exception('search: domain fan-out failed')++ # --- database (workspace-filtered via the service) ---+ try:+ from app.services.managed_database_service import ManagedDatabaseService+ matched = 0+ for mdb in ManagedDatabaseService.list(workspace_id=ws_id):+ if matched >= PER_TYPE_CAP:+ break+ haystack = ' '.join(filter(None, [mdb.name, mdb.engine, mdb.host])).lower()+ if needle in haystack:+ rows.append({+ 'type': 'database',+ 'label': mdb.name,+ 'sublabel': mdb.engine or '',+ 'path': '/databases',+ })+ matched += 1+ except Exception:+ logger.exception('search: database fan-out failed')++ # --- site (WordPress, inherits access from parent Application) ---+ try:+ if accessible_app_ids:+ from app.models.wordpress_site import WordPressSite+ from app.models.application import Application+ from app import db+ sites = (WordPressSite.query+ .join(Application, Application.id == WordPressSite.application_id)+ .filter(WordPressSite.application_id.in_(accessible_app_ids),+ db.or_(+ Application.name.ilike(like),+ WordPressSite.admin_email.ilike(like),+ ))+ .order_by(Application.name)+ .limit(PER_TYPE_CAP).all())+ for site in sites:+ parent = site.application+ rows.append({+ 'type': 'site',+ 'label': parent.name if parent else f'site #{site.id}',+ 'sublabel': 'WordPress',+ 'path': f'/services/{site.application_id}',+ })+ except Exception:+ logger.exception('search: site fan-out failed')++ # --- cron (admin-only system surface) ---+ try:+ if getattr(user, 'is_admin', False):+ from app.services.cron_service import CronService+ jobs = (CronService.list_jobs() or {}).get('jobs', [])+ matched = 0+ for job in jobs:+ if matched >= PER_TYPE_CAP:+ break+ name = job.get('name') or ''+ command = job.get('command') or ''+ haystack = ' '.join(filter(None, [+ name, job.get('description') or '', command,+ ])).lower()+ if needle in haystack:+ rows.append({+ 'type': 'cron',+ 'label': name or command,+ 'sublabel': job.get('schedule') or '',+ 'path': '/cron',+ })+ matched += 1+ except Exception:+ logger.exception('search: cron fan-out failed')++ # --- extension (any authenticated user may list) ---+ try:+ from app.models.plugin import InstalledPlugin+ from app import db+ plugins = (InstalledPlugin.query+ .filter(db.or_(+ InstalledPlugin.name.ilike(like),+ InstalledPlugin.display_name.ilike(like),+ InstalledPlugin.slug.ilike(like),+ InstalledPlugin.description.ilike(like),+ ))+ .order_by(InstalledPlugin.display_name)+ .limit(PER_TYPE_CAP).all())+ for p in plugins:+ rows.append({+ 'type': 'extension',+ 'label': p.display_name or p.name,+ 'sublabel': p.author or 'Extension',+ 'path': '/marketplace',+ })+ except Exception:+ logger.exception('search: extension fan-out failed')++ # --- vault (NAMES ONLY — never expose secret values) ---+ try:+ from app.models.secret_vault import SecretVault+ from app import db+ q = SecretVault.query+ if ws_id is not None:+ q = q.filter(SecretVault.workspace_id == ws_id)+ vaults = (q.filter(db.or_(+ SecretVault.name.ilike(like),+ SecretVault.slug.ilike(like),+ SecretVault.description.ilike(like),+ ))+ .order_by(SecretVault.name)+ .limit(PER_TYPE_CAP).all())+ for v in vaults:+ rows.append({+ 'type': 'vault',+ 'label': v.name,+ 'sublabel': v.description or 'Vault',+ 'path': '/vaults',+ })+ except Exception:+ logger.exception('search: vault fan-out failed')++ return rowsdiff --git a/backend/tests/test_search.py b/backend/tests/test_search.pynew file mode 100644index 00000000..58f5da1c--- /dev/null+++ b/backend/tests/test_search.py@@ -0,0 +1,165 @@+"""Tests for the unified entity omnisearch endpoint (plan 41, Phase 4).++Proves the /api/v1/search contract: response shape, the 2-char minimum, the+per-type cap, authz-aware fan-out (a member can't see another user's app; cron+is admin-only), and that vault rows never leak secret values.+"""+import pytest+from werkzeug.security import generate_password_hash+from flask_jwt_extended import create_access_token+++def _mk_user(db, username, role='developer'):+ from app.models import User+ u = User(email=f'{username}@t.local', username=username,+ password_hash=generate_password_hash('x'), role=role, is_active=True)+ db.session.add(u)+ db.session.commit()+ return u+++def _headers(user_id):+ return {'Authorization': f'Bearer {create_access_token(identity=user_id)}'}+++def personas(app):+ """An admin, a developer 'owner', and a foreign developer, plus one app the+ owner owns."""+ from types import SimpleNamespace+ from app import db+ from app.models.application import Application++ admin = _mk_user(db, 'srch_admin', role='admin')+ owner = _mk_user(db, 'srch_owner')+ foreign = _mk_user(db, 'srch_foreign')++ a = Application(name='SecretProjectOne', app_type='php', user_id=owner.id,+ root_path='/srv/secretprojectone')+ db.session.add(a)+ db.session.commit()++ return SimpleNamespace(+ admin=_headers(admin.id),+ owner=_headers(owner.id),+ foreign=_headers(foreign.id),+ app_id=a.id,+ )+++def test_shape(client, personas):+ """Response has a results list and each row carries type/label/sublabel/path."""+ r = client.get('/api/v1/search?q=SecretProject', headers=personas.owner)+ assert r.status_code == 200+ body = r.get_json()+ assert 'results' in body and isinstance(body['results'], list)+ assert len(body['results']) >= 1+ for row in body['results']:+ assert set(['type', 'label', 'sublabel', 'path']).issubset(row.keys())++ svc = [row for row in body['results'] if row['type'] == 'service']+ assert any(row['label'] == 'SecretProjectOne' for row in svc)+ assert svc[0]['path'] == f'/services/{personas.app_id}'+++def test_min_length_returns_empty(client, personas):+ """A term shorter than 2 chars returns an empty result set (200)."""+ r = client.get('/api/v1/search?q=a', headers=personas.owner)+ assert r.status_code == 200+ assert r.get_json() == {'results': []}++ # Missing q behaves the same.+ r2 = client.get('/api/v1/search', headers=personas.owner)+ assert r2.status_code == 200+ assert r2.get_json() == {'results': []}+++def test_per_type_cap(client, personas):+ """More than 5 matching apps yields at most 5 service rows."""+ from app import db+ from app.models import User+ from app.models.application import Application++ # Reuse the admin as owner so an admin search sees all 7 matches.+ admin = User.query.filter_by(username='srch_admin').first()+ for i in range(7):+ db.session.add(Application(name=f'CapApp{i}', app_type='php',+ user_id=admin.id, root_path=f'/srv/capapp{i}'))+ db.session.commit()++ r = client.get('/api/v1/search?q=CapApp', headers=personas.admin)+ assert r.status_code == 200+ service_rows = [row for row in r.get_json()['results'] if row['type'] == 'service']+ assert len(service_rows) == 5+++def test_member_cannot_see_foreign_app_but_admin_can(client, personas):+ """A non-owner developer does NOT see another user's app; an admin does."""+ # Foreign developer: no ownership, no grant -> no service row.+ r_foreign = client.get('/api/v1/search?q=SecretProject', headers=personas.foreign)+ assert r_foreign.status_code == 200+ foreign_services = [row for row in r_foreign.get_json()['results']+ if row['type'] == 'service']+ assert foreign_services == []++ # Admin bypasses ownership -> sees it.+ r_admin = client.get('/api/v1/search?q=SecretProject', headers=personas.admin)+ admin_services = [row for row in r_admin.get_json()['results']+ if row['type'] == 'service']+ assert any(row['label'] == 'SecretProjectOne' for row in admin_services)+++def test_cron_admin_only(client, personas, monkeypatch):+ """Cron rows appear for admins but never for members."""+ from app.services import cron_service++ monkeypatch.setattr(+ cron_service.CronService, 'list_jobs',+ classmethod(lambda cls: {'jobs': [{+ 'name': 'NightlyBackupTask',+ 'description': 'runs a NightlyBackupTask',+ 'command': '/usr/bin/backup.sh',+ 'schedule': '0 3 * * *',+ }]}),+ )++ r_admin = client.get('/api/v1/search?q=NightlyBackup', headers=personas.admin)+ admin_cron = [row for row in r_admin.get_json()['results'] if row['type'] == 'cron']+ assert len(admin_cron) == 1+ assert admin_cron[0]['label'] == 'NightlyBackupTask'+ assert admin_cron[0]['sublabel'] == '0 3 * * *'++ r_member = client.get('/api/v1/search?q=NightlyBackup', headers=personas.owner)+ member_cron = [row for row in r_member.get_json()['results'] if row['type'] == 'cron']+ assert member_cron == []+++def test_vault_names_only_never_leaks_secret(client, personas):+ """A vault row exposes only name/slug/description-derived fields — never the+ stored secret value."""+ from app import db+ from app.models.secret_vault import SecretVault, Secret+ from app.utils.crypto import encrypt_secret++ vault = SecretVault(name='ProdVaultAlpha', slug='prod-vault-alpha',+ description='production secrets')+ db.session.add(vault)+ db.session.commit()++ leak_marker = 'SUPERSECRETVALUE-DO-NOT-LEAK-12345'+ secret = Secret(vault_id=vault.id, name='API_KEY',+ encrypted_value=encrypt_secret(leak_marker))+ db.session.add(secret)+ db.session.commit()++ r = client.get('/api/v1/search?q=ProdVaultAlpha', headers=personas.admin)+ assert r.status_code == 200+ body = r.get_json()++ vault_rows = [row for row in body['results'] if row['type'] == 'vault']+ assert len(vault_rows) == 1+ assert vault_rows[0]['label'] == 'ProdVaultAlpha'++ # The secret value must not appear anywhere in the serialized response.+ import json+ assert leak_marker not in json.dumps(body)diff --git a/frontend/src/services/api/index.js b/frontend/src/services/api/index.jsindex 19920693..c2868e71 100644--- a/frontend/src/services/api/index.js+++ b/frontend/src/services/api/index.js@@ -42,6 +42,7 @@ import * as htaccessToolMethods from './htaccessTools.js';import * as manifestMethods from './manifests.js';import * as surveyMethods from './survey.js';import * as dnsCutoverMethods from './dnsCutover.js';+import * as searchMethods from './search.js';class ApiService extends ApiClient {constructor() {@@ -91,6 +92,7 @@ class ApiService extends ApiClient {manifestMethods,surveyMethods,dnsCutoverMethods,+ searchMethods,];for (const mod of modules) {for (const [key, fn] of Object.entries(mod)) {diff --git a/frontend/src/services/api/search.js b/frontend/src/services/api/search.jsnew file mode 100644index 00000000..d74a3def--- /dev/null+++ b/frontend/src/services/api/search.js@@ -0,0 +1,4 @@+// Unified entity omnisearch (plan 41, Phase 4).+export async function search(q) {+ return this.request(`/search?q=${encodeURIComponent(q)}`);+}