Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

refactor(secrets): vaults + webhook gateway onto the typed-error contract

Juan Denis6337066fadcf
diff --git a/backend/app/api/secrets_webhooks.py b/backend/app/api/secrets_webhooks.py
index c603231b..17eeb24c 100644
--- a/backend/app/api/secrets_webhooks.py
+++ b/backend/app/api/secrets_webhooks.py
@@ -129,11 +129,9 @@ def create_vault():
workspace_id = explicit_ws
else:
workspace_id = WorkspaceService.resolve_workspace_id(user, _resolve_ws_value())
- result = SecretVaultService.create_vault(name, description=data.get('description'),
- user_id=user.id, workspace_id=workspace_id)
- if not result.get('success'):
- return {'error': result.get('error')}, 409
- return result, 201
+ vault = SecretVaultService.create_vault(name, description=data.get('description'),
+ user_id=user.id, workspace_id=workspace_id)
+ return {'success': True, 'vault': vault}, 201
@bp.route('/vaults/<int:vault_id>', methods=['GET'])
@@ -152,10 +150,8 @@ def update_vault(vault_id):
if err:
return err
data = _json_or_form()
- result = SecretVaultService.update_vault(vault.id, name=data.get('name'), description=data.get('description'))
- if not result.get('success'):
- return {'error': result.get('error')}, 404 if 'not found' in result.get('error', '').lower() else 409
- return result
+ updated = SecretVaultService.update_vault(vault.id, name=data.get('name'), description=data.get('description'))
+ return {'success': True, 'vault': updated}
@bp.route('/vaults/<int:vault_id>', methods=['DELETE'])
@@ -164,10 +160,8 @@ def delete_vault(vault_id):
vault, err = _vault_gate(vault_id, roles=_WS_WRITE_ROLES)
if err:
return err
- result = SecretVaultService.delete_vault(vault.id)
- if not result.get('success'):
- return {'error': result.get('error')}, 404
- return result
+ SecretVaultService.delete_vault(vault.id)
+ return {'success': True, 'message': 'Vault deleted'}
# ---------- Secrets ----------
@@ -198,10 +192,8 @@ def create_secret(vault_id):
expires_at = datetime.fromisoformat(data['expires_at'])
except ValueError:
return {'error': 'Invalid expires_at format'}, 400
- result = SecretService.create_secret(vault.id, name, value, description=data.get('description'), expires_at=expires_at)
- if not result.get('success'):
- return {'error': result.get('error')}, 409 if 'already exists' in result.get('error', '').lower() else 400
- return result, 201
+ secret = SecretService.create_secret(vault.id, name, value, description=data.get('description'), expires_at=expires_at)
+ return {'success': True, 'secret': secret}, 201
@bp.route('/vaults/<int:vault_id>/secrets/bulk', methods=['POST'])
@@ -215,7 +207,7 @@ def bulk_create_secrets(vault_id):
if not isinstance(secrets_list, list):
return {'error': 'secrets must be a list'}, 400
result = SecretService.bulk_create_or_update(vault.id, secrets_list)
- return result, 207
+ return {'success': True, **result}, 207
@bp.route('/secrets/<int:secret_id>', methods=['GET'])
@@ -240,16 +232,14 @@ def update_secret(secret_id):
expires_at = datetime.fromisoformat(data['expires_at'])
except ValueError:
return {'error': 'Invalid expires_at format'}, 400
- result = SecretService.update_secret(
+ updated = SecretService.update_secret(
secret.id,
value=data.get('value'),
description=data.get('description'),
expires_at=expires_at,
rotate=data.get('rotate', False),
)
- if not result.get('success'):
- return {'error': result.get('error')}, 404
- return result
+ return {'success': True, 'secret': updated}
@bp.route('/secrets/<int:secret_id>/reveal', methods=['POST'])
@@ -260,10 +250,8 @@ def reveal_secret(secret_id):
secret, err = _secret_gate(secret_id, roles=_WS_WRITE_ROLES)
if err:
return err
- result = SecretService.reveal_secret(secret.id)
- if not result.get('success'):
- return {'error': result.get('error')}, 404
- return result
+ revealed = SecretService.reveal_secret(secret.id)
+ return {'success': True, 'secret': revealed}
@bp.route('/secrets/<int:secret_id>', methods=['DELETE'])
@@ -272,10 +260,8 @@ def delete_secret(secret_id):
secret, err = _secret_gate(secret_id, roles=_WS_WRITE_ROLES)
if err:
return err
- result = SecretService.delete_secret(secret.id)
- if not result.get('success'):
- return {'error': result.get('error')}, 404
- return result
+ SecretService.delete_secret(secret.id)
+ return {'success': True, 'message': 'Secret deleted'}
# ---------- Webhook Endpoints ----------
@@ -293,7 +279,7 @@ def create_webhook_endpoint():
name = data.get('name')
if not name:
return {'error': 'name is required'}, 400
- result = WebhookGatewayService.create_endpoint(
+ endpoint = WebhookGatewayService.create_endpoint(
name=name,
secret=data.get('secret'),
forward_url=data.get('forward_url'),
@@ -302,9 +288,7 @@ def create_webhook_endpoint():
user_id=_current_user_id(),
workspace_id=_resolve_ws(),
)
- if not result.get('success'):
- return {'error': result.get('error')}, 409
- return result, 201
+ return {'success': True, 'endpoint': endpoint}, 201
@bp.route('/webhooks/endpoints/<int:endpoint_id>', methods=['GET'])
@@ -323,7 +307,7 @@ def update_webhook_endpoint(endpoint_id):
if err:
return err
data = _json_or_form()
- result = WebhookGatewayService.update_endpoint(
+ updated = WebhookGatewayService.update_endpoint(
endpoint.id,
name=data.get('name'),
forward_url=data.get('forward_url'),
@@ -331,9 +315,7 @@ def update_webhook_endpoint(endpoint_id):
retry_count=data.get('retry_count'),
is_active=data.get('is_active'),
)
- if not result.get('success'):
- return {'error': result.get('error')}, 404 if 'not found' in result.get('error', '').lower() else 409
- return result
+ return {'success': True, 'endpoint': updated}
@bp.route('/webhooks/endpoints/<int:endpoint_id>/regenerate-secret', methods=['POST'])
@@ -344,9 +326,7 @@ def regenerate_webhook_secret(endpoint_id):
if err:
return err
result = WebhookGatewayService.regenerate_secret(endpoint.id)
- if not result.get('success'):
- return {'error': result.get('error')}, 404
- return result
+ return {'success': True, **result}
@bp.route('/webhooks/endpoints/<int:endpoint_id>', methods=['DELETE'])
@@ -355,10 +335,8 @@ def delete_webhook_endpoint(endpoint_id):
endpoint, err = _endpoint_gate(endpoint_id, roles=_WS_WRITE_ROLES)
if err:
return err
- result = WebhookGatewayService.delete_endpoint(endpoint.id)
- if not result.get('success'):
- return {'error': result.get('error')}, 404
- return result
+ WebhookGatewayService.delete_endpoint(endpoint.id)
+ return {'success': True, 'message': 'Endpoint deleted'}
@bp.route('/webhooks/endpoints/<int:endpoint_id>/deliveries', methods=['GET'])
@@ -378,10 +356,10 @@ def replay_webhook_delivery(delivery_id):
delivery, err = _delivery_gate(delivery_id, roles=_WS_WRITE_ROLES)
if err:
return err
+ # The replay operation succeeding and the forward succeeding are two
+ # different facts; a failed forward is data, not an HTTP error.
result = WebhookGatewayService.replay_delivery(delivery.id)
- if not result.get('success'):
- return {'error': result.get('error')}, 404
- return result
+ return {'success': result['forwarded'], 'delivery': result['delivery']}
# ---------- Public webhook receiver ----------
diff --git a/backend/app/services/secret_vault_service.py b/backend/app/services/secret_vault_service.py
index 4a35141a..d179a93d 100644
--- a/backend/app/services/secret_vault_service.py
+++ b/backend/app/services/secret_vault_service.py
@@ -7,6 +7,13 @@ from datetime import datetime
from typing import Dict, List, Optional
from app import db
+from app.exceptions import (
+ ApplicationError,
+ ConflictError,
+ DependencyUnavailableError,
+ NotFoundError,
+ ValidationError,
+)
from app.models import Secret, SecretVault
from app.utils.crypto import encrypt_secret, decrypt_secret_safe
from app.utils.slug import unique_slug
@@ -40,7 +47,7 @@ class SecretVaultService:
def create_vault(cls, name: str, description: str = None, user_id: int = None,
workspace_id: int = None) -> Dict:
if SecretVault.query.filter_by(name=name).first():
- return {'success': False, 'error': 'Vault name already exists'}
+ raise ConflictError('Vault name already exists')
vault = SecretVault(
name=name,
slug=_unique_slug(name),
@@ -50,31 +57,30 @@ class SecretVaultService:
)
db.session.add(vault)
db.session.commit()
- return {'success': True, 'vault': vault.to_dict()}
+ return vault.to_dict()
@classmethod
def update_vault(cls, vault_id: int, name: str = None, description: str = None) -> Dict:
vault = cls.get_vault(vault_id)
if not vault:
- return {'success': False, 'error': 'Vault not found'}
+ raise NotFoundError('Vault not found')
if name is not None:
existing = SecretVault.query.filter(SecretVault.name == name, SecretVault.id != vault_id).first()
if existing:
- return {'success': False, 'error': 'Vault name already exists'}
+ raise ConflictError('Vault name already exists')
vault.name = name
if description is not None:
vault.description = description
db.session.commit()
- return {'success': True, 'vault': vault.to_dict()}
+ return vault.to_dict()
@classmethod
def delete_vault(cls, vault_id: int) -> Dict:
vault = cls.get_vault(vault_id)
if not vault:
- return {'success': False, 'error': 'Vault not found'}
+ raise NotFoundError('Vault not found')
db.session.delete(vault)
db.session.commit()
- return {'success': True, 'message': 'Vault deleted'}
class SecretService:
@@ -95,27 +101,24 @@ class SecretService:
return Secret.query.filter_by(vault_id=vault_id, name=name).first()
@classmethod
- def _validate_name(cls, name: str) -> Optional[str]:
+ def _validate_name(cls, name: str) -> None:
if not name:
- return 'Name is required'
+ raise ValidationError('Name is required')
if not cls._NAME_RE.match(name):
- return 'Name must start with a letter or underscore and contain only letters, digits, and underscores'
- return None
+ raise ValidationError('Name must start with a letter or underscore and contain only letters, digits, and underscores')
@classmethod
def create_secret(cls, vault_id: int, name: str, value: str,
description: str = None, expires_at=None) -> Dict:
if not SecretVault.query.get(vault_id):
- return {'success': False, 'error': 'Vault not found'}
- err = cls._validate_name(name)
- if err:
- return {'success': False, 'error': err}
+ raise NotFoundError('Vault not found')
+ cls._validate_name(name)
if Secret.query.filter_by(vault_id=vault_id, name=name).first():
- return {'success': False, 'error': 'Secret name already exists in this vault'}
+ raise ConflictError('Secret name already exists in this vault')
try:
encrypted = encrypt_secret(value)
except Exception as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='encryption_error') from e
secret = Secret(
vault_id=vault_id,
name=name,
@@ -125,19 +128,19 @@ class SecretService:
)
db.session.add(secret)
db.session.commit()
- return {'success': True, 'secret': secret.to_dict(include_value=True, mask=True)}
+ return secret.to_dict(include_value=True, mask=True)
@classmethod
def update_secret(cls, secret_id: int, value: str = None, description: str = None,
expires_at=None, rotate: bool = False) -> Dict:
secret = cls.get_secret(secret_id)
if not secret:
- return {'success': False, 'error': 'Secret not found'}
+ raise NotFoundError('Secret not found')
if value is not None:
try:
secret.encrypted_value = encrypt_secret(value)
except Exception as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='encryption_error') from e
secret.updated_at = datetime.utcnow()
if description is not None:
secret.description = description
@@ -149,35 +152,37 @@ class SecretService:
try:
secret.encrypted_value = encrypt_secret(decrypted)
except Exception as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='encryption_error') from e
secret.updated_at = datetime.utcnow()
db.session.commit()
- return {'success': True, 'secret': secret.to_dict(include_value=True, mask=True)}
+ return secret.to_dict(include_value=True, mask=True)
@classmethod
def delete_secret(cls, secret_id: int) -> Dict:
secret = cls.get_secret(secret_id)
if not secret:
- return {'success': False, 'error': 'Secret not found'}
+ raise NotFoundError('Secret not found')
db.session.delete(secret)
db.session.commit()
- return {'success': True, 'message': 'Secret deleted'}
@classmethod
def reveal_secret(cls, secret_id: int) -> Dict:
secret = cls.get_secret(secret_id)
if not secret:
- return {'success': False, 'error': 'Secret not found'}
+ raise NotFoundError('Secret not found')
value = secret.value
if value is None:
- return {'success': False, 'error': 'Unable to decrypt secret'}
- return {'success': True, 'secret': secret.to_dict(include_value=True, mask=False)}
+ raise DependencyUnavailableError('Unable to decrypt secret')
+ return secret.to_dict(include_value=True, mask=False)
@classmethod
def bulk_create_or_update(cls, vault_id: int, secrets_list: List[Dict]) -> Dict:
- """Create or update many secrets. Each item needs name and value."""
+ """Create or update many secrets. Each item needs name and value.
+
+ Per-item failures are collected, not raised — a bulk import reports
+ what it could and could not apply."""
if not SecretVault.query.get(vault_id):
- return {'success': False, 'error': 'Vault not found'}
+ raise NotFoundError('Vault not found')
results = []
errors = []
for item in secrets_list:
@@ -187,15 +192,15 @@ class SecretService:
errors.append({'name': name, 'error': 'name and value required'})
continue
existing = cls.get_secret_by_name(vault_id, name)
- if existing:
- result = cls.update_secret(existing.id, value=value)
- else:
- result = cls.create_secret(vault_id, name, value, description=item.get('description'))
- if result.get('success'):
- results.append(result['secret'])
- else:
- errors.append({'name': name, 'error': result.get('error')})
- return {'success': True, 'secrets': results, 'errors': errors}
+ try:
+ if existing:
+ results.append(cls.update_secret(existing.id, value=value))
+ else:
+ results.append(cls.create_secret(
+ vault_id, name, value, description=item.get('description')))
+ except ApplicationError as e:
+ errors.append({'name': name, 'error': e.message})
+ return {'secrets': results, 'errors': errors}
@classmethod
def resolve_env_dict(cls, vault_id: int, prefix: str = '') -> Dict[str, str]:
diff --git a/backend/app/services/webhook_gateway_service.py b/backend/app/services/webhook_gateway_service.py
index 1d8779c6..4f3cb200 100644
--- a/backend/app/services/webhook_gateway_service.py
+++ b/backend/app/services/webhook_gateway_service.py
@@ -11,6 +11,7 @@ from typing import Dict, List, Optional
import requests
from app import db
+from app.exceptions import ConflictError, NotFoundError, ValidationError
from app.models import WebhookEndpoint, WebhookDelivery
from app.utils.slug import unique_slug
@@ -48,7 +49,7 @@ class WebhookGatewayService:
filter_paths: List[str] = None, retry_count: int = 3,
user_id: int = None, workspace_id: int = None) -> Dict:
if WebhookEndpoint.query.filter_by(name=name).first():
- return {'success': False, 'error': 'Endpoint name already exists'}
+ raise ConflictError('Endpoint name already exists')
endpoint = WebhookEndpoint(
name=name,
slug=cls._unique_slug(name),
@@ -62,7 +63,7 @@ class WebhookGatewayService:
endpoint.set_filter_paths(filter_paths)
db.session.add(endpoint)
db.session.commit()
- return {'success': True, 'endpoint': endpoint.to_dict()}
+ return endpoint.to_dict()
@classmethod
def update_endpoint(cls, endpoint_id: int, name: str = None, forward_url: str = None,
@@ -70,11 +71,11 @@ class WebhookGatewayService:
is_active: bool = None) -> Dict:
endpoint = cls.get_endpoint(endpoint_id)
if not endpoint:
- return {'success': False, 'error': 'Endpoint not found'}
+ raise NotFoundError('Endpoint not found')
if name is not None:
existing = WebhookEndpoint.query.filter(WebhookEndpoint.name == name, WebhookEndpoint.id != endpoint_id).first()
if existing:
- return {'success': False, 'error': 'Endpoint name already exists'}
+ raise ConflictError('Endpoint name already exists')
endpoint.name = name
if forward_url is not None:
endpoint.forward_url = forward_url
@@ -85,25 +86,24 @@ class WebhookGatewayService:
if is_active is not None:
endpoint.is_active = is_active
db.session.commit()
- return {'success': True, 'endpoint': endpoint.to_dict()}
+ return endpoint.to_dict()
@classmethod
def delete_endpoint(cls, endpoint_id: int) -> Dict:
endpoint = cls.get_endpoint(endpoint_id)
if not endpoint:
- return {'success': False, 'error': 'Endpoint not found'}
+ raise NotFoundError('Endpoint not found')
db.session.delete(endpoint)
db.session.commit()
- return {'success': True, 'message': 'Endpoint deleted'}
@classmethod
def regenerate_secret(cls, endpoint_id: int) -> Dict:
endpoint = cls.get_endpoint(endpoint_id)
if not endpoint:
- return {'success': False, 'error': 'Endpoint not found'}
+ raise NotFoundError('Endpoint not found')
endpoint.secret = secrets.token_urlsafe(32)
db.session.commit()
- return {'success': True, 'endpoint': endpoint.to_dict(), 'secret': endpoint.secret}
+ return {'endpoint': endpoint.to_dict(), 'secret': endpoint.secret}
@classmethod
def _extract_signature(cls, headers: Dict) -> tuple:
@@ -241,10 +241,10 @@ class WebhookGatewayService:
def replay_delivery(cls, delivery_id: int) -> Dict:
delivery = cls.get_delivery(delivery_id)
if not delivery:
- return {'success': False, 'error': 'Delivery not found'}
+ raise NotFoundError('Delivery not found')
endpoint = delivery.endpoint
if not endpoint or not endpoint.forward_url:
- return {'success': False, 'error': 'Endpoint has no forward URL'}
+ raise ValidationError('Endpoint has no forward URL')
payload = (delivery.payload or '').encode('utf-8')
headers = delivery.get_headers()
result = cls._forward(endpoint, delivery, payload, headers)
@@ -254,4 +254,4 @@ class WebhookGatewayService:
delivery.error_message = result.get('error')
delivery.completed_at = datetime.utcnow()
db.session.commit()
- return {'success': result.get('success', False), 'delivery': delivery.to_dict()}
+ return {'forwarded': result.get('success', False), 'delivery': delivery.to_dict()}
diff --git a/backend/tests/STATUS_SNIFFING_CEILING b/backend/tests/STATUS_SNIFFING_CEILING
index 1e8b3149..00750edc 100644
--- a/backend/tests/STATUS_SNIFFING_CEILING
+++ b/backend/tests/STATUS_SNIFFING_CEILING
@@ -1 +1 @@
-6
+3
diff --git a/frontend/src/components/settings/WebhooksTab.jsx b/frontend/src/components/settings/WebhooksTab.jsx
index 87f7b585..01836c5e 100644
--- a/frontend/src/components/settings/WebhooksTab.jsx
+++ b/frontend/src/components/settings/WebhooksTab.jsx
@@ -111,9 +111,15 @@ export default function WebhooksTab() {
async function replayDelivery(deliveryId) {
try {
- await api.replayWebhookDelivery(deliveryId);
+ // A failed forward answers 200 with success:false — the replay ran,
+ // the target refused it. Only transport/authz errors throw.
+ const res = await api.replayWebhookDelivery(deliveryId);
openEndpoint(selectedEndpoint.id);
- toast.success('Replayed delivery');
+ if (res && res.success === false) {
+ toast.error('Replayed, but the forward target did not accept it');
+ } else {
+ toast.success('Replayed delivery');
+ }
} catch (err) {
toast.error(`Replay failed: ${err.message}`);
}