feat(restore-points): add authorized lifecycle API

This commit is contained in:
Juan Denis committed 2026-08-23 17:00:50 -04:00
1 parent cf2cce6041
commit aa82fc4082
6 files changed
+890 -3

No files matched your search

+247
View File
@@ -0,0 +1,247 @@
"""Generic restore-point lifecycle API (Plan 81, M3).
Application-owned scopes use the existing ResourceGrant seam. Host-level
surfaces are operational and require a developer role even when their local
``server_id`` is NULL. Persistence and adapter work stay in the service layer.
"""
from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from app.exceptions import PermissionDeniedError, ValidationError
from app.middleware.rbac import developer_required, get_current_user
from app.services import restore_point_service
from app.services.resource_grant_service import ResourceGrantService
restore_points_bp = Blueprint('restore_points', __name__)
_APP_SCOPE_TYPES = frozenset({'application', 'env'})
_LIST_QUERY_KEYS = frozenset({'scope_type', 'scope_id', 'server_id', 'limit'})
_CREATE_BODY_KEYS = frozenset({'scope_type', 'scope_id', 'label'})
def _require_active_user(user):
if user is None:
raise PermissionDeniedError('Authenticated user not found')
if not user.is_active:
raise PermissionDeniedError('Account is deactivated')
def _require_developer(user):
_require_active_user(user)
if user is None or not user.is_developer:
raise PermissionDeniedError(
'Developer access required for operational restore points',
)
def _authorize_scope(user, scope_type, scope_id, *, write=False):
"""Authorize one scope and return its Application when app-owned."""
_require_active_user(user)
if scope_type in _APP_SCOPE_TYPES:
application = restore_point_service.resolve_application_scope(
scope_type, scope_id,
)
allowed = (
ResourceGrantService.can_edit_app(user, application)
if write else
ResourceGrantService.can_access_app(user, application)
)
if not allowed:
raise PermissionDeniedError('Access denied to application scope')
return application
_require_developer(user)
return None
def _authorize_point(point, *, write=False):
_authorize_scope(
get_current_user(), point.scope_type, point.scope_id, write=write,
)
return point
def _point_for_caller(point_id, *, write=False):
point = restore_point_service.get(point_id)
return _authorize_point(point, write=write)
def _text_field(value, name, *, required=False, max_length=None):
if value is None:
if required:
raise ValidationError(f'{name} is required')
return None
if not isinstance(value, str):
raise ValidationError(f'{name} must be a string')
value = value.strip()
if required and not value:
raise ValidationError(f'{name} is required')
if max_length is not None and len(value) > max_length:
raise ValidationError(
f'{name} must not exceed {max_length} characters',
)
return value or None
def _limit_arg():
raw = request.args.get('limit', '50')
try:
value = int(raw)
except (TypeError, ValueError) as exc:
raise ValidationError('limit must be an integer') from exc
if value < 1 or value > 200:
raise ValidationError('limit must be between 1 and 200')
return value
def _serialize(point, *, include_payload):
data = point.to_dict()
if not include_payload:
data.pop('payload', None)
return data
@restore_points_bp.route('', methods=['GET'])
@jwt_required()
def list_restore_points():
"""List a scope's linear restore-point timeline, newest first."""
unknown = set(request.args) - _LIST_QUERY_KEYS
if unknown:
raise ValidationError(
'Unknown query parameters',
details={'fields': sorted(unknown)},
)
scope_type = _text_field(
request.args.get('scope_type'), 'scope_type', max_length=32,
)
scope_id = _text_field(
request.args.get('scope_id'), 'scope_id', max_length=255,
)
server_id = _text_field(
request.args.get('server_id'), 'server_id', max_length=36,
)
if scope_id is not None and scope_type is None:
raise ValidationError('scope_type is required when scope_id is set')
user = get_current_user()
_require_active_user(user)
if scope_type is not None:
if scope_type in _APP_SCOPE_TYPES and scope_id is not None:
_authorize_scope(user, scope_type, scope_id)
elif scope_type not in _APP_SCOPE_TYPES:
_require_developer(user)
if server_id is not None:
_require_developer(user)
restore_point_service.resolve_server(server_id)
kwargs = {
'scope_type': scope_type,
'scope_id': scope_id,
'limit': _limit_arg(),
'allowed_application_scope_ids': (
restore_point_service.accessible_application_scope_ids(user)
),
'include_operational': bool(user.is_developer),
}
if server_id is not None:
kwargs['server_id'] = server_id
points = restore_point_service.list_points(**kwargs)
return jsonify({
'restore_points': [
_serialize(point, include_payload=False) for point in points
],
}), 200
@restore_points_bp.route('', methods=['POST'])
@developer_required
def create_restore_point():
"""Create a retained, manually labelled quicksave for one local scope."""
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise ValidationError('Request body must be a JSON object')
unknown = set(body) - _CREATE_BODY_KEYS
if unknown:
raise ValidationError(
'Unknown request fields', details={'fields': sorted(unknown)},
)
scope_type = _text_field(
body.get('scope_type'), 'scope_type', required=True, max_length=32,
)
scope_id = _text_field(
body.get('scope_id'), 'scope_id', required=True, max_length=255,
)
label = _text_field(body.get('label'), 'label', max_length=255)
user = get_current_user()
application = _authorize_scope(user, scope_type, scope_id, write=True)
# Environment state is application-owned. Its server association is
# derived from that trusted row; callers cannot stamp arbitrary servers.
server_id = application.server_id if scope_type == 'env' else None
point = restore_point_service.capture_manual(
scope_type, scope_id, label=label, actor=user, server_id=server_id,
)
return jsonify({
'restore_point': _serialize(point, include_payload=True),
}), 201
@restore_points_bp.route('/<point_id>', methods=['GET'])
@jwt_required()
def get_restore_point(point_id):
"""Fetch a restore point including its already-secret-safe payload."""
point = _point_for_caller(point_id)
return jsonify({
'restore_point': _serialize(point, include_payload=True),
}), 200
@restore_points_bp.route('/<point_id>/diff', methods=['GET'])
@jwt_required()
def diff_restore_point(point_id):
"""Diff against the previous point or an explicit same-scope point."""
unknown = set(request.args) - {'against'}
if unknown:
raise ValidationError(
'Unknown query parameters',
details={'fields': sorted(unknown)},
)
_point_for_caller(point_id)
against = request.args.get('against', 'previous')
if against not in ('', 'previous'):
# Load and authorize before the service compares scopes, so a guessed
# point id can never become an authorization bypass.
_point_for_caller(against)
return jsonify(restore_point_service.diff(point_id, against=against)), 200
@restore_points_bp.route('/<point_id>/preview', methods=['POST'])
@developer_required
def preview_restore_point(point_id):
"""Dry-run a restore with coverage and refusal information."""
point = _point_for_caller(point_id, write=True)
return jsonify(restore_point_service.preview(
point.id, actor=get_current_user(),
)), 200
@restore_points_bp.route('/<point_id>/restore', methods=['POST'])
@developer_required
def restore_restore_point(point_id):
"""Re-converge a scope through its adapter's normal mutation doors."""
point = _point_for_caller(point_id, write=True)
result = restore_point_service.restore(
point.id, actor=get_current_user(),
)
if isinstance(result, dict) and result.get('success') is False:
message = result.get('error') or 'Restore adapter reported failure'
if result.get('refused'):
raise restore_point_service.RestorePointRefusedError([message])
raise restore_point_service.RestorePointAdapterError(
message, details=result,
)
return jsonify(result or {'success': True}), 200
+5
View File
@@ -86,6 +86,11 @@ CORE_BLUEPRINTS: tuple[BlueprintSpec, ...] = (
),
BlueprintSpec('app.api.buildpacks', 'buildpacks_bp', '/api/v1/buildpacks'),
BlueprintSpec('app.api.snapshots', 'snapshots_bp', '/api/v1/apps'),
BlueprintSpec(
'app.api.restore_points',
'restore_points_bp',
'/api/v1/restore-points',
),
BlueprintSpec('app.api.manifests', 'manifests_bp', '/api/v1/manifests'),
BlueprintSpec('app.api.recipes', 'recipes_bp', '/api/v1/recipes'),
BlueprintSpec(
+8 -1
View File
@@ -25,10 +25,17 @@ def _new_batch_id():
def _auto_capture(application_id, action, user_id):
"""Best-effort checkpoint immediately before an env mutation."""
from app.services.restore_point_service import auto_capture
from app.services.restore_point_service import (
auto_capture,
auto_capture_is_suppressed,
)
if auto_capture_is_suppressed():
return None
application = Application.query_active().filter_by(id=application_id).first()
return auto_capture(
'env', str(application_id), action, actor=user_id,
server_id=application.server_id if application else None,
)
@@ -73,6 +73,10 @@ class RestorePointNotFoundError(NotFoundError):
code = 'restore_point_not_found'
class RestorePointScopeNotFoundError(NotFoundError):
code = 'restore_point_scope_not_found'
class RestorePointAdapterError(DependencyUnavailableError):
code = 'restore_point_adapter_unavailable'
@@ -135,6 +139,11 @@ def clear_adapters():
ADAPTERS.clear()
def auto_capture_is_suppressed():
"""Let mutation doors avoid pre-capture setup during restore replay."""
return _AUTO_CAPTURE_SUPPRESSED.get()
def auto_capture(scope_type, scope_id, action, label=None, actor=None,
server_id=None):
"""Best-effort pre-mutation capture for use at M2 mutation doors."""
@@ -346,6 +355,128 @@ def _point_or_raise(point_id):
return point
def get(point_id):
"""Return one restore point or raise the public typed 404."""
return _point_or_raise(point_id)
_FILTER_UNSET = object()
def list_points(scope_type=None, scope_id=None, server_id=_FILTER_UNSET,
limit=50, allowed_application_scope_ids=None,
include_operational=True):
"""List restore points without leaking ORM work into the API boundary.
``allowed_application_scope_ids`` applies the grant-aware application
portion of the union *before* limit/order. ``None`` means every app scope
(admin); an empty iterable means no app scopes. Operational rows are an
independent branch controlled by ``include_operational``.
"""
from app.models.restore_point import RestorePoint
query = RestorePoint.query
if scope_type is not None:
query = query.filter(RestorePoint.scope_type == str(scope_type))
if scope_id is not None:
query = query.filter(RestorePoint.scope_id == str(scope_id))
if server_id is not _FILTER_UNSET:
query = query.filter(RestorePoint.server_id == server_id)
app_types = ('application', 'env')
authorized = []
if include_operational:
authorized.append(RestorePoint.scope_type.notin_(app_types))
if allowed_application_scope_ids is None:
authorized.append(RestorePoint.scope_type.in_(app_types))
else:
allowed_ids = tuple(
str(value) for value in allowed_application_scope_ids
)
if allowed_ids:
authorized.append(and_(
RestorePoint.scope_type.in_(app_types),
RestorePoint.scope_id.in_(allowed_ids),
))
query = query.filter(or_(*authorized) if authorized else False)
return (query.order_by(
RestorePoint.created_at.desc(), RestorePoint.id.desc(),
).limit(int(limit)).all())
def accessible_application_scope_ids(user):
"""Application ids visible through the exact ResourceGrant seam."""
if user is None:
return set()
from app.models.application import Application
from app.services.workspace_service import WorkspaceService
query = WorkspaceService.scope_query(
Application.query_active(), Application, user,
owner_attr='user_id', grant_resource_type='application',
)
return {
str(application_id)
for application_id, in query.with_entities(Application.id).all()
}
def resolve_application_scope(scope_type, scope_id):
"""Resolve an app-owned scope for ResourceGrant authorization."""
if str(scope_type) not in {'application', 'env'}:
return None
try:
application_id = int(scope_id)
except (TypeError, ValueError) as exc:
raise RestorePointError('Invalid application scope id') from exc
from app.models.application import Application
application = Application.query_active().filter_by(id=application_id).first()
if application is None:
raise RestorePointScopeNotFoundError(
f'Application {application_id} not found',
)
return application
def resolve_server(server_id):
"""Resolve a server filter/target through the service persistence seam."""
if server_id in (None, ''):
return None
from app.models.server import Server
server = db.session.get(Server, str(server_id))
if server is None:
raise RestorePointScopeNotFoundError(
f'Server {server_id} not found',
)
return server
def capture_manual(scope_type, scope_id, label=None, actor=None,
server_id=None):
"""Strict HTTP-facing wrapper around best-effort door capture.
Automatic mutation hooks intentionally tolerate capture failure. A manual
quicksave is the requested operation itself, so failure must be visible to
the caller as a typed error instead of a false-success response.
"""
if get_adapter(scope_type) is None:
raise RestorePointError(
f'Unsupported restore-point scope type: {scope_type}',
)
point = capture(
scope_type, scope_id, 'manual', label=label, actor=actor,
server_id=server_id,
)
if point is None:
raise RestorePointAdapterError(
f'Could not capture restore point for {scope_type}/{scope_id}',
)
return point
def _strict_payload(point):
"""Parse a stored payload without JsonColumnMixin's lossy fallback."""
try:
@@ -653,10 +784,14 @@ class RestorePointService:
"""Class facade matching other ServerKit service modules."""
capture = staticmethod(capture)
capture_manual = staticmethod(capture_manual)
get = staticmethod(get)
list_points = staticmethod(list_points)
diff = staticmethod(diff)
preview = staticmethod(preview)
restore = staticmethod(restore)
prune = staticmethod(prune)
register_adapter = staticmethod(register_adapter)
auto_capture = staticmethod(auto_capture)
auto_capture_is_suppressed = staticmethod(auto_capture_is_suppressed)
suppress_auto_capture = staticmethod(suppress_auto_capture)
@@ -7,9 +7,9 @@ from pathlib import Path
from app.core_blueprints import CORE_BLUEPRINTS
EXPECTED_CORE_BLUEPRINT_COUNT = 111
EXPECTED_CORE_BLUEPRINT_COUNT = 112
EXPECTED_MANIFEST_SHA256 = (
'560d72b4a31a6ad7ac8f1c9dd906000c7fd3c315f9aaf7e2df61fa98fb782d6e'
'e0eb77cea08ddc21c49d00c25381371dc11b941c4a483ee1532739b4e6ad5013'
)
+493
View File
@@ -0,0 +1,493 @@
"""Plan 81 M3: generic restore-point HTTP contracts and authorization."""
from copy import deepcopy
import pytest
from factories import headers_for, make_application, make_server, make_user
class MemoryAdapter:
coverage = ('Only in-memory test state is covered.',)
def __init__(self, state=None):
self.state = deepcopy(state or {})
self.refusals = []
self.restore_result = None
self.restore_calls = []
def capture(self, scope_id, server_id=None):
return deepcopy(self.state)
def diff(self, old, new):
from app.services.restore_point_service import diff_payloads
return diff_payloads(old, new)
def validate_restore(self, scope_id, payload, current_payload,
actor=None, server_id=None):
return list(self.refusals)
def restore(self, scope_id, payload, actor=None, server_id=None):
self.restore_calls.append({
'scope_id': scope_id,
'actor_id': getattr(actor, 'id', None),
'server_id': server_id,
})
if self.restore_result is not None:
return deepcopy(self.restore_result)
self.state = deepcopy(payload)
return {'success': True, 'scope_id': scope_id}
@pytest.fixture
def memory_surface(monkeypatch):
from app.services import restore_point_service
adapter = MemoryAdapter({'mode': 'saved'})
monkeypatch.setitem(
restore_point_service.ADAPTERS, 'test_surface', adapter,
)
return adapter
def _capture(scope_type, scope_id, state, *, adapter=None, server_id=None):
from app.services import restore_point_service
if adapter is not None:
adapter.state = deepcopy(state)
point = restore_point_service.capture(
scope_type, scope_id, 'pre_mutation', server_id=server_id,
)
assert point is not None
return point
def test_route_authentication_boundaries(client, db_session, memory_surface):
missing = '00000000-0000-0000-0000-000000000000'
assert client.get('/api/v1/restore-points').status_code == 401
assert client.post('/api/v1/restore-points', json={}).status_code == 401
assert client.post(
f'/api/v1/restore-points/{missing}/preview', json={},
).status_code == 401
assert client.post(
f'/api/v1/restore-points/{missing}/restore', json={},
).status_code == 401
viewer = make_user(db_session, role='viewer')
viewer_headers = headers_for(viewer)
assert client.post(
'/api/v1/restore-points', headers=viewer_headers,
json={'scope_type': 'test_surface', 'scope_id': 'one'},
).status_code == 403
assert client.post(
f'/api/v1/restore-points/{missing}/preview', headers=viewer_headers,
).status_code == 403
assert client.post(
f'/api/v1/restore-points/{missing}/restore', headers=viewer_headers,
).status_code == 403
def test_local_operational_reads_require_developer(
client, db_session, memory_surface):
point = _capture('test_surface', 'local', {'mode': 'saved'},
adapter=memory_surface)
viewer = make_user(db_session, role='viewer')
headers = headers_for(viewer)
for path in (
'/api/v1/restore-points?scope_type=test_surface&scope_id=local',
f'/api/v1/restore-points/{point.id}',
f'/api/v1/restore-points/{point.id}/diff',
):
response = client.get(path, headers=headers)
assert response.status_code == 403, path
assert response.get_json()['code'] == 'permission_denied'
def test_list_is_grant_filtered_before_limit_and_detail_includes_payload(
client, db_session, monkeypatch, memory_surface):
from app.services import restore_point_service
from app.services.resource_grant_service import ResourceGrantService
owner = make_user(db_session, role='developer')
own_app = make_application(db_session, user_id=owner.id, name='owned')
foreign_owner = make_user(db_session, role='developer')
foreign_app = make_application(
db_session, user_id=foreign_owner.id, name='foreign',
)
viewer = make_user(db_session, role='viewer')
ResourceGrantService.grant(
viewer.id, 'application', own_app.id, role='viewer',
)
env_adapter = MemoryAdapter({'env': {'VISIBLE': {'value': 'yes'}}})
monkeypatch.setitem(restore_point_service.ADAPTERS, 'env', env_adapter)
own_point = _capture('env', own_app.id, env_adapter.state,
adapter=env_adapter)
env_adapter.state = {'env': {'HIDDEN': {'value': 'no'}}}
foreign_point = _capture('env', foreign_app.id, env_adapter.state,
adapter=env_adapter)
_capture('test_surface', 'local', {'mode': 'ops'},
adapter=memory_surface)
response = client.get(
'/api/v1/restore-points?scope_type=env&limit=1',
headers=headers_for(viewer),
)
assert response.status_code == 200
rows = response.get_json()['restore_points']
assert [row['id'] for row in rows] == [own_point.id]
assert 'payload' not in rows[0]
response = client.get(
f'/api/v1/restore-points/{own_point.id}',
headers=headers_for(viewer),
)
assert response.status_code == 200
assert response.get_json()['restore_point']['payload'] == {
'env': {'VISIBLE': {'value': 'yes'}},
}
denied = client.get(
f'/api/v1/restore-points/{foreign_point.id}',
headers=headers_for(viewer),
)
assert denied.status_code == 403
def test_broad_and_server_lists_union_ops_with_authorized_env_points(
client, db_session, monkeypatch, memory_surface):
from app.services import restore_point_service
developer = make_user(db_session, role='developer')
server = make_server(db_session)
own_app = make_application(
db_session, user_id=developer.id, server_id=server.id,
)
foreign_app = make_application(
db_session, user_id=make_user(db_session).id, server_id=server.id,
name='foreign',
)
env_adapter = MemoryAdapter({'env': {'OWN': {}}})
monkeypatch.setitem(restore_point_service.ADAPTERS, 'env', env_adapter)
own = _capture(
'env', own_app.id, env_adapter.state, adapter=env_adapter,
server_id=server.id,
)
env_adapter.state = {'env': {'FOREIGN': {}}}
foreign = _capture(
'env', foreign_app.id, env_adapter.state, adapter=env_adapter,
server_id=server.id,
)
memory_surface.state = {'ops': True}
operational = _capture(
'test_surface', 'local', memory_surface.state,
adapter=memory_surface, server_id=server.id,
)
headers = headers_for(developer)
broad = client.get('/api/v1/restore-points', headers=headers)
assert broad.status_code == 200
assert {row['id'] for row in broad.get_json()['restore_points']} == {
own.id, operational.id,
}
server_list = client.get(
f'/api/v1/restore-points?server_id={server.id}', headers=headers,
)
assert server_list.status_code == 200
ids = {row['id'] for row in server_list.get_json()['restore_points']}
assert ids == {own.id, operational.id}
assert foreign.id not in ids
def test_manual_env_quicksave_derives_server_and_rejects_client_stamp(
client, db_session):
from app.models import RestorePoint
developer = make_user(db_session, role='developer')
server = make_server(db_session)
application = make_application(
db_session, user_id=developer.id, server_id=server.id,
)
headers = headers_for(developer)
response = client.post(
'/api/v1/restore-points', headers=headers,
json={
'scope_type': 'env', 'scope_id': str(application.id),
'label': 'before launch',
},
)
assert response.status_code == 201
data = response.get_json()['restore_point']
assert data['server_id'] == server.id
assert data['trigger'] == 'manual'
assert data['label'] == 'before launch'
assert data['keep'] is True
assert data['actor_user_id'] == developer.id
assert data['payload'] == {'env': {}}
assert RestorePoint.query.get(data['id']).server_id == server.id
stamped = client.post(
'/api/v1/restore-points', headers=headers,
json={
'scope_type': 'env', 'scope_id': str(application.id),
'server_id': '00000000-0000-0000-0000-000000000000',
},
)
assert stamped.status_code == 400
assert stamped.get_json()['details']['fields'] == ['server_id']
def test_manual_capture_validation_and_failure_are_typed(
client, db_session, monkeypatch, memory_surface):
from app.services import restore_point_service
developer = make_user(db_session, role='developer')
application = make_application(db_session, user_id=developer.id)
headers = headers_for(developer)
unsupported = client.post(
'/api/v1/restore-points', headers=headers,
json={'scope_type': 'application', 'scope_id': str(application.id)},
)
assert unsupported.status_code == 400
assert unsupported.get_json()['code'] == 'restore_point_invalid'
too_long = client.post(
'/api/v1/restore-points', headers=headers,
json={
'scope_type': 'test_surface', 'scope_id': 'local',
'label': 'x' * 256,
},
)
assert too_long.status_code == 400
assert too_long.get_json()['code'] == 'validation_error'
monkeypatch.setattr(restore_point_service, 'capture', lambda *_a, **_k: None)
failed = client.post(
'/api/v1/restore-points', headers=headers,
json={'scope_type': 'test_surface', 'scope_id': 'local'},
)
assert failed.status_code == 503
assert failed.get_json()['code'] == 'restore_point_adapter_unavailable'
def test_diff_contract_default_explicit_and_cross_scope_error(
client, db_session, memory_surface):
developer = make_user(db_session, role='developer')
headers = headers_for(developer)
first = _capture('test_surface', 'one', {'mode': 'one'},
adapter=memory_surface)
second = _capture('test_surface', 'one', {'mode': 'two'},
adapter=memory_surface)
other = _capture('test_surface', 'other', {'mode': 'other'},
adapter=memory_surface)
response = client.get(
f'/api/v1/restore-points/{second.id}/diff', headers=headers,
)
assert response.status_code == 200
body = response.get_json()
assert body['against_point_id'] == first.id
assert body['has_changes'] is True
assert body['diff']['changed']['mode'] == {'old': 'one', 'new': 'two'}
explicit = client.get(
f'/api/v1/restore-points/{second.id}/diff?against={first.id}',
headers=headers,
)
assert explicit.status_code == 200
assert explicit.get_json()['against_point_id'] == first.id
crossed = client.get(
f'/api/v1/restore-points/{second.id}/diff?against={other.id}',
headers=headers,
)
assert crossed.status_code == 400
assert crossed.get_json()['code'] == 'restore_point_invalid'
unknown = client.get(
f'/api/v1/restore-points/{second.id}/diff?typo=true',
headers=headers,
)
assert unknown.status_code == 400
assert unknown.get_json()['details']['fields'] == ['typo']
def test_preview_and_restore_lifecycle_contract(
client, db_session, memory_surface):
from app.models import RestorePoint
developer = make_user(db_session, role='developer')
point = _capture('test_surface', 'local', {'mode': 'saved'},
adapter=memory_surface)
memory_surface.state = {'mode': 'drifted'}
headers = headers_for(developer)
preview = client.post(
f'/api/v1/restore-points/{point.id}/preview', headers=headers,
)
assert preview.status_code == 200
body = preview.get_json()
assert body['point_id'] == point.id
assert body['has_changes'] is True
assert body['can_restore'] is True
assert body['refusals'] == []
assert 'Only in-memory test state is covered.' in body['outside_checkpoint']
count_before = RestorePoint.query.count()
restored = client.post(
f'/api/v1/restore-points/{point.id}/restore', headers=headers,
)
assert restored.status_code == 200
assert restored.get_json() == {'success': True, 'scope_id': 'local'}
assert memory_surface.state == {'mode': 'saved'}
assert memory_surface.restore_calls[-1]['actor_id'] == developer.id
assert RestorePoint.query.count() == count_before + 1
def test_restore_refusal_and_adapter_failure_use_typed_errors(
client, db_session, memory_surface):
developer = make_user(db_session, role='developer')
headers = headers_for(developer)
point = _capture('test_surface', 'local', {'mode': 'saved'},
adapter=memory_surface)
memory_surface.state = {'mode': 'drifted'}
memory_surface.refusals = ['Safety admission would be lost.']
preview = client.post(
f'/api/v1/restore-points/{point.id}/preview', headers=headers,
)
assert preview.status_code == 200
assert preview.get_json()['can_restore'] is False
refused = client.post(
f'/api/v1/restore-points/{point.id}/restore', headers=headers,
)
assert refused.status_code == 409
assert refused.get_json()['code'] == 'restore_point_refused'
memory_surface.refusals = []
memory_surface.restore_result = {
'success': False, 'error': 'host write failed', 'rolled_back': True,
}
failed = client.post(
f'/api/v1/restore-points/{point.id}/restore', headers=headers,
)
assert failed.status_code == 503
body = failed.get_json()
assert body['code'] == 'restore_point_adapter_unavailable'
assert body['details']['rolled_back'] is True
def test_env_grants_split_read_and_write(
client, db_session, monkeypatch):
from app.services import restore_point_service
from app.services.resource_grant_service import ResourceGrantService
owner = make_user(db_session, role='developer')
application = make_application(db_session, user_id=owner.id)
viewer = make_user(db_session, role='viewer')
editor = make_user(db_session, role='developer')
foreign = make_user(db_session, role='developer')
ResourceGrantService.grant(
viewer.id, 'application', application.id, role='viewer',
)
ResourceGrantService.grant(
editor.id, 'application', application.id, role='editor',
)
adapter = MemoryAdapter({'env': {'KEY': {'value': 'saved'}}})
monkeypatch.setitem(restore_point_service.ADAPTERS, 'env', adapter)
point = _capture('env', application.id, adapter.state, adapter=adapter)
adapter.state = {'env': {'KEY': {'value': 'drifted'}}}
assert client.get(
f'/api/v1/restore-points/{point.id}', headers=headers_for(viewer),
).status_code == 200
assert client.get(
f'/api/v1/restore-points/{point.id}', headers=headers_for(foreign),
).status_code == 403
assert client.post(
f'/api/v1/restore-points/{point.id}/preview',
headers=headers_for(viewer),
).status_code == 403
assert client.post(
f'/api/v1/restore-points/{point.id}/preview',
headers=headers_for(foreign),
).status_code == 403
assert client.post(
f'/api/v1/restore-points/{point.id}/preview',
headers=headers_for(editor),
).status_code == 200
def test_deleted_and_inactive_jwt_users_fail_closed_on_get(
app, client, db_session, memory_surface):
from app import db
point = _capture('test_surface', 'local', {'mode': 'saved'},
adapter=memory_surface)
inactive = make_user(db_session, role='developer')
inactive_headers = headers_for(inactive)
inactive.is_active = False
db.session.commit()
response = client.get(
f'/api/v1/restore-points/{point.id}', headers=inactive_headers,
)
assert response.status_code == 403
assert response.get_json()['error'] == 'Account is deactivated'
deleted = make_user(db_session, role='developer')
deleted_headers = headers_for(deleted)
db.session.delete(deleted)
db.session.commit()
response = client.get(
f'/api/v1/restore-points/{point.id}', headers=deleted_headers,
)
assert response.status_code == 403
assert response.get_json()['error'] == 'Authenticated user not found'
def test_developer_api_key_reaches_policy_guarded_post(
client, db_session):
from app.services.api_key_service import ApiKeyService
developer = make_user(db_session, role='developer')
_, raw_key = ApiKeyService.create_key(
developer.id, name='restore-point-m3', scopes=['*'],
)
missing = '00000000-0000-0000-0000-000000000000'
response = client.post(
f'/api/v1/restore-points/{missing}/preview',
headers={'X-API-Key': raw_key},
)
assert response.status_code == 404
assert response.get_json()['code'] == 'restore_point_not_found'
def test_env_auto_capture_carries_application_server_id(
app, db_session, monkeypatch):
from app.models import RestorePoint
from app.services import restore_point_adapter_env, restore_point_service
from app.services.env_service import EnvService
owner = make_user(db_session, role='developer')
server = make_server(db_session)
application = make_application(
db_session, user_id=owner.id, server_id=server.id,
)
monkeypatch.setitem(
restore_point_service.ADAPTERS, 'env', restore_point_adapter_env,
)
EnvService.set_env_var(
application.id, 'FEATURE', 'on', user_id=owner.id,
)
point = RestorePoint.query.filter_by(
scope_type='env', scope_id=str(application.id),
).one()
assert point.server_id == server.id