HIGH api key exposurechiopenid connect

Api Key Exposure in Chi with Openid Connect

Api Key Exposure in Chi with Openid Connect — how this specific combination creates or exposes the vulnerability

Chi is a lightweight HTTP client library for .NET commonly used to call REST APIs. When developers use Chi in combination with OpenID Connect for authentication, a subtle misconfiguration can lead to API key exposure. The exposure typically occurs when an API key intended for server-to-server or backend use is embedded in client-side code, stored in configuration files that are inadvertently bundled with client artifacts, or logged in application telemetry.

OpenID Connect introduces an authentication layer that relies on tokens (ID tokens and access tokens) issued by an authorization server. If an API key is also required for accessing a protected resource, and that key is passed in an insecure manner—such as via query parameters, URL fragments, or non-HTTPS endpoints—it can be intercepted or leaked. For example, if Chi is configured to attach the API key as a static header or query parameter in every request, and the authorization flow exposes these requests to browser-based code or logs, the key becomes accessible to unauthorized parties.

In a typical OpenID Connect flow using Chi, the application obtains an access token after user authentication and uses it to call downstream APIs. If the API key is hardcoded or stored in environment variables that are accessible to client-side processes (e.g., in a Single Page Application that incorrectly hosts server-side code), an attacker who gains access to the runtime environment can extract both the token and the key. This is especially risky when the same key is used across multiple services, increasing the blast radius of a single exposure.

Another vector involves improper redirect URI configurations in OpenID Connect. If the redirect URI is not strictly validated, an attacker may manipulate the authorization flow to capture tokens or force the application to send requests with embedded API keys to malicious endpoints. Chi requests that include API keys in headers can be intercepted if the application does not enforce strict HTTPS and certificate validation, allowing an attacker to perform man-in-the-middle attacks and harvest sensitive credentials.

Logging and telemetry further contribute to exposure. If Chi requests include API keys in headers or payloads, and the application logs full request details for debugging, those logs may contain sensitive keys. In environments where logs are centralized or retained for long periods, this creates a persistent risk. The combination of OpenID Connect’s token-based model and Chi’s straightforward request customization can inadvertently amplify this risk if developers assume that authentication alone protects API keys.

Real-world attack patterns include compromised CI/CD pipelines that expose configuration files containing API keys, or dependency confusion attacks where malicious packages intercept Chi requests. Additionally, if the OpenID Connect implementation does not properly scope access tokens, an attacker may leverage a low-privilege token to access endpoints that also require an API key, bypassing intended isolation controls.

Openid Connect-Specific Remediation in Chi — concrete code fixes

To mitigate API key exposure when using Chi with OpenID Connect, implement strict separation of concerns between authentication tokens and API keys, enforce secure transport, and avoid storing sensitive values in client-accessible locations.

1. Secure Configuration and Environment Isolation

Store API keys in secure server-side configuration stores, such as Azure Key Vault or environment variables accessible only to backend services. Never embed API keys in client-side code or configuration files that are shipped to browsers.

// Example: Secure API key retrieval in a server-side Chi handler
var apiKey = Environment.GetEnvironmentVariable("API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
    throw new InvalidOperationException("API key is not configured.");
}

var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", apiKey);

var request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com/data");
var response = await client.SendAsync(request);

2. Use Access Tokens Instead of API Keys Where Possible

Leverage the access token issued by OpenID Connect to authorize requests, reducing reliance on static API keys. When API keys are necessary, ensure they are scoped to specific operations and rotated frequently.

// Example: Using OpenID Connect access token with Chi
var client = new HttpClient();

async Task CallApiWithTokenAsync(string accessToken)
{
    var request = new HttpRequestMessage(HttpMethod.Get, "https://api.example.com/secure-endpoint");
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    return await client.SendAsync(request);
}

// Access token obtained via OpenID Connect flow
string accessToken = await GetAccessTokenFromOidcAsync();
await CallApiWithTokenAsync(accessToken);

3. Enforce HTTPS and Validate Redirect URIs

Ensure all Chi requests use HTTPS and validate OpenID Connect redirect URIs against a strict allowlist to prevent authorization code interception and token leakage.

// Example: Configuring OpenID Connect with strict redirect validation in ASP.NET Core
services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "OpenIdConnect";
})
.AddCookie("Cookies")
.AddOpenIdConnect("OpenIdConnect", options =>
{
    options.Authority = "https://auth.example.com";
    options.ClientId = "chi-client";
    options.ResponseType = "code";
    options.RedirectUri = "https://app.example.com/callback";
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = "https://auth.example.com"
    };
    options.Configuration = new OpenIdConnectConfiguration
    {
        Issuer = "https://auth.example.com",
        AuthorizationEndpoint = "https://auth.example.com/connect/authorize",
        TokenEndpoint = "https://auth.example.com/connect/token"
    };
});

4. Avoid Logging Sensitive Headers

Configure logging filters to exclude API keys and authorization headers from request logs. This prevents accidental exposure in centralized logging systems.

// Example: Exclude sensitive headers in logging middleware
app.Use(async (context, next) =>
{
    var originalBody = context.Response.Body;
    using var newBody = new MemoryStream();
    context.Response.Body = newBody;

    await next();

    // Ensure headers do not contain sensitive data before logging
    if (context.Request.Headers.ContainsKey("X-API-Key"))
    {
        // Mask or omit the header in logs
        context.Request.Headers["X-API-Key"] = "[REDACTED]";
    }

    newBody.Seek(0, SeekOrigin.Begin);
    await newBody.CopyToAsync(originalBody);
    context.Response.Body = originalBody;
});

5. Implement Strict Scope and Token Binding

Configure OpenID Connect to request minimal scopes and bind tokens to specific audiences and endpoints. This limits the impact of token leakage and ensures that API keys are only used where explicitly required.

// Example: Requesting minimal scopes in OpenID Connect
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("api1.read"); // Specific scope for the target API

// Token binding to audience
options.TokenValidationParameters = new TokenValidationParameters
{
    ValidAudience = "https://api.example.com",
    ValidateAudience = true
};

Frequently Asked Questions

How does Chi handle API keys in requests when using OpenID Connect?
Chi does not manage API keys automatically. Developers must explicitly configure how keys are attached, preferring server-side handling and avoiding inclusion in client-side code or logs.
Can OpenID Connect tokens replace API keys entirely?
In many cases, yes. Use access tokens issued by OpenID Connect for API authorization. Reserve API keys for scenarios where token-based access is not feasible, and ensure they are stored and transmitted securely.