python-security
Guideline for designing, implementing, and verifying secure Python applications following OWASP Top 10 best practices. Use when the user wants to: (1) review Python code for security vulnerabilities, (2) design a secure Python application architecture, (3) implement security features (authentication, authorization, cryptography, input validation), (4) audit Python dependencies for known vulnerabilities, (5) create security checklists or verification plans, (6) fix security bugs or harden existing Python code, (7) set up security testing and static analysis (bandit, safety, semgrep), or (8) handle any Python security concern including injection prevention, secure deserialization, SSRF protection, secrets management, and secure deployment.
What this skill does
# Python Security Development Guide Provide a structured approach to building secure Python applications, covering the OWASP Top 10, secure coding patterns, and verification checklists. Apply these guidelines throughout the secure development lifecycle — from threat modeling through deployment. ## Secure Development Lifecycle ### Phase 1: Threat Modeling and Secure Design Before writing code, identify and mitigate threats at the design level: - **Identify trust boundaries** — Map where untrusted data enters the system (HTTP requests, file uploads, database reads, environment variables, third-party APIs) - **Map data flows** — Trace sensitive data (credentials, PII, tokens) through the system and verify protection at each stage - **Enumerate entry points** — List all routes, endpoints, CLI arguments, message queue consumers, and cron jobs - **Map attack surfaces to OWASP Top 10** — Cross-reference each entry point against the OWASP categories in the quick reference table below Design with security controls built-in: - Centralized authentication and authorization middleware — never scatter auth checks across handlers - Input validation at every trust boundary — validate early, reject invalid data before processing - Least-privilege database access — use read-only connections where writes are not needed - Defense in depth — layer multiple controls (input validation + parameterized queries + WAF) - Fail securely — deny by default, require explicit grants ### Phase 2: Secure Implementation #### Critical Prohibitions Never use these patterns. Violations are high-severity findings in any review. | Never | Instead | |-------|---------| | `eval()` / `exec()` with untrusted input | `ast.literal_eval()` or a dedicated parser | | `pickle.load()` with untrusted data | `json.loads()` or validated schema (e.g., Pydantic) | | `yaml.load()` | `yaml.safe_load()` | | `shell=True` + user input in subprocess | `subprocess.run([cmd, arg1, arg2])` with list args | | `os.system()` | `subprocess.run()` | | String formatting / f-strings in SQL | Parameterized queries (`cursor.execute(sql, params)`) | | `random` module for security purposes | `secrets` module | | MD5 / SHA1 for password hashing | `bcrypt` or `argon2-cffi` | | `assert` for security checks | `if not condition: raise SecurityError(...)` | | Bare `except:` or `except Exception:` | `except SpecificException:` with proper handling | | Hardcoded secrets in source code | Environment variables or secret manager (Vault, AWS SM) | | `DEBUG=True` in production | Environment-specific configuration | #### Secure Implementation References - For OWASP Top 10 details with vulnerable → secure code examples: See [references/owasp-top-10.md](references/owasp-top-10.md) - For secure coding patterns organized by domain (input validation, auth, crypto, serialization, subprocess, file I/O, web frameworks): See [references/secure-coding.md](references/secure-coding.md) ### Phase 3: Security Verification Apply a layered verification approach: 1. **Static Analysis** — Detect common vulnerability patterns automatically - `bandit` — Python-specific security linter (AST-based) - `semgrep` — Pattern-based analysis with OWASP and Python rulesets - `pylint` — General linting with some security-relevant checks 2. **Dependency Audit** — Identify known vulnerabilities in third-party packages - `pip-audit` — Check installed packages against the OSV database - `safety` — Check against the Safety vulnerability database 3. **Secrets Detection** — Find leaked credentials and API keys - `detect-secrets` — Baseline-aware secrets scanner 4. **Code Review** — Apply the security review workflow and checklists 5. **Security Testing** — Write negative tests that verify rejection of malicious inputs; fuzz-test parsers and validators Quick tool commands: ```bash # Bandit — static analysis bandit -r src/ -f json -o bandit-report.json # pip-audit — dependency vulnerabilities pip-audit # Safety — alternative dependency check safety check # detect-secrets — secrets scanning detect-secrets scan > .secrets.baseline # Semgrep — advanced pattern matching semgrep --config=p/python --config=p/owasp-top-ten src/ ``` For complete verification checklists (code review, architecture review, dependency audit, deployment, testing, incident response): See [references/security-checklist.md](references/security-checklist.md) ### Phase 4: Dependency and Deployment Security #### Dependency Management - Pin all dependencies with exact versions in `requirements.txt` - Use hash verification: `pip install --require-hashes -r requirements.txt` - Run `pip-audit` in CI/CD pipeline on every build - Monitor for typosquatting — verify package names carefully before installing - Review new dependencies before adding — check maintainership, download counts, known issues #### Deployment Hardening - **Container security** — Scan images with `trivy`; use minimal base images (distroless, alpine); run as non-root user - **HTTPS/TLS** — Enforce TLS 1.2+ for all connections; redirect HTTP to HTTPS; set `Strict-Transport-Security` header - **Security headers** — Configure `Content-Security-Policy`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY` - **Secrets at runtime** — Inject secrets via environment variables or mounted volumes; never bake into images - **Least privilege** — Run processes as non-root; use read-only filesystems where possible; limit network access - **Logging** — Use structured logging (JSON); never log passwords, tokens, PII, or full stack traces to users; log authentication events and access denials for audit ## OWASP Top 10:2025 Quick Reference Map each OWASP 2025 category to Python-specific risks and primary mitigations: | # | Category | Python-Specific Risks | Primary Mitigation | |---|----------|----------------------|-------------------| | A01 | Broken Access Control | Missing `@login_required` / auth decorators, IDOR via sequential IDs, path traversal, SSRF via `requests.get(user_url)` | Centralized auth middleware, object-level permissions, `pathlib.resolve()`, URL allowlisting | | A02 | Security Misconfiguration | `DEBUG=True` in prod, `CORS(origins="*")`, Swagger/docs exposed, default `SECRET_KEY`, XXE via xml.etree | Environment-specific config, explicit CORS origins, disable docs in prod, `defusedxml` | | A03 | Software Supply Chain Failures | Unpinned deps, typosquatting, no SBOM, unvetted transitive deps, CI/CD secrets exposure | `pip-audit` in CI, pinned versions with hashes, SBOM generation, CI/CD hardening | | A04 | Cryptographic Failures | `random` module for tokens, MD5/SHA1 password hashing, hardcoded API keys, no encryption at rest | `secrets` module, `bcrypt`/`argon2`, env vars / secret manager, `cryptography` library | | A05 | Injection | SQL via f-strings/`.format()`, `shell=True`, Jinja2 `|safe` / SSTI, `eval()`/`exec()` | Parameterized queries, `subprocess.run([list])`, Jinja2 autoescaping, `ast.literal_eval()` | | A06 | Insecure Design | No rate limiting, missing input validation layer, no abuse case modeling | Threat modeling, validation at boundaries (Pydantic), rate limiting middleware | | A07 | Authentication Failures | Weak session config, JWT `algorithm="none"` or HS256 with public key, no brute-force protection | Secure session settings, explicit `algorithms=["RS256"]`, account lockout / rate limiting | | A08 | Software or Data Integrity Failures | `pickle.loads()` / `yaml.load()` deserialization, unsigned updates, CI/CD pipeline injection | `json.loads()` / `yaml.safe_load()`, signed artifacts, pinned CI actions with SHA | | A09 | Security Logging and Alerting Failures | Logging passwords/tokens, no auth event logging, missing alerting, no playbooks | Structured logging with field filtering, audit trail, alerting thresholds, honeytokens | | A10 | Mishandling of Exceptional Conditions | Bare `except: pass`, failing open, transaction rollback failures, sensitive info in errors | Specifi
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.