📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: a start-up class stores builder.Configuration in a static AppConfig.Config property, services read keys from it in their constructors (one parses a port with int.Parse and opens a SQL connection), and appsettings.json, committed to git, contains an SMTP password and a live Stripe secret key. What do you find, ranked by severity, and how would you rewrite it?

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.

Senior CodeReview Advanced aspnet-core azure-key-vault code-review configuration options-pattern secrets-management

🎯 Key points

  • Committed live secrets are an incident: rotate immediately, then remove from code; deleting the file does not remove git history
  • Secrets move to Key Vault via managed identity, and SQL goes passwordless with Entra ID where possible
  • Constructors only store dependencies: int.Parse throws during DI resolution, and I/O belongs in methods that can handle and log failures with context
  • A singleton holding an open SqlConnection is not thread-safe and defeats pooling; data access is scoped and opens a pooled connection per operation
  • A static AppConfig hides dependencies, breaks parallel tests, is null before start-up and never sees reloads
  • Replace with options classes bound via BindConfiguration, validated with ValidateOnStart
  • Prevent it from day one: service template with Key Vault, ValidateOnStart and push protection; close the review with blocking comments and secret scanning

⏱ 30-second answer

Ranked by severity:

  1. Committed live secrets (SMTP password, 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.
  2. Constructors doing work: int.Parse throws when DI resolves the service, and a singleton holding an open SqlConnection leaks and breaks pooling.
  3. A static AppConfig.Config hides dependencies, is null before start-up, pollutes parallel tests and never reloads.
  4. No validation, so bad values fail on a live request.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 EmailSender constructor does int.Parse on 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 a SqlConnection and keeps it in a singleton: one physical connection shared across threads, which isn't thread-safe and defeats connection pooling. Then design: the static AppConfig.Config is a service locator. Classes don't declare what they need, the value is null if anything touches it before Program.cs sets it, parallel tests overwrite each other, and nothing reloads. I'd replace it with options classes bound with BindConfiguration, validated with ValidateOnStart, and injected. The principle: secrets out of the repo, work out of constructors, configuration in through the constructor."


Code under review

// 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
}

Findings, by severity

# 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()

The rewrite

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.

How I'd close the review

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate ranks issues by real risk and knows incident response for leaked secrets, not just better code shape.

Green flags

  • Puts rotation of the live key first and knows git history keeps secrets.
  • Explains why constructor parsing and a shared SqlConnection fail.
  • Replaces the static locator with validated options.
  • Proposes guardrails: secret scanning, push protection, passwordless auth.

Red flags

  • Suggests moving secrets to another committed file or environment-specific JSON.
  • Ranks the static class as the top issue and misses the leaked key.
  • Thinks deleting the line removes the exposure.

📚 Learn in depth

1. Why a committed secret is an incident

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.

2. Constructors and DI resolution

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).

3. Why a shared SqlConnection is wrong

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.

4. The static locator

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.

5. Passwordless SQL

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.

Try it yourself

  1. Run gitleaks (gitleaks detect) over a sample repository with a fake key in history.
  2. Make a singleton with int.Parse of a missing key and see when and how it fails; then move it to validated options.
  3. Share one SqlConnection across 20 parallel requests and watch the errors.
  4. Replace the static locator with options and write a test that runs two configurations in parallel.
  5. Connect to Azure SQL with Authentication=Active Directory Default from your developer login.

💻 Code

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/" }
}

⚠ Common mistakes

  • Mistake: Treating a committed live key as a code-style comment. Why it is wrong: It is already exposed; removing it later doesn't un-expose it. Instead: Rotate first, check for misuse, then fix the code.
  • Mistake: Deleting the secret in a new commit and calling it done. Why it is wrong: Git history and every clone keep it. Instead: Rotate; rewrite history only as a secondary clean-up.
  • Mistake: Parsing configuration in constructors. Why it is wrong: Failures happen during DI resolution on a live request with an unhelpful error. Instead: Bind to typed options and validate at start-up.
  • Mistake: Holding an open 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.
  • Mistake: Keeping a static IConfiguration holder "for convenience". Why it is wrong: Hidden dependencies, null before start-up, broken parallel tests, no reload. Instead: Inject options.
  • Mistake: Moving the secrets to appsettings.Production.json. Why it is wrong: Still committed. Instead: Key Vault, managed identity, passwordless auth.
  • Mistake: Reviewing only the diff and not asking about blast radius. Why it is wrong: The same key may be used in other services or environments. Instead: Ask where else the credential is used and rotate everywhere.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes replacing the static config with options classes. Why: Checks they can explain how the options pattern binds and why it beats IConfiguration in services.
    How to answer

    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.

  2. When: Candidate mentions failing fast on a missing SMTP port. Why: Checks they know ValidateOnStart, nested validation and custom validators.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Live payment key found in a pull request's appsettings.json
Situation
A [mid-sized] e-commerce team in Melbourne; a pull request for a new checkout feature added `Stripe:SecretKey` with a `sk_live_` value to `appsettings.json`, and the branch had already been pushed to GitHub with [15] people having access.
Signals
Spotted during code review; [no] secret scanning was enabled; the key also appeared in the CI build log's configuration dump.
Investigation
Confirmed the key was live in the Stripe dashboard, checked its recent API activity for requests from unknown IPs, searched other repositories and pipeline variables for the same key, and checked who had cloned or forked the repository.
Resolution
Immediate: rolled the key in Stripe, updated the replacement in Key Vault, and confirmed the production app picked it up through its managed identity. Then removed the value from the branch, rewrote the branch history before merge, and scrubbed the CI log.
Prevention
Enabled GitHub secret scanning with push protection for the organisation, added gitleaks to the pipeline, removed the configuration dump from CI, added a pull request checklist item, and made `ValidateOnStart` with Key Vault the service template default.

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.

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me