mistral-security-basics

0
0
Source

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".

Install

mkdir -p .claude/skills/mistral-security-basics && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4683" && unzip -o skill.zip -d .claude/skills/mistral-security-basics && rm skill.zip

Installs to .claude/skills/mistral-security-basics

About this skill

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

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

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

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

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

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

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

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

IssueCauseSolution
Key in logsLogging full requestLog metadata only
Prompt injectionUnsanitized user inputFilter + XML-wrap user content
PII in responsesModel generating PIISanitize output + use moderation
Key compromiseHardcoded or leakedUse secret manager, rotate immediately
XSS via outputModel generating HTML/JSStrip script tags before rendering

Resources

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

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

965

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318399

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

340397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

452339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.