Merge pull request #201 from jhd3197/dev

Release: agent permissions, mobile UX improvements, and security hardening
This commit is contained in:
Juan Denis authored and GitHub committed 2026-11-14 02:46:59 -05:00
commit b10e220300
489 files changed
+14985 -9234

No files matched your search

+12 -8
View File
@@ -13,11 +13,15 @@ on:
branches: [dev]
paths:
- 'backend/**'
- 'docs/MIGRATION_INVENTORY.md'
- 'scripts/generate-migration-inventory.py'
- '.github/workflows/backend-ci.yml'
pull_request:
branches: [main, dev]
paths:
- 'backend/**'
- 'docs/MIGRATION_INVENTORY.md'
- 'scripts/generate-migration-inventory.py'
- '.github/workflows/backend-ci.yml'
workflow_call:
@@ -29,8 +33,8 @@ jobs:
name: test-count ratchet
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.11'
cache: pip
@@ -82,8 +86,8 @@ jobs:
matrix:
group: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.11'
cache: pip
@@ -115,8 +119,8 @@ jobs:
name: real binaries
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.11'
cache: pip
@@ -149,8 +153,8 @@ jobs:
name: docker builds
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.11'
cache: pip
@@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Run exact and proxy image probes
run: >-
@@ -35,7 +35,7 @@ jobs:
- name: Upload detailed evidence
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: distro-compatibility-report
path: scripts/test/output/distro-compatibility/
+2 -2
View File
@@ -28,8 +28,8 @@ jobs:
name: builtin frontend drift check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: '22'
- name: Check builtin-extension frontends are in sync
+6 -3
View File
@@ -29,8 +29,8 @@ jobs:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: '22'
cache: npm
@@ -89,9 +89,12 @@ jobs:
- name: Assistant deployment browser regressions
working-directory: frontend
run: npm run test:ai-operations
- name: Layout screenshot regressions
working-directory: frontend
run: npm run test:layout
- name: Upload Settings screenshots
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: settings-browser-screenshots
path: frontend/test-results/
+2 -2
View File
@@ -38,8 +38,8 @@ jobs:
measurements:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.11'
- name: Test measurement tools (stdlib only)
+7 -7
View File
@@ -54,7 +54,7 @@ jobs:
dev_tag: ${{ steps.dev.outputs.tag }}
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
persist-credentials: false
@@ -73,7 +73,7 @@ jobs:
echo "Dev build: v$version"
- name: Set up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v7
with:
node-version: '22'
@@ -89,7 +89,7 @@ jobs:
- name: Save the dev release files
if: github.event_name == 'push'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: dev-release
path: |
@@ -108,7 +108,7 @@ jobs:
steps:
# No checkout or repository scripts run with the write token.
- name: Download the built release files
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
name: dev-release
@@ -157,13 +157,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Build image (amd64)
uses: docker/build-push-action@v5
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64
+12 -12
View File
@@ -77,7 +77,7 @@ jobs:
tag: ${{ steps.version.outputs.tag }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
fetch-depth: 0
@@ -130,10 +130,10 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Set up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v7
with:
node-version: '22'
@@ -148,7 +148,7 @@ jobs:
run: bash scripts/build-release.sh
- name: Upload release artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: serverkit-release-${{ matrix.arch }}
path: |
@@ -163,16 +163,16 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v3
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -186,7 +186,7 @@ jobs:
# catches that. The layers are cached, so the multi-arch push below reuses
# this build rather than repeating it.
- name: Build amd64 image for smoke test
uses: docker/build-push-action@v5
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64
@@ -204,7 +204,7 @@ jobs:
run: SKIP_BUILD=1 bash scripts/test/smoke-docker-image.sh serverkit:smoke
- name: Build and push Docker image
uses: docker/build-push-action@v5
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64,linux/arm64
@@ -227,10 +227,10 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Download release artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v8
with:
path: release-artifacts
pattern: serverkit-release-*
+7 -7
View File
@@ -44,7 +44,7 @@ jobs:
name: lint + unit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Syntax check (bash -n)
run: |
@@ -123,7 +123,7 @@ jobs:
- 'fedora:40'
- 'opensuse/leap:15.5'
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Pull ${{ matrix.image }} (Docker Hub, then mirror)
env:
@@ -209,7 +209,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Run probe matrix
run: bash scripts/test/probe-matrix.sh
@@ -241,7 +241,7 @@ jobs:
- 'fedora:40'
- 'opensuse/leap:15.5'
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: provision_python on ${{ matrix.image }}
run: |
@@ -265,7 +265,7 @@ jobs:
# fails here instead of on someone's Pi. Real-hardware validation (GPIO,
# SD-card I/O, 32-bit ARM) still needs a physical device.
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: bash -n + unit suites on arm64
run: |
set -e
@@ -294,7 +294,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install ServerKit (non-interactive, no domain, plain HTTP)
run: |
@@ -380,7 +380,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: ShellCheck --enable=all (advisory — never fails the build)
continue-on-error: true
+4 -4
View File
@@ -43,7 +43,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Verify the agent release chain
run: bash scripts/test/verify-agent-release-chain.sh
@@ -63,10 +63,10 @@ jobs:
timeout-minutes: 45
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Set up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v7
with:
node-version: '22'
@@ -143,7 +143,7 @@ jobs:
timeout-minutes: 60
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Install the latest published release (baseline)
id: baseline
+8 -8
View File
@@ -37,9 +37,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- uses: actions/setup-python@v5
- uses: actions/setup-python@v7
with:
python-version: '3.11'
@@ -54,7 +54,7 @@ jobs:
- name: Upload full Bandit report
if: always()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: bandit-report
path: bandit-report.json
@@ -76,9 +76,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- uses: actions/setup-python@v5
- uses: actions/setup-python@v7
with:
python-version: '3.11'
@@ -105,8 +105,8 @@ jobs:
name: Frontend Production Dependency Scan
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: '22'
cache: npm
@@ -133,7 +133,7 @@ jobs:
continue-on-error: true
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Run Safety CLI to check for vulnerabilities
continue-on-error: true
+3 -3
View File
@@ -56,7 +56,7 @@ jobs:
DEBIAN_FRONTEND: noninteractive
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install Python & pytest
shell: bash
@@ -86,10 +86,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v7
with:
python-version: '3.11'
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
+4
View File
@@ -132,6 +132,10 @@ SECURITY_AND_CODE_AUDIT.md
!/docs/screenshots/
!/docs/screenshots/*.png
# Layout screenshot baselines compared by `npm run test:layout`.
!/frontend/tests/layout-baselines/
!/frontend/tests/layout-baselines/*.png
# Video walkthrough thumbnails linked from the README.
!/docs/videos/*.png
+9
View File
@@ -22,6 +22,15 @@ release history; historical `agent-v*` tags are not panel releases.
### Added
- Agent permission levels (Monitor / Protect / Full), enforced by the agent and
reported to the panel. Adds a signed `POST /api/v1/agent/report` endpoint for
report-only Monitor agents, per-server level and service-check state (server
list badge and health, server detail panel), offline / service-down alerts
through the existing fleet alerts and notification channels, audited level
changes, and a panel-side command gate. The panel cannot set the level; it is
changed on the server with `serverkit-agent permissions set`. See
[docs/AGENT_PERMISSION_LEVELS.md](docs/AGENT_PERMISSION_LEVELS.md). Migration
112. The Add Server commands now pass `--level` / `-Level`.
- `GET /api/v1/servers` now accepts an API key (`X-API-Key`) carrying the
`servers:read` scope, in addition to the usual JWT, so external tools can
poll the server list read-only without a short-lived token. JWT callers are
+2 -2
View File
@@ -71,7 +71,7 @@ RUN pip install --no-cache-dir --upgrade pip \
# surfaces as a failed image build, never as a half-installed panel on a host.
#
# 1. Bundled test suites. Third-party packages ship their own pytest trees
# (passlib is the big one) that no running panel imports.
# that no running panel imports.
# 2. botocore API models. botocore carries JSON models for 400+ AWS services
# (~15 MB); ServerKit constructs exactly three clients — s3
# (storage_provider_service), route53 (dns_provider_service) and ses
@@ -190,4 +190,4 @@ WORKDIR /app/backend
# Single process (agent gateway state is in-memory) + threads: the app runs
# async_mode='threading' (simple-websocket serves WS); a gevent-websocket
# worker would double-answer the upgrade handshake and break WebSocket.
CMD ["sh", "-c", "exec gunicorn --workers 1 --threads 100 --bind 0.0.0.0:${SERVERKIT_BACKEND_PORT:-5000} --timeout 120 --access-logfile - --error-logfile - run:app"]
CMD ["sh", "-c", "exec gunicorn --workers 1 --threads ${SERVERKIT_THREADS:-100} --bind 0.0.0.0:${SERVERKIT_BACKEND_PORT:-5000} --timeout 120 --access-logfile - --error-logfile - run:app"]
+15 -2
View File
@@ -7,8 +7,8 @@ release line and the `main` branch.
| Version | Supported |
|---------|-----------|
| 1.7.x | ✅ |
| < 1.7 | ❌ (please upgrade) |
| 1.11.x | ✅ |
| < 1.11 | ❌ (please upgrade) |
The **agent** ships from its own repository, `jhd3197/serverkit-agent`, and is
versioned independently (`vX.Y.Z` — it used `agent-vX.Y.Z` while it lived in this
@@ -47,6 +47,12 @@ trust boundaries:
(`system:exec`) and interactive PTY sessions are controlled by the agent's
`Features.Exec` flag, which is **off by default**. Enable it only on servers
where you intend the panel to run shell commands.
- **Permission levels bound what a compromised panel can do.** An agent runs as
Monitor (report-only, no inbound command channel), Protect (security allowlist
only) or Full. The level is read only from the agent's local config and can
only be changed on the server (`serverkit-agent permissions set`); the panel
records and audits the reported level but has no API to set it. See
[docs/AGENT_PERMISSION_LEVELS.md](docs/AGENT_PERMISSION_LEVELS.md).
- **Transport & connection controls.** Agents authenticate to the panel with
per-connection HMAC-SHA256 (with nonce/replay protection and a timestamp-skew
check), and the panel enforces a per-server IP allowlist. Use `wss://`
@@ -137,6 +143,13 @@ carry a `sink-safe: <sanitizer> — <why>` comment. `scripts/check-html-sinks.mj
fails CI on any new unannotated sink, so a raw-HTML injection point can't land
silently.
## Known Limitations
- **Tokens in `localStorage`.** The SPA keeps its JWT access/refresh tokens in
`localStorage`, so an XSS bug would expose them. The production CSP now
forbids inline and `eval` scripts (`script-src 'self'`) to reduce that risk;
planned follow-up: move tokens to `httpOnly` `SameSite` cookies with CSRF protection.
## Extension Trust Model
Extensions are **in-process code**. An installed extension runs with the panel's
+1 -1
View File
@@ -1 +1 @@
1.11.27
1.11.40
+4 -1
View File
@@ -136,7 +136,10 @@ class AgentNamespace(Namespace):
return
metrics = data.get('metrics', {})
agent_registry.ingest_agent_state(agent, metrics=metrics)
agent_registry.ingest_agent_state(
agent, metrics=metrics,
permission_level=data.get('permission_level'),
service_checks=data.get('service_checks'))
emit('heartbeat_ack', {'type': 'heartbeat_ack'})
+6 -2
View File
@@ -1,3 +1,4 @@
import logging
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.services.advanced_ssl_service import AdvancedSSLService
@@ -6,6 +7,8 @@ from app.models.audit_log import AuditLog
from app.middleware.rbac import get_current_user
from app.api._request import json_object
logger = logging.getLogger(__name__)
advanced_ssl_bp = Blueprint('advanced_ssl', __name__)
@@ -79,8 +82,9 @@ def upload_cert():
try:
result = AdvancedSSLService.upload_custom_cert(domain, cert, key, chain)
return jsonify(result), 201
except Exception as e:
return jsonify({'error': str(e)}), 400
except Exception:
logger.exception('Custom certificate upload failed')
return jsonify({'error': 'Could not install the certificate'}), 400
@advanced_ssl_bp.route('/health/<domain>', methods=['GET'])
+3 -1
View File
@@ -108,7 +108,9 @@ def poll():
# Shared transport-neutral ingest: capability
# side-effects (e.g. tunnel reconcile) fire exactly as on the WS path.
agent_registry.ingest_agent_state(agent, metrics=metrics, sysinfo=sysinfo,
capabilities=caps)
capabilities=caps,
permission_level=body.get('permission_level'),
service_checks=body.get('service_checks'))
# Long-poll up to 25s for any queued command. Below the typical
# tunnel idle-timeout (Cloudflare ~100s, ngrok ~60s) so we never
+56
View File
@@ -0,0 +1,56 @@
"""Monitor-mode agent report endpoint.
``POST /api/v1/agent/report`` is the ONLY channel a monitor-level agent uses:
a signed, outbound-only HTTPS POST. The reply never carries commands.
Auth (no JWT/CSRF; the HMAC is the credential):
X-Agent-Key: <api key> -> server looked up by its key prefix
X-Timestamp: <unix seconds> -> |skew| <= 300s
X-Nonce: <hex, >=32 chars> -> single use (TTL cache, 5 min)
X-Signature: hex(HMAC_SHA256(api_secret, ts + "." + nonce + "." + sha256hex(body)))
"""
from flask import Blueprint, jsonify, request
from app import limiter
from app.exceptions import (
AuthenticationError, PayloadTooLargeError, PermissionDeniedError, ValidationError,
)
from app.services import agent_health_service, permission_levels
from app.utils.ip_utils import is_ip_allowed
agent_report_bp = Blueprint('agent_report', __name__)
MAX_BODY_BYTES = 64 * 1024
MAX_SKEW_SECONDS = 300
def _rate_key():
return f"{request.remote_addr}:{(request.headers.get('X-Agent-Key') or '')[:12]}"
@agent_report_bp.route('/report', methods=['POST'])
@limiter.limit("30 per minute", key_func=_rate_key)
def report():
if (request.content_length or 0) > MAX_BODY_BYTES:
raise PayloadTooLargeError()
raw = request.get_data(cache=True)
if len(raw) > MAX_BODY_BYTES:
raise PayloadTooLargeError()
server = agent_health_service.authenticate_report(raw, request.headers, MAX_SKEW_SECONDS)
if not server:
raise AuthenticationError('authentication failed')
if server.allowed_ips and not is_ip_allowed(request.remote_addr, server.allowed_ips):
raise PermissionDeniedError('IP not allowed')
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise ValidationError('JSON object required')
level = body.get('permission_level')
if level not in permission_levels.LEVELS:
raise ValidationError('permission_level must be monitor, protect or full')
interval = agent_health_service.ingest_report(server, level, body)
return jsonify({'ok': True, 'interval_seconds': interval})
+27 -3
View File
@@ -1,3 +1,4 @@
import logging
import os
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
@@ -7,10 +8,21 @@ from app.services.backup_service import BackupService
from app.services.backup_policy_service import BackupPolicyService, BackupPolicyError
from app.services.storage_provider_service import StorageProviderService
from app import db, paths
from app.exceptions import field_required, not_found
from app.exceptions import DependencyUnavailableError, field_required, not_found
from app.api._request import json_object
backups_bp = Blueprint('backups', __name__)
logger = logging.getLogger(__name__)
_STORAGE_UNAVAILABLE = ('Backup storage is not accessible: the panel cannot create or read '
'its backup directory. Check its ownership and permissions.')
@backups_bp.errorhandler(PermissionError)
def _backup_dir_unavailable(exc):
logger.error('Backup directory is not writable: %s', exc)
err = DependencyUnavailableError('Backup directory is not writable', code='backup_dir_unavailable')
return jsonify(err.to_dict()), err.status_code
# UI-facing metadata for the CORE target types. Extension kinds
@@ -62,7 +74,12 @@ def list_target_types():
def list_backups():
"""List all backups."""
backup_type = request.args.get('type')
backups = BackupService.list_backups(backup_type)
try:
backups = BackupService.list_backups(backup_type)
except OSError:
# e.g. PermissionError creating /var/backups/serverkit: keep the page usable.
logger.exception('Backup directory is not accessible')
return jsonify({'backups': [], 'warning': _STORAGE_UNAVAILABLE}), 200
return jsonify({'backups': backups}), 200
@@ -70,7 +87,14 @@ def list_backups():
@admin_required
def get_stats():
"""Get backup statistics."""
stats = BackupService.get_backup_stats()
try:
stats = BackupService.get_backup_stats()
except OSError:
logger.exception('Backup directory is not accessible')
stats = {'total_backups': 0, 'application_backups': 0, 'database_backups': 0,
'file_backups': 0, 'total_size': 0, 'total_size_human': '0 B',
'remote_count': 0, 'remote_size': 0, 'remote_size_human': '0 B',
'warning': _STORAGE_UNAVAILABLE}
return jsonify(stats), 200
+6 -2
View File
@@ -12,6 +12,7 @@ Two endpoints:
* POST /generate — pure: given a plan dict, return Dockerfile + compose.
"""
import logging
import os
import shutil
import tempfile
@@ -25,6 +26,8 @@ from app.services.source_connection_service import SourceConnectionService
from app.middleware.rbac import developer_required, get_current_user
from app.api._request import json_object
logger = logging.getLogger(__name__)
buildpacks_bp = Blueprint('buildpacks', __name__)
@@ -113,8 +116,9 @@ def detect():
plan = BuildpackService.detect(clone_target)
BuildpackService.cache_plan(cache_key_url, plan, commit or branch)
return jsonify(_build_response(plan, app_name)), 200
except Exception as exc: # pragma: no cover - defensive
return jsonify({'error': str(exc)}), 400
except Exception: # pragma: no cover - defensive
logger.exception('Buildpack detection failed')
return jsonify({'error': 'Could not detect a build plan for this repository'}), 400
finally:
shutil.rmtree(workdir, ignore_errors=True)
+23 -33
View File
@@ -23,6 +23,19 @@ logger = logging.getLogger(__name__)
databases_bp = Blueprint('databases', __name__)
def _attach_owner_user(engine, name, data, result):
"""Create the database's same-name user; report its credentials only if it
exists, and why not under `user_error` otherwise."""
password = data.get('user_password') or DatabaseService.generate_password()
created = DatabaseService.create_database_user(
engine, name, password, data.get('host', 'localhost'), data.get('root_password'))
if created.get('success'):
result['user'] = name
result['password'] = password
else:
result['user_error'] = created.get('error') or 'Could not create the database user'
def _persist_provisioned(engine, name, result, data):
"""Track a just-provisioned database as a managed resource. Best-effort and
additive — a persistence failure never fails the provisioning that succeeded."""
@@ -86,22 +99,7 @@ def create_mysql_database():
if result['success']:
# Optionally create user with same name
if data.get('create_user'):
password = data.get('user_password') or DatabaseService.generate_password()
DatabaseService.mysql_create_user(
data['name'],
password,
data.get('host', 'localhost'),
data.get('root_password')
)
DatabaseService.mysql_grant_privileges(
data['name'],
data['name'],
'ALL',
data.get('host', 'localhost'),
data.get('root_password')
)
result['user'] = data['name']
result['password'] = password
_attach_owner_user('mysql', data['name'], data, result)
_persist_provisioned('mysql', data['name'], result, data)
@@ -192,13 +190,15 @@ def create_mysql_user():
# Grant privileges if database specified
if data.get('database'):
DatabaseService.mysql_grant_privileges(
granted = DatabaseService.mysql_grant_privileges(
data['username'],
data['database'],
data.get('privileges', 'ALL'),
data.get('host', 'localhost'),
data.get('root_password')
)
if not granted.get('success'):
result['grant_error'] = granted.get('error') or 'Could not grant privileges'
return jsonify(result), 201 if result['success'] else 400
@@ -292,11 +292,7 @@ def create_pg_database():
if result['success']:
# Optionally create user with same name
if data.get('create_user'):
password = data.get('user_password') or DatabaseService.generate_password()
DatabaseService.pg_create_user(data['name'], password)
DatabaseService.pg_grant_privileges(data['name'], data['name'], 'ALL')
result['user'] = data['name']
result['password'] = password
_attach_owner_user('postgresql', data['name'], data, result)
_persist_provisioned('postgresql', data['name'], result, data)
@@ -368,11 +364,13 @@ def create_pg_user():
# Grant privileges if database specified
if data.get('database'):
DatabaseService.pg_grant_privileges(
granted = DatabaseService.pg_grant_privileges(
data['username'],
data['database'],
data.get('privileges', 'ALL')
)
if not granted.get('success'):
result['grant_error'] = granted.get('error') or 'Could not grant privileges'
return jsonify(result), 201 if result['success'] else 400
@@ -788,19 +786,11 @@ def create_managed_database():
name, data.get('charset', 'utf8mb4'),
data.get('collation', 'utf8mb4_unicode_ci'), data.get('root_password'))
if result.get('success') and data.get('create_user'):
password = data.get('user_password') or DatabaseService.generate_password()
DatabaseService.mysql_create_user(name, password, data.get('host', 'localhost'), data.get('root_password'))
DatabaseService.mysql_grant_privileges(name, name, 'ALL', data.get('host', 'localhost'), data.get('root_password'))
result['user'] = name
result['password'] = password
_attach_owner_user('mysql', name, data, result)
else:
result = DatabaseService.pg_create_database(name, data.get('owner'), data.get('encoding', 'UTF8'))
if result.get('success') and data.get('create_user'):
password = data.get('user_password') or DatabaseService.generate_password()
DatabaseService.pg_create_user(name, password)
DatabaseService.pg_grant_privileges(name, name, 'ALL')
result['user'] = name
result['password'] = password
_attach_owner_user('postgresql', name, data, result)
if not result.get('success'):
return jsonify(result), 400
+25 -14
View File
@@ -1,3 +1,5 @@
import logging
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import User, Application
@@ -7,6 +9,8 @@ from app import db, paths
from app.error_reporting import unexpected_response
from app.api._request import json_object
logger = logging.getLogger(__name__)
docker_bp = Blueprint('docker', __name__)
@@ -505,8 +509,9 @@ def docker_cleanup():
}
else:
results['containers'] = {'removed': 0, 'success': True}
except Exception as e:
results['containers'] = {'error': str(e)}
except Exception:
logger.exception('Docker cleanup step failed')
results['containers'] = {'error': 'Cleanup step failed; see server log'}
# Remove dangling images
try:
@@ -515,8 +520,9 @@ def docker_cleanup():
'success': result['success'],
'output': result['output'].strip()
}
except Exception as e:
results['images'] = {'error': str(e)}
except Exception:
logger.exception('Docker cleanup step failed')
results['images'] = {'error': 'Cleanup step failed; see server log'}
# Remove unused networks
try:
@@ -525,8 +531,9 @@ def docker_cleanup():
'success': result['success'],
'output': result['output'].strip()
}
except Exception as e:
results['networks'] = {'error': str(e)}
except Exception:
logger.exception('Docker cleanup step failed')
results['networks'] = {'error': 'Cleanup step failed; see server log'}
# Remove unused volumes (optional)
if include_volumes:
@@ -536,8 +543,9 @@ def docker_cleanup():
'success': result['success'],
'output': result['output'].strip()
}
except Exception as e:
results['volumes'] = {'error': str(e)}
except Exception:
logger.exception('Docker cleanup step failed')
results['volumes'] = {'error': 'Cleanup step failed; see server log'}
else:
results['volumes'] = {'skipped': True, 'message': 'Volume cleanup not requested'}
@@ -581,24 +589,27 @@ def cleanup_all_apps():
try:
compose_result = DockerService.compose_down(app.root_path, volumes=True, remove_orphans=True)
app_result['steps'].append({'action': 'docker_down', 'success': compose_result.get('success', False)})
except Exception as e:
app_result['steps'].append({'action': 'docker_down', 'error': str(e)})
except Exception:
logger.exception('App cleanup step failed')
app_result['steps'].append({'action': 'docker_down', 'error': 'Step failed; see server log'})
app_result['success'] = False
# Delete folder
try:
shutil.rmtree(app.root_path)
app_result['steps'].append({'action': 'delete_folder', 'success': True})
except Exception as e:
app_result['steps'].append({'action': 'delete_folder', 'error': str(e)})
except Exception:
logger.exception('App cleanup step failed')
app_result['steps'].append({'action': 'delete_folder', 'error': 'Step failed; see server log'})
app_result['success'] = False
# Remove from database
try:
db.session.delete(app)
app_result['steps'].append({'action': 'delete_db', 'success': True})
except Exception as e:
app_result['steps'].append({'action': 'delete_db', 'error': str(e)})
except Exception:
logger.exception('App cleanup step failed')
app_result['steps'].append({'action': 'delete_db', 'error': 'Step failed; see server log'})
app_result['success'] = False
results.append(app_result)
+9 -14
View File
@@ -407,20 +407,11 @@ def enable_ssl(domain_id):
if not result['success']:
return jsonify({'error': result.get('error', 'Failed to obtain certificate')}), 400
# Add SSL to Nginx site
nginx_result = NginxService.add_ssl_to_site(
app.name,
result['certificate_path'],
result['private_key_path']
)
if not nginx_result['success']:
return jsonify({'error': nginx_result.get('error', 'Failed to configure Nginx')}), 400
domain.ssl_enabled = True
domain.ssl_certificate_path = result['certificate_path']
domain.ssl_private_key_path = result['private_key_path']
db.session.commit()
from app.services.site_domain_service import SiteDomainService
error = SiteDomainService.enable_domain_ssl(
app, domain, result['certificate_path'], result['private_key_path'])
if error:
return jsonify({'error': error}), 400
# Only after issuance actually worked — remembering an address that
# Let's Encrypt rejected would be worse than not remembering one.
@@ -449,10 +440,14 @@ def disable_ssl(domain_id):
if not ResourceGrantService.can_edit_app(user, app):
raise permission_denied()
from app.services.site_domain_service import SiteDomainService
domain.ssl_enabled = False
db.session.commit()
# Drop the domain's HTTPS server block; best-effort like other rewrites.
published = SiteDomainService.write_app_vhost(app)
return jsonify({
'warning': published.get('warning'),
'message': 'SSL disabled for domain',
'domain': domain.to_dict()
}), 200
+4 -2
View File
@@ -21,8 +21,9 @@ This module is read-only; it does not write any state.
from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from app.models.server import Server
from app.services.agent_registry import agent_registry
from app.services.workspace_service import WorkspaceService
from app.middleware.rbac import get_current_user
fleet_bp = Blueprint('fleet', __name__)
@@ -48,6 +49,7 @@ def list_targets():
feature = (request.args.get('feature') or '').strip() or None
targets = [{'kind': 'local'}]
user = get_current_user()
# Walk the in-memory registry of connected agents. We intentionally
# do NOT pull from the Server table — capabilities are per-session
@@ -60,7 +62,7 @@ def list_targets():
# Look up the display name. We could cache this on
# ConnectedAgent, but the table is small and the lookup is
# cheap; not worth the staleness risk.
server = Server.query.get(server_id)
server = WorkspaceService.get_accessible_server(user, server_id)
if not server:
# Connected agent without a Server row would be a bug
# elsewhere; skip rather than 500.
+2
View File
@@ -12,6 +12,7 @@ from flask_jwt_extended import jwt_required
from app.services.fleet_monitor_service import fleet_monitor_service
from app.middleware.rbac import admin_required, get_current_user
from app.api._request import json_object
from app.api.servers import _get_operable_server
fleet_monitor_bp = Blueprint('fleet_monitor', __name__)
@@ -128,6 +129,7 @@ def get_anomalies():
@jwt_required()
def get_forecast(server_id):
"""Get capacity forecast for a server."""
_get_operable_server(server_id)
metric = request.args.get('metric', 'disk')
return jsonify(fleet_monitor_service.forecast_capacity(server_id, metric))
+20 -7
View File
@@ -643,10 +643,21 @@ def list_updates():
"""List installed plugins that have a newer version in the registry.
Each entry: {slug, plugin_id, installed_version, available_version,
update_available, compatible, source}.
update_available, compatible, source, display_name, update_source,
incompatible_reason, requires_ack, risk}. ``?refresh=1`` refetches the
registry index first.
"""
from datetime import datetime, timezone
from app.services import registry_service
from app.services.plugin_service import check_for_updates
return jsonify({'updates': check_for_updates()})
refresh = request.args.get('refresh', '').lower() in ('1', 'true', 'yes')
updates = check_for_updates(refresh=refresh)
return jsonify({
'updates': updates,
'count': sum(1 for u in updates if u['update_available'] and u['compatible']),
'checked_at': datetime.now(timezone.utc).isoformat(),
'registry_source': registry_service.registry_source_label(),
})
@plugins_bp.route('/<int:plugin_id>/update', methods=['POST'])
@@ -670,21 +681,23 @@ def update_plugin_route(plugin_id):
if not plugin:
return jsonify({'error': 'Plugin not found'}), 404
entry = registry_service.get_entry(plugin.slug)
if not entry:
builtin = plugin.source_type == 'builtin' # local bundled code: no consent
entry = None if builtin else registry_service.get_entry(plugin.slug)
if not builtin and not entry:
return jsonify({
'error': f"No registry entry for '{plugin.slug}' — cannot update "
f"from the registry."
}), 400
# Hidden means not updatable either: unreviewed entries only exist in
# development contexts (see registry_service._show_unreviewed).
if entry.get('trust') == 'unreviewed' \
if entry and entry.get('trust') == 'unreviewed' \
and not registry_service._show_unreviewed():
return jsonify({'error': 'Extension not found in the registry'}), 404
body = json_object(optional=True)
acknowledged = body.get('acknowledge_risk') is True
reason, message = registry_service.consent_gate(entry, acknowledged)
reason, message = (None, None) if builtin else \
registry_service.consent_gate(entry, acknowledged)
if reason:
return jsonify({
'error': f'{message} Resend with acknowledge_risk: true to proceed.',
@@ -703,7 +716,7 @@ def update_plugin_route(plugin_id):
target_id=plugin.id,
details={
'name': plugin.name, 'version': plugin.version,
'source': 'registry-update',
'source': 'builtin-update' if builtin else 'registry-update',
# Forensics (audit I7): the signature verdict of the bytes
# that just landed.
'signature': sig.get('status') or 'unsigned',
+3 -2
View File
@@ -13,7 +13,6 @@ from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models.server import Server
from app.middleware.rbac import developer_required
from app.services.proxy_stack_service import ProxyStackService
from app.api._request import json_object
@@ -23,7 +22,9 @@ proxy_bp = Blueprint('proxy', __name__)
def _require_server(server_id):
"""Return (server, None) or (None, error_response_tuple)."""
server = Server.query.get(server_id)
from app.middleware.rbac import get_current_user
from app.services.workspace_service import WorkspaceService
server = WorkspaceService.get_accessible_server(get_current_user(), server_id)
if not server:
return None, (jsonify({'error': 'Server not found'}), 404)
return server, None
+64 -66
View File
@@ -13,6 +13,7 @@ from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy.orm import joinedload
from app import db, limiter
from app.services import permission_levels
from app.services.server_metrics_service import latest_metrics_by_server
from app.api._query import apply_query, QueryParseError
from app.api._request import json_object
@@ -98,6 +99,18 @@ def _get_operable_server(server_id):
return server
def _ip_pattern_errors(allowed_ips):
"""One message per invalid allow-list entry; empty when all are valid."""
if not isinstance(allowed_ips, list):
return ['allowed_ips must be a list']
errors = []
for ip_pattern in allowed_ips:
is_valid, error = validate_ip_pattern(ip_pattern)
if not is_valid:
errors.append(f"Invalid pattern '{ip_pattern}': {error}")
return errors
def _get_external_base_url():
"""Return the public origin agents should use when this app sits behind a proxy."""
public_url = current_app.config.get('PUBLIC_URL') or os.environ.get('SERVERKIT_PUBLIC_URL')
@@ -179,6 +192,17 @@ PERMISSION_PROFILES = {
'survey:read',
]
},
'ssh_access': {
'name': 'SSH Access',
'description': 'Add and remove authorized SSH keys (Faro access grants), plus health reads',
'permissions': [
'ssh:keys:*',
'system:metrics:read',
'doctor:read',
'systemd:read',
'survey:read',
]
},
'full_access': {
'name': 'Full Access',
'description': 'All permissions including system commands',
@@ -300,6 +324,7 @@ def list_servers():
user, request.headers.get('X-Workspace-Id') or request.args.get('workspace_id'))
query = WorkspaceService.scope_query(Server.query, Server, user,
workspace_id=ws_id, owner_attr=None)
query = WorkspaceService.filter_accessible_servers(query, user)
if group_id:
query = query.filter_by(group_id=group_id)
@@ -416,6 +441,8 @@ def create_server():
registered_by=user_id,
workspace_id=ws_id,
registration_token_expires=expires_at,
# What the install command asks for; the agent's report is the truth.
requested_permission_level=permission_levels.normalize(data.get('requested_level')),
)
server.set_registration_token(registration_token)
@@ -486,9 +513,7 @@ def set_server_workspace(server_id):
@jwt_required()
def get_server(server_id):
"""Get a server by ID"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
result = server.to_dict(include_metrics=True)
# Surface the live transport so the UI can disable / banner features
@@ -581,9 +606,7 @@ def get_server_timeline(server_id):
@developer_required
def update_server(server_id):
"""Update a server"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
data = json_object()
@@ -598,6 +621,9 @@ def update_server(server_id):
if 'permissions' in data:
server.permissions = data['permissions']
if 'allowed_ips' in data:
errors = _ip_pattern_errors(data['allowed_ips'])
if errors:
raise ValidationError('Invalid IP patterns', details={'patterns': errors})
server.allowed_ips = data['allowed_ips']
# Handle permission profile
@@ -614,9 +640,7 @@ def update_server(server_id):
@admin_required
def delete_server(server_id):
"""Delete a server"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
# Disconnect agent if connected
if agent_registry.is_agent_connected(server_id):
@@ -637,9 +661,7 @@ def start_server_onboarding(server_id):
"""Begin the onboarding lifecycle for a server (pending -> validating ...)."""
from app.services.server_onboarding_service import ServerOnboardingService
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
try:
status = ServerOnboardingService.start(server_id)
@@ -654,9 +676,7 @@ def retry_server_onboarding(server_id):
"""Clear a failed onboarding and resume from validation."""
from app.services.server_onboarding_service import ServerOnboardingService
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
try:
status = ServerOnboardingService.retry(server_id)
@@ -671,9 +691,7 @@ def get_server_onboarding_status(server_id):
"""Return the onboarding state + ordered progress log for a server."""
from app.services.server_onboarding_service import ServerOnboardingService
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
try:
status = ServerOnboardingService.get_status(server_id)
@@ -703,6 +721,7 @@ def regenerate_token(server_id):
registration_token = Server.generate_registration_token()
server.set_registration_token(registration_token)
server.registration_token_expires = expires_at
server.requested_permission_level = permission_levels.normalize(data.get('requested_level'))
server.status = 'pending'
server.agent_id = None
@@ -742,15 +761,10 @@ def register_agent():
data = json_object()
token = data.get('token')
if not token:
if not token or not isinstance(token, str):
return jsonify({'error': 'Registration token required'}), 400
# Find server by token (need to check all servers)
server = None
for s in Server.query.filter(Server.registration_token_hash.isnot(None)).all():
if s.verify_registration_token(token):
server = s
break
server = Server.find_by_registration_token(token)
if not server:
return jsonify({'error': 'Invalid or expired registration token'}), 401
@@ -782,6 +796,10 @@ def register_agent():
server.total_disk = system_info.get('total_disk', server.total_disk)
server.agent_version = data.get('agent_version')
# Level is whatever the agent says it was installed with; the panel never
# sets it. A mismatch with the requested level is surfaced in the UI.
from app.services import agent_health_service
agent_health_service.record_level(server, data.get('permission_level'))
# Replace the panel-issued placeholder name with whatever the agent
# reports — preferring the OS hostname over the agent's optional
@@ -814,9 +832,7 @@ def register_agent():
@jwt_required()
def get_server_status(server_id):
"""Get current server status and live metrics"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
is_connected = agent_registry.is_agent_connected(server_id)
@@ -841,9 +857,7 @@ def get_server_status(server_id):
@developer_required
def ping_server(server_id):
"""Force a ping/health check on a server"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
if not agent_registry.is_agent_connected(server_id):
raise agent_offline()
@@ -864,9 +878,7 @@ def ping_server(server_id):
@jwt_required()
def get_server_metrics(server_id):
"""Get historical metrics for a server"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
# Query parameters
from_time = request.args.get('from')
@@ -879,15 +891,15 @@ def get_server_metrics(server_id):
try:
from_dt = datetime.fromisoformat(from_time.replace('Z', '+00:00'))
query = query.filter(ServerMetrics.timestamp >= from_dt)
except:
pass
except ValueError:
raise ValidationError("Invalid 'from' timestamp; use ISO 8601")
if to_time:
try:
to_dt = datetime.fromisoformat(to_time.replace('Z', '+00:00'))
query = query.filter(ServerMetrics.timestamp <= to_dt)
except:
pass
except ValueError:
raise ValidationError("Invalid 'to' timestamp; use ISO 8601")
metrics = query.order_by(ServerMetrics.timestamp.desc()).limit(limit).all()
@@ -905,9 +917,10 @@ def compare_server_metrics():
if not server_ids or server_ids == ['']:
return jsonify({'error': 'Server IDs required'}), 400
from app.services.workspace_service import WorkspaceService
result = {}
for server_id in server_ids:
server = Server.query.get(server_id)
server = WorkspaceService.get_accessible_server(get_current_user(), server_id)
if not server:
continue
@@ -936,9 +949,10 @@ def compare_server_metrics():
@jwt_required()
def get_servers_overview():
"""Get overview of all servers health"""
servers = Server.query.options(joinedload(Server.group)).all()
from app.services.workspace_service import WorkspaceService
servers = WorkspaceService.accessible_servers(get_current_user())
metrics_by_server = latest_metrics_by_server(server.id for server in servers)
connected_ids = set(agent_registry.get_connected_servers())
connected_ids = set(agent_registry.get_connected_servers()) & {s.id for s in servers}
total = len(servers)
online = len(connected_ids)
@@ -995,9 +1009,7 @@ def get_servers_overview():
@jwt_required()
def get_command_history(server_id):
"""Get command history for a server"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
limit = request.args.get('limit', 50, type=int)
@@ -1025,9 +1037,7 @@ def get_permission_profiles():
@jwt_required()
def get_allowed_ips(server_id):
"""Get allowed IPs for a server"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
return jsonify({
'allowed_ips': server.allowed_ips or [],
@@ -1048,20 +1058,12 @@ def update_allowed_ips(server_id):
- CIDR: "192.168.1.0/24"
- Wildcards: "192.168.1.*"
"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
data = json_object()
allowed_ips = data.get('allowed_ips', [])
# Validate each IP pattern
errors = []
for ip_pattern in allowed_ips:
is_valid, error = validate_ip_pattern(ip_pattern)
if not is_valid:
errors.append(f"Invalid pattern '{ip_pattern}': {error}")
errors = _ip_pattern_errors(allowed_ips)
if errors:
return jsonify({'error': 'Invalid IP patterns', 'details': errors}), 400
@@ -1078,9 +1080,7 @@ def update_allowed_ips(server_id):
@jwt_required()
def get_connection_info(server_id):
"""Get connection info for a server (current IP, connected status, etc.)"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
is_connected = agent_registry.is_agent_connected(server_id)
agent = agent_registry.get_agent(server_id) if is_connected else None
@@ -1109,9 +1109,7 @@ def rotate_api_key(server_id):
This generates new credentials and sends them to the connected agent.
The agent must acknowledge the update within 5 minutes.
"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
if not agent_registry.is_agent_connected(server_id):
raise agent_offline()
@@ -1180,9 +1178,7 @@ def rotate_api_key(server_id):
@jwt_required()
def get_server_security_alerts(server_id):
"""Get security alerts for a specific server"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
status = request.args.get('status')
severity = request.args.get('severity')
@@ -1264,6 +1260,7 @@ def get_server_metrics_history(server_id):
Query params:
period: '1h', '6h', '24h', '7d', '30d' (default: '24h')
"""
_get_operable_server(server_id)
period = request.args.get('period', '24h')
result = ServerMetricsService.get_server_history(server_id, period)
@@ -1279,6 +1276,7 @@ def get_server_metrics_aggregated(server_id):
period: '24h', '7d', '30d' (default: '24h')
aggregation: 'hourly', 'daily' (default: 'hourly')
"""
_get_operable_server(server_id)
period = request.args.get('period', '24h')
aggregation = request.args.get('aggregation', 'hourly')
+14 -13
View File
@@ -5,9 +5,10 @@ import os
import re
import requests
from app.models.server import AgentVersion, Server
from app.services import permission_levels
from flask import Response, current_app, jsonify, redirect, request
from app.middleware.rbac import admin_required, developer_required
from app.exceptions import agent_offline, field_required, not_found
from app.exceptions import agent_offline, field_required
from app.services.agent_registry import agent_registry
from datetime import datetime, timedelta
from app import db
@@ -16,7 +17,7 @@ from app.services.remote_command_dispatcher import dispatch_agent_command
from app.services.agent_fleet_service import fleet_service
from flask_jwt_extended import get_jwt_identity, jwt_required
from app.api._request import json_object
from app.api.servers import _get_external_base_url, servers_bp
from app.api.servers import _get_external_base_url, _get_operable_server, servers_bp
# ==================== Installation Scripts ====================
@@ -160,9 +161,7 @@ def get_install_instructions(server_id):
Returns installation commands with the correct API endpoint. Registration
tokens are only shown when they are generated, so the UI supplies the token.
"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
server = _get_operable_server(server_id)
# Check if server has a valid registration token
if not server.registration_token_hash:
@@ -180,8 +179,11 @@ def get_install_instructions(server_id):
# Get base URL
base_url = _get_external_base_url()
api_url = f"{base_url}/api/v1/servers"
level = (permission_levels.normalize(request.args.get('level'))
or server.requested_permission_level or 'monitor')
return jsonify({
'permission_level': level,
'linux': {
# Download-then-run rather than `curl … | sudo bash`: in a pipeline
# the shell reports bash's exit status, so a failed download exits 0
@@ -189,7 +191,7 @@ def get_install_instructions(server_id):
'one_liner': (
f'curl -fsSL {api_url}/install.sh -o /tmp/serverkit-agent-install.sh '
f'&& sudo bash /tmp/serverkit-agent-install.sh '
f'--token "YOUR_TOKEN" --server "{base_url}"'
f'--token "YOUR_TOKEN" --server "{base_url}" --level {level}'
),
'manual': [
f'# Download the script',
@@ -197,17 +199,17 @@ def get_install_instructions(server_id):
f'chmod +x install.sh',
f'',
f'# Run installation',
f'sudo ./install.sh --token "YOUR_TOKEN" --server "{base_url}"'
f'sudo ./install.sh --token "YOUR_TOKEN" --server "{base_url}" --level {level}'
]
},
'windows': {
'one_liner': f'irm {api_url}/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "{base_url}"',
'one_liner': f'irm {api_url}/install.ps1 | iex; Install-ServerKitAgent -Token "YOUR_TOKEN" -Server "{base_url}" -Level {level}',
'manual': [
f'# Download the script (run in PowerShell as Administrator)',
f'Invoke-WebRequest -Uri "{api_url}/install.ps1" -OutFile install.ps1',
f'',
f'# Run installation',
f'.\\install.ps1 -Token "YOUR_TOKEN" -Server "{base_url}"'
f'.\\install.ps1 -Token "YOUR_TOKEN" -Server "{base_url}" -Level {level}'
]
},
'note': 'Replace YOUR_TOKEN with the registration token shown in the UI'
@@ -411,7 +413,8 @@ def _compare_versions(v1, v2):
elif a > b:
return 1
return 0
except:
except (ValueError, AttributeError, TypeError):
current_app.logger.warning('Could not compare versions %r and %r', v1, v2)
return 0
@@ -492,9 +495,7 @@ def trigger_agent_update(server_id):
service across the fleet, so it must not be reachable by read-only viewers
(every other state-changing server route is already @developer_required).
"""
server = Server.query.get(server_id)
if not server:
raise not_found('server')
_get_operable_server(server_id)
if not agent_registry.is_agent_connected(server_id):
raise agent_offline()
+27 -3
View File
@@ -2,11 +2,11 @@
Registered on the shared ``servers_bp`` blueprint (see app.api.servers)."""
from app.services.remote_docker_service import RemoteDockerService
from app.middleware.rbac import developer_required
from app.middleware.rbac import developer_required, get_current_user
from app.exceptions import field_required
from flask_jwt_extended import get_jwt_identity, jwt_required
from flask import jsonify, request
from app.api.servers import _agent_failure_status, servers_bp
from app.api.servers import _agent_failure_status, _get_operable_server, servers_bp
from app.api._request import json_object
@@ -17,7 +17,7 @@ from app.api._request import json_object
@jwt_required()
def get_available_servers():
"""Get list of servers available for Docker operations"""
servers = RemoteDockerService.get_available_servers()
servers = RemoteDockerService.get_available_servers(get_current_user())
return jsonify(servers)
@@ -25,6 +25,7 @@ def get_available_servers():
@jwt_required()
def list_remote_containers(server_id):
"""List containers on a remote server"""
_get_operable_server(server_id)
all_containers = request.args.get('all', 'false').lower() == 'true'
user_id = get_jwt_identity()
@@ -40,6 +41,7 @@ def list_remote_containers(server_id):
@jwt_required()
def inspect_remote_container(server_id, container_id):
"""Inspect a container on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.inspect_container(server_id, container_id, user_id=user_id)
@@ -54,6 +56,7 @@ def inspect_remote_container(server_id, container_id):
@developer_required
def start_remote_container(server_id, container_id):
"""Start a container on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.start_container(server_id, container_id, user_id=user_id)
@@ -68,6 +71,7 @@ def start_remote_container(server_id, container_id):
@developer_required
def stop_remote_container(server_id, container_id):
"""Stop a container on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
timeout = data.get('timeout')
@@ -84,6 +88,7 @@ def stop_remote_container(server_id, container_id):
@developer_required
def restart_remote_container(server_id, container_id):
"""Restart a container on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
timeout = data.get('timeout')
@@ -100,6 +105,7 @@ def restart_remote_container(server_id, container_id):
@developer_required
def remove_remote_container(server_id, container_id):
"""Remove a container on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
force = request.args.get('force', 'false').lower() == 'true'
remove_volumes = request.args.get('v', 'false').lower() == 'true'
@@ -120,6 +126,7 @@ def remove_remote_container(server_id, container_id):
@jwt_required()
def get_remote_container_stats(server_id, container_id):
"""Get container stats from a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.get_container_stats(server_id, container_id, user_id=user_id)
@@ -141,6 +148,7 @@ def get_remote_container_logs(server_id, container_id):
since: Show logs since timestamp
timestamps: Include timestamps (default true)
"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
tail = request.args.get('tail', '100')
since = request.args.get('since')
@@ -162,6 +170,7 @@ def get_remote_container_logs(server_id, container_id):
@jwt_required()
def list_remote_images(server_id):
"""List images on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.list_images(server_id, user_id=user_id)
@@ -176,6 +185,7 @@ def list_remote_images(server_id):
@developer_required
def pull_remote_image(server_id):
"""Pull an image on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
@@ -194,6 +204,7 @@ def pull_remote_image(server_id):
@developer_required
def remove_remote_image(server_id, image_id):
"""Remove an image on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
force = request.args.get('force', 'false').lower() == 'true'
@@ -209,6 +220,7 @@ def remove_remote_image(server_id, image_id):
@jwt_required()
def list_remote_volumes(server_id):
"""List volumes on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.list_volumes(server_id, user_id=user_id)
@@ -223,6 +235,7 @@ def list_remote_volumes(server_id):
@developer_required
def remove_remote_volume(server_id, volume_name):
"""Remove a volume on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
force = request.args.get('force', 'false').lower() == 'true'
@@ -238,6 +251,7 @@ def remove_remote_volume(server_id, volume_name):
@jwt_required()
def list_remote_networks(server_id):
"""List networks on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.list_networks(server_id, user_id=user_id)
@@ -252,6 +266,7 @@ def list_remote_networks(server_id):
@developer_required
def remove_remote_network(server_id, network_id):
"""Remove a network on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.remove_network(server_id, network_id, user_id=user_id)
@@ -266,6 +281,7 @@ def remove_remote_network(server_id, network_id):
@jwt_required()
def get_remote_system_metrics(server_id):
"""Get system metrics from a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.get_system_metrics(server_id, user_id=user_id)
@@ -280,6 +296,7 @@ def get_remote_system_metrics(server_id):
@jwt_required()
def get_remote_system_info(server_id):
"""Get system info from a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.get_system_info(server_id, user_id=user_id)
@@ -296,6 +313,7 @@ def get_remote_system_info(server_id):
@jwt_required()
def list_remote_compose_projects(server_id):
"""List compose projects on a remote server"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteDockerService.compose_list(server_id, user_id=user_id)
@@ -310,6 +328,7 @@ def list_remote_compose_projects(server_id):
@developer_required
def remote_compose_ps(server_id):
"""List containers for a compose project"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
@@ -332,6 +351,7 @@ def remote_compose_ps(server_id):
@developer_required
def remote_compose_up(server_id):
"""Start a compose project"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
@@ -356,6 +376,7 @@ def remote_compose_up(server_id):
@developer_required
def remote_compose_down(server_id):
"""Stop a compose project"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
@@ -380,6 +401,7 @@ def remote_compose_down(server_id):
@developer_required
def remote_compose_logs(server_id):
"""Get logs from a compose project"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
@@ -404,6 +426,7 @@ def remote_compose_logs(server_id):
@developer_required
def remote_compose_restart(server_id):
"""Restart a compose project or specific service"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
@@ -427,6 +450,7 @@ def remote_compose_restart(server_id):
@developer_required
def remote_compose_pull(server_id):
"""Pull images for a compose project"""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object()
+37
View File
@@ -156,6 +156,7 @@ def _agent_result(result, ok_status=200):
@servers_bp.route('/<server_id>/cron/status', methods=['GET'])
@jwt_required()
def remote_cron_status(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteCronService.status(server_id, user_id=user_id)
return _agent_result(result)
@@ -164,6 +165,7 @@ def remote_cron_status(server_id):
@servers_bp.route('/<server_id>/cron/jobs', methods=['GET'])
@jwt_required()
def remote_cron_list(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteCronService.list_jobs(server_id, user_id=user_id)
return _agent_result(result)
@@ -172,6 +174,7 @@ def remote_cron_list(server_id):
@servers_bp.route('/<server_id>/cron/jobs', methods=['POST'])
@developer_required
def remote_cron_add(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
schedule = (data.get('schedule') or '').strip()
@@ -193,6 +196,7 @@ def remote_cron_add(server_id):
@servers_bp.route('/<server_id>/cron/jobs/<job_id>', methods=['DELETE'])
@developer_required
def remote_cron_remove(server_id, job_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteCronService.remove_job(server_id, job_id, user_id=user_id)
return _agent_result(result)
@@ -201,6 +205,7 @@ def remote_cron_remove(server_id, job_id):
@servers_bp.route('/<server_id>/cron/jobs/<job_id>/toggle', methods=['POST'])
@developer_required
def remote_cron_toggle(server_id, job_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
enabled = bool(data.get('enabled', True))
@@ -224,6 +229,7 @@ def remote_cron_toggle(server_id, job_id):
@servers_bp.route('/<server_id>/cloudflared/status', methods=['GET'])
@jwt_required()
def remote_cloudflared_status(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteCloudflaredService.status(server_id, user_id=user_id)
return _agent_result(result)
@@ -235,6 +241,7 @@ def remote_cloudflared_login(server_id):
"""Start `cloudflared tunnel login` on the agent. Returns
{job_id, channel}; the panel subscribes to the corresponding
Socket.IO room and renders the auth_url the agent surfaces."""
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteCloudflaredService.login(server_id, user_id=user_id)
return _agent_result(result)
@@ -243,6 +250,7 @@ def remote_cloudflared_login(server_id):
@servers_bp.route('/<server_id>/cloudflared/tunnels', methods=['GET'])
@jwt_required()
def remote_cloudflared_list(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteCloudflaredService.list_tunnels(server_id, user_id=user_id)
return _agent_result(result)
@@ -251,6 +259,7 @@ def remote_cloudflared_list(server_id):
@servers_bp.route('/<server_id>/cloudflared/tunnels', methods=['POST'])
@developer_required
def remote_cloudflared_create(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
name = (data.get('name') or '').strip()
@@ -264,6 +273,7 @@ def remote_cloudflared_create(server_id):
@servers_bp.route('/<server_id>/cloudflared/tunnels/<tunnel_ref>/route', methods=['POST'])
@developer_required
def remote_cloudflared_route(server_id, tunnel_ref):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
hostname = (data.get('hostname') or '').strip()
@@ -279,6 +289,7 @@ def remote_cloudflared_route(server_id, tunnel_ref):
@servers_bp.route('/<server_id>/cloudflared/tunnels/<tunnel_ref>', methods=['DELETE'])
@developer_required
def remote_cloudflared_delete(server_id, tunnel_ref):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteCloudflaredService.delete_tunnel(server_id, tunnel_ref, user_id=user_id)
return _agent_result(result)
@@ -296,6 +307,7 @@ def remote_cloudflared_delete(server_id, tunnel_ref):
@servers_bp.route('/<server_id>/refresh-capabilities', methods=['POST'])
@developer_required
def remote_refresh_capabilities(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = dispatch_agent_command(
server_id=server_id, action='agent:recapabilities',
@@ -315,6 +327,7 @@ def remote_refresh_capabilities(server_id):
@servers_bp.route('/<server_id>/packages', methods=['GET'])
@jwt_required()
def remote_packages_list(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemotePackagesService.list_installed(server_id, user_id=user_id)
return _agent_result(result)
@@ -323,6 +336,7 @@ def remote_packages_list(server_id):
@servers_bp.route('/<server_id>/packages/search', methods=['GET'])
@jwt_required()
def remote_packages_search(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
query = (request.args.get('q') or '').strip()
if not query:
@@ -338,6 +352,7 @@ def remote_packages_search(server_id):
@servers_bp.route('/<server_id>/packages/info/<name>', methods=['GET'])
@jwt_required()
def remote_packages_info(server_id, name):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemotePackagesService.info(server_id, name, user_id=user_id)
return _agent_result(result)
@@ -346,6 +361,7 @@ def remote_packages_info(server_id, name):
@servers_bp.route('/<server_id>/packages/update-cache', methods=['POST'])
@developer_required
def remote_packages_update_cache(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemotePackagesService.update_cache(server_id, user_id=user_id)
return _agent_result(result)
@@ -357,6 +373,7 @@ def remote_packages_install(server_id):
"""Streaming install. Body: {names: ['nginx', 'redis-server']}.
Returns {job_id, channel} immediately; the panel subscribes to the
matching Socket.IO room for live install output."""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
names = data.get('names') or []
@@ -371,6 +388,7 @@ def remote_packages_install(server_id):
@servers_bp.route('/<server_id>/packages/remove', methods=['POST'])
@developer_required
def remote_packages_remove(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
name = (data.get('name') or '').strip()
@@ -385,6 +403,7 @@ def remote_packages_remove(server_id):
def remote_packages_upgrade(server_id):
"""Streaming upgrade. Body: {all: bool, names?: [...]}. Returns
{job_id, channel}."""
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
names = data.get('names') or []
@@ -406,6 +425,7 @@ def remote_packages_upgrade(server_id):
@servers_bp.route('/<server_id>/services', methods=['GET'])
@jwt_required()
def remote_services_list(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
state = request.args.get('state')
type_ = request.args.get('type', 'service')
@@ -419,6 +439,7 @@ def remote_services_list(server_id):
@servers_bp.route('/<server_id>/services/daemon-reload', methods=['POST'])
@developer_required
def remote_services_daemon_reload(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteSystemdService.daemon_reload(server_id, user_id=user_id)
return _agent_result(result)
@@ -427,6 +448,7 @@ def remote_services_daemon_reload(server_id):
@servers_bp.route('/<server_id>/services/<unit>/logs', methods=['GET'])
@jwt_required()
def remote_services_logs(server_id, unit):
_get_operable_server(server_id)
user_id = get_jwt_identity()
try:
lines = int(request.args.get('lines', 200))
@@ -439,6 +461,7 @@ def remote_services_logs(server_id, unit):
@servers_bp.route('/<server_id>/services/<unit>', methods=['GET'])
@jwt_required()
def remote_services_status(server_id, unit):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteSystemdService.status(server_id, unit, user_id=user_id)
return _agent_result(result)
@@ -447,6 +470,7 @@ def remote_services_status(server_id, unit):
@servers_bp.route('/<server_id>/services/<unit>/<action>', methods=['POST'])
@developer_required
def remote_services_control(server_id, unit, action):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteSystemdService.control(server_id, unit, action, user_id=user_id)
return _agent_result(result)
@@ -462,6 +486,7 @@ def remote_services_control(server_id, unit, action):
@servers_bp.route('/<server_id>/runtimes', methods=['GET'])
@jwt_required()
def remote_runtimes_list(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteRuntimesService.list_state(server_id, user_id=user_id)
return _agent_result(result)
@@ -470,6 +495,7 @@ def remote_runtimes_list(server_id):
@servers_bp.route('/<server_id>/runtimes/pyenv/bootstrap', methods=['POST'])
@developer_required
def remote_runtimes_pyenv_bootstrap(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteRuntimesService.pyenv_bootstrap(server_id, user_id=user_id)
return _agent_result(result)
@@ -478,6 +504,7 @@ def remote_runtimes_pyenv_bootstrap(server_id):
@servers_bp.route('/<server_id>/runtimes/python', methods=['GET'])
@jwt_required()
def remote_runtimes_python_installed(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteRuntimesService.python_installed(server_id, user_id=user_id)
return _agent_result(result)
@@ -486,6 +513,7 @@ def remote_runtimes_python_installed(server_id):
@servers_bp.route('/<server_id>/runtimes/python/available', methods=['GET'])
@jwt_required()
def remote_runtimes_python_available(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteRuntimesService.python_available(server_id, user_id=user_id)
return _agent_result(result)
@@ -494,6 +522,7 @@ def remote_runtimes_python_available(server_id):
@servers_bp.route('/<server_id>/runtimes/python/current', methods=['GET'])
@jwt_required()
def remote_runtimes_python_current(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
result = RemoteRuntimesService.python_current(server_id, user_id=user_id)
return _agent_result(result)
@@ -502,6 +531,7 @@ def remote_runtimes_python_current(server_id):
@servers_bp.route('/<server_id>/runtimes/python/install', methods=['POST'])
@developer_required
def remote_runtimes_python_install(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
version = (data.get('version') or '').strip()
@@ -514,6 +544,7 @@ def remote_runtimes_python_install(server_id):
@servers_bp.route('/<server_id>/runtimes/python/uninstall', methods=['POST'])
@developer_required
def remote_runtimes_python_uninstall(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
version = (data.get('version') or '').strip()
@@ -526,6 +557,7 @@ def remote_runtimes_python_uninstall(server_id):
@servers_bp.route('/<server_id>/runtimes/python/global', methods=['POST'])
@developer_required
def remote_runtimes_python_set_global(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
version = (data.get('version') or '').strip()
@@ -538,6 +570,7 @@ def remote_runtimes_python_set_global(server_id):
@servers_bp.route('/<server_id>/runtimes/python/local', methods=['POST'])
@developer_required
def remote_runtimes_python_set_local(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
version = (data.get('version') or '').strip()
@@ -562,6 +595,7 @@ def remote_runtimes_python_set_local(server_id):
def remote_file_allowed_paths(server_id):
"""Return the file roots the agent advertised on connect. Lets the
file manager seed the browse picker without guessing or hardcoding."""
_get_operable_server(server_id)
paths = RemoteFileService.get_allowed_paths(server_id)
return jsonify({'allowed_paths': paths})
@@ -569,6 +603,7 @@ def remote_file_allowed_paths(server_id):
@servers_bp.route('/<server_id>/files/browse', methods=['GET'])
@jwt_required()
def remote_file_browse(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
path = request.args.get('path')
if not path:
@@ -580,6 +615,7 @@ def remote_file_browse(server_id):
@servers_bp.route('/<server_id>/files/read', methods=['GET'])
@jwt_required()
def remote_file_read(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
path = request.args.get('path')
if not path:
@@ -591,6 +627,7 @@ def remote_file_read(server_id):
@servers_bp.route('/<server_id>/files/write', methods=['POST'])
@developer_required
def remote_file_write(server_id):
_get_operable_server(server_id)
user_id = get_jwt_identity()
data = json_object(optional=True)
path = (data.get('path') or '').strip()
+9 -4
View File
@@ -1,4 +1,5 @@
"""SSO / OAuth API blueprint."""
import logging
from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify, session
from flask_jwt_extended import (
@@ -16,6 +17,8 @@ from app.error_reporting import record_unexpected
from app.exceptions import NotFoundError
from app.api._request import json_object
logger = logging.getLogger(__name__)
sso_bp = Blueprint('sso', __name__)
VALID_PROVIDERS = ('google', 'github', 'oidc', 'saml')
@@ -47,8 +50,9 @@ def authorize(provider):
try:
auth_url, state = sso_service.generate_auth_url(provider, redirect_uri)
return jsonify({'auth_url': auth_url, 'state': state}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
except Exception:
logger.exception('SSO authorize failed for %s', provider)
return jsonify({'error': 'Could not start single sign-on'}), 400
@sso_bp.route('/callback/<provider>', methods=['POST'])
@@ -169,8 +173,9 @@ def link_provider(provider):
try:
profile = sso_service.handle_oauth_callback(provider, code, state, redirect_uri)
except Exception as e:
return jsonify({'error': str(e)}), 400
except Exception:
logger.exception('SSO link callback failed for %s', provider)
return jsonify({'error': 'Single sign-on failed'}), 400
# Check if this identity is already linked to another user
existing = OAuthIdentity.query.filter_by(
+3 -2
View File
@@ -84,7 +84,7 @@ def check_update():
def parse_version(v):
try:
return tuple(int(x) for x in v.split('.'))
except:
except ValueError:
return (0, 0, 0)
if parse_version(latest_version) > parse_version(current_version):
@@ -96,7 +96,8 @@ def check_update():
else:
result['error'] = f'GitHub API error: {e.code}'
except Exception as e:
result['error'] = f'Failed to check for updates: {str(e)}'
current_app.logger.warning('Update check failed: %s', e)
result['error'] = 'Failed to check for updates'
# Cache the result
_update_cache['last_check'] = time.time()
+6 -2
View File
@@ -6,6 +6,7 @@ Routes are mounted at ``/api/v1/waf``. Reads require access to the target app;
mutations and install require an admin user (mirrors ``app/api/dns_zones.py``).
Service ``ValueError``s map to HTTP 400.
"""
import logging
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
@@ -14,6 +15,8 @@ from app.middleware.rbac import require_admin_user
from app.api._access import require_app
from app.api._request import json_object
logger = logging.getLogger(__name__)
waf_bp = Blueprint('waf', __name__)
@@ -47,8 +50,9 @@ def update_policy(app_id):
# ModSecurity isn't present on the host.
try:
apply_result = WafService.apply(app_id)
except Exception as e: # pragma: no cover - defensive
apply_result = {'success': False, 'error': str(e)}
except Exception: # pragma: no cover - defensive
logger.exception('WAF apply failed for app %s', app_id)
apply_result = {'success': False, 'error': 'Failed to apply WAF policy'}
response = policy.to_dict()
response['apply'] = apply_result
+1
View File
@@ -46,6 +46,7 @@ class BlueprintSpec:
CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = (
BlueprintSpec('app.api.auth', 'auth_bp', '/api/v1/auth'),
BlueprintSpec('app.api.agent_poll', 'agent_poll_bp', '/api/v1/agent'),
BlueprintSpec('app.api.agent_report', 'agent_report_bp', '/api/v1/agent'),
BlueprintSpec('app.api.linked_panel', 'linked_panel_bp', '/api/v1/linked-panel'),
BlueprintSpec('app.api.apps', 'apps_bp', '/api/v1/apps'),
BlueprintSpec('app.api.apps', 'apps_bp', '/api/v1/services', name='services'),
+16 -12
View File
@@ -1,6 +1,6 @@
{
"schema_version": 3,
"updated": "2026-10-23",
"updated": "2026-10-28",
"note": "Bundled fallback copy of the ServerKit extension registry index. The live index is fetched from SERVERKIT_REGISTRY_URL when configured; this file is used offline and in tests. It is a MIRROR of serverkit-extensions/index.json on main \u2014 do not hand-edit entries here, or it drifts from the artifacts it pins and installs fail checksum verification on exactly the panels that are already offline. Regenerate by copying that file's extensions array; tests/test_registry_bundled_index.py checks the two agree. Schema v3 adds optional per-entry `signature` + `publisher_key_id` (ed25519 minisign-style detached signature over the release zip, verified against the panel's pinned publisher keys at install \u2014 plan 55 D3). v1/v2 indexes without those fields remain valid; their entries are treated as unsigned.",
"extensions": [
{
@@ -299,7 +299,7 @@
"slug": "serverkit-wordpress",
"display_name": "WordPress",
"description": "The full WordPress suite: one-click site provisioning, a curated plugin library, environments and promote pipelines, update runs, security hardening, vulnerability scanning, analytics and reports. Offered during onboarding; uninstall it to slim the panel.",
"version": "1.0.4",
"version": "1.0.5",
"category": "integration",
"author": "ServerKit",
"first_party": true,
@@ -313,14 +313,14 @@
],
"min_panel_version": "1.11.18",
"max_panel_version": null,
"source": "https://github.com/jhd3197/serverkit-wordpress/releases/download/v1.0.4/serverkit-wordpress-1.0.4.zip",
"sha256": "dd755d298c86eec4da9e55760718141a2fe0248067b63d13730a32c7643773cf",
"source": "https://github.com/jhd3197/serverkit-wordpress/releases/download/v1.0.5/serverkit-wordpress-1.0.5.zip",
"sha256": "f541d6a9077146470a212c79149df25806a77bbc5bebefb296bf8e1d1dfef74a",
"repo": "https://github.com/jhd3197/serverkit-wordpress",
"homepage": "https://github.com/jhd3197/serverkit-wordpress",
"featured": true,
"feature_score": 80,
"logo": "assets/serverkit-wordpress/logo.png",
"signature": "RUSisf2r8uF4y2HOqYuZhdCDM07/Ft3TTMRCaJGbuGoUKPIlky587HkwFWe48XAm8DtPWAcIDUPMrBrHt86M7/A0yQ/Eb9qw7wA=",
"signature": "RUSisf2r8uF4ywWGOlXcW5biOIo140NvStZUiYr6N9bi4DIvkKbTu/7rDkNYnny9SvWGdrkqobVArkY89YDMIOuuQJKCYB0RYAs=",
"publisher_key_id": "serverkit-official"
},
{
@@ -405,23 +405,27 @@
{
"slug": "serverkit-faro",
"display_name": "Faro",
"description": "One-click Open in Faro. Adds a Connect with Faro button to Services, Domains, and WordPress sites that opens the Faro desktop client prefilled to SFTP into that site's web root, via faro:// deep links. No credentials ever leave the panel: a link only prefills Faro's connection editor for the user to review and connect.",
"version": "1.0.2",
"description": "Open in Faro and SSH access sharing. Connect with Faro buttons open the Faro desktop client prefilled for SFTP via faro:// links, and the Access pages let you give people time-boxed, revocable key-based access to managed servers: one-time links, or members whose devices you add and approve. Keys are installed and removed through the agent, including on bridge hosts.",
"version": "1.2.0",
"category": "utility",
"author": "Juan Denis",
"first_party": true,
"bundled": false,
"permissions": [],
"min_panel_version": "1.7.0",
"permissions": [
"db",
"agent.command:ssh:keys:add",
"agent.command:ssh:keys:remove"
],
"min_panel_version": "1.11.17",
"max_panel_version": null,
"source": "https://github.com/jhd3197/serverkit-faro/releases/download/v1.0.2/serverkit-faro-1.0.2.zip",
"sha256": "eba4a111bf7642fd4f72fbb491f78609f7663199d650950c21c88b706317f3b3",
"source": "https://github.com/jhd3197/serverkit-faro/releases/download/v1.2.0/serverkit-faro-1.2.0.zip",
"sha256": "b5bd467ecd86ccde6845b5e124590e12579d005f74ef92829a38afaefd1da196",
"repo": "https://github.com/jhd3197/serverkit-faro",
"homepage": "https://github.com/jhd3197/serverkit-faro",
"featured": true,
"feature_score": 100,
"logo": "assets/serverkit-faro/logo.png",
"signature": "RUSisf2r8uF4y0SdTvSDNBJHsTbpWumcmG7a9B7SoOsmhOOL3GhhExZJ1jdQpp2AwrPBtnTvwSb3f8C1f+J9OpG+2SspaHjSqA8=",
"signature": "RUSisf2r8uF4y63Lt0ub3cpRFaQvADy4FHpguNWqyjZZzVDISkdA1B3fq6JNP+rbNyP4KVOIv08ahrJbhcx1Rffct9rRLmjD2gQ=",
"publisher_key_id": "serverkit-official"
},
{
+2 -2
View File
@@ -20,7 +20,7 @@
"--border-strong": "#2c313b",
"--text": "#e9ebf0",
"--text-dim": "#9aa1af",
"--text-faint": "#646b7a",
"--text-faint": "#868e9c",
"--text-ghost": "#444b58",
"--green": "#3ddc97",
"--green-bg": "rgba(61,220,151,0.12)",
@@ -54,7 +54,7 @@
"--border-strong": "#cdd3e0",
"--text": "#161a23",
"--text-dim": "#515a6b",
"--text-faint": "#79818f",
"--text-faint": "#5f6777",
"--text-ghost": "#a6adba",
"--green": "#3ddc97",
"--green-bg": "rgba(61,220,151,0.12)",
+6
View File
@@ -57,6 +57,12 @@ class PermissionDeniedError(ApplicationError, PermissionError):
default_message = 'Access denied'
class PayloadTooLargeError(ApplicationError):
status_code = 413
code = 'payload_too_large'
default_message = 'Payload too large'
class NotFoundError(ApplicationError, LookupError):
status_code = 404
code = 'not_found'
+4 -2
View File
@@ -534,7 +534,7 @@ def _notify_fleet_alerts(opened, resolved):
'metric': alert.metric,
'value': alert.value,
'threshold': alert.threshold,
'message': (
'message': alert.detail or (
f'{hostname}: {alert.metric} averaged {alert.value} over '
f'{alert.duration_seconds}s, past the '
f'{alert.severity} threshold of {alert.threshold}.'),
@@ -555,7 +555,9 @@ def _notify_fleet_alerts(opened, resolved):
'hostname': hostname,
'alert_type': f'{alert.metric} recovered',
'metric': alert.metric,
'message': (f'{hostname}: {alert.metric} is back under its '
'message': (f'{hostname}: {alert.metric} recovered.'
if alert.detail else
f'{hostname}: {alert.metric} is back under its '
f'threshold.'),
},
)
+9 -1
View File
@@ -2,6 +2,10 @@
from flask import Flask
# sha256 of the build-injected import map (frontend/vite.config.js, from
# src/plugins/runtime/vendorManifest.js). test_security_headers recomputes it.
VENDOR_IMPORTMAP_HASH = 'sha256-lIJXjhqB4GwFLcjRTSjM91Q7vwXxH4Wbcn475CzkW4U='
def register_security_headers(app: Flask):
"""Register security headers as an after_request handler."""
@@ -37,9 +41,13 @@ def register_security_headers(app: Flask):
"form-action 'self' https://github.com",
]
else:
# style-src keeps 'unsafe-inline' because React renders style="" attributes;
# script-src has no 'unsafe-inline'/'unsafe-eval': the FOUC snippet is
# /theme-init.js; the one inline script (build-injected vendor importmap)
# is allowed by hash; blob: is for runtime extensions (plugins/runtime/loader.js).
csp_directives = [
"default-src 'self'",
"script-src 'self' 'unsafe-inline' 'unsafe-eval'",
"script-src 'self' '%s' blob:" % VENDOR_IMPORTMAP_HASH,
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self'",
+8 -3
View File
@@ -15,8 +15,13 @@ def issue_session_tokens(user_id):
create_refresh_token(identity=user_id, additional_claims=claims))
def validate_session_claims(claims, *, allow_pending=False, token_type='access'):
"""Return the live user only for an unexpired, unrevoked session JWT."""
def validate_session_claims(claims, *, allow_pending=False, token_type='access',
check_expiry=True):
"""Return the live user only for an unexpired, unrevoked session JWT.
check_expiry=False is for re-checking an already-authenticated live
connection: its token was unexpired at connect, and revocation, the
auth_version bump and deactivation still end it."""
from app.models import User, RevokedSession
if not isinstance(claims, dict) or claims.get('type') != token_type:
@@ -29,7 +34,7 @@ def validate_session_claims(claims, *, allow_pending=False, token_type='access')
if RevokedSession.query.filter_by(session_id=session_id).first() is not None:
return None
expiration = claims.get('exp')
if not isinstance(expiration, (int, float)) or expiration <= time.time():
if not isinstance(expiration, (int, float)) or (check_expiry and expiration <= time.time()):
return None
try:
user_id = int(claims['sub'])
+3
View File
@@ -49,6 +49,8 @@ class MetricAlert(db.Model):
threshold = db.Column(db.Float) # the threshold exceeded
duration_seconds = db.Column(db.Integer) # how long it was exceeded
detail = db.Column(db.Text) # human message for offline / service-check alerts
status = db.Column(db.String(20), default='active', index=True) # active, acknowledged, resolved
acknowledged_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True, index=True)
@@ -67,6 +69,7 @@ class MetricAlert(db.Model):
'value': self.value,
'threshold': self.threshold,
'duration_seconds': self.duration_seconds,
'detail': self.detail,
'status': self.status,
'acknowledged_by': self.acknowledged_by,
'created_at': self.created_at.isoformat() if self.created_at else None,
+48 -1
View File
@@ -1,3 +1,5 @@
import hashlib
import hmac
import uuid
import secrets
from datetime import datetime
@@ -124,6 +126,17 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model):
allow_agent_update_observed = db.Column(db.Boolean, nullable=False,
default=False, server_default='0')
# Agent permission level (monitor|protect|full). REPORTED BY THE AGENT
# only -- no panel API writes it. NULL = unknown/legacy, treated as full.
# requested_permission_level is what the install command asked for, kept
# only to flag a mismatch with what the agent reports.
permission_level = db.Column(db.String(16), nullable=True)
permission_level_updated_at = db.Column(db.DateTime, nullable=True)
requested_permission_level = db.Column(db.String(16), nullable=True)
last_report_at = db.Column(db.DateTime, nullable=True)
report_interval_seconds = db.Column(db.Integer, nullable=True)
service_checks = db.Column(db.JSON, nullable=True) # latest state per check
@property
def is_managed(self):
"""False only for observed boxes."""
@@ -203,9 +216,17 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model):
api_secret = secrets.token_urlsafe(32)
return api_key, api_secret
@staticmethod
def registration_token_digest(token):
"""SHA-256 of a registration token. The token is 256 random bits, so a
slow password hash buys nothing, and a fast exact digest lets the
public /register route look one row up instead of running a
deliberately slow check against every pending server."""
return 'sha256$' + hashlib.sha256(token.encode()).hexdigest()
def set_registration_token(self, token):
"""Hash and store registration token"""
self.registration_token_hash = generate_password_hash(token)
self.registration_token_hash = Server.registration_token_digest(token)
def verify_registration_token(self, token):
"""Verify a registration token"""
@@ -213,8 +234,28 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model):
return False
if self.registration_token_expires and datetime.utcnow() > self.registration_token_expires:
return False
if self.registration_token_hash.startswith('sha256$'):
return hmac.compare_digest(self.registration_token_hash,
Server.registration_token_digest(token))
# Tokens issued before the digest switch; they expire on their own.
return check_password_hash(self.registration_token_hash, token)
@staticmethod
def find_by_registration_token(token):
"""The pending server this token pairs, or None."""
server = Server.query.filter_by(
registration_token_hash=Server.registration_token_digest(token)).first()
if server is not None:
return server if server.verify_registration_token(token) else None
now = datetime.utcnow()
legacy = Server.query.filter(
Server.registration_token_hash.isnot(None),
~Server.registration_token_hash.startswith('sha256$'),
db.or_(Server.registration_token_expires.is_(None),
Server.registration_token_expires > now),
).all()
return next((s for s in legacy if s.verify_registration_token(token)), None)
def set_api_key(self, api_key):
"""Hash and store API key"""
self.api_key_hash = generate_password_hash(api_key)
@@ -460,6 +501,12 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model):
'last_error': self.last_error,
'management_mode': self.management_mode or 'managed',
'allow_agent_update_observed': bool(self.allow_agent_update_observed),
'permission_level': self.permission_level,
'permission_level_effective': self.permission_level or 'full',
'permission_level_updated_at': self.permission_level_updated_at.isoformat() if self.permission_level_updated_at else None,
'requested_permission_level': self.requested_permission_level,
'last_report_at': self.last_report_at.isoformat() if self.last_report_at else None,
'service_checks': self.service_checks or [],
'onboarding_state': self.onboarding_state,
'onboarding_updated_at': self.onboarding_updated_at.isoformat() if self.onboarding_updated_at else None,
'agent_version': self.agent_version,
@@ -0,0 +1,223 @@
"""Agent-reported health: permission level, service checks, silence, alerts.
Everything here consumes what the agent REPORTS (registration, auth, heartbeat,
or the monitor-mode ``/agent/report`` POST). Alerts reuse ``MetricAlert`` and the
fleet notification path; one active row per (server, metric) de-duplicates.
"""
import hashlib
import hmac
import logging
import time
from datetime import datetime, timedelta
from app import db
from app.models.audit_log import AuditLog
from app.models.metric_alert import MetricAlert
from app.models.server import Server
from app.services import permission_levels
from app.services.nonce_service import nonce_service
logger = logging.getLogger(__name__)
MIN_SILENCE_SECONDS = 180 # monitor agents: offline after max(3 min, 3x interval)
DEFAULT_INTERVAL_SECONDS = 60
DEFAULT_INTERVAL = DEFAULT_INTERVAL_SECONDS
OFFLINE_METRIC = 'offline'
OPEN = ('active', 'acknowledged')
BAD = ('down',)
def _notify(opened=(), resolved=()):
if not opened and not resolved:
return
try:
from app.jobs.builtin_handlers import _notify_fleet_alerts
_notify_fleet_alerts(list(opened), list(resolved))
except Exception:
logger.exception('Could not notify agent health alerts')
def _open_alert(server, metric, detail):
"""Open an alert unless one is already open. Returns it if newly opened."""
if MetricAlert.query.filter(MetricAlert.server_id == server.id,
MetricAlert.metric == metric,
MetricAlert.status.in_(OPEN)).first():
return None
alert = MetricAlert(server_id=server.id, metric=metric, severity='critical',
detail=detail, status='active')
db.session.add(alert)
return alert
def _resolve_alerts(server, metric):
rows = MetricAlert.query.filter(MetricAlert.server_id == server.id,
MetricAlert.metric == metric,
MetricAlert.status.in_(OPEN)).all()
for row in rows:
row.status = 'resolved'
row.resolved_at = datetime.utcnow()
return rows
def record_level(server, reported):
"""Persist a level reported by the agent; audit when it changes.
Invalid/missing values are ignored. Escalations (monitor->protect->full) are
logged like any change but flagged, since they mean someone re-ran the
local confirmation on the box.
"""
level = permission_levels.normalize(reported)
if level is None:
return
old = server.permission_level
if old == level:
return
server.permission_level = level
server.permission_level_updated_at = datetime.utcnow()
AuditLog.log(
'server.permission_level_changed', target_type='server', target_id=server.id,
details={'server_id': server.id, 'from': old, 'to': level,
'escalation': permission_levels.is_escalation(old, level),
'source': 'agent_report'})
logger.warning('Server %s reported permission level %s -> %s', server.id, old, level)
def record_service_checks(server, checks):
"""Store the latest per-check state and open/resolve alerts on transitions."""
if not isinstance(checks, list):
return
previous = {c.get('name'): c.get('status') for c in (server.service_checks or [])}
clean, opened, resolved = [], [], []
for raw in checks[:50]:
if not isinstance(raw, dict) or not isinstance(raw.get('name'), str):
continue
item = {k: (str(raw.get(k))[:200] if raw.get(k) is not None else None)
for k in ('name', 'kind', 'status', 'detail', 'checked_at')}
item['name'] = item['name'][:60]
if item['status'] not in ('up', 'down', 'degraded', 'unknown'):
item['status'] = 'unknown'
clean.append(item)
metric = f"svc:{item['name']}"[:20]
if item['status'] == 'down':
alert = _open_alert(
server, metric,
f"{server.name}: service '{item['name']}' is down since "
f"{datetime.utcnow():%Y-%m-%d %H:%M} UTC"
+ (f" ({item['detail']})" if item['detail'] else ''))
if alert:
opened.append(alert)
elif item['status'] == 'up' or (item['status'] == 'degraded'
and previous.get(item['name']) == 'down'):
resolved += _resolve_alerts(server, metric)
server.service_checks = clean
db.session.flush()
_notify(opened, resolved)
def mark_offline(server, reason):
"""Open the (de-duplicated) offline alert. Caller commits."""
since = server.last_report_at or server.last_seen or datetime.utcnow()
alert = _open_alert(
server, OFFLINE_METRIC,
f"{server.name} is offline since {since:%Y-%m-%d %H:%M} UTC: {reason}")
db.session.flush()
_notify([alert] if alert else [])
def mark_online(server):
resolved = _resolve_alerts(server, OFFLINE_METRIC)
db.session.flush()
_notify(resolved=resolved)
def silence_limit(server):
interval = server.report_interval_seconds or DEFAULT_INTERVAL_SECONDS
return timedelta(seconds=max(MIN_SILENCE_SECONDS, 3 * interval))
def sweep_silent_reporters(now=None):
"""Flip report-only (monitor) servers offline once their reports stop.
Reports are not a socket, so the registry's heartbeat reaper never sees
them. Only servers that have ever reported are considered.
"""
now = now or datetime.utcnow()
flipped = []
for server in Server.query.filter(Server.permission_level == 'monitor',
Server.last_report_at.isnot(None),
Server.status != 'offline').all():
if now - server.last_report_at > silence_limit(server):
server.status = 'offline'
server.last_error = 'Agent stopped reporting'
mark_offline(server, 'no report received')
flipped.append(server.id)
if flipped:
db.session.commit()
return flipped
def authenticate_report(raw, headers, max_skew):
"""Return the Server for a validly signed report request, else None."""
key = headers.get('X-Agent-Key') or ''
ts = headers.get('X-Timestamp') or ''
nonce = headers.get('X-Nonce') or ''
signature = headers.get('X-Signature') or ''
if not (key and ts and signature) or len(nonce) < 32:
return None
try:
if abs(time.time() - int(ts)) > max_skew:
return None
except ValueError:
return None
prefix = key[:12]
server = Server.query.filter(
(Server.api_key_prefix == prefix) | (Server.api_key_pending_prefix == prefix)
).first()
if not server:
return None
pending = (server.api_key_pending_prefix == prefix and server.api_key_prefix != prefix
and server.api_key_rotation_expires
and datetime.utcnow() <= server.api_key_rotation_expires)
secret = server.get_pending_api_secret() if pending else server.get_api_secret()
if not secret:
return None
message = f"{ts}.{nonce}.{hashlib.sha256(raw).hexdigest()}"
expected = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected):
return None
# Consume the nonce only after the signature proves valid.
if not nonce_service.check_and_record(server.id, nonce):
return None
return server
def ingest_report(server, level, body):
"""Apply a verified report to the server row; returns the interval in use."""
interval = body.get('interval_seconds')
interval = interval if isinstance(interval, int) and 5 <= interval <= 3600 else DEFAULT_INTERVAL
now = datetime.utcnow()
was_offline = server.status != 'online'
server.status = 'online'
server.last_error = None
server.last_seen = now
server.last_report_at = now
server.report_interval_seconds = interval
if isinstance(body.get('agent_version'), str):
server.agent_version = body['agent_version'][:20]
record_level(server, level)
record_service_checks(server, body.get('service_checks'))
if was_offline:
mark_online(server)
db.session.commit()
metrics = body.get('metrics')
if isinstance(metrics, dict):
from app.services.server_metrics_service import ServerMetricsService
ServerMetricsService.record_metrics(server.id, {
**{k: metrics.get(k) for k in ('cpu_percent', 'memory_percent', 'disk_percent')},
'extra': {k: metrics.get(k) for k in ('uptime_seconds', 'load1')},
})
return interval
+36 -1
View File
@@ -22,6 +22,7 @@ from collections import defaultdict
from app import db
from app.models.server import Server, ServerCommand, AgentSession
from app.services import permission_levels
# ---------------------------------------------------------------------------
# Per-IP auth rate limiter — transport-neutral state shared by the WS
@@ -245,6 +246,12 @@ class AgentRegistry:
self._agents.pop(server_id, None)
self._socket_to_server.pop(socket_id, None)
# Report-only (monitor) agents hold no socket; sweep them too.
if self._app is not None:
with self._app.app_context():
from app.services import agent_health_service
agent_health_service.sweep_silent_reporters()
except Exception as e:
logger.error("Error in heartbeat checker: %s", e)
@@ -279,6 +286,8 @@ class AgentRegistry:
if server:
server.status = 'offline'
server.last_error = 'Agent heartbeat timeout'
from app.services import agent_health_service
agent_health_service.mark_offline(server, 'heartbeat timeout')
db.session.commit()
# Mark session as inactive
@@ -392,6 +401,8 @@ class AgentRegistry:
# even for healthy connected agents.
if ip_address and ip_address != 'unknown':
server.ip_address = ip_address
from app.services import agent_health_service
agent_health_service.mark_online(server)
db.session.commit()
# Create session record
@@ -519,6 +530,8 @@ class AgentRegistry:
server.last_seen = now
if server.status != 'online':
server.status = 'online'
from app.services import agent_health_service
agent_health_service.mark_online(server)
db.session.commit()
# Update session latency
@@ -589,6 +602,12 @@ class AgentRegistry:
# Check permissions
server = Server.query.get(server_id)
# Defence in depth: never send what the agent's reported level refuses.
refused = permission_levels.refusal(
server.permission_level if server else None, action)
if refused:
return {'success': False, 'error': refused, 'code': 'LEVEL_DENIED'}
if server and not server.has_permission(action):
return {
'success': False,
@@ -863,13 +882,15 @@ class AgentRegistry:
# in-memory state — the adapter must not report success.
if not session_token:
return None, server, 'registration_failed'
self.record_agent_health(server.id, payload.get('permission_level'))
logger.info("Agent %s authenticated successfully from %s (%s)",
agent_id, ip_address, transport)
return session_token, server, None
def ingest_agent_state(self, agent, metrics=None, sysinfo=None,
capabilities=None):
capabilities=None, permission_level=None,
service_checks=None):
"""One ingest path for agent-reported state on BOTH transports.
Owns the capability side-effects (the WireGuard tunnel reconcile
@@ -882,6 +903,20 @@ class AgentRegistry:
self.update_system_info(agent.server_id, sysinfo)
if capabilities:
self.update_capabilities(agent.server_id, capabilities)
if permission_level is not None or service_checks is not None:
self.record_agent_health(agent.server_id, permission_level, service_checks)
def record_agent_health(self, server_id, permission_level=None, service_checks=None):
from app.services import agent_health_service
try:
server = Server.query.get(server_id)
if server:
agent_health_service.record_level(server, permission_level)
agent_health_service.record_service_checks(server, service_checks)
db.session.commit()
except Exception:
logger.exception("Error recording agent health")
db.session.rollback()
def verify_agent_auth(
self,
+4 -8
View File
@@ -10,14 +10,13 @@ from pathlib import Path
import threading
import time
import uuid
import schedule
from app import paths
from app.utils import backup_crypto
from app.utils.config_store import load_json_config, save_json_config
from app.utils.formatting import format_bytes
from app.utils.system import (
is_command_available, run_checked, run_from_gzip, run_to_gzip,
is_command_available, run_checked, run_from_gzip, run_to_gzip, secret_env,
)
from app.services.telemetry_service import TelemetryService, generate_correlation_id
from app.services import backup_schedule_service
@@ -197,13 +196,12 @@ class BackupService:
cmd = ['mysqldump']
if config.get('user'):
cmd.extend(['-u', config['user']])
if config.get('password'):
cmd.append(f"-p{config['password']}")
if config.get('host'):
cmd.extend(['-h', config['host']])
cmd.append(db_name)
result = run_to_gzip(cmd, backup_file)
result = run_to_gzip(cmd, backup_file,
env=secret_env(MYSQL_PWD=config.get('password')))
if not result['success']:
return {'success': False, 'error': result['error']}
@@ -470,13 +468,11 @@ class BackupService:
cmd = ['mysql']
if user:
cmd.extend(['-u', user])
if password:
cmd.append(f"-p{password}")
if host:
cmd.extend(['-h', host])
cmd.append(db_name)
result = run_from_gzip(cmd, backup_path)
result = run_from_gzip(cmd, backup_path, env=secret_env(MYSQL_PWD=password))
elif db_type == 'postgresql':
if not is_command_available('psql'):
+6 -4
View File
@@ -19,10 +19,9 @@ import logging
import re
from datetime import datetime
import requests
from app import db
from app.models.chat_webhook import ChatWebhookConnection
from app.utils import safe_http
from app.utils.crypto import encrypt_secret
logger = logging.getLogger(__name__)
@@ -405,8 +404,11 @@ class ChatWebhookService:
headers[SIGNATURE_HEADER] = 'sha256=' + signature
try:
resp = requests.post(url, data=body, headers=headers,
timeout=_REQUEST_TIMEOUT)
resp = safe_http.post(url, data=body, headers=headers,
timeout=_REQUEST_TIMEOUT)
except safe_http.UnsafeURLError as exc:
# Non-retryable: the URL itself is the problem, retrying can't help.
return DeliveryResult.skipped(f'webhook url refused: {exc}')
except Exception as exc: # network error -> retryable failure
return DeliveryResult.failed(str(exc))
+38 -30
View File
@@ -16,6 +16,7 @@ from typing import Dict, List, Optional
from datetime import datetime
import json
from app.utils.config_store import quarantine, save_json_config
from app.utils.system import run_checked, unit_is_active
# Path for storing job metadata
@@ -85,7 +86,12 @@ class CronService:
"""Load job metadata from file."""
try:
return cls._load_jobs_metadata_strict()
except (json.JSONDecodeError, IOError, ValueError):
except (json.JSONDecodeError, ValueError):
# Callers save what they load: without moving the file aside the
# next add would replace every job's metadata with the new one.
quarantine(JOBS_FILE)
return {'jobs': {}}
except IOError:
return {'jobs': {}}
@classmethod
@@ -103,9 +109,10 @@ class CronService:
@classmethod
def _save_jobs_metadata(cls, data: Dict):
"""Save job metadata to file."""
cls._ensure_data_dir()
with open(JOBS_FILE, 'w') as f:
json.dump(data, f, indent=2)
# Atomic: a full disk or a kill mid-write must not truncate the file.
result = save_json_config(JOBS_FILE, data)
if not result['success']:
raise IOError(result['error'])
@classmethod
def is_linux(cls) -> bool:
@@ -273,6 +280,8 @@ class CronService:
minute, hour, day, month, weekday, command = match.groups()
schedule = f"{minute} {hour} {day} {month} {weekday}"
# cron turns a bare % into a newline; lines we write escape it.
command = command.replace('\\%', '%')
return {
'id': f"cron_{index}",
@@ -325,7 +334,7 @@ class CronService:
return parsed['command'] in {
command,
f"{SHIM_PATH} {job_id} -- {command}",
cls._crontab_command(command, True, job_id),
cls._wrapped_command(command, True, job_id),
}
@classmethod
@@ -442,7 +451,7 @@ class CronService:
clean_name = re.sub(r'\s+', ' ', str(name)).strip()
if clean_name:
comment += f" ({clean_name})"
new_line = f"{schedule} {command}"
new_line = f"{schedule} {cls._crontab_command(command, False, job_id)}"
new_crontab = f"{current_crontab.rstrip()}\n{comment}\n{new_line}\n"
failure = cls._install_crontab(new_crontab)
@@ -656,17 +665,8 @@ class CronService:
current = cls._read_crontab()
if current is not None:
tracked = bool(job_data.get('tracked', False))
old_line = f"{old_schedule} {cls._crontab_command(old_command, tracked, job_id)}"
new_line = f"{new_schedule} {cls._crontab_command(new_command, tracked, job_id)}"
lines = current.split('\n')
new_lines = []
for line in lines:
if old_line in line:
new_lines.append(new_line)
else:
new_lines.append(line)
failure = cls._install_crontab('\n'.join(new_lines))
failure = cls._rewrite_job_line(old_schedule, old_command, job_id, new_line)
if failure:
return failure
@@ -759,18 +759,22 @@ class CronService:
# ------------------------------------------------------------------ #
@classmethod
def _crontab_command(cls, command: str, tracked: bool, job_id: str) -> str:
"""Build the crontab command for a job.
Tracked jobs are wrapped by the serverkit-cron-run shim so every run
records its exit code + output tail; untracked jobs are byte-identical
to the bare command (an untracked line is indistinguishable from a
hand-written one)."""
def _wrapped_command(cls, command: str, tracked: bool, job_id: str) -> str:
"""The command a job's line runs: tracked jobs are wrapped by the
serverkit-cron-run shim so every run records its exit code + output
tail; untracked jobs run the bare command."""
if not tracked:
return command
python = sys.executable or 'python3'
return f"{python} {SHIM_PATH} {job_id} -- {command}"
@classmethod
def _crontab_command(cls, command: str, tracked: bool, job_id: str) -> str:
"""The job's command as written into the crontab. An unescaped % ends
the command there and feeds the rest to it as stdin, so
`date +%F` would run as `date +`."""
return cls._wrapped_command(command, tracked, job_id).replace('%', '\\%')
@classmethod
def get_job(cls, job_id: str) -> Optional[Dict]:
"""Return a single job's metadata (with a normalized `tracked` flag), or
@@ -803,9 +807,8 @@ class CronService:
if cls.is_linux() and enabled != was_tracked:
schedule = job_data.get('schedule', '')
command = job_data.get('command', '')
old_line = f"{schedule} {cls._crontab_command(command, was_tracked, job_id)}"
new_line = f"{schedule} {cls._crontab_command(command, enabled, job_id)}"
err = cls._replace_crontab_line(old_line, new_line)
err = cls._rewrite_job_line(schedule, command, job_id, new_line)
if err is not None:
return err
@@ -822,14 +825,19 @@ class CronService:
}
@classmethod
def _replace_crontab_line(cls, old_line: str, new_line: str) -> Optional[Dict]:
"""Swap one line in the current user's crontab. Returns None on success
or an error dict. Linux-only (callers guard with is_linux)."""
def _rewrite_job_line(cls, schedule: str, command: str, job_id: str,
new_line: str) -> Optional[Dict]:
"""Replace the job's crontab line (found by parsing, so legacy unescaped
and escaped lines both match), keeping a disabled job commented out.
Returns None on success or an error dict. Linux-only."""
current = cls._read_crontab()
if current is None:
return None
lines = current.split('\n')
new_lines = [new_line if line == old_line else line for line in lines]
new_lines = [
(f"# {new_line}" if line.lstrip().startswith('#') else new_line)
if cls._line_is_job(line, schedule, command, job_id) else line
for line in current.split('\n')
]
return cls._install_crontab('\n'.join(new_lines))
# ------------------------------------------------------------------ #
+57 -10
View File
@@ -7,7 +7,7 @@ import json
from datetime import datetime
from app import paths
from app.utils.system import run_checked, unit_is_active
from app.utils.system import run_checked, secret_env, unit_is_active
def _validate_identifier(name: str, max_length: int = 64) -> bool:
@@ -15,6 +15,16 @@ def _validate_identifier(name: str, max_length: int = 64) -> bool:
return bool(re.match(r'^[a-zA-Z0-9_$]{1,}$', name)) and len(name) <= max_length
_INVALID_ID = {'success': False, 'error': 'Invalid identifier: only alphanumeric characters and underscores allowed'}
_INVALID_PRIVILEGES = {'success': False, 'error': 'Invalid privileges: use privilege keywords such as ALL or SELECT, INSERT'}
def _validate_privileges(privileges: str) -> bool:
"""A comma list of privilege keywords (`ALL`, `SELECT, INSERT`): letters and
spaces only, so it can sit unquoted in GRANT/REVOKE."""
return bool(re.fullmatch(r'[A-Za-z ]+(,[A-Za-z ]+)*', privileges or ''))
class DatabaseService:
"""Service for managing MySQL/MariaDB and PostgreSQL databases.
@@ -252,6 +262,8 @@ class DatabaseService:
return {'success': False, 'error': 'Invalid identifier: only alphanumeric characters and underscores allowed'}
if not _validate_identifier(host):
return {'success': False, 'error': 'Invalid host identifier'}
if not _validate_privileges(privileges):
return _INVALID_PRIVILEGES
query = f"GRANT {privileges} ON `{database}`.* TO '{username}'@'{host}'; FLUSH PRIVILEGES;"
result = DatabaseService.mysql_execute(query, root_password=root_password)
return result
@@ -265,6 +277,8 @@ class DatabaseService:
return {'success': False, 'error': 'Invalid identifier: only alphanumeric characters and underscores allowed'}
if not _validate_identifier(host):
return {'success': False, 'error': 'Invalid host identifier'}
if not _validate_privileges(privileges):
return _INVALID_PRIVILEGES
query = f"REVOKE {privileges} ON `{database}`.* FROM '{username}'@'{host}'; FLUSH PRIVILEGES;"
result = DatabaseService.mysql_execute(query, root_password=root_password)
return result
@@ -448,6 +462,10 @@ class DatabaseService:
@staticmethod
def pg_create_database(name, owner=None, encoding='UTF8'):
"""Create a PostgreSQL database."""
if not _validate_identifier(name) or (owner and not _validate_identifier(owner)):
return _INVALID_ID
if not _validate_identifier(encoding):
return {'success': False, 'error': 'Invalid encoding identifier'}
query = f"CREATE DATABASE \"{name}\" ENCODING '{encoding}'"
if owner:
query += f" OWNER \"{owner}\""
@@ -495,20 +513,30 @@ class DatabaseService:
@staticmethod
def pg_create_user(username, password):
"""Create a PostgreSQL user."""
if not _validate_identifier(username):
return _INVALID_ID
# Standard-conforming strings: doubling the quote is the whole escape.
escaped = password.replace("'", "''")
result = DatabaseService.pg_execute(
f"CREATE USER \"{username}\" WITH PASSWORD '{password}';"
f"CREATE USER \"{username}\" WITH PASSWORD '{escaped}';"
)
return result
@staticmethod
def pg_drop_user(username):
"""Drop a PostgreSQL user."""
if not _validate_identifier(username):
return _INVALID_ID
result = DatabaseService.pg_execute(f'DROP USER IF EXISTS "{username}";')
return result
@staticmethod
def pg_grant_privileges(username, database, privileges='ALL'):
"""Grant privileges to a PostgreSQL user."""
if not _validate_identifier(username) or not _validate_identifier(database):
return _INVALID_ID
if not _validate_privileges(privileges):
return _INVALID_PRIVILEGES
result = DatabaseService.pg_execute(
f'GRANT {privileges} PRIVILEGES ON DATABASE "{database}" TO "{username}";'
)
@@ -517,11 +545,30 @@ class DatabaseService:
@staticmethod
def pg_revoke_privileges(username, database, privileges='ALL'):
"""Revoke privileges from a PostgreSQL user."""
if not _validate_identifier(username) or not _validate_identifier(database):
return _INVALID_ID
if not _validate_privileges(privileges):
return _INVALID_PRIVILEGES
result = DatabaseService.pg_execute(
f'REVOKE {privileges} PRIVILEGES ON DATABASE "{database}" FROM "{username}";'
)
return result
@staticmethod
def create_database_user(engine, name, password, host='localhost', root_password=None):
"""Create a user named after database *name* with ALL on it. Returns the
first failing step's result, so callers never hand out credentials for
a user that was not created."""
if engine == 'mysql':
result = DatabaseService.mysql_create_user(name, password, host, root_password)
if result.get('success'):
result = DatabaseService.mysql_grant_privileges(name, name, 'ALL', host, root_password)
else:
result = DatabaseService.pg_create_user(name, password)
if result.get('success'):
result = DatabaseService.pg_grant_privileges(name, name, 'ALL')
return result
@staticmethod
def pg_backup(database, output_path=None):
"""Backup a PostgreSQL database."""
@@ -1153,9 +1200,10 @@ class DatabaseService:
try:
cmd = ['docker', 'exec']
# Use MYSQL_PWD env var to avoid passing password on CLI
# Bare `-e MYSQL_PWD`: docker reads the value from our env, so the
# password never sits in the docker command line.
if password:
cmd.extend(['-e', f'MYSQL_PWD={password}'])
cmd.extend(['-e', 'MYSQL_PWD'])
cmd.extend([container_name, DatabaseService._docker_db_client(container_name), '-u', user])
@@ -1167,7 +1215,7 @@ class DatabaseService:
cmd.extend(['-e', query])
return run_checked(cmd, timeout=timeout)
return run_checked(cmd, timeout=timeout, env=secret_env(MYSQL_PWD=password))
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -1189,7 +1237,7 @@ class DatabaseService:
cmd = ['docker', 'exec']
# PGPASSWORD via the exec environment, never on the command line.
if password:
cmd.extend(['-e', f'PGPASSWORD={password}'])
cmd.extend(['-e', 'PGPASSWORD'])
cmd.extend([container_name, 'psql', '-U', user,
'-d', database or 'postgres',
'-v', 'ON_ERROR_STOP=1',
@@ -1198,7 +1246,7 @@ class DatabaseService:
# tab, not the '|' default: the callers that parse this split
# on tabs, and a '|' is legal inside a value.
cmd.extend(['-F', '\t'])
return run_checked(cmd, timeout=timeout)
return run_checked(cmd, timeout=timeout, env=secret_env(PGPASSWORD=password))
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -1291,9 +1339,8 @@ class DatabaseService:
start_time = time.time()
cmd = ['docker', 'exec']
# Use MYSQL_PWD env var to avoid passing password on CLI
if password:
cmd.extend(['-e', f'MYSQL_PWD={password}'])
cmd.extend(['-e', 'MYSQL_PWD'])
cmd.extend([container_name, DatabaseService._docker_db_client(container_name), '-u', user])
cmd.extend([
'-D', database,
@@ -1301,7 +1348,7 @@ class DatabaseService:
'--batch'
])
result = run_checked(cmd, timeout=timeout)
result = run_checked(cmd, timeout=timeout, env=secret_env(MYSQL_PWD=password))
execution_time = time.time() - start_time
if not result['success']:
+19 -24
View File
@@ -8,7 +8,7 @@ Supports WordPress-specific features like URL search-replace and data anonymizat
import os
import subprocess
from app.utils.system import run_checked, run_from_gzip, run_to_gzip
from app.utils.system import run_checked, run_from_gzip, run_to_gzip, secret_env
import shutil
import json
import re
@@ -38,13 +38,11 @@ class DatabaseSyncService:
"""Execute a MySQL command."""
try:
cmd = ['mysql', '-h', host, '-u', user]
if password:
cmd.append(f'-p{password}')
if database:
cmd.extend(['-D', database])
cmd.extend(['-e', command])
return run_checked(cmd, timeout=300)
return run_checked(cmd, timeout=300, env=secret_env(MYSQL_PWD=password))
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -85,8 +83,6 @@ class DatabaseSyncService:
try:
# Build mysqldump command
cmd = ['mysqldump', '-h', host, '-u', user]
if password:
cmd.append(f'-p{password}')
# Add options for consistent snapshot
cmd.extend([
@@ -105,13 +101,13 @@ class DatabaseSyncService:
# Execute dump
if compress:
result = run_to_gzip(cmd, file_path)
result = run_to_gzip(cmd, file_path, env=secret_env(MYSQL_PWD=password))
if not result['success']:
return {'success': False, 'error': f"mysqldump failed: {result['error']}"}
else:
with open(file_path, 'w') as f:
result = run_checked(cmd, stdout=f, stderr=subprocess.PIPE,
timeout=None)
timeout=None, env=secret_env(MYSQL_PWD=password))
if not result['success']:
return {'success': False,
'error': f"mysqldump failed: {result['error']}"}
@@ -191,17 +187,17 @@ class DatabaseSyncService:
# Build mysql import command
cmd = ['mysql', '-h', host, '-u', user]
if password:
cmd.append(f'-p{password}')
cmd.append(target_db)
# Handle compressed files
if file_path.endswith('.gz'):
# 30 min bound for large DBs
result = run_from_gzip(cmd, file_path, timeout=1800)
result = run_from_gzip(cmd, file_path, timeout=1800,
env=secret_env(MYSQL_PWD=password))
else:
with open(file_path, 'r') as f:
result = run_checked(cmd, stdin=f, timeout=1800)
result = run_checked(cmd, stdin=f, timeout=1800,
env=secret_env(MYSQL_PWD=password))
if not result['success']:
return {'success': False, 'error': result['error']}
@@ -571,8 +567,6 @@ class DatabaseSyncService:
try:
# Build mysqldump command to run inside container
dump_cmd = ['mysqldump', '-u', db_user]
if db_password:
dump_cmd.append(f'-p{db_password}')
dump_cmd.extend([
'--single-transaction',
'--routines',
@@ -587,17 +581,19 @@ class DatabaseSyncService:
dump_cmd.append(db_name)
# Run via docker compose exec
full_cmd = ['docker', 'compose', '-f', compose_path, 'exec', '-T', 'db'] + dump_cmd
full_cmd = (['docker', 'compose', '-f', compose_path, 'exec', '-T']
+ (['-e', 'MYSQL_PWD'] if db_password else []) + ['db'] + dump_cmd)
env = secret_env(MYSQL_PWD=db_password)
if compress:
result = run_to_gzip(full_cmd, output_path, timeout=600)
result = run_to_gzip(full_cmd, output_path, timeout=600, env=env)
if not result['success']:
return {'success': False,
'error': f"Container mysqldump failed: {result['error']}"}
else:
with open(output_path, 'w') as f:
result = run_checked(full_cmd, stdout=f, stderr=subprocess.PIPE,
timeout=600)
timeout=600, env=env)
if not result['success']:
if os.path.exists(output_path):
os.remove(output_path)
@@ -647,17 +643,16 @@ class DatabaseSyncService:
try:
# Build mysql import command
import_cmd = ['docker', 'compose', '-f', compose_path, 'exec', '-T', 'db',
'mysql', '-u', db_user]
if db_password:
import_cmd.append(f'-p{db_password}')
import_cmd.append(db_name)
import_cmd = (['docker', 'compose', '-f', compose_path, 'exec', '-T']
+ (['-e', 'MYSQL_PWD'] if db_password else [])
+ ['db', 'mysql', '-u', db_user, db_name])
env = secret_env(MYSQL_PWD=db_password)
if snapshot_path.endswith('.gz'):
result = run_from_gzip(import_cmd, snapshot_path, timeout=1800)
result = run_from_gzip(import_cmd, snapshot_path, timeout=1800, env=env)
else:
with open(snapshot_path, 'r') as f:
result = run_checked(import_cmd, stdin=f, timeout=1800)
result = run_checked(import_cmd, stdin=f, timeout=1800, env=env)
if not result['success']:
return {'success': False,
+10 -8
View File
@@ -125,7 +125,6 @@ class DomainAttachService:
if want_ssl:
try:
from app.services.ssl_service import SSLService, get_acme_contact
from app.services.nginx_service import NginxService
# The stored panel contact before the admin@<host> guess —
# that guess is where Let's Encrypt expiry notices went to
# die, since the address usually does not exist.
@@ -135,13 +134,16 @@ class DomainAttachService:
domain.ssl_enabled = True
domain.ssl_certificate_path = cert.get('certificate_path')
domain.ssl_key_path = cert.get('private_key_path')
ssl_result['enabled'] = True
try:
NginxService.add_ssl_to_site(
app.name, cert.get('certificate_path'),
cert.get('private_key_path'))
except Exception as e:
warnings.append(f'certificate issued but nginx SSL wiring failed: {e}')
db.session.flush()
wired = SiteDomainService.write_app_vhost(app)
if wired.get('warning'):
# Keep the cert paths for a retry, but don't claim
# HTTPS that nginx is not serving.
domain.ssl_enabled = False
warnings.append('certificate issued but nginx SSL wiring '
f"failed: {wired['warning']}")
else:
ssl_result['enabled'] = True
else:
err = (cert or {}).get('error') or 'certificate request failed'
ssl_result['error'] = err
@@ -1779,7 +1779,9 @@ class EnvironmentPipelineService:
for attempt in range(max_attempts):
result = EnvironmentDockerService.exec_in_container(
compose_path, 'db',
f'mysqladmin -u {db_user} -p{db_password} ping'
# ping exits 0 whenever the server answers, even "Access
# denied", so it needs no password on the command line.
f'mysqladmin -u {db_user} ping'
)
if result.get('success'):
return True
+20 -1
View File
@@ -147,6 +147,19 @@ class FileService:
if not cls.is_path_allowed(path):
raise PermissionDeniedError(cls._DENIED)
@classmethod
def _require_no_protected_inside(cls, path: str) -> None:
"""Raise when a protected root sits inside *path*. The path checks only
look at the path itself, so copying, moving or deleting a parent such
as /opt would otherwise carry the panel's .env along with it."""
try:
real_path = os.path.realpath(path)
except (ValueError, OSError):
raise PermissionDeniedError(cls._DENIED)
prefix = real_path.rstrip(os.sep) + os.sep
if any(root.startswith(prefix) for root in cls.PROTECTED_ROOTS):
raise PermissionDeniedError(cls._DENIED)
@classmethod
def _require_writable(cls, path: str) -> None:
"""Raise unless a mutating operation may touch *path*."""
@@ -362,6 +375,7 @@ class FileService:
def delete(cls, path: str) -> Dict:
"""Delete a file or directory."""
cls._require_writable(path)
cls._require_no_protected_inside(path)
if not os.path.exists(path):
raise NotFoundError('Path not found')
@@ -381,6 +395,7 @@ class FileService:
def rename(cls, old_path: str, new_name: str) -> Dict:
"""Rename a file or directory."""
cls._require_writable(old_path)
cls._require_no_protected_inside(old_path)
if not os.path.exists(old_path):
raise NotFoundError('Path not found')
@@ -414,6 +429,7 @@ class FileService:
# is written, so it gets the full check.
if not cls.is_path_allowed(src_path):
raise PermissionDeniedError(cls._DENIED)
cls._require_no_protected_inside(src_path)
cls._require_writable(dest_path)
if not os.path.exists(src_path):
@@ -424,7 +440,9 @@ class FileService:
try:
if os.path.isdir(src_path):
shutil.copytree(src_path, dest_path)
# Links stay links: following one would copy whatever it
# points at, protected roots included.
shutil.copytree(src_path, dest_path, symlinks=True)
else:
shutil.copy2(src_path, dest_path)
return {'src': src_path, 'dest': dest_path}
@@ -439,6 +457,7 @@ class FileService:
# A move removes the source, so unlike copy both ends must be writable.
for candidate in (src_path, dest_path):
cls._require_writable(candidate)
cls._require_no_protected_inside(src_path)
if not os.path.exists(src_path):
raise NotFoundError('Source not found')
+6 -1
View File
@@ -76,8 +76,13 @@ def redeem(token, remote_ip=None):
if user is None or not user.is_active:
return None, 'inactive'
link.used_at = datetime.utcnow()
# Claim it in one conditional UPDATE: two concurrent redeems both pass the
# is_used check above, but only one can flip used_at from NULL.
claimed = LoginLink.query.filter_by(id=link.id, used_at=None).update(
{'used_at': datetime.utcnow()}, synchronize_session=False)
db.session.commit()
if claimed != 1:
return None, 'used'
return user, None
@@ -1,68 +0,0 @@
"""Manifest-powered previews.
A PR preview for a manifest-managed app is an apply with a namespace prefix and
a TTL: it clones the manifest-resolved config (env + the existing
pr-{pr}.{app_domain} domain) with per-preview overrides. This service produces
that resolved config; the preview provisioner consumes it. Real container
spin-up for generic apps stays best-effort (Docker-dependent) — the resolved
config is the portable unit this adds on top of the WordPress-only path.
"""
import logging
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
class ManifestPreviewService:
@classmethod
def build_preview_config(cls, app, preview) -> Optional[Dict[str, Any]]:
"""Resolved config for a manifest-managed app's preview, or None."""
from app.services.manifest_apply_service import ManifestApplyService
resolved = ManifestApplyService.resolved_for_app(app)
if not resolved:
return None
# base env = the app's effective env (manifest literals + resolved refs)
from app.services.env_service import EnvService
try:
env = dict(EnvService.get_effective_env(app.id))
except Exception:
env = {}
# per-preview overrides
env['SERVERKIT_PREVIEW'] = 'true'
env['SERVERKIT_PR_NUMBER'] = str(getattr(preview, 'pr_number', '') or '')
if getattr(preview, 'branch', None):
env['SERVERKIT_PREVIEW_BRANCH'] = preview.branch
return {
'env': env,
'domain': getattr(preview, 'domain', None),
'port': resolved.get('port'),
'target_server_id': cls._preview_server_id(app, resolved),
'service': resolved.get('name'),
}
@staticmethod
def _preview_server_id(app, resolved) -> Optional[str]:
"""Where the preview should run: preview settings win, then manifest server,
then the app's own server. (ApplicationPreviewSettings.target_server_id was
plumbed but unused — this makes it live.)"""
try:
from app.models.application_preview import ApplicationPreviewSettings
settings = ApplicationPreviewSettings.query.filter_by(
application_id=app.id).first()
if settings and settings.target_server_id:
return settings.target_server_id
except Exception:
pass
server_ref = resolved.get('server')
if server_ref:
from app.services.manifest_apply_service import ManifestApplyService
resolved_id = ManifestApplyService._resolve_server_id(server_ref)
if resolved_id:
return resolved_id
return getattr(app, 'server_id', None)
+4 -2
View File
@@ -214,7 +214,7 @@ class MonitoringService:
@classmethod
def send_webhook_alert(cls, alerts: List[Dict]) -> Dict:
"""Send webhook alert notification."""
import requests
from app.utils import safe_http
config = cls.get_config()
webhook_config = config.get('webhook', {})
@@ -229,7 +229,7 @@ class MonitoringService:
'alerts': alerts
}
response = requests.post(
response = safe_http.post(
webhook_config['url'],
json=payload,
timeout=10
@@ -239,6 +239,8 @@ class MonitoringService:
return {'success': True, 'message': 'Webhook sent'}
return {'success': False, 'error': f'Webhook returned {response.status_code}'}
except safe_http.UnsafeURLError as e:
return {'success': False, 'error': f'Webhook URL refused: {e}'}
except Exception as e:
return {'success': False, 'error': str(e)}
+19
View File
@@ -39,15 +39,34 @@ def render_site_config(name: str, app_type: str, domains: List[str],
micro_cache_ttl: Optional[int] = None,
immutable_assets: bool = False,
wordpress_protection: bool = False, *,
cert_groups: Optional[List[tuple]] = None,
settings: RenderSettings = DEFAULT_SETTINGS) -> Dict:
"""Render the vhost config for a site to a string — no side effects.
This is the exact template pipeline :meth:`create_site` writes to disk;
it is exposed separately so callers (e.g. drift detection) can compute
the expected on-disk content without touching the filesystem.
``cert_groups`` — ``[(domains, cert, key), ...]`` — serves each group of
domains from its own certificate (``cert=None`` for plain HTTP): one
server set per group, since a server block has exactly one certificate.
It replaces ``domains``/``ssl_cert``/``ssl_key``. Templates hold only
``server`` blocks, so concatenated groups are a valid file.
Returns ``{'success': True, 'config': str}`` or
``{'success': False, 'error': msg}``.
"""
if cert_groups:
parts = []
for group_domains, group_cert, group_key in cert_groups:
rendered = render_site_config(
name, app_type, list(group_domains), root_path, port, php_version,
group_cert, group_key, upstream, micro_cache, micro_cache_ttl,
immutable_assets, wordpress_protection, settings=settings)
if not rendered.get('success'):
return rendered
parts.append(rendered['config'])
return {'success': True, 'config': '\n'.join(parts)}
if not domains:
return {'success': False, 'error': 'At least one domain is required'}
+2 -2
View File
@@ -214,13 +214,13 @@ SSL_BLOCK = '''
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# Baseline response-header hardening. These are safe for reverse-proxied apps;
# the CSP is deliberately permissive so it does not break managed apps while
# the CSP is permissive (inline allowed, no eval) so it does not break managed apps while
# still satisfying "a CSP is present" and blocking cross-origin framing.
# Tighten the CSP per-app when the upstream can support a stricter policy.
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always;
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' data: blob: https:; frame-ancestors 'self'; upgrade-insecure-requests" always;
'''
SSL_REDIRECT_TEMPLATE = '''server {{
+17 -4
View File
@@ -240,12 +240,14 @@ class NginxService:
micro_cache: bool = False,
micro_cache_ttl: Optional[int] = None,
immutable_assets: bool = False,
wordpress_protection: bool = False) -> Dict:
wordpress_protection: bool = False,
cert_groups: Optional[List[tuple]] = None) -> Dict:
"""Compatibility entry point for the pure configuration layer."""
return rendering.render_site_config(
name, app_type, domains, root_path, port, php_version, ssl_cert,
ssl_key, upstream, micro_cache, micro_cache_ttl, immutable_assets,
wordpress_protection, settings=cls._render_settings())
wordpress_protection, cert_groups=cert_groups,
settings=cls._render_settings())
@classmethod
def _with_wordpress_protection(cls, config: str, port: int) -> str:
@@ -457,7 +459,8 @@ class NginxService:
upstream: str = None, micro_cache: bool = False,
micro_cache_ttl: Optional[int] = None,
immutable_assets: bool = False,
wordpress_protection: bool = False) -> Dict:
wordpress_protection: bool = False,
cert_groups: Optional[List[tuple]] = None) -> Dict:
"""Create a new site configuration.
When ``ssl_cert``/``ssl_key`` are given the generated vhost serves HTTPS
@@ -471,7 +474,7 @@ class NginxService:
php_version=php_version, ssl_cert=ssl_cert, ssl_key=ssl_key,
upstream=upstream, micro_cache=micro_cache,
micro_cache_ttl=micro_cache_ttl, immutable_assets=immutable_assets,
wordpress_protection=wordpress_protection,
wordpress_protection=wordpress_protection, cert_groups=cert_groups,
)
if not rendered.get('success'):
return rendered
@@ -721,6 +724,16 @@ class NginxService:
if content is None:
return {'success': False, 'error': f'Could not read site {name}'}
# Already HTTPS: swap the certificate in place. Re-running the
# insert below would rewrite the redirect block's `listen 80;`
# too and leave a duplicate 443 listen that fails `nginx -t`.
if re.search(r'^\s*ssl_certificate\s', content, re.M):
swapped = re.sub(r'^(\s*ssl_certificate)\s+[^;]+;',
lambda m: f'{m.group(1)} {cert_path};', content, flags=re.M)
swapped = re.sub(r'^(\s*ssl_certificate_key)\s+[^;]+;',
lambda m: f'{m.group(1)} {key_path};', swapped, flags=re.M)
return cls.write_vhost(name, swapped)
# Extract domains for redirect
match = re.search(r'server_name\s+([^;]+);', content)
domains_str = match.group(1).strip() if match else name
+56
View File
@@ -0,0 +1,56 @@
"""Agent permission levels and the one command-gate table.
The level is chosen on the server (``permissions.level`` in the agent's
config.yaml) and REPORTED to the panel. The panel never sets it. This module
is only the panel's defence in depth: it refuses to send a command the agent
would refuse anyway. ``PROTECT_ACTIONS`` must stay identical to the agent's
allowlist (docs/AGENT_PERMISSION_LEVELS.md; checked by a test).
"""
LEVELS = ('monitor', 'protect', 'full')
_RANK = {level: i for i, level in enumerate(LEVELS)}
LABELS = {'monitor': 'Monitor', 'protect': 'Protect', 'full': 'Full'}
PROTECT_ACTIONS = frozenset({
'firewall:allow_port', 'firewall:deny_port', 'firewall:status',
'firewall:allow_ip', 'firewall:deny_ip',
'fail2ban:status', 'fail2ban:ban', 'fail2ban:unban',
'crowdsec:decisions:list', 'crowdsec:ban', 'crowdsec:unban',
'cloudflare:origin_lock:status', 'cloudflare:origin_lock:apply',
'cloudflare:origin_lock:remove',
})
# Signature-verified key rotation is not control; allowed at every level.
ALWAYS_ALLOWED = frozenset({'credential_update'})
def normalize(level):
"""Return a valid level string, or None for missing/unknown values."""
level = level.strip().lower() if isinstance(level, str) else None
return level if level in _RANK else None
def effective_level(level):
"""Unknown/legacy (None) means a pre-levels agent, i.e. full."""
return normalize(level) or 'full'
def is_escalation(old, new):
return old is not None and _RANK[new] > _RANK[old]
def refusal(level, action):
"""Message explaining why ``action`` is refused at ``level``, else None."""
level = effective_level(level)
if level == 'full' or action in ALWAYS_ALLOWED:
return None
if level == 'protect' and action in PROTECT_ACTIONS:
return None
if level == 'monitor':
return (f"server is in Monitor mode: '{action}' refused. Monitor agents "
"are report-only and accept no commands. The level can only be "
"changed on the server itself (serverkit-agent permissions set).")
return (f"server is in Protect mode: '{action}' refused. Protect agents only "
"run firewall, fail2ban, CrowdSec and Cloudflare origin-lock actions. "
"The level can only be changed on the server itself "
"(serverkit-agent permissions set).")
+67 -24
View File
@@ -2133,37 +2133,71 @@ def install_registry_extension(slug, user_id=None):
)
def check_for_updates():
"""Compare installed plugins to the registry; return update candidates.
def check_for_updates(refresh=False):
"""Compare installed plugins to the registry / bundled manifests.
Update v1 is registry-driven: a plugin whose slug is in the registry with a
higher version than installed is flagged. Panel-version compatibility is
surfaced so the UI can gray out an update the panel can't run yet. The
installed plugin's ``source_type`` is included so callers can see the
provenance the update would cross (audit M2 — a registry entry only ever
matches on slug; the update route's consent gate is the enforcement).
Registry-driven for url/registry rows (matched on slug); ``builtin`` rows
compare against the bundled manifest in builtin-extensions/. Rows with no
known source of truth (url/local/upload/git without a registry entry) are
skipped. A malformed version means "no update"; one bad row never breaks
the list. ``requires_ack``/``risk`` mirror the update route's consent gate.
"""
from app.services import registry_service
from app.utils.version import compare_versions, version_satisfies, get_panel_version
if refresh:
registry_service.refresh(force=True)
panel = get_panel_version()
bundled = {b['slug']: b['manifest'] for b in list_builtin_extensions()}
out = []
for p in InstalledPlugin.query.all():
entry = registry_service.get_entry(p.slug)
if not entry:
continue
available = entry.get('version')
out.append({
'slug': p.slug,
'plugin_id': p.id,
'installed_version': p.version,
'available_version': available,
'update_available': compare_versions(available, p.version) > 0,
'compatible': version_satisfies(
panel, entry.get('min_panel_version'), entry.get('max_panel_version')
),
'source': entry.get('source'),
'installed_source_type': p.source_type,
})
try:
if p.source_type == 'builtin':
m = bundled.get(p.slug)
if not m:
continue
available = m.get('version')
row = {
'display_name': m.get('display_name') or p.name,
'update_source': 'builtin', 'source': None,
'compatible': True, 'requires_ack': False, 'risk': None,
}
minv = m.get('min_panel_version')
maxv = m.get('max_panel_version')
else:
entry = registry_service.get_entry(p.slug)
if not entry:
continue
available = entry.get('version')
minv = entry.get('min_panel_version')
maxv = entry.get('max_panel_version')
risk, _ = registry_service.consent_gate(entry, False)
row = {
'display_name': entry.get('display_name') or p.name,
'update_source': 'registry', 'source': entry.get('source'),
'requires_ack': bool(risk), 'risk': risk,
}
try:
newer = compare_versions(available, p.version) > 0
except Exception: # noqa: BLE001 - malformed version = no update
newer = False
compatible = version_satisfies(panel, minv, maxv)
row['compatible'] = bool(compatible)
row['incompatible_reason'] = None if compatible else (
f"Needs panel {minv or '*'}–{maxv or '*'} (this panel is {panel})."
)
if minv:
row['min_panel_version'] = minv
out.append({
'slug': p.slug,
'plugin_id': p.id,
'installed_version': p.version,
'available_version': available,
'update_available': newer,
'installed_source_type': p.source_type,
**row,
})
except Exception as exc: # noqa: BLE001 - isolate bad rows
logger.warning(f'Update check skipped {p.slug}: {exc}')
return out
@@ -2173,6 +2207,15 @@ def update_plugin(plugin_id, user_id=None):
plugin = InstalledPlugin.query.get(plugin_id)
if not plugin:
raise ValueError('Plugin not found')
folder = next((b['path'] for b in list_builtin_extensions()
if b['slug'] == plugin.slug), None) \
if plugin.source_type == 'builtin' else None
# A builtin row with no bundled folder (e.g. stamped by hand) falls
# through to the registry path below.
if folder:
return install_from_path(
folder, user_id=user_id, force=True, source_type='builtin',
)
entry = registry_service.get_entry(plugin.slug)
if not entry:
raise ValueError(
@@ -491,7 +491,7 @@ class RemoteDockerService:
# ==================== Utility ====================
@staticmethod
def get_available_servers() -> List[Dict[str, Any]]:
def get_available_servers(user=None) -> List[Dict[str, Any]]:
"""
Get list of available servers for Docker operations.
@@ -510,9 +510,11 @@ class RemoteDockerService:
# Get remote servers
connected_ids = set(agent_registry.get_connected_servers())
remote_servers = Server.query.filter(
Server.status.in_(['online', 'connecting'])
).all()
query = Server.query.filter(Server.status.in_(['online', 'connecting']))
if user is not None:
from app.services.workspace_service import WorkspaceService
query = WorkspaceService.filter_accessible_servers(query, user)
remote_servers = query.all()
for server in remote_servers:
has_docker_perm = server.has_permission('docker:container:read')
@@ -52,6 +52,7 @@ _AUDIT_DETAIL_KEYS = frozenset({
'application_id',
'code',
'endpoint',
'escalation',
'from',
'kind',
'label',
@@ -214,11 +215,13 @@ def _require_developer(user):
raise PermissionDeniedError('Developer access required')
def _resolve_server(server_id):
def _resolve_server(user, server_id):
from app.models.server import Server
from app.services.workspace_service import WorkspaceService
server = db.session.get(Server, str(server_id))
if server is None:
# A foreign workspace's server reads as missing, like every server route.
if server is None or not WorkspaceService.can_access_server(user, server):
raise ServerTimelineNotFoundError(f'Server {server_id} not found')
return server
@@ -493,7 +496,7 @@ def _event_sort_key(event):
def get_timeline(user, server_id, *, types=None, before=None, limit=None):
"""Return one authorization-filtered keyset page, newest first."""
_require_developer(user)
server = _resolve_server(server_id)
server = _resolve_server(user, server_id)
requested_types = _parse_types(types)
page_limit = _parse_limit(limit)
cursor = decode_cursor(
+4 -2
View File
@@ -171,8 +171,10 @@ class SettingsService:
'sso_saml_idp_metadata_url': {'value': '', 'type': 'string', 'description': 'SAML IdP metadata URL'},
'sso_saml_idp_sso_url': {'value': '', 'type': 'string', 'description': 'SAML IdP SSO URL'},
'sso_saml_idp_cert': {'value': '', 'type': 'string', 'description': 'SAML IdP certificate (PEM)'},
'sso_auto_provision': {'value': True, 'type': 'boolean', 'description': 'Auto-create users on first SSO login'},
'sso_default_role': {'value': 'developer', 'type': 'string', 'description': 'Default role for SSO-provisioned users'},
# Off by default: enabling a provider for yourself must not let every
# account at that provider sign up. Registration is closed by default too.
'sso_auto_provision': {'value': False, 'type': 'boolean', 'description': 'Auto-create users on first SSO login'},
'sso_default_role': {'value': 'viewer', 'type': 'string', 'description': 'Default role for SSO-provisioned users'},
'sso_force_sso': {'value': False, 'type': 'boolean', 'description': 'Disable password login (SSO only)'},
'sso_allowed_domains': {'value': [], 'type': 'json', 'description': 'Restrict SSO to these email domains'},
# Source provider connections
+56 -10
View File
@@ -477,7 +477,8 @@ class SiteDomainService:
return warnings
@classmethod
def _vhost_create_kwargs(cls, app, domains, ssl_cert, ssl_key, force_type=None):
def _vhost_create_kwargs(cls, app, domains, ssl_cert, ssl_key, force_type=None,
cert_groups=None):
"""Build ``NginxService.create_site(**kwargs)`` for ``app``, or
``(None, reason)`` when the app type can't be served by host nginx or is
missing what it needs (a port for proxied apps, a root for served ones).
@@ -492,6 +493,7 @@ class SiteDomainService:
# (app_vhost_kwargs -> render_site_config) always agree on it —
# an enabled cache must never show up as config drift.
base = dict(name=app.name, domains=domains, ssl_cert=ssl_cert, ssl_key=ssl_key,
**({'cert_groups': cert_groups} if cert_groups else {}),
micro_cache=bool(getattr(app, 'micro_cache_enabled', False)),
micro_cache_ttl=getattr(app, 'micro_cache_ttl', None),
immutable_assets=bool(getattr(app, 'immutable_assets', False)))
@@ -541,18 +543,62 @@ class SiteDomainService:
# straight back into server_name — the vhost would keep serving a domain
# the user removed, and drift detection (which renders through this same
# function) would report the correct config as drifted.
domains = [d.name for d in Domain.query_active().filter_by(application_id=app.id).all()]
if not domains:
rows = Domain.query_active().filter_by(application_id=app.id).all()
if not rows:
return None, None
domains = [d.name for d in rows]
# Pick a wildcard cert only when all domains sit under one base (whichever
# base covers them) and that base has HTTPS set up.
ssl_cert = ssl_key = None
cover = cls.covering_base(domains[0])
if cover and cls.https_enabled(cover) and all(cls.covering_base(d) == cover for d in domains):
ssl_cert, ssl_key = cls.wildcard_cert_paths(cover)
# Each domain's certificate: its base's wildcard when that base has
# HTTPS, else the domain's own issued cert. Rebuilding the vhost from
# rows (deploys, slot switches, drift repair, restore) used to know
# only wildcards, so a custom domain's HTTPS vanished on the next one.
pairs = [(d.name, cls._domain_cert(d)) for d in rows]
certs = {cert for _, cert in pairs}
if len(certs) == 1:
ssl_cert, ssl_key = next(iter(certs)) or (None, None)
return cls._vhost_create_kwargs(app, domains, ssl_cert, ssl_key, force_type)
return cls._vhost_create_kwargs(app, domains, ssl_cert, ssl_key, force_type)
groups = {}
for name, cert in pairs:
groups.setdefault(cert, []).append(name)
cert_groups = [(names, *(cert or (None, None))) for cert, names in groups.items()]
return cls._vhost_create_kwargs(app, domains, None, None, force_type,
cert_groups=cert_groups)
@classmethod
def _domain_cert(cls, domain):
"""``(cert, key)`` serving ``domain`` over HTTPS, or ``None`` for HTTP."""
cover = cls.covering_base(domain.name)
if cover and cls.https_enabled(cover):
return cls.wildcard_cert_paths(cover)
if domain.ssl_enabled and domain.ssl_certificate_path:
key = domain.ssl_key_path
if not key and domain.ssl_certificate_path.endswith('/fullchain.pem'):
# Rows enabled through the domains API before it stored the
# key path: certbot keeps privkey.pem next to fullchain.pem.
key = domain.ssl_certificate_path[:-len('fullchain.pem')] + 'privkey.pem'
if key:
return domain.ssl_certificate_path, key
return None
@classmethod
def enable_domain_ssl(cls, app, domain, cert_path, key_path):
"""Record ``domain``'s issued cert and republish ``app``'s vhost.
The vhost is regenerated from the rows - the same door every later
rewrite uses, so the HTTPS block survives them. Returns None on
success, else the reason, with the row left as it was."""
from app import db
domain.ssl_enabled = True
domain.ssl_certificate_path = cert_path
domain.ssl_key_path = key_path
db.session.flush()
published = cls.write_app_vhost(app)
if published.get('warning'):
db.session.rollback()
return published['warning']
db.session.commit()
return None
@classmethod
def set_immutable_assets(cls, app, enabled):
+20 -2
View File
@@ -206,12 +206,19 @@ def handle_oauth_callback(provider, code, state, redirect_uri):
return profile
def _claims_verified(info):
"""OIDC `email_verified`; some IdPs send it as the string "true"."""
value = info.get('email_verified')
return value is True or (isinstance(value, str) and value.lower() == 'true')
def _normalize_profile(provider, info, headers=None):
"""Convert provider-specific userinfo into a standard dict."""
if provider == 'google':
return {
'provider_user_id': info.get('sub', ''),
'email': info.get('email', ''),
'email_verified': _claims_verified(info),
'display_name': info.get('name', ''),
}
elif provider == 'github':
@@ -231,6 +238,9 @@ def _normalize_profile(provider, info, headers=None):
return {
'provider_user_id': str(info.get('id', '')),
'email': email,
# GitHub only publishes verified addresses on a profile, and the
# /user/emails fallback above takes a verified primary only.
'email_verified': bool(email),
'display_name': info.get('name') or info.get('login', ''),
}
else:
@@ -238,6 +248,7 @@ def _normalize_profile(provider, info, headers=None):
return {
'provider_user_id': info.get('sub', ''),
'email': info.get('email', ''),
'email_verified': _claims_verified(info),
'display_name': info.get('name', ''),
}
@@ -307,6 +318,8 @@ def handle_saml_callback(saml_response_data, request_data):
'provider_user_id': name_id,
'email': attrs.get('email', [name_id])[0] if attrs.get('email') else name_id,
'display_name': attrs.get('displayName', [''])[0] if attrs.get('displayName') else '',
# A signed assertion from the IdP the admin configured vouches for it.
'email_verified': True,
'_tokens': {},
}
@@ -351,17 +364,22 @@ def find_or_create_user(provider, profile):
if user:
if not user.is_active:
raise ValueError('Account is deactivated')
# Anyone can put any address on an unverified IdP profile; linking on
# it would hand them the existing account, admin included.
if profile.get('email_verified') is not True:
raise ValueError("This SSO account's email is not verified by the provider; "
'sign in with your password and link it from your profile')
link_identity(user.id, provider, profile, profile.get('_tokens', {}))
return user, False
# 3. Auto-provision
if not SettingsService.get('sso_auto_provision', True):
if not SettingsService.get('sso_auto_provision', False):
raise ValueError('No matching account found and auto-provisioning is disabled')
if not email:
raise ValueError('SSO provider did not return an email address')
default_role = SettingsService.get('sso_default_role', 'developer')
default_role = SettingsService.get('sso_default_role', 'viewer')
username = _generate_username(email, profile.get('display_name', ''))
user = User(
@@ -6,6 +6,7 @@ from datetime import datetime
from typing import Dict, List, Optional
from urllib.parse import urlparse
from app.utils.config_store import load_json_config, save_json_config
from app import paths
from app.utils.crypto import encrypt_secret, decrypt_secret_safe, is_encrypted
from app.utils.formatting import format_bytes
@@ -33,12 +34,11 @@ class StorageProviderService:
@classmethod
def get_config(cls) -> Dict:
"""Get storage provider configuration (secrets decrypted in memory)."""
if os.path.exists(cls.CONFIG_FILE):
try:
with open(cls.CONFIG_FILE, 'r') as f:
return cls._decrypt_config(json.load(f))
except Exception:
pass
# An unreadable file is moved aside rather than silently read as
# "local", which would quietly stop off-site backups.
stored = load_json_config(cls.CONFIG_FILE, None)
if stored is not None:
return cls._decrypt_config(stored)
return {
'provider': 'local',
@@ -118,8 +118,9 @@ class StorageProviderService:
if val and not is_encrypted(val):
config[provider][field] = encrypt_secret(val)
with open(cls.CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=2)
saved = save_json_config(cls.CONFIG_FILE, config)
if not saved['success']:
return saved
if os.name != 'nt':
os.chmod(cls.CONFIG_FILE, 0o600)
return {'success': True, 'message': 'Storage configuration saved'}
+22
View File
@@ -159,6 +159,28 @@ class WorkspaceService:
return True
return WorkspaceService.get_user_role(server.workspace_id, user.id) is not None
@staticmethod
def filter_accessible_servers(query, user):
"""Narrow a Server query to what can_access_server allows, in SQL."""
if user.is_admin:
return query
from app.models.server import Server
member_ws = db.session.query(WorkspaceMember.workspace_id).filter_by(user_id=user.id)
allowed = [Server.workspace_id.is_(None), Server.workspace_id.in_(member_ws)]
default = Workspace.query.filter_by(
slug=WorkspaceService.DEFAULT_WORKSPACE_SLUG).first()
if default is not None:
allowed.append(Server.workspace_id == default.id)
return query.filter(db.or_(*allowed))
@staticmethod
def accessible_servers(user):
"""Every server *user* may operate, with its group loaded."""
from sqlalchemy.orm import joinedload
from app.models.server import Server
query = WorkspaceService.filter_accessible_servers(Server.query, user)
return query.options(joinedload(Server.group)).all()
@staticmethod
def get_accessible_server(user, server_id):
"""The server if *user* may operate it (see can_access_server), else None."""
+38 -13
View File
@@ -5,6 +5,8 @@ import threading
import time
import queue
import re
import logging
import subprocess
from app.services.system_service import SystemService
from app.services.log_service import LogService, LogStreamer
@@ -12,6 +14,8 @@ from app.services.docker_service import DockerService
from app import sockets_rooms as rooms
from app.utils.background_loop import BackgroundLoop
logger = logging.getLogger(__name__)
class AuthorizedSocketIO(SocketIO):
"""Recheck audience authorization before every server-side delivery.
@@ -65,7 +69,9 @@ def _client_user(sid):
info = connected_clients.get(sid)
if not info:
return None
user = validate_session_claims(info.get('claims', {}))
# A socket outlives its 15-minute access token; ending it at `exp` froze
# every live view, since clients don't reconnect after a server disconnect.
user = validate_session_claims(info.get('claims', {}), check_expiry=False)
# Disconnect on role changes instead of retaining previously joined rooms.
if not user or user.role != info['role']:
_disconnect_client(sid)
@@ -140,6 +146,17 @@ def _room_allowed(user, room):
and _server_visible(user, server_id))
def _emit_to_member(sid, room, event, payload):
"""Emit to one socket, only while it is still allowed in ``room``."""
application = getattr(socketio, '_security_app', None)
if application is not None:
with application.app_context():
_prune_audience(room)
members = socketio.server.manager.get_participants('/', room)
if any(member == sid for member, _ in members):
socketio.emit(event, payload, to=sid)
def _prune_audience(room=None):
# Inspect only this delivery's audience; per-sid metrics should not scan
# every other connection for each subscriber.
@@ -719,6 +736,14 @@ def handle_subscribe_container_logs(data):
# Create stop event for this stream
stop_event = threading.Event()
room = rooms.app_logs_room(app_id)
def deliver(event, payload):
# This `docker logs` process is this socket's alone, so are its lines:
# sending them to the shared room showed every line once per open
# viewer. Room membership is still the gate - pruning drops a socket
# whose access to the app was removed, and then it gets nothing.
_emit_to_member(sid, room, event, payload)
# Create thread to read and emit logs
def stream_logs():
@@ -728,37 +753,37 @@ def handle_subscribe_container_logs(data):
if not line:
# Process ended (container stopped or exited)
if not stop_event.is_set():
socketio.emit('container_log_ended', {
deliver('container_log_ended', {
'app_id': app_id,
'message': 'Container log stream ended'
}, room=rooms.app_logs_room(app_id))
})
break
# Parse the log line
parsed = DockerService.parse_log_line(line.rstrip('\n'))
socketio.emit('container_log', {
deliver('container_log', {
'app_id': app_id,
'line': line.rstrip('\n'),
'parsed': parsed,
'timestamp': time.time()
}, room=rooms.app_logs_room(app_id))
})
except Exception as e:
if not stop_event.is_set():
socketio.emit('container_log_error', {
deliver('container_log_error', {
'app_id': app_id,
'message': f'Stream error: {str(e)}'
}, room=rooms.app_logs_room(app_id))
})
finally:
# Clean up
try:
process.terminate()
process.wait(timeout=2)
except:
except (OSError, subprocess.SubprocessError):
try:
process.kill()
except:
pass
except OSError as kill_err:
logger.debug('Could not kill log stream process: %s', kill_err)
thread = threading.Thread(target=stream_logs, daemon=True)
thread.start()
@@ -815,11 +840,11 @@ def stop_container_log_stream(sid: str):
try:
process.terminate()
process.wait(timeout=2)
except:
except (OSError, subprocess.SubprocessError):
try:
process.kill()
except:
pass
except OSError as kill_err:
logger.debug('Could not kill log stream process: %s', kill_err)
def emit_container_log(app_id: int, line: str, level: str = 'info'):
+3 -2
View File
@@ -57,11 +57,12 @@ def load_json_config(path, default):
with open(path, 'r') as f:
return json.load(f)
except Exception: # noqa: BLE001
_quarantine(path)
quarantine(path)
return copy.deepcopy(default)
def _quarantine(path):
def quarantine(path):
"""Move an unreadable config aside so the next save can't overwrite it."""
aside = f'{path}.corrupt-{time.strftime("%Y%m%d%H%M%S")}'
try:
os.replace(path, aside)
+9
View File
@@ -335,6 +335,15 @@ def _streamed(cmd: List[str], pump, *, env: Optional[dict], timeout: Optional[in
}
def secret_env(**secrets) -> dict:
"""This process's environment plus *secrets*, for passing a password to a
child (MYSQL_PWD, PGPASSWORD) without putting it on the command line,
where every local account can read it from ps or /proc/<pid>/cmdline.
For ``docker exec``/``docker compose exec`` name the variable bare
(``-e MYSQL_PWD``) so docker copies the value from this environment."""
return {**os.environ, **{k: v for k, v in secrets.items() if v}}
def run_to_gzip(cmd: List[str], dest: str, *, env: Optional[dict] = None,
timeout: Optional[int] = None) -> dict:
"""Run *cmd* and gzip its stdout into *dest*; *dest* is removed on failure."""
@@ -0,0 +1,36 @@
"""Agent-reported permission level, report bookkeeping and service checks."""
import sqlalchemy as sa
from alembic import op
revision = '112_agent_permission_levels'
down_revision = '111_preview_runtime'
branch_labels = None
depends_on = None
SERVER_COLUMNS = [
('permission_level', sa.String(16)),
('permission_level_updated_at', sa.DateTime()),
('requested_permission_level', sa.String(16)),
('last_report_at', sa.DateTime()),
('report_interval_seconds', sa.Integer()),
('service_checks', sa.JSON()),
]
def upgrade():
inspector = sa.inspect(op.get_bind())
existing = {c['name'] for c in inspector.get_columns('servers')}
for name, kind in SERVER_COLUMNS:
if name not in existing:
op.add_column('servers', sa.Column(name, kind, nullable=True))
existing = {c['name'] for c in inspector.get_columns('metric_alerts')}
if 'detail' not in existing:
op.add_column('metric_alerts', sa.Column('detail', sa.Text(), nullable=True))
def downgrade():
with op.batch_alter_table('metric_alerts') as batch:
batch.drop_column('detail')
with op.batch_alter_table('servers') as batch:
for name, _ in reversed(SERVER_COLUMNS):
batch.drop_column(name)
+22 -24
View File
@@ -10,23 +10,23 @@ Flask-SQLAlchemy==3.1.1
# attributes and SQLAlchemy's TypingOnly guard rejected them. Debian 13 ships
# only 3.13, so this pin is what lets the panel install there at all.
# Verified: 3542 passed / 0 failed on 3.11 with 2.0.52, identical to 2.0.23.
SQLAlchemy==2.0.52
Flask-Migrate==4.0.7
SQLAlchemy==2.0.55
Flask-Migrate==4.1.0
# Authentication
Flask-JWT-Extended==4.6.0
Flask-JWT-Extended==4.7.4
PyJWT==2.15.1
# CORS
Flask-Cors==6.0.2
Flask-Cors==6.0.5
# WebSocket support
Flask-SocketIO==5.6.1
python-socketio==5.16.3
python-engineio==4.13.3
Flask-SocketIO==5.7.0
python-socketio==5.17.1
python-engineio==4.15.1
# WebSocket CLIENT for the ServerKit Cloud relay (see
# app/services/connect_client.py). The server-side stack above cannot dial out.
websockets==15.0.1
websockets==16.1.1
# System monitoring
psutil==5.9.7
@@ -35,45 +35,43 @@ psutil==5.9.7
# threading driver) under a plain threaded gunicorn worker — do NOT deploy
# with the gevent-websocket worker class; it double-answers the WS handshake
# against async_mode='threading' (browser: "Invalid frame header").
gunicorn==23.0.0
gunicorn==26.2.0
simple-websocket==1.1.0
# Environment variables
python-dotenv==1.2.2
python-dotenv==1.2.4
# YAML / TOML parsing (for Docker Compose and repository manifests)
PyYAML==6.0.1
PyYAML==6.0.3
tomli>=2.0.0; python_version < '3.11'
# Rate limiting
Flask-Limiter==3.5.0
# CLI
click==8.3.3
click==8.5.0
schedule==1.2.2
croniter==6.0.0
passlib==1.7.4
bcrypt==4.2.1
croniter==6.2.4
bcrypt==5.0.0
# Encryption for env vars
cryptography==50.0.0
cryptography==50.0.2
# Two-Factor Authentication
pyotp==2.9.0
pyotp==2.10.0
qrcode[pil]==7.4.2
# WebAuthn / Passkeys
webauthn==2.5.0
# HTTP Requests (for webhooks & notifications)
requests==2.33.1
requests==2.34.2
# S3-compatible storage (AWS S3, Backblaze B2, MinIO, Wasabi)
boto3==1.35.0
boto3==1.43.123
# SSO / OAuth
Authlib==1.6.12
Authlib==1.9.1
python3-saml==1.16.0
# Cross-platform local IANA timezone resolution (SystemService.get_server_time
@@ -82,12 +80,12 @@ python3-saml==1.16.0
tzlocal>=5.0
# OpenAPI documentation
apispec==6.4.0
marshmallow==3.26.2
apispec==6.10.0
marshmallow==4.3.1
# AI assistant (core primitive — powered by Prompture)
# Multi-provider LLM orchestration: Conversation, ToolRegistry, ask_live streaming,
# ProviderEnvironment, guardrails. Native OpenAI and Anthropic SDKs ship with the
# panel; compatible gateways use Prompture's raw-HTTP driver. Other SDKs remain
# optional. Pin the tested descriptor, streaming, and conversation APIs.
prompture[openai,anthropic]==1.11.0
prompture[openai,anthropic]==1.16.0
+80
View File
@@ -0,0 +1,80 @@
"""Seed five demo servers showing every permission-level / health state.
Dev sandbox only; never run automatically. Idempotent: demo rows are keyed by
agent_id 'demo-perm-*' and are rebuilt on each run.
cd backend && python scripts/seed_permission_demo.py
"""
import os
import sys
from datetime import datetime, timedelta
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app import create_app, db # noqa: E402
from app.models.metric_alert import MetricAlert # noqa: E402
from app.models.server import Server, ServerMetrics # noqa: E402
UP, DOWN, DEG = 'up', 'down', 'degraded'
def checks(now, web=UP, php=UP, database=UP, disk=UP):
stamp = now.isoformat() + 'Z'
rows = [('nginx', 'web', web, ''), ('php8.2-fpm', 'php_fpm', php, 'slow pool' if php == DEG else ''),
('mysql', 'database', database, 'connection refused on 3306' if database == DOWN else ''),
('disk /', 'disk', disk, ''), ('cpu', 'cpu', UP, ''), ('memory', 'memory', UP, '')]
return [{'name': n, 'kind': k, 'status': s, 'detail': d, 'checked_at': stamp} for n, k, s, d in rows]
# (name, level, status, minutes since last report, check overrides, cpu)
DEMOS = [
('demo-monitor-healthy', 'monitor', 'online', 1, {}, 14.0),
('demo-monitor-degraded', 'monitor', 'online', 1, {'database': DOWN, 'php': DEG}, 71.0),
('demo-protect-healthy', 'protect', 'online', 0, {}, 22.0),
('demo-full-healthy', 'full', 'online', 0, {}, 35.0),
('demo-monitor-offline', 'monitor', 'offline', 20, {'database': DOWN}, 9.0),
]
def seed():
now = datetime.utcnow()
for name, level, status, age, overrides, cpu in DEMOS:
agent_id = f'demo-perm-{name}'
old = Server.query.filter_by(agent_id=agent_id).first()
if old:
MetricAlert.query.filter_by(server_id=old.id).delete()
ServerMetrics.query.filter_by(server_id=old.id).delete()
db.session.delete(old)
db.session.flush()
reported = now - timedelta(minutes=age)
srv = Server(name=name, agent_id=agent_id, hostname=name, status=status,
os_type='linux', permission_level=level, requested_permission_level=level,
permission_level_updated_at=reported, last_seen=reported,
last_report_at=reported, report_interval_seconds=60,
service_checks=checks(reported, **overrides))
db.session.add(srv)
db.session.flush()
for i in range(12):
db.session.add(ServerMetrics(
server_id=srv.id, timestamp=reported - timedelta(minutes=i),
cpu_percent=cpu + i % 3, memory_percent=48.0, disk_percent=61.0))
for check in srv.service_checks:
if check['status'] == DOWN:
db.session.add(MetricAlert(
server_id=srv.id, metric=f"svc:{check['name']}"[:20], severity='critical',
status='active', created_at=reported,
detail=f"{name}: service '{check['name']}' is down since "
f"{reported:%Y-%m-%d %H:%M} UTC ({check['detail']})"))
if status == 'offline':
db.session.add(MetricAlert(
server_id=srv.id, metric='offline', severity='critical', status='active',
created_at=now, detail=f"{name} is offline since {reported:%Y-%m-%d %H:%M} UTC: "
"no report received"))
db.session.commit()
print(f'Seeded {len(DEMOS)} demo servers.')
if __name__ == '__main__':
app = create_app(os.environ.get('FLASK_ENV') or 'development')
with app.app_context():
seed()
+1 -1
View File
@@ -1 +1 @@
5279
6102
@@ -3,7 +3,7 @@
"policy": "Exact reviewed inventory of direct persistence, subprocess, and filesystem mutation calls in Flask API controllers. New calls are forbidden; remove entries as controllers delegate to services.",
"counts": {
"filesystem": 8,
"persistence": 468
"persistence": 445
},
"owners": {
"api/admin.py": {
@@ -78,10 +78,6 @@
"owner": "ServerKit backend / files domain",
"rationale": "Legacy files controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."
},
"api/fleet.py": {
"owner": "ServerKit backend / fleet domain",
"rationale": "Legacy fleet controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."
},
"api/git.py": {
"owner": "ServerKit backend / git domain",
"rationale": "Legacy git controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."
@@ -114,10 +110,6 @@
"owner": "ServerKit backend / private urls domain",
"rationale": "Legacy private urls controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."
},
"api/proxy.py": {
"owner": "ServerKit backend / proxy domain",
"rationale": "Legacy proxy controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."
},
"api/python.py": {
"owner": "ServerKit backend / python domain",
"rationale": "Legacy python controllers still cross a persistence or host-operation boundary; move each call into an app.services use case before removing it."
@@ -465,7 +457,6 @@
"api/domains.py::enable_ssl::persistence::Application.query_active().filter_by(id=domain.application_id).first()::1",
"api/domains.py::enable_ssl::persistence::Domain.query_active().filter_by(id=domain_id).first()::1",
"api/domains.py::enable_ssl::persistence::User.query.get(current_user_id)::1",
"api/domains.py::enable_ssl::persistence::db.session.commit()::1",
"api/domains.py::get_domain::persistence::Application.query_active().filter_by(id=domain.application_id).first()::1",
"api/domains.py::get_domain::persistence::Domain.query_active().filter_by(id=domain_id).first()::1",
"api/domains.py::get_domain::persistence::User.query.get(current_user_id)::1",
@@ -491,7 +482,6 @@
"api/domains.py::verify_domain::persistence::Domain.query_active().filter_by(id=domain_id).first()::1",
"api/environments.py::create_environment::persistence::db.session.commit()::1",
"api/files.py::upload_file::filesystem::os.makedirs(parent)::1",
"api/fleet.py::list_targets::persistence::Server.query.get(server_id)::1",
"api/git.py::_webhook_visible_to::persistence::Application.query.get(webhook.app_id)::1",
"api/git.py::get_deployment::persistence::Application.query_active().filter_by(id=deployment.app_id).first()::1",
"api/git.py::get_deployment::persistence::GitDeployment.query.get(deployment_id)::1",
@@ -537,7 +527,6 @@
"api/private_urls.py::update_private_url::persistence::Application.query_active().filter_by(id=app_id).first()::1",
"api/private_urls.py::update_private_url::persistence::User.query.get(current_user_id)::1",
"api/private_urls.py::update_private_url::persistence::db.session.commit()::1",
"api/proxy.py::_require_server::persistence::Server.query.get(server_id)::1",
"api/python.py::create_django_app::persistence::db.session.add(app)::1",
"api/python.py::create_django_app::persistence::db.session.commit()::1",
"api/python.py::create_flask_app::persistence::db.session.add(app)::1",
@@ -557,7 +546,6 @@
"api/recipes.py::submit_recipe_handoff::persistence::DeploymentJob.query.get(job_id)::1",
"api/secrets_webhooks.py::create_vault::persistence::Workspace.query.get(explicit_ws)::1",
"api/servers.py::acknowledge_alert::persistence::SecurityAlert.query.get(alert_id)::1",
"api/servers.py::compare_server_metrics::persistence::Server.query.get(server_id)::1",
"api/servers.py::compare_server_metrics::persistence::ServerMetrics.query.filter_by(server_id=server_id).order_by(ServerMetrics.timestamp.desc()).limit(limit).all()::1",
"api/servers.py::create_group::persistence::db.session.add(group)::1",
"api/servers.py::create_group::persistence::db.session.commit()::1",
@@ -568,48 +556,29 @@
"api/servers.py::delete_group::persistence::ServerGroup.query.get(group_id)::1",
"api/servers.py::delete_group::persistence::db.session.commit()::1",
"api/servers.py::delete_group::persistence::db.session.delete(group)::1",
"api/servers.py::delete_server::persistence::Server.query.get(server_id)::1",
"api/servers.py::delete_server::persistence::db.session.commit()::1",
"api/servers.py::delete_server::persistence::db.session.delete(server)::1",
"api/servers.py::get_allowed_ips::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_command_history::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_command_history::persistence::ServerCommand.query.filter_by(server_id=server_id).order_by(ServerCommand.created_at.desc()).limit(limit).all()::1",
"api/servers.py::get_connection_info::persistence::AgentSession.query.filter_by(server_id=server_id, is_active=True).first()::1",
"api/servers.py::get_connection_info::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_group::persistence::ServerGroup.query.get(group_id)::1",
"api/servers.py::get_server::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_server::persistence::db.session.commit()::1",
"api/servers.py::get_server::persistence::db.session.rollback()::1",
"api/servers.py::get_server_metrics::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_server_metrics::persistence::ServerMetrics.query.filter_by(server_id=server_id)::1",
"api/servers.py::get_server_onboarding_status::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_server_security_alerts::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_server_status::persistence::Server.query.get(server_id)::1",
"api/servers.py::get_servers_overview::persistence::Server.query.options(joinedload(Server.group)).all()::1",
"api/servers.py::list_groups::persistence::ServerGroup.query.all()::1",
"api/servers.py::ping_server::persistence::Server.query.get(server_id)::1",
"api/servers.py::regenerate_token::persistence::db.session.commit()::1",
"api/servers.py::register_agent::persistence::Server.query.filter(Server.registration_token_hash.isnot(None)).all()::1",
"api/servers.py::register_agent::persistence::db.session.commit()::1",
"api/servers.py::resolve_alert::persistence::SecurityAlert.query.get(alert_id)::1",
"api/servers.py::retry_server_onboarding::persistence::Server.query.get(server_id)::1",
"api/servers.py::rotate_api_key::persistence::Server.query.get(server_id)::1",
"api/servers.py::rotate_api_key::persistence::db.session.commit()::1",
"api/servers.py::set_server_workspace::persistence::Server.query.filter_by(workspace_id=ws.id).count()::1",
"api/servers.py::set_server_workspace::persistence::Workspace.query.get(target)::1",
"api/servers.py::set_server_workspace::persistence::db.session.commit()::1",
"api/servers.py::start_server_onboarding::persistence::Server.query.get(server_id)::1",
"api/servers.py::update_allowed_ips::persistence::Server.query.get(server_id)::1",
"api/servers.py::update_allowed_ips::persistence::db.session.commit()::1",
"api/servers.py::update_group::persistence::ServerGroup.query.get(group_id)::1",
"api/servers.py::update_group::persistence::db.session.commit()::1",
"api/servers.py::update_server::persistence::Server.query.get(server_id)::1",
"api/servers.py::update_server::persistence::db.session.commit()::1",
"api/servers_agents.py::add_agent_version::persistence::db.session.add(version)::1",
"api/servers_agents.py::add_agent_version::persistence::db.session.commit()::1",
"api/servers_agents.py::get_install_instructions::persistence::Server.query.get(server_id)::1",
"api/servers_agents.py::list_agent_versions::persistence::AgentVersion.query.order_by(AgentVersion.version.desc()).all()::1",
"api/servers_agents.py::trigger_agent_update::persistence::Server.query.get(server_id)::1",
"api/servers_agents.py::upgrade_fleet::persistence::Server.query.filter_by(status='online').all()::1",
"api/shared_resources.py::_check_resource_write::persistence::ManagedDatabase.query_active().filter_by(id=int(resource_id)).first()::1",
"api/shared_resources.py::_check_resource_write::persistence::Server.query.get(str(resource_id))::1",
+8 -8
View File
@@ -1,10 +1,10 @@
{
"php": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a",
"wordpress": "e6d77fd5ac90d438b9f694b3dcf50d63746bd87f3e20030e0c4bd6e94c6f372a",
"flask": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b",
"django": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b",
"python": "dba3ba47c2d2407bcbcf3b8014bc6f5dc105db8a7e5837f849b871fd5960329b",
"docker": "a18576b49626ed0f88126de8946163720d715016ee24119de22afdb38fda4400",
"remote": "7bc871f2c95a333cfe14129ae40df409a3a2165e79fb7c9205510957c95af99f",
"static": "91d63c4279f9fa1fa1ecc1cfd0e3f8c5b63e134613d319ae189a4560d3738e28"
"php": "a1de4fd08a9d277ecf4c7aaa46514bcae28a05b0a90a87bc2190cfa18dbb237f",
"wordpress": "a1de4fd08a9d277ecf4c7aaa46514bcae28a05b0a90a87bc2190cfa18dbb237f",
"flask": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c",
"django": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c",
"python": "15ffdb7f2221e465689f1662d49cf913861032d1ba1689f71ed78cd0dc2d963c",
"docker": "362d30566ba5452cb3ed9e7376da4f95c1fda61e6ec5b6a65b1ef98aa461aca5",
"remote": "0589dd632da88d569e41c339681c0a38656037d40b733179986bfc5f80f5bd27",
"static": "d3ff984ff1aac1c22e8e59f70f7fdf0c3d838726b4621f3313aa7cd4d78ee139"
}
@@ -0,0 +1,208 @@
"""Agent permission levels: report endpoint, level reporting, dispatch gate,
silence sweep, service-check alerts and install commands."""
import hashlib
import hmac
import json
import re
import secrets
import time
from datetime import datetime, timedelta
from pathlib import Path
import pytest
from app import db
from app.models.audit_log import AuditLog
from app.models.metric_alert import MetricAlert
from app.models.server import Server
from app.services import agent_health_service, permission_levels
from app.services.agent_registry import ConnectedAgent, agent_registry
REPORT = '/api/v1/agent/report'
SECRET = 'test-secret'
@pytest.fixture
def server(app, monkeypatch):
monkeypatch.setattr(Server, 'get_api_secret', lambda self: SECRET)
key, _ = Server.generate_api_credentials()
srv = Server(name='web-1', agent_id=secrets.token_hex(8))
srv.set_api_key(key)
db.session.add(srv)
db.session.commit()
srv.test_key = key
return srv
def _post(client, srv, body=None, ts=None, nonce=None, secret=SECRET, raw=None):
body = body if body is not None else {
'permission_level': 'monitor', 'interval_seconds': 60,
'metrics': {'cpu_percent': 12.5, 'memory_percent': 40.0, 'disk_percent': 55.0,
'uptime_seconds': 99, 'load1': 0.3},
'service_checks': []}
raw = raw if raw is not None else json.dumps(body).encode()
ts = str(int(time.time())) if ts is None else str(ts)
nonce = nonce or secrets.token_hex(16)
sig = hmac.new(secret.encode(),
f'{ts}.{nonce}.{hashlib.sha256(raw).hexdigest()}'.encode(),
hashlib.sha256).hexdigest()
return client.post(REPORT, data=raw, content_type='application/json', headers={
'X-Agent-Key': srv.test_key, 'X-Timestamp': ts, 'X-Nonce': nonce,
'X-Signature': sig})
def test_good_signature_updates_server(client, server):
resp = _post(client, server)
assert resp.status_code == 200
assert resp.get_json() == {'ok': True, 'interval_seconds': 60}
srv = db.session.get(Server, server.id)
assert srv.status == 'online' and srv.last_report_at is not None
assert srv.permission_level == 'monitor'
assert 'commands' not in resp.get_json()
def test_bad_signature_rejected(client, server):
assert _post(client, server, secret='wrong').status_code == 401
def test_stale_timestamp_rejected(client, server):
assert _post(client, server, ts=int(time.time()) - 400).status_code == 401
def test_replayed_nonce_rejected(client, server):
nonce = secrets.token_hex(16)
assert _post(client, server, nonce=nonce).status_code == 200
assert _post(client, server, nonce=nonce).status_code == 401
def test_oversize_body_rejected(client, server):
assert _post(client, server, raw=b'{"x":"' + b'a' * 70000 + b'"}').status_code == 413
def test_invalid_level_rejected(client, server):
assert _post(client, server, body={'permission_level': 'root'}).status_code == 400
def test_level_persisted_and_escalation_audited(client, server):
_post(client, server, body={'permission_level': 'monitor'})
_post(client, server, body={'permission_level': 'full'})
rows = AuditLog.query.filter_by(action='server.permission_level_changed').order_by(AuditLog.id).all()
details = [r.get_details() for r in rows]
assert [(d['from'], d['to'], d['escalation']) for d in details] == [
(None, 'monitor', False), ('monitor', 'full', True)]
assert db.session.get(Server, server.id).permission_level == 'full'
def test_no_api_sets_level(client, server, auth_headers):
resp = client.put(f'/api/v1/servers/{server.id}', headers=auth_headers,
json={'permission_level': 'full', 'name': 'x'})
assert resp.status_code in (200, 400)
assert db.session.get(Server, server.id).permission_level is None
writers = [r.rule for r in client.application.url_map.iter_rules()
if 'level' in r.rule and r.methods & {'POST', 'PUT', 'PATCH'}]
assert writers == []
def _connect(server_id):
agent_registry._agents[server_id] = ConnectedAgent(
server_id=server_id, socket_id='s', session_token='t',
connected_at=datetime.utcnow(), last_heartbeat=datetime.utcnow(),
ip_address='1.1.1.1', agent_version='1', transport='poll')
@pytest.mark.parametrize('level,action,refused', [
('monitor', 'firewall:status', True),
('monitor', 'docker:container:list', True),
('protect', 'docker:container:list', True),
('protect', 'system:exec', True),
('protect', 'firewall:status', False),
('protect', 'cloudflare:origin_lock:apply', False),
('protect', 'credential_update', False),
('full', 'system:exec', False),
(None, 'system:exec', False),
])
def test_refusal_table(level, action, refused):
assert bool(permission_levels.refusal(level, action)) is refused
@pytest.mark.parametrize('level', ['monitor', 'protect'])
def test_send_command_gate(server, level):
server.permission_level = level
db.session.commit()
_connect(server.id)
try:
result = agent_registry.send_command(server.id, 'system:exec', {})
finally:
agent_registry._agents.pop(server.id, None)
assert result['code'] == 'LEVEL_DENIED'
assert result['error'].startswith(f'server is in {level.title()} mode')
def test_protect_allowlist_matches_documented_contract():
doc = Path(__file__).parents[2] / 'docs/AGENT_PERMISSION_LEVELS.md'
block = re.search(r'```text allowlist\n(.*?)```', doc.read_text(), re.S).group(1)
assert set(block.split()) == set(permission_levels.PROTECT_ACTIONS)
def test_silent_monitor_goes_offline_with_one_alert(server):
server.permission_level = 'monitor'
server.status = 'online'
server.last_report_at = datetime.utcnow() - timedelta(minutes=20)
db.session.commit()
assert agent_health_service.sweep_silent_reporters() == [server.id]
assert agent_health_service.sweep_silent_reporters() == []
assert db.session.get(Server, server.id).status == 'offline'
assert MetricAlert.query.filter_by(metric='offline', status='active').count() == 1
def test_recent_monitor_stays_online(server):
server.permission_level, server.status = 'monitor', 'online'
server.last_report_at = datetime.utcnow() - timedelta(minutes=2)
db.session.commit()
assert agent_health_service.sweep_silent_reporters() == []
def _checks(status):
return {'permission_level': 'monitor', 'service_checks': [
{'name': 'mysql', 'kind': 'database', 'status': status, 'detail': 'refused',
'checked_at': '2026-01-01T00:00:00Z'}]}
def test_service_down_alert_dedupes_and_resolves(client, server):
_post(client, server, body=_checks('up'))
assert MetricAlert.query.count() == 0
_post(client, server, body=_checks('down'))
_post(client, server, body=_checks('down'))
alert = MetricAlert.query.one()
assert alert.status == 'active' and 'mysql' in alert.detail and 'web-1' in alert.detail
_post(client, server, body=_checks('up'))
assert MetricAlert.query.one().status == 'resolved'
def test_degraded_to_down_alerts_and_report_recovers_offline(client, server):
_post(client, server, body=_checks('degraded'))
assert MetricAlert.query.count() == 0
_post(client, server, body=_checks('down'))
assert MetricAlert.query.filter_by(status='active').count() == 1
agent_health_service.mark_offline(server, 'test')
db.session.commit()
server.status = 'offline'
db.session.commit()
_post(client, server, body=_checks('down'))
assert MetricAlert.query.filter_by(metric='offline', status='resolved').count() == 1
def test_install_instructions_include_level(client, server, auth_headers):
server.set_registration_token('sk_reg_x')
db.session.commit()
data = client.get(f'/api/v1/servers/install-instructions/{server.id}?level=protect',
headers=auth_headers).get_json()
assert data['permission_level'] == 'protect'
assert '--level protect' in data['linux']['one_liner']
assert '-Level protect' in data['windows']['one_liner']
def test_token_records_requested_level(client, server, auth_headers):
client.post(f'/api/v1/servers/{server.id}/regenerate-token', headers=auth_headers,
json={'requested_level': 'protect'})
assert db.session.get(Server, server.id).requested_permission_level == 'protect'
@@ -0,0 +1,33 @@
"""GET /backups must not 500 when the backup directory cannot be created."""
import pytest
from app.services.backup_service import BackupService
@pytest.fixture
def unwritable(monkeypatch):
def deny():
raise PermissionError(13, 'Permission denied', '/var/backups/serverkit')
monkeypatch.setattr(BackupService, 'ensure_backup_dirs', deny)
@pytest.mark.parametrize('path', ['/api/v1/backups', '/api/v1/backups/stats'])
def test_get_degrades_with_a_warning(client, auth_headers, unwritable, path):
resp = client.get(path, headers=auth_headers)
assert resp.status_code == 200
body = resp.get_json()
assert 'not accessible' in body['warning']
assert '/var/backups' not in body['warning']
assert body.get('backups', []) == []
def test_create_returns_503_with_code_when_dir_unwritable(client, auth_headers, unwritable):
resp = client.post('/api/v1/backups/database', headers=auth_headers,
json={'db_type': 'mysql', 'db_name': 'x'})
assert resp.status_code == 503
body = resp.get_json()
assert body['code'] == 'backup_dir_unavailable'
assert body['error'] == 'Backup directory is not writable'
assert '/var/backups' not in resp.get_data(as_text=True)
@@ -7,9 +7,9 @@ from pathlib import Path
from app.core_blueprints import CORE_BLUEPRINTS
EXPECTED_CORE_BLUEPRINT_COUNT = 116
EXPECTED_CORE_BLUEPRINT_COUNT = 117
EXPECTED_MANIFEST_SHA256 = (
'25d28d92ccddddc246d5b2081d84b11f1df10cb662f33c256ebcbe390d2813d5'
'52abbc7429d079c7cf6ea61a638f5dc4dbd991e4f02ec31c81563e01442aa7fb'
)
+43
View File
@@ -0,0 +1,43 @@
"""A bare % in a crontab command is cron syntax: it ends the command there
and pipes the rest to it as stdin. `date +%F >> log` therefore ran as
`date +` on schedule while "Run now" (bash -c) ran the real thing, so
testing it in the panel looked fine. Lines are written escaped, and every
lookup still finds both escaped and legacy unescaped lines."""
from app.services.cron_service import CronService
from test_cron_crontab_join import linux_cron # noqa: F401 (fixture)
CMD = '/usr/bin/date +%F'
SCHEDULE = '0 3 * * *'
def _job_line(crontab):
return [line for line in crontab.split('\n') if line.lstrip('# ').startswith(SCHEDULE)]
def test_written_line_escapes_percent(linux_cron):
job_id = CronService.add_job(SCHEDULE, CMD, name='stamp')['job_id']
assert _job_line(linux_cron['crontab']) == [f'{SCHEDULE} /usr/bin/date +\%F']
job = next(j for j in CronService.list_jobs()['jobs'] if j['id'] == job_id)
assert job['command'] == CMD
def test_toggle_track_and_edit_find_the_escaped_line(linux_cron):
job_id = CronService.add_job(SCHEDULE, CMD, name='stamp')['job_id']
assert CronService.toggle_job(job_id, False)['success']
assert _job_line(linux_cron['crontab']) == [f'# {SCHEDULE} /usr/bin/date +\%F']
assert CronService.toggle_job(job_id, True)['success']
assert CronService.set_tracking(job_id, True)['success']
[line] = _job_line(linux_cron['crontab'])
assert line.endswith(f'{job_id} -- /usr/bin/date +\%F')
assert CronService.update_job(job_id, command='/usr/bin/date +%H%M')['success']
[line] = _job_line(linux_cron['crontab'])
assert line.endswith(f'{job_id} -- /usr/bin/date +\%H\%M')
def test_legacy_unescaped_line_is_still_found_and_fixed(linux_cron):
job_id = CronService.add_job(SCHEDULE, CMD, name='stamp')['job_id']
linux_cron['crontab'] = linux_cron['crontab'].replace('\%', '%') # pre-fix line
assert CronService.update_job(job_id, schedule='0 4 * * *')['success']
assert '0 4 * * * /usr/bin/date +\%F' in linux_cron['crontab']
assert '+%F' not in linux_cron['crontab'].replace('\%', '')
@@ -0,0 +1,98 @@
"""A custom domain's own certificate must survive every vhost rebuild.
"Enable SSL" used to edit the vhost in place (add_ssl_to_site) while every
later rewrite — deploys, slot switches, attaching a domain, drift repair,
restore — rebuilt it from the Domain rows, which only knew wildcard certs.
So HTTPS on shop.com vanished at the next deploy while the row still said
ssl_enabled. Rebuilds now read each domain's own cert.
"""
import pytest
from app import db
from app.models import Domain
from factories import make_application
from app.services.nginx_service import NginxService
from app.services.site_domain_service import SiteDomainService
SHOP = ('/etc/letsencrypt/live/shop.com/fullchain.pem', '/etc/letsencrypt/live/shop.com/privkey.pem')
WILD = ('/etc/le/live/acme.dev/fullchain.pem', '/etc/le/live/acme.dev/privkey.pem')
@pytest.fixture
def site(app, monkeypatch):
monkeypatch.setattr(SiteDomainService, 'covering_base',
classmethod(lambda cls, h: 'acme.dev' if h.endswith('.acme.dev') else None))
monkeypatch.setattr(SiteDomainService, 'https_enabled', classmethod(lambda cls, base: True))
monkeypatch.setattr(SiteDomainService, 'wildcard_cert_paths', classmethod(lambda cls, base: WILD))
application = make_application(db, name='shopcssl', port=8011)
shop = Domain(name='shop.com', application_id=application.id, is_primary=True,
ssl_enabled=True, ssl_certificate_path=SHOP[0], ssl_key_path=SHOP[1])
db.session.add(shop)
db.session.commit()
yield application
Domain.query.filter_by(application_id=application.id).delete()
db.session.delete(application)
db.session.commit()
def _render(application):
kwargs, reason = SiteDomainService.app_vhost_kwargs(application)
assert reason is None
rendered = NginxService.render_site_config(**kwargs)
assert rendered['success'], rendered
return kwargs, rendered['config']
def test_custom_domain_cert_is_rendered(site):
kwargs, config = _render(site)
assert (kwargs['ssl_cert'], kwargs['ssl_key']) == SHOP
assert f'ssl_certificate {SHOP[0]};' in config
def test_legacy_row_without_key_path_still_serves_https(site):
"""The domains API saved the key under a column that doesn't exist, so
older rows carry only the fullchain path."""
Domain.query.filter_by(name='shop.com').update({'ssl_key_path': None})
db.session.commit()
kwargs, _ = _render(site)
assert (kwargs['ssl_cert'], kwargs['ssl_key']) == SHOP
def test_mixed_certs_get_one_server_set_each(site):
db.session.add(Domain(name='shop.acme.dev', application_id=site.id))
db.session.add(Domain(name='plain.example.org', application_id=site.id))
db.session.commit()
kwargs, config = _render(site)
groups = {tuple(names): cert for names, *cert in kwargs['cert_groups']}
assert groups[('shop.com',)] == list(SHOP)
assert groups[('shop.acme.dev',)] == list(WILD)
assert groups[('plain.example.org',)] == [None, None]
assert config.count('listen 443 ssl') == 2 # one per HTTPS group
assert 'server_name plain.example.org;' in config
assert f'ssl_certificate {SHOP[0]};' in config and f'ssl_certificate {WILD[0]};' in config
def test_disabled_ssl_drops_back_to_http(site):
Domain.query.filter_by(name='shop.com').update({'ssl_enabled': False})
db.session.commit()
kwargs, config = _render(site)
assert kwargs['ssl_cert'] is None
assert 'ssl_certificate' not in config
def test_add_ssl_to_site_twice_swaps_the_cert(tmp_path, monkeypatch):
"""The manual path re-run must not duplicate the 443 listen."""
first = NginxService.render_site_config(
'manual', 'static', ['m.example.com'], root_path='/var/www/m',
ssl_cert='/old/fullchain.pem', ssl_key='/old/privkey.pem')['config']
written = {}
monkeypatch.setattr(NginxService, 'SITES_AVAILABLE', str(tmp_path))
(tmp_path / 'manual').write_text(first, encoding='utf-8')
monkeypatch.setattr(NginxService, 'read_vhost', classmethod(lambda cls, n: first))
monkeypatch.setattr(NginxService, 'write_vhost',
classmethod(lambda cls, n, c, **k: written.setdefault('c', c) and {'success': True}))
NginxService.add_ssl_to_site('manual', '/new/fullchain.pem', '/new/privkey.pem')
assert written['c'].count('listen 443 ssl') == first.count('listen 443 ssl')
assert 'ssl_certificate /new/fullchain.pem;' in written['c']
assert 'ssl_certificate_key /new/privkey.pem;' in written['c']
assert '/old/' not in written['c']
@@ -0,0 +1,72 @@
"""Database passwords travel in the child's environment, never on its command
line: argv is world-readable (ps, /proc/<pid>/cmdline), so `-p<pw>` or
`docker exec -e MYSQL_PWD=<pw>` handed the root DB password to every local
account — a compromised site's PHP-FPM user included."""
from unittest.mock import patch
import pytest
PW = 's3cr3t-root'
class Spy:
def __init__(self):
self.calls = []
def __call__(self, cmd, *args, **kwargs):
self.calls.append((cmd, kwargs.get('env') or {}))
return {'success': True, 'output': '', 'error': '', 'returncode': 0}
def assert_hidden(self, var):
# Only the calls that log in; a `<client> --version` probe runs first.
logins = [(cmd, env) for cmd, env in self.calls if '--version' not in cmd]
assert logins
for cmd, env in logins:
assert not any(PW in str(part) for part in cmd), cmd
assert env.get(var) == PW
def test_docker_exec_mysql_and_pg():
from app.services import database_service as mod
from app.services.database_service import DatabaseService
spy = Spy()
with patch.object(mod, 'run_checked', spy):
DatabaseService.docker_mysql_execute('db1', 'SELECT 1', password=PW)
spy.assert_hidden('MYSQL_PWD')
assert 'MYSQL_PWD' in spy.calls[-1][0] # bare name: docker copies our env
spy = Spy()
with patch.object(mod, 'run_checked', spy):
DatabaseService.docker_pg_execute('pg1', 'SELECT 1', password=PW)
spy.assert_hidden('PGPASSWORD')
def test_backup_and_restore(tmp_path):
from app.services import backup_service as mod
from app.services.backup_service import BackupService
spy = Spy()
with patch.object(mod, 'is_command_available', lambda c: True), \
patch.object(mod, 'run_to_gzip', spy):
BackupService._backup_database_internal(
'mysql', 'shop', str(tmp_path), {'user': 'root', 'password': PW})
spy.assert_hidden('MYSQL_PWD')
dump = tmp_path / 'shop.sql.gz'
dump.write_bytes(b'')
spy = Spy()
with patch.object(mod, 'is_command_available', lambda c: True), \
patch.object(mod, 'run_from_gzip', spy), \
patch.object(BackupService, '_resolve_for_restore', lambda p: (p, None)):
BackupService.restore_database(str(dump), 'mysql', 'shop', user='root', password=PW)
spy.assert_hidden('MYSQL_PWD')
@pytest.mark.parametrize('call', [
lambda S: S._run_mysql('SELECT 1', password=PW),
])
def test_db_sync(call):
from app.services import db_sync_service as mod
spy = Spy()
with patch.object(mod, 'run_checked', spy):
call(mod.DatabaseSyncService)
spy.assert_hidden('MYSQL_PWD')
@@ -0,0 +1,58 @@
"""Copying, moving, renaming or deleting a PARENT of a protected root must not
reach the panel's secrets (GHSA-rm3m-9mvw-68fh, second door): the path checks
only look at the path typed, so `copy /opt -> /home/u/x` used to carry
/opt/serverkit/.env along with it."""
import os
import pytest
from app.exceptions import PermissionDeniedError
from app.services.file_service import FileService
@pytest.fixture
def tree(tmp_path, monkeypatch):
opt = tmp_path / 'opt'
panel = opt / 'serverkit'
panel.mkdir(parents=True)
(panel / '.env').write_text('JWT_SECRET_KEY=s3cret\n', encoding='utf-8')
app_dir = opt / 'myapp'
app_dir.mkdir()
(app_dir / 'index.html').write_text('hi', encoding='utf-8')
home = tmp_path / 'home'
home.mkdir()
monkeypatch.setattr(FileService, 'ALLOWED_ROOTS', [str(opt), str(home)])
monkeypatch.setattr(FileService, 'READ_ONLY_ROOTS', [])
monkeypatch.setattr(FileService, 'PROTECTED_ROOTS', [os.path.realpath(panel)])
return {'opt': opt, 'panel': panel, 'app': app_dir, 'home': home}
def test_copying_a_parent_is_refused(tree):
dest = tree['home'] / 'loot'
with pytest.raises(PermissionDeniedError):
FileService.copy(str(tree['opt']), str(dest))
assert not dest.exists()
def test_moving_renaming_or_deleting_a_parent_is_refused(tree):
with pytest.raises(PermissionDeniedError):
FileService.move(str(tree['opt']), str(tree['home'] / 'moved'))
with pytest.raises(PermissionDeniedError):
FileService.rename(str(tree['opt']), 'renamed')
with pytest.raises(PermissionDeniedError):
FileService.delete(str(tree['opt']))
assert (tree['panel'] / '.env').exists()
def test_siblings_still_work(tree):
FileService.copy(str(tree['app']), str(tree['home'] / 'copy'))
assert (tree['home'] / 'copy' / 'index.html').read_text(encoding='utf-8') == 'hi'
FileService.delete(str(tree['app']))
assert not tree['app'].exists()
@pytest.mark.skipif(os.name == 'nt', reason='symlinks need privileges on Windows')
def test_copied_symlinks_stay_links(tree):
(tree['app'] / 'env').symlink_to(tree['panel'] / '.env')
FileService.copy(str(tree['app']), str(tree['home'] / 'copy'))
assert os.path.islink(tree['home'] / 'copy' / 'env')
+13
View File
@@ -193,3 +193,16 @@ def test_register_jobs_registers_reap_kind(app):
from app.jobs import registry
login_link_service.register_jobs()
assert login_link_service.REAP_JOB_KIND in registry.registered_kinds()
def test_concurrent_redeems_only_one_wins(client, auth_headers, monkeypatch):
"""Two requests that both read the link before either commits used to
both get a session. The claim is a conditional UPDATE, so the loser sees
zero rows even though its earlier is_used check passed."""
token = _mint(client, auth_headers).get_json()['token']
user, reason = login_link_service.redeem(token)
assert user is not None and reason is None
# Replay the race: the second request's check saw an unused link.
monkeypatch.setattr(LoginLink, 'is_used', property(lambda self: False))
user, reason = login_link_service.redeem(token)
assert user is None and reason == 'used'
-41
View File
@@ -78,44 +78,3 @@ def test_unknown_server_is_plan_issue(project, owner):
plan = ManifestApplyService.plan(project, n)
assert any(i['kind'] == 'unknown_server' and i['server'] == 'ghost'
for i in plan['issues'])
def test_manifest_preview_config(project, owner):
from app import db
from app.models import Application
from app.models.application_manifest import ApplicationManifest
from app.services.manifest_persistence_service import ManifestPersistenceService
from app.services.manifest_preview_service import ManifestPreviewService
from types import SimpleNamespace
# a manifest-managed app with declared env
manifest = {'version': 1, 'services': [{
'name': 'api', 'type': 'web', 'port': 8000,
'envVars': [{'key': 'LOG_LEVEL', 'value': 'info'}]}]}
n = ManifestSpecService.normalize(manifest)
ManifestApplyService.apply(project, n, user_id=owner.id)
ManifestPersistenceService.store_manifest(project.id, n)
db.session.commit()
api = Application.query.filter_by(project_id=project.id, name='api').first()
preview = SimpleNamespace(pr_number=42, branch='feature/x',
domain='pr-42.api.example.com')
config = ManifestPreviewService.build_preview_config(api, preview)
assert config is not None
assert config['env']['LOG_LEVEL'] == 'info' # cloned manifest env
assert config['env']['SERVERKIT_PREVIEW'] == 'true' # per-preview override
assert config['env']['SERVERKIT_PR_NUMBER'] == '42'
assert config['domain'] == 'pr-42.api.example.com'
def test_preview_config_none_for_unmanaged_app(project, owner):
from app import db
from app.models import Application
from app.services.manifest_preview_service import ManifestPreviewService
from types import SimpleNamespace
a = Application(name='plain', app_type='docker', user_id=owner.id,
project_id=project.id, status='running')
db.session.add(a)
db.session.commit()
preview = SimpleNamespace(pr_number=1, branch='b', domain='d')
assert ManifestPreviewService.build_preview_config(a, preview) is None
@@ -0,0 +1,13 @@
"""Unexpected failures answer with a generic message; the detail is only logged."""
from app.services import sso_service
def test_sso_authorize_does_not_echo_exception_text(client, monkeypatch):
def boom(*a, **kw):
raise RuntimeError('secret internal path /etc/serverkit/oidc.key')
monkeypatch.setattr(sso_service, 'generate_auth_url', boom)
resp = client.get('/api/v1/sso/authorize/google?redirect_uri=http://localhost/cb')
assert resp.status_code == 400
assert '/etc/serverkit' not in resp.get_data(as_text=True)
@@ -321,7 +321,7 @@ class TestSigningAndDelivery:
captured.update({'url': url, 'data': data, 'headers': headers})
return _Resp()
monkeypatch.setattr('app.services.chat_webhook_service.requests.post', fake_post)
monkeypatch.setattr('app.services.chat_webhook_service.safe_http.post', fake_post)
user = _make_user()
conn = ChatWebhookService.add({'kind': 'webhook', 'name': 'Ops', 'url': 'https://hooks/x',
@@ -392,7 +392,7 @@ class TestConnectionTesting:
status_code = 503
monkeypatch.setattr(
'app.services.chat_webhook_service.requests.post',
'app.services.chat_webhook_service.safe_http.post',
lambda *args, **kwargs: _Resp(),
)
conn = ChatWebhookService.add({
@@ -428,7 +428,7 @@ class TestConnectionTesting:
raise RuntimeError(f'failed POST {url}')
monkeypatch.setattr(
'app.services.chat_webhook_service.requests.post', fail_post,
'app.services.chat_webhook_service.safe_http.post', fail_post,
)
secret_url = 'https://hooks.example/super-secret-token'
conn = ChatWebhookService.add({
@@ -454,7 +454,7 @@ class TestConnectionTesting:
raise RuntimeError(f'failed POST {url}')
monkeypatch.setattr(
'app.services.chat_webhook_service.requests.post', fail_post,
'app.services.chat_webhook_service.safe_http.post', fail_post,
)
conn = ChatWebhookService.add({
'kind': 'webhook',
@@ -624,7 +624,7 @@ class TestApi:
status_code = 503
monkeypatch.setattr(
'app.services.chat_webhook_service.requests.post',
'app.services.chat_webhook_service.safe_http.post',
lambda *args, **kwargs: _Resp(),
)
conn = ChatWebhookService.add({
+107
View File
@@ -0,0 +1,107 @@
"""PermissionService + User permission resolution per role."""
import pytest
from werkzeug.security import generate_password_hash
from app import db
from app.models import User
from app.services.permission_service import PermissionService
def _user(role, name=None):
u = User(email=f'{name or role}@example.com', username=name or role,
password_hash=generate_password_hash('x'), role=role, is_active=True)
db.session.add(u)
db.session.commit()
return u
def test_role_templates_cover_every_feature_for_admin():
admin = PermissionService.get_role_template('admin')
assert set(admin) == set(User.PERMISSION_FEATURES)
assert all(v == {'read': True, 'write': True} for v in admin.values())
def test_unknown_role_has_no_permissions(app):
assert PermissionService.get_role_template('wizard') == {}
u = _user('viewer', 'nobody')
u.role = 'wizard'
assert not u.has_permission('files')
def test_developer_defaults_follow_template(app):
dev = _user('developer')
assert dev.has_permission('applications', 'write')
assert dev.has_permission('monitoring', 'read')
assert not dev.has_permission('monitoring', 'write')
assert not dev.has_permission('users') # not in the developer template
def test_admin_always_allowed(app):
admin = _user('admin')
assert all(admin.has_permission(f, 'write') for f in User.PERMISSION_FEATURES)
assert admin.has_permission('anything-at-all')
def test_viewer_cannot_write_anything(app):
viewer = _user('viewer')
assert not any(viewer.has_permission(f, 'write') for f in User.PERMISSION_FEATURES)
def test_get_user_permissions_missing_user(app):
assert PermissionService.get_user_permissions(999999) is None
def test_update_custom_permissions_overrides_role(app):
dev = _user('developer')
res = PermissionService.update_user_permissions(
dev.id, {'files': {'read': True, 'write': False}})
assert res['success']
assert res['permissions'] == {'files': {'read': True, 'write': False}}
assert not dev.has_permission('files', 'write')
assert not dev.has_permission('applications') # custom set replaces the template wholesale
def test_reset_restores_role_template(app):
dev = _user('developer')
PermissionService.update_user_permissions(dev.id, {'files': {'read': True}})
res = PermissionService.reset_to_role_defaults(dev.id)
assert res['success'] and res['permissions'] == User.ROLE_PERMISSION_TEMPLATES['developer']
assert dev.permissions is None
def test_admin_permissions_cannot_be_customized(app):
admin = _user('admin')
res = PermissionService.update_user_permissions(admin.id, {'files': {'read': False}})
assert res == {'success': False, 'error': 'Admin permissions cannot be customized'}
def test_unknown_user_is_reported(app):
assert PermissionService.update_user_permissions(424242, {}) == {
'success': False, 'error': 'User not found'}
assert PermissionService.reset_to_role_defaults(424242) == {
'success': False, 'error': 'User not found'}
@pytest.mark.parametrize('perms, fragment', [
('nope', 'must be an object'),
({'bogus': {'read': True}}, 'Unknown feature'),
({'files': True}, 'read/write object'),
({'files': {'execute': True}}, 'Invalid permission key'),
({'files': {'read': 'yes'}}, 'must be boolean'),
({'files': {'read': False, 'write': True}}, 'without read'),
])
def test_validate_permissions_rejects(perms, fragment):
assert fragment in PermissionService.validate_permissions(perms)
def test_validate_permissions_accepts_good_input():
assert PermissionService.validate_permissions({}) is None
assert PermissionService.validate_permissions(
{'files': {'read': True, 'write': True}, 'cron': {'read': True}}) is None
def test_invalid_update_does_not_persist(app):
dev = _user('developer')
res = PermissionService.update_user_permissions(dev.id, {'bogus': {}})
assert not res['success']
assert dev.permissions is None
+56
View File
@@ -0,0 +1,56 @@
"""The legacy Postgres helpers run as the postgres superuser, so every value
they put in SQL is validated or escaped like the MySQL ones next to them, and
the create-with-user routes never return credentials for a user that failed."""
from unittest.mock import patch
import pytest
from app.services.database_service import DatabaseService
@pytest.fixture
def executed():
sql = []
with patch.object(DatabaseService, 'pg_execute',
side_effect=lambda q: sql.append(q) or {'success': True, 'output': ''}):
yield sql
def test_password_quote_is_escaped(executed):
assert DatabaseService.pg_create_user('shop', "pa'ss")['success']
assert executed == ["CREATE USER \"shop\" WITH PASSWORD 'pa''ss';"]
@pytest.mark.parametrize('call', [
lambda: DatabaseService.pg_create_database('x"; DROP DATABASE prod; --'),
lambda: DatabaseService.pg_create_database('shop', owner='a" SUPERUSER'),
lambda: DatabaseService.pg_create_database('shop', encoding="UTF8'; DROP"),
lambda: DatabaseService.pg_create_user('a"b', 'pw'),
lambda: DatabaseService.pg_drop_user('a"b'),
lambda: DatabaseService.pg_grant_privileges('u', 'd', 'ALL ON SCHEMA public TO u; --'),
lambda: DatabaseService.pg_revoke_privileges('u', 'd"x'),
lambda: DatabaseService.mysql_grant_privileges('u', 'd', 'ALL; DROP USER root'),
])
def test_unsafe_values_never_reach_sql(executed, call):
with patch.object(DatabaseService, 'mysql_execute') as mysql:
assert call()['success'] is False
assert executed == []
mysql.assert_not_called()
def test_privilege_lists_still_work(executed):
assert DatabaseService.pg_grant_privileges('u', 'd', 'SELECT, INSERT')['success']
assert executed == ['GRANT SELECT, INSERT PRIVILEGES ON DATABASE "d" TO "u";']
def test_failed_user_is_not_reported_with_credentials(app, client, auth_headers):
with patch.object(DatabaseService, 'pg_create_database', return_value={'success': True}), \
patch.object(DatabaseService, 'pg_create_user',
return_value={'success': False, 'error': 'role exists'}), \
patch.object(DatabaseService, 'pg_grant_privileges') as grant:
resp = client.post('/api/v1/databases/postgresql', headers=auth_headers,
json={'name': 'pgshop', 'create_user': True})
body = resp.get_json()
assert 'password' not in body and 'user' not in body
assert body['user_error'] == 'role exists'
grant.assert_not_called()
+137
View File
@@ -0,0 +1,137 @@
"""Update detection: registry + builtin rows, compat, consent hints, API shape."""
import io
import json
import zipfile
import pytest
from app import db
from app.models.plugin import InstalledPlugin
from app.services import plugin_service, registry_service
pytestmark = pytest.mark.fresh_app
@pytest.fixture(autouse=True)
def _reset_registry_cache():
registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None})
yield
registry_service._cache.update({'ts': 0.0, 'entries': None, 'source': None})
@pytest.fixture
def plugin_dirs(tmp_path, monkeypatch):
d = {n: tmp_path / n for n in ('b', 'f', 'builtin')}
for p in d.values():
p.mkdir()
monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(d['b']))
monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(d['f']))
monkeypatch.setattr(plugin_service, 'BUILTIN_EXTENSIONS_DIR', str(d['builtin']))
return d
def _manifest(slug, version):
return {'name': slug, 'display_name': 'Ext ' + slug, 'version': version,
'category': 'utility',
'contributions': {'nav': [{'id': slug, 'label': 'X', 'route': '/x'}]}}
def _zip(slug, version):
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w') as zf:
zf.writestr('plugin.json', json.dumps(_manifest(slug, version)))
zf.writestr('frontend/index.jsx', 'export function P(){return null;}\n')
return buf.getvalue()
def _install_registry_row(monkeypatch, version='1.0.0'):
data = _zip('regext', version)
monkeypatch.setattr(plugin_service, '_download_zip', lambda url: io.BytesIO(data))
return plugin_service.install_from_url('https://x/regext.zip')
def _advertise(version, **extra):
registry_service._cache.update({
'ts': 9e18, 'source': 'test',
'entries': [registry_service._normalize({
'slug': 'regext', 'display_name': 'Registry Ext', 'version': version,
'source': 'https://x/regext.zip', 'min_panel_version': '0.0.1',
**extra})],
})
def _by_slug():
return {u['slug']: u for u in plugin_service.check_for_updates()}
def test_registry_update_fields(app, plugin_dirs, monkeypatch):
_install_registry_row(monkeypatch)
_advertise('2.0.0')
u = _by_slug()['regext']
assert u['update_available'] is True
assert u['display_name'] == 'Registry Ext'
assert u['update_source'] == 'registry'
assert isinstance(u['requires_ack'], bool)
assert u['requires_ack'] == (u['risk'] is not None)
assert u['incompatible_reason'] is None
def test_up_to_date(app, plugin_dirs, monkeypatch):
_install_registry_row(monkeypatch)
_advertise('1.0.0')
assert _by_slug()['regext']['update_available'] is False
def test_incompatible_panel(app, plugin_dirs, monkeypatch):
_install_registry_row(monkeypatch)
_advertise('2.0.0', min_panel_version='999.0.0')
u = _by_slug()['regext']
assert u['compatible'] is False
assert '999.0.0' in u['incompatible_reason']
def test_malformed_version_no_raise(app, plugin_dirs, monkeypatch):
p = _install_registry_row(monkeypatch)
_advertise('banana')
assert _by_slug()['regext']['update_available'] is False
p.version = 'also-bad'
db.session.commit()
assert _by_slug()['regext']['update_available'] is False
def test_builtin_update(app, plugin_dirs, monkeypatch):
folder = plugin_dirs['builtin'] / 'bi-ext'
(folder / 'frontend').mkdir(parents=True)
(folder / 'frontend' / 'index.jsx').write_text('export function P(){return null;}\n')
(folder / 'plugin.json').write_text(json.dumps(_manifest('bi-ext', '1.0.0')))
p = plugin_service.install_from_path(str(folder), source_type='builtin')
assert p.source_type == 'builtin'
# A registry entry with the same slug must be ignored for builtin rows.
assert plugin_service.check_for_updates()[0]['update_available'] is False
(folder / 'plugin.json').write_text(json.dumps(_manifest('bi-ext', '1.1.0')))
u = _by_slug()['bi-ext']
assert u['update_available'] is True
assert u['update_source'] == 'builtin'
assert u['requires_ack'] is False and u['risk'] is None
updated = plugin_service.update_plugin(p.id)
assert updated.version == '1.1.0'
assert updated.source_type == 'builtin'
assert InstalledPlugin.query.filter_by(slug='bi-ext').count() == 1
def test_api_shape_and_refresh(app, client, auth_headers, plugin_dirs, monkeypatch):
calls = []
_install_registry_row(monkeypatch)
_advertise('2.0.0')
monkeypatch.setattr(registry_service, 'refresh',
lambda force=False: calls.append(force) or registry_service._cache['entries'])
r = client.get('/api/v1/plugins/updates', headers=auth_headers)
assert r.status_code == 200
body = r.get_json()
assert body['count'] == 1 and body['checked_at']
assert 'registry_source' in body
assert True not in calls
client.get('/api/v1/plugins/updates?refresh=1', headers=auth_headers)
assert True in calls
@@ -0,0 +1,54 @@
"""The public /servers/register route ran a deliberately slow PBKDF2 check
against EVERY pending server for each request, so one bad token cost one slow
hash per pending server — unauthenticated CPU burn on the single worker.
Tokens are 256 random bits, so a SHA-256 digest is enough and is looked up
directly; pre-switch hashes still verify until they expire."""
from datetime import datetime, timedelta
from unittest.mock import patch
from werkzeug.security import generate_password_hash
from app import db
from app.models.server import Server
from factories import make_server
def _pending(token, legacy=False):
server = make_server(db, name=f'reg-{token[-6:]}')
if legacy:
server.registration_token_hash = generate_password_hash(token)
else:
server.set_registration_token(token)
server.registration_token_expires = datetime.utcnow() + timedelta(hours=1)
db.session.commit()
return server
def test_bad_token_runs_no_slow_hash(app):
for n in range(5):
_pending(Server.generate_registration_token())
with patch('app.models.server.check_password_hash') as slow:
assert Server.find_by_registration_token('sk_reg_nope') is None
slow.assert_not_called()
def test_good_and_legacy_tokens_pair(app):
token = Server.generate_registration_token()
server = _pending(token)
assert Server.find_by_registration_token(token).id == server.id
old = Server.generate_registration_token()
legacy = _pending(old, legacy=True)
assert Server.find_by_registration_token(old).id == legacy.id
def test_expired_digest_token_is_refused(app):
token = Server.generate_registration_token()
server = _pending(token)
server.registration_token_expires = datetime.utcnow() - timedelta(minutes=1)
db.session.commit()
assert Server.find_by_registration_token(token) is None
def test_register_route_rejects_non_string_token(client):
assert client.post('/api/v1/servers/register', json={'token': 12345}).status_code == 400
+1
View File
@@ -145,6 +145,7 @@ PUBLIC_ALT_AUTH = {
# Public by design; the value names the mechanism that authenticates the call.
'agent_poll.connect': 'agent HMAC handshake + per-IP throttle',
'agent_poll.disconnect': 'X-Session-Token lookup',
'agent_report.report': 'HMAC over timestamp+nonce+body hash, skew/replay/rate limits',
'agent_poll.poll': 'X-Session-Token resolves the ConnectedAgent',
'agent_poll.result': 'X-Session-Token resolves the ConnectedAgent',
'auth.connect_session': 'loopback-only + Cloud grant verified against JWKS, 30/min',
+1
View File
@@ -221,6 +221,7 @@ VIEWER_WRITABLE = {
'docker.get_containers_stats',
# PUBLIC transport — agent long-poll fallback; user JWT is ignored here.
'agent_poll.disconnect',
'agent_report.report',
# PUBLIC authentication challenge only; credential verification and UV are
# required by passkey_authenticate before any session tokens are issued.
'auth.passkey_auth_options',
+48
View File
@@ -20,6 +20,14 @@ PANEL_NGINX_CONFIGS = [
/ 'sites-available'
/ 'serverkit.conf',
]
ROOT = Path(__file__).resolve().parents[2]
ALL_CSP_CONFIGS = PANEL_NGINX_CONFIGS + [
ROOT / 'nginx' / 'sites-available' / 'example.conf.template',
]
def _script_src(csp):
return next(d.strip() for d in csp.split(';') if d.strip().startswith('script-src '))
def _make_app(hsts_enabled, debug):
@@ -86,3 +94,43 @@ def test_resolve_ssl_mode(monkeypatch):
assert cfg._resolve_ssl_mode() == 'insecure'
monkeypatch.delenv('SERVERKIT_SSL_MODE', raising=False)
assert cfg._resolve_ssl_mode() == 'insecure'
def test_prod_csp_script_src_is_strict():
r = _make_app(hsts_enabled=False, debug=False).test_client().get('/ping')
script_src = _script_src(r.headers['Content-Security-Policy'])
assert 'unsafe-eval' not in script_src
assert 'unsafe-inline' not in script_src
@pytest.mark.parametrize('config_path', ALL_CSP_CONFIGS)
def test_nginx_csp_script_src_is_strict(config_path):
line = next(
l for l in config_path.read_text(encoding='utf-8').splitlines()
if 'Content-Security-Policy' in l
)
script_src = _script_src(line.split('"')[1])
assert 'unsafe-eval' not in script_src
assert 'unsafe-inline' not in script_src
def test_index_html_has_no_inline_script():
html = (ROOT / 'frontend' / 'index.html').read_text(encoding='utf-8')
assert '<script>' not in html
def test_csp_importmap_hash_matches_vendor_manifest():
import base64, hashlib, json, re
from app.middleware.security import VENDOR_IMPORTMAP_HASH
src = (ROOT / 'frontend/src/plugins/runtime/vendorManifest.js').read_text(encoding='utf-8')
pairs = re.findall(r"specifier: '([^']+)', file: '([^']+)'", src)
body = json.dumps({'imports': {s: '/serverkit-vendor/' + f for s, f in pairs}}, separators=(',', ':'))
digest = base64.b64encode(hashlib.sha256(body.encode()).digest()).decode()
assert VENDOR_IMPORTMAP_HASH == 'sha256-' + digest
for path in ALL_CSP_CONFIGS:
assert VENDOR_IMPORTMAP_HASH in path.read_text(encoding='utf-8')
def test_managed_app_nginx_template_has_no_unsafe_eval():
from app.services.nginx import templates
assert 'unsafe-eval' not in Path(templates.__file__).read_text(encoding='utf-8')
@@ -94,7 +94,6 @@ APPLICATION_BASELINE = {
'test_manifest_appliance_volumes_bootstrap.py',
'test_manifest_network_identity.py',
'test_manifest_persistence.py',
'test_manifest_reach.py',
'test_manifest_references.py',
'test_manifest_spec.py',
'test_manifest_sync.py',
@@ -0,0 +1,17 @@
import importlib.util
from pathlib import Path
from app.models.metric_alert import MetricAlert
from app.models.server import Server
def test_seed_is_idempotent(app):
path = Path(__file__).parents[1] / 'scripts/seed_permission_demo.py'
spec = importlib.util.spec_from_file_location('seed_demo', path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
mod.seed()
mod.seed()
assert Server.query.filter(Server.agent_id.like('demo-perm-%')).count() == 5
assert Server.query.filter_by(status='offline').count() == 1
assert MetricAlert.query.filter_by(metric='offline').count() == 1
Loaded 100 of 489 files, more files were not shown because too many files have changed in this diff. Show more