HIGH zip slipfiberfirestore

Zip Slip in Fiber with Firestore

Zip Slip in Fiber with Firestore — how this specific combination creates or exposes the vulnerability

Zip Slip is a path traversal vulnerability that occurs when user-supplied filenames are used to build file system paths without proper validation. In a Go Fiber application that interacts with Google Cloud Firestore, the risk emerges from two vectors: unsafe handling of uploaded or referenced file paths and insecure deserialization or storage patterns that write data to predictable locations. When a Fiber handler accepts a filename or path parameter and directly concatenates it with a base directory—such as when staging files before Firestore backup or export—the application can be tricked into writing outside the intended directory using sequences like ../../../etc/passwd.

Consider a scenario where a Fiber endpoint receives a Firestore document ID and a proposed filename, then constructs a local path to stage a file before further processing. If the endpoint does not sanitize or validate the filename, an attacker can supply a malicious path that traverses directories. Even when the eventual data is stored in Firestore, the vulnerable staging area or temporary path can lead to unauthorized file overwrites, information disclosure, or serve as a pivot for SSRF or injection if the filename is later used in system commands or passed to other services.

Firestore itself does not directly expose Zip Slip, but the surrounding application logic does. For example, if your Fiber service exports collections to files on disk or uses Cloud Functions triggers that write to a mounted volume, unsanitized inputs can corrupt paths. An attacker might leverage this to overwrite critical files or to manipulate the runtime environment of downstream processes that consume the staged data. Because the scan categories in middleBrick include Input Validation and Unsafe Consumption, such path manipulation patterns are detectable as insecure handling of user-controlled data that can lead to traversal or injection outcomes.

Moreover, when Firestore documents contain fields used to derive filesystem paths—such as a filename or storagePath property—missing validation on these fields can turn seemingly safe NoSQL storage into a vector for traversal. The interaction between Fiber routing, middleware that may normalize paths, and Firestore document fields creates a chain where a single unchecked input can compromise integrity. middleBrick’s checks for BFLA/Privilege Escalation and Property Authorization help surface these logic flaws by correlating runtime behavior with OpenAPI specifications and identifying endpoints where path or permission assumptions are inconsistent.

Firestore-Specific Remediation in Fiber — concrete code fixes

To mitigate Zip Slip in a Fiber application that uses Firestore, enforce strict path validation and avoid direct concatenation of user input into filesystem paths. Use canonicalization and allowlisting, and keep Firestore document fields that influence storage paths tightly controlled. Below are concrete, idiomatic examples for Fiber handlers that safely interact with Firestore.

1. Validate and sanitize filenames before using them in paths

Never trust filenames from clients. Use a strict allowlist of characters and reject paths containing .. or path separators. Prefer generating safe, unique filenames on the server.

package main

import (
    "path/filepath"
    "regexp"
    "strings"

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

var safeFilename = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)

func sanitizeFilename(input string) (string, bool) {
    base := filepath.Base(input)
    if !safeFilename.MatchString(base) {
        return "", false
    }
    return base, true
}

func uploadHandler(db *firestore.Client) fiber.Handler {
    return func(c *fiber.Ctx) error {
        filename := c.FormValue("filename")
        safe, ok := sanitizeFilename(filename)
        if !ok {
            return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid filename"})
        }

        // Use safe filename with a server-side directory
        dst := filepath.Join("/tmp/uploads", safe)
        // Proceed to stream upload to dst, then store metadata in Firestore
        docRef := db.Collection("uploads").NewDoc()
        _, err := docRef.Set(c.Context(), firestore.DocumentData{
            "original": filename,
            "stored":   dst,
            "userId":   c.Locals("uid"),
        })
        if err != nil {
            return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "store failed"})
        }
        return c.JSON(fiber.Map{"ref": docRef.ID})
    }
}

2. Use Firestore for metadata, avoid deriving executable paths from document fields without validation

If Firestore documents include fields that could influence file handling, treat them as untrusted. Do not directly use them in filesystem operations without validation.

type UploadMeta struct {
    FileName string `firestore:"fileName"`
    UserID   string `firestore:"userId"`
}

func getMetadataHandler(db *firestore.Client) fiber.Handler {
    return func(c *fiber.Ctx) error {
        id := c.Params("id")
        var meta UploadMeta
        iter := db.Collection("uploads").Doc(id).Documents(c.Context())
        for {
            doc, err := iter.Next()
            if err == iterator.Done {
                break
            }
            if err != nil {
                return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "read failed"})
            }
            if err := doc.DataTo(&meta); err != nil {
                return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "parse failed"})
            }
        }

        // Validate before any path usage
        safe, ok := sanitizeFilename(meta.FileName)
        if !ok {
            return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid file name in metadata"})
        }
        // Safe usage: use server-controlled base path
        safePath := filepath.Join("/data/incoming", safe)
        // Continue processing with safePath
        return c.JSON(fiber.Map{"path": safePath})
    }
}

3. Apply principle of least privilege and isolate Firestore operations from filesystem actions

Ensure that service accounts used by Fiber have minimal permissions on Cloud Storage and Firestore, and avoid using Firestore-triggered functions to perform unchecked filesystem writes. If you must stage files, isolate the staging directory and clean up after processing.

4. Leverage middleBrick for detection

Use the middleBrick CLI to scan your Fiber endpoints and identify patterns where user input influences file paths or where Firestore document fields are used in system-level operations. The scanner’s Input Validation and Property Authorization checks can highlight risky concatenations and missing allowlists, helping you prioritize fixes.

Frequently Asked Questions

Can Firestore document fields that look like paths be safely used in filesystem operations?
No. Treat any Firestore field that could influence a path as untrusted. Always validate, sanitize, and prefer server-generated paths to prevent traversal or overwrite vulnerabilities.
Does middleBrick fix Zip Slip issues automatically?
middleBrick detects and reports findings with remediation guidance; it does not automatically fix or patch code. Use the provided guidance to update validation and path handling in your Fiber handlers.