Skip to content
mistral-security-basics logo

Mistral AI Security Basics

mistral-security-basics

Apply Mistral AI security best practices for secrets and access control. Use when securing API keys, implementing least privilege access, or auditing Mistral AI security configuration. Trigger with phrases like "mistral security", "mistral secrets", "secure mistral", "mistral API key security".

SKILL.md

Full skill instructions

Mistral AI Security Basics

Overview

Security best practices for Mistral AI API keys and access control.

Prerequisites

  • Mistral AI SDK installed
  • Understanding of environment variables
  • Access to Mistral AI console

Instructions

Step 1: Configure Environment Variables

# .env (NEVER commit to git)
MISTRAL_API_KEY=your-api-key-here

# .gitignore - Add these lines
.env
.env.local
.env.*.local
*.pem
*.key
secrets/

Validate .gitignore:

# Check if .env would be committed
git check-ignore .env || echo "WARNING: .env is not ignored!"

# Check for exposed secrets in history
git log -p --all -S 'MISTRAL_API_KEY' -- '*.ts' '*.js' '*.py' '*.env'

Step 2: Secure Key Loading

// src/​config/​mistral.ts
import { z } from 'zod';

const envSchema = z.object({
  MISTRAL_API_KEY: z.string().min(20, 'Invalid API key format'),
  NODE_ENV: z.enum(['development', 'staging', 'production']).default('development'),
});

export function loadMistralConfig() {
  const result = envSchema.safeParse(process.env);

  if (!result.success) {
    console.error('Environment validation failed:', result.error.format());
    throw new Error('Missing or invalid MISTRAL_API_KEY');
  }

  return result.data;
}

// Usage
const config = loadMistralConfig();
const client = new Mistral({ apiKey: config.MISTRAL_API_KEY });

Step 3: Key Rotation Procedure

# 1. Generate new key in Mistral console
#    https://console.mistral.ai/​api-keys/

# 2. Test new key before rotation
MISTRAL_API_KEY_NEW="new-key-here"
curl -H "Authorization: Bearer ${MISTRAL_API_KEY_NEW}" \
  https://api.mistral.ai/​v1/​models

# 3. Update environment variable / secrets manager
export MISTRAL_API_KEY="${MISTRAL_API_KEY_NEW}"

# 4. Deploy with new key

# 5. Revoke old key in Mistral console

Step 4: Environment-Specific Keys

EnvironmentKey TypePermissions
DevelopmentDev keyAll models, low limits
StagingStaging keyAll models, medium limits
ProductionProduction keyRequired models only
// src/​config/​environments.ts
interface MistralEnvConfig {
  apiKey: string;
  allowedModels: string[];
  maxTokensPerRequest: number;
}

const configs: Record<string, MistralEnvConfig> = {
  development: {
    apiKey: process.env.MISTRAL_API_KEY_DEV!,
    allowedModels: ['mistral-small-latest', 'mistral-large-latest'],
    maxTokensPerRequest: 1000,
  },
  production: {
    apiKey: process.env.MISTRAL_API_KEY_PROD!,
    allowedModels: ['mistral-small-latest'],
    maxTokensPerRequest: 4000,
  },
};

export function getEnvConfig(): MistralEnvConfig {
  const env = process.env.NODE_ENV || 'development';
  return configs[env] || configs.development;
}

Step 5: Request Validation & Sanitization

import { z } from 'zod';

const messageSchema = z.object({
  role: z.enum(['system', 'user', 'assistant']),
  content: z.string().max(100000), // Prevent huge payloads
});

const chatRequestSchema = z.object({
  model: z.enum(['mistral-small-latest', 'mistral-large-latest']),
  messages: z.array(messageSchema).min(1).max(100),
  temperature: z.number().min(0).max(1).optional(),
  maxTokens: z.number().min(1).max(4000).optional(),
});

function validateChatRequest(input: unknown) {
  return chatRequestSchema.parse(input);
}

