HIGH cross site request forgeryfiberfirestore

Cross Site Request Forgery in Fiber with Firestore

Cross Site Request Forgery in Fiber with Firestore — how this specific combination creates or exposes the vulnerability

Cross Site Request Forgery (CSRF) in a Fiber application that uses Firestore arises when an authenticated user’s session relies only on cookies (e.g., session cookies) without anti-CSRF protections, and the app performs state-changing Firestore operations based on requests that can be forged by a malicious site. Because Firestore operations are typically authorized by an ID token or session established via cookies, forged requests from another origin can trigger unintended writes or deletions if the server does not validate the request origin and intent.

In this stack, CSRF risk is elevated when:

  • The server sets a long-lived session cookie and does not require a same-site attribute or anti-CSRF token.
  • Endpoints accept POST/PUT/DELETE actions that directly call Firestore with user-supplied IDs or paths without verifying the request source.
  • The client-side code embeds user identity (e.g., UID) in request parameters or headers that an attacker can replicate in a forged request.

For example, consider a Fiber endpoint that deletes a Firestore document based on a document ID provided by the client. If the request is authenticated only by a cookie and lacks a CSRF token, an attacker can craft an HTML form on a malicious site that submits to this endpoint. When the victim’s browser sends the request, the session cookie is included automatically, and Firestore deletes the document on behalf of the victim.

Real-world attack patterns mirror those seen in OWASP API Top 10 A05:2023 (Broken Function Level Authorization) and A01:2021 (Broken Access Control), where lack of proper authorization checks and anti-CSRF controls enable unauthorized operations. Although Firestore enforces its own security rules, those rules often assume the caller is authenticated and authorized at the application layer; they do not inherently prevent CSRF if the application does not enforce origin validation or token-based request verification.

To detect this using spec-driven scanning, an OpenAPI 3.0 definition for a Fiber endpoint might declare cookie-based security schemes without anti-CSRF requirements. middleBrick’s OpenAPI/Swagger analysis resolves $ref paths and cross-references runtime behavior, highlighting endpoints where cookie-only authentication exists without recommended CSRF mitigations. This helps identify where state-changing operations are vulnerable to forged requests.

Firestore-Specific Remediation in Fiber — concrete code fixes

Remediation focuses on ensuring each request is intentional and tied to the user’s session, combined with strict Firestore security rules. Below are concrete Fiber handlers that implement anti-CSRF patterns while interacting with Firestore using the official Go client.

1) Use same-site cookies and anti-CSRF tokens for state-changing endpoints:

package main

import (
	"context"
	"net/http"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/session"
	"cloud.google.com/go/firestore"
	"google.golang.org/api/option"
)

var db *firestore.Client

func init() {
	ctx := context.Background()
	// Use Application Default Credentials or a service account key file
	db, _ = firestore.NewClient(ctx, "your-project-id", option.WithoutAuthentication())
}

func main() {
	app := fiber.New()
	store := session.New(session.Config{
		Key:            "session_id",
		Expiration:     3600,
		CookieDomain:   "",
		CookiePath:     "/",
		CookieSecure:   true,
		CookieHTTPOnly: true,
		CookieSameSite: "lax", // or "strict" for stronger protection
	})
	app.Use(session.Middleware(store))

	// Protected endpoint with CSRF token in header and cookie-based session
	app.Delete("/document/:docID", func(c *fiber.Ctx) error {
		session, err := store.Get(c)
		if err != nil || session.Get("userID") == nil {
			return c.SendStatus(http.StatusUnauthorized)
		}

		// Expect a CSRF token in header; in practice, generate and store this per session
		token := c.Get("X-CSRF-Token")
		sessionToken := session.Get("csrf_token")
		if token != sessionToken {
			return c.SendStatus(http.StatusForbidden)
		}

		docID := c.Params("docID")
		ctx := c.Context()
		_, err = db.Collection("items").Doc(docID).Delete(ctx)
		if err != nil {
			return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to delete"})
		}
		return c.SendStatus(http.StatusNoContent)
	})

	app.Listen(":3000")
}

2) Validate Firestore paths and enforce user ownership in security rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /items/{docID} {
      allow read, write: if request.auth != null
        && request.auth.uid == request.resource.data.userId
        && request.time < request.auth.token.exp * 1000;
    }
  }
}

3) For APIs consumed by browsers, expose a dedicated endpoint to fetch a per-session CSRF token and include it in requests:

app.Get("/csrf-token", func(c *fiber.Ctx) error {
	session, _ := store.Get(c)
	if session.Get("userID") == nil {
		return c.SendStatus(http.StatusUnauthorized)
	}
	// Generate a cryptographically random token per session
	token := generateSecureToken()
	session.Set("csrf_token", token)
	session.Save()
	return c.JSON(fiber.Map{"csrfToken": token})
})

These measures align with best practices for API security, ensuring that even if an attacker can trick a user’s browser into making a request, the missing or mismatched CSRF token blocks the action. middleBrick’s scans can highlight endpoints that rely solely on cookies by analyzing the authentication scheme in the OpenAPI spec and runtime tests, helping you prioritize fixes.

Frequently Asked Questions

Can Firestore security rules alone prevent CSRF in a Fiber app?
No. Firestore rules validate authentication and data conditions but do not block forged cross-origin requests. Application-layer anti-CSRF controls (same-site cookies, tokens) are required.
Does middleBrick test for CSRF in Firestore-backed APIs?
Yes. middleBrick runs 12 parallel security checks, including Authentication and BOLA/IDOR, and can flag endpoints that rely on cookie-only authentication without CSRF protections, using both spec analysis and runtime tests.