Pii Leakage in Fiber with Api Keys
Pii Leakage in Fiber with Api Keys
Pii Leakage in a Fiber-based API often occurs when API keys are handled in ways that expose personally identifiable information during request processing, logging, or error reporting. In Go Fiber, developers sometimes attach API keys to request headers or contexts and inadvertently propagate them into logs, error messages, or response bodies that may include user data such as email addresses, names, or IDs. For example, if a middleware logs the full request context including the API key and the handler returns user details, a stack trace or debug output might combine both, creating a data exposure path where PII and credential material coexist in an uncontrolled channel.
Another common pattern involves routing logic that uses API keys to determine tenant or user scope. If the key is parsed and stored in a context value and later used to index a database query that returns PII, misconfigured authorization checks can lead to IDOR-like scenarios where one keyed request retrieves another user’s sensitive data. Because the API key is treated as authorization metadata, developers may overlook that it can also act as an indirect link to PII when response serialization is too broad. A typical endpoint that returns a user profile might include fields such as address or phone number; if the response is not carefully filtered, those fields can be included alongside the keyed identity, resulting in unintended Pii Leakage.
During black-box scanning, middleBrick runs the LLM/AI Security checks which include system prompt leakage detection and output scanning for PII. These checks are designed to identify scenarios where model or handler responses might inadvertently include sensitive data. For instance, if an LLM integration echoes API key context or user input in completions, the scanner can detect exposed patterns such as credit card numbers or email addresses in the output. This is particularly relevant in Fiber services that embed API keys in prompts or tool calls for AI features, as the model’s response may reflect those values unless strict output filtering is applied. The scanner also flags configurations where unauthenticated LLM endpoints exist, which can further increase the risk of PII exposure through uncontrolled model interactions.
Real-world attack patterns mirror these risks. Consider a handler that logs incoming headers for debugging:
app.Use(func(c *fiber.Ctx) error {
apiKey := c.Get("X-API-Key")
c.Locals("apiKey", apiKey)
// Risky: logging full context can expose PII if response is included
util.DebugLog(map[string]interface{}{
"key": apiKey,
"ip": c.IP(),
"body": string(c.Body()),
})
return c.Next()
})
If the debug log is ever exposed or aggregated with user data, Pii Leakage can occur. Additionally, an endpoint that returns enriched data without scrubbing sensitive fields can produce outputs that contain both API key context and PII, which middleBrick would identify under its Data Exposure checks. These findings are mapped to frameworks such as OWASP API Top 10 and can appear alongside compliance references for PCI-DSS and GDPR when PII handling is involved.
Api Keys-Specific Remediation in Fiber
Remediation focuses on isolating API keys from PII at every stage: ingestion, processing, logging, and response. In Fiber, use structured middleware to extract and store keys in a controlled context without attaching user data. Avoid logging raw headers or context values that may contain PII, and ensure serialization functions explicitly exclude sensitive fields.
Below is a secure Fiber middleware pattern that extracts an API key and places it in context without logging sensitive payloads:
func apiKeyMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
apiKey := c.Get("X-API-Key")
if apiKey == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": "missing api key",
})
}
// Store only the key, avoid attaching PII
c.Locals("apiKey", apiKey)
// Explicitly clear sensitive data from logs
requestClone := c.Acquire()
requestClone.Body = nil // avoid logging body
return c.Next()
}
}
In your route handlers, validate authorization against a trusted source and ensure responses exclude PII when the key is used for scoping:
app.Get("/profile", apiKeyMiddleware(), func(c *fiber.Ctx) error {
key := c.Locals("apiKey").(string)
// Authorize key against a store or introspection endpoint
user, err := getUserByApiKey(key)
if err != nil || user == nil {
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"error": "invalid key",
})
}
// Return only safe fields, excluding PII where not needed
return c.JSON(fiber.Map{
"user_id": user.ID,
"scope": user.Scope,
// Do not include email or phone unless explicitly required and protected
})
})
For AI-enabled endpoints, apply output filtering before sending model responses back to the client. This prevents the model from echoing API key context or PII:
func safeLLMResponse() fiber.Handler {
return func(c *fiber.Ctx) error {
// Assume modelResponse is obtained from an LLM call
modelResponse := generateFromLLM(c.Locals("apiKey").(string))
// Remove or mask any PII and keys before returning
sanitized := filterSensitive(modelResponse)
return c.JSON(sanitized)
}
}
These examples emphasize defense-in-depth: restrict logging, enforce least-privilege authorization, and sanitize outputs. middleBrick’s Pro plan supports continuous monitoring and CI/CD integration, allowing you to enforce security thresholds in pipelines and receive alerts when findings related to Pii Leakage or Data Exposure appear. This helps maintain consistent remediation without relying on manual audits.
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 |