HIGH excessive data exposureecho gomongodb

Excessive Data Exposure in Echo Go with Mongodb

Excessive Data Exposure in Echo Go with Mongodb — how this specific combination creates or exposes the vulnerability

Excessive Data Exposure occurs when an API returns more data than the client needs, and the Echo Go framework combined with direct Mongodb usage commonly contributes to this risk. When handlers query Mongodb without field-level filtering, they may return entire documents that include sensitive fields such as password hashes, internal identifiers, audit logs, or personal information.

In Echo Go, a typical pattern is to call collection.Find() and bind results directly to a response struct or return the raw document. If the handler does not explicitly limit the projection, Mongodb returns all fields stored in the document. For example, a user profile endpoint might return a full user document that contains fields like password_reset_token, email_verified_at, and internal metadata, which should never be exposed to API consumers.

Additionally, if query parameters are reflected into Mongodb queries without strict allowlisting (e.g., using raw bson.M built from user input), developers risk unintentionally exposing related data through indirect references or lookups. An attacker who gains access to a token or enumeration behavior might chain requests to retrieve adjacent records, amplifying exposure across collections.

When using the Echo Go middleware stack without a strict serialization layer, developers might also inadvertently expose nested objects or arrays that contain sensitive data. This is especially dangerous when APIs are consumed by frontend JavaScript clients or third-party integrations that assume a minimal contract. The mismatch between what the API intends to expose and what Mongodb returns by default is a common root cause of Excessive Data Exposure in this stack.

middleBrick detects Excessive Data Exposure by comparing runtime responses against expected schema shapes and identifying fields that align with sensitive categories (e.g., authentication tokens, PII, internal statuses). When combined with OpenAPI/Swagger spec analysis, it cross-references declared response models with actual Mongodb-returned fields to highlight discrepancies and provide remediation guidance aligned with OWASP API Top 10 and data protection best practices.

Mongodb-Specific Remediation in Echo Go — concrete code fixes

To prevent Excessive Data Exposure in Echo Go with Mongodb, explicitly define a projection that includes only necessary fields, and avoid returning raw database documents. Use structs that represent the intended public contract and apply field-level filtering in your queries.

Example: Unsafe handler returning full document

func getUser(c echo.Context) error {
    userID := c.Param("id")
    var user bson.M
    err := collection.FindOne(context.Background(), bson.M{"_id": userID}).Decode(&user)
    if err != nil {
        return echo.NewHTTPError(http.StatusNotFound, "user not found")
    }
    return c.JSON(http.StatusOK, user)
}

This handler returns the entire Mongodb document, which may contain sensitive fields. An attacker could enumerate IDs and harvest credentials or internal metadata.

Safe handler with explicit projection and response struct

type UserPublic struct {
    ID        string    `json:"id"`
    Username  string    `json:"username"`
    Email     string    `json:"email"`
    CreatedAt time.Time `json:"created_at"`
}

func getUserSafe(c echo.Context) error {
    userID := c.Param("id")
    var result struct {
        ID        string    `bson:"_id"`
        Username  string    `bson:"username"`
        Email     string    `bson:"email"`
        CreatedAt time.Time `bson:"created_at"`
    }
    projection := bson.M{
        "_id":        1,
        "username":   1,
        "email":      1,
        "created_at": 1,
    }
    err := collection.FindOne(
        context.Background(),
        bson.M{"_id": userID},
        options.FindOne().SetProjection(projection),
    ).Decode(&result)
    if err != nil {
        return echo.NewHTTPError(http.StatusNotFound, "user not found")
    }
    publicUser := UserPublic{
        ID:        result.ID,
        Username:  result.Username,
        Email:     result.Email,
        CreatedAt: result.CreatedAt,
    }
    return c.JSON(http.StatusOK, publicUser)
}

By using SetProjection, only the intended fields are retrieved from Mongodb, and the response is mapped to a dedicated public struct. This ensures that sensitive fields such as password_hash, email_verified_at, or internal flags are never serialized into the HTTP response.

Safe handler with filtered query parameters

func searchUsers(c echo.Context) error {
    q := c.QueryParam("q")
    if q == "" {
        return echo.NewHTTPError(http.StatusBadRequest, "q is required")
    }
    cursor, err := collection.Find(
        context.Background(),
        bson.M{"username": bson.M{"$regex": primitive.Regex{Pattern: q, Options: "i"}}},
        options.Find().SetProjection(bson.M{"_id": 1, "username": 1, "email": 1}),
    )
    if err != nil {
        return echo.NewHTTPError(http.StatusInternalServerError, "search failed")
    }
    var results []UserPublic
    if err = cursor.All(context.Background(), &results); err != nil {
        return echo.NewHTTPError(http.StatusInternalServerError, "failed to decode results")
    }
    return c.JSON(http.StatusOK, results)
}

Here, the query uses a regex on username only, and the projection restricts returned fields. This pattern prevents leakage of fields that exist in the collection but are not explicitly requested.

middleBrick’s CLI tool (middlebrick scan <url>) can validate that your endpoints apply projections correctly and flag responses that include unexpected fields. For teams using the Pro plan, continuous monitoring can alert you when new sensitive fields appear in API responses, helping maintain data minimization over time.

Related CWEs: propertyAuthorization

CWE IDNameSeverity
CWE-915Mass Assignment HIGH

Frequently Asked Questions

How can I verify that my Echo Go handlers are not exposing sensitive Mongodb fields?
Use middleBrick’s CLI to scan your endpoints: middlebrick scan . Review the findings for Excessive Data Exposure and check whether response payloads include fields like password hashes or internal IDs. Compare reported fields against your intended public schema and apply projections as shown in the remediation examples.
Does enabling field projections in Mongodb affect performance or require schema changes in Echo Go?
No significant performance impact; projections reduce network payload size by returning only requested fields. You do not need to change your Mongodb schema, but you should define clear response structs in Echo Go and consistently use SetProjection in queries to enforce data minimization.