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(search): add resource picker contract

Juan Denisee152eb1bd67
diff --git a/backend/app/api/schemas/search.py b/backend/app/api/schemas/search.py
index 851d38c8..6b187993 100644
--- a/backend/app/api/schemas/search.py
+++ b/backend/app/api/schemas/search.py
@@ -1,6 +1,6 @@
"""Contracts for the unified entity search endpoint."""
-from marshmallow import fields, post_load
+from marshmallow import fields, post_load, validate
from app.api.contracts import ApiSchema
@@ -8,24 +8,61 @@ from app.api.contracts import ApiSchema
class SearchQuerySchema(ApiSchema):
q = fields.String(load_default='')
workspace_id = fields.String(load_default=None, allow_none=True)
+ project_id = fields.Integer(load_default=None, allow_none=True)
+ environment_id = fields.Integer(load_default=None, allow_none=True)
+ types = fields.String(load_default=None, allow_none=True)
+ capabilities = fields.String(load_default=None, allow_none=True)
+ cursor = fields.String(
+ load_default=None,
+ allow_none=True,
+ validate=validate.Length(max=256),
+ )
+ limit = fields.Integer(
+ load_default=None,
+ allow_none=True,
+ validate=validate.Range(min=1, max=100),
+ )
@post_load
def normalize(self, data, **_kwargs):
data['q'] = data['q'].strip()
if data.get('workspace_id') is not None:
data['workspace_id'] = data['workspace_id'].strip() or None
+ for key in ('types', 'capabilities'):
+ raw = data.get(key)
+ if raw is None:
+ continue
+ values = []
+ for value in raw.split(','):
+ value = value.strip()
+ if value and value not in values:
+ values.append(value)
+ data[key] = values or None
+ if data.get('cursor') is not None:
+ data['cursor'] = data['cursor'].strip() or None
return data
+class SearchScopeSchema(ApiSchema):
+ workspace_id = fields.Integer(required=False, allow_none=True)
+ project_id = fields.Integer(required=False, allow_none=True)
+ environment_id = fields.Integer(required=False, allow_none=True)
+
+
class SearchResultSchema(ApiSchema):
type = fields.String(required=True)
+ id = fields.String(required=True)
label = fields.String(required=True)
sublabel = fields.String(required=True)
path = fields.String(required=True)
+ scope = fields.Nested(SearchScopeSchema, required=True)
+ status = fields.String(required=False, allow_none=True)
+ capabilities = fields.List(fields.String(), required=True)
class ListMetaSchema(ApiSchema):
total = fields.Integer(required=True)
+ next_cursor = fields.String(required=False, allow_none=True)
class SearchResponseSchema(ApiSchema):
diff --git a/backend/app/api/search.py b/backend/app/api/search.py
index 41dd3ff2..a05ae82c 100644
--- a/backend/app/api/search.py
+++ b/backend/app/api/search.py
@@ -6,27 +6,46 @@ 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
-from flask_jwt_extended import jwt_required
-
from app.api.contracts import api_contract
from app.api.responses import list_response
from app.api.schemas.search import SearchQuerySchema, SearchResponseSchema
from app.services.search_service import SearchService
-from app.middleware.rbac import get_current_user
+from app.middleware.rbac import auth_required, get_current_user
search_bp = Blueprint('search', __name__)
@search_bp.route('', methods=['GET'])
-@jwt_required()
+@auth_required()
@api_contract(query=SearchQuerySchema, responses={200: SearchResponseSchema})
def search(query):
- """Search entities by name. ``q`` terms shorter than two chars return none."""
+ """Search accessible resources without making the palette a second API."""
q = query['q']
- if len(q) < 2:
+ extended = any(query.get(key) is not None for key in (
+ 'types', 'project_id', 'environment_id', 'capabilities', 'cursor', 'limit',
+ ))
+ if len(q) < 2 and not query.get('types'):
return list_response([], legacy_key='results')
user = get_current_user()
workspace = request.headers.get('X-Workspace-Id') or query['workspace_id']
- rows = SearchService.search(user, q, workspace)
- return list_response(rows, legacy_key='results')
+ if not extended:
+ rows = SearchService.search(user, q, workspace)
+ return list_response(rows, legacy_key='results')
+
+ page = SearchService.search_page(
+ user,
+ q,
+ workspace,
+ types=query.get('types'),
+ project_id=query.get('project_id'),
+ environment_id=query.get('environment_id'),
+ capabilities=query.get('capabilities'),
+ cursor=query.get('cursor'),
+ limit=query.get('limit'),
+ )
+ return list_response(
+ page.rows,
+ meta={'next_cursor': page.next_cursor},
+ legacy_key='results',
+ )
diff --git a/backend/app/services/search_provider_registry.py b/backend/app/services/search_provider_registry.py
index ffa8d9cc..afe5b7ba 100644
--- a/backend/app/services/search_provider_registry.py
+++ b/backend/app/services/search_provider_registry.py
@@ -31,8 +31,8 @@ _PROVIDERS = {}
# The core entity types, reserved so a plugin cannot impersonate one — rows
# tagged 'service' or 'vault' are trusted to have been scoped by core.
-CORE_TYPES = ('service', 'server', 'domain', 'database', 'site', 'cron',
- 'extension', 'vault')
+CORE_TYPES = ('service', 'server', 'project', 'environment', 'domain',
+ 'database', 'site', 'cron', 'extension', 'vault')
@dataclass(frozen=True)
@@ -47,6 +47,9 @@ class SearchQuery:
term: str
user: Any = None
workspace_id: Optional[int] = None
+ project_id: Optional[int] = None
+ environment_id: Optional[int] = None
+ capabilities: tuple[str, ...] = ()
limit: int = 5
@@ -112,11 +115,43 @@ def clean_rows(entity_type: str, rows, limit: int):
logger.warning('search: %s dropped a row with off-site path %r',
entity_type, path)
continue
+ raw_scope = row.get('scope') if isinstance(row.get('scope'), dict) else {}
+ scope = {}
+ invalid_scope = False
+ for key in ('workspace_id', 'project_id', 'environment_id'):
+ value = raw_scope.get(key)
+ if value in (None, ''):
+ scope[key] = None
+ continue
+ try:
+ scope[key] = int(value)
+ except (TypeError, ValueError):
+ invalid_scope = True
+ break
+ if invalid_scope:
+ logger.warning('search: %s dropped a row with invalid scope', entity_type)
+ continue
+ capabilities = row.get('capabilities') or []
+ if not isinstance(capabilities, (list, tuple, set)):
+ logger.warning('search: %s dropped a row with invalid capabilities', entity_type)
+ continue
+ capabilities = sorted({
+ str(capability).strip() for capability in capabilities
+ if str(capability).strip()
+ })
+ stable_id = str(row.get('id') or path).strip()
cleaned.append({
'type': entity_type,
+ # Path fallback keeps existing extension providers compatible.
+ # New providers must return a domain id so identity survives moves.
+ 'id': stable_id,
'label': label,
'sublabel': str(row.get('sublabel') or ''),
'path': path,
+ 'scope': scope,
+ 'status': (str(row['status']).strip()
+ if row.get('status') is not None else None),
+ 'capabilities': capabilities,
})
return cleaned
diff --git a/backend/app/services/search_service.py b/backend/app/services/search_service.py
index d6278e6f..e44e68a3 100644
--- a/backend/app/services/search_service.py
+++ b/backend/app/services/search_service.py
@@ -12,11 +12,25 @@ Design rules:
(missing table, migration skew, service error) degrades to "no rows of that
type" instead of 500-ing the whole search.
"""
+import base64
+import binascii
import logging
+from dataclasses import dataclass
+
+from app.exceptions import ValidationError
logger = logging.getLogger(__name__)
PER_TYPE_CAP = 5
+DEFAULT_PAGE_SIZE = 20
+MAX_PAGE_SIZE = 100
+MAX_CURSOR_OFFSET = 10_000
+
+
+@dataclass(frozen=True)
+class SearchPage:
+ rows: list[dict]
+ next_cursor: str | None
class SearchService:
@@ -30,14 +44,82 @@ class SearchService:
already trimmed and >= 2 chars by the route; we still guard here so the
service is safe to call directly.
"""
+ return SearchService._search_rows(user, term, workspace_header)
+
+ @staticmethod
+ def search_page(user, term, workspace_header=None, *, types=None,
+ project_id=None, environment_id=None, capabilities=None,
+ cursor=None, limit=None):
+ """Return one cursor page of ResourceRef-shaped search results.
+
+ The palette continues to call :meth:`search`, retaining its five rows
+ per type. Resource pickers opt into this contract with ``types`` and a
+ global page size.
+ """
+ page_size = limit or DEFAULT_PAGE_SIZE
+ offset = SearchService._decode_cursor(cursor)
+ fetch_cap = min(MAX_CURSOR_OFFSET + 1, offset + page_size + 1)
+ rows = SearchService._search_rows(
+ user,
+ term,
+ workspace_header,
+ types=types,
+ project_id=project_id,
+ environment_id=environment_id,
+ capabilities=capabilities,
+ per_type_cap=fetch_cap,
+ strict_scope=True,
+ )
+ page_rows = rows[offset:offset + page_size]
+ next_offset = offset + len(page_rows)
+ next_cursor = (
+ SearchService._encode_cursor(next_offset)
+ if next_offset < len(rows) else None
+ )
+ return SearchPage(page_rows, next_cursor)
+
+ @staticmethod
+ def _encode_cursor(offset):
+ raw = f'v1:{offset}'.encode('ascii')
+ return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
+
+ @staticmethod
+ def _decode_cursor(cursor):
+ if not cursor:
+ return 0
+ try:
+ encoded = cursor.encode('ascii')
+ encoded += b'=' * (-len(encoded) % 4)
+ version, raw_offset = base64.urlsafe_b64decode(encoded).decode('ascii').split(':', 1)
+ offset = int(raw_offset)
+ if version != 'v1' or offset < 0 or offset > MAX_CURSOR_OFFSET:
+ raise ValueError
+ return offset
+ except (binascii.Error, UnicodeError, ValueError, TypeError):
+ raise ValidationError('Invalid search cursor', code='invalid_cursor')
+
+ @staticmethod
+ def _search_rows(user, term, workspace_header=None, *, types=None,
+ project_id=None, environment_id=None, capabilities=None,
+ per_type_cap=PER_TYPE_CAP, strict_scope=False):
+ """Build accessible ResourceRef rows before global cursor slicing."""
if user is None:
return []
term = (term or '').strip()
- if len(term) < 2:
+ requested_types = set(types or [])
+ if len(term) < 2 and not requested_types:
return []
from app.services.workspace_service import WorkspaceService
ws_id = WorkspaceService.resolve_workspace_id(user, workspace_header)
+ if (strict_scope and workspace_header not in (None, '', 'all')
+ and ws_id is None):
+ return []
+
+ required_capabilities = set(capabilities or [])
+
+ def includes(entity_type):
+ return not requested_types or entity_type in requested_types
like = f'%{term}%'
needle = term.lower()
@@ -50,6 +132,8 @@ class SearchService:
# --- service / app ---
try:
+ if not any(includes(kind) for kind in ('service', 'domain', 'site')):
+ raise StopIteration
from app.models.application import Application
# Deleted apps are not findable: the recycle bin is where they
# live now, and this id list also scopes the domain/backup
@@ -59,86 +143,192 @@ class SearchService:
workspace_id=ws_id, owner_attr='user_id',
grant_resource_type='application',
)
+ if project_id is not None:
+ q = q.filter(Application.project_id == project_id)
+ if environment_id is not None:
+ q = q.filter(Application.environment_id == environment_id)
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}',
- })
+ if includes('service') and not required_capabilities:
+ apps = (q.filter(Application.name.ilike(like))
+ .order_by(Application.name)
+ .limit(per_type_cap).all())
+ for a in apps:
+ rows.append({
+ 'type': 'service',
+ 'id': str(a.id),
+ 'label': a.name,
+ 'sublabel': a.app_type or '',
+ 'path': f'/services/{a.id}',
+ 'scope': SearchService._scope(a),
+ 'status': a.status,
+ 'capabilities': [],
+ })
+ except StopIteration:
+ pass
except Exception:
logger.exception('search: service/app fan-out failed')
# --- server ---
try:
+ if not includes('server') or project_id is not None or environment_id is not None:
+ raise StopIteration
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
+ server_query_limit = (MAX_CURSOR_OFFSET + 1
+ if required_capabilities else per_type_cap)
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())
+ .limit(server_query_limit).all())
for s in servers:
+ server_capabilities = SearchService._server_capabilities(s)
+ if not required_capabilities.issubset(server_capabilities):
+ continue
rows.append({
'type': 'server',
+ 'id': str(s.id),
'label': s.name or s.hostname or '',
'sublabel': s.ip_address or s.hostname or '',
'path': f'/servers/{s.id}',
+ 'scope': SearchService._scope(s),
+ 'status': s.status,
+ 'capabilities': sorted(server_capabilities),
})
+ except StopIteration:
+ pass
except Exception:
logger.exception('search: server fan-out failed')
+ # --- project / environment (access derives from Workspace membership) ---
+ accessible_workspace_ids = SearchService._accessible_workspace_ids(user, ws_id)
+ try:
+ if (not includes('project') or required_capabilities
+ or environment_id is not None):
+ raise StopIteration
+ from app.models.project import Project
+ projects_q = Project.query.filter(Project.workspace_id.in_(accessible_workspace_ids))
+ if project_id is not None:
+ projects_q = projects_q.filter(Project.id == project_id)
+ projects = (projects_q.filter(Project.name.ilike(like))
+ .order_by(Project.name)
+ .limit(per_type_cap).all())
+ for project in projects:
+ rows.append({
+ 'type': 'project',
+ 'id': str(project.id),
+ 'label': project.name,
+ 'sublabel': project.description or '',
+ 'path': f'/projects/{project.id}',
+ 'scope': {
+ 'workspace_id': project.workspace_id,
+ 'project_id': project.id,
+ 'environment_id': None,
+ },
+ 'status': None,
+ 'capabilities': [],
+ })
+ except StopIteration:
+ pass
+ except Exception:
+ logger.exception('search: project fan-out failed')
+
+ try:
+ if not includes('environment') or required_capabilities:
+ raise StopIteration
+ from app.models.environment import Environment
+ from app.models.project import Project
+ environments_q = (Environment.query
+ .join(Project, Project.id == Environment.project_id)
+ .filter(Project.workspace_id.in_(accessible_workspace_ids)))
+ if project_id is not None:
+ environments_q = environments_q.filter(Environment.project_id == project_id)
+ if environment_id is not None:
+ environments_q = environments_q.filter(Environment.id == environment_id)
+ environments = (environments_q.filter(Environment.name.ilike(like))
+ .order_by(Project.name, Environment.order, Environment.id)
+ .limit(per_type_cap).all())
+ for environment in environments:
+ rows.append({
+ 'type': 'environment',
+ 'id': str(environment.id),
+ 'label': environment.name,
+ 'sublabel': environment.project.name if environment.project else '',
+ 'path': f'/projects/{environment.project_id}',
+ 'scope': {
+ 'workspace_id': (environment.project.workspace_id
+ if environment.project else None),
+ 'project_id': environment.project_id,
+ 'environment_id': environment.id,
+ },
+ 'status': None,
+ 'capabilities': [],
+ })
+ except StopIteration:
+ pass
+ except Exception:
+ logger.exception('search: environment fan-out failed')
+
# --- domain (inherits access from parent Application) ---
try:
- if accessible_app_ids:
+ if includes('domain') and not required_capabilities and 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())
+ .limit(per_type_cap).all())
for d in domains:
rows.append({
'type': 'domain',
+ 'id': str(d.id),
'label': d.name,
'sublabel': '',
'path': '/domains',
+ 'scope': SearchService._scope(d.application),
+ 'status': None,
+ 'capabilities': [],
})
except Exception:
logger.exception('search: domain fan-out failed')
# --- database (workspace-filtered via the service) ---
try:
+ if (not includes('database') or required_capabilities
+ or project_id is not None or environment_id is not None):
+ raise StopIteration
from app.services.managed_database_service import ManagedDatabaseService
matched = 0
for mdb in ManagedDatabaseService.list(workspace_id=ws_id):
- if matched >= PER_TYPE_CAP:
+ 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',
+ 'id': str(mdb.id),
'label': mdb.name,
'sublabel': mdb.engine or '',
'path': '/databases',
+ 'scope': SearchService._scope(mdb),
+ 'status': None,
+ 'capabilities': [],
})
matched += 1
+ except StopIteration:
+ pass
except Exception:
logger.exception('search: database fan-out failed')
# --- site (WordPress, inherits access from parent Application) ---
try:
- if accessible_app_ids:
+ if includes('site') and not required_capabilities and accessible_app_ids:
from app.models.wordpress_site import WordPressSite
from app.models.application import Application
from app import db
@@ -150,26 +340,32 @@ class SearchService:
WordPressSite.admin_email.ilike(like),
))
.order_by(Application.name)
- .limit(PER_TYPE_CAP).all())
+ .limit(per_type_cap).all())
for site in sites:
parent = site.application
rows.append({
'type': 'site',
+ 'id': str(site.id),
'label': parent.name if parent else f'site #{site.id}',
'sublabel': 'WordPress',
'path': f'/services/{site.application_id}',
+ 'scope': SearchService._scope(parent),
+ 'status': parent.status if parent else None,
+ 'capabilities': [],
})
except Exception:
logger.exception('search: site fan-out failed')
# --- cron (admin-only system surface) ---
try:
- if getattr(user, 'is_admin', False):
+ if (includes('cron') and not required_capabilities
+ and project_id is None and environment_id is None
+ and 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:
+ if matched >= per_type_cap:
break
name = job.get('name') or ''
command = job.get('command') or ''
@@ -179,9 +375,14 @@ class SearchService:
if needle in haystack:
rows.append({
'type': 'cron',
+ 'id': str(job.get('id') or job.get('job_id') or
+ f"{name}:{job.get('schedule') or ''}:{command}"),
'label': name or command,
'sublabel': job.get('schedule') or '',
'path': '/cron',
+ 'scope': SearchService._empty_scope(),
+ 'status': job.get('status'),
+ 'capabilities': [],
})
matched += 1
except Exception:
@@ -189,6 +390,9 @@ class SearchService:
# --- extension (any authenticated user may list) ---
try:
+ if (not includes('extension') or required_capabilities
+ or project_id is not None or environment_id is not None):
+ raise StopIteration
from app.models.plugin import InstalledPlugin
from app import db
plugins = (InstalledPlugin.query
@@ -199,38 +403,55 @@ class SearchService:
InstalledPlugin.description.ilike(like),
))
.order_by(InstalledPlugin.display_name)
- .limit(PER_TYPE_CAP).all())
+ .limit(per_type_cap).all())
for p in plugins:
rows.append({
'type': 'extension',
+ 'id': str(p.id),
'label': p.display_name or p.name,
'sublabel': p.author or 'Extension',
'path': '/marketplace',
+ 'scope': SearchService._empty_scope(),
+ 'status': p.status,
+ 'capabilities': [],
})
+ except StopIteration:
+ pass
except Exception:
logger.exception('search: extension fan-out failed')
# --- vault (NAMES ONLY — never expose secret values) ---
try:
+ if (not includes('vault') or required_capabilities
+ or project_id is not None or environment_id is not None):
+ raise StopIteration
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)
+ elif not getattr(user, 'is_admin', False):
+ q = q.filter(SecretVault.workspace_id.in_(accessible_workspace_ids))
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())
+ .limit(per_type_cap).all())
for v in vaults:
rows.append({
'type': 'vault',
+ 'id': str(v.id),
'label': v.name,
'sublabel': v.description or 'Vault',
'path': '/vaults',
+ 'scope': SearchService._scope(v),
+ 'status': None,
+ 'capabilities': [],
})
+ except StopIteration:
+ pass
except Exception:
logger.exception('search: vault fan-out failed')
@@ -245,12 +466,68 @@ class SearchService:
logger.exception('search: provider registry unavailable')
contributed = []
for entity_type, provider in contributed:
+ if requested_types and entity_type not in requested_types:
+ continue
try:
query = search_provider_registry.SearchQuery(
- term=term, user=user, workspace_id=ws_id, limit=PER_TYPE_CAP)
- rows.extend(search_provider_registry.clean_rows(
- entity_type, provider(query), PER_TYPE_CAP))
+ term=term,
+ user=user,
+ workspace_id=ws_id,
+ project_id=project_id,
+ environment_id=environment_id,
+ capabilities=tuple(sorted(required_capabilities)),
+ limit=per_type_cap,
+ )
+ provider_rows = search_provider_registry.clean_rows(
+ entity_type, provider(query), per_type_cap)
+ for row in provider_rows:
+ row_scope = row['scope']
+ if (ws_id is not None
+ and row_scope['workspace_id'] != ws_id):
+ continue
+ if project_id is not None and row_scope['project_id'] != project_id:
+ continue
+ if (environment_id is not None
+ and row_scope['environment_id'] != environment_id):
+ continue
+ if not required_capabilities.issubset(row['capabilities']):
+ continue
+ rows.append(row)
except Exception:
logger.exception('search: %s fan-out failed', entity_type)
return rows
+
+ @staticmethod
+ def _empty_scope():
+ return {
+ 'workspace_id': None,
+ 'project_id': None,
+ 'environment_id': None,
+ }
+
+ @staticmethod
+ def _scope(resource):
+ if resource is None:
+ return SearchService._empty_scope()
+ return {
+ 'workspace_id': getattr(resource, 'workspace_id', None),
+ 'project_id': getattr(resource, 'project_id', None),
+ 'environment_id': getattr(resource, 'environment_id', None),
+ }
+
+ @staticmethod
+ def _server_capabilities(server):
+ raw = server.cached_capabilities if isinstance(server.cached_capabilities, dict) else {}
+ return {str(name) for name, enabled in raw.items() if enabled is True}
+
+ @staticmethod
+ def _accessible_workspace_ids(user, workspace_id):
+ if workspace_id is not None:
+ return [workspace_id]
+ from app.services.workspace_service import WorkspaceService
+ if getattr(user, 'is_admin', False):
+ from app.models.workspace import Workspace
+ return [workspace.id for workspace in Workspace.query.all()]
+ return [workspace.id for workspace in
+ WorkspaceService.list_workspaces(user_id=user.id)]
diff --git a/backend/tests/test_plugin_search_sdk.py b/backend/tests/test_plugin_search_sdk.py
index 1a12ee21..e25520d0 100644
--- a/backend/tests/test_plugin_search_sdk.py
+++ b/backend/tests/test_plugin_search_sdk.py
@@ -116,9 +116,20 @@ class TestFanOut:
assert res.status_code == 200
rows = res.get_json()['results']
contributed = [r for r in rows if r['type'] == 'minecraft.world']
- assert contributed == [{'type': 'minecraft.world', 'label': 'Overworld',
- 'sublabel': 'Minecraft world',
- 'path': '/minecraft/worlds/1'}]
+ assert contributed == [{
+ 'type': 'minecraft.world',
+ 'id': '/minecraft/worlds/1',
+ 'label': 'Overworld',
+ 'sublabel': 'Minecraft world',
+ 'path': '/minecraft/worlds/1',
+ 'scope': {
+ 'workspace_id': None,
+ 'project_id': None,
+ 'environment_id': None,
+ },
+ 'status': None,
+ 'capabilities': [],
+ }]
def test_a_broken_provider_does_not_break_search(self, app, client, owner):
def explode(query):
@@ -141,6 +152,9 @@ class TestFanOut:
seen['user_id'] = query.user.id
seen['limit'] = query.limit
seen['workspace_id'] = query.workspace_id
+ seen['project_id'] = query.project_id
+ seen['environment_id'] = query.environment_id
+ seen['capabilities'] = query.capabilities
return []
search_provider_registry.register('demo.capture', capture)
@@ -155,6 +169,9 @@ class TestFanOut:
assert seen['user_id'] == owner['id']
assert seen['limit'] == 5
assert seen['workspace_id'] is None
+ assert seen['project_id'] is None
+ assert seen['environment_id'] is None
+ assert seen['capabilities'] == ()
def test_short_terms_never_reach_providers(self, app, client, owner):
called = []
diff --git a/backend/tests/test_search.py b/backend/tests/test_search.py
index 1343c887..26049315 100644
--- a/backend/tests/test_search.py
+++ b/backend/tests/test_search.py
@@ -29,14 +29,31 @@ def personas(app):
from types import SimpleNamespace
from app import db
from app.models.application import Application
+ from app.models.server import Server
+ from app.services.project_service import ProjectService
+ from app.services.workspace_service import WorkspaceService
admin = _mk_user(db, 'srch_admin', role='admin')
owner = _mk_user(db, 'srch_owner')
foreign = _mk_user(db, 'srch_foreign')
+ workspace = WorkspaceService.create_workspace(
+ {'name': 'Search Owner Workspace'}, owner.id)
+ project = ProjectService.create_project(workspace.id, 'Picker Project')
+ environment = ProjectService.list_environments(project.id)[0]
+
a = Application(name='SecretProjectOne', app_type='php', user_id=owner.id,
- root_path='/srv/secretprojectone')
- db.session.add(a)
+ root_path='/srv/secretprojectone', workspace_id=workspace.id,
+ project_id=project.id, environment_id=environment.id)
+ server = Server(
+ name='PickerFleetNode',
+ hostname='picker-node.local',
+ ip_address='192.0.2.30',
+ workspace_id=workspace.id,
+ status='online',
+ cached_capabilities={'docker': True, 'systemd': True, 'cron': False},
+ )
+ db.session.add_all([a, server])
db.session.commit()
return SimpleNamespace(
@@ -44,6 +61,10 @@ def personas(app):
owner=_headers(owner.id),
foreign=_headers(foreign.id),
app_id=a.id,
+ workspace_id=workspace.id,
+ project_id=project.id,
+ environment_id=environment.id,
+ server_id=server.id,
)
@@ -57,7 +78,10 @@ def test_shape(client, personas):
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())
+ assert {
+ 'type', 'id', 'label', 'sublabel', 'path', 'scope',
+ 'status', 'capabilities',
+ }.issubset(row.keys())
svc = [row for row in body['results'] if row['type'] == 'service']
assert any(row['label'] == 'SecretProjectOne' for row in svc)
@@ -181,3 +205,104 @@ def test_vault_names_only_never_leaks_secret(client, personas):
# The secret value must not appear anywhere in the serialized response.
import json
assert leak_marker not in json.dumps(body)
+
+
+def test_resource_contract_filters_types_scope_and_capabilities(client, personas):
+ response = client.get(
+ '/api/v1/search?q=PickerFleet&types=server&capabilities=docker,systemd&limit=10',
+ headers={**personas.owner, 'X-Workspace-Id': str(personas.workspace_id)},
+ )
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body['meta'] == {'total': 1, 'next_cursor': None}
+ assert body['data'] == [{
+ 'type': 'server',
+ 'id': personas.server_id,
+ 'label': 'PickerFleetNode',
+ 'sublabel': '192.0.2.30',
+ 'path': f'/servers/{personas.server_id}',
+ 'scope': {
+ 'workspace_id': personas.workspace_id,
+ 'project_id': None,
+ 'environment_id': None,
+ },
+ 'status': 'online',
+ 'capabilities': ['docker', 'systemd'],
+ }]
+
+ missing_capability = client.get(
+ '/api/v1/search?q=PickerFleet&types=server&capabilities=cron',
+ headers={**personas.owner, 'X-Workspace-Id': str(personas.workspace_id)},
+ )
+ assert missing_capability.status_code == 200
+ assert missing_capability.get_json()['data'] == []
+
+
+def test_project_environment_filters_and_foreign_workspace_are_sealed(client, personas):
+ projects = client.get(
+ '/api/v1/search?types=project&limit=10',
+ headers={**personas.owner, 'X-Workspace-Id': str(personas.workspace_id)},
+ )
+ assert projects.status_code == 200
+ assert [(row['type'], row['id']) for row in projects.get_json()['data']] == [
+ ('project', str(personas.project_id)),
+ ]
+
+ environments = client.get(
+ f'/api/v1/search?types=environment&project_id={personas.project_id}&limit=10',
+ headers={**personas.owner, 'X-Workspace-Id': str(personas.workspace_id)},
+ )
+ assert environments.status_code == 200
+ assert [row['id'] for row in environments.get_json()['data']] == [
+ str(personas.environment_id),
+ ]
+ assert environments.get_json()['data'][0]['scope'] == {
+ 'workspace_id': personas.workspace_id,
+ 'project_id': personas.project_id,
+ 'environment_id': personas.environment_id,
+ }
+
+ foreign = client.get(
+ '/api/v1/search?types=project&limit=10',
+ headers={**personas.foreign, 'X-Workspace-Id': str(personas.workspace_id)},
+ )
+ assert foreign.status_code == 200
+ assert foreign.get_json()['data'] == []
+
+
+def test_resource_search_cursor_pages_are_stable(client, personas):
+ from app.services.project_service import ProjectService
+
+ for name in ('Picker Alpha', 'Picker Beta', 'Picker Gamma'):
+ ProjectService.create_project(personas.workspace_id, name)
+
+ first = client.get(
+ '/api/v1/search?q=Picker&types=project&limit=2',
+ headers={**personas.owner, 'X-Workspace-Id': str(personas.workspace_id)},
+ )
+ assert first.status_code == 200
+ first_body = first.get_json()
+ assert len(first_body['data']) == 2
+ assert first_body['meta']['next_cursor']
+
+ second = client.get(
+ f"/api/v1/search?q=Picker&types=project&limit=2&cursor={first_body['meta']['next_cursor']}",
+ headers={**personas.owner, 'X-Workspace-Id': str(personas.workspace_id)},
+ )
+ assert second.status_code == 200
+ second_body = second.get_json()
+ assert len(second_body['data']) == 2
+ assert {row['id'] for row in first_body['data']}.isdisjoint(
+ row['id'] for row in second_body['data'])
+ assert second_body['meta']['next_cursor'] is None
+
+
+def test_invalid_resource_search_cursor_is_typed(client, personas):
+ response = client.get(
+ '/api/v1/search?q=Picker&types=project&cursor=not-a-cursor',
+ headers=personas.owner,
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()['code'] == 'invalid_cursor'