Api Key Exposure in Chi with Firestore
Api Key Exposure in Chi with Firestore — how this specific combination creates or exposes the vulnerability
Chi is a lightweight HTTP library for the Crystal language, commonly used to build REST APIs. When a Chi service interacts with Google Cloud Firestore, developers may inadvertently expose API keys or service account credentials through insecure request handling, logging, or configuration. In this context, api key exposure occurs when sensitive keys are transmitted in URLs, response bodies, logs, or error messages that an attacker can observe via an unauthenticated or insufficiently authenticated endpoint.
Firestore requires authentication via service account keys or workload identity. If a Chi application embeds these keys in source code, environment variables that are logged, or query parameters that are reflected in responses, the keys become part of the unauthenticated attack surface that middleBrick scans. For example, a route that echoes request headers or query strings might return a key if it is passed as a parameter and not properly sanitized.
During a black-box scan, middleBrick tests unauthenticated endpoints for data exposure. If a Chi endpoint returns JSON that includes a Firestore key or a token derived from it, this finding is flagged under Data Exposure and API Key Exposure categories. The scan also checks whether the API key appears in error traces or verbose stack outputs that are returned to the client, which can happen when error handlers are too verbose.
Additionally, Firestore security rules may be misconfigured to allow read or write access without proper authentication. If Chi endpoints expose Firestore document IDs or paths that should be protected, middleBrick’s BOLA/IDOR and Property Authorization checks can identify insecure direct object references. An attacker could manipulate identifiers in URLs to access data they should not see, especially when those identifiers are tied to key-based access patterns.
Because middleBrick runs 12 security checks in parallel, including Data Exposure, Input Validation, and Authentication, it can detect whether API keys are reflected in responses or whether insecure Firestore rules allow unauthorized enumeration. The scanner reviews OpenAPI specs if available, resolving $ref references to cross-check where keys or sensitive structures might be documented or returned unintentionally.
Real-world examples include a Chi route like /users/:id/profile that passes a Firestore document path to the client in error messages, or a debug endpoint that returns environment variables containing keys. middleBrick flags these patterns and provides remediation guidance, such as removing sensitive data from responses and enforcing strict input validation.
Firestore-Specific Remediation in Chi — concrete code fixes
To prevent api key exposure when using Chi with Firestore, apply strict separation between application logic and credentials. Never embed service account keys in source code or environment variables that are logged. Instead, use Google Cloud workload identity federation so that your Chi service accesses Firestore without long-lived keys.
Ensure that Chi responses do not reflect user-controlled input that could contain sensitive values. Use strict input validation and avoid echoing headers or query parameters directly in JSON outputs.
Example: Unsafe Chi route exposing Firestore key
import chi.ci
let router = newRout()
router.get("/debug") do (req: Request, res: Response) =>
let apiKey = ENV["FIRESTORE_API_KEY"]?
res.send(%{"key": apiKey}) # DO NOT DO THIS
This pattern is flagged by middleBrick as high severity data exposure. The key should never be returned to the client.
Secure Chi route with input validation and no key reflection
import chi.ci
import google.cloud.firestore
let db = FirestoreClient.new()
router.get("/users/:id") do (req: Request, res: Response) =>
let id = req.urlParams["id"]?
if not id.all(it.isDigit):
res.status = 400
res.send(%{"error": "invalid user id"})
return
let docRef = db.collection("users").document(id)
let snapshot = docRef.get()
if snapshot.exists:
res.send(%{"name": snapshot["name"], "email": snapshot["email"]})
else:
res.status = 404
res.send(%{"error": "not found"})
This example demonstrates proper input validation and safe Firestore access without exposing credentials. The Chi application uses a service account initialized through secure environment setup, and the response contains only public document fields.
Firestore security rules best practices
Even when using Chi, you must secure Firestore with rules that enforce authentication and least privilege. Avoid rules that allow read/write if true for testing. Instead, scope access to user-specific documents:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
middleBrick’s Property Authorization and BOLA checks validate that such rules are enforced and that endpoints do not allow unauthorized enumeration. If your Chi API exposes Firestore document paths, ensure they are validated against allowed patterns and that tokens are not leaked in URLs or logs.
Use the middleBrick CLI to regularly scan your Chi endpoints: middlebrick scan https://your-api.example.com. The tool provides prioritized findings and remediation guidance without requiring credentials or agents. For ongoing protection, the Pro plan enables continuous monitoring and CI/CD integration to fail builds if risk scores degrade.