Skip to content

API Reference parrot_formdesigner.services.rbac

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_formdesigner.services.rbac

View source

RBACService — policies ABAC/PBAC (nav-auth format) + RBACContext.

Implementa Module 3 de FEAT-302 (C4 RESUELTO §8):

  • NO motor RBAC paralelo.
  • NO columna scope en auth.permissions.
  • NUNCA escribe en auth.user_permissions.

Las policies son declarativas, compatibles con el formato YAML del engine ABAC/PBAC de nav-auth, persistidas como JSONB en fieldsync.auth_policies. El enforcement autoritativo lo ejecuta nav-auth; este módulo gestiona la emisión, almacenamiento y compilación de policies, y proyecta el RBACContext a los handlers para shadow-mode gate-keeping.

RBACScope es vocabulario de alto nivel que se compila a una Policy ABAC antes de persistir:

  • own → subjects.users = [user_id]
  • team → subjects.groups = [team/<program_id>]
  • client → conditions.resource.client_id = (computed)
  • global → sin restricción de subjects/conditions

Ejemplo de policy referencia (§8)::

Policy(
    name="eng_agents_biz_hours",
    effect="allow",
    description="Engineering agents during business hours",
    resources=["agent:*"],
    actions=["agent:chat"],
    subjects={"groups": ["engineering", "developers"]},
    conditions={"environment": {"is_business_hours": True}},
    priority=20,
    enforcing=False,
)

Uso::

svc = RBACService(pool)
record = await svc.assign_role(
    "user-abc",
    program_id=7,
    codename="edit_form",
    scope=RBACScope.OWN,
    tenant="acme",
)
ctx = await svc.resolve("user-abc", program_id=7, tenant="acme")
ctx.has_permission("edit_form", scope=RBACScope.OWN)   # → True

Class PermissionRecord

A compiled permission entry (result of assign_role).

Fields:

Field Type Default Description
user_id str The user this record belongs to.
codename str Permission code (e.g. "edit_form").
scope RBACScope The RBACScope the permission was issued with.
program_id int Program context for the permission.
policy_name str Name of the generated Policy in DB.
tenant str Tenant this record is scoped to.

Class Policy

Declarative ABAC/PBAC policy — mirrors the nav-auth YAML format.

Fields:

Field Type Default Description
name str Unique policy identifier (UNIQUE constraint in DB).
effect Literal['allow', 'deny'] 'allow' "allow" or "deny".
description str '' Human-readable description.
resources list[str] List of resource patterns (e.g. ["form:*", "agent:chat"]).
actions list[str] List of permitted/denied action patterns.
subjects dict[str, Any] Dict with groups and/or users keys.
conditions dict[str, Any] Optional conditions dict (e.g. environment, resource).
priority int 50 Numeric priority; lower = evaluated first. Default 50.
enforcing bool False When False, policy is in shadow mode (log only). Default False.
tenant str | None None Tenant scope for this policy, or None for global.

Class RBACContext

Runtime RBAC context projected for a user in a program.

Used by handlers for shadow-mode gate-keeping. The authoritative enforcement lives in nav-auth.

Fields:

Field Type Default Description
user_id str Authenticated user identifier.
program_id int Program context.
permissions list[PermissionRecord] List of PermissionRecord resolved for this user.
groups list[str] Group memberships resolved from auth.* (read-only).

Method RBACContext.has_permission

Return True if the user has the given permission at the given scope.

Scope enforcement: a permission issued at scope S grants access to scope S' only if S' is at least as narrow as S (i.e. level(S') <= level(S)).

has_permission(codename: str, scope: RBACScope | None = None) -> bool

Parameter Type Default Description
codename str Permission codename to check.
scope RBACScope | None None Required scope level. When None, any scope matches.

Returns: bool — True if at least one matching PermissionRecord is found.

Class RBACScope

Vocabulary of RBAC scopes that compile to ABAC policies.

Class RBACService

Manage ABAC/PBAC policies in fieldsync.auth_policies + project context.

All writes target fieldsync.* exclusively — NEVER auth.*. Auth tables are only read (read-only pool) for group resolution.

Example::

svc = RBACService(pool)
record = await svc.assign_role(
    "user-1", program_id=7, codename="edit_form",
    scope=RBACScope.OWN, tenant="acme"
)
ctx = await svc.resolve("user-1", program_id=7, tenant="acme")
assert ctx.has_permission("edit_form", scope=RBACScope.OWN)
Parameter Type Default Description
pool Any asyncpg pool (or fake pool for tests).

Method RBACService.create_policy

Upsert a policy in fieldsync.auth_policies.

If a policy with the same name already exists, its content is updated (ON CONFLICT DO UPDATE).

create_policy(policy: Policy) -> Policy

Parameter Type Default Description
policy Policy Policy instance to persist.

Returns: Policy — The persisted Policy (reflected from DB row).

Method RBACService.get_policy

Retrieve a policy by name.

get_policy(name: str) -> Policy | None

Parameter Type Default Description
name str Unique policy name.

Returns: Policy | None — Policy or None if not found.

Method RBACService.list_policies

List all policies for a tenant, ordered by priority.

list_policies(*, tenant: str) -> list[Policy]

Parameter Type Default Description
tenant str Tenant slug to filter by.

Returns: list[Policy] — List of Policy instances (empty if none found).

Method RBACService.delete_policy

Delete a policy by name.

delete_policy(name: str) -> bool

Parameter Type Default Description
name str Unique policy name.

Returns: bool — True if the policy was deleted; False if it did not exist.

Method RBACService.assign_role

Compile (user_id, codename, scope) to a Policy and persist it.

NEVER writes to auth.user_permissions. The compiled policy is stored in fieldsync.auth_policies (JSONB).

assign_role(user_id: str, *, program_id: int, codename: str, scope: RBACScope, tenant: str) -> PermissionRecord

Parameter Type Default Description
user_id str User to assign the role to.
program_id int Program context.
codename str Permission codename.
scope RBACScope RBACScope level.
tenant str Tenant this assignment belongs to.

Returns: PermissionRecord — PermissionRecord reflecting the persisted policy.

Method RBACService.resolve

Build RBACContext for a user by reading fieldsync.auth_policies.

Reads policies from fieldsync.auth_policies for the tenant. Optionally reads group memberships from auth.groups / auth.user_groups (read-only). Falls back to empty groups list if auth tables are unavailable.

resolve(user_id: str, *, program_id: int, tenant: str) -> RBACContext

Parameter Type Default Description
user_id str Authenticated user identifier.
program_id int Program context.
tenant str Tenant slug.

Returns: RBACContext — RBACContext with permissions and groups populated.

Method RBACService.revoke_all

Delete all policies compiled for user_id in tenant.

NEVER touches auth.user_permissions.

revoke_all(user_id: str, *, tenant: str) -> int

Parameter Type Default Description
user_id str User whose compiled policies should be deleted.
tenant str Tenant scope.

Returns: int — Number of policies deleted.

Attribute logger

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally