Audit endpoints for CSRF

A quick review of a web app's endpoints catches most CSRF mistakes: state changes over GET, missing tokens, and cookies that are sent cross-site.

What to build

Review a list of endpoints and the session cookie's settings, and report every CSRF problem.

Requirements

  • Line 1: the session cookie's SameSite setting and whether it is Secure, for example Lax yes.
  • Each remaining line is an endpoint METHOD path changes token, where changes and token are yes or no.
  • Problems, checked in this order for each endpoint: GET changes state (method GET and changes yes); no CSRF token (changes yes and token no, for any method).
  • Print each endpoint's problems as METHOD path: problem; problem, only for endpoints that have problems.
  • Then print one cookie line: cookie: None without Secure is rejected if SameSite is None and not Secure; cookie: sent cross-site, tokens are the only defence if None and Secure; otherwise cookie: ok.
  • If no endpoint has a problem, print endpoints: ok before the cookie line.

Input

As described.

Output

As described.

Constraints

1 to 50 endpoints.

Example

Input:

Lax yes
GET /profile no no
POST /transfer yes yes
GET /delete yes no

Output:

GET /delete: GET changes state; no CSRF token
cookie: ok

Why it works

A forged request needs a way to trigger a state change and the cookie to come along; GET changes can be fired by any link or image, a missing token removes the main check, and SameSite=None lets the cookie travel cross-site, so these three checks cover the usual holes.

Examples

Example 1 · Input
Lax yes
GET /profile no no
POST /transfer yes yes
GET /delete yes no
Expected output
GET /delete: GET changes state; no CSRF token
cookie: ok
Example 2 · Input
None yes
POST /post yes no
Expected output
POST /post: no CSRF token
cookie: sent cross-site, tokens are the only defence

Hints

Hint 1

Collect problems per endpoint in an array and join them with "; ".

Solution

Show one correct solution (try it yourself first)
const [sameSite, secure] = prompt().trim().split(/\s+/);
let any = false;
let line = prompt();
while (line !== null) {
  if (line.trim()) {
    const [method, path, changes, token] = line.trim().split(/\s+/);
    const problems = [];
    if (method === "GET" && changes === "yes") problems.push("GET changes state");
    if (changes === "yes" && token === "no") problems.push("no CSRF token");
    if (problems.length) {
      any = true;
      console.log(`${method} ${path}: ${problems.join("; ")}`);
    }
  }
  line = prompt();
}
if (!any) console.log("endpoints: ok");
if (sameSite === "None" && secure !== "yes") console.log("cookie: None without Secure is rejected");
else if (sameSite === "None") console.log("cookie: sent cross-site, tokens are the only defence");
else console.log("cookie: ok");

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Cross-site request forgery (CSRF) →