Code review of configuration anti-patterns: secrets committed in appsettings.json (incident response, rotation, history, Privacy Act and NDB), constructors that parse configuration and open connections, a static IConfiguration singleton (hidden dependencies, test pollution, no reload), no validation, and the rewrite with options classes, ValidateOnStart, Key Vault with managed identity and passwordless SQL, plus blocking versus suggested review comments and secret scanning.
Ranked by severity:
sk_live_ Stripe key). Treat this as an incident: rotate first, then move the values to Key Vault with managed identity. Deleting the file doesn't remove them from git history.int.Parse throws when DI resolves the service, and a singleton holding an open SqlConnection leaks and breaks pooling.AppConfig.Config hides dependencies, is null before start-up, pollutes parallel tests and never reloads.The rewrite uses options classes with BindConfiguration and ValidateOnStart, Key Vault for secrets, passwordless Entra ID auth to SQL, and connections opened per operation. The trade-off: a little more set-up, in exchange for secure, testable, fail-fast configuration.
"The first thing I'd do isn't write a review comment: it's ask whether that Stripe key is live, because
sk_live_says it is. A live secret in git is an incident, not a style issue. The key has been exposed to everyone with repository access, every clone and the CI logs, so I'd get it rotated in the Stripe dashboard straight away, rotate the SMTP password, and check the Stripe logs for misuse. Deleting the line doesn't help, because it's in history. Then the values move to Key Vault, read through the app's managed identity, and the SQL connection should use Entra ID authentication so there's no password at all.For example, at [company] I found an equivalent leak in a pull request. We [rotated the key within the hour], turned on GitHub push protection for the organisation and added gitleaks to the pipeline, and the next attempt to commit a key was blocked before it reached the remote. [Result].
Next is correctness. The
EmailSenderconstructor doesint.Parseon a configuration value, so a missing port throws inside DI resolution, on the first request that needs email, with a confusing activation exception. Another constructor opens aSqlConnectionand keeps it in a singleton: one physical connection shared across threads, which isn't thread-safe and defeats connection pooling. Then design: the staticAppConfig.Configis a service locator. Classes don't declare what they need, the value is null if anything touches it beforeProgram.cssets it, parallel tests overwrite each other, and nothing reloads. I'd replace it with options classes bound withBindConfiguration, validated withValidateOnStart, and injected. The principle: secrets out of the repo, work out of constructors, configuration in through the constructor."
// Program.cs
var builder = WebApplication.CreateBuilder(args);
AppConfig.Config = builder.Configuration; // 1
builder.Services.AddSingleton<EmailSender>();
builder.Services.AddSingleton<OrderRepository>();
public static class AppConfig { public static IConfiguration Config = null!; } // 1
public class EmailSender
{
private readonly string _password; private readonly int _port;
public EmailSender()
{
_password = AppConfig.Config["Smtp:Password"]!; // 2
_port = int.Parse(AppConfig.Config["Smtp:Port"]!); // 3
}
}
public class OrderRepository
{
private readonly SqlConnection _conn;
public OrderRepository()
{
_conn = new SqlConnection(AppConfig.Config.GetConnectionString("Default"));
_conn.Open(); // 4
}
}
// appsettings.json (committed)
{
"ConnectionStrings": { "Default": "Server=prod-sql;User Id=app;Password=Winter2026!" }, // 5
"Smtp": { "Host": "smtp.example.com", "Port": "587", "Password": "P@ssw0rd!" }, // 5
"Stripe": { "SecretKey": "sk_live_51H..." } // 5
}
| # | Severity | Finding | Fix |
|---|---|---|---|
| 5 | Security: critical | Live Stripe key, SMTP and SQL passwords committed | Rotate now; Key Vault + managed identity; passwordless SQL; secret scanning |
| 4 | Stall / crash | Singleton holds one open SqlConnection shared across threads; connection drops are never recovered |
Open per operation (await using), or use DbContext/SqlDataSource-style factories |
| 3 | Crash | int.Parse in a constructor throws during DI resolution on first use |
Bind to int Port in options and validate with [Range] at start-up |
| 2 | Wrong data | Values copied in constructors of singletons never reload | Inject options; IOptionsMonitor if live changes matter |
| 1 | Design | Static config locator: hidden dependencies, null before set, shared across parallel tests | Constructor-inject typed options |
| - | Diagnostics | No validation: misconfiguration appears as a 500 hours later | ValidateDataAnnotations().ValidateOnStart() |
See the code example: SmtpOptions and StripeOptions bound and validated at start-up, Key Vault loaded with a managed identity outside Development, the SQL connection string without a password using Authentication=Active Directory Default, and a repository that opens a pooled connection per call.
| Comment | Type |
|---|---|
| Rotate the Stripe key, SMTP and SQL passwords today; raise a security incident | Blocking, before anything else |
| Remove secrets from appsettings; Key Vault + managed identity | Blocking |
No I/O or parsing in constructors; no shared SqlConnection |
Blocking |
Replace AppConfig with options classes and ValidateOnStart |
Blocking |
| Turn on push protection / gitleaks in CI; add the PR checklist item | Suggested, as follow-up work |
In a similar codebase, removing a shared singleton SqlConnection eliminated intermittent InvalidOperationException: There is already an open DataReader errors that hit about [0.5%] of requests under load, and the first ValidateOnStart deployment caught a missing SMTP port in the test environment before release.
Checks whether the candidate ranks issues by real risk and knows incident response for leaked secrets, not just better code shape.
Green flags
SqlConnection fail.Red flags
commit ─► push ─► every clone, fork, CI cache, PR diff, backup
│
└─► deleting the file creates a new commit; history keeps the old one
Once pushed, assume compromise. The order is: rotate (revoke the old secret), check for misuse (provider logs), remove from code, and optionally rewrite history (git filter-repo) knowing clones keep copies. If personal information could be reached with the credentials, assess it under the Privacy Act's Notifiable Data Breaches scheme.
DI constructs a singleton lazily on first resolve, usually inside a request:
GET /orders/42 ─► resolve OrderService ─► resolve EmailSender (singleton, first time)
└─► ctor: int.Parse(null) ─► ArgumentNullException
wrapped as an activation error ─► 500
Constructors should only store dependencies. Anything that can fail belongs in validated options (fails at start-up) or in methods (fails with context).
SqlConnection is not thread-safe and supports one active command at a time (without MARS). ADO.NET already pools physical connections per connection string; opening and disposing a SqlConnection per operation borrows and returns a pooled connection in microseconds. Holding one open in a singleton serialises or corrupts concurrent use and never recovers from a dropped connection.
AppConfig.Config (static)
├─ null until Program.cs runs ─► static initialisers or tests crash
├─ shared by every test in the process ─► parallel tests overwrite it
└─ any class can read any key ─► dependencies invisible in signatures
The options pattern fixes all three: typed, injected, overridable per test with Options.Create.
Microsoft.Data.SqlClient supports Authentication=Active Directory Default (uses DefaultAzureCredential) or Active Directory Managed Identity. Grant the app's identity a contained database user (CREATE USER [shop-api] FROM EXTERNAL PROVIDER) and the connection string holds no secret at all.
gitleaks detect) over a sample repository with a fake key in history.int.Parse of a missing key and see when and how it fails; then move it to validated options.SqlConnection across 20 parallel requests and watch the errors.Authentication=Active Directory Default from your developer login.The rewrite: typed, validated options, secrets from Key Vault, passwordless SQL, and no work in constructors.
// Program.cs
using System.ComponentModel.DataAnnotations;
using Azure.Identity;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
if (!builder.Environment.IsDevelopment())
{
// Secrets (Smtp--Password, Stripe--SecretKey) come from Key Vault via the managed identity
builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["KeyVault:Uri"]!), new ManagedIdentityCredential());
}
builder.Services.AddOptions<SmtpOptions>().BindConfiguration(SmtpOptions.Section).ValidateDataAnnotations().ValidateOnStart();
builder.Services.AddOptions<StripeOptions>().BindConfiguration(StripeOptions.Section).ValidateDataAnnotations().ValidateOnStart();
builder.Services.AddSingleton<EmailSender>();
builder.Services.AddScoped<OrderRepository>();
var app = builder.Build();
app.MapGet("/orders/{id:int}/total", (int id, OrderRepository repo, CancellationToken ct) => repo.GetTotalAsync(id, ct));
app.Run();
public sealed class SmtpOptions
{
public const string Section = "Smtp";
[Required] public string Host { get; init; } = "";
[Range(1, 65535)] public int Port { get; init; } = 587; // parsed and validated once, at start-up
[Required] public string Password { get; init; } = ""; // supplied by Key Vault, never by appsettings
}
public sealed class StripeOptions
{
public const string Section = "Stripe";
[Required] public string SecretKey { get; init; } = "";
}
// Constructor only stores the dependency; no parsing, no I/O
public sealed class EmailSender(IOptions<SmtpOptions> options)
{
public string Describe() => $"{options.Value.Host}:{options.Value.Port}";
}
public sealed class OrderRepository(IConfiguration config)
{
// Pooled: opening per operation is cheap and thread-safe
public async Task<decimal> GetTotalAsync(int id, CancellationToken ct)
{
await using var conn = new SqlConnection(config.GetConnectionString("Default"));
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("SELECT Total FROM dbo.Orders WHERE Id = @id", conn);
cmd.Parameters.AddWithValue("@id", id);
return (decimal)(await cmd.ExecuteScalarAsync(ct) ?? 0m);
}
}
// appsettings.json: no secrets; passwordless SQL via Entra ID
{
"ConnectionStrings": { "Default": "Server=tcp:shop-sql.database.windows.net;Database=Shop;Authentication=Active Directory Default;Encrypt=True" },
"Smtp": { "Host": "smtp.example.com", "Port": 587 },
"KeyVault": { "Uri": "https://kv-shop-aue.vault.azure.net/" }
}
SqlConnection in a singleton. Why it is wrong: It is not thread-safe, defeats pooling and never recovers from drops. Instead: Open and dispose per operation; pooling makes it cheap.IConfiguration holder "for convenience". Why it is wrong: Hidden dependencies, null before start-up, broken parallel tests, no reload. Instead: Inject options.appsettings.Production.json. Why it is wrong: Still committed. Instead: Key Vault, managed identity, passwordless auth.In a review like this, ordering is the senior signal: security incident first, crash and data bugs second, design third. I also turn the findings into guardrails so the next reviewer doesn't need to catch them: push protection and gitleaks for secrets, ValidateOnStart as a template default, an analyser or checklist item banning I/O in constructors, and a team rule that IConfiguration is only touched in Program.cs. Under the Privacy Act and the ACSC Essential Eight, removing long-lived credentials entirely (managed identity, passwordless SQL) is worth more than storing them better.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Key Vault + managed identity | Third-party secrets (Stripe, SMTP) | Azure set-up, RBAC | Values that aren't secret |
| Passwordless Entra ID auth | Azure SQL, Storage, Service Bus | Database user and role set-up | Services without Entra ID support |
| History rewrite | Secret in a public or widely cloned repo | Disrupts every clone | As a substitute for rotation |
The options pattern binds a configuration section to a strongly typed class once, at the composition root, and injects IOptions<T> (or IOptionsSnapshot<T> / IOptionsMonitor<T>) where it is needed. You register it with builder.Services.AddOptions<PaymentOptions>().BindConfiguration("Payments"), usually chained with ValidateDataAnnotations().ValidateOnStart().
The ConfigurationBinder matches keys to public properties case-insensitively and converts strings to the property type; missing keys leave defaults.
Injecting IConfiguration everywhere instead spreads magic strings, hides what a class really depends on, makes tests build fake configuration, and skips validation. The trade-off: one small class and a registration per section, in exchange for typed, validated, discoverable settings.
Options validation runs as the last step when an options object is built. ValidateDataAnnotations() applies attributes such as [Required], [Range] and [Url]; Validate(o => ..., "message") adds small rules; IValidateOptions<T> handles cross-property rules, named options or rules that need services.
Without ValidateOnStart() validation is lazy: a missing key surfaces as a 500 on the first request that reads the options, possibly hours after the deployment looked healthy. With it, the host validates during start-up, the process exits with every failure listed, and the orchestrator keeps the old version serving.
Nested objects need [ValidateObjectMembers] and collections [ValidateEnumeratedItems]. For Native AOT, the [OptionsValidator] source generator writes the DataAnnotations checks at compile time with no reflection.
The trade-off: a few attributes and a class, in exchange for configuration errors becoming start-up errors with clear messages.
How to tell it (STAR)
**S:** At [company], I was reviewing a checkout pull request and saw a live Stripe secret key committed in appsettings.json on a branch already pushed to GitHub. **T:** I needed to contain the exposure before discussing the code, then stop it happening again. **A:** I flagged it as a blocking security issue, got the key rotated in Stripe within [30 minutes], checked the Stripe logs for misuse, and moved the new key into Key Vault read by the app's managed identity. I then rewrote the branch history, scrubbed the CI log, and turned on push protection and gitleaks. **R:** No misuse was found, and in the following [six months] push protection blocked [three] further attempts to commit keys before they reached GitHub.
Last updated 23 Nov 2026.