HIGH server side template injectionfibermongodb

Server Side Template Injection in Fiber with Mongodb

Server Side Template Injection in Fiber with Mongodb — how this specific combination creates or exposes the vulnerability

Server Side Template Injection (SSTI) occurs when user-controlled data is embedded into a server-side template without proper sanitization, enabling an attacker to alter template logic. In a Fiber application using MongoDB as the backend, risk arises when dynamic values (e.g., user input from query parameters or JSON bodies) are passed into a Go template that also interacts with MongoDB queries. If a developer builds a handler that injects user input into a template and then uses that template-rendered context to drive MongoDB operations (such as building filter documents or options), an attacker can manipulate template execution to affect query structure or behavior.

For example, consider a handler that accepts a collection parameter and uses Go’s text/template to produce a response. If the template includes user-controlled values without escaping, an attacker can inject template actions that read or modify variables in the template’s context. Even when the template output itself is not directly used for MongoDB commands, the surrounding application code may construct a MongoDB query using values derived from the template execution context, thereby allowing an attacker to influence which fields are queried, filtered, or returned. This becomes especially dangerous when the application logic implicitly trusts the template context as a source of query constraints, enabling unintended data access or data leakage.

Because middleBrick tests unauthenticated attack surfaces and includes SSTI patterns within its 12 security checks, it can identify unsafe use of templates combined with MongoDB-driven behavior. The scanner does not assume trust in any part of the request flow and evaluates how user input propagates through templates and into backend interactions such as database queries. Findings include severity ratings and remediation guidance mapped to frameworks like OWASP API Top 10, helping teams understand how improper handling of templates in a Fiber + MongoDB stack can lead to data exposure or logic manipulation.

Mongodb-Specific Remediation in Fiber — concrete code fixes

To mitigate SSTI in Fiber when working with MongoDB, ensure that user input never reaches Go templates, and keep data separate from template logic. Use strict allowlists for collection and field names, avoid constructing query options from template context, and rely on strongly typed structures for MongoDB operations. The following examples show safe patterns.

  • Safe handler with explicit collection selection and no user-driven templates:
// main.go
package main

import (
	"context"
	"log"
	"net/http"

	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var allowedCollections = map[string]string{
	"users": "users",
	"posts": "posts",
}

func main() {
	app := fiber.New()
	client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
	db := client.Database("mydb")

	app.Get("/collection/:name", func(c *fiber.Ctx) error {
		name := c.Params("name")
		collName, ok := allowedCollections[name]
		if !ok {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid collection"})
		}
		collection := db.Collection(collName)
		var result map[string]interface{}
		if err := collection.FindOne(c.Context(), fiber.Map{}).Decode(&result); err != nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
		}
		return c.JSON(result)
	})

	log.Fatal(app.Listen(":3000"))
}
  • Using structured queries instead of building filters from template variables:
// handlers.go
package main

import (
	"context"
	"encoding/json"
	"net/http"

	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type UserFilter struct {
	Status string `json:"status"`
	Limit  int32  `json:"limit"`
}

func GetUsersHandler(db *mongo.Database) fiber.Handler {
	return func(c *fiber.Ctx) error {
		var f UserFilter
		if err := c.BodyParser(&f); err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid payload"})
		}
		// Validate allowed status values with an allowlist
		allowedStatus := map[string]bool{"active": true, "inactive": true}
		if f.Status != "" && !allowedStatus[f.Status] {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "invalid status"})
		}
		filter := bson.M{}
		if f.Status != "" {
			filter["status"] = f.Status
		}
		if f.Limit > 0 {
			filter["limit"] = f.Limit
		}
		cursor, err := db.Collection("users").Find(c.Context(), filter)
		if err != nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
		}
		defer cursor.Close(c.Context())
		var users []map[string]interface{}
		if err = cursor.All(c.Context(), &users); err != nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
		}
		return c.JSON(users)
	}
}

These patterns avoid placing user input into templates and instead enforce strict allowlists and typed structures when forming MongoDB queries, reducing the attack surface for SSTI and related injection paths.

Frequently Asked Questions

Can middleBrick detect SSTI in a Fiber + MongoDB API without authentication?
Yes. middleBrick scans the unauthenticated attack surface and includes patterns that can identify unsafe template usage combined with MongoDB-driven behavior, even without credentials.
Does middleBrick provide specific guidance for fixing SSTI in Go templates?
middleBrick reports findings with prioritized severity and remediation guidance, including recommendations such as avoiding user input in templates and using allowlists for collection and field names.