Secure System Development Specification / 安全系统开发规范
If the runtime environment has a global asset prohibition (forbidding attacks/scans on certain owned assets), the global configuration takes precedence; this skill does not override it. For generic templates, see
references/internal-policy.example.md(the release version contains no real internal addresses).
Usage
Read the "Red Line Checklist" before writing any code, and self-check after finishing. Read "Phase 1: Design" when designing or reviewing. When a specific module is involved, open the corresponding file under references/ as indicated by the pointer. Run the "Pre-Release Review" before committing. For runtime and zero-day situations, see "Phase 4: Runtime & 0-Day Mitigation".
If a task involves only one area (e.g., writing just a login endpoint, or designing just an orders table), read only that section and its corresponding reference. Do not memorize everything.
Executable Self-Check (Recommended to Run First)
python scripts/scan_redlines.py <target_directory> --format text # Human-readable
python scripts/scan_redlines.py <target_directory> --format sarif --fail-on high # CI blocking
python scripts/scan_redlines.py <target_directory> --code-only # Skip docs, scan code only
Pure Python standard library, no installation dependencies required. Covers 18 rule categories including SQL injection via concatenation, innerHTML/eval, CORS wildcard and reflection, global fallback to homepage, hardcoded secrets, MD5 password storage, command injection, disabled certificate verification, debug toggles, sensitive fields in logs, and unvalidated upload paths. Results will point to the relevant reference.
False Positive Handling: Add a comment redline: ignore at the end of the line (ignores the entire line) or redline: ignore SQL001 (ignores only the specified rule). Do not disable an entire rule just to silence alerts—document the reason and explain during review.
Two templates are available: assets/threat-model-template.md (for design-time threat modeling) and assets/review-checklist.md (a pre-release checklist by project type).
1. Determine Project Type (Decides Which Rules Apply)
| Scenario | Typical Form | Security Rules | Integrity Requirements | Indexing (SEO) |
|---|---|---|---|---|
| Public Site | Official site, landing page, blog, docs, e-commerce frontend | Full set | Low (public content) | Mandatory: real 404, sitemap, canonical, structured data |
| Logged-in Product | SaaS, tool site, community user-facing app | Full set + complete account system | Medium (sensitive operations need signing) | Only submit public pages (marketing/help center); private pages: noindex |
| Admin Panel | admin, operations backend, customer service/review system | Full set + separate entry point + MFA + audit log | High (all write operations signed + audited) | Prohibited: full site noindex + mandatory authentication |
| Internal/Personal System | Internal platform, personal tools, script panel, home NAS | Authentication + minimal exposure + rate limiting + timely updates | Medium (depending on exposure) | Prohibited: do not place on public network default paths; do not rely on "obscurity" for security |
| Pure API | REST / GraphQL / Service-to-service calls | Authentication + input validation + rate limiting + version management | Per business (mandatory high for payments/funds) | Not applicable (no pages generated) |
There is only one determination question: Should this URL appear in search engines?
- Yes → Execute as a public site; all SEO chapter rules apply.
- No → Execute "Prohibit Indexing": full site
X-Robots-Tag: noindex, robots block crawling, mandatory authentication. Do not apply SEO optimizations (sitemap, canonical, structured data) to admin panels or internal systems—it's wasteful and exposes attack surface. - Regardless of the scenario, return a true 404 for non-existent paths must be followed—it's HTTP correctness, not just SEO.
2. Five Fundamental Principles
- All Input is Untrusted: URL, query, body, header, cookie, uploaded files, webhooks, message queues, third-party API responses, and even historical dirty data in databases.
- Fail Closed by Default: When authentication/validation/parsing fails, return a rejection, not a grant; exceptional paths must not reach a "skip validation" branch.
- Least Privilege: Database accounts should be scoped by function (read/write separation, no DDL), cloud IAM/object storage by prefix, processes run as non-root, container filesystems read-only.
- Defense in Depth: When one layer fails, the next is still active. Frontend validation is for user experience; server-side validation is security. WAF is a safety net, not a replacement.
- Limit Blast Radius: Zero-days cannot be prevented by code conventions. Mitigate via isolation, privilege restriction, outbound allowlisting, and a fast patch channel to minimize damage.
3. Red Line Checklist (Mandatory, Self-Check Each Item)
Authentication & Sessions
- Passwords hashed with Argon2id/bcrypt(cost≥12)/scrypt; prohibit MD5/SHA1/reversible encryption
- Login failure rate limiting on both account+IP dimensions, with progressive delay, CAPTCHA/temporary lockout when necessary
- Response text and timing consistent for login/registration/password reset; do not reveal if an account exists
- Rotate session ID after successful login (prevent session fixation); Cookies set with HttpOnly + Secure + SameSite
- JWT: fixed algorithm allowlist on the server; reject
alg:noneand algorithm confusion; short expiry + refresh rotation + revocability - Authentication ≠ Authorization: Explicitly check at each endpoint if the current user can operate on the specific object (prevent IDOR/privilege escalation)
Injection & Output
- All SQL uses parameterized queries or ORM binding; prohibit string concatenation; table names/sort columns use allowlist mapping
- Prohibit concatenating user input into shell/commands; use execFile series with parameter arrays
- Output encode based on context;
dangerouslySetInnerHTML/v-html/innerHTMLmust pass through a sanitizer like DOMPurify - Rich text, Markdown, URL parameters: always allowlist; do not trust any frontend filtering
- Outbound requests (SSRF): allowlist only; do not follow arbitrary redirects; block internal/metadata addresses (169.254.169.254, 127.0.0.1, 10/8, 172.16/12, 192.168/16, ::1, file://, gopher://)
- File paths: validate prefix after
path.resolve; reject..; uploaded files: random naming, MIME-type sniffing, isolated storage, no execution permissions
Data & Concurrency
- Core write operations are idempotent (unique index / idempotency key); ordering, payment, callbacks must be idempotent
- Stock, balance, usage counter fields: use conditional update
UPDATE ... WHERE remaining >= ?; prohibit read-then-write - Transactions are short; do not perform network calls, send messages, or render templates inside a transaction
- All new queries must have an
EXPLAINplan; prohibit largeOFFSETpagination,SELECT *, and N+1 queries - Monetary values use integer cents or DECIMAL; prohibit float/double
Async & Stability
- All external calls (HTTP/DB/Redis/MQ) have explicit timeouts; prohibit infinite waits
- Retries only for idempotent operations; exponential backoff + jitter + max retry count
- Message consumption is idempotent (message_id deduplication table); failures go to DLQ with alerting
- Persist critical state changes to the database before sending messages (Outbox / transactional outbox); prohibit dual writes
Business Logic & Race Conditions (Most Frequently Overlooked)
- Prices, amounts, discounts, permission levels: always calculated server-side; client-submitted values are display-only
- Coupons/redeem codes/invitation codes: bind to user and usage count; atomic redemption (conditional update or unique constraint)
- State machine: explicit transitions; illegal transitions rejected (e.g., pending bypassing payment callback to become paid)
- Payment/fund/callback endpoints: validate signature + timestamp + idempotency key; prevent replay and forgery
- Purchase limits, rate limits: judge by user + device + IP combination; cannot be bypassed by only one dimension
- Export, batch, search endpoints: rate limited + data volume cap + audit trail
Secrets & Operations
- Secrets only in environment variables or a secrets management service; prohibit them in code repositories, Docker image layers, frontend bundles, logs, and error reports
- CI/CD credentials with least privilege; production deployments require approval; third-party dependencies: lock version + scan
- Sensitive operations (login, permission change, export, delete, refund): write audit logs that cannot be tampered with by application code
API Integrity (Anti-Packet-Capture, Anti-Tampering, Anti-Replay, Anti-Forgery)
- Sensitive requests (payment, funds, authorization, password change) use signing:
HMAC(secret, method+path+sortedQuery+sha256(body)+timestamp+nonce); server recalculates - Nonce storage for deduplication (TTL = time window); time window ±300s; reject expired and replayed nonces
- Sensitive responses (payment result, authorization result, balance) include server-side signature; client validates; but the ultimate truth is always re-verified server-side
- Any "validated" flag, price, or role submitted by the client is not a source of truth; server must recalculate/re-verify
- Mobile: certificate pinning; release builds must not trust user certificates; debug and packet capture toggles must be disabled
- Client-side hardening (obfuscation/anti-debugging) only raises the cost of attack, not a security boundary; keys must not be sent to the client
AI / LLM Applications
- Model output is treated as untrusted input: do not
eval, do not directly concatenate into HTML/SQL/commands, do not directly execute tool arguments - Tool/function calls: least privilege + parameter schema validation + human confirmation for high-risk actions
- Documents retrieved by RAG are treated as untrusted content, isolated from system prompts, to prevent indirect prompt injection
- System prompts and user input are separated; do not place secrets or internal rules in positions that can be extracted via prompt injection
- Rate limit per user/tenant based on cost and frequency; log sanitization (do not record sensitive data from full prompts)
Mobile / Mini-Programs
- Sensitive data stored in Keychain (iOS) / Keystore (Android); prohibit plaintext SharedPreferences
- Transport forced TLS with certificate pinning;
InsecureSkipVerify/verify=Falseis strictly prohibited - WebView: disable file access and JS bridge exposure surface;
onShouldStartLoadWithRequestwith domain allowlist - Mini-program
session_keyonly used server-side; never sent to the frontend; issue your own session aftercode2session - Root/jailbreak detection only as a risk signal, not as an authentication basis
HTTP & Routing (All Scenarios)
- Non-existent paths return a real HTTP 404 with a 404 page; prohibit 302/200 redirect to homepage
- SPA history fallback only applies to known frontend routes;
/apiand static resources with extensions always return 404 - CORS: use exact Origin allowlist; prohibit
Access-Control-Allow-Origin: *with credentials; prohibit echoing any Origin back - Production: enable security response headers: HSTS, CSP, X-Content-Type-Options, Referrer-Policy, frame-ancestors
- Authentication/sensitive endpoint responses include
Cache-Control: no-store - Error responses: do not return stack traces, SQL, framework versions, or internal paths
Indexing (Public Sites Only; Admin/Internal Systems Do the Opposite)
- Public site: sitemap lists only 200 pages; canonical deduplication; robots does not leak admin paths; staging environment: full site noindex
- Admin/Internal/Personal systems: full site
X-Robots-Tag: noindex+ robotsDisallow: /; do not generate a sitemap; and require authentication (robots.txt is not access control)
Phase 1: Design Time
Spend 5 minutes on a lightweight threat model before starting:
- Define the scenario: Refer to the project type table above. Confirm if it's a public site, admin panel, internal system, or API. Decide whether to execute the SEO chapter and what the attack surface is.
- Draw the data flow: User → Gateway → Service → Database/Cache/MQ/Third Party. Mark every cross-trust-boundary point.
- List and classify assets: Accounts, credentials, payments, personal data, admin panel. For each, ask: "Who can read it? Who can write it? What is the impact of tampering? How long should it be retained?"
- At each boundary, ask three questions: Who can reach it? Is the input validated? Does failure result in a default deny?
- Define the authorization model: Role → Resource → Action; enforce server-side; hiding buttons on the frontend does not count. For multi-tenant systems, additionally define isolation policies.
- Define async boundaries: Which operations must be synchronous (login, payment confirmation) and which can be asynchronous (notifications, reports, exports).
Design documents must at least specify: project type & indexing strategy, authentication method, authorization model, sensitive data classification & encryption, rate limiting strategy, idempotency keys, graceful degradation on failure, and log/audit scope.
Phase 2: Implementation
Authentication & Login (Highest Priority)
Login is the most common entry point for brute force, credential stuffing, and bypass attacks. Full rules in references/auth-and-session.md. Core non-negotiables:
- Layered rate limiting: per IP, per account, per device fingerprint; use Redis expiring keys for failure counters; do not rely solely on in-memory state.
- Unify error messages to "Incorrect account or password"; align response time (even if the account does not exist, run a fake hash to prevent timing enumeration).
- After successful login, regenerate the session identifier; invalidate old sessions.
- Sensitive operations (password change, binding change, withdrawal, delete) require secondary verification or check the time since last authentication (re-auth window).
- Password reset token: high entropy, one-time, short TTL (≤15 minutes), bound to the user and purpose.
- Admin panel: separate entry point, separate domain or IP allowlist; do not share sessions with the user-facing side.
Input, Injection & Output
See references/web-vulnerability-prevention.md. Principle: Unified input validation (schema), context-aware output encoding.
// Input: validate with schema; reject unknown fields instead of "taking what's needed"
const LoginBody = z.object({ email: z.string().email(), password: z.string().min(8).max(128) }).strict();
// SQL: parameterized; never concatenate
await db.query('SELECT id, password_hash FROM users WHERE email = $1', [email]);
// For positions that cannot be parameterized (ORDER BY, table names): use allowlist
const orderBy = { created_at: 'created_at', amount: 'amount_cents' }[sort] ?? 'created_at';
- XSS: React/Vue default escaping is sufficient; dangerous APIs must be sanitized; CSP as a second line of defense.
- IDOR: Include
owner_id = $currentUserin query conditions; do not "query all then filter on the frontend". - Deserialization/Template injection: no
eval; do not concatenate user input into templates/expressions/regex. - Upload: limit size and type (detect by magic bytes), use random filenames, store in object storage, re-encode images.
Database & High Concurrency
See references/database-concurrency.md. Key points:
- Indexes before optimization: run
EXPLAINon new queries before deployment; watch for type=ALL, filesort, temporary tables. - Pagination: use cursor (keyset), not deep OFFSET; list endpoints must have a stable sort order and an upper limit.
- Hotspot writes: use "conditional update + row lock". Stock deduction example:
UPDATE sku SET stock = stock - $1, version = version + 1
WHERE id = $2 AND stock >= $1;
-- Affected rows = 0 → insufficient stock or concurrency conflict; retry or fail per business logic
- Cache triad: prevent penetration (empty-value cache / Bloom filter), prevent hotkey breakdown (mutex lock / single-flight), prevent avalanche (add random jitter to TTL).
- Connection pool upper limit must be less than database
max_connectionsdivided by number of instances; configure acquisition timeouts. - Revisit sharding/partitioning only when scale demands it; first do indexes, caching, read replicas, hot/cold data separation.
Business Logic & Race Conditions
See references/business-logic-and-race-conditions.md. This type of vulnerability has no universal scanner; it must be thought through one item at a time during design: prices/amounts calculated server-side, coupon atomic redemption, state machine validation, replay prevention, multi-dimensional purchase limits, export rate limiting. All concurrent "read-then-write" patterns must be converted to conditional updates or locking + idempotency.
Async-First Architecture
See references/async-architecture.md. The system defaults to async design:
- All I/O is non-blocking; in Node.js, prohibit synchronous fs/crypto and CPU-heavy operations on the request path (use worker_threads).
- Every external call must have a timeout; propagate trace IDs across the call chain.
- Queue consumption = at-least-once delivery, so consumption must be idempotent; retries have an upper limit; exceed → DLQ + alert.
- Cross-service consistency: use Outbox/CDC; do not perform dual writes.
- Long tasks (exports, batch, reviews): enqueue, immediately return a task ID to the frontend; frontend polls or uses SSE for status pushes.
- Graceful shutdown: stop accepting new requests → await in-flight completions → close queue consumers → close connections.
HTTP, Routing, CORS & SEO
See references/http-routing-cors-seo.md. The three most common pitfalls:
- 404 must be truly 404. Do not globally fallback to the homepage: SPA only falls back to
index.htmlfor known build-time routes;/api/*and paths with extensions return 404 directly. - CORS with an exact allowlist: Compare the Origin to the configured value as a set equality; do not use
includes, prefix matching, or directly echo the request header. - Correct status codes: 401 for unauthenticated, 403 for unauthorized, 404 for not found, 409 for conflict, 422 for validation failure, 429 for rate limited.
SEO applies only to public sites; for admin panels and internal systems, follow the "Prohibit Indexing" rules in the scenario table above. Do not add sitemaps, canonical, or structured data to them—that gives crawlers an attack surface.
Secrets, Operations & Email
See references/operations-and-secrets.md. Key points: layered secret storage and rotation; CI/CD least privilege; containers as non-root; object storage and cloud IAM minimalization; tamper-proof audit logs; email domain SPF/DKIM/DMARC configuration to prevent forgery; data retention and deletion procedures.
API Integrity & Anti-Tampering
See references/api-integrity-and-tampering.md. Packet capture and tampering is the #1 problem for mobile apps and open APIs: request signing (HMAC + timestamp + nonce + body hash), server-side recalculation, signed sensitive responses, nonce deduplication, time windows, certificate pinning. Remember: everything the client can modify is untrustworthy; signing only raises the barrier; server-side recalculation is the truth.
AI / LLM Security
See references/ai-llm-security.md. Model output is equivalent to external input: do not execute, do not concatenate directly, do not use as SQL/commands; tool calls require least privilege + schema validation + human confirmation for high-risk actions; RAG content is untrusted; rate limit per tenant to control cost.
Mobile & Mini-Programs
See references/mobile-and-miniprogram.md. Keychain/Keystore, certificate pinning, WebView hardening, mini-program session_key not sent to the frontend, root detection as a signal only.
Phase 3: Pre-Release Review
Go through in order; mark any "unsure" item as failed:
- Red line checklist 100% checked. Then cross-check by project type: public site checks SEO items; admin/internal system checks noindex and entry isolation; sensitive business checks API integrity.
- Run
python scripts/scan_redlines.py <directory> --fail-on high; high-severity findings must be zeroed out. - Dependency scanning (npm audit / pip-audit / govulncheck / OWASP Dependency-Check); high-severity vulnerabilities must be addressed.
- Secrets check: no secrets in the repository, image, logs, or frontend bundle;
.envmust not be version-controlled; CI logs must also be checked. - Container/host: non-root user, read-only root filesystem, minimal port exposure, outbound allowlist.
- Monitoring and alerting: login failure rate, 5xx errors, queue backlogs, slow queries, abnormal outbound requests.
- Backup and recovery drill; database accounts with least privilege.
- Load test critical paths (login, order, list) to confirm rate limiting and caching are effective.
- Email domain: SPF/DKIM/DMARC configured, sending endpoint rate limited, to prevent abuse for phishing or being blacklisted as a spam source.
- Data lifecycle: define minimum collection, retention period, export & deletion procedure; sanitize logs before retention.
- Incident response plan: who is responsible, how to isolate, how to notify users, how to conduct post-mortem.
- Compliance mapping (if needed): check against OWASP/ASVS/等保/PIPL items using
references/compliance-mapping.md.
Phase 4: Runtime & Zero-Day Mitigation
Code conventions cannot prevent unknown vulnerabilities. Mitigate impact using the following:
- Outbound traffic: default deny + allowlist (first wall against SSRF and supply-chain callbacks).
- Critical services: sandbox/container isolation, process privilege reduction, seccomp/AppArmor as needed.
- Dependency lock + fast image rebuild process; monitor security advisories and reserve an emergency patch channel.
- WAF/gateway: generic signature blocking and rate limiting, but do not rely on it exclusively.
- Behavioral monitoring: abnormal login geo/device changes, batch reads/writes, abnormal outbound traffic.
- Data classification: encrypt sensitive fields at rest (AES-GCM/KMS), sanitize logs, require approval for exports.
References Index
| File | When to Read |
|---|---|
references/auth-and-session.md | Login, registration, passwords, JWT, 2FA, password reset, CSRF, IDOR, admin panel |
references/web-vulnerability-prevention.md | SQL injection, XSS, SSRF, file upload, path traversal, deserialization, response headers, API-specific risks |
references/business-logic-and-race-conditions.md | Prices/amounts, coupons, inventory, state machines, TOCTOU race conditions, purchase limits, export abuse |
references/database-concurrency.md | Table design, indexes, transactions, locks, idempotency, caching, read replicas, sharding |
references/async-architecture.md | Timeouts, retries, queue consumption, Outbox, backpressure, graceful shutdown, observability |
references/http-routing-cors-seo.md | 404, status codes, CORS, caching, robots/sitemap, indexing separation for public vs. admin sites |
references/operations-and-secrets.md | Secrets, CI/CD, containers/cloud, email domains, audit logs, data lifecycle, incident response |
references/api-integrity-and-tampering.md | Packet capture/tampering, request/response signing, replay protection, certificate pinning, client hardening boundaries |
references/ai-llm-security.md | Prompt injection, tool call permissions, RAG poisoning, model output handling, cost rate limiting |
references/mobile-and-miniprogram.md | Local storage, certificate pinning, WebView, mini-program login state, root detection |
references/compliance-mapping.md | OWASP Top 10 / ASVS / 等保 2.0 / PIPL mapping, for audit or review presentations |
references/internal-policy.example.md | When a custom asset prohibition template is needed (placeholder domain, no real addresses) |
Delivery Conventions
- In every code delivery, include a 3–6 line summary of the security decisions made for that iteration (validation points, authorization points, idempotency keys, rate limiting, error handling). Do not skip this.
- First specify the project type: if delivering an admin panel or internal system, explicitly state "No SEO, full site noindex". Only public sites get indexing-related configurations.
- When existing code violates a red line, point out the exact location and provide a fix; do not just say "consider hardening".
- For parts that cannot be verified (e.g., not having actually executed an attack test), explicitly state "Not verified"; do not claim the code has passed security testing.