security

A set of security guidelines for Rust applications, covering secure handling of input, cryptography, secrets, authentication, access control, and data protection.

In plain words
What is it for?
Use it to guide threat modeling, input validation, password hashing, encryption, token security, and role-based access control.
Why use it?
It helps developers identify common security risks, such as unsafe input, path traversal, and injection attacks, while designing or reviewing Rust code.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/tyrchen/cursor-rust-rules/security
Clone the repo
git clone --depth 1 https://github.com/tyrchen/cursor-rust-rules

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 4,903 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.04903
Opus 5 $0.00000 $0.02452
Sonnet 5 $0.00000 $0.00981
Haiku 4.5 $0.00000 $0.00490

Measured 2d ago against content hash 6827189f014a, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

security scanned grade A with 0 findings against 26 rules in 11 categories โ€” prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency โ€” measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.cursor/rules/rust/core/security.mdc ยท 745 lines

How it starts

The opening of the file, as written. The whole thing โ€” 745 lines โ€” stays where its author put it; the contents beside it link to each section on GitHub.

๐Ÿ” RUST SECURITY BEST PRACTICES

TL;DR: Security-focused programming patterns for Rust applications, covering input validation, cryptography, secrets management, and secure coding practices.

๐Ÿ” SECURITY IMPLEMENTATION STRATEGY

graph TD
    Start["Security Assessment"] --> ThreatModel["Threat Modeling"]

    ThreatModel --> InputSecurity{"Input<br>Validation?"}
    ThreatModel --> AuthSecurity{"Authentication<br>Required?"}
    ThreatModel --> DataSecurity{"Data<br>Protection?"}
    ThreatModel --> AccessSecurity{"Access<br>Control?"}

    InputSecurity -->|Yes| Validation["Input Validation"]
    InputSecurity -->|No| InputDone["โœ“"]

    AuthSecurity -->|Yes| PasswordHash["Password Hashing"]
    AuthSecurity -->|No| AuthDone["โœ“"]

    DataSecurity -->|Yes| Encryption["Data Encryption"]
    DataSecurity -->|No| DataDone["โœ“"]

    AccessSecurity -->|Yes| RBAC["Role-Based Access Control"]
    AccessSecurity -->|No| AccessDone["โœ“"]

    Validation --> PathTraversal["Path Traversal Prevention"]
    PathTraversal --> SQLInjection["SQL Injection Prevention"]

    PasswordHash --> Argon2["Argon2 Implementation"]
    Argon2 --> JWT["JWT Token Security"]

    Encryption --> SecretsManagement["Secrets Management"]
    SecretsManagement --> AESGCMEncryption["AES-GCM Encryption"]

    RBAC --> RateLimiting["Rate Limiting"]
    RateLimiting --> Audit["Security Audit Logging"]

    SQLInjection --> SecurityDone["Security Verified"]
    JWT --> SecurityDone
    AESGCMEncryption --> SecurityDone
    Audit --> SecurityDone
    InputDone --> SecurityDone
    AuthDone --> SecurityDone
    DataDone --> SecurityDone
    AccessDone --> SecurityDone

    style Start fill:#4da6ff,stroke:#0066cc,color:white
    style ThreatModel fill:#ffa64d,stroke:#cc7a30,color:white
    style Argon2 fill:#4dbb5f,stroke:#36873f,color:white
    style SecurityDone fill:#d94dbb,stroke:#a3378a,color:white

๐ŸŽฏ SECURITY PRINCIPLES

Input Validation and Sanitization

use validator::{Validate, ValidationError};
use regex::Regex;
use std::collections::HashSet;

// โœ… Always validate and sanitize user input
#[derive(Debug, Clone, Validate)]
pub struct UserRegistration {
    #[validate(email, message = "Invalid email format")]
    pub email: String,

    #[validate(length(min = 8, max = 128, message = "Password must be 8-128 characters"))]
    #[validate(custom = "validate_password_strength")]
    pub password: String,

    #[validate(length(min = 2, max = 50, message = "Username must be 2-50 characters"))]
    #[validate(regex = "USERNAME_REGEX", message = "Username contains invalid characters")]
    pub username: String,
}

lazy_static::lazy_static! {
    static ref USERNAME_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap();
    static ref FORBIDDEN_PASSWORDS: HashSet<&'static str> = {
        let mut set = HashSet::new();
        set.insert("password");
        set.insert("123456");
        set.insert("admin");
        set.insert("qwerty");
        set
    };
}

fn validate_password_strength(password: &str) -> Result<(), ValidationError> {
    // Check for forbidden passwords
    if FORBIDDEN_PASSWORDS.contains(&password.to_lowercase().as_str()) {
        return Err(ValidationError::new("forbidden_password"));
    }

    // Require at least one uppercase, lowercase, digit, and special character
    let has_upper = password.chars().any(|c| c.is_uppercase());
    let has_lower = password.chars().any(|c| c.is_lowercase());
    let has_digit = password.chars().any(|c| c.is_numeric());
    let has_special = password.chars().any(|c| "!@#$%^&*()_+-=[]{}|;:,.<>?".contains(c));

    if !(has_upper && has_lower && has_digit && has_special) {
        return Err(ValidationError::new("weak_password"));
    }

    Ok(())
}

// โœ… SQL injection prevention with parameterized queries
pub async fn find_user_by_email(
    pool: &sqlx::PgPool,
    email: &str,
) -> Result<Option<User>, sqlx::Error> {
    // โœ… Safe: Uses parameterized query
    sqlx::query_as::<_, User>(
        "SELECT id, email, username FROM users WHERE email = $1"
    )
    .bind(email)
    .fetch_optional(pool)
    .await
}

// โŒ NEVER: String interpolation vulnerable to SQL injection
// let query = format!("SELECT * FROM users WHERE email = '{}'", email);

Read the full file on GitHub ยท 745 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen ยท 745 lines ยท 0 tokens per session scan A 6827189f014a

Subscribe to this mod's changes

security is a cursor rule published in the GitHub repository tyrchen/cursor-rust-rules (27 stars, last pushed 1y ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 4,903 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.