> ## Documentation Index
> Fetch the complete documentation index at: https://docs.databunker.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Conditional Role-Based Access Control (CRBAC)

**Conditional Role-Based Access Control (CRBAC)** is an advanced access control system that extends traditional Role-Based Access Control (RBAC) by introducing dynamic conditions that determine access rights. For the credential types that policies govern (root, tenant, role, and user tokens), see the [Authentication reference](/pro/api/authentication).

CRBAC is particularly useful for businesses that need to comply with various privacy laws, such as:

1. **DPDPA** (India's Digital Personal Data Protection Act)

2. **FERPA** (Family Educational Rights and Privacy Act in the USA), which governs student education records

3. **GDPR** (General Data Protection Regulation in the EU)

With Databunker Pro, customers can easily implement solutions that align with these regulations, ensuring secure and compliant PII management.

## Key Features of CRBAC

* **Hierarchical Access Control:** Supports parent-child relationships in data access, enabling fine-grained permissions.
* **Context-Aware Policies:** Defines access based on specific attributes like user roles, organizational structures, and compliance requirements.
* **Dynamic Consent Enforcement:** Incorporates consent management for accessing PII.
* **Group-Based Roles:** Databunker supports groups of users, where each member within a group can have distinct roles. For instance, in an educational group, roles like **Teacher** and **Student** can be assigned, or in a family group, roles such as **Parent** and **Child**.
* **Similar to AWS IAM Policies:** Uses a declarative approach to grant or deny access based on conditions.

## Policy Structure

CRBAC policies resemble AWS IAM policies, defining **who** (principale) can perform **what** (actions) on **which** (resources) under **which conditions**.

### Example Policy: Parent-Child Relationship Enforcement

In Databunker Pro, you can create a custom group for family members. Within this group, parents will have read and write access to their child's information.

You can use the following policy to grant parents access to their child's PII and consent information.

```json theme={null}
{
  "Effect": "Allow",
  "Principal": { "Role": "parent" },
  "Action": [
    "UserGet",
    "UserUpdate",
    "BulkListGroupUsers",
    "AgreementGet",
    "AgreementAccept",
    "AgreementCancel",
    "AgreementListUserAgreements"
  ],
  "Resource": [
    "${target_group_members:role/child}.profile",
    "${target_group_members:role/child}.agreement"
  ],
  "Condition": {
    "StringEquals": {
      "${user_group_id}": "${target_group_id}"
    }
  }
}
```

### Example Policy: Teacher-Parent Access

This policy will grant to a teacher entity access to the student's parent information.

```json theme={null}
{
  "Effect": "Allow",
  "Principal": { "Role": "teacher" },
  "Action": ["UserGet", "BulkListGroupUsers"],
  "Resource": [
    "${target_group_members:role/parent}.profile.name",
    "${target_group_members:role/parent}.profile.phone"
  ],
  "Condition": {
    "ForAnyValue:ListIntersect": {
      "${user_group_members:role/student}": "${target_group_members:role/child}"
    }
  }
}
```

## Passing runtime context with `request_metadata`

Most Databunker Pro API endpoints accept an optional **`request_metadata`** object on the request body. The caller (application code, an API gateway, or a tokenisation proxy) uses it to pass runtime context — values like the calling environment, the purpose of the request, the originating IP address, a ticket number — that the access-control engine can evaluate at policy time.

CRBAC `Condition` blocks can reference `request_metadata` values directly, so the same policy can grant or deny access based on **why** and **where** the request is coming from, not just **who** is making it. This is purpose-of-use enforcement.

### Example: caller-supplied context

```bash theme={null}
curl -X POST https://your-databunker-instance/v2/UserGet \
  -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "email",
    "identity": "jane@example.com",
    "request_metadata": {
      "environment": "production",
      "purpose": "fraud-investigation",
      "caller_ip": "10.0.12.34",
      "ticket_id": "INC-44218"
    }
  }'
```

### Example: policy that evaluates `request_metadata`

This policy allows a `security-analyst` role to read full user records **only** when the request is tagged with `purpose: fraud-investigation` and originates from the production environment:

```json theme={null}
{
  "Effect": "Allow",
  "Principal": { "Role": "security-analyst" },
  "Action": ["UserGet"],
  "Resource": ["*.profile"],
  "Condition": {
    "StringEquals": {
      "${request_metadata.purpose}":     "fraud-investigation",
      "${request_metadata.environment}": "production"
    }
  }
}
```

A request from the same role without those metadata values — or with different ones — is denied.

### What to put in `request_metadata`

`request_metadata` is free-form, so the keys are conventions you adopt for your deployment. Typical keys we see in production:

| Key           | Purpose                                                              |
| ------------- | -------------------------------------------------------------------- |
| `environment` | `production` / `staging` / `dev` — scopes policies per environment.  |
| `purpose`     | A business-domain purpose-of-use code (e.g., `fraud-investigation`). |
| `caller_ip`   | Client IP — useful for IP-range conditions.                          |
| `ticket_id`   | Linking the access to a ticket / case for accountability.            |
| `app_name`    | Calling application — useful when multiple apps share a role.        |

Every value passed in `request_metadata` is recorded in the audit event for the request, so it doubles as accountability metadata even when no policy references it.

## Field-Level Masking in Responses

When a policy grants access to a subset of a user's profile fields, Databunker Pro applies the policy at response time. The original record stays untouched in the vault; the API response is filtered for the calling principal.

The masking strategy is **asymmetric by type** so that strongly-typed clients (TypeScript, Python type-hints, Java, generated SDKs) do not encounter silent type mismatches:

* **String fields** that the caller is not authorized to read are replaced with the literal `"***"`. The field stays in the response so the client can detect that the field exists.
* **All other types** (`number`, `boolean`, array, nested object) are **omitted from the response entirely** when masked. This avoids type-corruption bugs like `profile.age + 1` evaluating to `"***1"` because the engine had substituted a string for a number.

### Example

Suppose a `sales` user has a policy allowing only `${target_group_members:role/lead}.profile.email`. A lead's stored profile is:

```json theme={null}
{
  "login": "lead42",
  "name":  "Jane Doe",
  "email": "jane@example.com",
  "phone": "+15551234567",
  "age":   34,
  "verified": true,
  "tags":  ["enterprise", "warm"],
  "address": { "city": "Springfield", "zip": "99999" }
}
```

Calling `UserGet` with the sales user's token returns:

```json theme={null}
{
  "status":  "ok",
  "profile": {
    "email": "jane@example.com",
    "login": "***",
    "name":  "***",
    "phone": "***"
  }
}
```

Notice:

* `email` is visible because the policy granted it.
* `login`, `name`, `phone` are strings — present in the response with value `"***"`.
* `age` (number), `verified` (boolean), `tags` (array), `address` (object) are absent from the `profile` object entirely.

### TypeScript example

```typescript theme={null}
interface UserResponse {
  status: string;
  profile: {
    email?:    string;
    login?:    string;
    name?:     string;
    phone?:    string;
    age?:      number;
    verified?: boolean;
    tags?:     string[];
    address?:  { city: string; zip: string };
  };
}

const r: UserResponse = await api.userGet({mode: "login", identity: "lead42"});

// Safe: optional fields handled with the `?` operator.
if (r.profile.age !== undefined) {
  console.log("Age:", r.profile.age + 1);   // never executes when age is masked
}
```

## Why Choose CRBAC?

1. **Compliance-Ready:** CRBAC ensures organizations meet legal and regulatory requirements, including FERPA and DPDPA.
2. **Dynamic Access Control:** Unlike static RBAC, CRBAC adapts access rights based on real-time conditions.
3. **Fine-Grained Permissions:** Allows precise control over PII data access, reducing the risk of unauthorized exposure.

## Implementing CRBAC with Databunker Pro

Databunker Pro simplifies CRBAC implementation by providing:

1. Built-in support for conditional access policies
2. Secure PII storage with compliance enforcement
3. A developer-friendly API for managing role-based conditions

By leveraging **Databunker Pro**, organizations can seamlessly enforce FERPA-compliant data access policies while maintaining flexibility for other regulatory frameworks.

## Conclusion

Conditional Role-Based Access Control (CRBAC) is essential for organizations handling sensitive PII under strict compliance regulations. With Databunker Pro, businesses can implement secure, scalable, and regulation-compliant access control mechanisms tailored to their needs.