// Usage in API endpoint
app.post('/​api/​chat', async (req, res) => {
  try {
    const validated = validateChatRequest(req.body);
    const response = await client.chat.complete(validated);
    res.json(response);
  } catch (error) {
    if (error instanceof z.ZodError) {
      res.status(400).json({ error: 'Invalid request', details: error.errors });
    } else {
      res.status(500).json({ error: 'Internal error' });
    }
  }
});

Step 6: Audit Logging

interface AuditEntry {
  timestamp: Date;
  action: string;
  userId?: string;
  model: string;
  tokensUsed?: number;
  success: boolean;
  errorCode?: string;
  ipAddress?: string;
}

async function auditLog(entry: Omit<AuditEntry, 'timestamp'>): Promise<void> {
  const log: AuditEntry = { ...entry, timestamp: new Date() };

  // Log to your audit system
  console.log('[AUDIT]', JSON.stringify(log));

  // Optional: send to logging service
  // await loggingService.record(log);
}

// Usage
async function chatWithAudit(
  userId: string,
  messages: Message[],
  ipAddress?: string
): Promise<string> {
  const start = Date.now();
  try {
    const response = await client.chat.complete({
      model: 'mistral-small-latest',
      messages,
    });

    await auditLog({
      action: 'chat.complete',
      userId,
      model: 'mistral-small-latest',
      tokensUsed: response.usage?.totalTokens,
      success: true,
      ipAddress,
    });

    return response.choices?.[0]?.message?.content ?? '';
  } catch (error: any) {
    await auditLog({
      action: 'chat.complete',
      userId,
      model: 'mistral-small-latest',
      success: false,
      errorCode: error.status?.toString(),
      ipAddress,
    });
    throw error;
  }
}

Security Checklist

  • API key stored in environment variable (not code)
  • .env files in .gitignore
  • Different keys for dev/​staging/​prod
  • Input validation on all requests
  • Output sanitization before display
  • Audit logging enabled
  • Rate limiting implemented
  • Error messages don't expose internals
  • HTTPS enforced for all endpoints
  • Regular key rotation scheduled

Output

  • Secure API key storage
  • Environment-specific access controls
  • Input validation
  • Audit logging enabled

Error Handling

Security IssueDetectionMitigation
Exposed API keyGit scanning, log reviewRotate immediately, revoke old key
Injection attacksInput validationZod schemas, sanitization
Missing audit trailLog reviewImplement comprehensive logging
Excessive permissionsAccess reviewLimit models per environment

Examples

Secrets Manager Integration (AWS)

import { SecretsManager } from '@aws-sdk/​client-secrets-manager';

const sm = new SecretsManager({ region: 'us-east-1' });

async function getMistralApiKey(): Promise<string> {
  const secret = await sm.getSecretValue({
    SecretId: 'mistral/​api-key',
  });
  return secret.SecretString!;
}

Secrets Manager Integration (GCP)

import { SecretManagerServiceClient } from '@google-cloud/​secret-manager';

const client = new SecretManagerServiceClient();

async function getMistralApiKey(): Promise<string> {
  const [version] = await client.accessSecretVersion({
    name: 'projects/​my-project/​secrets/​mistral-api-key/​versions/​latest',
  });
  return version.payload?.data?.toString()!;
}

Content Filtering

const BLOCKED_PATTERNS = [
  /\b(password|secret|key)\s*[:=]/​i,
  /\b\d{16}\b/, // Credit card numbers
  /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/​i, // Emails
];

function containsSensitiveData(text: string): boolean {
  return BLOCKED_PATTERNS.some(pattern => pattern.test(text));
}

async function safeChatComplete(messages: Message[]): Promise<string> {
  // Check input for sensitive data
  for (const msg of messages) {
    if (containsSensitiveData(msg.content)) {
      throw new Error('Message contains potentially sensitive data');
    }
  }

  return client.chat.complete({ model: 'mistral-small-latest', messages });
}

Resources

Next Steps

For production deployment, see mistral-prod-checklist.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...

1.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View