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

# Security

> Protect sensitive data and block malicious users from abusing your AI features

# Security

The AI Gateway provides powerful security features to protect your data and prevent abuse. Block sensitive information from being sent to AI providers, and stop malicious users from exploiting your applications.

## Sensitive Data Protection

### The Risk

When using AI assistants or building AI-powered apps, sensitive data can accidentally be exposed:

<Warning>
  **Real scenarios we've seen:**

  * AWS keys sent in code context to ChatGPT
  * Database passwords included in error messages
  * Customer PII processed by AI for "analysis"
  * API secrets in environment variable debugging
</Warning>

### Automatic Detection

The gateway scans all requests for sensitive patterns:

<Frame>
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/leanmcp/images/ai-gateway-sensitive-detection.png" alt="Sensitive data detection" />
</Frame>

**Detected patterns include:**

* AWS Access Keys and Secret Keys
* GitHub Personal Access Tokens
* Database connection strings
* API keys (various providers)
* Private keys (RSA, SSH, etc.)
* Credit card numbers
* Social Security Numbers
* Email addresses
* Phone numbers

### Blocking Sensitive Data

Configure the gateway to block requests containing sensitive data:

```typescript theme={null}
// Configure blocking rules
await leanmcp.gateway.setSecurityRules({
  blockPatterns: [
    { type: 'aws_key', action: 'block' },
    { type: 'api_key', action: 'block' },
    { type: 'password', action: 'warn' },
  ],
  alertOnDetection: true,
});
```

#### Action Types

| Action     | Behavior                                                   |
| ---------- | ---------------------------------------------------------- |
| **block**  | Request is rejected, never sent to AI provider             |
| **warn**   | Request proceeds but alert is generated                    |
| **redact** | Sensitive data is replaced with \[REDACTED] before sending |
| **log**    | Request proceeds, logged for review                        |

### Remediation

When sensitive data is detected:

1. **Review the log** - see exactly what was exposed
2. **Rotate credentials** - change any exposed secrets immediately
3. **Update your code** - ensure secrets aren't in files that get sent to AI
4. **Enable blocking** - prevent future exposure

<Tip>
  Keep secrets in `.env` files and ensure `.env` is in your `.gitignore`. Most AI assistants respect gitignore patterns.
</Tip>

## Blocking Malicious Users

When building AI-powered applications, you need to protect against abuse.

### Common Abuse Patterns

<CardGroup cols={2}>
  <Card title="Prompt Injection" icon="syringe">
    Users trying to manipulate your AI to bypass restrictions
  </Card>

  <Card title="Cost Attacks" icon="money-bill-wave">
    Users making excessive requests to run up your AI costs
  </Card>

  <Card title="Data Extraction" icon="database">
    Attempts to extract training data or system prompts
  </Card>

  <Card title="Jailbreaking" icon="lock-open">
    Trying to make the AI produce harmful content
  </Card>
</CardGroup>

### User Blocking

Block abusive users instantly:

<Frame>
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/leanmcp/images/ai-gateway-block-user.png" alt="Block user interface" />
</Frame>

```typescript theme={null}
// Block a user via API
await leanmcp.gateway.blockUser({
  userId: 'abusive-user-123',
  reason: 'Excessive usage and prompt injection attempts',
  duration: 'permanent', // or '24h', '7d', etc.
});
```

When a blocked user makes a request:

* Request is immediately rejected
* No tokens are consumed
* Event is logged for audit

### Unblocking Users

```typescript theme={null}
// Unblock a user
await leanmcp.gateway.unblockUser({
  userId: 'user-123',
  reason: 'Issue resolved, user warned',
});
```

### Viewing Blocked Users

