Data Exposure in Fiber
How Data Exposure Manifests in Fiber
Data exposure in Fiber applications typically occurs through improper handling of sensitive information in HTTP responses, logs, or error messages. The most common patterns include:
- Returning database connection strings, API keys, or internal configuration in error responses
- Exposing user PII (email addresses, phone numbers, addresses) in API responses when not required
- Logging sensitive request parameters that appear in stack traces or error logs
- Returning full object models when only partial data is needed
- Exposing internal system metadata through debugging endpoints
In Fiber applications, data exposure often manifests through specific code patterns. For example, using ctx.JSON() with entire struct models without filtering sensitive fields:
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Password string `json:"password"`
SSN string `json:"ssn"`
}
func getUser(ctx *fiber.Ctx) error {
user := getUserFromDB(ctx.Params("id"))
return ctx.JSON(user) // Exposes password and SSN!
}
Another common pattern is improper error handling that reveals internal implementation details:
func createPost(ctx *fiber.Ctx) error {
var post Post
if err := ctx.BodyParser(&post); err != nil {
return ctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": err.Error(), // Exposes internal error details
"stack": string(debug.Stack()), // FULL stack trace exposure
})
}
return ctx.JSON(fiber.Map{"status": "created"})
}
Data exposure can also occur through improper logging configurations. Fiber's default logger may log request bodies containing sensitive information:
app := fiber.New()
app.Use(logger.New()) // Logs request bodies by default
app.Post("/login", func(ctx *fiber.Ctx) {
var creds Credentials
ctx.BodyParser(&creds) // Password logged in plaintext!
// ... authentication logic
})
Fiber-Specific Detection
Detecting data exposure in Fiber applications requires both static code analysis and runtime scanning. Here's how to identify these vulnerabilities:
Static Analysis Techniques
Review your Fiber handlers for these red flags:
// Check for struct tags and field exposure
func inspectStructExposure(s interface{}) {
v := reflect.ValueOf(s)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
for i := 0; i < v.NumField(); i++ {
field := v.Type().Field(i)
jsonTag := field.Tag.Get("json")
// Look for sensitive field names without omitempty/omitempty
if strings.Contains(strings.ToLower(jsonTag), "password") ||
strings.Contains(strings.ToLower(jsonTag), "secret") ||
strings.Contains(strings.ToLower(jsonTag), "key") {
fmt.Printf("Potential exposure: %s\n", field.Name)
}
}
}
Runtime Scanning with middleBrick
middleBrick's black-box scanning approach is particularly effective for detecting data exposure in Fiber APIs without requiring source code access. The scanner tests for:
- Unauthenticated access to sensitive endpoints
- Information leakage in error responses
- Excessive data returned in API responses
- Debug endpoints exposed in production
To scan your Fiber API:
npm install -g middlebrick
middlebrick scan https://your-fiber-api.com
The scanner will automatically detect and report data exposure vulnerabilities, including:
- Debug information in responses
- Stack traces exposed to users
- Sensitive headers returned
- Excessive data in responses
Middleware-Based Detection
Create custom middleware to detect potential data exposure patterns:
func dataExposureDetector() fiber.Handler {
return func(ctx *fiber.Ctx) error {
// Check response for sensitive patterns
originalWrite = ctx.Response().Write
ctx.Response().Write = func(p []byte) (int, error) {
response := string(p)
// Detect potential exposures
if strings.Contains(response, "password") ||
strings.Contains(response, "secret") ||
strings.Contains(response, "key") ||
strings.Contains(response, "token") {
log.Printf("Potential data exposure detected: %s", response)
}
return originalWrite(p)
}
return ctx.Next()
}
}
Fiber-Specific Remediation
Remediating data exposure in Fiber requires a combination of code-level fixes and architectural patterns. Here are Fiber-specific solutions:
Response Filtering with Struct Tags
Use struct tags to control JSON serialization:
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Password string `json:"-"` // Excluded from JSON
SSN string `json:"-"`
InternalID int `json:"-"`
}
// For cases where you need different views
type UserResponse struct {
ID string `json:"id"`
Email string `json:"email"`
}
func getUser(ctx *fiber.Ctx) error {
user := getUserFromDB(ctx.Params("id"))
return ctx.JSON(UserResponse{
ID: user.ID,
Email: user.Email,
})
}
Centralized Error Handling
Implement proper error handling to prevent information leakage:
func errorHandler(err error, ctx *fiber.Ctx) {
// Log full error internally
log.Printf("ERROR: %v\n%v", err, debug.Stack())
// Return generic error to client
ctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "An unexpected error occurred",
"code": "GENERIC_ERROR",
})
}
func createPost(ctx *fiber.Ctx) error {
var post Post
if err := ctx.BodyParser(&post); err != nil {
errorHandler(err, ctx)
return nil
}
// ... business logic
return ctx.JSON(fiber.Map{"status": "created"})
}
Request Logging Configuration
Configure Fiber's logger to exclude sensitive data:
app := fiber.New()
// Custom logger that excludes sensitive data
app.Use(logger.New(logger.Config{
Format: "${blue}INFO${reset} ${time} ${blue}${pid}${reset} ${status} ${method} ${path}\n",
Output: io.Discard, // Or write to secure location
}))
// Custom middleware for safe logging
app.Use(func(ctx *fiber.Ctx) error {
// Mask sensitive headers
req := ctx.Copy()
req.Headers["Authorization"] = "[REDACTED]"
// Log only necessary information
log.Printf("%s %s %s", ctx.Method(), ctx.Path(), ctx.IP())
return ctx.Next()
})
Input Validation and Sanitization
Prevent data exposure through proper input handling:
func sanitizeInput(input string) string {
// Remove potential sensitive patterns
return strings.NewReplacer(
"password=", "[REDACTED]",
"secret=", "[REDACTED]",
"token=", "[REDACTED]",
).Replace(input)
}
func createSensitiveEndpoint(ctx *fiber.Ctx) error {
data := sanitizeInput(string(ctx.Context().PostBody()))
// Process sanitized data
result := processData(data)
// Filter response
filtered := filterSensitiveData(result)
return ctx.JSON(filtered)
}
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |
Frequently Asked Questions
How can I test my Fiber API for data exposure vulnerabilities?
middlebrick scan https://your-api.com and it will automatically detect data exposure issues including sensitive information in responses, debug endpoints, and excessive data leakage. The scanner tests unauthenticated attack surfaces and provides specific findings with severity levels and remediation guidance.