feat(identity-trust): add governed DSAR coverage
This commit is contained in:
@@ -0,0 +1,461 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
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_identity_trust.backend.db.models import (
|
||||
AssuranceEvidence,
|
||||
DevicePublicKey,
|
||||
KeyAccessDecisionRecord,
|
||||
TrustKeyEpoch,
|
||||
)
|
||||
|
||||
|
||||
IDENTITY_TRUST_DSAR_CAPABILITY = dsar_capability_name("identity_trust")
|
||||
_MAX_RECORDS = 5_000
|
||||
_CONFLICT = object()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _SubjectSelectors:
|
||||
account_id: str | None
|
||||
identity_id: str | None
|
||||
device_id: str | None
|
||||
key_id: str | None
|
||||
|
||||
|
||||
class IdentityTrustDsarProvider:
|
||||
provider_id = "identity_trust"
|
||||
module_id = "identity_trust"
|
||||
|
||||
def search_subject(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
tenant_id: str,
|
||||
subject: DsarSubjectRef,
|
||||
) -> Sequence[DsarRecordRef]:
|
||||
db = _session(session)
|
||||
selectors = _subject_selectors(subject)
|
||||
if selectors is None:
|
||||
return ()
|
||||
|
||||
devices = db.query(DevicePublicKey).filter(
|
||||
DevicePublicKey.tenant_id == tenant_id
|
||||
)
|
||||
if selectors.account_id:
|
||||
devices = devices.filter(
|
||||
DevicePublicKey.account_id == selectors.account_id
|
||||
)
|
||||
if selectors.identity_id:
|
||||
devices = devices.filter(
|
||||
DevicePublicKey.identity_id == selectors.identity_id
|
||||
)
|
||||
if selectors.device_id:
|
||||
devices = devices.filter(DevicePublicKey.device_id == selectors.device_id)
|
||||
if selectors.key_id:
|
||||
devices = devices.filter(DevicePublicKey.key_id == selectors.key_id)
|
||||
records: list[DsarRecordRef] = [
|
||||
_device_record(row)
|
||||
for row in _limited(
|
||||
devices,
|
||||
DevicePublicKey.registered_at,
|
||||
DevicePublicKey.id,
|
||||
label="device key",
|
||||
)
|
||||
]
|
||||
|
||||
if selectors.account_id:
|
||||
assurances = db.query(AssuranceEvidence).filter(
|
||||
AssuranceEvidence.tenant_id == tenant_id,
|
||||
AssuranceEvidence.account_id == selectors.account_id,
|
||||
)
|
||||
if selectors.key_id:
|
||||
assurances = assurances.filter(
|
||||
AssuranceEvidence.device_key_id == selectors.key_id
|
||||
)
|
||||
records.extend(
|
||||
_assurance_record(row)
|
||||
for row in _limited(
|
||||
assurances,
|
||||
AssuranceEvidence.verified_at,
|
||||
AssuranceEvidence.id,
|
||||
label="assurance evidence",
|
||||
)
|
||||
)
|
||||
decisions = db.query(KeyAccessDecisionRecord).filter(
|
||||
KeyAccessDecisionRecord.tenant_id == tenant_id,
|
||||
KeyAccessDecisionRecord.account_id == selectors.account_id,
|
||||
)
|
||||
if selectors.key_id:
|
||||
decisions = decisions.filter(
|
||||
KeyAccessDecisionRecord.device_key_id == selectors.key_id
|
||||
)
|
||||
records.extend(
|
||||
_access_decision_record(row)
|
||||
for row in _limited(
|
||||
decisions,
|
||||
KeyAccessDecisionRecord.created_at,
|
||||
KeyAccessDecisionRecord.id,
|
||||
label="key-access decision",
|
||||
)
|
||||
)
|
||||
|
||||
subject_conditions = []
|
||||
if selectors.device_id:
|
||||
subject_conditions.append(
|
||||
(TrustKeyEpoch.subject_kind == "device")
|
||||
& (TrustKeyEpoch.subject_id == selectors.device_id)
|
||||
)
|
||||
elif not selectors.key_id:
|
||||
if selectors.account_id:
|
||||
subject_conditions.append(
|
||||
(TrustKeyEpoch.subject_kind == "account")
|
||||
& (TrustKeyEpoch.subject_id == selectors.account_id)
|
||||
)
|
||||
if selectors.identity_id:
|
||||
subject_conditions.append(
|
||||
(TrustKeyEpoch.subject_kind == "identity")
|
||||
& (TrustKeyEpoch.subject_id == selectors.identity_id)
|
||||
)
|
||||
if subject_conditions:
|
||||
epochs = db.query(TrustKeyEpoch).filter(
|
||||
TrustKeyEpoch.tenant_id == tenant_id,
|
||||
or_(*subject_conditions),
|
||||
)
|
||||
records.extend(
|
||||
_epoch_record(row)
|
||||
for row in _limited(
|
||||
epochs,
|
||||
TrustKeyEpoch.effective_at,
|
||||
TrustKeyEpoch.id,
|
||||
label="key epoch",
|
||||
)
|
||||
)
|
||||
|
||||
if len(records) > _MAX_RECORDS:
|
||||
raise ValueError(
|
||||
"Identity Trust DSAR result limit exceeded; narrow the selectors."
|
||||
)
|
||||
return tuple(
|
||||
sorted(records, key=lambda item: (item.resource_type, item.resource_id))
|
||||
)
|
||||
|
||||
def plan_erasure(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
tenant_id: str,
|
||||
subject: DsarSubjectRef,
|
||||
records: Sequence[DsarRecordRef],
|
||||
) -> Sequence[DsarErasureActionRef]:
|
||||
del tenant_id
|
||||
_session(session)
|
||||
if _subject_selectors(subject) is None:
|
||||
raise ValueError("Identity Trust DSAR subject selectors conflict.")
|
||||
actions: list[DsarErasureActionRef] = []
|
||||
for record in records:
|
||||
_validate_record(record)
|
||||
device = record.resource_type == "device_public_key"
|
||||
actions.append(
|
||||
DsarErasureActionRef(
|
||||
action_id=(
|
||||
f"identity_trust:{'manual_review' if device else 'retain'}:"
|
||||
f"{record.resource_type}:{record.resource_id}"
|
||||
),
|
||||
provider_id=self.provider_id,
|
||||
module_id=self.module_id,
|
||||
kind="manual_review" if device else "retain",
|
||||
resource_type=record.resource_type,
|
||||
resource_id=record.resource_id,
|
||||
title=("Review " if device else "Retain ") + record.title,
|
||||
rationale=(
|
||||
"Revocation or removal must account for encrypted-resource "
|
||||
"recovery, active sessions, and the current key epoch."
|
||||
if device
|
||||
else record.retention_reason
|
||||
or "Trust and access evidence remains immutable."
|
||||
),
|
||||
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 _subject_selectors(subject) is None:
|
||||
raise ValueError("Identity Trust DSAR subject selectors conflict.")
|
||||
results: list[DsarExecutionResultRef] = []
|
||||
for action in actions:
|
||||
_validate_action(action)
|
||||
if action.executable or action.kind not in {"manual_review", "retain"}:
|
||||
raise ValueError(
|
||||
"Identity Trust DSAR publishes non-executable actions only."
|
||||
)
|
||||
results.append(
|
||||
DsarExecutionResultRef(
|
||||
action_id=action.action_id,
|
||||
status="blocked",
|
||||
summary=(
|
||||
"The device key remains unchanged pending cryptographic "
|
||||
"recovery and revocation review."
|
||||
if action.kind == "manual_review"
|
||||
else "Trust and key-access evidence remains immutable."
|
||||
),
|
||||
evidence={"request_id": request_id},
|
||||
)
|
||||
)
|
||||
return tuple(results)
|
||||
|
||||
|
||||
def _subject_selectors(subject: DsarSubjectRef) -> _SubjectSelectors | None:
|
||||
references = subject.external_references
|
||||
values = {
|
||||
"account_id": _coalesce(
|
||||
subject.account_id,
|
||||
references.get("identity_trust.account"),
|
||||
references.get("access.account"),
|
||||
),
|
||||
"identity_id": _coalesce(
|
||||
subject.identity_id,
|
||||
references.get("identity_trust.identity"),
|
||||
references.get("identity.id"),
|
||||
),
|
||||
"device_id": _coalesce(
|
||||
references.get("identity_trust.device"),
|
||||
references.get("identity_trust.device_id"),
|
||||
),
|
||||
"key_id": _coalesce(
|
||||
references.get("identity_trust.key"),
|
||||
references.get("identity_trust.key_id"),
|
||||
),
|
||||
}
|
||||
if any(value is _CONFLICT for value in values.values()):
|
||||
return None
|
||||
account_id = _optional_string(values["account_id"])
|
||||
identity_id = _optional_string(values["identity_id"])
|
||||
if not (account_id or identity_id):
|
||||
return None
|
||||
return _SubjectSelectors(
|
||||
account_id=account_id,
|
||||
identity_id=identity_id,
|
||||
device_id=_optional_string(values["device_id"]),
|
||||
key_id=_optional_string(values["key_id"]),
|
||||
)
|
||||
|
||||
|
||||
def _limited(query, first, second, *, label: str):
|
||||
rows = query.order_by(first, second).limit(_MAX_RECORDS + 1).all()
|
||||
if len(rows) > _MAX_RECORDS:
|
||||
raise ValueError(
|
||||
f"Identity Trust DSAR {label} limit exceeded; narrow the selectors."
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _device_record(row: DevicePublicKey) -> DsarRecordRef:
|
||||
return DsarRecordRef(
|
||||
provider_id="identity_trust",
|
||||
module_id="identity_trust",
|
||||
resource_type="device_public_key",
|
||||
resource_id=row.id,
|
||||
category="personal_device_trust",
|
||||
title=f"Device public key {row.key_id[:255]}",
|
||||
data={
|
||||
"identity_id": row.identity_id,
|
||||
"account_id": row.account_id,
|
||||
"device_id": row.device_id,
|
||||
"key_id": row.key_id,
|
||||
"algorithm": row.algorithm,
|
||||
"public_jwk": _public_jwk(row.public_jwk),
|
||||
"purpose": row.purpose,
|
||||
"assurance_level": row.assurance_level,
|
||||
"attestation_ref": (row.attestation_ref or "")[:1_000] or None,
|
||||
"status": row.status,
|
||||
"epoch": row.epoch,
|
||||
"registered_at": _iso(row.registered_at),
|
||||
"expires_at": _iso(row.expires_at),
|
||||
"revoked_at": _iso(row.revoked_at),
|
||||
"revocation_reason": (row.revocation_reason or "")[:4_000] or None,
|
||||
},
|
||||
observed_at=_aware(row.updated_at),
|
||||
retention_reason=(
|
||||
"Device-key changes require recovery and active-resource review."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _assurance_record(row: AssuranceEvidence) -> DsarRecordRef:
|
||||
return DsarRecordRef(
|
||||
provider_id="identity_trust",
|
||||
module_id="identity_trust",
|
||||
resource_type="assurance_evidence",
|
||||
resource_id=row.id,
|
||||
category="identity_assurance_evidence",
|
||||
title="Identity assurance evidence",
|
||||
data={
|
||||
"account_id": row.account_id,
|
||||
"device_key_id": row.device_key_id,
|
||||
"evidence_ref": row.evidence_ref[:1_000],
|
||||
"assurance_level": row.assurance_level,
|
||||
"provider_id": row.provider_id,
|
||||
"verified_at": _iso(row.verified_at),
|
||||
"expires_at": _iso(row.expires_at),
|
||||
},
|
||||
observed_at=_aware(row.created_at),
|
||||
immutable_evidence=True,
|
||||
retention_reason=(
|
||||
"Assurance verification is immutable security and accountability evidence."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _epoch_record(row: TrustKeyEpoch) -> DsarRecordRef:
|
||||
return DsarRecordRef(
|
||||
provider_id="identity_trust",
|
||||
module_id="identity_trust",
|
||||
resource_type="key_epoch",
|
||||
resource_id=row.id,
|
||||
category="cryptographic_access_history",
|
||||
title="Subject key epoch",
|
||||
data={
|
||||
"subject_kind": row.subject_kind,
|
||||
"subject_id": row.subject_id,
|
||||
"epoch": row.epoch,
|
||||
"previous_epoch": row.previous_epoch,
|
||||
"state": row.state,
|
||||
"history_policy": row.history_policy,
|
||||
"reason": row.reason[:4_000],
|
||||
"access_decision_ref": row.access_decision_ref[:1_000],
|
||||
"effective_at": _iso(row.effective_at),
|
||||
},
|
||||
observed_at=_aware(row.effective_at),
|
||||
immutable_evidence=True,
|
||||
retention_reason="Key-epoch history is immutable cryptographic-access evidence.",
|
||||
)
|
||||
|
||||
|
||||
def _access_decision_record(row: KeyAccessDecisionRecord) -> DsarRecordRef:
|
||||
return DsarRecordRef(
|
||||
provider_id="identity_trust",
|
||||
module_id="identity_trust",
|
||||
resource_type="key_access_decision",
|
||||
resource_id=row.id,
|
||||
category="cryptographic_access_decision",
|
||||
title="Key-access decision",
|
||||
data={
|
||||
"decision_ref": row.decision_ref,
|
||||
"account_id": row.account_id,
|
||||
"device_key_id": row.device_key_id,
|
||||
"subject_kind": row.subject_kind,
|
||||
"subject_id": row.subject_id,
|
||||
"key_epoch": row.key_epoch,
|
||||
"access_decision_ref": row.access_decision_ref[:1_000],
|
||||
"purpose": row.purpose[:255],
|
||||
"allowed": row.allowed,
|
||||
"reason": row.reason[:4_000],
|
||||
"resource_ref": (row.resource_ref or "")[:1_000] or None,
|
||||
"function_assignment_id": row.function_assignment_id,
|
||||
"delegation_id": row.delegation_id,
|
||||
"recorded_at": _iso(row.created_at),
|
||||
},
|
||||
observed_at=_aware(row.created_at),
|
||||
immutable_evidence=True,
|
||||
retention_reason=(
|
||||
"Key-access decisions are immutable authorization and security evidence."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _public_jwk(value: object) -> dict[str, object]:
|
||||
if not isinstance(value, Mapping):
|
||||
raise ValueError("Identity Trust public JWK is invalid.")
|
||||
projection: dict[str, object] = {}
|
||||
for key in ("kty", "crv", "x", "y", "use", "alg"):
|
||||
if key in value:
|
||||
projection[key] = str(value[key])[:2_000]
|
||||
key_ops = value.get("key_ops")
|
||||
if key_ops is not None:
|
||||
if not isinstance(key_ops, list) or len(key_ops) > 20:
|
||||
raise ValueError("Identity Trust public JWK key operations are invalid.")
|
||||
projection["key_ops"] = [str(item)[:120] for item in key_ops]
|
||||
return projection
|
||||
|
||||
|
||||
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 _optional_string(value: object) -> str | None:
|
||||
return value if isinstance(value, str) and value else 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("Identity Trust DSAR requires a SQLAlchemy Session.")
|
||||
return value
|
||||
|
||||
|
||||
_RESOURCE_TYPES = {
|
||||
"device_public_key",
|
||||
"assurance_evidence",
|
||||
"key_epoch",
|
||||
"key_access_decision",
|
||||
}
|
||||
|
||||
|
||||
def _validate_record(record: DsarRecordRef) -> None:
|
||||
if (
|
||||
record.provider_id != "identity_trust"
|
||||
or record.module_id != "identity_trust"
|
||||
):
|
||||
raise ValueError("Identity Trust DSAR cannot plan a foreign provider record.")
|
||||
if record.resource_type not in _RESOURCE_TYPES or not record.resource_id:
|
||||
raise ValueError("Identity Trust DSAR record identity is invalid.")
|
||||
|
||||
|
||||
def _validate_action(action: DsarErasureActionRef) -> None:
|
||||
if (
|
||||
action.provider_id != "identity_trust"
|
||||
or action.module_id != "identity_trust"
|
||||
):
|
||||
raise ValueError("Identity Trust DSAR cannot execute a foreign action.")
|
||||
if not action.action_id.startswith("identity_trust:"):
|
||||
raise ValueError("Identity Trust DSAR action identity is invalid.")
|
||||
|
||||
|
||||
__all__ = ["IDENTITY_TRUST_DSAR_CAPABILITY", "IdentityTrustDsarProvider"]
|
||||
@@ -26,6 +26,10 @@ from govoplan_core.core.modules import (
|
||||
from govoplan_core.core.provider_governance import declared_module_architecture
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_identity_trust.backend.db import models
|
||||
from govoplan_identity_trust.backend.dsar_provider import (
|
||||
IDENTITY_TRUST_DSAR_CAPABILITY,
|
||||
IdentityTrustDsarProvider,
|
||||
)
|
||||
from govoplan_identity_trust.backend.service import SqlIdentityTrustService
|
||||
|
||||
|
||||
@@ -64,6 +68,10 @@ def _service(_context: ModuleContext) -> SqlIdentityTrustService:
|
||||
return SqlIdentityTrustService()
|
||||
|
||||
|
||||
def _dsar_provider(_context: ModuleContext) -> IdentityTrustDsarProvider:
|
||||
return IdentityTrustDsarProvider()
|
||||
|
||||
|
||||
manifest = ModuleManifest(
|
||||
id=MODULE_ID,
|
||||
name=MODULE_NAME,
|
||||
@@ -72,6 +80,10 @@ manifest = ModuleManifest(
|
||||
provides_interfaces=(
|
||||
ModuleInterfaceProvider(name="identity_trust.directory", version="1.0.0"),
|
||||
ModuleInterfaceProvider(name="identity_trust.assurance", version="1.0.0"),
|
||||
ModuleInterfaceProvider(
|
||||
name=IDENTITY_TRUST_DSAR_CAPABILITY,
|
||||
version="0.1.0",
|
||||
),
|
||||
),
|
||||
permissions=(
|
||||
_permission(
|
||||
@@ -165,6 +177,7 @@ manifest = ModuleManifest(
|
||||
capability_factories={
|
||||
CAPABILITY_IDENTITY_TRUST_DIRECTORY: _service,
|
||||
CAPABILITY_IDENTITY_TRUST_ASSURANCE: _service,
|
||||
IDENTITY_TRUST_DSAR_CAPABILITY: _dsar_provider,
|
||||
},
|
||||
capability_documentation={
|
||||
CAPABILITY_IDENTITY_TRUST_DIRECTORY: CapabilityDocumentation(
|
||||
@@ -177,6 +190,14 @@ manifest = ModuleManifest(
|
||||
summary="Verifies bounded, recent assurance evidence for high-risk cryptographic operations.",
|
||||
contract_version="1.0.0",
|
||||
),
|
||||
IDENTITY_TRUST_DSAR_CAPABILITY: CapabilityDocumentation(
|
||||
label="Identity Trust data-subject request provider",
|
||||
summary=(
|
||||
"Exports bounded device-key and assurance records while keeping "
|
||||
"cryptographic history under governed retention and review."
|
||||
),
|
||||
contract_version="0.1.0",
|
||||
),
|
||||
},
|
||||
migration_spec=MigrationSpec(
|
||||
module_id=MODULE_ID,
|
||||
@@ -202,6 +223,47 @@ manifest = ModuleManifest(
|
||||
),
|
||||
),
|
||||
documentation=(
|
||||
DocumentationTopic(
|
||||
id="identity-trust.data-subject-requests",
|
||||
title="Identity Trust data-subject requests",
|
||||
summary=(
|
||||
"Export tenant-scoped device trust, assurance, epoch, and key-access "
|
||||
"evidence without private or operational key material."
|
||||
),
|
||||
body=(
|
||||
"Identity Trust correlates exact account and identity identifiers in "
|
||||
"the active tenant and can narrow results to an exact device or key. "
|
||||
"The access package includes bounded public-key registration fields, "
|
||||
"assurance state, matching key epochs, and key-access decisions. It "
|
||||
"never exports private JWK parameters, request digests, idempotency "
|
||||
"keys, or arbitrary provenance payloads. Device-key revocation requires "
|
||||
"manual review of recovery, active encrypted resources, and the current "
|
||||
"epoch. Assurance, epoch, and access-decision records remain immutable "
|
||||
"security evidence."
|
||||
),
|
||||
layer="configured",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("user", "administrator", "security_officer", "auditor"),
|
||||
related_modules=("core", "access", "encryption", "postbox"),
|
||||
metadata={
|
||||
"help_contexts": [
|
||||
"identity_trust.settings.devices",
|
||||
"identity_trust.admin.trust",
|
||||
"privacy.data-subject-requests",
|
||||
],
|
||||
"consequence_classes": {
|
||||
"export_trust_state": (
|
||||
"Returns bounded public trust and assurance evidence only."
|
||||
),
|
||||
"review_device_revocation": (
|
||||
"Requires recovery and encrypted-resource impact review."
|
||||
),
|
||||
"retain_security_evidence": (
|
||||
"Preserves epoch, assurance, and access-decision history."
|
||||
),
|
||||
},
|
||||
},
|
||||
),
|
||||
DocumentationTopic(
|
||||
id="identity-trust.device-keys",
|
||||
title="Device keys and key epochs",
|
||||
|
||||
Reference in New Issue
Block a user