HIGH pii leakagefiberfirestore

Pii Leakage in Fiber with Firestore

Pii Leakage in Fiber with Firestore — how this specific combination creates or exposes the vulnerability

Pii Leakage in a Fiber application that uses Firestore as a backend typically occurs when application logic or Firestore rules allow unauthorized read or export of documents containing personally identifiable information. Firestore stores data as JSON-like documents within collections and subcollections. If security rules are misconfigured or requests are made without proper validation, a service route in Fiber can inadvertently expose fields such as email, name, phone, or government identifiers.

Consider a Fiber handler that retrieves a user document by ID directly from Firestore without verifying that the requesting user is authorized to view that resource. If the handler trusts client-supplied identifiers (e.g., :id in the path) and does not enforce ownership or role checks, an attacker can iterate through IDs and access other users’ Pii. Firestore’s rule evaluation applies to the request identity; if the rule is permissive (e.g., allowing read access to authenticated users without scoping to the user’s own document), Pii becomes broadly accessible.

Another common pattern is logging or error reporting in Fiber that includes Firestore document contents. If error handlers serialize and return full documents, Pii can be exposed in stack traces or API responses. Similarly, Firestore queries that lack explicit field selection may return entire documents, and if those documents include sensitive fields and the response is forwarded to an LLM or logged, the risk of inadvertent disclosure increases.

The LLM/AI Security checks in middleBrick specifically look for System Prompt Leakage and PII in outputs. When a Fiber endpoint returns Firestore documents that include Pii, middleBrick’s active prompt injection testing and output scanning can detect whether sensitive data appears in responses or is exposed to downstream AI tooling. This is relevant because Firestore documents often contain user profile data that must be protected under frameworks such as GDPR and PCI-DSS.

Additionally, Firestore rules that rely on request.auth != null without validating request.auth.uid against document fields enable horizontal privilege escalation. An attacker authenticated with one account could potentially access another account’s data if the rule does not enforce tenant isolation. middleBrick’s BOLA/IDOR checks are designed to surface these authorization gaps by comparing spec-defined authorization models with runtime behavior.

Remediation guidance centers on scoping Firestore rules to the requesting user, validating ownership on the server in Fiber, and avoiding the inclusion of Pii in logs or error payloads. Use field-level reads only when necessary, and enforce strict rule conditions that tie document paths to authenticated identifiers.

Firestore-Specific Remediation in Fiber — concrete code fixes

To mitigate Pii Leakage in Fiber with Firestore, apply server-side authorization, avoid exposing raw documents, and tighten Firestore security rules. Below are concrete, realistic examples aligned with Firestore security best practices.

1. Authorize access by UID in Fiber before reading Firestore

Ensure the authenticated user’s identity from the session matches the document they are requesting. Do not rely on client-supplied IDs alone.

// Example using Firestore Go SDK
func getUserProfile(c *fiber.Ctx) error {
    uid := c.Locals("uid").(string) // authenticated UID from session/JWT
    paramID := c.Params("id")
    if uid != paramID {
        return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "forbidden"})
    }
    ctx := context.Background()
    client, err := firestore.NewClient(ctx, "your-project-id")
    if err != nil {
        return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "unable to create client"})
    }
    defer client.Close()
    docRef := client.Collection("users").Doc(paramID)
    docSnap, err := docRef.Get(ctx)
    if err != nil || !docSnap.Exists() {
        return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "not found"})
    }
    // Select only safe fields
    data := docSnap.Data()
    safe := map[string]interface{}{
        "displayName": data["displayName"],
        "photoURL":    data["photoURL"],
    }
    return c.JSON(fiber.Map{"profile": safe})
}

2. Use Firestore rules that scope reads to the requesting user

Rules should enforce that a user can only read their own document. This is evaluated on the server side by Firestore and cannot be bypassed by the client.

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
      allow list: if false; // avoid collection-wide listing
    }
  }
}

3. Avoid returning full documents from Fiber handlers

Return only necessary fields and never include sensitive Pii unless explicitly required and consented. This reduces the impact of accidental leaks.

// Filter fields before sending response
type SafeUser struct {
    DisplayName string `json:"displayName"`
    Email       string `json:"email"` // only include if necessary and consented
}
func listUsers(c *fiber.Ctx) error {
    ctx := context.Background()
    client, err := firestore.NewClient(ctx, "your-project-id")
    if err != nil {
        return c.SendStatus(fiber.StatusInternalServerError)
    }
    defer client.Close()
    iter := client.Collection("users").Limit(10).Documents(ctx)
    var results []SafeUser
    for {
        doc, err := iter.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            continue
        }
        var su SafeUser
        // explicitly map safe fields
        if v, ok := doc.Data()["displayName"].(string); ok {
            su.DisplayName = v
        }
        if v, ok := doc.Data()["email"].(string); ok {
            su.Email = v
        }
        results = append(results, su)
    }
    return c.JSON(fiber.Map{"users": results})
}

4. Sanitize logs and error messages

Ensure Firestore documents or Pii are not included in logs returned to the client. Use structured logging that excludes sensitive fields.

func safeError(c *fiber.Ctx, msg string) error {
    // Log internally without Pii
    fmt.Printf("api error: %s\n", msg)
    return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": msg})
}

5. Use middleware to validate authentication and ownership

Centralize checks so handlers do not repeat authorization logic incorrectly.

func AuthMiddleware(c *fiber.Ctx) error {
    token := c.Get("Authorization")
    // validate token and extract uid
    uid, err := validateToken(token)
    if err != nil {
        return c.SendStatus(fiber.StatusUnauthorized)
    }
    c.Locals("uid", uid)
    return c.Next()
}

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

How does middleBrick detect Pii Leakage in Fiber responses that include Firestore data?
middleBrick scans API responses for patterns matching PII such as email, phone, and government IDs. If a Fiber endpoint returns Firestore documents containing these fields, the scanner flags them as potential Pii Leakage findings.
Can Firestore security rules alone prevent Pii Leakage in a Fiber application?
Firestore rules are essential and should scope access to the requesting user, but they must be complemented by server-side validation in Fiber. Rules alone cannot prevent application-layer bugs or insecure logging that can lead to Pii Leakage.