security
Secure backend applications against OWASP threats. Implement authentication, encryption, scanning, compliance, and incident response procedures.
What this skill does
# Security Skill
**Bonded to:** `testing-security-agent`
---
## Quick Start
```bash
# Invoke security skill
"Check my code for OWASP vulnerabilities"
"Implement JWT authentication securely"
"Prepare for GDPR compliance audit"
```
---
## Instructions
1. **Assess Risks**: Identify threats and vulnerabilities
2. **Implement Controls**: Add authentication, encryption
3. **Configure Scanning**: Set up SAST, DAST, SCA
4. **Ensure Compliance**: Meet regulatory requirements
5. **Prepare Response**: Create incident response plan
---
## OWASP Top 10 (2025)
| # | Vulnerability | Prevention | Severity |
|---|---------------|------------|----------|
| 1 | Broken Access Control | RBAC, least privilege | Critical |
| 2 | Cryptographic Failures | Strong encryption, TLS | Critical |
| 3 | Injection | Parameterized queries | Critical |
| 4 | Insecure Design | Threat modeling | High |
| 5 | Security Misconfiguration | Hardening | High |
| 6 | Vulnerable Components | SCA scanning | High |
| 7 | Auth Failures | MFA, secure sessions | High |
| 8 | Data Integrity Failures | Signatures | Medium |
| 9 | Logging Failures | Audit logging | Medium |
| 10 | SSRF | Input validation | Medium |
---
## Security Scanning Tools
| Type | Purpose | Tools |
|------|---------|-------|
| SAST | Static code | SonarQube, Semgrep |
| DAST | Dynamic testing | OWASP ZAP, Burp |
| SCA | Dependencies | Snyk, Dependabot |
| Container | Images | Trivy, Grype |
| Secrets | Detection | GitLeaks, TruffleHog |
---
## Examples
### Example 1: Secure Authentication
```python
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from jose import jwt
import secrets
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def create_token(user_id: str) -> str:
return jwt.encode(
{"sub": user_id, "jti": secrets.token_urlsafe(16)},
SECRET_KEY,
algorithm="HS256"
)
```
### Example 2: SQL Injection Prevention
```python
# BAD - Vulnerable to SQL injection
def get_user_bad(user_id: str):
query = f"SELECT * FROM users WHERE id = '{user_id}'"
return db.execute(query)
# GOOD - Parameterized query
def get_user_good(user_id: str):
query = "SELECT * FROM users WHERE id = :id"
return db.execute(query, {"id": user_id})
```
### Example 3: Security Headers
```python
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Strict-Transport-Security"] = "max-age=31536000"
response.headers["Content-Security-Policy"] = "default-src 'self'"
return response
app = FastAPI()
app.add_middleware(SecurityHeadersMiddleware)
```
---
## Compliance Checklists
### GDPR
- [ ] Lawful basis for processing
- [ ] Data minimization
- [ ] Right to access/deletion
- [ ] Breach notification (72h)
- [ ] DPO if required
### PCI-DSS
- [ ] Encrypt cardholder data
- [ ] No CVV storage
- [ ] Access controls
- [ ] Regular testing
- [ ] Audit logging
---
## Troubleshooting
### Common Issues
| Issue | Cause | Solution |
|-------|-------|----------|
| Token expired | Short TTL | Implement refresh tokens |
| CORS blocked | Missing headers | Configure CORS properly |
| Weak encryption | Old algorithms | Use AES-256, RSA-2048+ |
| SQL injection | String concat | Use parameterized queries |
### Incident Response
```
Incident Detected
│
├─→ Contain: Isolate affected systems
├─→ Assess: Determine scope
├─→ Remediate: Fix vulnerability
├─→ Recover: Restore services
└─→ Post-mortem: Document & improve
```
---
## Test Template
```python
# tests/test_security.py
import pytest
class TestSecurityControls:
def test_password_is_hashed(self):
password = "secure123"
hashed = hash_password(password)
assert password not in hashed
assert verify_password(password, hashed)
def test_sql_injection_prevented(self):
malicious_input = "'; DROP TABLE users; --"
# Should not execute the DROP TABLE
result = get_user(malicious_input)
assert result is None # User not found, not table dropped
def test_auth_required_for_protected_routes(self, client):
response = client.get("/api/v1/users/me")
assert response.status_code == 401
```
---
## Resources
- [OWASP Top 10](https://owasp.org/Top10/)
- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)
- [CWE Top 25](https://cwe.mitre.org/top25/)
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.