Cors Wildcard in Chi with Api Keys
Cors Wildcard in Chi with Api Keys — how this specific combination creates or exposes the vulnerability
Chi is a lightweight HTTP router for .NET that allows flexible route pattern definitions and middleware composition. When an API uses Api Keys for authorization but also sets a CORS policy with a wildcard origin (AllowAnyOrigin), it can unintentionally expose key validation to cross-origin contexts.
In Chi, developers often configure CORS using app.UseCors(builder => builder.AllowAnyOrigin()). This directive adds an Access-Control-Allow-Origin: * header to responses. If the same endpoint requires an Api Key, the browser may still include credentials or custom headers from a malicious origin during a preflight request. Because AllowAnyOrigin does not restrict origins, an attacker’s page can trigger requests that include cookies or authorization headers, and the presence of the Api Key in headers or query strings may be observable or inferable via side channels.
The vulnerability is not that Chi mishandles Api Keys; rather, the combination of per-request key validation and a wildcard CORS policy weakens the boundary between origins. For example, a key passed in the X-API-Key header may be accepted by the endpoint, and if the response includes sensitive data, a compromised page on another origin could indirectly learn whether a key is valid by measuring timing or observing error differences. OWASP API Security Top 10 item Broken Object Level Authorization (BOLA) and CORS misconfigurations are relevant here because improper origin constraints can enable unauthorized cross-origin access patterns.
During a middleBrick scan, endpoints with both Api Key requirements and AllowAnyOrigin may receive a high severity finding under Authentication and CORS/Origin Validation. The scanner checks whether credentials are allowed alongside a wildcard and highlights mismatches between declared CORS policy and intended authentication controls.
To illustrate a correct configuration, consider this Chi setup that avoids the wildcard while still using Api Keys:
var apiKeyAuth = new ApiKeyAuthenticationOptions("X-API-Key");
var policy = new CorsPolicyBuilder()
.WithOrigins("https://trusted.example.com")
.AllowAnyMethod()
.AllowAnyHeader()
.Build();
app.UseCors(builder => builder
.WithOrigins("https://trusted.example.com")
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/secure", (HttpRequest req) =>
{
var key = req.Headers["X-API-Key"].ToString();
if (string.IsNullOrWhiteSpace(key) || !ValidateKey(key))
{
Results.Unauthorized();
return;
}
return Results.Ok("Access granted");
}).RequireAuthorization();
});
In this example, origins are explicitly declared, preventing wildcard leakage while maintaining Api Key checks. middleBrick’s OpenAPI/Swagger analysis can detect mismatches between CORS origins and security schemes, supporting frameworks like OpenAPI 3.0 and 3.1 with full $ref resolution to ensure runtime behavior aligns with declared policies.
Api Keys-Specific Remediation in Chi — concrete code fixes
Remediation focuses on narrowing CORS scope and ensuring Api Key validation is consistent across all origins. The primary fix is to replace AllowAnyOrigin with explicit origins, particularly when keys are involved.
First, configure CORS with specific origins and avoid exposing sensitive responses to arbitrary origins:
app.UseCors(builder => builder
.WithOrigins("https://api.yourdomain.com", "https://app.yourdomain.com")
.AllowAnyMethod()
.AllowAnyHeader());
Second, enforce Api Key validation before request processing and avoid branching logic that might skip checks based on origin:
var apiKeyValidator = new ApiKeyValidator();
app.Use(async (context, next) =>
{
if (!context.Request.Headers.TryGetValue("X-API-Key", out var extractedKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Api Key missing");
return;
}
if (!apiKeyValidator.IsValid(extractedKey))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Invalid Api Key");
return;
}
await next(context);
});
Third, combine CORS and key validation in endpoint definitions to ensure authorization is applied uniformly:
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/data", (HttpRequest request) =>
{
var key = request.Headers["X-API-Key"].ToString();
if (!ValidateKey(key))
{
return Results.StatusCode(401);
}
return Results.Json(new { message = "Authorized" });
}).RequireCors("AllowSpecificOrigins");
});
Finally, when using the middleBrick CLI to verify these changes, you can run:
middlebrick scan https://api.yourdomain.com/openapi.json
The tool reports findings aligned with frameworks such as OWASP API Top 10 and can be integrated into CI/CD via the GitHub Action to fail builds if risk scores degrade. The Pro plan provides continuous monitoring so that future changes to CORS or key handling do not reintroduce wildcard issues.
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 |