A Developer's Guide to Common Web Vulnerabilities and How to Fix Them

2026-11-29来源 dev.toEnglish

Most web security fixes start at a trust boundary. A route accepts an invoice ID from a browser. A database query takes a search term. A page displays a comment. Before deploying, identify what each boundary accepts, what authority it grants, and how it handles failure.

The OWASP Top 10:2025 gives teams a shared vocabulary for this review. The examples below use Express 5, PostgreSQL via pg, and browser JavaScript. The same controls apply in other stacks.

Enforce access control where you load the data

Authentication establishes who made a request. Authorization determines whether that person can perform the requested action on a specific record. A route can require login and still expose another customer’s invoice if it queries by invoice ID alone.

For an application where each invoice belongs to one user, scope the query to the authenticated user. The example assumes session middleware has already populated req.session.userId after login and pool is a configured pg.Pool.

The route accepts positive invoice IDs written with ASCII decimal digits. It checks the format before calling Number() to reject inputs such as 1e3 and 0x10. The example assumes invoices.id is a PostgreSQL integer, so the accepted range is 1 through 2,147,483,647. PostgreSQL numeric types

app.get("/invoices/:id", async (req, res) => { const userId = req.session?.userId; if (!userId) { return res.sendStatus(401); } const rawInvoiceId = req.params.id; if (!/^[0-9]+$/.test(rawInvoiceId)) { return res.sendStatus(400); } const invoiceId = Number(rawInvoiceId); if (invoiceId < 1 || invoiceId > 2_147_483_647) { return res.sendStatus(400); } const { rows } = await pool.query( `SELECT id, total_cents, status FROM invoices WHERE id = $1 AND owner_id = $2`, [invoiceId, userId], ); if (rows.length === 0) { return res.sendStatus(404); } return res.json(rows[0]); }); 

Apply the authorization rule to updates, deletes, exports, and bulk operations as well. For shared workspaces, resolve membership and check the permission required for the action. Include two users in your integration fixtures. Verify that each can see their own invoice and that requests for another user’s invoice return 404 under this policy. OWASP Broken Access Control

Pass SQL values as query parameters

SQL injection occurs when application input becomes part of a SQL statement’s syntax. Pass every dynamic value separately from the SQL text. The invoice route already does this with $1 and $2. Use the same pattern for less obvious inputs, such as pagination and search. findInvoices expects ownerId from trusted server-side authorization context, such as the authenticated session.

async function findInvoices(pool, ownerId, status, limit = 25) { if (!["open", "paid", "void"].includes(status)) { throw new RangeError("Invalid invoice status"); } if (!Number.isInteger(limit) || limit < 1 || limit > 100) { throw new RangeError("Limit must be between 1 and 100"); } const { rows } = await pool.query( `SELECT id, total_cents, status FROM invoices WHERE owner_id = $1 AND status = $2 ORDER BY id DESC LIMIT $3`, [ownerId, status, limit], ); return rows; } 

Validation enforces business rules and bounds the size of the result. Parameterization keeps values out of SQL syntax. SQL identifiers such as column names require a different approach. If the UI supports sorting, map each accepted sort key to a fixed clause defined in code and reject unknown keys. Give the application’s database role only the permissions it needs at runtime. node-postgres query documentation

Render untrusted text with text APIs

Cross-site scripting (XSS) happens when a browser interprets untrusted content as executable code. Content can come from a database, a URL, or an API. For plain-text comments, create an element and set its textContent. This snippet assumes the page contains an element with id="comments" and the script runs after that element is available in the DOM.

function appendComment(list, comment) { const item = document.createElement("li"); item.textContent = comment.body; list.append(item); } const comments = document.querySelector("#comments"); appendComment(comments, { body: "<b>Leave at reception</b>", }); const item = comments.lastElementChild; console.assert(item.textContent === "<b>Leave at reception</b>"); console.assert(item.querySelector("b") === null); 

The page displays <b>Leave at reception</b> literally, without creating a <b> element. In server-rendered templates, keep automatic escaping enabled. If a feature requires user-authored HTML, sanitize it with a maintained HTML sanitizer and a narrow allowlist. Use a Content Security Policy to limit script execution, and check its behavior on the actual production pages, including pages that load third-party assets. OWASP XSS Prevention Cheat Sheet

Protect cookie-based sessions and writes

Browsers can attach session cookies automatically. Cross-site request forgery (CSRF) takes advantage of that behavior when a server accepts a state-changing request without checking whether it came from the application.

Serve session cookies over HTTPS with Secure and HttpOnly. Choose a SameSite setting that fits your login flow. Express 5 has no built-in CSRF protection. For cookie-authenticated writes, add CSRF middleware or use a per-session token. The server must generate an unpredictable token, bind it to the session, and validate it against that session on every state-changing request. Give the token to the application through a same-origin response and require it in a header or form field on each write. Do not use GET for actions that change application state. Express middleware · OWASP CSRF Prevention Cheat Sheet

Test that a write with a valid session and a missing or invalid CSRF token returns 403. Also test that login regenerates the session ID, logout invalidates the server-side session, and expired sessions require sign-in. Apply rate limits to login and recovery endpoints. If you manage passwords locally, use a maintained password-hashing library with Argon2id and follow its configuration guidance. Express production security guidance · OWASP Password Storage Cheat Sheet

Restrict outbound requests

Server-side request forgery (SSRF) occurs when user input steers a server into making a request to an unintended destination. Review features such as link previews, remote imports, and webhooks because their requests originate from your infrastructure.

If an integration only needs known providers, accept a provider ID and resolve it to an endpoint from server-owned configuration. Disable automatic redirects unless the integration needs them. Block loopback addresses, private networks, and cloud metadata endpoints. Apply the destination policy to the resolved IP address before connecting on the initial request and on every redirect hop. Address checks must cover both IPv4 and IPv6. Connect only to an address that passed the check. If arbitrary public URLs are a product requirement, use an allowlist of schemes such as HTTP and HTTPS, and enforce destination restrictions at a controlled outbound proxy or network layer. Set timeouts and response-size limits so a slow or oversized response cannot hold resources indefinitely. OWASP SSRF Prevention Cheat Sheet

Verify the production configuration before release

Run these checks against a staging deployment with the same proxy, session, and network settings as production.

  • Configuration and secrets. Confirm that the public endpoint uses HTTPS, debug output is disabled, and secrets come from the deployment’s secret store. Inspect response headers and cookie attributes through the public endpoint, where proxy settings affect what the browser receives.
  • Dependencies and builds. Commit the lockfile, install from it in CI, and scan direct and transitive dependencies. Restrict who can modify the release workflow and publish artifacts. Verify signatures or digests when an update or deployment depends on externally produced artifacts.
  • Design and failure paths. Define business rules such as who may approve a refund and how many times it can be issued. Test retries and concurrent requests. If authorization cannot be checked, reject the operation. If a multi-step write fails, roll it back or use a workflow that can safely resume.
  • Logging and alerting. Record failed authentication, denied access, and privileged changes with a correlation ID. Exclude passwords, session cookies, and tokens. Trigger a staging alert and confirm the on-call recipient can trace it to the relevant request.

These checks address risks across application code, deployment configuration, and operations. OWASP Developer Guide

Summary

Authorize every protected operation, parameterize database queries, render untrusted text safely, and protect session-backed writes. Restrict what the server can reach, then verify the controls and their failure paths in staging before deployment.

原文:https://www.a8q9.cn/en/article/a-developer-s-guide-to-common-web-vulnerabilities-and-how-to-fix-them-93192e.html

相关文章