@dmint.protect decorator places a deterministic authorization gate directly in front of Python callables.def)async def)self)@classmethod, taking cls)@staticmethod)yield) and asynchronous generators (yield in async def) cannot be decorated because execution resumes in chunks across multiple caller ticks, violating atomic pre-execution authorization.Dmint.local)Dmint.local() automatically provisions .dmint/signing.key (0600), .dmint/integrity.key (0600), and .dmint/approvals.sqlite3:from dmint import ApprovalRequiredError, Dmint, Policy, Rule policy = Policy([ Rule.allow("payments", "get_status"), Rule.approval_required("payments", "refund"), ]) dmint = Dmint.local(policy, agent_id="agent-01") @dmint.protect("payments.refund") def issue_refund(payment_id: str, amount: float) -> dict: return {"id": payment_id, "refunded": amount}
Dmint)from datetime import datetime, timezone, timedelta from dmint import ( Dmint, Policy, Rule, PolicyProvenance, SQLiteApprovalStore, TrustedContext, policy_digest, ) policy = Policy([ Rule.allow("payments", "get_status"), Rule.approval_required("payments", "refund"), ]) store = SQLiteApprovalStore("approvals.sqlite3", deployment_epoch="default") provenance = PolicyProvenance("v1", policy_digest(policy), datetime.now(timezone.utc)) dmint = Dmint( policy=policy, agent_id="agent-01", context=TrustedContext({"environment": "production"}), approval_store=store, policy_provenance=provenance, approval_ttl=timedelta(minutes=5), ) @dmint.protect("payments.get_status") def get_payment_status(payment_id: str) -> dict: return {"id": payment_id, "status": "SETTLED"} @dmint.protect("payments.refund") def issue_refund(payment_id: str, amount: float) -> dict: return {"id": payment_id, "refunded": amount}
async def) Protectionasync def coroutine, Dmint evaluates authorization before the coroutine begins and returns an awaitable result:import asyncio from dmint import Dmint, Policy, Rule, TrustedContext, ApprovalRequiredError policy = Policy([ Rule.allow("api", "fetch"), Rule.approval_required("api", "mutate"), ]) dmint = Dmint( policy=policy, agent_id="async-worker-01", context=TrustedContext({"environment": "staging"}), ) @dmint.protect("api.mutate") async def async_database_mutate(record_id: str, payload: dict) -> dict: await asyncio.sleep(0.01) # Simulated async I/O return {"record_id": record_id, "updated": True} async def main(): try: result = await async_database_mutate("rec_99", {"status": "archived"}) print(f"Result: {result}") except ApprovalRequiredError as exc: print(f"Halted: {exc.code} for request {exc.request_id}") if __name__ == "__main__": asyncio.run(main())
class LedgerService: def __init__(self, tenant_id: str): self.tenant_id = tenant_id # Instance method: Dmint strips 'self' from arguments and scopes action as 'LedgerService.record_entry' # (Matched by Rule.allow("ledger", "LedgerService.record_entry") or Rule.allow("ledger", "*")) @dmint.protect("ledger.record_entry") def record_entry(self, entry_id: str, amount: float) -> str: return f"Tenant {self.tenant_id}: Recorded entry {entry_id} for ${amount:.2f}" # Class method: Dmint preserves class reference @classmethod @dmint.protect("ledger.get_version") def get_version(cls) -> str: return "ledger-v2.1" # Static method: @staticmethod @dmint.protect("ledger.compute_tax") def compute_tax(subtotal: float, rate: float) -> float: return subtotal * rate
resource resolver to extract the resource string dynamically from the function's arguments:# Resource extracted dynamically from arguments dict: @dmint.protect( "filesystem.read", resource=lambda args: args["path"], ) def read_system_file(path: str) -> str: with open(path, "r", encoding="utf-8") as f: return f.read() # Dynamic resource with compound formatting: @dmint.protect( "database.table_operation", resource=lambda args: f"{args['schema']}.{args['table']}", ) def run_table_op(schema: str, table: str, query: str): ...
RequestValidationError.import os from dmint import Dmint, TrustedContext # Remote policy loading requires expected_policy_digest: dmint = Dmint( policy_file="https://internal-security.company.com/policies/billing-v2.json", expected_policy_digest=os.environ["DMINT_EXPECTED_POLICY_DIGEST"], agent_id="agent-01", context=TrustedContext({"env": "prod"}), )
PolicyError.datetime, Decimal, UUID, Path)str, int, float, bool, None, list, dict). Passing non-JSON objects such as datetime, Decimal, UUID, or pathlib.Path fails closed with CanonicalizationError (code="DMT_CANONICALIZATION_ERROR").from datetime import datetime from pathlib import Path from uuid import UUID @dmint.protect("audit.write_event") def write_event(event_id: str, path: str, occurred_at: str) -> dict: return {"event_id": event_id, "path": path, "occurred_at": occurred_at} # Normalize rich Python objects to strings at the call site: def log_user_event(event_id: UUID, path: Path, occurred_at: datetime) -> dict: return write_event(str(event_id), path.as_posix(), occurred_at.isoformat())