HIGH cross site request forgerychijwt tokens

Cross Site Request Forgery in Chi with Jwt Tokens

Cross Site Request Forgery in Chi with Jwt Tokens — how this specific combination creates or exposes the vulnerability

Cross Site Request Forgery (CSRF) in the context of Chi with JWT tokens involves a mismatch between authentication and state-changing request handling. Chi is a lightweight HTTP router for Nim, and when JWT tokens are used for authentication, developers may assume that including the token in headers is sufficient protection. However, if anti-CSRF measures are not implemented, an attacker can trick a logged-in user’s browser into submitting unauthorized requests to protected endpoints.

Consider a Chi application that validates JWT tokens in an authentication middleware but does not enforce same-site cookie policies or require custom headers (e.g., X-Requested-With or Authorization: Bearer) for state-changing methods like POST, PUT, or DELETE. If the JWT is stored in an HttpOnly cookie (a common practice to protect against XSS), the browser automatically includes it with requests to the domain. An attacker can craft a malicious form on another site that targets a Chi endpoint such as /api/transfer. When the victim is authenticated, the browser sends the JWT cookie along with the forged request, and the server may process the action as valid because it only checks token presence and signature, not the request origin.

Chi does not enforce CSRF protections by default. If routes rely solely on JWTs in cookies without additional safeguards, the application is vulnerable. For example, a route like post "/api/transfer" that reads the JWT from a cookie and performs fund transfers without verifying that the request originates from a trusted source can be exploited. The OWASP API Top 10 and related standards highlight such authorization and validation gaps. The attack does not require the attacker to read the token; it only requires the victim to be authenticated in the browser.

In a black-box scan by middleBrick, such a Chi endpoint might be flagged under the Authentication and BOLA/IDOR checks if token validation is incomplete, and under BFLA/Privilege Escalation if insufficient authorization checks allow actions a lower-privilege user should not perform. middleBrick’s scans, which include unauthenticated testing of the attack surface, can surface these risks without requiring credentials, providing a score and prioritized findings with remediation guidance.

To illustrate, a vulnerable Chi handler might look like this, where only the JWT cookie is verified without additional CSRF considerations:

import jwt
import chi

type Claims = object
  sub*: string
  exp*: int

proc verifyToken(token: string): Claims =
  # simplified: in practice use proper key and validation
  decode(token, "secret", {VerifyNone})

let api = newRouter()

api.post "/api/transfer":
  let token = request.cookies["token"]
  let claims = verifyToken(token)
  # Process transfer — vulnerable to CSRF because no origin/header check
  response.write("Transferred for " & claims.sub)

In this setup, the JWT token in a cookie is automatically sent by the browser. Without synchronizer token patterns, custom headers, or SameSite cookie attributes, the route is susceptible. middleBrick’s checks for Property Authorization and Unsafe Consumption help identify these gaps by correlating spec definitions with runtime behavior, and its LLM/AI Security module can detect system prompt leakage or prompt injection attempts that might further expose authorization logic.

middleBrick supports OpenAPI/Swagger spec analysis (2.0, 3.0, 3.1) with full $ref resolution, which can cross-reference documented authentication mechanisms against runtime findings. This is valuable when JWTs are described as header-based but implemented in cookies, creating a discrepancy that attackers can exploit. The scanner runs 12 security checks in parallel, including Authentication, BOLA/IDOR, and Unsafe Consumption, delivering a letter-grade risk score and prioritized findings within 5–15 seconds.

Jwt Tokens-Specific Remediation in Chi — concrete code fixes

Remediation for CSRF in Chi with JWT tokens centers on ensuring that requests with side effects are not automatically trusted from the browser. Since JWTs in cookies are automatically sent, defenses must differentiate between safe and unsafe requests.

1) Require custom headers for state-changing methods. Configure Chi routes to require an Authorization: Bearer header or a custom header like X-Requested-With for POST, PUT, DELETE, and other mutating operations. This ensures that requests initiated by third-party sites, which cannot set custom headers, are rejected.

import jwt
import chi

type Claims = object
  sub*: string

proc verifyToken(token: string): Claims =
  decode(token, "your-public-key", {VerifyRS256})

let secure = newRouter()

secure.post "/api/transfer":
  let authHeader = request.headers["Authorization"]
  if not authHeader.startsWith("Bearer "):
    response.status = 401
    response.write("Missing Bearer token")
    return
  let token = authHeader[7..^1]
  let claims = verifyToken(token)
  response.write("Transferred for " & claims.sub)

This pattern ensures that only requests with explicit Authorization headers are processed, mitigating CSRF from cookie-included JWTs.

2) Use SameSite cookie attributes and secure flags. When storing JWTs in cookies, set SameSite=Lax or SameSite=Strict and Secure to limit cookie inclusion in cross-site requests. This is a browser-level control that complements server-side checks.

import cookies

proc setTokenCookie(response: var Response, token: string) =
  response.cookies["token"] = token & "; Path=/; HttpOnly; Secure; SameSite=Lax"

3) Implement synchronizer token pattern or anti-CSRF tokens. Generate a per-session or per-request token stored in the session and required in a header or form field. This token is not automatically sent by the browser, breaking CSRF attacks.

import uuid, strutils

var csrfTokens = initTable[string, string]()

proc generateCsrf(sessionId: string): string =
  let token = $generate(uuid4())
  csrfTokens[sessionId] = token
  return token

proc validateCsrf(sessionId, token: string): bool =
  csrfTokens.getOrDefault(sessionId) == token

# In a route:
let csrf = generateCsrf(sessionId)
# Include csrf in forms as a hidden field, and require it in header X-CSRF-Token

4) Validate Origin and Referer headers. For endpoints that are not embedded in iframes or cross-origin contexts, check that the Origin or Referer header matches the expected domain. This is not foolproof but adds a layer of defense.

proc checkOrigin(request: Request): bool =
  let origin = request.headers.getOrDefault("Origin")
  let referer = request.headers.getOrDefault("Referer")
  let allowed = "https://example.com"
  origin == allowed or referer.startsWith(allowed)

app.route "/api/transfer":
  if request.method == HttpPost:
    if not checkOrigin(request):
      response.status = 403
      response.write("Invalid origin")
      return
    # proceed with JWT validation and business logic

These remediation steps align with best practices around JWT usage and CSRF mitigation. middleBrick’s scans can verify that such measures are in place by analyzing OpenAPI specs and runtime behavior, mapping findings to frameworks such as OWASP API Top 10 and SOC2. The CLI tool (middlebrick scan <url>) and GitHub Action enable teams to integrate these checks into development workflows, while the Web Dashboard tracks security scores over time.

Frequently Asked Questions

Can middleBrick detect CSRF issues when JWTs are stored in cookies?
Yes. middleBrick scans unauthenticated attack surfaces and includes checks for Authentication and Unsafe Consumption. It cross-references OpenAPI/Swagger specs with runtime behavior to identify mismatches, such as JWTs in cookies without required header-based authentication for state-changing methods.
Does middleBrick provide guidance on SameSite and Secure cookie attributes for JWTs?
middleBrick reports on security configurations observed during scanning and provides remediation guidance, including recommendations to use SameSite and Secure cookie attributes for JWTs stored in cookies as part of defense-in-depth for CSRF mitigation.