HIGH api key exposureaspnetpostgresql

Api Key Exposure in Aspnet with Postgresql

Api Key Exposure in Aspnet with Postgresql — how this specific combination creates or exposes the vulnerability

In an ASP.NET application that connects to a PostgreSQL database, API key exposure typically occurs when sensitive credentials are handled as configuration values or connection strings and then inadvertently surfaced through logging, error messages, or insecure deserialization. A common pattern is storing the PostgreSQL connection string, which may contain embedded credentials or a password, in appsettings.json or environment variables. If the application does not properly restrict access to these configuration sources or fails to sanitize exception details, an authenticated or unauthenticated attacker may be able to read these values through endpoints that return configuration, debug pages, or verbose errors.

For example, consider an endpoint that constructs a connection string at runtime by concatenating values from configuration and returning them as part of a diagnostic response:

// Example of vulnerable code in an ASP.NET controller
[ApiController]
[Route("[controller]")]
public class DiagnosticController : ControllerBase
{
    private readonly IConfiguration _config;
    public DiagnosticController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("connection-string")]
    public IActionResult GetConnectionString()
    {
        var conn = $"Host={_config["DbHost"]};Username={_config["DbUser"]};Password={_config["DbPassword"]};Database={_config["DbName"]};Port={_config["DbPort"]};";
        return Ok(new { ConnectionString = conn });
    }
}

If this endpoint is unintentionally exposed, an attacker can retrieve the full PostgreSQL credentials. Additionally, if the application logs connection strings or query parameters (for example, using ILogger without redaction), credentials may be persisted in log stores and accessed later. A further risk arises when deserialization of user input is performed without strict type constraints, potentially allowing an attacker to inject crafted payloads that lead to configuration or connection-string exposure via object graphs that map to sensitive configuration keys.

In the context of middleBrick’s checks, this behavior would be flagged under multiple categories: Authentication (for exposed credentials), Data Exposure (for sensitive values in responses), and Unsafe Consumption (if untrusted input is bound to configuration or objects). Even when authentication is required to reach the endpoint, exposing any credential material violates the principle of least privilege and can enable lateral movement. The PostgreSQL-specific nature of the exposure is significant because connection strings often include hostnames, ports, and database names that, when combined with leaked credentials, provide everything needed to connect directly to the database.

Postgresql-Specific Remediation in Aspnet — concrete code fixes

To mitigate API key exposure in an ASP.NET application using PostgreSQL, design configuration handling so that sensitive values are never constructed into runtime strings that can be returned to clients or logged. Use strongly typed options, avoid echoing credentials in responses, and ensure logging filters out sensitive keys.

First, define a strongly typed options class and bind it securely:

// Options class
public class DatabaseOptions
{
    public string Host { get; set; } = string.Empty;
    public string Username { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
    public string Database { get; set; } = string.Empty;
    public int Port { get; set; } = 5432;
}

Register and bind the options in Program.cs:

// Program.cs
builder.Services.Configure<DatabaseOptions>(builder.Configuration.GetSection("Database"));

Use configuration keys like the following in appsettings.json (never commit secrets here; use user secrets or environment variables in production):

{  
  "Database": {  
    "Host": "localhost",  
    "Username": "appuser",  
    "Password": "ExampleSecurePassword123!",  
    "Database": "appdb",  
    "Port": 5432  
  }  
}

Consume the options in a service without exposing them:

// Database service example
public class PostgreService
{
    private readonly DatabaseOptions _options;
    public PostgreService(IOptions<DatabaseOptions> options)
    {
        _options = options.Value;
    }

    public NpgsqlConnection CreateConnection()
    {
        var csb = new NpgsqlConnectionStringBuilder
        {
            Host = _options.Host,
            Username = _options.Username,
            Password = _options.Password,
            Database = _options.Database,
            Port = _options.Port
        };
        return new NpgsqlConnection(csb.ConnectionString);
    }
}

Ensure endpoints that could reflect configuration are restricted or removed. For diagnostics, return non-sensitive metadata only:

[ApiController]
[Route("[controller]")]
public class DiagnosticController : ControllerBase
{
    [HttpGet("health")]
    public IActionResult HealthCheck()
    {
        return Ok(new { Status = "Healthy" });
    }
}

Configure logging filters to exclude sensitive keys such as Password and ConnectionStrings:

// In Program.cs
builder.Logging.AddFilter("Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider", null);
// Use a custom filter or redaction middleware to scrub sensitive values from logs

When using environment variables or user secrets, ensure they are not inadvertently printed in error responses. Validate that no action returns raw connection strings or key names. The PostgreSQL server should also be configured to reject cleartext password authentication where possible, using SCRAM-SHA-256 or certificates, reducing the impact if credentials are exposed elsewhere.

Frequently Asked Questions

What specific endpoints should I audit to prevent API key exposure in ASP.NET with PostgreSQL?
Audit any endpoint that reads configuration values and returns data to the client, including diagnostics, health, or debug endpoints. Also review logging output and exception handlers that may include connection strings or credentials.
How can I test whether my ASP.NET application is leaking PostgreSQL credentials via error messages?
Trigger controlled error conditions (for example, invalid connection parameters) and inspect error payloads and logs. Ensure error responses do not contain stack traces with configuration values and that logs redact keys such as Password and ConnectionStrings.