rust-security
Rust security patterns for web applications. Covers memory safety guarantees, dependency auditing, secure coding practices, and OWASP for Rust ecosystem. USE WHEN: user works with "Rust", "Actix", "Axum", "Rocket", "Warp", asks about "Rust vulnerabilities", "cargo audit", "Rust injection", "Rust authentication" DO NOT USE FOR: general OWASP concepts - use `owasp` or `owasp-top-10` instead, other language security - use language-specific skills
What this skill does
# Rust Security - Quick Reference
## When NOT to Use This Skill
- **General OWASP concepts** - Use `owasp` or `owasp-top-10` skill
- **Java security** - Use `java-security` skill
- **Python security** - Use `python-security` skill
- **Secrets management** - Use `secrets-management` skill
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `rust` for Rust security documentation.
## Rust's Built-in Security Advantages
Rust provides memory safety by default:
- No null pointer dereferences (Option<T> instead)
- No buffer overflows (bounds checking)
- No use-after-free (ownership system)
- No data races (borrow checker)
However, Rust does NOT protect against:
- Logic errors (authorization bugs)
- SQL injection (string handling)
- XSS (template handling)
- Secrets exposure
- Dependency vulnerabilities
## Dependency Auditing
```bash
# cargo-audit - Check for known vulnerabilities
cargo install cargo-audit
cargo audit
# cargo-deny - Policy-based linting
cargo install cargo-deny
cargo deny check
# Check outdated dependencies
cargo install cargo-outdated
cargo outdated
# Snyk for Rust
snyk test
```
### cargo-deny Configuration (deny.toml)
```toml
[advisories]
vulnerability = "deny"
unmaintained = "warn"
yanked = "deny"
[licenses]
unlicensed = "deny"
allow = ["MIT", "Apache-2.0", "BSD-3-Clause"]
[bans]
multiple-versions = "warn"
wildcards = "deny"
[sources]
unknown-registry = "deny"
unknown-git = "deny"
```
### CI/CD Integration
```yaml
# GitHub Actions
- name: Security audit
run: |
cargo install cargo-audit
cargo audit
- name: Dependency policy check
run: |
cargo install cargo-deny
cargo deny check
```
## SQL Injection Prevention
### SQLx - Safe (Compile-time Checked)
```rust
use sqlx::{PgPool, query_as};
// SAFE - Compile-time verified query
let user: Option<User> = sqlx::query_as!(
User,
"SELECT * FROM users WHERE email = $1",
email
)
.fetch_optional(&pool)
.await?;
// SAFE - Runtime query with bind
let user: Option<User> = sqlx::query_as::<_, User>(
"SELECT * FROM users WHERE email = $1"
)
.bind(&email)
.fetch_optional(&pool)
.await?;
```
### Diesel - Safe (Type-safe ORM)
```rust
use diesel::prelude::*;
// SAFE - Type-safe query
let user = users::table
.filter(users::email.eq(&email))
.first::<User>(&mut conn)
.optional()?;
// SAFE - Explicit parameter binding
diesel::sql_query("SELECT * FROM users WHERE email = $1")
.bind::<Text, _>(&email)
.load::<User>(&mut conn)?;
```
### UNSAFE Patterns
```rust
// UNSAFE - String formatting
let query = format!("SELECT * FROM users WHERE email = '{}'", email); // NEVER!
// UNSAFE - String concatenation
let query = "SELECT * FROM users WHERE email = '".to_owned() + &email + "'"; // NEVER!
```
## XSS Prevention
### Askama (Compile-time Templates - Auto-escaping)
```rust
use askama::Template;
#[derive(Template)]
#[template(path = "page.html")]
struct PageTemplate<'a> {
user_input: &'a str, // Auto-escaped in template
}
```
```html
<!-- page.html - auto-escaped -->
<p>{{ user_input }}</p>
<!-- Explicit raw (use with caution) -->
<p>{{ user_input|safe }}</p> <!-- Only if already sanitized -->
```
### Tera (Runtime Templates)
```rust
use tera::{Tera, Context};
let tera = Tera::new("templates/**/*")?;
let mut ctx = Context::new();
ctx.insert("user_input", &user_input); // Auto-escaped
let rendered = tera.render("page.html", &ctx)?;
```
### Manual Sanitization with ammonia
```rust
use ammonia::clean;
// Sanitize HTML input
let safe_html = clean(&user_input);
// Custom policy
use ammonia::Builder;
let safe_html = Builder::default()
.tags(hashset!["p", "b", "i", "a"])
.url_schemes(hashset!["http", "https"])
.link_rel(Some("noopener noreferrer"))
.clean(&user_input)
.to_string();
```
## Authentication - JWT
### jsonwebtoken
```rust
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
use serde::{Serialize, Deserialize};
use chrono::{Utc, Duration};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String, // user_id
email: String,
exp: usize, // expiration
iat: usize, // issued at
}
fn generate_token(user_id: &str, email: &str, secret: &[u8]) -> Result<String, Error> {
let expiration = Utc::now()
.checked_add_signed(Duration::hours(1))
.expect("valid timestamp")
.timestamp() as usize;
let claims = Claims {
sub: user_id.to_owned(),
email: email.to_owned(),
exp: expiration,
iat: Utc::now().timestamp() as usize,
};
encode(
&Header::new(Algorithm::HS256),
&claims,
&EncodingKey::from_secret(secret)
)
}
fn validate_token(token: &str, secret: &[u8]) -> Result<Claims, Error> {
let mut validation = Validation::new(Algorithm::HS256);
validation.validate_exp = true;
let token_data = decode::<Claims>(
token,
&DecodingKey::from_secret(secret),
&validation
)?;
Ok(token_data.claims)
}
```
### Password Hashing with argon2
```rust
use argon2::{
password_hash::{
rand_core::OsRng,
PasswordHash, PasswordHasher, PasswordVerifier, SaltString
},
Argon2
};
fn hash_password(password: &str) -> Result<String, Error> {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
Ok(argon2
.hash_password(password.as_bytes(), &salt)?
.to_string())
}
fn verify_password(password: &str, hash: &str) -> Result<bool, Error> {
let parsed_hash = PasswordHash::new(hash)?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok())
}
```
## Input Validation with validator
```rust
use validator::{Validate, ValidationError};
use regex::Regex;
use lazy_static::lazy_static;
lazy_static! {
static ref NAME_REGEX: Regex = Regex::new(r"^[a-zA-Z\s\-']+$").unwrap();
}
#[derive(Debug, Validate, Deserialize)]
struct CreateUserRequest {
#[validate(email, length(max = 255))]
email: String,
#[validate(length(min = 12, max = 128), custom = "validate_password_strength")]
password: String,
#[validate(length(min = 2, max = 100), regex = "NAME_REGEX")]
name: String,
}
fn validate_password_strength(password: &str) -> Result<(), ValidationError> {
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 {
Ok(())
} else {
Err(ValidationError::new("password_strength"))
}
}
// Axum handler
async fn create_user(
Json(payload): Json<CreateUserRequest>
) -> Result<Json<User>, AppError> {
payload.validate()?;
// payload is validated
}
```
## Secure File Upload (Axum)
```rust
use axum::{
extract::Multipart,
response::Json,
};
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use uuid::Uuid;
const MAX_FILE_SIZE: usize = 10 * 1024 * 1024; // 10 MB
const ALLOWED_TYPES: &[&str] = &["image/jpeg", "image/png", "application/pdf"];
async fn upload_file(mut multipart: Multipart) -> Result<Json<UploadResponse>, AppError> {
while let Some(field) = multipart.next_field().await? {
let content_type = field.content_type()
.ok_or(AppError::BadRequest("Missing content type"))?;
// Validate content type
if !ALLOWED_TYPES.contains(&content_type) {
return Err(AppError::BadRequest("File type not allowed"));
}
let data = field.bytes().await?;
// Validate size
if data.len() > MAX_FILE_SIZE {
return Err(AppError::BadRequest("File too large"));
}
// Generate safe filename
let ext = match content_type {
"image/jpeg" => "jpg",
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.