mistral-security-basics
Apply Mistral AI security best practices for secrets, prompt injection, and access control. Use when securing API keys, defending against prompt injection, or auditing Mistral AI security configuration. Trigger with phrases like "mistral security", "mistral secrets", "secure mistral", "mistral prompt injection".
What this skill does
# Mistral Security Basics
## Overview
Security practices for Mistral AI integrations: API key management, prompt injection defense, output sanitization, content moderation with `mistral-moderation-latest`, request logging without secrets, and key rotation.
## Prerequisites
- Mistral API key provisioned
- Understanding of OWASP LLM Top 10 risks
- Secret management infrastructure
## Instructions
### Step 1: API Key Management
```python
import os
# NEVER: api_key = "sk-abc123"
# Development — env vars
api_key = os.environ.get("MISTRAL_API_KEY")
if not api_key:
raise RuntimeError("MISTRAL_API_KEY not set")
# Production — secret manager
from google.cloud import secretmanager
def get_api_key() -> str:
client = secretmanager.SecretManagerServiceClient()
response = client.access_secret_version(
name="projects/my-project/secrets/mistral-api-key/versions/latest"
)
return response.payload.data.decode("UTF-8")
```
### Step 2: Prompt Injection Defense
```typescript
function sanitizeUserInput(input: string): string {
// Strip common injection patterns
const patterns = [
/ignore (?:previous|all|above) instructions/gi,
/you are now/gi,
/system prompt/gi,
/\boverride\b/gi,
/\bforget\b.*\binstructions\b/gi,
];
let sanitized = input;
for (const pattern of patterns) {
sanitized = sanitized.replace(pattern, '[FILTERED]');
}
// Limit length to prevent context stuffing
return sanitized.slice(0, 4000);
}
function buildSafeMessages(system: string, userInput: string) {
return [
{ role: 'system', content: system },
{
role: 'user',
content: `<user_query>\n${sanitizeUserInput(userInput)}\n</user_query>`,
},
];
}
```
### Step 3: Content Moderation with Mistral API
```typescript
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
async function moderateContent(text: string): Promise<{ safe: boolean; flags: string[] }> {
const result = await client.classifiers.moderate({
model: 'mistral-moderation-latest',
inputs: [text],
});
const categories = result.results[0].categories;
const flags = Object.entries(categories)
.filter(([, flagged]) => flagged)
.map(([category]) => category);
return { safe: flags.length === 0, flags };
}
// Gate user input before processing
async function safeChatFlow(userInput: string) {
const inputCheck = await moderateContent(userInput);
if (!inputCheck.safe) {
throw new Error(`Input flagged: ${inputCheck.flags.join(', ')}`);
}
const response = await client.chat.complete({
model: 'mistral-small-latest',
messages: [{ role: 'user', content: userInput }],
safePrompt: true, // Built-in safety system prompt
});
const output = response.choices?.[0]?.message?.content ?? '';
const outputCheck = await moderateContent(output);
if (!outputCheck.safe) {
return 'I cannot provide that response.';
}
return output;
}
```
### Step 4: Output Sanitization
```typescript
function sanitizeOutput(response: string): string {
let cleaned = response;
// Remove leaked system prompts
cleaned = cleaned.replace(/(?:system prompt|instructions):?\s*.*/gi, '[REDACTED]');
// Remove script tags (XSS prevention)
cleaned = cleaned.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// Remove PII patterns
cleaned = cleaned.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]');
cleaned = cleaned.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/gi, '[EMAIL]');
return cleaned;
}
```
### Step 5: Request Logging Without Secrets
```typescript
function logRequest(model: string, messages: any[], response: any): void {
// Log metadata ONLY — never log content (may contain PII)
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
model,
messageCount: messages.length,
inputChars: messages.reduce((sum, m) => sum + (m.content?.length ?? 0), 0),
outputChars: response.choices?.[0]?.message?.content?.length ?? 0,
usage: {
promptTokens: response.usage?.promptTokens,
completionTokens: response.usage?.completionTokens,
},
// NEVER log: API keys, message content, user identifiers
}));
}
```
### Step 6: API Key Rotation
```typescript
class KeyRotator {
private keys: string[];
private current = 0;
private lastRotated = Date.now();
private readonly rotationIntervalMs = 3_600_000; // 1 hour
constructor(keys: string[]) {
if (keys.length === 0) throw new Error('At least one API key required');
this.keys = keys;
}
getKey(): string {
if (Date.now() - this.lastRotated > this.rotationIntervalMs) {
this.rotate();
}
return this.keys[this.current];
}
reportAuthFailure(): void {
console.error(`Key ${this.current} failed auth, rotating`);
this.rotate();
}
private rotate(): void {
this.current = (this.current + 1) % this.keys.length;
this.lastRotated = Date.now();
}
}
```
## Security Audit Checklist
```python
def audit_mistral_security():
checks = {
"api_key_from_env": bool(os.environ.get("MISTRAL_API_KEY")),
"gitignore_has_env": ".env" in open(".gitignore").read() if os.path.exists(".gitignore") else False,
"no_hardcoded_keys": True, # scan src/ for patterns
"moderation_enabled": True, # verify in code
"output_sanitization": True, # verify in code
"audit_logging": True, # verify in code
}
passed = all(checks.values())
return {"passed": passed, "checks": checks}
```
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Key in logs | Logging full request | Log metadata only |
| Prompt injection | Unsanitized user input | Filter + XML-wrap user content |
| PII in responses | Model generating PII | Sanitize output + use moderation |
| Key compromise | Hardcoded or leaked | Use secret manager, rotate immediately |
| XSS via output | Model generating HTML/JS | Strip script tags before rendering |
## Resources
- [Mistral Guardrails](https://docs.mistral.ai/capabilities/guardrailing/)
- Mistral Moderation API
- [OWASP LLM Top 10](https://owasp.org/www-project-top-10-for-large-language-model-applications/)
## Output
- API key management via secret managers
- Prompt injection defense layer
- Content moderation with `mistral-moderation-latest`
- Output sanitization pipeline
- Secure audit logging
- Key rotation automation
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.