Access the block list at [app.leanmcp.com/security](https://app.leanmcp.com/security):

1. Open [app.leanmcp.com/security](https://app.leanmcp.com/security) → **Blocked Users**
2. View all blocked users with reasons and timestamps
3. Manage blocks (extend, reduce, remove)

## Rate Limiting

Prevent abuse with intelligent rate limiting:

```typescript theme={null}
// Set rate limits
await leanmcp.gateway.setRateLimit({
  scope: 'per_user',
  limits: {
    requestsPerMinute: 20,
    requestsPerHour: 200,
    tokensPerDay: 500000,
    maxCostPerMonth: 100.00,
  },
  action: 'block', // or 'queue', 'throttle'
});
```

### Rate Limit Strategies

| Strategy        | Use Case                          |
| --------------- | --------------------------------- |
| **Per User**    | Limit individual user consumption |
| **Per IP**      | Prevent anonymous abuse           |
| **Per API Key** | Limit by integration              |
| **Global**      | Overall service protection        |

### Handling Rate Limits

When users hit limits:

```typescript theme={null}
// Client receives 429 response
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Too many requests. Please try again in 60 seconds.",
    "retry_after": 60
  }
}
```

## Content Filtering

Block requests based on content:

### Input Filtering

```typescript theme={null}
// Block certain input patterns
await leanmcp.gateway.setContentFilter({
  inputFilters: [
    { pattern: 'ignore previous instructions', action: 'block' },
    { pattern: 'reveal your system prompt', action: 'block' },
    { pattern: /jailbreak/i, action: 'warn' },
  ]
});
```

### Output Filtering

```typescript theme={null}
// Filter AI responses
await leanmcp.gateway.setContentFilter({
  outputFilters: [
    { pattern: 'internal_api_endpoint', action: 'redact' },
    { pattern: /\b\d{4}-\d{4}-\d{4}-\d{4}\b/, action: 'redact' }, // Credit cards
  ]
});
```

## Audit Logging

All security events are logged:

<Frame>
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/leanmcp/images/ai-gateway-audit-log.png" alt="Audit log" />
</Frame>

| Event Type                    | Details Logged                    |
| ----------------------------- | --------------------------------- |
| **blocked\_request**          | User, reason, request content     |
| **sensitive\_data\_detected** | Pattern, location, severity       |
| **rate\_limit\_hit**          | User, limit type, current count   |
| **user\_blocked**             | User, reason, admin who blocked   |
| **user\_unblocked**           | User, reason, admin who unblocked |

### Export Audit Logs

For compliance and review:

```bash theme={null}
curl -X GET "https://api.leanmcp.com/gateway/audit-logs?days=30" \
  -H "Authorization: Bearer your-api-key" \
  -o audit-logs.json
```

## Security Alerts

Get notified of security events:

### Alert Configuration

```typescript theme={null}
await leanmcp.gateway.createSecurityAlert({
  events: ['sensitive_data_detected', 'rate_limit_exceeded', 'suspicious_pattern'],
  channels: {
    email: ['security@yourcompany.com'],
    slack: 'https://hooks.slack.com/...',
    webhook: 'https://your-server.com/alerts',
  },
  severity: 'medium', // or 'low', 'high', 'critical'
});
```

### Alert Examples

<Frame>
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/leanmcp/images/ai-gateway-security-alert.png" alt="Security alert example" />
</Frame>

## Best Practices

<AccordionGroup>
  <Accordion title="Start with warn, then block">
    Begin with 'warn' actions to understand what would be blocked, then switch to 'block' once tuned.
  </Accordion>

  <Accordion title="Review blocks regularly">
    Check blocked requests weekly to ensure legitimate users aren't being affected.
  </Accordion>

  <Accordion title="Set up alerts early">
    Configure security alerts before launch so you're notified of issues immediately.
  </Accordion>

  <Accordion title="Use appropriate rate limits">
    Set limits that allow normal use while preventing abuse. Adjust based on observed patterns.
  </Accordion>

  <Accordion title="Document your policies">
    Make sure users know your usage policies and what behavior will result in blocking.
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Observability" icon="eye" href="/ai-gateway/observability">
    Monitor all requests and detect issues
  </Card>

  <Card title="Token Optimization" icon="chart-pie" href="/ai-gateway/token-optimization">
    Reduce costs while maintaining quality
  </Card>
</CardGroup>

***

<Card title="Ready? Open your Observability Dashboard →" icon="eye" href="https://app.leanmcp.com/observability" color="#ff6b35">
  View your first logged AI request at **app.leanmcp.com/observability**
</Card>
