<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: implementing-llm-access-controls
description: >-
  Implement access controls for LLM applications including rate limiting,
  authentication, token budgets, tool permission boundaries, and privilege
  separation to prevent excessive agency and unauthorized resource access.
domain: cybersecurity
subdomain: ai-llm-security
tags:
  - access-control
  - rate-limiting
  - llm-security
  - excessive-agency
  - authorization
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1078", "T1098"]
  owasp-llm: ["LLM08", "LLM10"]
  mitre-atlas: ["AML.T0044"]
  tools: ["python3", "redis", "pyjwt", "fastapi"]
---

# Implementing LLM Access Controls

## Overview

LLM applications require multi-layered access controls to prevent excessive agency
(LLM08), model theft (LLM10), and unauthorized resource access. This includes API
authentication and rate limiting, token budget enforcement, tool-level permission
boundaries for AI agents, privilege separation between user and system contexts,
and audit logging of all model interactions.

## Prerequisites

| Tool / Requirement | Details |
|---|---|
| `python3` | Security tooling |
| `fastapi` | Security tooling |
| `redis` | Security tooling |
| `pyjwt` | Security tooling |
| Understanding of the application's user roles and permission model | Environment requirement |
| Inventory of agent tools and their required permissions | Environment requirement |
| Rate limiting infrastructure (Redis or equivalent) | Environment requirement |

## Key Concepts

- **Excessive agency (LLM08)**: Agent with overprivileged tools executing unintended actions
- **Token budget**: Maximum tokens per request/session to prevent cost abuse and DoS
- **Tool permission boundary**: Restricting tools an agent can invoke based on user role
- **Confirmation gate**: Requiring human approval for high-impact or irreversible actions
- **Audit trail**: Logging all model inputs, outputs, and tool invocations

## Workflow

### Step 1: Rate Limiting Implementation

```python
import redis

class TokenRateLimiter:
    def __init__(self, redis_client: redis.Redis) -> None:
        self.redis = redis_client

    def check_limit(
        self, user_id: str, max_requests: int = 100,
        max_tokens: int = 100000, window: int = 3600,
    ) -> dict:
        key_req = f"ratelimit:req:{user_id}"
        key_tok = f"ratelimit:tok:{user_id}"
        pipe = self.redis.pipeline()
        pipe.get(key_req)
        pipe.get(key_tok)
        results = pipe.execute()
        current_requests = int(results[0] or 0)
        current_tokens = int(results[1] or 0)
        return {
            "allowed": current_requests < max_requests and current_tokens < max_tokens,
            "remaining_requests": max(0, max_requests - current_requests),
            "remaining_tokens": max(0, max_tokens - current_tokens),
        }
```

### Step 2: Tool Permission Boundaries

```python
from dataclasses import dataclass
from enum import Enum

class ToolRisk(Enum):
    READ_ONLY = "read_only"
    WRITE = "write"
    DESTRUCTIVE = "destructive"
    EXTERNAL = "external"

@dataclass
class ToolPermission:
    name: str
    risk: ToolRisk
    requires_confirmation: bool
    allowed_roles: list[str]

TOOL_REGISTRY = [
    ToolPermission("search_docs", ToolRisk.READ_ONLY, False, ["user", "admin"]),
    ToolPermission("read_file", ToolRisk.READ_ONLY, False, ["user", "admin"]),
    ToolPermission("write_file", ToolRisk.WRITE, True, ["admin"]),
    ToolPermission("execute_code", ToolRisk.DESTRUCTIVE, True, ["admin"]),
    ToolPermission("send_email", ToolRisk.EXTERNAL, True, ["admin"]),
]

def check_tool_permission(tool_name: str, user_role: str) -> dict:
    for tool in TOOL_REGISTRY:
        if tool.name == tool_name:
            return {
                "tool": tool_name,
                "risk_level": tool.risk.value,
                "authorized": user_role in tool.allowed_roles,
                "requires_confirmation": tool.requires_confirmation,
            }
    return {"tool": tool_name, "authorized": False, "error": "Unknown tool"}
```

### Step 3: Audit Logging

```python
import json
import logging
from datetime import datetime, timezone

audit_logger = logging.getLogger("llm_audit")

def log_interaction(
    user_id: str, input_text: str, output_text: str,
    tools_used: list[str], tokens: int,
) -> dict:
    entry = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "user_id": user_id,
        "input_preview": input_text[:500],
        "output_preview": output_text[:500],
        "tools_used": tools_used,
        "tokens_consumed": tokens,
    }
    audit_logger.info(json.dumps(entry))
    return entry
```

## Detection

```yaml
title: Llm Access Controls Detection
id: e12f0941-02fa-4d78-8d37-13eb4f9d3d61
status: experimental
description: Detects suspicious activity related to implementing llm access controls techniques in ai llm security context
logsource:
  category: application
  product: webserver
detection:
  selection:
    EventType: error
  condition: selection
level: medium
tags:
  - attack.t1078
  - attack.t1098
  - attack.initial_access
falsepositives:
  - Automated AI model training and inference pipeline operations
```


**Detection Opportunities**

| Indicator | Source | Detection Logic |
|---|---|---|
| Llm Access Controls Detection | webserver/application | Sigma rule (medium) |
| ATT&CK Coverage | MITRE ATT&CK | T1078, T1098 |

## Verification

- [ ] Rate limiting enforced per-user for requests and tokens
- [ ] Tool permissions restrict access based on user role
- [ ] Confirmation gates active for destructive and external tools
- [ ] Audit logging captures all model interactions and tool calls
- [ ] Token budgets prevent cost abuse and DoS
- [ ] Access controls tested for bypass resistance

## References

- [OWASP LLM08 — Excessive Agency](https://genai.owasp.org/llmrisk/llm08-excessive-agency/)
- [OWASP LLM10 — Model Theft](https://genai.owasp.org/llmrisk/llm10-model-theft/)
- [NIST AI RMF — Govern Function](https://airc.nist.gov/AI_RMF_Playbook)
- [CIS Controls v8 — Access Control](https://www.cisecurity.org/controls)
