Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d6caf8a9e | ||
|
|
2bd7487ba7 | ||
|
|
29a9aea3b1 | ||
|
|
b5f431c766 | ||
|
|
5753488375 | ||
|
|
72779d0277 | ||
|
|
016965917e | ||
|
|
861e9b8b8d | ||
|
|
be5e3a7d72 | ||
|
|
8fcc12dbb2 | ||
|
|
a8ec72d8a9 | ||
|
|
fba4117b0c |
@@ -19,6 +19,18 @@ activation. Optional View-ID and surface-ID ceilings are intersected across the
|
||||
scope path, and the UI displays effective limits and provenance. Lower scopes
|
||||
can narrow but never broaden an ancestor restriction.
|
||||
|
||||
Before saving a View-policy draft, administrators can call
|
||||
`POST /api/v1/admin/policy-impact/preview` with one to ten explicitly selected,
|
||||
bounded subject populations. The dry run does not persist the proposal. It
|
||||
groups newly allowed, newly denied, unchanged, and indeterminate effects and
|
||||
reports complete, sampled, truncated, unavailable, or permission-hidden
|
||||
coverage with rule and source provenance. Aggregate counts follow normal
|
||||
policy-read authority; resource details additionally require
|
||||
`policy:impact:details`. System-wide View-policy commits require a login less
|
||||
than 15 minutes old. Preview and commit are recorded as separate audit events.
|
||||
Optional modules contribute subjects through the Core provider contract, so
|
||||
Policy never imports their implementation.
|
||||
|
||||
Policy decision and provenance payloads use the shared kernel DTOs documented
|
||||
in [docs/POLICY_DECISION_PROVENANCE.md](docs/POLICY_DECISION_PROVENANCE.md)
|
||||
and `/mnt/DATA/git/govoplan-core/docs/POLICY_CONTRACTS.md`.
|
||||
|
||||
@@ -130,3 +130,18 @@ bounded outcome counts in audit evidence.
|
||||
The shared core WebUI helper `PolicySourcePath` renders the source path shape
|
||||
for module UIs. Modules may use their own field layout, but the data contract
|
||||
should remain this shape.
|
||||
# Function assignment delegation and escalation
|
||||
|
||||
The `policy.functionAssignmentGovernance` decision includes the effective
|
||||
`delegation_allowed`, `maximum_delegation_depth`, and
|
||||
`maximum_delegated_validity_days` values plus zero or more per-step escalation
|
||||
rules. Each rule binds `holder`, `authority`, or `recipient` review to one exact
|
||||
target function and a bounded timeout. Consumers must treat the decision as a
|
||||
current limit, not a captured grant: IDM rechecks it across the complete source
|
||||
chain at every consequential transition.
|
||||
|
||||
An elapsed timeout does not change the approval result. IDM records an explicit
|
||||
escalated state and the target function; Policy authorizes only a current holder
|
||||
of that target for the escalated decision. Missing, malformed, vacant, expired,
|
||||
cyclic, over-depth, or tightened routes fail closed with their reason preserved
|
||||
in the decision and transition evidence.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@govoplan/policy-webui",
|
||||
"version": "0.1.18",
|
||||
"version": "0.1.23",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "webui/src/index.ts",
|
||||
@@ -18,7 +18,7 @@
|
||||
"LICENSE"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"@govoplan/core-webui": "^0.1.18",
|
||||
"@govoplan/core-webui": "^0.1.45",
|
||||
"lucide-react": "^1.23.0",
|
||||
"react": ">=19.2.7 <20",
|
||||
"react-dom": ">=19.2.7 <20",
|
||||
|
||||
+2
-2
@@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "govoplan-policy"
|
||||
version = "0.1.18"
|
||||
version = "0.1.23"
|
||||
description = "GovOPlaN policy platform module."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
authors = [{ name = "GovOPlaN" }]
|
||||
dependencies = [
|
||||
"govoplan-core>=0.1.18",
|
||||
"govoplan-core>=0.1.45",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from govoplan_core.core.access import (
|
||||
AccessExplanationSubjectDecision,
|
||||
PrincipalRef,
|
||||
)
|
||||
from govoplan_core.security.module_permissions import scopes_grant_compatible
|
||||
|
||||
|
||||
ACCESS_EXPLANATION_SUBJECT_SCOPE = "policy:access_explanation:select_user"
|
||||
|
||||
|
||||
class AccessExplanationSubjectPolicyProvider:
|
||||
"""Decide whether an actor may run an explanation for another user."""
|
||||
|
||||
def decide_subject_selection(
|
||||
self,
|
||||
session: object,
|
||||
principal: PrincipalRef,
|
||||
*,
|
||||
tenant_id: str,
|
||||
) -> AccessExplanationSubjectDecision:
|
||||
del session
|
||||
if principal.tenant_id != tenant_id:
|
||||
return AccessExplanationSubjectDecision(
|
||||
allow_other_users=False,
|
||||
reason="Access explanations are limited to the active tenant.",
|
||||
source="policy.tenant_boundary",
|
||||
required_scope=ACCESS_EXPLANATION_SUBJECT_SCOPE,
|
||||
provenance={"tenant_id": tenant_id, "mode": "current_user"},
|
||||
)
|
||||
|
||||
allowed = scopes_grant_compatible(
|
||||
principal.scopes,
|
||||
ACCESS_EXPLANATION_SUBJECT_SCOPE,
|
||||
)
|
||||
return AccessExplanationSubjectDecision(
|
||||
allow_other_users=allowed,
|
||||
reason=(
|
||||
"Policy permits selected-user access diagnostics."
|
||||
if allowed
|
||||
else "Policy limits access explanations to the signed-in user."
|
||||
),
|
||||
source="policy.permission",
|
||||
required_scope=ACCESS_EXPLANATION_SUBJECT_SCOPE,
|
||||
provenance={
|
||||
"tenant_id": tenant_id,
|
||||
"mode": "cross_user" if allowed else "current_user",
|
||||
},
|
||||
)
|
||||
@@ -1,8 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope, require_scope
|
||||
@@ -34,6 +35,17 @@ from govoplan_policy.backend.definition_policy_service import (
|
||||
save_definition_policy,
|
||||
)
|
||||
from govoplan_policy.backend.policy_overrides import PolicyOverrideError
|
||||
from govoplan_policy.backend.impact_preview import (
|
||||
PolicyImpactPopulationSpec,
|
||||
PolicyImpactPreviewError,
|
||||
policy_impact_proposal_hash,
|
||||
preview_policy_impact as build_policy_impact_preview,
|
||||
)
|
||||
from govoplan_policy.backend.campaign_archive_encryption import (
|
||||
CampaignArchiveEncryptionPolicyError,
|
||||
campaign_archive_encryption_policy_state,
|
||||
save_campaign_archive_encryption_policy,
|
||||
)
|
||||
from govoplan_policy.backend.view_policy_service import (
|
||||
ViewPolicyError,
|
||||
remove_view_policy,
|
||||
@@ -43,6 +55,8 @@ from govoplan_policy.backend.view_policy_service import (
|
||||
)
|
||||
|
||||
from .schemas import (
|
||||
CampaignArchiveEncryptionPolicyScopeRequest,
|
||||
CampaignArchiveEncryptionPolicyScopeResponse,
|
||||
DefinitionPolicyScopeRequest,
|
||||
DefinitionPolicyScopeResponse,
|
||||
PrivacyRetentionPolicyExplainResponse,
|
||||
@@ -50,6 +64,8 @@ from .schemas import (
|
||||
PrivacyRetentionPolicyScopeRequest,
|
||||
PrivacyRetentionPolicyScopeResponse,
|
||||
PrivacyRetentionPolicySimulationResponse,
|
||||
PolicyImpactPreviewRequest,
|
||||
PolicyImpactPreviewResponse,
|
||||
RetentionRunRequest,
|
||||
RetentionRunResponse,
|
||||
ViewPolicyScopeRequest,
|
||||
@@ -58,6 +74,8 @@ from .schemas import (
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
RECENT_POLICY_AUTHENTICATION_WINDOW = timedelta(minutes=15)
|
||||
|
||||
|
||||
def _require_permission(principal: ApiPrincipal, scope: str) -> None:
|
||||
if not has_scope(principal, scope):
|
||||
@@ -87,6 +105,174 @@ def _configuration_control_http_error(exc: ConfigurationControlError) -> HTTPExc
|
||||
)
|
||||
|
||||
|
||||
def _require_recent_policy_authentication(principal: ApiPrincipal) -> None:
|
||||
auth_session = principal.auth_session
|
||||
created_at = getattr(auth_session, "created_at", None)
|
||||
if isinstance(created_at, datetime):
|
||||
if created_at.tzinfo is None:
|
||||
created_at = created_at.replace(tzinfo=timezone.utc)
|
||||
elapsed = datetime.now(timezone.utc) - created_at
|
||||
if timedelta(0) <= elapsed <= RECENT_POLICY_AUTHENTICATION_WINDOW:
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail={
|
||||
"code": "recent_authentication_required",
|
||||
"message": (
|
||||
"System-wide policy changes require authentication within the "
|
||||
"last 15 minutes."
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _archive_encryption_policy_response(
|
||||
*,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
state,
|
||||
) -> CampaignArchiveEncryptionPolicyScopeResponse:
|
||||
row = state.row
|
||||
return CampaignArchiveEncryptionPolicyScopeResponse(
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
id=row.id if row else None,
|
||||
revision=row.revision if row else None,
|
||||
policy=dict(row.policy) if row and isinstance(row.policy, dict) else {},
|
||||
effective_policy=state.effective.to_dict(),
|
||||
parent_policy=state.parent.to_dict(),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/campaign-archive-encryption/policies/{scope_type}",
|
||||
response_model=CampaignArchiveEncryptionPolicyScopeResponse,
|
||||
)
|
||||
def read_campaign_archive_encryption_policy(
|
||||
scope_type: str,
|
||||
scope_id: str | None = Query(default=None),
|
||||
owner_type: str | None = Query(default=None),
|
||||
owner_id: str | None = Query(default=None),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
):
|
||||
_require_permission(principal, "admin:policies:read")
|
||||
clean_scope = scope_type.strip().casefold()
|
||||
try:
|
||||
state = campaign_archive_encryption_policy_state(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
owner_type=owner_type,
|
||||
owner_id=owner_id,
|
||||
)
|
||||
return _archive_encryption_policy_response(
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
state=state,
|
||||
)
|
||||
except (CampaignArchiveEncryptionPolicyError, PolicyOverrideError) as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
|
||||
|
||||
@router.put(
|
||||
"/campaign-archive-encryption/policies/{scope_type}",
|
||||
response_model=CampaignArchiveEncryptionPolicyScopeResponse,
|
||||
)
|
||||
def write_campaign_archive_encryption_policy(
|
||||
scope_type: str,
|
||||
payload: CampaignArchiveEncryptionPolicyScopeRequest,
|
||||
scope_id: str | None = Query(default=None),
|
||||
owner_type: str | None = Query(default=None),
|
||||
owner_id: str | None = Query(default=None),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
):
|
||||
_require_permission(principal, "admin:policies:write")
|
||||
clean_scope = scope_type.strip().casefold()
|
||||
policy_value = payload.policy.model_dump(mode="json", exclude_none=True)
|
||||
try:
|
||||
before = campaign_archive_encryption_policy_state(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
owner_type=owner_type,
|
||||
owner_id=owner_id,
|
||||
)
|
||||
# Saving updates the same ORM row held by ``before``. Capture its
|
||||
# value now so history/rollback does not silently record the new policy.
|
||||
before_policy = dict(before.row.policy) if before.row else {}
|
||||
if clean_scope == "system":
|
||||
approval = ensure_configuration_change_allowed(
|
||||
session,
|
||||
key="campaign_archive_encryption_policy",
|
||||
value=policy_value,
|
||||
actor_user_id=principal.user.id,
|
||||
actor_scopes=tuple(principal.scopes),
|
||||
change_request_id=payload.change_request_id,
|
||||
target={"scope_type": clean_scope},
|
||||
)
|
||||
else:
|
||||
approval = None
|
||||
state = save_campaign_archive_encryption_policy(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
owner_type=owner_type,
|
||||
owner_id=owner_id,
|
||||
policy=policy_value,
|
||||
actor_id=principal.user.id,
|
||||
)
|
||||
if clean_scope == "system":
|
||||
record_configuration_change_applied(
|
||||
session,
|
||||
key="campaign_archive_encryption_policy",
|
||||
before_value=before_policy,
|
||||
after_value=policy_value,
|
||||
actor_user_id=principal.user.id,
|
||||
approval=approval,
|
||||
target={"scope_type": clean_scope},
|
||||
audit_event="campaign_archive_encryption_policy.updated",
|
||||
)
|
||||
audit_from_principal(
|
||||
session,
|
||||
principal,
|
||||
action="campaign_archive_encryption_policy.updated",
|
||||
scope="system" if clean_scope == "system" else "tenant",
|
||||
object_type="campaign_archive_encryption_policy",
|
||||
object_id=f"{clean_scope}:{scope_id or ''}",
|
||||
details={
|
||||
"scope_type": clean_scope,
|
||||
"scope_id": scope_id,
|
||||
"owner_type": owner_type,
|
||||
"owner_id": owner_id,
|
||||
"policy_hash": state.effective.policy_hash,
|
||||
"fields": sorted(policy_value),
|
||||
},
|
||||
)
|
||||
session.commit()
|
||||
return _archive_encryption_policy_response(
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
state=state,
|
||||
)
|
||||
except ConfigurationControlError as exc:
|
||||
session.rollback()
|
||||
raise _configuration_control_http_error(exc) from exc
|
||||
except (CampaignArchiveEncryptionPolicyError, PolicyOverrideError) as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
|
||||
|
||||
def _definition_policy_response(
|
||||
*,
|
||||
module_id: str,
|
||||
@@ -327,6 +513,83 @@ def _view_policy_response(
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/policy-impact/preview",
|
||||
response_model=PolicyImpactPreviewResponse,
|
||||
)
|
||||
def preview_policy_impact_route(
|
||||
payload: PolicyImpactPreviewRequest,
|
||||
request: Request,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
):
|
||||
_require_privacy_policy_read(principal, payload.scope_type)
|
||||
registry = getattr(request.app.state, "govoplan_registry", None)
|
||||
if registry is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="The platform registry is not available.",
|
||||
)
|
||||
try:
|
||||
preview = build_policy_impact_preview(
|
||||
session,
|
||||
registry=registry,
|
||||
tenant_id=principal.tenant_id,
|
||||
policy_family=payload.policy_family,
|
||||
scope_type=payload.scope_type,
|
||||
scope_id=payload.scope_id,
|
||||
proposed_policy=payload.proposed_policy.model_dump(
|
||||
mode="json",
|
||||
exclude_none=True,
|
||||
),
|
||||
populations=tuple(
|
||||
PolicyImpactPopulationSpec(
|
||||
provider_id=population.provider_id,
|
||||
selector=population.selector,
|
||||
limit=population.limit,
|
||||
)
|
||||
for population in payload.populations
|
||||
),
|
||||
actor_scopes=tuple(principal.scopes),
|
||||
include_details=payload.include_details,
|
||||
details_allowed=has_scope(principal, "policy:impact:details"),
|
||||
)
|
||||
audit_from_principal(
|
||||
session,
|
||||
principal,
|
||||
action="policy.impact_previewed",
|
||||
scope="system" if payload.scope_type == "system" else "tenant",
|
||||
object_type="policy_impact_preview",
|
||||
object_id=preview.preview_id,
|
||||
details={
|
||||
"policy_family": preview.policy_family,
|
||||
"scope_type": preview.scope_type,
|
||||
"scope_id": preview.scope_id,
|
||||
"proposal_hash": preview.proposal_hash,
|
||||
"counts": dict(preview.counts),
|
||||
"providers": [
|
||||
{
|
||||
"provider_id": population.get("provider_id"),
|
||||
"state": population.get("state"),
|
||||
"returned": population.get("returned"),
|
||||
"total_available": population.get("total_available"),
|
||||
}
|
||||
for population in preview.populations
|
||||
],
|
||||
"details_hidden": preview.details_hidden,
|
||||
"high_impact": preview.high_impact,
|
||||
},
|
||||
)
|
||||
session.commit()
|
||||
return PolicyImpactPreviewResponse.model_validate(preview.to_dict())
|
||||
except (PolicyImpactPreviewError, ViewPolicyError, PolicyOverrideError) as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
|
||||
|
||||
@router.get(
|
||||
"/view-policies/{scope_type}",
|
||||
response_model=ViewPolicyScopeResponse,
|
||||
@@ -371,7 +634,16 @@ def write_view_policy(
|
||||
):
|
||||
clean_scope = scope_type.strip().casefold()
|
||||
_require_privacy_policy_write(principal, clean_scope)
|
||||
if clean_scope == "system":
|
||||
_require_recent_policy_authentication(principal)
|
||||
policy_value = payload.policy.model_dump(mode="json", exclude_none=True)
|
||||
if bool(payload.impact_preview_id) != bool(payload.impact_proposal_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
detail=(
|
||||
"Impact preview ID and proposal hash must be supplied together."
|
||||
),
|
||||
)
|
||||
try:
|
||||
before = view_policy_state(
|
||||
session,
|
||||
@@ -379,6 +651,26 @@ def write_view_policy(
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
)
|
||||
if payload.impact_proposal_hash is not None:
|
||||
proposal_hash = policy_impact_proposal_hash(
|
||||
family="view",
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
policy=policy_value,
|
||||
base_policy=before.local_policy,
|
||||
base_revision=(before.row.revision if before.row is not None else None),
|
||||
)
|
||||
if proposal_hash != payload.impact_proposal_hash:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail={
|
||||
"code": "policy_impact_preview_stale",
|
||||
"message": (
|
||||
"The policy draft or saved base changed after its "
|
||||
"impact preview. Run the preview again before saving."
|
||||
),
|
||||
},
|
||||
)
|
||||
if clean_scope == "system":
|
||||
approval = ensure_configuration_change_allowed(
|
||||
session,
|
||||
@@ -421,6 +713,8 @@ def write_view_policy(
|
||||
"scope_type": clean_scope,
|
||||
"scope_id": scope_id,
|
||||
"fields": sorted(policy_value),
|
||||
"impact_preview_id": payload.impact_preview_id,
|
||||
"impact_proposal_hash": payload.impact_proposal_hash,
|
||||
},
|
||||
)
|
||||
session.commit()
|
||||
@@ -448,11 +742,26 @@ def delete_view_policy_route(
|
||||
scope_type: str,
|
||||
scope_id: str | None = Query(default=None),
|
||||
change_request_id: str | None = Query(default=None),
|
||||
impact_preview_id: str | None = Query(default=None, max_length=36),
|
||||
impact_proposal_hash: str | None = Query(
|
||||
default=None,
|
||||
min_length=64,
|
||||
max_length=64,
|
||||
),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
):
|
||||
clean_scope = scope_type.strip().casefold()
|
||||
_require_privacy_policy_write(principal, clean_scope)
|
||||
if clean_scope == "system":
|
||||
_require_recent_policy_authentication(principal)
|
||||
if bool(impact_preview_id) != bool(impact_proposal_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
detail=(
|
||||
"Impact preview ID and proposal hash must be supplied together."
|
||||
),
|
||||
)
|
||||
try:
|
||||
before = view_policy_state(
|
||||
session,
|
||||
@@ -460,6 +769,27 @@ def delete_view_policy_route(
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
)
|
||||
if impact_proposal_hash is not None:
|
||||
proposal_hash = policy_impact_proposal_hash(
|
||||
family="view",
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
policy={},
|
||||
base_policy=before.local_policy,
|
||||
base_revision=(before.row.revision if before.row is not None else None),
|
||||
)
|
||||
if proposal_hash != impact_proposal_hash:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail={
|
||||
"code": "policy_impact_preview_stale",
|
||||
"message": (
|
||||
"The saved policy base changed after its inherited-policy "
|
||||
"impact preview. Run the preview again before removing "
|
||||
"the override."
|
||||
),
|
||||
},
|
||||
)
|
||||
if clean_scope == "system":
|
||||
approval = ensure_configuration_change_allowed(
|
||||
session,
|
||||
@@ -497,7 +827,12 @@ def delete_view_policy_route(
|
||||
scope="system" if clean_scope == "system" else "tenant",
|
||||
object_type="view_policy",
|
||||
object_id=f"{clean_scope}:{scope_id or ''}",
|
||||
details={"scope_type": clean_scope, "scope_id": scope_id},
|
||||
details={
|
||||
"scope_type": clean_scope,
|
||||
"scope_id": scope_id,
|
||||
"impact_preview_id": impact_preview_id,
|
||||
"impact_proposal_hash": impact_proposal_hash,
|
||||
},
|
||||
)
|
||||
session.commit()
|
||||
state = view_policy_state(
|
||||
|
||||
@@ -46,6 +46,36 @@ class PolicyDecisionItem(BaseModel):
|
||||
details: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class CampaignArchiveEncryptionPolicyItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
allowed_password_encryption_methods: list[
|
||||
Literal["aes", "zip_standard"]
|
||||
] | None = None
|
||||
allowed_password_delivery_channels: list[
|
||||
Literal["separate_mail", "sms", "letter", "phone", "in_person"]
|
||||
] | None = None
|
||||
|
||||
|
||||
class CampaignArchiveEncryptionPolicyScopeRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
policy: CampaignArchiveEncryptionPolicyItem = Field(
|
||||
default_factory=CampaignArchiveEncryptionPolicyItem
|
||||
)
|
||||
change_request_id: str | None = None
|
||||
|
||||
|
||||
class CampaignArchiveEncryptionPolicyScopeResponse(BaseModel):
|
||||
scope_type: Literal["system", "tenant", "group", "user", "campaign"]
|
||||
scope_id: str | None = None
|
||||
id: str | None = None
|
||||
revision: int | None = None
|
||||
policy: dict[str, Any] = Field(default_factory=dict)
|
||||
effective_policy: dict[str, Any]
|
||||
parent_policy: dict[str, Any]
|
||||
|
||||
|
||||
class DefinitionPolicyItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
@@ -95,6 +125,8 @@ class ViewPolicyScopeRequest(BaseModel):
|
||||
|
||||
policy: ViewPolicyItem = Field(default_factory=ViewPolicyItem)
|
||||
change_request_id: str | None = None
|
||||
impact_preview_id: str | None = Field(default=None, max_length=36)
|
||||
impact_proposal_hash: str | None = Field(default=None, min_length=64, max_length=64)
|
||||
|
||||
|
||||
class ViewPolicyScopeResponse(BaseModel):
|
||||
@@ -109,6 +141,87 @@ class ViewPolicyScopeResponse(BaseModel):
|
||||
diagnostics: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PolicyImpactPopulationRequestItem(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
provider_id: str = Field(min_length=1, max_length=120)
|
||||
selector: dict[str, Any] = Field(default_factory=dict)
|
||||
limit: int = Field(default=200, ge=1, le=500)
|
||||
|
||||
|
||||
class PolicyImpactPreviewRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
policy_family: Literal["view"] = "view"
|
||||
scope_type: Literal["system", "tenant", "group", "user"]
|
||||
scope_id: str | None = Field(default=None, max_length=240)
|
||||
proposed_policy: ViewPolicyItem = Field(default_factory=ViewPolicyItem)
|
||||
populations: list[PolicyImpactPopulationRequestItem] = Field(
|
||||
min_length=1,
|
||||
max_length=10,
|
||||
)
|
||||
include_details: bool = False
|
||||
|
||||
|
||||
class PolicyImpactSubjectItem(BaseModel):
|
||||
module_id: str
|
||||
resource_type: str
|
||||
resource_id: str
|
||||
action: str
|
||||
label: str | None = None
|
||||
scope_type: str | None = None
|
||||
scope_id: str | None = None
|
||||
attributes: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class PolicyImpactEffectItem(BaseModel):
|
||||
category: Literal[
|
||||
"newly_allowed",
|
||||
"newly_denied",
|
||||
"unchanged",
|
||||
"indeterminate",
|
||||
]
|
||||
subject: PolicyImpactSubjectItem
|
||||
current_allowed: bool | None = None
|
||||
proposed_allowed: bool | None = None
|
||||
rule: str
|
||||
current_sources: list[PolicySourceStepItem] = Field(default_factory=list)
|
||||
proposed_sources: list[PolicySourceStepItem] = Field(default_factory=list)
|
||||
explanation: str | None = None
|
||||
|
||||
|
||||
class PolicyImpactPopulationResponseItem(BaseModel):
|
||||
provider_id: str
|
||||
state: Literal["complete", "sampled", "truncated", "unavailable"]
|
||||
returned: int
|
||||
total_available: int | None = None
|
||||
explanation: str | None = None
|
||||
subjects: list[PolicyImpactSubjectItem] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PolicyImpactPreviewResponse(BaseModel):
|
||||
preview_id: str
|
||||
proposal_hash: str
|
||||
policy_family: str
|
||||
scope_type: str
|
||||
scope_id: str | None = None
|
||||
base_revision: int | None = None
|
||||
counts: dict[
|
||||
Literal[
|
||||
"newly_allowed",
|
||||
"newly_denied",
|
||||
"unchanged",
|
||||
"indeterminate",
|
||||
],
|
||||
int,
|
||||
]
|
||||
effects: list[PolicyImpactEffectItem] = Field(default_factory=list)
|
||||
populations: list[PolicyImpactPopulationResponseItem] = Field(default_factory=list)
|
||||
details_hidden: bool = False
|
||||
details_explanation: str | None = None
|
||||
high_impact: bool = False
|
||||
|
||||
|
||||
class PrivacyRetentionPolicyExplainResponse(BaseModel):
|
||||
scope_type: Literal["system", "tenant", "user", "group", "campaign"]
|
||||
scope_id: str | None = None
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.core.policy import (
|
||||
CampaignArchiveEncryptionDecision,
|
||||
CampaignArchiveEncryptionRequest,
|
||||
PolicySourceStep,
|
||||
)
|
||||
from govoplan_policy.backend.policy_overrides import (
|
||||
PolicyOverride,
|
||||
get_policy_override,
|
||||
resolution_policy_overrides,
|
||||
set_policy_override,
|
||||
)
|
||||
|
||||
|
||||
POLICY_FAMILY = "campaign_archive_encryption"
|
||||
POLICY_TARGET = "*"
|
||||
ENCRYPTION_METHODS = frozenset({"aes", "zip_standard"})
|
||||
PASSWORD_DELIVERY_CHANNELS = frozenset(
|
||||
{"separate_mail", "sms", "letter", "phone", "in_person"}
|
||||
)
|
||||
DEFAULT_METHODS = frozenset({"aes"})
|
||||
DEFAULT_DELIVERY_CHANNELS = PASSWORD_DELIVERY_CHANNELS
|
||||
|
||||
|
||||
class CampaignArchiveEncryptionPolicyError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CampaignArchiveEncryptionPolicyState:
|
||||
row: PolicyOverride | None
|
||||
effective: CampaignArchiveEncryptionDecision
|
||||
parent: CampaignArchiveEncryptionDecision
|
||||
|
||||
|
||||
class CampaignArchiveEncryptionPolicyProvider:
|
||||
def resolve_campaign_archive_encryption(
|
||||
self,
|
||||
session: object | None = None,
|
||||
*,
|
||||
request: CampaignArchiveEncryptionRequest,
|
||||
) -> CampaignArchiveEncryptionDecision:
|
||||
if not isinstance(session, Session):
|
||||
return _decision((), reason="Policy storage is unavailable; only AES is safe by default.")
|
||||
rows = resolution_policy_overrides(
|
||||
session,
|
||||
policy_family=POLICY_FAMILY,
|
||||
target_keys=(POLICY_TARGET,),
|
||||
tenant_id=request.tenant_id,
|
||||
group_ids=(request.owner_id,)
|
||||
if request.owner_type == "group" and request.owner_id
|
||||
else (),
|
||||
user_ids=(request.owner_id,)
|
||||
if request.owner_type == "user" and request.owner_id
|
||||
else (),
|
||||
campaign_ids=(request.campaign_id,),
|
||||
)
|
||||
return resolve_campaign_archive_encryption_rows(rows)
|
||||
|
||||
|
||||
def validate_campaign_archive_encryption_policy(
|
||||
value: object,
|
||||
) -> dict[str, tuple[str, ...]]:
|
||||
if not isinstance(value, Mapping):
|
||||
raise CampaignArchiveEncryptionPolicyError("Archive-encryption policy must be an object")
|
||||
supported = {
|
||||
"allowed_password_encryption_methods": ENCRYPTION_METHODS,
|
||||
"allowed_password_delivery_channels": PASSWORD_DELIVERY_CHANNELS,
|
||||
}
|
||||
unknown = sorted(str(key) for key in value if str(key) not in supported)
|
||||
if unknown:
|
||||
raise CampaignArchiveEncryptionPolicyError(
|
||||
f"Unsupported archive-encryption policy fields: {', '.join(unknown)}"
|
||||
)
|
||||
result: dict[str, tuple[str, ...]] = {}
|
||||
for key, raw in value.items():
|
||||
if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes)):
|
||||
raise CampaignArchiveEncryptionPolicyError(f"{key} must be a list")
|
||||
normalized = tuple(dict.fromkeys(str(item).strip() for item in raw))
|
||||
invalid = sorted(set(normalized).difference(supported[str(key)]))
|
||||
if invalid:
|
||||
raise CampaignArchiveEncryptionPolicyError(
|
||||
f"Unsupported values for {key}: {', '.join(invalid)}"
|
||||
)
|
||||
result[str(key)] = normalized
|
||||
return result
|
||||
|
||||
|
||||
def resolve_campaign_archive_encryption_rows(
|
||||
rows: Sequence[PolicyOverride],
|
||||
) -> CampaignArchiveEncryptionDecision:
|
||||
methods = set(DEFAULT_METHODS)
|
||||
channels = set(DEFAULT_DELIVERY_CHANNELS)
|
||||
sources: list[PolicySourceStep] = [
|
||||
PolicySourceStep(
|
||||
scope_type="system",
|
||||
label="Secure archive-encryption baseline",
|
||||
applied_fields=(
|
||||
"allowed_password_encryption_methods",
|
||||
"allowed_password_delivery_channels",
|
||||
),
|
||||
policy={
|
||||
"allowed_password_encryption_methods": sorted(DEFAULT_METHODS),
|
||||
"allowed_password_delivery_channels": sorted(DEFAULT_DELIVERY_CHANNELS),
|
||||
"implicit": True,
|
||||
},
|
||||
)
|
||||
]
|
||||
diagnostics: list[Mapping[str, Any]] = []
|
||||
explicit_system = False
|
||||
for row in rows:
|
||||
try:
|
||||
policy = validate_campaign_archive_encryption_policy(row.policy)
|
||||
except CampaignArchiveEncryptionPolicyError as exc:
|
||||
methods.clear()
|
||||
channels.clear()
|
||||
diagnostics.append(
|
||||
{
|
||||
"code": "campaign_archive_encryption.invalid_fail_closed",
|
||||
"scope": row.scope_key,
|
||||
"message": str(exc),
|
||||
}
|
||||
)
|
||||
sources.append(
|
||||
PolicySourceStep(
|
||||
scope_type=row.scope_type, # type: ignore[arg-type]
|
||||
scope_id=row.scope_id,
|
||||
label=f"{row.scope_type.capitalize()} archive-encryption policy",
|
||||
applied_fields=("configuration_status",),
|
||||
policy={"configuration_status": "invalid_fail_closed"},
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
configured_methods = policy.get("allowed_password_encryption_methods")
|
||||
configured_channels = policy.get("allowed_password_delivery_channels")
|
||||
if row.scope_type == "system" and not explicit_system:
|
||||
explicit_system = True
|
||||
if configured_methods is not None:
|
||||
methods = set(configured_methods)
|
||||
if configured_channels is not None:
|
||||
channels = set(configured_channels)
|
||||
sources[0] = PolicySourceStep(
|
||||
scope_type="system",
|
||||
label="System archive-encryption policy",
|
||||
applied_fields=tuple(sorted(policy)),
|
||||
policy={key: list(items) for key, items in policy.items()},
|
||||
)
|
||||
continue
|
||||
if configured_methods is not None:
|
||||
methods.intersection_update(configured_methods)
|
||||
if configured_channels is not None:
|
||||
channels.intersection_update(configured_channels)
|
||||
sources.append(
|
||||
PolicySourceStep(
|
||||
scope_type=row.scope_type, # type: ignore[arg-type]
|
||||
scope_id=row.scope_id,
|
||||
label=f"{row.scope_type.capitalize()} archive-encryption policy",
|
||||
applied_fields=tuple(sorted(policy)),
|
||||
policy={key: list(items) for key, items in policy.items()},
|
||||
)
|
||||
)
|
||||
return _decision(tuple(sources), methods=methods, channels=channels, diagnostics=diagnostics)
|
||||
|
||||
|
||||
def campaign_archive_encryption_policy_state(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
owner_type: str | None = None,
|
||||
owner_id: str | None = None,
|
||||
) -> CampaignArchiveEncryptionPolicyState:
|
||||
clean_scope = scope_type.strip().casefold()
|
||||
if clean_scope not in {"system", "tenant", "group", "user", "campaign"}:
|
||||
raise CampaignArchiveEncryptionPolicyError("Unsupported policy scope")
|
||||
effective_rows = _rows_for_scope(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
owner_type=owner_type,
|
||||
owner_id=owner_id,
|
||||
)
|
||||
parent_rows = tuple(row for row in effective_rows if row.scope_type != clean_scope)
|
||||
row = get_policy_override(
|
||||
session,
|
||||
policy_family=POLICY_FAMILY,
|
||||
target_key=POLICY_TARGET,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
)
|
||||
return CampaignArchiveEncryptionPolicyState(
|
||||
row=row,
|
||||
effective=resolve_campaign_archive_encryption_rows(effective_rows),
|
||||
parent=resolve_campaign_archive_encryption_rows(parent_rows),
|
||||
)
|
||||
|
||||
|
||||
def save_campaign_archive_encryption_policy(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
owner_type: str | None,
|
||||
owner_id: str | None,
|
||||
policy: object,
|
||||
actor_id: str | None,
|
||||
) -> CampaignArchiveEncryptionPolicyState:
|
||||
clean_policy = validate_campaign_archive_encryption_policy(policy)
|
||||
before = campaign_archive_encryption_policy_state(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
owner_type=owner_type,
|
||||
owner_id=owner_id,
|
||||
)
|
||||
if scope_type.strip().casefold() != "system":
|
||||
requested_methods = set(
|
||||
clean_policy.get(
|
||||
"allowed_password_encryption_methods",
|
||||
tuple(before.parent.allowed_password_encryption_methods),
|
||||
)
|
||||
)
|
||||
requested_channels = set(
|
||||
clean_policy.get(
|
||||
"allowed_password_delivery_channels",
|
||||
tuple(before.parent.allowed_password_delivery_channels),
|
||||
)
|
||||
)
|
||||
if not requested_methods.issubset(before.parent.allowed_password_encryption_methods):
|
||||
raise CampaignArchiveEncryptionPolicyError(
|
||||
"A child scope cannot enable an archive-encryption method blocked by its parent"
|
||||
)
|
||||
if not requested_channels.issubset(before.parent.allowed_password_delivery_channels):
|
||||
raise CampaignArchiveEncryptionPolicyError(
|
||||
"A child scope cannot enable a password-delivery channel blocked by its parent"
|
||||
)
|
||||
set_policy_override(
|
||||
session,
|
||||
policy_family=POLICY_FAMILY,
|
||||
target_key=POLICY_TARGET,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
policy={key: list(items) for key, items in clean_policy.items()},
|
||||
actor_id=actor_id,
|
||||
)
|
||||
return campaign_archive_encryption_policy_state(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
owner_type=owner_type,
|
||||
owner_id=owner_id,
|
||||
)
|
||||
|
||||
|
||||
def _rows_for_scope(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
owner_type: str | None,
|
||||
owner_id: str | None,
|
||||
) -> tuple[PolicyOverride, ...]:
|
||||
group_ids: tuple[str, ...] = ()
|
||||
user_ids: tuple[str, ...] = ()
|
||||
campaign_ids: tuple[str, ...] = ()
|
||||
if scope_type == "group" and scope_id:
|
||||
group_ids = (scope_id,)
|
||||
elif scope_type == "user" and scope_id:
|
||||
user_ids = (scope_id,)
|
||||
elif scope_type == "campaign":
|
||||
if not scope_id:
|
||||
raise CampaignArchiveEncryptionPolicyError("Campaign scope requires scope_id")
|
||||
campaign_ids = (scope_id,)
|
||||
if owner_type == "group" and owner_id:
|
||||
group_ids = (owner_id,)
|
||||
elif owner_type == "user" and owner_id:
|
||||
user_ids = (owner_id,)
|
||||
elif owner_type or owner_id:
|
||||
raise CampaignArchiveEncryptionPolicyError("Campaign owner context is invalid")
|
||||
rows = resolution_policy_overrides(
|
||||
session,
|
||||
policy_family=POLICY_FAMILY,
|
||||
target_keys=(POLICY_TARGET,),
|
||||
tenant_id=tenant_id,
|
||||
group_ids=group_ids,
|
||||
user_ids=user_ids,
|
||||
campaign_ids=campaign_ids,
|
||||
)
|
||||
maximum = {"system": 0, "tenant": 1, "group": 2, "user": 2, "campaign": 3}[scope_type]
|
||||
rank = {"system": 0, "tenant": 1, "group": 2, "user": 2, "campaign": 3}
|
||||
return tuple(row for row in rows if rank.get(row.scope_type, 99) <= maximum)
|
||||
|
||||
|
||||
def _decision(
|
||||
source_path: tuple[PolicySourceStep, ...],
|
||||
*,
|
||||
methods: set[str] | frozenset[str] = DEFAULT_METHODS,
|
||||
channels: set[str] | frozenset[str] = DEFAULT_DELIVERY_CHANNELS,
|
||||
reason: str | None = None,
|
||||
diagnostics: Sequence[Mapping[str, Any]] = (),
|
||||
) -> CampaignArchiveEncryptionDecision:
|
||||
payload = {
|
||||
"allowed_password_encryption_methods": sorted(methods),
|
||||
"allowed_password_delivery_channels": sorted(channels),
|
||||
"source_path": [step.to_dict() for step in source_path],
|
||||
"diagnostics": [dict(item) for item in diagnostics],
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode()
|
||||
).hexdigest()
|
||||
if reason is None:
|
||||
reason = (
|
||||
"Legacy ZipCrypto is permitted by the effective policy."
|
||||
if "zip_standard" in methods
|
||||
else "Legacy ZipCrypto is blocked by the effective archive-encryption policy."
|
||||
)
|
||||
return CampaignArchiveEncryptionDecision(
|
||||
allowed_password_encryption_methods=frozenset(methods), # type: ignore[arg-type]
|
||||
allowed_password_delivery_channels=frozenset(channels), # type: ignore[arg-type]
|
||||
policy_hash=digest,
|
||||
source_path=source_path,
|
||||
reason=reason,
|
||||
diagnostics=tuple(diagnostics),
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CampaignArchiveEncryptionPolicyError",
|
||||
"CampaignArchiveEncryptionPolicyProvider",
|
||||
"CampaignArchiveEncryptionPolicyState",
|
||||
"campaign_archive_encryption_policy_state",
|
||||
"resolve_campaign_archive_encryption_rows",
|
||||
"save_campaign_archive_encryption_policy",
|
||||
"validate_campaign_archive_encryption_policy",
|
||||
]
|
||||
@@ -0,0 +1,129 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Mapping
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.core.datasources import (
|
||||
DatasourceVisibilityPolicyDecision,
|
||||
DatasourceVisibilityPolicyRequest,
|
||||
)
|
||||
from govoplan_policy.backend.policy_overrides import resolution_policy_overrides
|
||||
|
||||
|
||||
POLICY_FAMILY = "datasource_visibility"
|
||||
GLOBAL_TARGET = "*"
|
||||
|
||||
|
||||
class DatasourceVisibilityPolicyProvider:
|
||||
"""Resolve referenced and hierarchical policy overlays without reading rows."""
|
||||
|
||||
def decide_datasource_visibility(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
request: DatasourceVisibilityPolicyRequest,
|
||||
) -> DatasourceVisibilityPolicyDecision:
|
||||
if not isinstance(session, Session):
|
||||
raise TypeError(
|
||||
"Datasource visibility policy requires a SQLAlchemy session"
|
||||
)
|
||||
target_keys = tuple(
|
||||
dict.fromkeys(
|
||||
item for item in (GLOBAL_TARGET, request.policy_ref) if item is not None
|
||||
)
|
||||
)
|
||||
rows = resolution_policy_overrides(
|
||||
session,
|
||||
policy_family=POLICY_FAMILY,
|
||||
target_keys=target_keys,
|
||||
tenant_id=request.tenant_id,
|
||||
group_ids=request.principal.group_ids,
|
||||
user_ids=tuple(
|
||||
dict.fromkeys(
|
||||
item
|
||||
for item in (
|
||||
request.principal.account_id,
|
||||
request.principal.membership_id,
|
||||
)
|
||||
if item
|
||||
)
|
||||
),
|
||||
)
|
||||
normalized_ref = str(request.policy_ref or "").strip().casefold()
|
||||
if normalized_ref and not any(row.target_key == normalized_ref for row in rows):
|
||||
return DatasourceVisibilityPolicyDecision(
|
||||
allowed=False,
|
||||
reason="The referenced Datasource visibility policy is unavailable.",
|
||||
decision_ref=_decision_ref(request, rows),
|
||||
provenance={
|
||||
"provider": "policy.datasource_visibility",
|
||||
"version": "1",
|
||||
"status": "reference_unresolved",
|
||||
"policy_ref": request.policy_ref,
|
||||
},
|
||||
)
|
||||
policies: list[Mapping[str, object]] = []
|
||||
for row in rows:
|
||||
if not isinstance(row.policy, Mapping):
|
||||
return DatasourceVisibilityPolicyDecision(
|
||||
allowed=False,
|
||||
reason="A Datasource visibility policy is malformed.",
|
||||
decision_ref=_decision_ref(request, rows),
|
||||
provenance={
|
||||
"provider": "policy.datasource_visibility",
|
||||
"version": "1",
|
||||
"status": "malformed",
|
||||
"policy_id": row.id,
|
||||
},
|
||||
)
|
||||
policies.append({str(key): value for key, value in row.policy.items()})
|
||||
return DatasourceVisibilityPolicyDecision(
|
||||
allowed=True,
|
||||
policies=tuple(policies),
|
||||
decision_ref=_decision_ref(request, rows),
|
||||
provenance={
|
||||
"provider": "policy.datasource_visibility",
|
||||
"version": "1",
|
||||
"status": "resolved",
|
||||
"sources": [
|
||||
{
|
||||
"policy_id": row.id,
|
||||
"target_key": row.target_key,
|
||||
"scope_type": row.scope_type,
|
||||
"scope_id": row.scope_id,
|
||||
"revision": row.revision,
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _decision_ref(request, rows) -> str:
|
||||
payload = {
|
||||
"tenant_id": request.tenant_id,
|
||||
"datasource_ref": request.datasource_ref,
|
||||
"action": request.action,
|
||||
"consistency": request.consistency,
|
||||
"materialization_ref": request.materialization_ref,
|
||||
"policy_ref": request.policy_ref,
|
||||
"rows": [
|
||||
{
|
||||
"id": row.id,
|
||||
"revision": row.revision,
|
||||
"target_key": row.target_key,
|
||||
"scope_key": row.scope_key,
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
).hexdigest()
|
||||
return f"datasource-visibility:{digest}"
|
||||
|
||||
|
||||
__all__ = ["DatasourceVisibilityPolicyProvider", "POLICY_FAMILY"]
|
||||
@@ -0,0 +1,208 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.core.dsar import (
|
||||
DsarErasureActionRef,
|
||||
DsarExecutionResultRef,
|
||||
DsarRecordRef,
|
||||
DsarSubjectRef,
|
||||
dsar_capability_name,
|
||||
)
|
||||
from govoplan_policy.backend.db.models import PolicyOverride
|
||||
|
||||
|
||||
POLICY_DSAR_CAPABILITY = dsar_capability_name("policy")
|
||||
_MAX_RECORDS = 5_000
|
||||
_CONFLICT = object()
|
||||
|
||||
|
||||
class PolicyDsarProvider:
|
||||
provider_id = "policy"
|
||||
module_id = "policy"
|
||||
|
||||
def search_subject(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
tenant_id: str,
|
||||
subject: DsarSubjectRef,
|
||||
) -> Sequence[DsarRecordRef]:
|
||||
db = _session(session)
|
||||
selectors = _selectors(subject)
|
||||
if selectors is None:
|
||||
return ()
|
||||
account_id, override_id = selectors
|
||||
query = db.query(PolicyOverride).filter(
|
||||
PolicyOverride.tenant_id == tenant_id,
|
||||
or_(
|
||||
PolicyOverride.created_by == account_id,
|
||||
PolicyOverride.updated_by == account_id,
|
||||
),
|
||||
)
|
||||
if override_id:
|
||||
query = query.filter(PolicyOverride.id == override_id)
|
||||
rows = (
|
||||
query.order_by(PolicyOverride.created_at, PolicyOverride.id)
|
||||
.limit(_MAX_RECORDS + 1)
|
||||
.all()
|
||||
)
|
||||
if len(rows) > _MAX_RECORDS:
|
||||
raise ValueError("Policy DSAR result limit exceeded; narrow selectors.")
|
||||
return tuple(_record(row, account_id) for row in rows)
|
||||
|
||||
def plan_erasure(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
tenant_id: str,
|
||||
subject: DsarSubjectRef,
|
||||
records: Sequence[DsarRecordRef],
|
||||
) -> Sequence[DsarErasureActionRef]:
|
||||
del tenant_id
|
||||
_session(session)
|
||||
if _selectors(subject) is None:
|
||||
raise ValueError("Policy DSAR subject selectors conflict.")
|
||||
actions = []
|
||||
for record in records:
|
||||
_validate_record(record)
|
||||
actions.append(
|
||||
DsarErasureActionRef(
|
||||
action_id=f"policy:retain:{record.resource_id}",
|
||||
provider_id=self.provider_id,
|
||||
module_id=self.module_id,
|
||||
kind="retain",
|
||||
resource_type=record.resource_type,
|
||||
resource_id=record.resource_id,
|
||||
title=f"Retain {record.title}",
|
||||
rationale=(
|
||||
record.retention_reason
|
||||
or "Policy-change attribution remains governance evidence."
|
||||
),
|
||||
executable=False,
|
||||
)
|
||||
)
|
||||
return tuple(actions)
|
||||
|
||||
def execute_erasure(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
tenant_id: str,
|
||||
subject: DsarSubjectRef,
|
||||
actions: Sequence[DsarErasureActionRef],
|
||||
request_id: str,
|
||||
) -> Sequence[DsarExecutionResultRef]:
|
||||
del tenant_id
|
||||
_session(session)
|
||||
if _selectors(subject) is None:
|
||||
raise ValueError("Policy DSAR subject selectors conflict.")
|
||||
results = []
|
||||
for action in actions:
|
||||
_validate_action(action)
|
||||
if action.executable or action.kind != "retain":
|
||||
raise ValueError("Policy DSAR publishes retain actions only.")
|
||||
results.append(
|
||||
DsarExecutionResultRef(
|
||||
action_id=action.action_id,
|
||||
status="blocked",
|
||||
summary="Policy-change attribution remains governance evidence.",
|
||||
evidence={"request_id": request_id},
|
||||
)
|
||||
)
|
||||
return tuple(results)
|
||||
|
||||
|
||||
def _selectors(subject: DsarSubjectRef) -> tuple[str, str | None] | None:
|
||||
references = subject.external_references
|
||||
account = _coalesce(
|
||||
subject.account_id,
|
||||
references.get("policy.account"),
|
||||
references.get("access.account"),
|
||||
)
|
||||
override_id = _coalesce(
|
||||
references.get("policy.override"), references.get("policy.override_id")
|
||||
)
|
||||
if account is _CONFLICT or override_id is _CONFLICT:
|
||||
return None
|
||||
if not isinstance(account, str) or not account:
|
||||
return None
|
||||
return account, override_id if isinstance(override_id, str) else None
|
||||
|
||||
|
||||
def _record(row: PolicyOverride, account_id: str) -> DsarRecordRef:
|
||||
activities = []
|
||||
if row.created_by == account_id:
|
||||
activities.append("created_policy_override")
|
||||
if row.updated_by == account_id:
|
||||
activities.append("updated_policy_override")
|
||||
return DsarRecordRef(
|
||||
provider_id="policy",
|
||||
module_id="policy",
|
||||
resource_type="policy_override_actor_attribution",
|
||||
resource_id=row.id,
|
||||
category="policy_governance_attribution",
|
||||
title="Policy override actor attribution",
|
||||
data={
|
||||
"override_id": row.id,
|
||||
"policy_family": row.policy_family,
|
||||
"scope_type": row.scope_type,
|
||||
"revision": row.revision,
|
||||
"activities": activities,
|
||||
"created_at": _iso(row.created_at),
|
||||
"updated_at": _iso(row.updated_at),
|
||||
},
|
||||
observed_at=_aware(row.updated_at),
|
||||
immutable_evidence=True,
|
||||
retention_reason=(
|
||||
"Policy-change attribution is retained for governance and accountability."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _coalesce(*values: str | None) -> str | None | object:
|
||||
normalized = {str(value).strip() for value in values if str(value or "").strip()}
|
||||
if len(normalized) > 1:
|
||||
return _CONFLICT
|
||||
return next(iter(normalized), None)
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
aware = _aware(value)
|
||||
return aware.isoformat() if aware else None
|
||||
|
||||
|
||||
def _aware(value: datetime | None) -> datetime | None:
|
||||
if value is None or value.tzinfo is not None:
|
||||
return value
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
|
||||
|
||||
def _session(value: object) -> Session:
|
||||
if not isinstance(value, Session):
|
||||
raise TypeError("Policy DSAR requires a SQLAlchemy Session.")
|
||||
return value
|
||||
|
||||
|
||||
def _validate_record(record: DsarRecordRef) -> None:
|
||||
if record.provider_id != "policy" or record.module_id != "policy":
|
||||
raise ValueError("Policy DSAR cannot plan a foreign provider record.")
|
||||
if (
|
||||
record.resource_type != "policy_override_actor_attribution"
|
||||
or not record.resource_id
|
||||
):
|
||||
raise ValueError("Policy DSAR record identity is invalid.")
|
||||
|
||||
|
||||
def _validate_action(action: DsarErasureActionRef) -> None:
|
||||
if action.provider_id != "policy" or action.module_id != "policy":
|
||||
raise ValueError("Policy DSAR cannot execute a foreign provider action.")
|
||||
if not action.action_id.startswith("policy:retain:"):
|
||||
raise ValueError("Policy DSAR action identity is invalid.")
|
||||
|
||||
|
||||
__all__ = ["POLICY_DSAR_CAPABILITY", "PolicyDsarProvider"]
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
from collections.abc import Mapping
|
||||
|
||||
from govoplan_core.core.policy import (
|
||||
FunctionAssignmentEscalationRule,
|
||||
FunctionAssignmentGovernanceDecision,
|
||||
FunctionAssignmentGovernanceRequest,
|
||||
PolicySourceStep,
|
||||
@@ -50,6 +51,25 @@ class FunctionAssignmentGovernancePolicyProvider:
|
||||
),
|
||||
)
|
||||
authority_function_id = _text(policy.get("authority_function_id"))
|
||||
delegation_allowed = _bool(
|
||||
policy.get("delegation_allowed"),
|
||||
default=False,
|
||||
)
|
||||
maximum_delegation_depth = (
|
||||
_bounded_int(
|
||||
policy.get("maximum_delegation_depth"),
|
||||
default=1,
|
||||
minimum=1,
|
||||
maximum=20,
|
||||
)
|
||||
if delegation_allowed
|
||||
else 0
|
||||
)
|
||||
maximum_delegated_validity_days = _optional_positive_int(
|
||||
policy.get("maximum_delegated_validity_days"),
|
||||
maximum=3650,
|
||||
)
|
||||
escalation_rules, escalation_requirements = _escalation_rules(policy)
|
||||
requirements: list[str] = []
|
||||
if "authority" in required_steps and authority_function_id is None:
|
||||
requirements.append("authority_function")
|
||||
@@ -59,6 +79,7 @@ class FunctionAssignmentGovernancePolicyProvider:
|
||||
)
|
||||
if evidence_required and not request.context.get("has_evidence"):
|
||||
requirements.append("evidence")
|
||||
requirements.extend(escalation_requirements)
|
||||
allowed, reason = _action_decision(
|
||||
request,
|
||||
profile=profile,
|
||||
@@ -79,6 +100,10 @@ class FunctionAssignmentGovernancePolicyProvider:
|
||||
required_steps=required_steps,
|
||||
authority_function_id=authority_function_id,
|
||||
evidence_required=evidence_required,
|
||||
delegation_allowed=delegation_allowed,
|
||||
maximum_delegation_depth=maximum_delegation_depth,
|
||||
maximum_delegated_validity_days=maximum_delegated_validity_days,
|
||||
escalation_rules=escalation_rules,
|
||||
requirements=tuple(requirements),
|
||||
)
|
||||
|
||||
@@ -106,19 +131,44 @@ def _action_decision(
|
||||
return True, None
|
||||
if profile == "authority_only":
|
||||
allowed = bool(context.get("actor_is_authority"))
|
||||
reason = "Only the designated authority may initiate this grant."
|
||||
reason = _route_reason(
|
||||
context,
|
||||
"authority",
|
||||
"Only the designated authority may initiate this grant.",
|
||||
)
|
||||
else:
|
||||
allowed = bool(context.get("actor_is_holder"))
|
||||
reason = "An effective function holder must initiate this grant."
|
||||
reason = _route_reason(
|
||||
context,
|
||||
"holder",
|
||||
"An effective function holder must initiate this grant.",
|
||||
)
|
||||
return allowed, None if allowed else reason
|
||||
if action == "approve_holder":
|
||||
allowed = "holder" in required_steps and bool(context.get("actor_is_holder"))
|
||||
return allowed, None if allowed else "A current holder must approve."
|
||||
return allowed, None if allowed else _route_reason(
|
||||
context,
|
||||
"holder",
|
||||
"A current holder must approve.",
|
||||
)
|
||||
if action == "approve_authority":
|
||||
allowed = "authority" in required_steps and bool(
|
||||
context.get("actor_is_authority")
|
||||
)
|
||||
return allowed, None if allowed else "The designated authority must approve."
|
||||
return allowed, None if allowed else _route_reason(
|
||||
context,
|
||||
"authority",
|
||||
"The designated authority must approve.",
|
||||
)
|
||||
if action == "approve_escalation":
|
||||
allowed = request.current_state == "escalated" and bool(
|
||||
context.get("actor_is_escalation_target")
|
||||
)
|
||||
return allowed, None if allowed else _route_reason(
|
||||
context,
|
||||
"escalation",
|
||||
"A current holder of the explicit escalation target must approve.",
|
||||
)
|
||||
if action == "accept_recipient":
|
||||
allowed = "recipient" in required_steps and bool(
|
||||
context.get("candidate_is_actor")
|
||||
@@ -134,6 +184,13 @@ def _action_decision(
|
||||
elif request.current_state == "awaiting_recipient":
|
||||
allowed = bool(context.get("candidate_is_actor"))
|
||||
reason = "Only the candidate may act at recipient acceptance."
|
||||
elif request.current_state == "escalated":
|
||||
allowed = bool(context.get("actor_is_escalation_target"))
|
||||
reason = _route_reason(
|
||||
context,
|
||||
"escalation",
|
||||
"Only a current holder of the explicit escalation target may act.",
|
||||
)
|
||||
else:
|
||||
allowed = False
|
||||
reason = "The current state does not accept this review action."
|
||||
@@ -196,6 +253,10 @@ def _decision(
|
||||
required_steps: tuple[str, ...] = (),
|
||||
authority_function_id: str | None = None,
|
||||
evidence_required: bool = False,
|
||||
delegation_allowed: bool = False,
|
||||
maximum_delegation_depth: int = 0,
|
||||
maximum_delegated_validity_days: int | None = None,
|
||||
escalation_rules: tuple[FunctionAssignmentEscalationRule, ...] = (),
|
||||
requirements: tuple[str, ...] = (),
|
||||
) -> FunctionAssignmentGovernanceDecision:
|
||||
recipient_required = "recipient" in required_steps
|
||||
@@ -216,6 +277,10 @@ def _decision(
|
||||
policy.get("maximum_validity_days"),
|
||||
maximum=3650,
|
||||
),
|
||||
delegation_allowed=delegation_allowed,
|
||||
maximum_delegation_depth=maximum_delegation_depth,
|
||||
maximum_delegated_validity_days=maximum_delegated_validity_days,
|
||||
escalation_rules=escalation_rules,
|
||||
request_expiry_hours=_bounded_int(
|
||||
policy.get("request_expiry_hours"),
|
||||
default=336,
|
||||
@@ -236,6 +301,7 @@ def _decision(
|
||||
"function_id": request.function_id,
|
||||
"kind": request.kind,
|
||||
"action": request.action,
|
||||
"actor_routes": dict(request.context.get("actor_routes") or {}),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -250,6 +316,9 @@ def _requirements_reason(requirements: list[str]) -> str:
|
||||
"authority_function": "a designated authority function",
|
||||
"evidence": "the required evidence",
|
||||
"valid_profile": "a supported governance profile",
|
||||
"escalation_holder": "a valid holder-step escalation rule",
|
||||
"escalation_authority": "a valid authority-step escalation rule",
|
||||
"escalation_recipient": "a valid recipient-step escalation rule",
|
||||
}
|
||||
return (
|
||||
"Submission requires "
|
||||
@@ -258,6 +327,55 @@ def _requirements_reason(requirements: list[str]) -> str:
|
||||
)
|
||||
|
||||
|
||||
def _escalation_rules(
|
||||
policy: Mapping[str, object],
|
||||
) -> tuple[tuple[FunctionAssignmentEscalationRule, ...], list[str]]:
|
||||
raw = policy.get("escalation")
|
||||
if raw is None:
|
||||
return (), []
|
||||
if not isinstance(raw, Mapping):
|
||||
return (), ["escalation_holder"]
|
||||
rules: list[FunctionAssignmentEscalationRule] = []
|
||||
requirements: list[str] = []
|
||||
for step in ("holder", "authority", "recipient"):
|
||||
value = raw.get(step)
|
||||
if value is None:
|
||||
continue
|
||||
if not isinstance(value, Mapping):
|
||||
requirements.append(f"escalation_{step}")
|
||||
continue
|
||||
target_function_id = _text(value.get("target_function_id"))
|
||||
timeout_hours = _optional_positive_int(
|
||||
value.get("timeout_hours"),
|
||||
maximum=8760,
|
||||
)
|
||||
if target_function_id is None or timeout_hours is None:
|
||||
requirements.append(f"escalation_{step}")
|
||||
continue
|
||||
rules.append(
|
||||
FunctionAssignmentEscalationRule(
|
||||
step=step, # type: ignore[arg-type]
|
||||
target_function_id=target_function_id,
|
||||
timeout_hours=timeout_hours,
|
||||
)
|
||||
)
|
||||
return tuple(rules), requirements
|
||||
|
||||
|
||||
def _route_reason(
|
||||
context: Mapping[str, object],
|
||||
route: str,
|
||||
fallback: str,
|
||||
) -> str:
|
||||
routes = context.get("actor_routes")
|
||||
if not isinstance(routes, Mapping):
|
||||
return fallback
|
||||
value = routes.get(route)
|
||||
if not isinstance(value, Mapping):
|
||||
return fallback
|
||||
return _text(value.get("reason")) or fallback
|
||||
|
||||
|
||||
def _has_scope(
|
||||
request: FunctionAssignmentGovernanceRequest,
|
||||
scope: str,
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
"""German translations for public structured documentation metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
GERMAN_STRUCTURED_TRANSLATIONS: dict[str, dict[str, Any]] = {'policy.data-subject-requests': {'consequence_classes': {'export_policy_attribution': 'Returns '
|
||||
'minimiert '
|
||||
'Politik '
|
||||
'Aktivität '
|
||||
'für das '
|
||||
'genaue '
|
||||
'Konto.',
|
||||
'retain_policy_evidence': 'Bewahrt die '
|
||||
'politische '
|
||||
'Governance-Rechenschaftspflicht.'}},
|
||||
'policy.function-assignment-delegation-escalation': {'fields': [{'consequence': 'Erlaubt nur dann '
|
||||
'geregelte '
|
||||
'abgeleitete '
|
||||
'Zuweisungen, '
|
||||
'wenn '
|
||||
'Organisationen '
|
||||
'auch die '
|
||||
'Funktion '
|
||||
'delegierbar '
|
||||
'markieren.',
|
||||
'key': 'delegation_allowed'},
|
||||
{'consequence': 'Lehnt längere '
|
||||
'aktuelle Ketten '
|
||||
'ab, '
|
||||
'einschließlich '
|
||||
'Ketten, die vor '
|
||||
'einem engeren '
|
||||
'Limit akzeptiert '
|
||||
'wurden.',
|
||||
'key': 'maximum_delegation_depth'},
|
||||
{'consequence': 'Caps jedes '
|
||||
'delegierte '
|
||||
'Gültigkeitsfenster '
|
||||
'zusätzlich zu '
|
||||
'seinem '
|
||||
'Quellfenster.',
|
||||
'key': 'maximum_delegated_validity_days'},
|
||||
{'consequence': 'Pins eine '
|
||||
'Zielfunktion und '
|
||||
'Frist ohne '
|
||||
'Erteilung oder '
|
||||
'Ersatz '
|
||||
'Genehmigung.',
|
||||
'key': 'escalation.<step>'}]},
|
||||
'policy.hierarchy-overrides-and-retention': {'outcome': 'Der ausgewählte Berechtigungsumfang hat '
|
||||
'eine erklärbare Aufbewahrungsrichtlinie '
|
||||
'und jeder destruktiven Anwendung wird '
|
||||
'eine Dry-Run-Überprüfung vorausgegangen.',
|
||||
'prerequisites': ['Policy und Access sind aktiviert.',
|
||||
'Die handelnde Person kann die '
|
||||
'Richtlinieneinstellungen am '
|
||||
'ausgewählten Bereich lesen.'],
|
||||
'steps': ['Überprüfen Sie den effektiven Wert und '
|
||||
'seinen Policy Source Path.',
|
||||
'Schmale nur Felder, die die übergeordnete '
|
||||
'Richtlinie diesen Bereich außer Kraft '
|
||||
'setzt.',
|
||||
'Speichern Sie die Richtlinie und führen '
|
||||
'Sie dann einen System-Dry-Run aus, bevor '
|
||||
'Sie die Retention anwenden.',
|
||||
'Überprüfen Sie das Bounded Outcome und '
|
||||
'prüfen Sie den Nachweis nach einem '
|
||||
'angewandten Durchlauf.'],
|
||||
'verification': 'Laden Sie die Richtlinie neu, '
|
||||
'bestätigen Sie ihren Quellpfad und '
|
||||
'vergleichen Sie die Trockenlauf- '
|
||||
'oder angewandte Ergebnistabelle mit '
|
||||
'den Prüfungsnachweisen.'},
|
||||
'policy.impact-preview': {'limitations': ['Nicht verfügbare optionale Anbieter werden erklärt und '
|
||||
'niemals als Null-Auswirkungen behandelt.',
|
||||
'Ressourcendetails werden ohne policy:impact:details '
|
||||
'ausgeblendet.'],
|
||||
'steps': ['Wählen Sie eine explizite Impact-Provider-Population und ein '
|
||||
'begrenztes Limit.',
|
||||
'Preview und Inspect Outcome Counts, Coverage State und '
|
||||
'Provenienz.',
|
||||
'Reauthentifizieren, wenn eine systemweite Änderung als hohe '
|
||||
'Auswirkungen eingestuft wird.',
|
||||
'Speichern Sie erst, nachdem die Vorschau mit dem aktuellen '
|
||||
'Dirty Draft übereinstimmt.']},
|
||||
'policy.retention-execution-and-recovery': {'limitations': ['Die Anwendung kann gelöschte EML- '
|
||||
'oder Mock-Mailbox-Inhalte nicht '
|
||||
'wiederherstellen.',
|
||||
'Ein Trockenlauf ist eine Vorschau '
|
||||
'und reserviert den gemeldeten Satz '
|
||||
'nicht gegen gleichzeitige '
|
||||
'Änderungen.'],
|
||||
'outcome': 'Förderfähige Details werden redigiert und '
|
||||
'förderfähige generierte Artefakte werden '
|
||||
'mit begrenztem Ergebnis und '
|
||||
'Prüfungsnachweis gelöscht.',
|
||||
'prerequisites': ['Die handelnde Person kann '
|
||||
'Systemeinstellungen schreiben.',
|
||||
'Die vorgesehene '
|
||||
'Systemaufbewahrungsrichtlinie wird '
|
||||
'gespeichert und neu geladen.',
|
||||
'Recovery Evidenz ist aktuell für '
|
||||
'generierte Artefakte.'],
|
||||
'steps': ['Führen Sie einen Trockenlauf durch und '
|
||||
'überprüfen Sie jede Datenklasse und '
|
||||
'Ergebniszahl.',
|
||||
'Stoppen Sie, wenn Anbieter ausfallen, die '
|
||||
'Wiederherstellung blockiert wird oder '
|
||||
'Zählungen unerwartet sind.',
|
||||
'Bestätigen Sie den destruktiven Lauf erst '
|
||||
'nach einer Überprüfung der Politik und der '
|
||||
'Wiederherstellung.',
|
||||
'Vergleichen Sie das angewandte Ergebnis '
|
||||
'mit den Prüfungsnachweisen.'],
|
||||
'verification': 'Überprüfen Sie das neueste Ergebnis, '
|
||||
'die Fehler- und '
|
||||
'Wiederherstellungszahlen des '
|
||||
'Anbieters und suchen Sie dann den '
|
||||
'Auditdatensatz retention '
|
||||
'policy.run.'}}
|
||||
@@ -0,0 +1,429 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.core.policy import (
|
||||
PolicyImpactPopulationRequest,
|
||||
PolicyImpactSubject,
|
||||
PolicyImpactSubjectBatch,
|
||||
PolicySourceStep,
|
||||
normalize_policy_scope_type,
|
||||
policy_impact_subject_provider,
|
||||
)
|
||||
from govoplan_policy.backend.view_governance import (
|
||||
VIEW_POLICY_BOOLEAN_FIELDS,
|
||||
ViewPolicyResolution,
|
||||
)
|
||||
from govoplan_policy.backend.view_policy_service import (
|
||||
validate_view_policy_change,
|
||||
)
|
||||
|
||||
|
||||
PolicyImpactCategory = Literal[
|
||||
"newly_allowed",
|
||||
"newly_denied",
|
||||
"unchanged",
|
||||
"indeterminate",
|
||||
]
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PolicyImpactPreviewError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PolicyImpactPopulationSpec:
|
||||
provider_id: str
|
||||
selector: Mapping[str, Any] = field(default_factory=dict)
|
||||
limit: int = 200
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PolicyImpactEffect:
|
||||
category: PolicyImpactCategory
|
||||
subject: PolicyImpactSubject
|
||||
current_allowed: bool | None
|
||||
proposed_allowed: bool | None
|
||||
rule: str
|
||||
current_sources: tuple[PolicySourceStep, ...] = ()
|
||||
proposed_sources: tuple[PolicySourceStep, ...] = ()
|
||||
explanation: str | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"category": self.category,
|
||||
"subject": self.subject.to_dict(),
|
||||
"current_allowed": self.current_allowed,
|
||||
"proposed_allowed": self.proposed_allowed,
|
||||
"rule": self.rule,
|
||||
"current_sources": [step.to_dict() for step in self.current_sources],
|
||||
"proposed_sources": [step.to_dict() for step in self.proposed_sources],
|
||||
"explanation": self.explanation,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PolicyImpactPreview:
|
||||
preview_id: str
|
||||
proposal_hash: str
|
||||
policy_family: str
|
||||
scope_type: str
|
||||
scope_id: str | None
|
||||
base_revision: int | None
|
||||
counts: Mapping[PolicyImpactCategory, int]
|
||||
effects: tuple[PolicyImpactEffect, ...]
|
||||
populations: tuple[Mapping[str, Any], ...]
|
||||
details_hidden: bool
|
||||
details_explanation: str | None
|
||||
high_impact: bool
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"preview_id": self.preview_id,
|
||||
"proposal_hash": self.proposal_hash,
|
||||
"policy_family": self.policy_family,
|
||||
"scope_type": self.scope_type,
|
||||
"scope_id": self.scope_id,
|
||||
"base_revision": self.base_revision,
|
||||
"counts": dict(self.counts),
|
||||
"effects": [effect.to_dict() for effect in self.effects],
|
||||
"populations": [dict(population) for population in self.populations],
|
||||
"details_hidden": self.details_hidden,
|
||||
"details_explanation": self.details_explanation,
|
||||
"high_impact": self.high_impact,
|
||||
}
|
||||
|
||||
|
||||
def preview_policy_impact(
|
||||
session: Session,
|
||||
*,
|
||||
registry: object,
|
||||
tenant_id: str,
|
||||
policy_family: str,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
proposed_policy: object,
|
||||
populations: Sequence[PolicyImpactPopulationSpec],
|
||||
actor_scopes: Sequence[str] = (),
|
||||
include_details: bool = False,
|
||||
details_allowed: bool = False,
|
||||
) -> PolicyImpactPreview:
|
||||
clean_family = policy_family.strip().casefold()
|
||||
clean_scope = normalize_policy_scope_type(scope_type)
|
||||
if clean_family != "view":
|
||||
raise PolicyImpactPreviewError(
|
||||
"The current impact evaluator supports the View policy family."
|
||||
)
|
||||
if not populations or len(populations) > 10:
|
||||
raise PolicyImpactPreviewError(
|
||||
"Policy impact preview requires between 1 and 10 explicit populations."
|
||||
)
|
||||
|
||||
clean_policy, current_state = validate_view_policy_change(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
policy=proposed_policy,
|
||||
)
|
||||
proposed = _proposed_view_resolution(
|
||||
parent=current_state.parent,
|
||||
policy=clean_policy,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
)
|
||||
allow_details = include_details and details_allowed
|
||||
counts: dict[PolicyImpactCategory, int] = {
|
||||
"newly_allowed": 0,
|
||||
"newly_denied": 0,
|
||||
"unchanged": 0,
|
||||
"indeterminate": 0,
|
||||
}
|
||||
effects: list[PolicyImpactEffect] = []
|
||||
population_results: list[Mapping[str, Any]] = []
|
||||
seen_subjects: set[tuple[str, str, str, str]] = set()
|
||||
|
||||
for specification in populations:
|
||||
provider_id = specification.provider_id.strip()
|
||||
provider = policy_impact_subject_provider(registry, provider_id)
|
||||
if provider is None:
|
||||
population_results.append(
|
||||
PolicyImpactSubjectBatch(
|
||||
provider_id=provider_id or "unknown",
|
||||
state="unavailable",
|
||||
explanation=(
|
||||
"The requested impact-subject provider is not enabled or "
|
||||
"does not implement the Core contract."
|
||||
),
|
||||
).to_dict(include_subjects=False)
|
||||
)
|
||||
continue
|
||||
if clean_family not in provider.supported_policy_families:
|
||||
population_results.append(
|
||||
PolicyImpactSubjectBatch(
|
||||
provider_id=provider_id,
|
||||
state="unavailable",
|
||||
explanation=(
|
||||
"The provider does not support the requested policy family."
|
||||
),
|
||||
).to_dict(include_subjects=False)
|
||||
)
|
||||
continue
|
||||
try:
|
||||
batch = provider.collect_policy_impact_subjects(
|
||||
session,
|
||||
request=PolicyImpactPopulationRequest(
|
||||
tenant_id=tenant_id,
|
||||
policy_family=clean_family,
|
||||
selector=specification.selector,
|
||||
limit=specification.limit,
|
||||
actor_scopes=tuple(actor_scopes),
|
||||
allow_sensitive_details=allow_details,
|
||||
),
|
||||
)
|
||||
if batch.provider_id != provider_id:
|
||||
raise PolicyImpactPreviewError(
|
||||
"Policy impact provider returned a mismatched provider ID."
|
||||
)
|
||||
except Exception: # noqa: BLE001 - isolate optional providers.
|
||||
logger.exception(
|
||||
"Policy impact subject provider failed provider_id=%s family=%s",
|
||||
provider_id,
|
||||
clean_family,
|
||||
)
|
||||
batch = PolicyImpactSubjectBatch(
|
||||
provider_id=provider_id,
|
||||
state="unavailable",
|
||||
explanation=(
|
||||
"The provider could not evaluate this population. Inspect "
|
||||
"operator logs before committing the proposed change."
|
||||
),
|
||||
)
|
||||
population_results.append(batch.to_dict(include_subjects=False))
|
||||
for subject in batch.subjects:
|
||||
if subject.key in seen_subjects:
|
||||
continue
|
||||
seen_subjects.add(subject.key)
|
||||
effect = _compare_view_subject(
|
||||
subject,
|
||||
current=current_state.effective,
|
||||
proposed=proposed,
|
||||
)
|
||||
counts[effect.category] += 1
|
||||
if allow_details:
|
||||
effects.append(effect)
|
||||
|
||||
changed = counts["newly_allowed"] + counts["newly_denied"]
|
||||
return PolicyImpactPreview(
|
||||
preview_id=str(uuid4()),
|
||||
proposal_hash=policy_impact_proposal_hash(
|
||||
family=clean_family,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
policy=clean_policy,
|
||||
base_policy=current_state.local_policy,
|
||||
base_revision=(
|
||||
current_state.row.revision if current_state.row is not None else None
|
||||
),
|
||||
),
|
||||
policy_family=clean_family,
|
||||
scope_type=clean_scope,
|
||||
scope_id=scope_id,
|
||||
base_revision=(
|
||||
current_state.row.revision if current_state.row is not None else None
|
||||
),
|
||||
counts=counts,
|
||||
effects=tuple(effects),
|
||||
populations=tuple(population_results),
|
||||
details_hidden=include_details and not details_allowed,
|
||||
details_explanation=(
|
||||
None
|
||||
if not include_details or details_allowed
|
||||
else "Subject details require policy:impact:details; aggregate counts remain visible."
|
||||
),
|
||||
high_impact=changed > 0 and clean_scope == "system",
|
||||
)
|
||||
|
||||
|
||||
def _proposed_view_resolution(
|
||||
*,
|
||||
parent: ViewPolicyResolution,
|
||||
policy: Mapping[str, bool | tuple[str, ...]],
|
||||
tenant_id: str,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
) -> ViewPolicyResolution:
|
||||
limits = dict(parent.limits)
|
||||
for field_name in VIEW_POLICY_BOOLEAN_FIELDS:
|
||||
value = policy.get(field_name)
|
||||
if isinstance(value, bool):
|
||||
limits[field_name] = limits[field_name] and value
|
||||
allowed_view_ids = _narrow_set(
|
||||
parent.allowed_view_ids,
|
||||
policy.get("allowed_view_ids"),
|
||||
)
|
||||
visible_surface_ids = _narrow_set(
|
||||
parent.visible_surface_ids,
|
||||
policy.get("visible_surface_ids"),
|
||||
)
|
||||
source_path = parent.source_path
|
||||
if policy:
|
||||
source_path = (
|
||||
*source_path,
|
||||
PolicySourceStep(
|
||||
scope_type=normalize_policy_scope_type(scope_type),
|
||||
scope_id=tenant_id if scope_type == "tenant" else scope_id,
|
||||
label=f"Proposed {scope_type.capitalize()} View policy",
|
||||
applied_fields=tuple(sorted(policy)),
|
||||
policy={
|
||||
key: list(value) if isinstance(value, tuple) else value
|
||||
for key, value in policy.items()
|
||||
},
|
||||
),
|
||||
)
|
||||
return ViewPolicyResolution(
|
||||
limits=limits,
|
||||
allowed_view_ids=allowed_view_ids,
|
||||
visible_surface_ids=visible_surface_ids,
|
||||
source_path=source_path,
|
||||
diagnostics=parent.diagnostics,
|
||||
)
|
||||
|
||||
|
||||
def _narrow_set(
|
||||
parent: frozenset[str] | None,
|
||||
value: object,
|
||||
) -> frozenset[str] | None:
|
||||
if not isinstance(value, tuple):
|
||||
return parent
|
||||
proposed = frozenset(value)
|
||||
return proposed if parent is None else parent.intersection(proposed)
|
||||
|
||||
|
||||
def _compare_view_subject(
|
||||
subject: PolicyImpactSubject,
|
||||
*,
|
||||
current: ViewPolicyResolution,
|
||||
proposed: ViewPolicyResolution,
|
||||
) -> PolicyImpactEffect:
|
||||
current_allowed, rule = _view_subject_decision(subject, current)
|
||||
proposed_allowed, _ = _view_subject_decision(subject, proposed)
|
||||
if current_allowed is None or proposed_allowed is None:
|
||||
category: PolicyImpactCategory = "indeterminate"
|
||||
elif current_allowed == proposed_allowed:
|
||||
category = "unchanged"
|
||||
elif proposed_allowed:
|
||||
category = "newly_allowed"
|
||||
else:
|
||||
category = "newly_denied"
|
||||
source_fields = [
|
||||
field_name
|
||||
for field_name in (rule.removeprefix("view."), "allow_view")
|
||||
if field_name
|
||||
]
|
||||
if subject.resource_type == "view":
|
||||
source_fields.append("allowed_view_ids")
|
||||
elif subject.resource_type == "surface":
|
||||
source_fields.append("visible_surface_ids")
|
||||
return PolicyImpactEffect(
|
||||
category=category,
|
||||
subject=subject,
|
||||
current_allowed=current_allowed,
|
||||
proposed_allowed=proposed_allowed,
|
||||
rule=rule,
|
||||
current_sources=_sources_for_fields(current.source_path, tuple(source_fields)),
|
||||
proposed_sources=_sources_for_fields(proposed.source_path, tuple(source_fields)),
|
||||
explanation=(
|
||||
"The provider subject or action is not supported by the View evaluator."
|
||||
if category == "indeterminate"
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _view_subject_decision(
|
||||
subject: PolicyImpactSubject,
|
||||
resolution: ViewPolicyResolution,
|
||||
) -> tuple[bool | None, str]:
|
||||
if subject.resource_type == "surface":
|
||||
allowed = resolution.limits["allow_view"]
|
||||
if resolution.visible_surface_ids is not None:
|
||||
allowed = allowed and subject.resource_id in resolution.visible_surface_ids
|
||||
return allowed, "view.visible_surface_ids"
|
||||
if subject.resource_type != "view" or subject.action not in {
|
||||
"view",
|
||||
"select",
|
||||
"assign",
|
||||
"edit",
|
||||
"derive",
|
||||
"workflow_activate",
|
||||
}:
|
||||
return None, "view.unsupported"
|
||||
action_field = f"allow_{subject.action}"
|
||||
allowed = resolution.limits["allow_view"] and resolution.limits[action_field]
|
||||
if resolution.allowed_view_ids is not None:
|
||||
allowed = allowed and subject.resource_id in resolution.allowed_view_ids
|
||||
return allowed, f"view.{action_field}"
|
||||
|
||||
|
||||
def _sources_for_fields(
|
||||
source_path: Sequence[PolicySourceStep],
|
||||
fields: Sequence[str],
|
||||
) -> tuple[PolicySourceStep, ...]:
|
||||
relevant = set(fields)
|
||||
return tuple(
|
||||
step
|
||||
for step in source_path
|
||||
if relevant.intersection(step.applied_fields)
|
||||
)
|
||||
|
||||
|
||||
def policy_impact_proposal_hash(
|
||||
*,
|
||||
family: str,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
policy: Mapping[str, Any],
|
||||
base_policy: Mapping[str, Any],
|
||||
base_revision: int | None,
|
||||
) -> str:
|
||||
payload = json.dumps(
|
||||
{
|
||||
"policy_family": family,
|
||||
"scope_type": scope_type,
|
||||
"scope_id": scope_id,
|
||||
"base_revision": base_revision,
|
||||
"base_policy": {
|
||||
key: list(value) if isinstance(value, tuple) else value
|
||||
for key, value in base_policy.items()
|
||||
},
|
||||
"policy": {
|
||||
key: list(value) if isinstance(value, tuple) else value
|
||||
for key, value in policy.items()
|
||||
},
|
||||
},
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PolicyImpactEffect",
|
||||
"PolicyImpactPopulationSpec",
|
||||
"PolicyImpactPreview",
|
||||
"PolicyImpactPreviewError",
|
||||
"policy_impact_proposal_hash",
|
||||
"preview_policy_impact",
|
||||
]
|
||||
@@ -1,19 +1,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from govoplan_core.core.modules import with_documentation_structured_translations
|
||||
from govoplan_policy.backend.german_structured_documentation import GERMAN_STRUCTURED_TRANSLATIONS
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from govoplan_core.core.access import (
|
||||
CAPABILITY_AUTH_PERMISSION_EVALUATOR,
|
||||
CAPABILITY_AUTH_PRINCIPAL_RESOLVER,
|
||||
CAPABILITY_POLICY_ACCESS_EXPLANATION_SUBJECTS,
|
||||
)
|
||||
from govoplan_core.core.distribution_lists import (
|
||||
CAPABILITY_POLICY_DISTRIBUTION_CHANNELS,
|
||||
)
|
||||
from govoplan_core.core.datasources import CAPABILITY_POLICY_DATASOURCE_VISIBILITY
|
||||
from govoplan_core.core.module_guards import (
|
||||
drop_table_retirement_provider,
|
||||
persistent_table_uninstall_guard,
|
||||
)
|
||||
from govoplan_core.core.policy import (
|
||||
CAPABILITY_POLICY_CAMPAIGN_ARCHIVE_ENCRYPTION,
|
||||
CAPABILITY_POLICY_DEFINITION_GOVERNANCE,
|
||||
CAPABILITY_POLICY_FUNCTION_ASSIGNMENT_GOVERNANCE,
|
||||
CAPABILITY_POLICY_PRIVACY_RETENTION,
|
||||
@@ -22,18 +28,24 @@ from govoplan_core.core.policy import (
|
||||
)
|
||||
from govoplan_core.core.modules import (
|
||||
CapabilityDocumentation,
|
||||
DocumentationLink,
|
||||
DocumentationTopic,
|
||||
FrontendModule,
|
||||
MigrationSpec,
|
||||
ModuleContext,
|
||||
ModuleInterfaceProvider,
|
||||
ModuleManifest,
|
||||
PermissionDefinition,
|
||||
)
|
||||
from govoplan_core.core.reporting import CAPABILITY_POLICY_REPORTING_GOVERNANCE
|
||||
from govoplan_core.core.provider_governance import declared_module_architecture
|
||||
from govoplan_core.core.views import ViewSurface
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_policy.backend.db import models as policy_models
|
||||
from govoplan_policy.backend.dsar_provider import (
|
||||
POLICY_DSAR_CAPABILITY,
|
||||
PolicyDsarProvider,
|
||||
)
|
||||
|
||||
|
||||
def _route_factory(context: ModuleContext):
|
||||
@@ -104,10 +116,72 @@ def _reporting_governance_policy(context: ModuleContext) -> object:
|
||||
return ReportingGovernancePolicyProvider()
|
||||
|
||||
|
||||
def _access_explanation_subject_policy(context: ModuleContext) -> object:
|
||||
del context
|
||||
from govoplan_policy.backend.access_explanation_subjects import (
|
||||
AccessExplanationSubjectPolicyProvider,
|
||||
)
|
||||
|
||||
return AccessExplanationSubjectPolicyProvider()
|
||||
|
||||
|
||||
def _campaign_archive_encryption_policy(context: ModuleContext) -> object:
|
||||
del context
|
||||
from govoplan_policy.backend.campaign_archive_encryption import (
|
||||
CampaignArchiveEncryptionPolicyProvider,
|
||||
)
|
||||
|
||||
return CampaignArchiveEncryptionPolicyProvider()
|
||||
|
||||
|
||||
def _datasource_visibility_policy(context: ModuleContext) -> object:
|
||||
del context
|
||||
from govoplan_policy.backend.datasource_visibility import (
|
||||
DatasourceVisibilityPolicyProvider,
|
||||
)
|
||||
|
||||
return DatasourceVisibilityPolicyProvider()
|
||||
|
||||
|
||||
def _dsar_provider(_context: ModuleContext) -> PolicyDsarProvider:
|
||||
return PolicyDsarProvider()
|
||||
|
||||
|
||||
ACCESS_EXPLANATION_SUBJECT_SCOPE = "policy:access_explanation:select_user"
|
||||
POLICY_IMPACT_DETAILS_SCOPE = "policy:impact:details"
|
||||
|
||||
|
||||
manifest = ModuleManifest(
|
||||
id="policy",
|
||||
name="Policy",
|
||||
version="0.1.18",
|
||||
version="0.1.23",
|
||||
permissions=(
|
||||
PermissionDefinition(
|
||||
scope=ACCESS_EXPLANATION_SUBJECT_SCOPE,
|
||||
label="Select users for access diagnostics",
|
||||
description=(
|
||||
"Run resource-access explanations for another user in the active tenant."
|
||||
),
|
||||
category="Policy",
|
||||
level="tenant",
|
||||
module_id="policy",
|
||||
resource="access_explanation",
|
||||
action="select_user",
|
||||
),
|
||||
PermissionDefinition(
|
||||
scope=POLICY_IMPACT_DETAILS_SCOPE,
|
||||
label="Inspect policy impact subjects",
|
||||
description=(
|
||||
"Inspect resource identifiers and provenance in bounded policy "
|
||||
"impact previews; aggregate counts require only policy-read authority."
|
||||
),
|
||||
category="Policy",
|
||||
level="tenant",
|
||||
module_id="policy",
|
||||
resource="impact",
|
||||
action="details",
|
||||
),
|
||||
),
|
||||
required_capabilities=(
|
||||
CAPABILITY_AUTH_PRINCIPAL_RESOLVER,
|
||||
CAPABILITY_AUTH_PERMISSION_EVALUATOR,
|
||||
@@ -125,6 +199,10 @@ manifest = ModuleManifest(
|
||||
name="policy.function_assignment_governance",
|
||||
version="1.0.0",
|
||||
),
|
||||
ModuleInterfaceProvider(
|
||||
name="policy.impact_preview",
|
||||
version="1.0.0",
|
||||
),
|
||||
ModuleInterfaceProvider(
|
||||
name=CAPABILITY_POLICY_DISTRIBUTION_CHANNELS,
|
||||
version="1.0.0",
|
||||
@@ -133,20 +211,170 @@ manifest = ModuleManifest(
|
||||
name=CAPABILITY_POLICY_REPORTING_GOVERNANCE,
|
||||
version="1.0.0",
|
||||
),
|
||||
ModuleInterfaceProvider(
|
||||
name=CAPABILITY_POLICY_ACCESS_EXPLANATION_SUBJECTS,
|
||||
version="1.0.0",
|
||||
),
|
||||
ModuleInterfaceProvider(
|
||||
name="policy.datasource_visibility",
|
||||
version="1.0.0",
|
||||
),
|
||||
ModuleInterfaceProvider(name=POLICY_DSAR_CAPABILITY, version="0.1.0"),
|
||||
),
|
||||
route_factory=_route_factory,
|
||||
documentation=(
|
||||
DocumentationTopic(
|
||||
id="policy.datasource-visibility",
|
||||
title="Datasource visibility policy overlays",
|
||||
summary="Tighten Datasources-owned ACL, field, and row visibility through referenced hierarchical policies.",
|
||||
body=(
|
||||
"Datasources owns enforcement and a local visibility baseline. Policy can add system, tenant, group, or user overlays for the global target and an explicitly referenced policy key. Every matching overlay is applied as an additional restriction; it cannot restore a source, field, or row removed by another layer. An unresolved referenced policy, malformed payload, or unavailable decision fails closed. Decision evidence retains policy identifiers, scopes, revisions, and a stable hash but never row values, field values, connector endpoints, or credentials. When Policy is not installed and no external policy reference is configured, Datasources continues to enforce its local scope, ACL, projection, redaction, and row-filter rules."
|
||||
),
|
||||
layer="configured",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("policy_admin", "data_steward", "auditor"),
|
||||
related_modules=("datasources", "access", "audit"),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Richtlinienebenen für die Sichtbarkeit von Datenquellen",
|
||||
"summary": (
|
||||
"Die von Datasources verwaltete Sichtbarkeit für ACLs, Felder und Zeilen durch referenzierte hierarchische "
|
||||
"Richtlinien weiter einschränken."
|
||||
),
|
||||
"body": (
|
||||
"Datasources besitzt die Durchsetzung und eine lokale Sichtbarkeitsgrundlage. Policy kann für das globale Ziel und "
|
||||
"einen ausdrücklich referenzierten Richtlinienschlüssel zusätzliche Ebenen auf System-, Mandanten-, Gruppen- oder "
|
||||
"Benutzerebene liefern. Jede passende Ebene wirkt als weitere Einschränkung und kann keine Quelle, kein Feld und keine "
|
||||
"Zeile wiederherstellen, die eine andere Ebene entfernt hat. Eine nicht auflösbare Referenz, fehlerhafte Nutzdaten oder "
|
||||
"eine nicht verfügbare Entscheidung schließen den Zugriff sicher. Entscheidungsnachweise enthalten Richtlinienkennungen, "
|
||||
"Geltungsbereiche, Revisionen und einen stabilen Hash, aber niemals Zeilen- oder Feldwerte, Connector-Endpunkte oder "
|
||||
"Zugangsdaten. Ist Policy nicht installiert und keine externe Richtlinienreferenz konfiguriert, setzt Datasources seine "
|
||||
"lokalen Regeln für Umfang, ACL, Projektion, Schwärzung und Zeilenfilterung weiterhin durch."
|
||||
),
|
||||
}
|
||||
},
|
||||
order=28,
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.data-subject-requests",
|
||||
title="Policy data-subject requests",
|
||||
summary=(
|
||||
"Export policy-change attribution without disclosing policy documents "
|
||||
"or scoped subject identifiers."
|
||||
),
|
||||
body=(
|
||||
"Policy correlates only an exact account identifier within the active "
|
||||
"tenant and can narrow an already verified search to one override. It "
|
||||
"returns minimized creation and update activity with the policy family, "
|
||||
"scope type, revision, and timestamps. Policy values, target and scope "
|
||||
"keys, scope identifiers, and decision provenance are not included. "
|
||||
"System-scoped overrides are not projected into a tenant request. Policy "
|
||||
"change attribution remains governance evidence and is retained rather "
|
||||
"than automatically erased."
|
||||
),
|
||||
layer="configured",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("user", "policy_admin", "privacy_officer", "auditor"),
|
||||
related_modules=("core", "access", "audit"),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Betroffenenanfragen für Richtlinien",
|
||||
"summary": (
|
||||
"Zuordnung von Richtlinienänderungen exportieren, ohne Richtliniendokumente oder eingegrenzte "
|
||||
"Betroffenenkennungen offenzulegen."
|
||||
),
|
||||
"body": (
|
||||
"Policy gleicht innerhalb des aktiven Mandanten nur eine exakte Kontokennung ab und kann eine bereits verifizierte Suche "
|
||||
"auf eine einzelne Überschreibung begrenzen. Ausgegeben werden minimierte Erstellungs- und Änderungsaktivitäten mit "
|
||||
"Richtlinienfamilie, Bereichstyp, Revision und Zeitpunkten. Richtlinienwerte, Ziel- und Bereichsschlüssel, "
|
||||
"Bereichskennungen und Entscheidungsherkunft sind nicht enthalten. Systemweite Überschreibungen werden nicht in eine "
|
||||
"Mandantenanfrage projiziert. Die Zuordnung von Richtlinienänderungen bleibt Governance-Nachweis und wird aufbewahrt, "
|
||||
"statt automatisch gelöscht zu werden."
|
||||
),
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"help_contexts": ["privacy.data-subject-requests"],
|
||||
"consequence_classes": {
|
||||
"export_policy_attribution": "Returns minimized policy activity for the exact account.",
|
||||
"retain_policy_evidence": "Preserves policy governance accountability.",
|
||||
},
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.access-explanation-subjects",
|
||||
title="Choose subjects for access diagnostics",
|
||||
summary=(
|
||||
"Policy keeps access explanations on the signed-in user unless "
|
||||
"the actor has the selected-user diagnostic permission."
|
||||
),
|
||||
body=(
|
||||
"Files and Campaign use the shared access-explanation picker. "
|
||||
"Without policy:access_explanation:select_user, Access returns "
|
||||
"only the signed-in user and does not disclose tenant-directory "
|
||||
"metadata. Permitted cross-user explanations remain limited to "
|
||||
"the active tenant and are recorded as administrator diagnostics "
|
||||
"in audit evidence. The permission changes diagnostic visibility; "
|
||||
"it does not grant access to the explained resource."
|
||||
),
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("user", "tenant_admin", "policy_admin"),
|
||||
related_modules=("access", "audit", "campaign", "files"),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Zielpersonen für Zugriffsdiagnosen auswählen",
|
||||
"summary": (
|
||||
"Policy beschränkt Zugriffserklärungen auf die angemeldete Person, sofern die handelnde Person nicht die Berechtigung "
|
||||
"zur Diagnose für ausgewählte Benutzende besitzt."
|
||||
),
|
||||
"body": (
|
||||
"Files und Campaign verwenden die gemeinsame Auswahl für Zugriffserklärungen. Ohne "
|
||||
"policy:access_explanation:select_user liefert Access nur die angemeldete Person und legt keine Metadaten des "
|
||||
"Mandantenverzeichnisses offen. Erlaubte Erklärungen für andere Personen bleiben auf den aktiven Mandanten begrenzt und "
|
||||
"werden als administrative Diagnose im Auditnachweis festgehalten. Die Berechtigung erweitert nur die Sichtbarkeit der "
|
||||
"Diagnose; sie gewährt keinen Zugriff auf die erklärte Ressource."
|
||||
),
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"kind": "reference",
|
||||
"help_contexts": ["access.resource-explanation.subject"],
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.view-governance-administration",
|
||||
title="Govern View availability and actions",
|
||||
summary="View policy limits which definitions and surfaces remain available and which View actions lower scopes may perform.",
|
||||
body=(
|
||||
"Documentation books sit immediately beside the visible heading or contextual label for View "
|
||||
"policy and retention settings, not among operational action buttons. Field help remains "
|
||||
"beside its label. "
|
||||
"System, tenant, group, and user View policies form a restrictive hierarchy. Each scope may inherit, allow, or block viewing, selecting, assigning, editing, deriving, and workflow activation. Optional View-ID and surface-ID ceilings are intersected through the hierarchy, so a lower scope cannot restore an item excluded above it. Available, default, and required View assignments remain owned by Views; Policy supplies the action and catalogue ceiling and records provenance and malformed-policy diagnostics."
|
||||
),
|
||||
layer="configured",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("system_admin", "tenant_admin", "policy_admin"),
|
||||
related_modules=("views", "admin", "access"),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "View-Verfügbarkeit und -Aktionen steuern",
|
||||
"summary": (
|
||||
"View-Richtlinien begrenzen verfügbare Definitionen und Oberflächen sowie die View-Aktionen, die untergeordnete "
|
||||
"Ebenen ausführen dürfen."
|
||||
),
|
||||
"body": (
|
||||
"Dokumentationsbücher stehen unmittelbar neben der sichtbaren Überschrift oder "
|
||||
"Kontextbezeichnung für Ansichtsrichtlinien und Aufbewahrungseinstellungen, nicht zwischen "
|
||||
"ausführbaren Aktionsschaltflächen. Feldhilfe bleibt neben der Feldbezeichnung. "
|
||||
"View-Richtlinien auf System-, Mandanten-, Gruppen- und Benutzerebene bilden eine einschränkende Hierarchie. Jede Ebene "
|
||||
"kann Anzeigen, Auswählen, Zuweisen, Bearbeiten, Ableiten und Workflow-Aktivierung erben, erlauben oder blockieren. "
|
||||
"Optionale Obergrenzen für View- und Oberflächenkennungen werden entlang der Hierarchie geschnitten, sodass eine "
|
||||
"untergeordnete Ebene einen darüber ausgeschlossenen Eintrag nicht wiederherstellen kann. Verfügbare, standardmäßige "
|
||||
"und verpflichtende View-Zuweisungen gehören weiterhin Views; Policy liefert die Aktions- und Katalogobergrenze und "
|
||||
"zeichnet Herkunft sowie Diagnosen fehlerhafter Richtlinien auf."
|
||||
),
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"kind": "reference",
|
||||
"help_contexts": [
|
||||
@@ -158,6 +386,66 @@ manifest = ModuleManifest(
|
||||
],
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.function-assignment-delegation-escalation",
|
||||
title="Govern function delegation and review escalation",
|
||||
summary="Policy bounds complete delegation chains and defines explicit target functions for overdue assignment reviews.",
|
||||
body=(
|
||||
"Tenant defaults and function settings may allow delegation, cap its chain depth and validity, and configure a holder, authority, or recipient review timeout with an exact escalation target function. IDM rechecks the complete current chain and the effective Policy at submission, every decision, recovery, and application. A tightened limit invalidates an old route with an explanation. A timeout creates a visible escalated state but never substitutes an approver or completes the review; a current target-function holder must decide explicitly. Malformed or incomplete escalation rules fail closed."
|
||||
),
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("tenant_admin", "policy_admin", "access_admin", "user"),
|
||||
related_modules=(
|
||||
"idm",
|
||||
"organizations",
|
||||
"workflow_engine",
|
||||
"notifications",
|
||||
"audit",
|
||||
),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Funktionsdelegation und Prüfeskalation steuern",
|
||||
"summary": (
|
||||
"Policy begrenzt vollständige Delegationsketten und definiert ausdrückliche Zielfunktionen für überfällige "
|
||||
"Zuweisungsprüfungen."
|
||||
),
|
||||
"body": (
|
||||
"Mandantenstandards und Funktionseinstellungen können Delegation erlauben, Kettentiefe und Gültigkeit begrenzen und "
|
||||
"eine Prüfungsfrist für Inhaber, verantwortliche Stelle oder empfangende Person mit exakter Eskalations-Zielfunktion "
|
||||
"festlegen. IDM prüft die vollständige aktuelle Kette und die wirksame Policy bei Einreichung, jeder Entscheidung, "
|
||||
"Wiederherstellung und Anwendung erneut. Eine verschärfte Grenze verwirft einen älteren Weg mit Begründung. Eine "
|
||||
"Fristüberschreitung erzeugt einen sichtbaren eskalierten Zustand, ersetzt aber keine freigebende Person und schließt "
|
||||
"die Prüfung nicht ab; eine aktuelle Inhaberin oder ein aktueller Inhaber der Zielfunktion muss ausdrücklich entscheiden. "
|
||||
"Fehlerhafte oder unvollständige Eskalationsregeln schließen sicher."
|
||||
),
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"kind": "reference",
|
||||
"help_contexts": [
|
||||
"idm.field.delegation-ceilings",
|
||||
"idm.field.escalation",
|
||||
],
|
||||
"fields": [
|
||||
{
|
||||
"key": "delegation_allowed",
|
||||
"consequence": "Allows governed derived assignments only when Organizations also marks the function delegable.",
|
||||
},
|
||||
{
|
||||
"key": "maximum_delegation_depth",
|
||||
"consequence": "Rejects longer current chains, including chains accepted before a tighter limit.",
|
||||
},
|
||||
{
|
||||
"key": "maximum_delegated_validity_days",
|
||||
"consequence": "Caps each delegated validity window in addition to its source window.",
|
||||
},
|
||||
{
|
||||
"key": "escalation.<step>",
|
||||
"consequence": "Pins a target function and deadline without granting or substituting approval.",
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.effective-decisions-and-provenance",
|
||||
title="Understand effective policy decisions",
|
||||
@@ -165,29 +453,213 @@ manifest = ModuleManifest(
|
||||
body="A lower scope may narrow an inherited ceiling but cannot silently loosen a stronger system or tenant rule. Consuming modules remain responsible for enforcing the returned decision and displaying its reason. Malformed explicit policy fails closed for the affected governed action rather than being treated as absent.",
|
||||
documentation_types=("user",),
|
||||
audience=("user", "tenant_admin", "policy_admin"),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Wirksame Richtlinienentscheidungen verstehen",
|
||||
"summary": (
|
||||
"Richtlinienentscheidungen erläutern, ob eine Aktion erlaubt, begrenzt, geerbt oder nicht verfügbar ist, und nennen "
|
||||
"die Quellen des Ergebnisses."
|
||||
),
|
||||
"body": (
|
||||
"Eine untergeordnete Ebene darf eine geerbte Obergrenze verschärfen, aber eine stärkere System- oder Mandantenregel "
|
||||
"nicht stillschweigend lockern. Die nutzenden Module bleiben dafür verantwortlich, die gelieferte Entscheidung "
|
||||
"durchzusetzen und ihre Begründung anzuzeigen. Eine ausdrücklich konfigurierte fehlerhafte Richtlinie schließt die "
|
||||
"betroffene gesteuerte Aktion sicher, statt als nicht vorhanden zu gelten."
|
||||
),
|
||||
}
|
||||
},
|
||||
metadata={"kind": "reference"},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.impact-preview",
|
||||
title="Preview policy impact before saving",
|
||||
summary=(
|
||||
"Compare the current and proposed effective policy over explicit, "
|
||||
"bounded provider populations without persisting the proposal."
|
||||
),
|
||||
body=(
|
||||
"The Policy impact preview groups newly allowed, newly denied, "
|
||||
"unchanged, and indeterminate effects and retains rule, source, and "
|
||||
"scope provenance. Callers must select one to ten provider populations "
|
||||
"and a limit of at most 500 subjects per population; Policy never scans "
|
||||
"the platform implicitly. Population evidence says whether results are "
|
||||
"complete, sampled, truncated, or unavailable. Policy-read authority "
|
||||
"may inspect aggregate counts, while policy:impact:details controls "
|
||||
"resource identifiers and labels. Every preview is audited using its "
|
||||
"proposal hash and bounded counts. System-wide View-policy commits "
|
||||
"require authentication within the last 15 minutes and retain their "
|
||||
"existing commit audit and configuration-approval evidence. Optional "
|
||||
"modules contribute subjects through the Core provider contract; Policy "
|
||||
"does not import their models or services."
|
||||
),
|
||||
documentation_types=("admin",),
|
||||
audience=("system_admin", "tenant_admin", "policy_admin"),
|
||||
related_modules=("admin", "audit", "views"),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Richtlinienauswirkung vor dem Speichern prüfen",
|
||||
"summary": (
|
||||
"Aktuelle und vorgeschlagene wirksame Richtlinie über ausdrücklich ausgewählte, begrenzte Provider-Populationen "
|
||||
"vergleichen, ohne den Vorschlag zu speichern."
|
||||
),
|
||||
"body": (
|
||||
"Die Policy-Auswirkungsvorschau gruppiert neu erlaubte, neu verweigerte, unveränderte und unbestimmte Wirkungen und "
|
||||
"hält Regel-, Quellen- und Bereichsherkunft fest. Aufrufende müssen eine bis zehn Provider-Populationen und je Population "
|
||||
"eine Grenze von höchstens 500 Subjekten wählen; Policy durchsucht die Plattform niemals implizit. Der "
|
||||
"Populationsnachweis kennzeichnet Ergebnisse als vollständig, stichprobenartig, abgeschnitten oder nicht verfügbar. "
|
||||
"Mit Leseberechtigung für Richtlinien sind aggregierte Anzahlen sichtbar, während policy:impact:details "
|
||||
"Ressourcenkennungen und -bezeichnungen steuert. Jede Vorschau wird mit Vorschlagshash und begrenzten Anzahlen auditiert. "
|
||||
"Systemweite View-Richtlinienänderungen verlangen eine Authentifizierung innerhalb der letzten 15 Minuten und behalten "
|
||||
"ihre vorhandenen Audit- und Konfigurationsfreigabenachweise. Optionale Module liefern Subjekte über den Core-Providervertrag; "
|
||||
"Policy importiert weder ihre Modelle noch ihre Dienste."
|
||||
),
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"kind": "workflow",
|
||||
"route": "/admin?section=system-view-policy",
|
||||
"screen": "View policy impact preview",
|
||||
"help_contexts": [
|
||||
"policy.impact-preview",
|
||||
"policy.impact-preview.action.preview",
|
||||
"policy.impact-preview.results",
|
||||
],
|
||||
"api": {
|
||||
"preview": "/api/v1/admin/policy-impact/preview",
|
||||
"maximum_populations": 10,
|
||||
"maximum_subjects_per_population": 500,
|
||||
},
|
||||
"steps": [
|
||||
"Select an explicit impact provider population and bounded limit.",
|
||||
"Preview and inspect outcome counts, coverage state, and provenance.",
|
||||
"Reauthenticate when a system-wide change is classified as high impact.",
|
||||
"Save only after the preview matches the current dirty draft.",
|
||||
],
|
||||
"limitations": [
|
||||
"Unavailable optional providers are explained and are never treated as zero impact.",
|
||||
"Resource details are hidden without policy:impact:details.",
|
||||
],
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.campaign-archive-encryption",
|
||||
title="Govern Campaign archive encryption",
|
||||
summary="Restrict password-protected Campaign ZIP formats and password-delivery channels through an explainable hierarchy.",
|
||||
body=(
|
||||
"The secure baseline permits AES only. An authorized policy administrator may explicitly permit legacy ZipCrypto at system scope, after which tenant, owner group or user, and campaign rules may only narrow the inherited methods. The same intersection controls the separate channel used to convey a password. Policy records the complete source path and a stable policy hash; malformed configuration fails closed. Policy changes never rewrite old build evidence, while Campaign rejects a queued or sent build whose effective policy is now more restrictive."
|
||||
" To configure the exception, open Administration → SYSTEM → Campaign archive encryption, enable Legacy ZipCrypto, and Save. The system methods and channels remain editable before any explicit override exists; opening default settings alone does not create an override or unsaved changes. Lower scopes inherit until their inheritance switch is disabled and may select only parent-permitted methods and channels. Campaign Settings, Policies, and Attachments link authorized readers to the system and tenant settings and let them reload effective policy. Reading requires admin:policies:read. Saving the global system ceiling requires both system:settings:write and admin:policies:write; lower-scope saves require admin:policies:write. Core's configuration safety catalog validates this registered setting and retains audited before/after and rollback choices; only the two validated format/channel enum lists are exempted from password-name redaction, never real secrets or unknown values. Using the exception additionally requires Campaign's dedicated legacy-encryption permission and a weak-encryption acknowledgment with a reason of at least 10 characters. Saving policy does not send mail or silently change any archive's selected method."
|
||||
),
|
||||
documentation_types=("admin", "user"),
|
||||
audience=(
|
||||
"system_admin",
|
||||
"tenant_admin",
|
||||
"policy_admin",
|
||||
"campaign_manager",
|
||||
),
|
||||
related_modules=("campaign", "audit", "access"),
|
||||
links=(
|
||||
DocumentationLink(
|
||||
label="System Campaign archive encryption",
|
||||
href="/admin?section=system-campaign-archive-encryption",
|
||||
kind="runtime",
|
||||
),
|
||||
DocumentationLink(
|
||||
label="Tenant Campaign archive encryption",
|
||||
href="/admin?section=tenant-campaign-archive-encryption",
|
||||
kind="runtime",
|
||||
),
|
||||
),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Verschlüsselung von Campaign-Archiven steuern",
|
||||
"summary": (
|
||||
"Formate passwortgeschützter Campaign-ZIP-Dateien und Übertragungskanäle für Passwörter über eine erklärbare "
|
||||
"Hierarchie einschränken."
|
||||
),
|
||||
"body": (
|
||||
"Die sichere Grundlage erlaubt nur AES. Eine berechtigte Richtlinienadministration kann das veraltete ZipCrypto auf "
|
||||
"Systemebene ausdrücklich zulassen; Regeln auf Mandanten-, Eigentümergruppen-, Benutzer- und Campaign-Ebene dürfen die "
|
||||
"geerbten Methoden anschließend nur weiter einschränken. Derselbe Schnitt steuert getrennt den Kanal zur Übermittlung "
|
||||
"eines Passworts. Policy zeichnet den vollständigen Quellenpfad und einen stabilen Richtlinienhash auf; fehlerhafte "
|
||||
"Konfiguration schließt sicher. Richtlinienänderungen schreiben alte Erstellungsnachweise niemals um, während Campaign "
|
||||
"einen eingereihten oder versandten Build zurückweist, wenn dessen wirksame Richtlinie inzwischen strenger ist."
|
||||
" Öffnen Sie zur Konfiguration Administration → SYSTEM → Campaign archive encryption, aktivieren Sie Legacy ZipCrypto und speichern Sie. "
|
||||
"Methoden und Kanäle auf Systemebene sind schon vor der ersten ausdrücklichen Ausnahme bearbeitbar; das bloße Öffnen erzeugt weder eine Ausnahme noch ungespeicherte Änderungen. "
|
||||
"Untergeordnete Ebenen erben bis zum Abschalten ihres Vererbungsschalters und dürfen nur übergeordnet erlaubte Methoden und Kanäle wählen. "
|
||||
"Kampagneneinstellungen, Richtlinien und Anhänge verlinken berechtigte Lesende auf System- und Mandantenkonfiguration und erlauben das Neuladen der wirksamen Richtlinie. "
|
||||
"Lesen erfordert admin:policies:read. Das Speichern der globalen Systemgrenze benötigt system:settings:write und admin:policies:write gemeinsam; untergeordnete Ebenen benötigen admin:policies:write. "
|
||||
"Der zentrale Konfigurations-Sicherheitskatalog prüft dieses registrierte Feld und bewahrt auditierte Vorher-/Nachherwerte sowie Rücknahmewerte. Nur die beiden validierten Format-/Kanal-Enumlisten bleiben trotz Passwortbegriff im Feldnamen sichtbar, niemals echte Geheimnisse oder unbekannte Werte. "
|
||||
"Die Nutzung benötigt zusätzlich Campaigns gesonderte Legacy-Verschlüsselungsberechtigung und die Bestätigung schwacher Verschlüsselung mit mindestens 10 Zeichen Begründung. "
|
||||
"Das Speichern einer Richtlinie versendet keine E-Mail und ändert keine gewählte Archivmethode stillschweigend."
|
||||
),
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"kind": "reference",
|
||||
"help_contexts": [
|
||||
"policy.campaign-archive-encryption",
|
||||
"campaign.archive-encryption",
|
||||
],
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.hierarchy-overrides-and-retention",
|
||||
title="Administer policy hierarchy and overrides",
|
||||
summary="Policy evaluates versioned system, tenant, group, and user rules for retention and module-owned governed actions.",
|
||||
body="Administrators can simulate effective retention before saving a lower-level change. Explicit overrides retain source and provenance information and are evaluated through typed capabilities for definitions, Views, function assignments, distribution channels, scheduling privacy, cross-module reporting, and retention. Templates and inherited definitions keep their upstream ceilings when reused or derived.",
|
||||
body=(
|
||||
"Documentation books sit immediately beside the visible heading or contextual label for View "
|
||||
"policy and retention settings, not among operational action buttons. Field help remains "
|
||||
"beside its label. "
|
||||
"Retention fields govern separate data classes: raw campaign JSON, generated EML artifacts, stored report details, mock-mailbox records, and audit details. A blank system day limit keeps the class indefinitely; a blank lower-scope value inherits its parent. Lower scopes may only shorten an allowed limit or reduce audit detail. Disabling raw campaign JSON makes it immediately eligible for redaction when retention is applied. Audit detail level controls how new audit details are recorded, while audit-detail retention redacts eligible historical detail but preserves the audit record and a bounded retention marker. The lower-level switch controls whether child scopes may narrow that specific field. Inspect the effective value and source path before saving."
|
||||
),
|
||||
documentation_types=("admin",),
|
||||
audience=("policy_admin", "tenant_admin", "system_admin"),
|
||||
related_modules=(
|
||||
"audit",
|
||||
"campaign",
|
||||
"dataflow",
|
||||
"mail",
|
||||
"reporting",
|
||||
"workflow_engine",
|
||||
"views",
|
||||
"idm",
|
||||
"dist_lists",
|
||||
"scheduling",
|
||||
"reporting",
|
||||
),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Richtlinienhierarchie und Aufbewahrung verwalten",
|
||||
"summary": "Policy wertet versionierte System-, Mandanten-, Gruppen- und Benutzerregeln für Aufbewahrung sowie modulbezogene Steuerungsentscheidungen aus.",
|
||||
"body": "Dokumentationsbücher stehen unmittelbar neben der sichtbaren Überschrift oder "
|
||||
"Kontextbezeichnung für Ansichtsrichtlinien und Aufbewahrungseinstellungen, nicht zwischen "
|
||||
"ausführbaren Aktionsschaltflächen. Feldhilfe bleibt neben der Feldbezeichnung. "
|
||||
"Die Felder steuern getrennte Datenklassen: Kampagnen-Rohdaten im JSON-Format, erzeugte EML-Dateien, gespeicherte Berichtsdetails, Einträge im Testpostfach und Auditdetails. Ein leeres Tageslimit auf Systemebene bedeutet unbegrenzte Aufbewahrung; auf tieferen Ebenen wird der Elternwert geerbt. Tiefere Ebenen dürfen ein erlaubtes Limit nur verkürzen oder Auditdetails weiter reduzieren. Wenn die Speicherung von Kampagnen-Rohdaten deaktiviert wird, werden diese bei der nächsten Ausführung sofort zur Schwärzung vorgemerkt. Die Auditdetailstufe steuert neue Auditdetails; die Aufbewahrungsfrist für Auditdetails schwärzt historische Details, erhält aber den Auditdatensatz und einen begrenzten Aufbewahrungsnachweis. Der Schalter für tiefere Ebenen bestimmt, ob Kindebenen genau dieses Feld weiter einschränken dürfen. Prüfen Sie vor dem Speichern den effektiven Wert und seinen Quellenpfad.",
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"kind": "workflow",
|
||||
"route": "/admin?section=system-retention",
|
||||
"screen": "Retention administration",
|
||||
"help_contexts": ["policy.retention", "privacy.retention"],
|
||||
"help_contexts": [
|
||||
"policy.retention",
|
||||
"privacy.retention",
|
||||
"policy.admin.system-retention",
|
||||
"policy.admin.tenant-retention",
|
||||
"policy.admin.group-retention",
|
||||
"policy.admin.user-retention",
|
||||
"policy.retention.target",
|
||||
"policy.retention.action.reload-targets",
|
||||
"policy.retention.action.reload",
|
||||
"policy.retention.action.save",
|
||||
"policy.retention.field.store-raw-campaign-json",
|
||||
"policy.retention.field.raw-campaign-json-retention-days",
|
||||
"policy.retention.field.generated-eml-retention-days",
|
||||
"policy.retention.field.stored-report-detail-retention-days",
|
||||
"policy.retention.field.mock-mailbox-retention-days",
|
||||
"policy.retention.field.audit-detail-retention-days",
|
||||
"policy.retention.field.audit-detail-level",
|
||||
"policy.retention.field.allow-lower-level-limits",
|
||||
],
|
||||
"prerequisites": [
|
||||
"Policy and Access are enabled.",
|
||||
"The actor may read policy settings at the selected scope.",
|
||||
@@ -202,6 +674,53 @@ manifest = ModuleManifest(
|
||||
"verification": "Reload the policy, confirm its source path, and compare the dry-run or applied outcome table with audit evidence.",
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="policy.retention-execution-and-recovery",
|
||||
title="Preview and apply retention safely",
|
||||
summary="A dry run reports eligible records without changing them; applying retention redacts details and deletes eligible generated artifacts.",
|
||||
body=(
|
||||
"Save and reload the intended system policy before execution. Run a dry run first and review every reported data class and count. Apply retention only when those counts match the approved policy and recovery evidence is current. An applied run redacts eligible raw campaign JSON, stored report summaries, reporting details, and audit details; it deletes eligible generated EML and mock-mailbox artifacts. The application cannot restore deleted content. Generated EML deletion uses the Campaign recovery boundary, while the applied run and bounded outcome counts remain in audit evidence. Treat provider failures, recovery blocks, missing artifacts, or unexpected counts as a stop condition and investigate before another run."
|
||||
),
|
||||
documentation_types=("admin",),
|
||||
audience=("system_admin", "policy_admin", "privacy_officer"),
|
||||
related_modules=("audit", "campaign", "mail", "reporting"),
|
||||
translations={
|
||||
"de": {
|
||||
"title": "Aufbewahrung sicher prüfen und anwenden",
|
||||
"summary": "Ein Probelauf meldet betroffene Datensätze ohne Änderung; die Anwendung schwärzt Details und löscht vorgemerkte erzeugte Artefakte.",
|
||||
"body": "Speichern und laden Sie die beabsichtigte Systemrichtlinie vor der Ausführung neu. Führen Sie zuerst einen Probelauf aus und prüfen Sie jede Datenklasse und Anzahl. Wenden Sie die Aufbewahrung nur an, wenn die Zahlen der genehmigten Richtlinie entsprechen und die Wiederherstellungsnachweise aktuell sind. Ein angewendeter Lauf schwärzt vorgemerkte Kampagnen-Rohdaten, gespeicherte Berichtsdetails und Auditdetails; vorgemerkte EML-Dateien und Testpostfach-Artefakte werden gelöscht. Die Anwendung kann gelöschte Inhalte nicht wiederherstellen. Die EML-Löschung verwendet die Wiederherstellungsgrenze des Campaign-Moduls; der Lauf und begrenzte Ergebniszahlen bleiben als Auditnachweis erhalten. Anbieterfehler, blockierte Wiederherstellung, fehlende Artefakte oder unerwartete Zahlen sind ein Abbruchgrund und müssen vor einem weiteren Lauf untersucht werden.",
|
||||
}
|
||||
},
|
||||
metadata={
|
||||
"kind": "workflow",
|
||||
"route": "/admin?section=system-retention",
|
||||
"screen": "Retention execution",
|
||||
"help_contexts": [
|
||||
"policy.retention.execution",
|
||||
"policy.retention.action.dry-run",
|
||||
"policy.retention.action.apply",
|
||||
"policy.retention.confirm-apply",
|
||||
"policy.retention.outcome",
|
||||
],
|
||||
"prerequisites": [
|
||||
"The actor may write system settings.",
|
||||
"The intended system retention policy is saved and reloaded.",
|
||||
"Recovery evidence is current for generated artifacts.",
|
||||
],
|
||||
"steps": [
|
||||
"Run a dry run and review each data class and outcome count.",
|
||||
"Stop if providers fail, recovery is blocked, or counts are unexpected.",
|
||||
"Confirm the destructive run only after policy and recovery review.",
|
||||
"Compare the applied outcome with audit evidence.",
|
||||
],
|
||||
"outcome": "Eligible details are redacted and eligible generated artifacts are deleted with bounded outcome and audit evidence.",
|
||||
"limitations": [
|
||||
"The application cannot restore deleted EML or mock-mailbox content.",
|
||||
"A dry run is a preview and does not reserve the reported set against concurrent changes.",
|
||||
],
|
||||
"verification": "Review the latest outcome, provider failure and recovery counts, then locate the retention_policy.run audit record.",
|
||||
},
|
||||
),
|
||||
),
|
||||
migration_spec=MigrationSpec(
|
||||
module_id="policy",
|
||||
@@ -255,6 +774,34 @@ manifest = ModuleManifest(
|
||||
label="User View policy",
|
||||
order=70,
|
||||
),
|
||||
ViewSurface(
|
||||
id="policy.admin.system-campaign-archive-encryption",
|
||||
module_id="policy",
|
||||
kind="section",
|
||||
label="System Campaign archive encryption",
|
||||
order=75,
|
||||
),
|
||||
ViewSurface(
|
||||
id="policy.admin.tenant-campaign-archive-encryption",
|
||||
module_id="policy",
|
||||
kind="section",
|
||||
label="Tenant Campaign archive encryption",
|
||||
order=75,
|
||||
),
|
||||
ViewSurface(
|
||||
id="policy.admin.group-campaign-archive-encryption",
|
||||
module_id="policy",
|
||||
kind="section",
|
||||
label="Group Campaign archive encryption",
|
||||
order=75,
|
||||
),
|
||||
ViewSurface(
|
||||
id="policy.admin.user-campaign-archive-encryption",
|
||||
module_id="policy",
|
||||
kind="section",
|
||||
label="User Campaign archive encryption",
|
||||
order=75,
|
||||
),
|
||||
ViewSurface(
|
||||
id="policy.admin.system-retention",
|
||||
module_id="policy",
|
||||
@@ -293,10 +840,26 @@ manifest = ModuleManifest(
|
||||
),
|
||||
CAPABILITY_POLICY_DISTRIBUTION_CHANNELS: _distribution_channel_policy,
|
||||
CAPABILITY_POLICY_REPORTING_GOVERNANCE: _reporting_governance_policy,
|
||||
CAPABILITY_POLICY_ACCESS_EXPLANATION_SUBJECTS: (
|
||||
_access_explanation_subject_policy
|
||||
),
|
||||
CAPABILITY_POLICY_PRIVACY_RETENTION: _privacy_retention_service,
|
||||
CAPABILITY_POLICY_SCHEDULING_PARTICIPANT_PRIVACY: _scheduling_participant_privacy_policy,
|
||||
CAPABILITY_POLICY_CAMPAIGN_ARCHIVE_ENCRYPTION: _campaign_archive_encryption_policy,
|
||||
CAPABILITY_POLICY_DATASOURCE_VISIBILITY: _datasource_visibility_policy,
|
||||
POLICY_DSAR_CAPABILITY: _dsar_provider,
|
||||
},
|
||||
capability_documentation={
|
||||
CAPABILITY_POLICY_ACCESS_EXPLANATION_SUBJECTS: CapabilityDocumentation(
|
||||
label="Access-explanation subject policy",
|
||||
summary=(
|
||||
"Limits access explanations to the current user or permits "
|
||||
"audited selected-user administrator diagnostics."
|
||||
),
|
||||
contract_version="1.0",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("tenant_admin", "policy_admin"),
|
||||
),
|
||||
CAPABILITY_POLICY_REPORTING_GOVERNANCE: CapabilityDocumentation(
|
||||
label="Reporting privacy governance",
|
||||
summary=(
|
||||
@@ -307,6 +870,27 @@ manifest = ModuleManifest(
|
||||
documentation_types=("admin",),
|
||||
audience=("policy_admin", "privacy_officer", "system_admin"),
|
||||
),
|
||||
CAPABILITY_POLICY_CAMPAIGN_ARCHIVE_ENCRYPTION: CapabilityDocumentation(
|
||||
label="Campaign archive-encryption policy",
|
||||
summary="Returns the restrictive format and password-delivery ceiling with complete provenance and a stable hash.",
|
||||
contract_version="1.0",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("policy_admin", "campaign_manager"),
|
||||
),
|
||||
CAPABILITY_POLICY_DATASOURCE_VISIBILITY: CapabilityDocumentation(
|
||||
label="Datasource visibility policy",
|
||||
summary="Returns restrictive referenced policy overlays without reading or exposing datasource content.",
|
||||
contract_version="1.0",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("policy_admin", "data_steward", "auditor"),
|
||||
),
|
||||
POLICY_DSAR_CAPABILITY: CapabilityDocumentation(
|
||||
label="Policy data-subject request provider",
|
||||
summary=(
|
||||
"Exports minimized tenant policy-change attribution without policy payloads."
|
||||
),
|
||||
contract_version="0.1.0",
|
||||
),
|
||||
},
|
||||
architecture=declared_module_architecture(
|
||||
layer="governance_accountability",
|
||||
@@ -321,6 +905,7 @@ manifest = ModuleManifest(
|
||||
"policy definition",
|
||||
"policy override",
|
||||
"policy decision provenance",
|
||||
"bounded policy impact preview",
|
||||
),
|
||||
non_owned_concepts=("application permission", "domain record", "audit record"),
|
||||
recovery_docs=("docs/POLICY_DECISION_PROVENANCE.md",),
|
||||
@@ -329,5 +914,10 @@ manifest = ModuleManifest(
|
||||
)
|
||||
|
||||
|
||||
manifest = with_documentation_structured_translations(
|
||||
manifest, locale="de", translations=GERMAN_STRUCTURED_TRANSLATIONS
|
||||
)
|
||||
|
||||
|
||||
def get_manifest() -> ModuleManifest:
|
||||
return manifest
|
||||
|
||||
@@ -9,8 +9,16 @@ from sqlalchemy.orm import Session
|
||||
from govoplan_policy.backend.db.models import PolicyOverride
|
||||
|
||||
|
||||
POLICY_SCOPE_TYPES = frozenset({"system", "tenant", "group", "user"})
|
||||
POLICY_FAMILIES = frozenset({"definition", "distribution_channels", "view"})
|
||||
POLICY_SCOPE_TYPES = frozenset({"system", "tenant", "group", "user", "campaign"})
|
||||
POLICY_FAMILIES = frozenset(
|
||||
{
|
||||
"campaign_archive_encryption",
|
||||
"datasource_visibility",
|
||||
"definition",
|
||||
"distribution_channels",
|
||||
"view",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class PolicyOverrideError(ValueError):
|
||||
@@ -22,7 +30,7 @@ def normalize_policy_target(policy_family: str, target_key: str) -> tuple[str, s
|
||||
target = target_key.strip().casefold()
|
||||
if family not in POLICY_FAMILIES:
|
||||
raise PolicyOverrideError(
|
||||
"Policy family must be definition, distribution_channels, or view"
|
||||
"Policy family must be campaign_archive_encryption, datasource_visibility, definition, distribution_channels, or view"
|
||||
)
|
||||
if not target or len(target) > 120:
|
||||
raise PolicyOverrideError("Policy target must contain 1 to 120 characters")
|
||||
@@ -40,7 +48,9 @@ def normalize_policy_scope(
|
||||
clean_scope = scope_type.strip().casefold()
|
||||
clean_id = str(scope_id or "").strip() or None
|
||||
if clean_scope not in POLICY_SCOPE_TYPES:
|
||||
raise PolicyOverrideError("Policy scope must be system, tenant, group, or user")
|
||||
raise PolicyOverrideError(
|
||||
"Policy scope must be system, tenant, group, user, or campaign"
|
||||
)
|
||||
if clean_scope == "system":
|
||||
if clean_id is not None:
|
||||
raise PolicyOverrideError("System policy cannot declare a scope ID")
|
||||
@@ -142,6 +152,7 @@ def resolution_policy_overrides(
|
||||
tenant_id: str,
|
||||
group_ids: Iterable[str] = (),
|
||||
user_ids: Iterable[str] = (),
|
||||
campaign_ids: Iterable[str] = (),
|
||||
) -> tuple[PolicyOverride, ...]:
|
||||
family = policy_family.strip().casefold()
|
||||
targets = tuple(
|
||||
@@ -151,6 +162,9 @@ def resolution_policy_overrides(
|
||||
)
|
||||
groups = tuple(sorted({str(value) for value in group_ids if str(value)}))
|
||||
users = tuple(sorted({str(value) for value in user_ids if str(value)}))
|
||||
campaigns = tuple(
|
||||
sorted({str(value) for value in campaign_ids if str(value)})
|
||||
)
|
||||
scope_filters = [
|
||||
PolicyOverride.scope_key == "system",
|
||||
PolicyOverride.scope_key == f"tenant:{tenant_id}",
|
||||
@@ -167,6 +181,15 @@ def resolution_policy_overrides(
|
||||
[f"user:{tenant_id}:{user_id}" for user_id in users]
|
||||
)
|
||||
)
|
||||
if campaigns:
|
||||
scope_filters.append(
|
||||
PolicyOverride.scope_key.in_(
|
||||
[
|
||||
f"campaign:{tenant_id}:{campaign_id}"
|
||||
for campaign_id in campaigns
|
||||
]
|
||||
)
|
||||
)
|
||||
rows = (
|
||||
session.query(PolicyOverride)
|
||||
.filter(
|
||||
@@ -177,7 +200,13 @@ def resolution_policy_overrides(
|
||||
.all()
|
||||
)
|
||||
target_order = {target: index for index, target in enumerate(targets)}
|
||||
scope_order = {"system": 0, "tenant": 1, "group": 2, "user": 3}
|
||||
scope_order = {
|
||||
"system": 0,
|
||||
"tenant": 1,
|
||||
"group": 2,
|
||||
"user": 2,
|
||||
"campaign": 3,
|
||||
}
|
||||
return tuple(
|
||||
sorted(
|
||||
rows,
|
||||
|
||||
@@ -85,6 +85,43 @@ def save_view_policy(
|
||||
policy: object,
|
||||
actor_id: str | None,
|
||||
) -> ViewPolicyState:
|
||||
clean_policy, _before = validate_view_policy_change(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
policy=policy,
|
||||
)
|
||||
set_policy_override(
|
||||
session,
|
||||
policy_family="view",
|
||||
target_key="*",
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
policy={
|
||||
key: list(value) if isinstance(value, tuple) else value
|
||||
for key, value in clean_policy.items()
|
||||
},
|
||||
actor_id=actor_id,
|
||||
)
|
||||
_clear_resolution_cache(session)
|
||||
return view_policy_state(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
)
|
||||
|
||||
|
||||
def validate_view_policy_change(
|
||||
session: Session,
|
||||
*,
|
||||
tenant_id: str,
|
||||
scope_type: str,
|
||||
scope_id: str | None,
|
||||
policy: object,
|
||||
) -> tuple[dict[str, bool | tuple[str, ...]], ViewPolicyState]:
|
||||
clean_policy, malformed = validate_view_policy(policy)
|
||||
if malformed:
|
||||
raise ViewPolicyError("View policy fields have invalid names or values")
|
||||
@@ -115,26 +152,7 @@ def save_view_policy(
|
||||
"Lower-scope View policy cannot broaden parent restrictions: "
|
||||
+ ", ".join(broadened)
|
||||
)
|
||||
set_policy_override(
|
||||
session,
|
||||
policy_family="view",
|
||||
target_key="*",
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
policy={
|
||||
key: list(value) if isinstance(value, tuple) else value
|
||||
for key, value in clean_policy.items()
|
||||
},
|
||||
actor_id=actor_id,
|
||||
)
|
||||
_clear_resolution_cache(session)
|
||||
return view_policy_state(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
)
|
||||
return clean_policy, before
|
||||
|
||||
|
||||
def remove_view_policy(
|
||||
@@ -239,6 +257,7 @@ __all__ = [
|
||||
"ViewPolicyState",
|
||||
"remove_view_policy",
|
||||
"save_view_policy",
|
||||
"validate_view_policy_change",
|
||||
"view_policy_response_payload",
|
||||
"view_policy_state",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from govoplan_core.core.access import PrincipalRef
|
||||
from govoplan_policy.backend.access_explanation_subjects import (
|
||||
ACCESS_EXPLANATION_SUBJECT_SCOPE,
|
||||
AccessExplanationSubjectPolicyProvider,
|
||||
)
|
||||
|
||||
|
||||
class AccessExplanationSubjectPolicyTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.provider = AccessExplanationSubjectPolicyProvider()
|
||||
|
||||
def test_defaults_to_current_user_without_permission(self) -> None:
|
||||
decision = self.provider.decide_subject_selection(
|
||||
object(),
|
||||
PrincipalRef(
|
||||
account_id="account-1",
|
||||
membership_id="user-1",
|
||||
tenant_id="tenant-1",
|
||||
),
|
||||
tenant_id="tenant-1",
|
||||
)
|
||||
|
||||
self.assertFalse(decision.allow_other_users)
|
||||
self.assertEqual(ACCESS_EXPLANATION_SUBJECT_SCOPE, decision.required_scope)
|
||||
self.assertEqual("current_user", decision.provenance["mode"])
|
||||
|
||||
def test_permission_enables_cross_user_diagnostics(self) -> None:
|
||||
decision = self.provider.decide_subject_selection(
|
||||
object(),
|
||||
PrincipalRef(
|
||||
account_id="account-1",
|
||||
membership_id="user-1",
|
||||
tenant_id="tenant-1",
|
||||
scopes=frozenset({ACCESS_EXPLANATION_SUBJECT_SCOPE}),
|
||||
),
|
||||
tenant_id="tenant-1",
|
||||
)
|
||||
|
||||
self.assertTrue(decision.allow_other_users)
|
||||
self.assertEqual("cross_user", decision.provenance["mode"])
|
||||
|
||||
def test_never_crosses_the_active_tenant(self) -> None:
|
||||
decision = self.provider.decide_subject_selection(
|
||||
object(),
|
||||
PrincipalRef(
|
||||
account_id="account-1",
|
||||
membership_id="user-1",
|
||||
tenant_id="tenant-1",
|
||||
scopes=frozenset({ACCESS_EXPLANATION_SUBJECT_SCOPE}),
|
||||
),
|
||||
tenant_id="tenant-2",
|
||||
)
|
||||
|
||||
self.assertFalse(decision.allow_other_users)
|
||||
self.assertEqual("policy.tenant_boundary", decision.source)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,192 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from govoplan_core.admin.models import SystemSettings
|
||||
from govoplan_core.auth import ApiPrincipal, get_api_principal
|
||||
from govoplan_core.core.access import PrincipalRef
|
||||
from govoplan_core.core.change_sequence import ChangeSequenceEntry
|
||||
from govoplan_core.core.configuration_control import (
|
||||
configuration_control_snapshot,
|
||||
create_configuration_change_request,
|
||||
)
|
||||
from govoplan_core.core.configuration_safety import (
|
||||
classify_configuration_field,
|
||||
plan_configuration_change,
|
||||
)
|
||||
from govoplan_core.db.session import get_session
|
||||
from govoplan_policy.backend.api.v1.routes import router
|
||||
from govoplan_policy.backend.db.models import PolicyOverride
|
||||
|
||||
|
||||
class CampaignArchiveEncryptionApiTests(unittest.TestCase):
|
||||
"""Exercise the real HTTP route, safety catalog, persistence, and history."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.engine = create_engine(
|
||||
"sqlite:///:memory:",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
self.addCleanup(self.engine.dispose)
|
||||
for table in (SystemSettings.__table__, PolicyOverride.__table__, ChangeSequenceEntry.__table__):
|
||||
table.create(self.engine)
|
||||
self.principal = self._principal("admin:policies:read", "admin:policies:write", "system:settings:write")
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api/v1")
|
||||
|
||||
def session_dependency():
|
||||
with Session(self.engine) as session:
|
||||
yield session
|
||||
|
||||
app.dependency_overrides[get_session] = session_dependency
|
||||
app.dependency_overrides[get_api_principal] = lambda: self.principal
|
||||
self.client = TestClient(app)
|
||||
self.addCleanup(self.client.close)
|
||||
|
||||
@staticmethod
|
||||
def _principal(*scopes: str) -> ApiPrincipal:
|
||||
return ApiPrincipal(
|
||||
principal=PrincipalRef(
|
||||
account_id="admin-account", membership_id="admin-user", tenant_id="tenant-1",
|
||||
scopes=frozenset(scopes),
|
||||
),
|
||||
account=SimpleNamespace(id="admin-account"),
|
||||
user=SimpleNamespace(id="admin-user"),
|
||||
)
|
||||
|
||||
def test_system_legacy_opt_in_passes_real_catalog_and_retains_history(self) -> None:
|
||||
path = "/api/v1/admin/campaign-archive-encryption/policies/system"
|
||||
field = classify_configuration_field("campaign_archive_encryption_policy")
|
||||
self.assertIsNotNone(field)
|
||||
self.assertEqual("policy", field.owner_module)
|
||||
self.assertTrue(field.validation_required)
|
||||
self.assertTrue(field.rollback_history_required)
|
||||
self.assertEqual({}, self.client.get(path).json()["policy"])
|
||||
policy = {
|
||||
"allowed_password_encryption_methods": ["aes", "zip_standard"],
|
||||
"allowed_password_delivery_channels": ["phone", "letter"],
|
||||
}
|
||||
response = self.client.put(path, json={"policy": policy})
|
||||
self.assertEqual(200, response.status_code, response.text)
|
||||
self.assertEqual(policy["allowed_password_encryption_methods"], response.json()["effective_policy"]["allowed_password_encryption_methods"])
|
||||
loaded = self.client.get(path)
|
||||
self.assertEqual(200, loaded.status_code)
|
||||
self.assertEqual(policy, loaded.json()["policy"])
|
||||
with Session(self.engine) as session:
|
||||
history = configuration_control_snapshot(session)["history"]
|
||||
self.assertEqual(1, len(history))
|
||||
self.assertEqual("campaign_archive_encryption_policy", history[0]["key"])
|
||||
self.assertEqual("campaign_archive_encryption_policy.updated", history[0]["audit_event"])
|
||||
self.assertEqual({}, history[0]["before"])
|
||||
self.assertEqual(policy, history[0]["after"])
|
||||
self.assertTrue(history[0]["plan"]["allowed"])
|
||||
self.assertEqual([], history[0]["plan"]["blockers"])
|
||||
audit_changes = session.query(ChangeSequenceEntry).filter(
|
||||
ChangeSequenceEntry.module_id == "audit"
|
||||
).all()
|
||||
self.assertEqual(1, len(audit_changes))
|
||||
self.assertEqual("campaign_archive_encryption_policy.updated", audit_changes[0].payload["action"])
|
||||
|
||||
narrowed_policy = {"allowed_password_encryption_methods": ["aes"]}
|
||||
narrowed = self.client.put(path, json={"policy": narrowed_policy})
|
||||
self.assertEqual(200, narrowed.status_code, narrowed.text)
|
||||
with Session(self.engine) as session:
|
||||
history = configuration_control_snapshot(session)["history"]
|
||||
self.assertEqual(2, len(history))
|
||||
self.assertEqual(policy, history[0]["before"])
|
||||
self.assertEqual(policy, history[0]["rollback_value"])
|
||||
self.assertEqual(narrowed_policy, history[0]["after"])
|
||||
|
||||
def test_read_only_actor_cannot_change_system_policy(self) -> None:
|
||||
self.principal = self._principal("admin:policies:read")
|
||||
policy = {"allowed_password_encryption_methods": ["aes", "zip_standard"]}
|
||||
response = self.client.put(
|
||||
"/api/v1/admin/campaign-archive-encryption/policies/system", json={"policy": policy}
|
||||
)
|
||||
self.assertEqual(403, response.status_code)
|
||||
plan = plan_configuration_change("campaign_archive_encryption_policy", actor_scopes=tuple(self.principal.scopes), value=policy)
|
||||
self.assertFalse(plan.allowed)
|
||||
self.assertEqual(("system:settings:write", "admin:policies:write"), plan.missing_scopes)
|
||||
with Session(self.engine) as session:
|
||||
self.assertEqual(0, session.query(PolicyOverride).count())
|
||||
|
||||
def test_tenant_policy_writer_cannot_loosen_global_system_ceiling(self) -> None:
|
||||
self.principal = self._principal("admin:policies:read", "admin:policies:write")
|
||||
policy = {"allowed_password_encryption_methods": ["aes", "zip_standard"]}
|
||||
response = self.client.put(
|
||||
"/api/v1/admin/campaign-archive-encryption/policies/system", json={"policy": policy}
|
||||
)
|
||||
self.assertIn(response.status_code, (403, 409))
|
||||
self.assertIn("system:settings:write", response.text)
|
||||
with Session(self.engine) as session:
|
||||
self.assertEqual(0, session.query(PolicyOverride).count())
|
||||
self.assertEqual(0, session.query(ChangeSequenceEntry).count())
|
||||
|
||||
narrowed = self.client.put(
|
||||
"/api/v1/admin/campaign-archive-encryption/policies/tenant",
|
||||
json={"policy": {"allowed_password_encryption_methods": ["aes"]}},
|
||||
)
|
||||
self.assertEqual(200, narrowed.status_code, narrowed.text)
|
||||
|
||||
def test_invalid_method_and_child_ceiling_still_fail_closed(self) -> None:
|
||||
path = "/api/v1/admin/campaign-archive-encryption/policies"
|
||||
invalid = self.client.put(f"{path}/system", json={"policy": {"allowed_password_encryption_methods": ["plaintext"]}})
|
||||
self.assertEqual(422, invalid.status_code)
|
||||
child = self.client.put(f"{path}/tenant", json={"policy": {"allowed_password_encryption_methods": ["aes", "zip_standard"]}})
|
||||
self.assertEqual(422, child.status_code)
|
||||
self.assertIn("parent", child.text)
|
||||
with Session(self.engine) as session:
|
||||
self.assertEqual(0, session.query(PolicyOverride).count())
|
||||
|
||||
def test_configuration_preview_preserves_only_known_non_secret_enum_lists(self) -> None:
|
||||
unsafe = {
|
||||
"allowed_password_encryption_methods": ["aes", "literal-secret"],
|
||||
"allowed_password_delivery_channels": {"password": "nested-secret"},
|
||||
"password": "actual-secret",
|
||||
"arbitrary_field": ["unknown-secret"],
|
||||
}
|
||||
with Session(self.engine) as session:
|
||||
request = create_configuration_change_request(
|
||||
session,
|
||||
key="campaign_archive_encryption_policy",
|
||||
value=unsafe,
|
||||
actor_user_id="admin-user",
|
||||
actor_scopes=tuple(self.principal.scopes),
|
||||
dry_run=False,
|
||||
target={"scope_type": "system"},
|
||||
)
|
||||
self.assertEqual({key: "<redacted>" for key in unsafe}, request["value_preview"])
|
||||
self.assertNotIn("literal-secret", str(configuration_control_snapshot(session)))
|
||||
self.assertNotIn("actual-secret", str(configuration_control_snapshot(session)))
|
||||
for malformed in ("scalar-secret", ["list-secret"], None, 7):
|
||||
with self.subTest(malformed=type(malformed).__name__):
|
||||
malformed_request = create_configuration_change_request(
|
||||
session,
|
||||
key="campaign_archive_encryption_policy",
|
||||
value=malformed,
|
||||
actor_user_id="admin-user",
|
||||
actor_scopes=tuple(self.principal.scopes),
|
||||
dry_run=False,
|
||||
target={"scope_type": "system"},
|
||||
)
|
||||
self.assertEqual("<redacted>", malformed_request["value_preview"])
|
||||
snapshot = str(configuration_control_snapshot(session))
|
||||
self.assertNotIn("scalar-secret", snapshot)
|
||||
self.assertNotIn("list-secret", snapshot)
|
||||
invalid = self.client.put(
|
||||
"/api/v1/admin/campaign-archive-encryption/policies/system",
|
||||
json={"policy": unsafe},
|
||||
)
|
||||
self.assertEqual(422, invalid.status_code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_policy.backend.campaign_archive_encryption import (
|
||||
CampaignArchiveEncryptionPolicyError,
|
||||
campaign_archive_encryption_policy_state,
|
||||
resolve_campaign_archive_encryption_rows,
|
||||
save_campaign_archive_encryption_policy,
|
||||
)
|
||||
from govoplan_policy.backend.db.models import PolicyOverride
|
||||
|
||||
|
||||
class CampaignArchiveEncryptionPolicyTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.engine = create_engine("sqlite:///:memory:")
|
||||
PolicyOverride.__table__.create(self.engine)
|
||||
|
||||
def test_secure_default_denies_legacy(self) -> None:
|
||||
decision = resolve_campaign_archive_encryption_rows(())
|
||||
|
||||
self.assertEqual(frozenset({"aes"}), decision.allowed_password_encryption_methods)
|
||||
self.assertNotIn("zip_standard", decision.allowed_password_encryption_methods)
|
||||
self.assertEqual("system", decision.source_path[0].path)
|
||||
self.assertTrue(decision.policy_hash)
|
||||
|
||||
def test_child_scope_can_narrow_but_not_loosen_parent(self) -> None:
|
||||
with Session(self.engine) as session:
|
||||
save_campaign_archive_encryption_policy(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
scope_type="system",
|
||||
scope_id=None,
|
||||
owner_type=None,
|
||||
owner_id=None,
|
||||
policy={"allowed_password_encryption_methods": ["aes", "zip_standard"]},
|
||||
actor_id="admin",
|
||||
)
|
||||
tenant = save_campaign_archive_encryption_policy(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
scope_type="tenant",
|
||||
scope_id=None,
|
||||
owner_type=None,
|
||||
owner_id=None,
|
||||
policy={"allowed_password_encryption_methods": ["aes"]},
|
||||
actor_id="admin",
|
||||
)
|
||||
self.assertEqual(
|
||||
frozenset({"aes"}),
|
||||
tenant.effective.allowed_password_encryption_methods,
|
||||
)
|
||||
|
||||
with self.assertRaises(CampaignArchiveEncryptionPolicyError):
|
||||
save_campaign_archive_encryption_policy(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
scope_type="user",
|
||||
scope_id="owner-1",
|
||||
owner_type=None,
|
||||
owner_id=None,
|
||||
policy={"allowed_password_encryption_methods": ["aes", "zip_standard"]},
|
||||
actor_id="admin",
|
||||
)
|
||||
|
||||
def test_owner_and_campaign_sources_are_complete(self) -> None:
|
||||
with Session(self.engine) as session:
|
||||
for scope_type, scope_id, methods in (
|
||||
("system", None, ["aes", "zip_standard"]),
|
||||
("tenant", None, ["aes", "zip_standard"]),
|
||||
("group", "owner-group", ["aes", "zip_standard"]),
|
||||
("campaign", "campaign-1", ["aes"]),
|
||||
):
|
||||
save_campaign_archive_encryption_policy(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
scope_type=scope_type,
|
||||
scope_id=scope_id,
|
||||
owner_type="group" if scope_type == "campaign" else None,
|
||||
owner_id="owner-group" if scope_type == "campaign" else None,
|
||||
policy={"allowed_password_encryption_methods": methods},
|
||||
actor_id="admin",
|
||||
)
|
||||
state = campaign_archive_encryption_policy_state(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
scope_type="campaign",
|
||||
scope_id="campaign-1",
|
||||
owner_type="group",
|
||||
owner_id="owner-group",
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
["system", "tenant", "group", "campaign"],
|
||||
[step.scope_type for step in state.effective.source_path],
|
||||
)
|
||||
self.assertEqual(
|
||||
frozenset({"aes"}),
|
||||
state.effective.allowed_password_encryption_methods,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,109 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from govoplan_core.core.access import PrincipalRef
|
||||
from govoplan_core.core.datasources import DatasourceVisibilityPolicyRequest
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_policy.backend.datasource_visibility import (
|
||||
DatasourceVisibilityPolicyProvider,
|
||||
)
|
||||
from govoplan_policy.backend.db.models import PolicyOverride
|
||||
from govoplan_policy.backend.policy_overrides import set_policy_override
|
||||
|
||||
|
||||
class DatasourceVisibilityPolicyTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.engine = create_engine("sqlite:///:memory:")
|
||||
Base.metadata.create_all(self.engine, tables=[PolicyOverride.__table__])
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
self.session = self.Session()
|
||||
self.provider = DatasourceVisibilityPolicyProvider()
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.session.close()
|
||||
Base.metadata.drop_all(self.engine, tables=[PolicyOverride.__table__])
|
||||
self.engine.dispose()
|
||||
|
||||
def _request(self, policy_ref: str | None) -> DatasourceVisibilityPolicyRequest:
|
||||
return DatasourceVisibilityPolicyRequest(
|
||||
tenant_id="tenant-1",
|
||||
datasource_ref="datasource:cases",
|
||||
principal=PrincipalRef(
|
||||
account_id="account-1",
|
||||
membership_id="member-1",
|
||||
tenant_id="tenant-1",
|
||||
group_ids=frozenset({"group-1"}),
|
||||
),
|
||||
action="read",
|
||||
policy_ref=policy_ref,
|
||||
)
|
||||
|
||||
def test_unresolved_explicit_reference_fails_closed(self) -> None:
|
||||
decision = self.provider.decide_datasource_visibility(
|
||||
self.session,
|
||||
request=self._request("missing"),
|
||||
)
|
||||
|
||||
self.assertFalse(decision.allowed)
|
||||
self.assertEqual("reference_unresolved", decision.provenance["status"])
|
||||
self.assertTrue(decision.decision_ref.startswith("datasource-visibility:"))
|
||||
|
||||
def test_global_and_referenced_hierarchy_are_returned_as_overlays(self) -> None:
|
||||
set_policy_override(
|
||||
self.session,
|
||||
policy_family="datasource_visibility",
|
||||
target_key="*",
|
||||
tenant_id="tenant-1",
|
||||
scope_type="system",
|
||||
scope_id=None,
|
||||
policy={"source_acl": {"auth_methods": ["session"]}},
|
||||
actor_id="admin",
|
||||
)
|
||||
set_policy_override(
|
||||
self.session,
|
||||
policy_family="datasource_visibility",
|
||||
target_key="Case-Workers",
|
||||
tenant_id="tenant-1",
|
||||
scope_type="tenant",
|
||||
scope_id="tenant-1",
|
||||
policy={"source_acl": {"group_ids": ["group-1"]}},
|
||||
actor_id="admin",
|
||||
)
|
||||
set_policy_override(
|
||||
self.session,
|
||||
policy_family="datasource_visibility",
|
||||
target_key="case-workers",
|
||||
tenant_id="tenant-1",
|
||||
scope_type="user",
|
||||
scope_id="member-1",
|
||||
policy={
|
||||
"fields": {
|
||||
"secret": {
|
||||
"action": "omit",
|
||||
"allow": {"role_ids": ["privileged"]},
|
||||
}
|
||||
}
|
||||
},
|
||||
actor_id="admin",
|
||||
)
|
||||
|
||||
decision = self.provider.decide_datasource_visibility(
|
||||
self.session,
|
||||
request=self._request("CASE-WORKERS"),
|
||||
)
|
||||
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual(3, len(decision.policies))
|
||||
self.assertEqual("resolved", decision.provenance["status"])
|
||||
self.assertEqual(
|
||||
["system", "tenant", "user"],
|
||||
[source["scope_type"] for source in decision.provenance["sources"]],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.core.dsar import DsarProvider, DsarSubjectRef
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_policy.backend.db.models import PolicyOverride
|
||||
from govoplan_policy.backend.dsar_provider import (
|
||||
POLICY_DSAR_CAPABILITY,
|
||||
PolicyDsarProvider,
|
||||
)
|
||||
from govoplan_policy.backend.manifest import manifest
|
||||
|
||||
|
||||
class PolicyDsarProviderTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.engine = create_engine("sqlite+pysqlite:///:memory:")
|
||||
Base.metadata.create_all(self.engine)
|
||||
self.session = Session(self.engine)
|
||||
self.provider = PolicyDsarProvider()
|
||||
self.session.add_all(
|
||||
(
|
||||
PolicyOverride(
|
||||
id="override-1",
|
||||
policy_family="retention",
|
||||
target_key="target-secret-do-not-export",
|
||||
tenant_id="tenant-1",
|
||||
scope_type="user",
|
||||
scope_id="scope-subject-do-not-export",
|
||||
scope_key="scope-key-do-not-export",
|
||||
policy={"secret": "policy-payload-do-not-export"},
|
||||
revision=2,
|
||||
created_by="account-1",
|
||||
updated_by="account-1",
|
||||
),
|
||||
PolicyOverride(
|
||||
id="override-system",
|
||||
policy_family="retention",
|
||||
target_key="system",
|
||||
tenant_id=None,
|
||||
scope_type="system",
|
||||
scope_key="system",
|
||||
policy={},
|
||||
revision=1,
|
||||
created_by="account-1",
|
||||
updated_by="account-1",
|
||||
),
|
||||
PolicyOverride(
|
||||
id="override-other",
|
||||
policy_family="retention",
|
||||
target_key="other",
|
||||
tenant_id="tenant-2",
|
||||
scope_type="tenant",
|
||||
scope_key="tenant-2",
|
||||
policy={},
|
||||
revision=1,
|
||||
created_by="account-1",
|
||||
updated_by="account-1",
|
||||
),
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.session.close()
|
||||
self.engine.dispose()
|
||||
|
||||
def test_search_is_tenant_safe_and_minimized(self) -> None:
|
||||
self.assertIsInstance(self.provider, DsarProvider)
|
||||
records = self.provider.search_subject(
|
||||
self.session,
|
||||
tenant_id="tenant-1",
|
||||
subject=DsarSubjectRef(account_id="account-1"),
|
||||
)
|
||||
self.assertEqual(["override-1"], [record.resource_id for record in records])
|
||||
exported = json.dumps([record.to_dict() for record in records])
|
||||
for excluded in (
|
||||
"target-secret-do-not-export",
|
||||
"scope-subject-do-not-export",
|
||||
"scope-key-do-not-export",
|
||||
"policy-payload-do-not-export",
|
||||
):
|
||||
self.assertNotIn(excluded, exported)
|
||||
|
||||
def test_requires_exact_account_and_supports_narrowing(self) -> None:
|
||||
self.assertEqual(
|
||||
(),
|
||||
self.provider.search_subject(
|
||||
self.session,
|
||||
tenant_id="tenant-1",
|
||||
subject=DsarSubjectRef(email="policy@example.test"),
|
||||
),
|
||||
)
|
||||
records = self.provider.search_subject(
|
||||
self.session,
|
||||
tenant_id="tenant-1",
|
||||
subject=DsarSubjectRef(
|
||||
account_id="account-1",
|
||||
external_references={"policy.override": "override-1"},
|
||||
),
|
||||
)
|
||||
self.assertEqual(1, len(records))
|
||||
|
||||
def test_records_are_retained_and_manifest_is_complete(self) -> None:
|
||||
subject = DsarSubjectRef(account_id="account-1")
|
||||
records = self.provider.search_subject(
|
||||
self.session, tenant_id="tenant-1", subject=subject
|
||||
)
|
||||
actions = self.provider.plan_erasure(
|
||||
self.session,
|
||||
tenant_id="tenant-1",
|
||||
subject=subject,
|
||||
records=records,
|
||||
)
|
||||
self.assertTrue(all(action.kind == "retain" for action in actions))
|
||||
self.assertIn(POLICY_DSAR_CAPABILITY, manifest.capability_factories)
|
||||
self.assertIn(
|
||||
"policy.data-subject-requests",
|
||||
{topic.id for topic in manifest.documentation},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -132,6 +132,58 @@ class FunctionAssignmentGovernancePolicyTests(unittest.TestCase):
|
||||
self.assertTrue(responder.allowed)
|
||||
self.assertFalse(unrelated.allowed)
|
||||
|
||||
def test_delegation_ceilings_and_escalation_rules_are_bounded(self) -> None:
|
||||
decision = self.resolve(
|
||||
function_settings={
|
||||
"assignment_governance": {
|
||||
"request_profile": "holder_with_authority_clearance",
|
||||
"authority_function_id": "authority-1",
|
||||
"delegation_allowed": True,
|
||||
"maximum_delegation_depth": 3,
|
||||
"maximum_delegated_validity_days": 45,
|
||||
"escalation": {
|
||||
"holder": {
|
||||
"target_function_id": "escalation-1",
|
||||
"timeout_hours": 24,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
self.assertTrue(decision.delegation_allowed)
|
||||
self.assertEqual(3, decision.maximum_delegation_depth)
|
||||
self.assertEqual(45, decision.maximum_delegated_validity_days)
|
||||
self.assertEqual("escalation-1", decision.escalation_rules[0].target_function_id)
|
||||
self.assertEqual(24, decision.escalation_rules[0].timeout_hours)
|
||||
|
||||
def test_escalated_review_requires_explicit_target_holder(self) -> None:
|
||||
allowed = self.resolve(
|
||||
action="approve_escalation",
|
||||
current_state="escalated",
|
||||
context={
|
||||
"actor_is_escalation_target": True,
|
||||
"actor_routes": {"escalation": {"effective": True}},
|
||||
},
|
||||
)
|
||||
unavailable = self.resolve(
|
||||
action="approve_escalation",
|
||||
current_state="escalated",
|
||||
context={
|
||||
"actor_is_escalation_target": False,
|
||||
"actor_routes": {
|
||||
"escalation": {
|
||||
"effective": False,
|
||||
"reason": "The target function is vacant.",
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
self.assertTrue(allowed.allowed)
|
||||
self.assertFalse(unavailable.allowed)
|
||||
self.assertEqual("The target function is vacant.", unavailable.reason)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from govoplan_core.core.policy import (
|
||||
CAPABILITY_POLICY_IMPACT_SUBJECT_PREFIX,
|
||||
PolicyImpactPopulationRequest,
|
||||
PolicyImpactSubject,
|
||||
PolicyImpactSubjectBatch,
|
||||
)
|
||||
from govoplan_policy.backend.db.models import PolicyOverride
|
||||
from govoplan_policy.backend.impact_preview import (
|
||||
PolicyImpactPopulationSpec,
|
||||
preview_policy_impact,
|
||||
)
|
||||
from govoplan_policy.backend.api.v1.routes import (
|
||||
_require_recent_policy_authentication,
|
||||
)
|
||||
|
||||
|
||||
class _SubjectProvider:
|
||||
provider_id = "example"
|
||||
supported_policy_families = ("view",)
|
||||
|
||||
def collect_policy_impact_subjects(
|
||||
self,
|
||||
session: object | None = None,
|
||||
*,
|
||||
request: PolicyImpactPopulationRequest,
|
||||
) -> PolicyImpactSubjectBatch:
|
||||
del session
|
||||
subjects = (
|
||||
PolicyImpactSubject(
|
||||
module_id="views",
|
||||
resource_type="view",
|
||||
resource_id="view-1",
|
||||
action="edit",
|
||||
label="First" if request.allow_sensitive_details else None,
|
||||
),
|
||||
PolicyImpactSubject(
|
||||
module_id="views",
|
||||
resource_type="view",
|
||||
resource_id="view-2",
|
||||
action="view",
|
||||
label="Second" if request.allow_sensitive_details else None,
|
||||
),
|
||||
)
|
||||
return PolicyImpactSubjectBatch(
|
||||
provider_id=self.provider_id,
|
||||
subjects=subjects[: request.limit],
|
||||
state="truncated" if request.limit < len(subjects) else "complete",
|
||||
total_available=len(subjects),
|
||||
explanation="Explicit test population.",
|
||||
)
|
||||
|
||||
|
||||
class _Registry:
|
||||
def __init__(self, provider: object | None = None) -> None:
|
||||
self.provider = provider
|
||||
|
||||
def has_capability(self, name: str) -> bool:
|
||||
return (
|
||||
self.provider is not None
|
||||
and name == f"{CAPABILITY_POLICY_IMPACT_SUBJECT_PREFIX}example"
|
||||
)
|
||||
|
||||
def capability(self, name: str) -> object | None:
|
||||
del name
|
||||
return self.provider
|
||||
|
||||
|
||||
class PolicyImpactPreviewTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.engine = create_engine("sqlite+pysqlite:///:memory:")
|
||||
PolicyOverride.__table__.create(self.engine)
|
||||
self.session: Session = sessionmaker(
|
||||
bind=self.engine,
|
||||
expire_on_commit=False,
|
||||
)()
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.session.close()
|
||||
self.engine.dispose()
|
||||
|
||||
def test_preview_compares_effective_view_policy_without_persistence(self) -> None:
|
||||
preview = preview_policy_impact(
|
||||
self.session,
|
||||
registry=_Registry(_SubjectProvider()),
|
||||
tenant_id="tenant-1",
|
||||
policy_family="view",
|
||||
scope_type="tenant",
|
||||
scope_id=None,
|
||||
proposed_policy={
|
||||
"allow_edit": False,
|
||||
"allowed_view_ids": ["view-1"],
|
||||
},
|
||||
populations=(PolicyImpactPopulationSpec(provider_id="example"),),
|
||||
actor_scopes=("admin:policies:read", "policy:impact:details"),
|
||||
include_details=True,
|
||||
details_allowed=True,
|
||||
)
|
||||
|
||||
self.assertEqual(2, preview.counts["newly_denied"])
|
||||
self.assertEqual(2, len(preview.effects))
|
||||
self.assertEqual(
|
||||
{"view.allow_edit", "view.allow_view"},
|
||||
{effect.rule for effect in preview.effects},
|
||||
)
|
||||
self.assertTrue(
|
||||
all(
|
||||
effect.proposed_sources[-1].label.startswith("Proposed Tenant")
|
||||
for effect in preview.effects
|
||||
)
|
||||
)
|
||||
self.assertEqual(0, self.session.query(PolicyOverride).count())
|
||||
|
||||
def test_details_are_hidden_but_permission_filtered_counts_remain(self) -> None:
|
||||
preview = preview_policy_impact(
|
||||
self.session,
|
||||
registry=_Registry(_SubjectProvider()),
|
||||
tenant_id="tenant-1",
|
||||
policy_family="view",
|
||||
scope_type="system",
|
||||
scope_id=None,
|
||||
proposed_policy={"allow_view": False},
|
||||
populations=(
|
||||
PolicyImpactPopulationSpec(provider_id="example", limit=1),
|
||||
),
|
||||
include_details=True,
|
||||
details_allowed=False,
|
||||
)
|
||||
|
||||
self.assertEqual(1, preview.counts["newly_denied"])
|
||||
self.assertEqual((), preview.effects)
|
||||
self.assertTrue(preview.details_hidden)
|
||||
self.assertIn("policy:impact:details", preview.details_explanation or "")
|
||||
self.assertEqual("truncated", preview.populations[0]["state"])
|
||||
self.assertTrue(preview.high_impact)
|
||||
|
||||
def test_unavailable_provider_is_explained_instead_of_counted_as_zero(self) -> None:
|
||||
preview = preview_policy_impact(
|
||||
self.session,
|
||||
registry=_Registry(),
|
||||
tenant_id="tenant-1",
|
||||
policy_family="view",
|
||||
scope_type="tenant",
|
||||
scope_id=None,
|
||||
proposed_policy={},
|
||||
populations=(PolicyImpactPopulationSpec(provider_id="missing"),),
|
||||
)
|
||||
|
||||
self.assertEqual("unavailable", preview.populations[0]["state"])
|
||||
self.assertIn("not enabled", preview.populations[0]["explanation"])
|
||||
|
||||
def test_system_policy_guard_requires_a_recent_interactive_session(self) -> None:
|
||||
fresh = SimpleNamespace(
|
||||
auth_session=SimpleNamespace(
|
||||
created_at=datetime.now(timezone.utc) - timedelta(minutes=2)
|
||||
)
|
||||
)
|
||||
_require_recent_policy_authentication(fresh) # type: ignore[arg-type]
|
||||
|
||||
stale = SimpleNamespace(
|
||||
auth_session=SimpleNamespace(
|
||||
created_at=datetime.now(timezone.utc) - timedelta(minutes=30)
|
||||
)
|
||||
)
|
||||
with self.assertRaises(HTTPException) as context:
|
||||
_require_recent_policy_authentication(stale) # type: ignore[arg-type]
|
||||
self.assertEqual(403, context.exception.status_code)
|
||||
self.assertEqual(
|
||||
"recent_authentication_required",
|
||||
context.exception.detail["code"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,23 +5,39 @@ import tomllib
|
||||
import unittest
|
||||
|
||||
from govoplan_core.core.policy import (
|
||||
CAPABILITY_POLICY_CAMPAIGN_ARCHIVE_ENCRYPTION,
|
||||
CAPABILITY_POLICY_DEFINITION_GOVERNANCE,
|
||||
CAPABILITY_POLICY_FUNCTION_ASSIGNMENT_GOVERNANCE,
|
||||
CAPABILITY_POLICY_PRIVACY_RETENTION,
|
||||
CAPABILITY_POLICY_SCHEDULING_PARTICIPANT_PRIVACY,
|
||||
CAPABILITY_POLICY_VIEW_GOVERNANCE,
|
||||
)
|
||||
from govoplan_core.core.access import CAPABILITY_POLICY_ACCESS_EXPLANATION_SUBJECTS
|
||||
from govoplan_core.core.distribution_lists import (
|
||||
CAPABILITY_POLICY_DISTRIBUTION_CHANNELS,
|
||||
)
|
||||
from govoplan_core.core.datasources import CAPABILITY_POLICY_DATASOURCE_VISIBILITY
|
||||
from govoplan_core.core.reporting import CAPABILITY_POLICY_REPORTING_GOVERNANCE
|
||||
from govoplan_policy.backend.manifest import manifest
|
||||
from govoplan_policy.backend.dsar_provider import POLICY_DSAR_CAPABILITY
|
||||
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class PolicyModuleContractTests(unittest.TestCase):
|
||||
def test_all_static_topics_have_complete_german_content(self) -> None:
|
||||
for topic in manifest.documentation:
|
||||
german = (topic.translations or {}).get("de", {})
|
||||
self.assertEqual(
|
||||
{"title", "summary", "body"},
|
||||
set(german),
|
||||
topic.id,
|
||||
)
|
||||
self.assertTrue(
|
||||
all(str(value).strip() for value in german.values()), topic.id
|
||||
)
|
||||
|
||||
def test_policy_package_does_not_hard_require_access(self) -> None:
|
||||
project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))[
|
||||
"project"
|
||||
@@ -49,11 +65,15 @@ class PolicyModuleContractTests(unittest.TestCase):
|
||||
{
|
||||
CAPABILITY_POLICY_DEFINITION_GOVERNANCE,
|
||||
CAPABILITY_POLICY_DISTRIBUTION_CHANNELS,
|
||||
CAPABILITY_POLICY_DATASOURCE_VISIBILITY,
|
||||
CAPABILITY_POLICY_FUNCTION_ASSIGNMENT_GOVERNANCE,
|
||||
CAPABILITY_POLICY_PRIVACY_RETENTION,
|
||||
CAPABILITY_POLICY_REPORTING_GOVERNANCE,
|
||||
CAPABILITY_POLICY_SCHEDULING_PARTICIPANT_PRIVACY,
|
||||
CAPABILITY_POLICY_VIEW_GOVERNANCE,
|
||||
CAPABILITY_POLICY_ACCESS_EXPLANATION_SUBJECTS,
|
||||
CAPABILITY_POLICY_CAMPAIGN_ARCHIVE_ENCRYPTION,
|
||||
POLICY_DSAR_CAPABILITY,
|
||||
},
|
||||
set(manifest.capability_factories),
|
||||
)
|
||||
@@ -65,14 +85,44 @@ class PolicyModuleContractTests(unittest.TestCase):
|
||||
if item.id == "policy.hierarchy-overrides-and-retention"
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
["policy.retention", "privacy.retention"],
|
||||
topic.metadata["help_contexts"],
|
||||
self.assertTrue(
|
||||
{
|
||||
"policy.retention",
|
||||
"privacy.retention",
|
||||
"policy.retention.action.save",
|
||||
"policy.retention.field.store-raw-campaign-json",
|
||||
"policy.retention.field.generated-eml-retention-days",
|
||||
"policy.retention.field.audit-detail-level",
|
||||
"policy.retention.field.allow-lower-level-limits",
|
||||
}.issubset(topic.metadata["help_contexts"])
|
||||
)
|
||||
self.assertEqual("workflow", topic.metadata["kind"])
|
||||
self.assertIn("/admin", topic.metadata["route"])
|
||||
self.assertEqual({"title", "summary", "body"}, set(topic.translations["de"]))
|
||||
self.assertIn("Quellenpfad", topic.translations["de"]["body"])
|
||||
|
||||
def test_view_policy_administration_contract_is_documented_and_exposed(self) -> None:
|
||||
execution_topic = next(
|
||||
item
|
||||
for item in manifest.documentation
|
||||
if item.id == "policy.retention-execution-and-recovery"
|
||||
)
|
||||
self.assertEqual(
|
||||
{
|
||||
"policy.retention.execution",
|
||||
"policy.retention.action.dry-run",
|
||||
"policy.retention.action.apply",
|
||||
"policy.retention.confirm-apply",
|
||||
"policy.retention.outcome",
|
||||
},
|
||||
set(execution_topic.metadata["help_contexts"]),
|
||||
)
|
||||
self.assertIn(
|
||||
"nicht wiederherstellen", execution_topic.translations["de"]["body"]
|
||||
)
|
||||
|
||||
def test_view_policy_administration_contract_is_documented_and_exposed(
|
||||
self,
|
||||
) -> None:
|
||||
topic = next(
|
||||
item
|
||||
for item in manifest.documentation
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@govoplan/policy-webui",
|
||||
"version": "0.1.18",
|
||||
"version": "0.1.23",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
@@ -13,10 +13,11 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test:interface-patterns": "node scripts/test-interface-pattern-language.mjs"
|
||||
"test:interface-patterns": "node scripts/test-interface-pattern-language.mjs",
|
||||
"test:archive-encryption": "node --experimental-strip-types scripts/test-archive-encryption-draft.mjs"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@govoplan/core-webui": "^0.1.18",
|
||||
"@govoplan/core-webui": "^0.1.45",
|
||||
"lucide-react": "^1.23.0",
|
||||
"react": ">=19.2.7 <20",
|
||||
"react-dom": ">=19.2.7 <20",
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import {
|
||||
buildPolicy, draftFromPolicy, inheritedControlDisabled, setDraftChannel,
|
||||
setDraftMethod, stable
|
||||
} from "../src/features/policy/archiveEncryptionDraft.ts";
|
||||
|
||||
const baseline = {
|
||||
allowed_password_encryption_methods: ["aes"],
|
||||
allowed_password_delivery_channels: ["separate_mail", "sms", "letter", "phone", "in_person"],
|
||||
policy_hash: "baseline", source_path: [], reason: "Secure baseline", diagnostics: []
|
||||
};
|
||||
const initial = draftFromPolicy({}, baseline);
|
||||
assert.deepEqual(buildPolicy(initial), {}, "Opening default system settings must not create an override or dirty state");
|
||||
assert.equal(inheritedControlDisabled("system", initial.inheritMethods), false, "System defaults must be editable without a hidden inheritance toggle");
|
||||
assert.equal(inheritedControlDisabled("system", initial.inheritChannels), false);
|
||||
const enabled = setDraftMethod(initial, "zip_standard", true);
|
||||
assert.deepEqual(buildPolicy(enabled), { allowed_password_encryption_methods: ["aes", "zip_standard"] }, "The first system Legacy click must produce an explicit override");
|
||||
assert.notEqual(stable(buildPolicy(enabled)), stable({}));
|
||||
assert.deepEqual(buildPolicy(initial), {}, "Changing a draft must preserve the original policy");
|
||||
const narrowedChannels = setDraftChannel(initial, "sms", false);
|
||||
assert.deepEqual(buildPolicy(narrowedChannels), { allowed_password_delivery_channels: ["separate_mail", "letter", "phone", "in_person"] });
|
||||
assert.equal(inheritedControlDisabled("tenant", initial.inheritMethods), true, "Child scopes retain explicit inheritance controls");
|
||||
assert.equal(inheritedControlDisabled("user", false), false);
|
||||
assert.deepEqual(buildPolicy(draftFromPolicy(buildPolicy(enabled), baseline)), buildPolicy(enabled), "An explicit system policy survives save/reload");
|
||||
assert.deepEqual(buildPolicy(setDraftMethod(enabled, "zip_standard", false)), { allowed_password_encryption_methods: ["aes"] });
|
||||
|
||||
const panel = readFileSync(new URL("../src/features/policy/ArchiveEncryptionPoliciesPanel.tsx", import.meta.url), "utf8");
|
||||
assert.match(panel, /inheritedControlDisabled\(scopeType, draft\.inheritMethods\)/);
|
||||
assert.match(panel, /inheritedControlDisabled\(scopeType, draft\.inheritChannels\)/);
|
||||
assert.match(panel, /setDraft\(setDraftMethod\(draft, method\.id, checked\)\)/);
|
||||
assert.match(panel, /setDraft\(setDraftChannel\(draft, channel\.id, checked\)\)/);
|
||||
assert.match(panel, /scopeType !== "system" && !parentMethods\.includes\(method\.id\)/, "Child scopes must still respect parent ceilings");
|
||||
const moduleSource = readFileSync(new URL("../src/module.ts", import.meta.url), "utf8");
|
||||
assert.match(moduleSource, /scopeType: "system",\s*canWrite: hasScope\(auth, "system:settings:write"\) && hasScope\(auth, "admin:policies:write"\)/, "Tenant policy administration alone must not enable edits to the global system archive ceiling");
|
||||
console.log("Archive encryption settings regressions passed.");
|
||||
@@ -5,13 +5,25 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const webuiRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));
|
||||
const panel = readFileSync(resolve(webuiRoot, "src/features/policy/RetentionPoliciesPanel.tsx"), "utf8");
|
||||
const viewPanel = readFileSync(resolve(webuiRoot, "src/features/policy/ViewPoliciesPanel.tsx"), "utf8");
|
||||
|
||||
assert.match(panel, /<RetentionPolicyScopeManager/, "Policy delegates effective-policy blockers and provenance to the shared Core contract");
|
||||
assert.match(panel, /contextId: "policy\.retention"/, "retention exposes stable contextual documentation");
|
||||
assert.match(panel, /policy\.retention\.action\.dry-run/, "retention dry runs expose exact contextual help");
|
||||
assert.match(panel, /policy\.retention\.action\.apply/, "destructive retention exposes exact contextual help");
|
||||
assert.match(panel, /policy\.retention\.confirm-apply/, "retention confirmation exposes consequence and recovery help");
|
||||
assert.match(panel, /helpModuleId="policy"/, "retention confirmation retains Policy as its documentation owner");
|
||||
assert.match(panel, /disabledReason=\{actionDisabledReason\}/, "retention execution explains unavailable actions");
|
||||
assert.match(panel, /<ConfirmDialog/, "destructive retention uses shared confirmation");
|
||||
assert.match(panel, /<DataGrid/, "retention outcomes use the shared data-grid pattern");
|
||||
assert.doesNotMatch(panel, /admin-json-preview/, "retention outcome is not presented as raw JSON");
|
||||
assert.doesNotMatch(panel, /<pre/, "retention outcome is a typed projection");
|
||||
|
||||
assert.match(viewPanel, /policy\.impact-preview\.action\.preview/, "View policy exposes stable impact-preview help");
|
||||
assert.match(viewPanel, /previewCurrent/, "View policy binds Save to the current dirty-draft preview");
|
||||
assert.match(viewPanel, /updateViewPolicy\([\s\S]*impactPreview/, "View policy carries preview evidence into the commit request");
|
||||
assert.match(viewPanel, /prepareResetPolicy/, "inherited-policy removal receives its own impact preview");
|
||||
assert.match(viewPanel, /newly_allowed/, "View policy presents typed impact outcome counts");
|
||||
assert.match(viewPanel, /populations\.map/, "View policy explains provider coverage state");
|
||||
|
||||
console.log("Policy interface-pattern contracts passed.");
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { apiFetch, type ApiSettings } from "@govoplan/core-webui";
|
||||
|
||||
export type ArchiveEncryptionPolicyScope = "system" | "tenant" | "group" | "user";
|
||||
export type ArchiveEncryptionMethod = "aes" | "zip_standard";
|
||||
export type PasswordDeliveryChannel = "separate_mail" | "sms" | "letter" | "phone" | "in_person";
|
||||
|
||||
export type ArchiveEncryptionPolicyItem = {
|
||||
allowed_password_encryption_methods?: ArchiveEncryptionMethod[];
|
||||
allowed_password_delivery_channels?: PasswordDeliveryChannel[];
|
||||
};
|
||||
|
||||
export type EffectiveArchiveEncryptionPolicy = {
|
||||
allowed_password_encryption_methods: ArchiveEncryptionMethod[];
|
||||
allowed_password_delivery_channels: PasswordDeliveryChannel[];
|
||||
policy_hash: string;
|
||||
source_path: Array<{ path: string; label: string }>;
|
||||
reason: string;
|
||||
diagnostics: Array<Record<string, unknown>>;
|
||||
};
|
||||
|
||||
export type ArchiveEncryptionPolicyResponse = {
|
||||
scope_type: ArchiveEncryptionPolicyScope;
|
||||
scope_id?: string | null;
|
||||
id?: string | null;
|
||||
revision?: number | null;
|
||||
policy: ArchiveEncryptionPolicyItem;
|
||||
effective_policy: EffectiveArchiveEncryptionPolicy;
|
||||
parent_policy: EffectiveArchiveEncryptionPolicy;
|
||||
};
|
||||
|
||||
function policyPath(scope: ArchiveEncryptionPolicyScope, scopeId?: string | null): string {
|
||||
const params = new URLSearchParams();
|
||||
if (scopeId) params.set("scope_id", scopeId);
|
||||
const suffix = params.toString();
|
||||
return `/api/v1/admin/campaign-archive-encryption/policies/${scope}${suffix ? `?${suffix}` : ""}`;
|
||||
}
|
||||
|
||||
export function fetchArchiveEncryptionPolicy(
|
||||
settings: ApiSettings,
|
||||
scope: ArchiveEncryptionPolicyScope,
|
||||
scopeId?: string | null
|
||||
): Promise<ArchiveEncryptionPolicyResponse> {
|
||||
return apiFetch(settings, policyPath(scope, scopeId));
|
||||
}
|
||||
|
||||
export function updateArchiveEncryptionPolicy(
|
||||
settings: ApiSettings,
|
||||
scope: ArchiveEncryptionPolicyScope,
|
||||
scopeId: string | null,
|
||||
policy: ArchiveEncryptionPolicyItem
|
||||
): Promise<ArchiveEncryptionPolicyResponse> {
|
||||
return apiFetch(settings, policyPath(scope, scopeId), {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ policy })
|
||||
});
|
||||
}
|
||||
@@ -46,6 +46,46 @@ export type ViewPolicyReferenceData = {
|
||||
surfaces: Array<{ id: string; label: string; module_id: string; kind: string }>;
|
||||
};
|
||||
|
||||
export type PolicyImpactCategory = "newly_allowed" | "newly_denied" | "unchanged" | "indeterminate";
|
||||
|
||||
export type PolicyImpactPreviewResponse = {
|
||||
preview_id: string;
|
||||
proposal_hash: string;
|
||||
policy_family: string;
|
||||
scope_type: string;
|
||||
scope_id?: string | null;
|
||||
base_revision?: number | null;
|
||||
counts: Record<PolicyImpactCategory, number>;
|
||||
effects: Array<{
|
||||
category: PolicyImpactCategory;
|
||||
subject: {
|
||||
module_id: string;
|
||||
resource_type: string;
|
||||
resource_id: string;
|
||||
action: string;
|
||||
label?: string | null;
|
||||
scope_type?: string | null;
|
||||
scope_id?: string | null;
|
||||
};
|
||||
current_allowed?: boolean | null;
|
||||
proposed_allowed?: boolean | null;
|
||||
rule: string;
|
||||
current_sources: Array<{ path: string; label: string }>;
|
||||
proposed_sources: Array<{ path: string; label: string }>;
|
||||
explanation?: string | null;
|
||||
}>;
|
||||
populations: Array<{
|
||||
provider_id: string;
|
||||
state: "complete" | "sampled" | "truncated" | "unavailable";
|
||||
returned: number;
|
||||
total_available?: number | null;
|
||||
explanation?: string | null;
|
||||
}>;
|
||||
details_hidden: boolean;
|
||||
details_explanation?: string | null;
|
||||
high_impact: boolean;
|
||||
};
|
||||
|
||||
export function fetchViewPolicy(
|
||||
settings: ApiSettings,
|
||||
scope: ViewPolicyScope,
|
||||
@@ -60,26 +100,73 @@ export function updateViewPolicy(
|
||||
settings: ApiSettings,
|
||||
scope: ViewPolicyScope,
|
||||
scopeId: string | null | undefined,
|
||||
policy: ViewPolicyItem
|
||||
policy: ViewPolicyItem,
|
||||
impactPreview?: Pick<PolicyImpactPreviewResponse, "preview_id" | "proposal_hash"> | null
|
||||
): Promise<ViewPolicyScopeResponse> {
|
||||
return apiFetch(settings, apiPath(`/api/v1/admin/view-policies/${scope}`, {
|
||||
scope_id: scopeId || undefined
|
||||
}), {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ policy })
|
||||
body: JSON.stringify({
|
||||
policy,
|
||||
impact_preview_id: impactPreview?.preview_id,
|
||||
impact_proposal_hash: impactPreview?.proposal_hash
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteViewPolicy(
|
||||
settings: ApiSettings,
|
||||
scope: ViewPolicyScope,
|
||||
scopeId?: string | null
|
||||
scopeId?: string | null,
|
||||
impactPreview?: Pick<PolicyImpactPreviewResponse, "preview_id" | "proposal_hash"> | null
|
||||
): Promise<ViewPolicyScopeResponse> {
|
||||
return apiFetch(settings, apiPath(`/api/v1/admin/view-policies/${scope}`, {
|
||||
scope_id: scopeId || undefined
|
||||
scope_id: scopeId || undefined,
|
||||
impact_preview_id: impactPreview?.preview_id,
|
||||
impact_proposal_hash: impactPreview?.proposal_hash
|
||||
}), { method: "DELETE" });
|
||||
}
|
||||
|
||||
export function previewViewPolicyImpact(
|
||||
settings: ApiSettings,
|
||||
scope: ViewPolicyScope,
|
||||
scopeId: string | null | undefined,
|
||||
policy: ViewPolicyItem,
|
||||
population: { viewIds: string[]; surfaceIds: string[] }
|
||||
): Promise<PolicyImpactPreviewResponse> {
|
||||
return apiFetch(settings, "/api/v1/admin/policy-impact/preview", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
policy_family: "view",
|
||||
scope_type: scope,
|
||||
scope_id: scopeId || null,
|
||||
proposed_policy: policy,
|
||||
populations: [
|
||||
{
|
||||
provider_id: "views",
|
||||
selector: {
|
||||
include_views: true,
|
||||
include_surfaces: false,
|
||||
view_ids: population.viewIds.slice(0, 500)
|
||||
},
|
||||
limit: 500
|
||||
},
|
||||
{
|
||||
provider_id: "views",
|
||||
selector: {
|
||||
include_views: false,
|
||||
include_surfaces: true,
|
||||
surface_ids: population.surfaceIds.slice(0, 500)
|
||||
},
|
||||
limit: 500
|
||||
}
|
||||
],
|
||||
include_details: true
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchViewPolicyReferences(settings: ApiSettings): Promise<ViewPolicyReferenceData> {
|
||||
const [definitionResult, surfaceResult] = await Promise.allSettled([
|
||||
apiFetch<{ definitions: Array<{ id: string; name: string; scope_type?: string }> }>(
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
AdminPageLayout,
|
||||
adminErrorMessage,
|
||||
Button,
|
||||
Card,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
DismissibleAlert,
|
||||
FormField,
|
||||
SearchableSelect,
|
||||
ToggleSwitch,
|
||||
useUnsavedDraftGuard,
|
||||
type ApiSettings,
|
||||
type SearchableSelectOption
|
||||
} from "@govoplan/core-webui";
|
||||
import { RefreshCw, Save, Undo2 } from "lucide-react";
|
||||
import { fetchGroupsDelta, fetchUsersDelta } from "../../api/adminTargets";
|
||||
import {
|
||||
fetchArchiveEncryptionPolicy,
|
||||
updateArchiveEncryptionPolicy,
|
||||
type ArchiveEncryptionMethod,
|
||||
type ArchiveEncryptionPolicyResponse,
|
||||
type ArchiveEncryptionPolicyScope,
|
||||
type PasswordDeliveryChannel
|
||||
} from "../../api/archiveEncryptionPolicies";
|
||||
import {
|
||||
buildPolicy,
|
||||
draftFromPolicy,
|
||||
inheritedControlDisabled,
|
||||
setDraftChannel,
|
||||
setDraftMethod,
|
||||
stable,
|
||||
type ArchiveEncryptionDraft
|
||||
} from "./archiveEncryptionDraft";
|
||||
|
||||
type Props = {
|
||||
settings: ApiSettings;
|
||||
scopeType: ArchiveEncryptionPolicyScope;
|
||||
canWrite: boolean;
|
||||
};
|
||||
|
||||
const METHODS: Array<{ id: ArchiveEncryptionMethod; label: string; description: string }> = [
|
||||
{ id: "aes", label: "AES (strong, default)", description: "Modern AES encryption for compatible ZIP clients." },
|
||||
{ id: "zip_standard", label: "Legacy ZipCrypto — Windows-compatible, weak encryption", description: "Requires a separate Campaign permission and reasoned acknowledgement." }
|
||||
];
|
||||
|
||||
const CHANNELS: Array<{ id: PasswordDeliveryChannel; label: string }> = [
|
||||
{ id: "separate_mail", label: "Separate email (never the campaign message)" },
|
||||
{ id: "sms", label: "SMS" },
|
||||
{ id: "letter", label: "Letter" },
|
||||
{ id: "phone", label: "Telephone" },
|
||||
{ id: "in_person", label: "In person" }
|
||||
];
|
||||
|
||||
export default function ArchiveEncryptionPoliciesPanel({ settings, scopeType, canWrite }: Props) {
|
||||
const [targets, setTargets] = useState<SearchableSelectOption[]>([]);
|
||||
const [targetId, setTargetId] = useState("");
|
||||
const [state, setState] = useState<ArchiveEncryptionPolicyResponse | null>(null);
|
||||
const [draft, setDraft] = useState<ArchiveEncryptionDraft | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
const needsTarget = scopeType === "group" || scopeType === "user";
|
||||
const dirty = Boolean(state && draft && stable(buildPolicy(draft)) !== stable(state.policy));
|
||||
|
||||
useUnsavedDraftGuard({ dirty, onSave: save, onDiscard: discard });
|
||||
|
||||
useEffect(() => { void initialize(); }, [scopeType, settings.accessToken, settings.apiBaseUrl, settings.apiKey]);
|
||||
|
||||
async function initialize() {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const loadedTargets = await loadTargets(settings, scopeType);
|
||||
setTargets(loadedTargets);
|
||||
const next = needsTarget ? loadedTargets[0]?.value ?? "" : "";
|
||||
setTargetId(next);
|
||||
if (!needsTarget || next) await load(next, false);
|
||||
} catch (cause) {
|
||||
setError(adminErrorMessage(cause));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function load(nextTarget = targetId, manageLoading = true) {
|
||||
if (needsTarget && !nextTarget) return;
|
||||
if (manageLoading) setLoading(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const loaded = await fetchArchiveEncryptionPolicy(settings, scopeType, nextTarget || null);
|
||||
setState(loaded);
|
||||
setDraft(draftFromPolicy(loaded.policy, loaded.parent_policy));
|
||||
} catch (cause) {
|
||||
setError(adminErrorMessage(cause));
|
||||
} finally {
|
||||
if (manageLoading) setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function selectTarget(value: string) {
|
||||
if (!value || value === targetId) return;
|
||||
setTargetId(value);
|
||||
await load(value);
|
||||
}
|
||||
|
||||
function discard() {
|
||||
if (state) setDraft(draftFromPolicy(state.policy, state.parent_policy));
|
||||
setError("");
|
||||
setSuccess("");
|
||||
}
|
||||
|
||||
async function save(): Promise<boolean> {
|
||||
if (!draft || !dirty) return true;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const loaded = await updateArchiveEncryptionPolicy(settings, scopeType, targetId || null, buildPolicy(draft));
|
||||
setState(loaded);
|
||||
setDraft(draftFromPolicy(loaded.policy, loaded.parent_policy));
|
||||
setSuccess("Campaign archive-encryption policy saved.");
|
||||
return true;
|
||||
} catch (cause) {
|
||||
setError(adminErrorMessage(cause));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const scopeLabel = scopeType[0].toUpperCase() + scopeType.slice(1);
|
||||
const parentMethods = state?.parent_policy.allowed_password_encryption_methods ?? ["aes"];
|
||||
const parentChannels = state?.parent_policy.allowed_password_delivery_channels ?? [];
|
||||
|
||||
return <AdminPageLayout
|
||||
title={`${scopeLabel} Campaign archive encryption`}
|
||||
description="Restrict password-protected ZIP methods and the separate channel used to convey passwords. Lower scopes can only narrow inherited choices."
|
||||
loading={loading}
|
||||
error={error}
|
||||
success={success}
|
||||
actions={<>
|
||||
<Button title="Reload saved archive policy" aria-label="Reload saved archive policy" onClick={() => void load()} disabled={loading || busy || (needsTarget && !targetId)}><RefreshCw size={16} /></Button>
|
||||
<Button onClick={discard} disabled={!dirty || busy}><Undo2 size={16} /> Discard</Button>
|
||||
<Button variant="primary" onClick={() => void save()} disabled={!canWrite || !dirty || busy}><Save size={16} /> {busy ? "Saving..." : "Save"}</Button>
|
||||
</>}>
|
||||
{needsTarget && <Card title={`${scopeLabel} target`}>
|
||||
<FormField label={`Select ${scopeType}`}>
|
||||
<SearchableSelect value={targetId} options={targets} onChange={(value) => void selectTarget(value)} disabled={busy} />
|
||||
</FormField>
|
||||
</Card>}
|
||||
{draft && state && <>
|
||||
<DismissibleAlert tone={state.effective_policy.allowed_password_encryption_methods.includes("zip_standard") ? "warning" : "info"} dismissible={false}>
|
||||
{state.effective_policy.reason} Legacy ZipCrypto remains a weak compatibility exception and is never an automatic fallback.
|
||||
</DismissibleAlert>
|
||||
<Card title="Allowed password-encryption methods">
|
||||
{scopeType !== "system" && <ToggleSwitch label="Inherit methods from the parent scope" checked={draft.inheritMethods} disabled={!canWrite || busy} onChange={(checked) => setDraft({ ...draft, inheritMethods: checked, methods: checked ? [...parentMethods] : draft.methods })} />}
|
||||
{METHODS.map((method) => <ToggleSwitch key={method.id} label={method.label} help={method.description} checked={draft.methods.includes(method.id)} disabled={!canWrite || busy || inheritedControlDisabled(scopeType, draft.inheritMethods) || (scopeType !== "system" && !parentMethods.includes(method.id))} onChange={(checked) => setDraft(setDraftMethod(draft, method.id, checked))} />)}
|
||||
</Card>
|
||||
<Card title="Allowed separate password-delivery channels">
|
||||
{scopeType !== "system" && <ToggleSwitch label="Inherit channels from the parent scope" checked={draft.inheritChannels} disabled={!canWrite || busy} onChange={(checked) => setDraft({ ...draft, inheritChannels: checked, channels: checked ? [...parentChannels] : draft.channels })} />}
|
||||
{CHANNELS.map((channel) => <ToggleSwitch key={channel.id} label={channel.label} checked={draft.channels.includes(channel.id)} disabled={!canWrite || busy || inheritedControlDisabled(scopeType, draft.inheritChannels) || (scopeType !== "system" && !parentChannels.includes(channel.id))} onChange={(checked) => setDraft(setDraftChannel(draft, channel.id, checked))} />)}
|
||||
</Card>
|
||||
<Card title="Effective policy evidence">
|
||||
<DescriptionList>
|
||||
<DescriptionItem term="Policy hash"><code>{state.effective_policy.policy_hash}</code></DescriptionItem>
|
||||
<DescriptionItem term="Source path">{state.effective_policy.source_path.map((step) => step.label).join(" → ")}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</Card>
|
||||
</>}
|
||||
</AdminPageLayout>;
|
||||
}
|
||||
|
||||
async function loadTargets(settings: ApiSettings, scope: ArchiveEncryptionPolicyScope): Promise<SearchableSelectOption[]> {
|
||||
if (scope === "group") {
|
||||
const response = await fetchGroupsDelta(settings, { limit: 1000 });
|
||||
return response.groups.map((group) => ({ value: group.id, label: group.name, description: group.slug }));
|
||||
}
|
||||
if (scope === "user") {
|
||||
const response = await fetchUsersDelta(settings, { limit: 1000 });
|
||||
return response.users.map((user) => ({ value: user.id, label: user.display_name || user.email, description: user.email }));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DescriptionList } from "@govoplan/core-webui";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
AdminPageLayout,
|
||||
@@ -188,8 +189,9 @@ export default function RetentionPoliciesPanel({ settings, scopeType, canWrite }
|
||||
return (
|
||||
<>
|
||||
<AdminPageLayout
|
||||
title={labels.title}
|
||||
title={labels.title} titleHelp={<DocumentationHelpLink reference={RETENTION_DOCUMENTATION} label="i18n:govoplan-core.open_admin_documentation.6adbdae3" />}
|
||||
description={labels.description}
|
||||
helpContextId="policy.retention"
|
||||
loading={loadingTargets}
|
||||
error={targetError || runError}
|
||||
success={success}
|
||||
@@ -199,6 +201,7 @@ export default function RetentionPoliciesPanel({ settings, scopeType, canWrite }
|
||||
<Button
|
||||
title="Reload policy targets"
|
||||
aria-label="Reload policy targets"
|
||||
helpContextId="policy.retention.action.reload-targets"
|
||||
onClick={() => void loadTargets()}
|
||||
disabled={loadingTargets}
|
||||
disabledReason={loadingTargets ? "Policy targets are already loading." : undefined}
|
||||
@@ -206,7 +209,7 @@ export default function RetentionPoliciesPanel({ settings, scopeType, canWrite }
|
||||
<RefreshCw size={16} />
|
||||
</Button>
|
||||
)}
|
||||
<DocumentationHelpLink reference={RETENTION_DOCUMENTATION} label="i18n:govoplan-core.open_admin_documentation.6adbdae3" />
|
||||
|
||||
</>
|
||||
}
|
||||
>
|
||||
@@ -223,25 +226,26 @@ export default function RetentionPoliciesPanel({ settings, scopeType, canWrite }
|
||||
{scopeType === "system" && (
|
||||
<div className="retention-run-section">
|
||||
<Card
|
||||
title="Retention execution"
|
||||
actions={<DocumentationHelpLink reference={RETENTION_DOCUMENTATION} label="i18n:govoplan-core.open_admin_documentation.6adbdae3" />}
|
||||
title="Retention execution" titleHelp={<DocumentationHelpLink reference={RETENTION_DOCUMENTATION} label="i18n:govoplan-core.open_admin_documentation.6adbdae3" />}
|
||||
helpContextId="policy.retention.execution"
|
||||
|
||||
>
|
||||
<p className="muted small-note">Run the saved effective retention policy against retained platform data.</p>
|
||||
<div className="button-row compact-actions subsection-bottom-actions">
|
||||
<Button onClick={() => void runRetention(true)} disabled={Boolean(actionDisabledReason)} disabledReason={actionDisabledReason}>Dry run</Button>
|
||||
<Button variant="danger" onClick={() => setConfirmRetentionRun(true)} disabled={Boolean(actionDisabledReason)} disabledReason={actionDisabledReason}>Apply retention</Button>
|
||||
<Button helpContextId="policy.retention.action.dry-run" onClick={() => void runRetention(true)} disabled={Boolean(actionDisabledReason)} disabledReason={actionDisabledReason}>Dry run</Button>
|
||||
<Button helpContextId="policy.retention.action.apply" variant="danger" onClick={() => setConfirmRetentionRun(true)} disabled={Boolean(actionDisabledReason)} disabledReason={actionDisabledReason}>Apply retention</Button>
|
||||
</div>
|
||||
</Card>
|
||||
{retentionResult && (
|
||||
<Card title="Latest retention outcome">
|
||||
<dl className="detail-list compact-detail-list">
|
||||
<Card title="Latest retention outcome" helpContextId="policy.retention.outcome">
|
||||
<DescriptionList variant="inline" density="compact">
|
||||
<div>
|
||||
<dt>Operation</dt>
|
||||
<dd><StatusBadge status={retentionResult.result.dry_run ? "info" : "success"} label={retentionResult.result.dry_run ? "Dry run" : "Applied"} /></dd>
|
||||
</div>
|
||||
<div><dt>Policy scope</dt><dd>{humanize(retentionResult.result.effective_policy_scope || "system")}</dd></div>
|
||||
<div><dt>Reported outcomes</dt><dd>{resultRows.length}</dd></div>
|
||||
</dl>
|
||||
</DescriptionList>
|
||||
<div className="admin-table-surface">
|
||||
<DataGrid
|
||||
id="policy-retention-outcomes"
|
||||
@@ -259,6 +263,8 @@ export default function RetentionPoliciesPanel({ settings, scopeType, canWrite }
|
||||
</AdminPageLayout>
|
||||
<ConfirmDialog
|
||||
open={confirmRetentionRun}
|
||||
helpContextId="policy.retention.confirm-apply"
|
||||
helpModuleId="policy"
|
||||
title="Apply retention policy"
|
||||
message="This will redact or delete eligible retained data according to the saved policy. The application cannot restore deleted content; the run and bounded outcome counts remain in audit evidence. Run a dry run first and verify recovery evidence before continuing."
|
||||
confirmLabel="Apply retention"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DescriptionItem, DescriptionList } from "@govoplan/core-webui";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
AdminPageLayout,
|
||||
@@ -18,14 +19,16 @@ import {
|
||||
type ReferenceOption,
|
||||
type SearchableSelectOption
|
||||
} from "@govoplan/core-webui";
|
||||
import { RefreshCw, Save, Trash2, Undo2 } from "lucide-react";
|
||||
import { RefreshCw, Save, ScanSearch, Trash2, Undo2 } from "lucide-react";
|
||||
import { fetchGroupsDelta, fetchUsersDelta } from "../../api/adminTargets";
|
||||
import {
|
||||
deleteViewPolicy,
|
||||
fetchViewPolicy,
|
||||
fetchViewPolicyReferences,
|
||||
previewViewPolicyImpact,
|
||||
updateViewPolicy,
|
||||
type EffectiveViewPolicy,
|
||||
type PolicyImpactPreviewResponse,
|
||||
type ViewPolicyItem,
|
||||
type ViewPolicyScope,
|
||||
type ViewPolicyScopeResponse
|
||||
@@ -90,6 +93,9 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
const [error, setError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
const [confirmReset, setConfirmReset] = useState(false);
|
||||
const [impactPreview, setImpactPreview] = useState<PolicyImpactPreviewResponse | null>(null);
|
||||
const [previewDraftKey, setPreviewDraftKey] = useState("");
|
||||
const [resetImpactPreview, setResetImpactPreview] = useState<PolicyImpactPreviewResponse | null>(null);
|
||||
|
||||
const needsTarget = scopeType === "group" || scopeType === "user";
|
||||
const parentViewIds = state?.parent_policy.allowed_view_ids;
|
||||
@@ -108,6 +114,8 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
&& stablePolicy(buildPolicy(draft))
|
||||
!== stablePolicy(buildPolicy(draftFromPolicy(state.policy)))
|
||||
);
|
||||
const draftKey = draft ? stablePolicy(buildPolicy(draft)) : "";
|
||||
const previewCurrent = Boolean(impactPreview && previewDraftKey === draftKey);
|
||||
|
||||
useUnsavedDraftGuard({ dirty, onSave: save, onDiscard: discard });
|
||||
|
||||
@@ -164,6 +172,9 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
const loaded = await fetchViewPolicy(settings, scopeType, nextTargetId || null);
|
||||
setState(loaded);
|
||||
setDraft(draftFromPolicy(loaded.policy));
|
||||
setImpactPreview(null);
|
||||
setPreviewDraftKey("");
|
||||
setResetImpactPreview(null);
|
||||
} catch (err) {
|
||||
setError(adminErrorMessage(err));
|
||||
} finally {
|
||||
@@ -179,19 +190,63 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
|
||||
function discard() {
|
||||
if (state) setDraft(draftFromPolicy(state.policy));
|
||||
setImpactPreview(null);
|
||||
setPreviewDraftKey("");
|
||||
setResetImpactPreview(null);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
}
|
||||
|
||||
async function save(): Promise<boolean> {
|
||||
if (!draft || !state || !dirty) return true;
|
||||
async function previewImpact() {
|
||||
if (!draft || !state || !dirty) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const loaded = await updateViewPolicy(settings, scopeType, targetId || null, buildPolicy(draft));
|
||||
const policy = buildPolicy(draft);
|
||||
const preview = await previewViewPolicyImpact(
|
||||
settings,
|
||||
scopeType,
|
||||
targetId || null,
|
||||
policy,
|
||||
{
|
||||
viewIds: viewOptions.map((option) => option.value),
|
||||
surfaceIds: surfaceOptions.map((option) => option.value)
|
||||
}
|
||||
);
|
||||
setImpactPreview(preview);
|
||||
setPreviewDraftKey(stablePolicy(policy));
|
||||
setSuccess("Policy impact preview completed without saving the draft.");
|
||||
} catch (err) {
|
||||
setImpactPreview(null);
|
||||
setPreviewDraftKey("");
|
||||
setError(adminErrorMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function save(): Promise<boolean> {
|
||||
if (!draft || !state || !dirty) return true;
|
||||
if (!previewCurrent) {
|
||||
setError("Preview the current policy draft before saving it.");
|
||||
return false;
|
||||
}
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const loaded = await updateViewPolicy(
|
||||
settings,
|
||||
scopeType,
|
||||
targetId || null,
|
||||
buildPolicy(draft),
|
||||
impactPreview
|
||||
);
|
||||
setState(loaded);
|
||||
setDraft(draftFromPolicy(loaded.policy));
|
||||
setImpactPreview(null);
|
||||
setPreviewDraftKey("");
|
||||
setSuccess("View policy saved.");
|
||||
return true;
|
||||
} catch (err) {
|
||||
@@ -202,14 +257,50 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
}
|
||||
}
|
||||
|
||||
async function resetPolicy() {
|
||||
async function prepareResetPolicy() {
|
||||
if (!state?.id) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const loaded = await deleteViewPolicy(settings, scopeType, targetId || null);
|
||||
const preview = await previewViewPolicyImpact(
|
||||
settings,
|
||||
scopeType,
|
||||
targetId || null,
|
||||
{},
|
||||
{
|
||||
viewIds: viewOptions.map((option) => option.value),
|
||||
surfaceIds: surfaceOptions.map((option) => option.value)
|
||||
}
|
||||
);
|
||||
setResetImpactPreview(preview);
|
||||
setConfirmReset(true);
|
||||
setSuccess("Inherited-policy impact preview completed without removing the override.");
|
||||
} catch (err) {
|
||||
setResetImpactPreview(null);
|
||||
setError(adminErrorMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function resetPolicy() {
|
||||
if (!resetImpactPreview) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
try {
|
||||
const loaded = await deleteViewPolicy(
|
||||
settings,
|
||||
scopeType,
|
||||
targetId || null,
|
||||
resetImpactPreview
|
||||
);
|
||||
setState(loaded);
|
||||
setDraft(draftFromPolicy(loaded.policy));
|
||||
setImpactPreview(null);
|
||||
setPreviewDraftKey("");
|
||||
setResetImpactPreview(null);
|
||||
setSuccess("Local View policy removed; inherited policy now applies.");
|
||||
setConfirmReset(false);
|
||||
} catch (err) {
|
||||
@@ -224,7 +315,7 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
return (
|
||||
<>
|
||||
<AdminPageLayout
|
||||
title={`${scopeLabel} View policy`}
|
||||
title={`${scopeLabel} View policy`} titleHelp={<DocumentationHelpLink reference={DOCUMENTATION} label="Open View policy documentation" />}
|
||||
description="Control which Views and surfaces are available, forced by assignment, selectable, editable, derivable, or workflow-activatable at this scope."
|
||||
loading={loading}
|
||||
error={error}
|
||||
@@ -235,9 +326,10 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
<RefreshCw size={16} />
|
||||
</Button>
|
||||
<Button onClick={discard} disabled={!dirty || busy}><Undo2 size={16} /> Discard</Button>
|
||||
<Button onClick={() => setConfirmReset(true)} disabled={!canWrite || !state?.id || busy}><Trash2 size={16} /> Use inherited</Button>
|
||||
<Button variant="primary" onClick={() => void save()} disabled={!canWrite || !dirty || busy}><Save size={16} /> {busy ? "Saving..." : "Save"}</Button>
|
||||
<DocumentationHelpLink reference={DOCUMENTATION} label="Open View policy documentation" />
|
||||
<Button onClick={() => void prepareResetPolicy()} disabled={!canWrite || !state?.id || busy}><Trash2 size={16} /> Use inherited</Button>
|
||||
<Button helpContextId="policy.impact-preview.action.preview" onClick={() => void previewImpact()} disabled={!canWrite || !dirty || busy}><ScanSearch size={16} /> Preview impact</Button>
|
||||
<Button variant="primary" onClick={() => void save()} disabled={!canWrite || !dirty || busy || !previewCurrent} disabledReason={dirty && !previewCurrent ? "Preview the current draft before saving." : undefined}><Save size={16} /> {busy ? "Working..." : "Save"}</Button>
|
||||
|
||||
</>
|
||||
}
|
||||
>
|
||||
@@ -333,13 +425,42 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
</Card>
|
||||
|
||||
<Card title="Effective policy and provenance">
|
||||
<dl className="admin-details-grid">
|
||||
<div><dt>Local override</dt><dd><StatusBadge status={state.id ? "info" : "neutral"} label={state.id ? `Revision ${state.revision}` : "Inherited"} /></dd></div>
|
||||
<div><dt>Allowed Views</dt><dd>{ceilingLabel(state.effective_policy.allowed_view_ids)}</dd></div>
|
||||
<div><dt>Visible surfaces</dt><dd>{ceilingLabel(state.effective_policy.visible_surface_ids)}</dd></div>
|
||||
<div><dt>Policy path</dt><dd>{state.source_path.length ? state.source_path.map((step) => `${step.scope_type}${step.scope_id ? `:${step.scope_id}` : ""}`).join(" -> ") : "Platform defaults"}</dd></div>
|
||||
</dl>
|
||||
<DescriptionList>
|
||||
<DescriptionItem term={<>Local override</>}><StatusBadge status={state.id ? "info" : "neutral"} label={state.id ? `Revision ${state.revision}` : "Inherited"} /></DescriptionItem>
|
||||
<DescriptionItem term={<>Allowed Views</>}>{ceilingLabel(state.effective_policy.allowed_view_ids)}</DescriptionItem>
|
||||
<DescriptionItem term={<>Visible surfaces</>}>{ceilingLabel(state.effective_policy.visible_surface_ids)}</DescriptionItem>
|
||||
<DescriptionItem term={<>Policy path</>}>{state.source_path.length ? state.source_path.map((step) => `${step.scope_type}${step.scope_id ? `:${step.scope_id}` : ""}`).join(" -> ") : "Platform defaults"}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</Card>
|
||||
|
||||
{impactPreview && (
|
||||
<Card title="Policy impact preview">
|
||||
<DescriptionList>
|
||||
<DescriptionItem term={<>Preview</>}><code>{impactPreview.preview_id}</code></DescriptionItem>
|
||||
<DescriptionItem term={<>Draft state</>}><StatusBadge status={previewCurrent ? "success" : "warning"} label={previewCurrent ? "Current" : "Outdated"} /></DescriptionItem>
|
||||
<DescriptionItem term={<>Newly allowed</>}>{impactPreview.counts.newly_allowed}</DescriptionItem>
|
||||
<DescriptionItem term={<>Newly denied</>}>{impactPreview.counts.newly_denied}</DescriptionItem>
|
||||
<DescriptionItem term={<>Unchanged</>}>{impactPreview.counts.unchanged}</DescriptionItem>
|
||||
<DescriptionItem term={<>Indeterminate</>}>{impactPreview.counts.indeterminate}</DescriptionItem>
|
||||
<DescriptionItem term={<>Risk</>}><StatusBadge status={impactPreview.high_impact ? "warning" : "neutral"} label={impactPreview.high_impact ? "High impact - recent login required" : "Bounded change"} /></DescriptionItem>
|
||||
<DescriptionItem term={<>Coverage</>}>{impactPreview.populations.map((population) => `${population.provider_id}: ${population.state} (${population.returned}${population.total_available == null ? "" : `/${population.total_available}`})${population.explanation ? ` - ${population.explanation}` : ""}`).join("; ")}</DescriptionItem>
|
||||
{impactPreview.details_hidden && <DescriptionItem term={<>Details</>}>{impactPreview.details_explanation || "Subject details are hidden by policy."}</DescriptionItem>}
|
||||
</DescriptionList>
|
||||
{impactPreview.effects.length > 0 && (
|
||||
<div help-context-id="policy.impact-preview.results">
|
||||
<h4>Changed subjects</h4>
|
||||
<ul>
|
||||
{impactPreview.effects.filter((effect) => effect.category !== "unchanged").slice(0, 20).map((effect) => (
|
||||
<li key={`${effect.subject.module_id}:${effect.subject.resource_type}:${effect.subject.resource_id}:${effect.subject.action}`}>
|
||||
<strong>{effect.category.replaceAll("_", " ")}</strong>: {effect.subject.label || effect.subject.resource_id} - {effect.subject.action} ({effect.rule})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{impactPreview.effects.filter((effect) => effect.category !== "unchanged").length > 20 && <p>Only the first 20 changed subjects are shown; aggregate counts cover the complete returned population.</p>}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</AdminPageLayout>
|
||||
@@ -347,11 +468,14 @@ export default function ViewPoliciesPanel({ settings, scopeType, canWrite }: Pro
|
||||
<ConfirmDialog
|
||||
open={confirmReset}
|
||||
title="Use inherited View policy?"
|
||||
message="The local override will be removed. All restrictions inherited from higher scopes continue to apply."
|
||||
message={resetImpactPreview ? `The local override will be removed. The bounded preview found ${resetImpactPreview.counts.newly_allowed} newly allowed, ${resetImpactPreview.counts.newly_denied} newly denied, and ${resetImpactPreview.counts.indeterminate} indeterminate effects. All restrictions inherited from higher scopes continue to apply.` : "Previewing inherited-policy impact..."}
|
||||
confirmLabel="Use inherited policy"
|
||||
busy={busy}
|
||||
onConfirm={() => void resetPolicy()}
|
||||
onCancel={() => setConfirmReset(false)}
|
||||
onCancel={() => {
|
||||
setConfirmReset(false);
|
||||
setResetImpactPreview(null);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import type {
|
||||
ArchiveEncryptionMethod,
|
||||
ArchiveEncryptionPolicyItem,
|
||||
ArchiveEncryptionPolicyResponse,
|
||||
ArchiveEncryptionPolicyScope,
|
||||
PasswordDeliveryChannel
|
||||
} from "../../api/archiveEncryptionPolicies";
|
||||
|
||||
export type ArchiveEncryptionDraft = {
|
||||
inheritMethods: boolean;
|
||||
methods: ArchiveEncryptionMethod[];
|
||||
inheritChannels: boolean;
|
||||
channels: PasswordDeliveryChannel[];
|
||||
};
|
||||
|
||||
export function draftFromPolicy(policy: ArchiveEncryptionPolicyItem, parent: ArchiveEncryptionPolicyResponse["parent_policy"]): ArchiveEncryptionDraft {
|
||||
return {
|
||||
inheritMethods: policy.allowed_password_encryption_methods === undefined,
|
||||
methods: [...(policy.allowed_password_encryption_methods ?? parent.allowed_password_encryption_methods)],
|
||||
inheritChannels: policy.allowed_password_delivery_channels === undefined,
|
||||
channels: [...(policy.allowed_password_delivery_channels ?? parent.allowed_password_delivery_channels)]
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPolicy(draft: ArchiveEncryptionDraft): ArchiveEncryptionPolicyItem {
|
||||
return {
|
||||
...(draft.inheritMethods ? {} : { allowed_password_encryption_methods: draft.methods }),
|
||||
...(draft.inheritChannels ? {} : { allowed_password_delivery_channels: draft.channels })
|
||||
};
|
||||
}
|
||||
|
||||
export function stable(value: ArchiveEncryptionPolicyItem): string {
|
||||
return JSON.stringify({
|
||||
methods: value.allowed_password_encryption_methods ? [...value.allowed_password_encryption_methods].sort() : null,
|
||||
channels: value.allowed_password_delivery_channels ? [...value.allowed_password_delivery_channels].sort() : null
|
||||
});
|
||||
}
|
||||
|
||||
/** System defaults are editable even before the first explicit override exists. */
|
||||
export function inheritedControlDisabled(scope: ArchiveEncryptionPolicyScope, inherited: boolean): boolean {
|
||||
return scope !== "system" && inherited;
|
||||
}
|
||||
|
||||
export function setDraftMethod(draft: ArchiveEncryptionDraft, method: ArchiveEncryptionMethod, checked: boolean): ArchiveEncryptionDraft {
|
||||
return { ...draft, inheritMethods: false, methods: toggle(draft.methods, method, checked) };
|
||||
}
|
||||
|
||||
export function setDraftChannel(draft: ArchiveEncryptionDraft, channel: PasswordDeliveryChannel, checked: boolean): ArchiveEncryptionDraft {
|
||||
return { ...draft, inheritChannels: false, channels: toggle(draft.channels, channel, checked) };
|
||||
}
|
||||
|
||||
function toggle<T extends string>(values: T[], value: T, checked: boolean): T[] {
|
||||
return checked ? Array.from(new Set([...values, value])) : values.filter((item) => item !== value);
|
||||
}
|
||||
@@ -3,4 +3,5 @@ export { default as ViewPoliciesPanel } from "./features/policy/ViewPoliciesPane
|
||||
export * from "./module";
|
||||
export * from "./api/adminTargets";
|
||||
export { default as RetentionPoliciesPanel } from "./features/policy/RetentionPoliciesPanel";
|
||||
export { default as ArchiveEncryptionPoliciesPanel } from "./features/policy/ArchiveEncryptionPoliciesPanel";
|
||||
export type { PlatformWebModule } from "@govoplan/core-webui";
|
||||
|
||||
@@ -3,6 +3,7 @@ import { hasScope, type AdminSectionsUiCapability, type PlatformWebModule } from
|
||||
|
||||
const RetentionPoliciesPanel = lazy(() => import("./features/policy/RetentionPoliciesPanel"));
|
||||
const ViewPoliciesPanel = lazy(() => import("./features/policy/ViewPoliciesPanel"));
|
||||
const ArchiveEncryptionPoliciesPanel = lazy(() => import("./features/policy/ArchiveEncryptionPoliciesPanel"));
|
||||
|
||||
const policyAdminSections: AdminSectionsUiCapability = {
|
||||
sections: [
|
||||
@@ -66,6 +67,66 @@ const policyAdminSections: AdminSectionsUiCapability = {
|
||||
canWrite: hasScope(auth, "admin:policies:write")
|
||||
})
|
||||
},
|
||||
{
|
||||
id: "system-campaign-archive-encryption",
|
||||
moduleId: "policy",
|
||||
kind: "settings",
|
||||
surfaceId: "policy.admin.system-campaign-archive-encryption",
|
||||
label: "Campaign archive encryption",
|
||||
group: "SYSTEM",
|
||||
order: 75,
|
||||
allOf: ["admin:policies:read"],
|
||||
render: ({ settings, auth }) => createElement(ArchiveEncryptionPoliciesPanel, {
|
||||
settings,
|
||||
scopeType: "system",
|
||||
canWrite: hasScope(auth, "system:settings:write") && hasScope(auth, "admin:policies:write")
|
||||
})
|
||||
},
|
||||
{
|
||||
id: "tenant-campaign-archive-encryption",
|
||||
moduleId: "policy",
|
||||
kind: "settings",
|
||||
surfaceId: "policy.admin.tenant-campaign-archive-encryption",
|
||||
label: "Campaign archive encryption",
|
||||
group: "TENANT",
|
||||
order: 75,
|
||||
allOf: ["admin:policies:read"],
|
||||
render: ({ settings, auth }) => createElement(ArchiveEncryptionPoliciesPanel, {
|
||||
settings,
|
||||
scopeType: "tenant",
|
||||
canWrite: hasScope(auth, "admin:policies:write")
|
||||
})
|
||||
},
|
||||
{
|
||||
id: "group-campaign-archive-encryption",
|
||||
moduleId: "policy",
|
||||
kind: "settings",
|
||||
surfaceId: "policy.admin.group-campaign-archive-encryption",
|
||||
label: "Campaign archive encryption",
|
||||
group: "GROUP",
|
||||
order: 25,
|
||||
allOf: ["admin:policies:read", "admin:groups:read"],
|
||||
render: ({ settings, auth }) => createElement(ArchiveEncryptionPoliciesPanel, {
|
||||
settings,
|
||||
scopeType: "group",
|
||||
canWrite: hasScope(auth, "admin:policies:write")
|
||||
})
|
||||
},
|
||||
{
|
||||
id: "user-campaign-archive-encryption",
|
||||
moduleId: "policy",
|
||||
kind: "settings",
|
||||
surfaceId: "policy.admin.user-campaign-archive-encryption",
|
||||
label: "Campaign archive encryption",
|
||||
group: "USER",
|
||||
order: 25,
|
||||
allOf: ["admin:policies:read", "admin:users:read"],
|
||||
render: ({ settings, auth }) => createElement(ArchiveEncryptionPoliciesPanel, {
|
||||
settings,
|
||||
scopeType: "user",
|
||||
canWrite: hasScope(auth, "admin:policies:write")
|
||||
})
|
||||
},
|
||||
{
|
||||
id: "system-retention",
|
||||
moduleId: "policy",
|
||||
@@ -139,6 +200,10 @@ export const policyModule: PlatformWebModule = {
|
||||
{ id: "policy.admin.tenant-view-policy", moduleId: "policy", kind: "section", label: "Tenant View policy", order: 70 },
|
||||
{ id: "policy.admin.group-view-policy", moduleId: "policy", kind: "section", label: "Group View policy", order: 70 },
|
||||
{ id: "policy.admin.user-view-policy", moduleId: "policy", kind: "section", label: "User View policy", order: 70 },
|
||||
{ id: "policy.admin.system-campaign-archive-encryption", moduleId: "policy", kind: "section", label: "System Campaign archive encryption", order: 75 },
|
||||
{ id: "policy.admin.tenant-campaign-archive-encryption", moduleId: "policy", kind: "section", label: "Tenant Campaign archive encryption", order: 75 },
|
||||
{ id: "policy.admin.group-campaign-archive-encryption", moduleId: "policy", kind: "section", label: "Group Campaign archive encryption", order: 75 },
|
||||
{ id: "policy.admin.user-campaign-archive-encryption", moduleId: "policy", kind: "section", label: "User Campaign archive encryption", order: 75 },
|
||||
{ id: "policy.admin.system-retention", moduleId: "policy", kind: "section", label: "System retention", order: 80 },
|
||||
{ id: "policy.admin.tenant-retention", moduleId: "policy", kind: "section", label: "Tenant retention", order: 80 },
|
||||
{ id: "policy.admin.group-retention", moduleId: "policy", kind: "section", label: "Group retention", order: 80 },
|
||||
|
||||
Reference in New Issue
Block a user