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

📚 Interview question

Code review: an ASP.NET Core invoices controller has a search action that concatenates the customer name and sort column into a SQL string, a Void action that loads any invoice by id with no ownership check and then redirects to a returnUrl from the query string, and a catch block that returns ex.ToString() to the client. What do you flag, in what order, and what does the fixed version look like?

A security-focused code review of an ASP.NET Core endpoint with SQL injection, broken object-level authorisation, an open redirect and verbose error disclosure, ranked by severity with a full rewrite.

Senior CodeReview Advanced aspnet-core code-review idor open-redirect security sql-injection

🎯 Key points

  • Rank by severity: SQL injection and BOLA are blocking, then open redirect, then information disclosure
  • The query is built by concatenation with no parameters: parameterise values (EF Core LINQ/FromSql or Dapper parameters) and allow-list the sort column
  • Load the invoice scoped to the caller's customer, or check with IAuthorizationService and a resource policy
  • Prefer 404 for objects the caller may not see (no id enumeration); 403 is fine where existence isn't sensitive, but be consistent
  • LocalRedirect with Url.IsLocalUrl, or return 204 from the API and let the client navigate
  • Centralised error handling: UseExceptionHandler + ProblemDetails with a trace id; full detail only in logs
  • SELECT * over-exposes columns; project to a DTO
  • Close with blocking vs suggested comments, a failing test per finding, analysers (EF1002), logging of denied access, and a checklist

⏱ 30-second answer

I'd rank the findings by impact. 1. SQL injection: the customer name and ORDER BY column are concatenated, so one request can read or change any data; fix with parameters and an allow-listed sort map. 2. Broken object-level authorisation (IDOR): Void loads any invoice by id, so any user can void any customer's invoice; fix by scoping the query to the caller's customer (or IAuthorizationService with a resource policy) and returning 404. 3. Open redirect: Redirect(returnUrl) enables phishing; use LocalRedirect with Url.IsLocalUrl. 4. Verbose errors: ex.ToString() leaks stack traces, SQL and schema; use UseExceptionHandler + ProblemDetails. Plus SELECT * over-exposure. The first two block the merge; I'd ask for a test per finding.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd review it the way an attacker would read it: what's the worst thing one request can do? The search action builds SQL by concatenation, including the sort column, so that's SQL injection: read every invoice, possibly modify data depending on the login's permissions. That's the top blocker. Close behind is Void: it takes an id, loads the invoice and changes it with no check that the caller owns it. That's broken object-level authorisation, number one on the OWASP API list, and it's a data-integrity issue across customers. Both block the merge.

Then the redirect: Redirect(returnUrl) from the query string is an open redirect, a phishing aid on our trusted domain. And the catch block returns ex.ToString(), which hands attackers stack traces, SQL text and table names, the exact feedback that makes the injection easy to exploit. At [company] I reviewed [a very similar controller in an internal billing tool]; the [IDOR] had shipped and was found by [a customer]. We fixed it with tenant-scoped queries and added an authorisation test for every endpoint, which [found two more].

For the rewrite: EF Core with a projection and an allow-listed sort map; the invoice loaded with Where(i => i.Id == id && i.CustomerId == callerCustomerId), returning 404 rather than 403 so ids can't be probed; LocalRedirect with a safe fallback, or better, an API that returns 204 and lets the client navigate; and no try/catch at all in the action, because the global exception handler returns ProblemDetails with a trace id. The mistake I see in reviews is listing these as equal 'nits'. Ranking them is the point: two of them are breach-level, two are hardening."


Code under review

[ApiController]
[Route("api/invoices")]
[Authorize]
public class InvoicesController(IConfiguration config, BillingDb db) : ControllerBase
{
    [HttpGet("search")]
    public IActionResult Search(string customer, string sort)
    {
        try
        {
            using var conn = new SqlConnection(config.GetConnectionString("Billing"));
            var sql = "SELECT * FROM Invoices WHERE CustomerName LIKE '%" + customer + "%' " +   // 1
                      "ORDER BY " + sort;                                                      // 1
            var rows = conn.Query(sql);                                                       // 5 SELECT *
            return Ok(rows);
        }
        catch (Exception ex)
        {
            return StatusCode(500, ex.ToString());                                            // 4
        }
    }

    [HttpPost("{id:int}/void")]
    public async Task<IActionResult> Void(int id, [FromQuery] string returnUrl)
    {
        var invoice = await db.Invoices.FindAsync(id);                                        // 2 no ownership check
        invoice!.Status = InvoiceStatus.Voided;
        await db.SaveChangesAsync();
        return Redirect(returnUrl);                                                           // 3
    }
}

Findings, by severity

# Severity Finding Impact Fix
1 Critical SQL injection via customer and sort Read or modify any data the login can reach Parameters + allow-listed sort
2 Critical BOLA/IDOR on Void Any user voids any customer's invoice Scope query to caller's customer; 404
3 Medium Open redirect via returnUrl Phishing on our domain LocalRedirect + Url.IsLocalUrl, or no redirect in an API
4 Medium ex.ToString() to client Leaks stack, SQL, schema; aids finding 1 Global exception handler + ProblemDetails
5 Low SELECT * returned directly Over-exposes columns (and future columns) Project to a DTO
— Low invoice! null-forgiving 500 instead of 404 Handle null

The rewrite

(See the code example section for the full, compilable version.) Key points: EF Core with AsNoTracking and a DTO projection, EF.Functions.Like with a parameter, a Dictionary mapping API sort names to expressions, a ICurrentCustomer abstraction from claims, tenant-scoped loading, NoContent() for the API, and no local try/catch.

How I'd close the review

Comment Type
SQL injection in Search Blocking, with a failing test showing sort=Id;-- is rejected
Missing ownership check in Void Blocking, with an integration test: user A can't void user B's invoice (404)
Open redirect Blocking for a browser-facing endpoint; suggest removing the redirect from the API
Error disclosure Blocking: remove local catch, rely on UseExceptionHandler
SELECT *, null handling Suggested

Then the systemic follow-up: enable EF1002 and security analysers as errors, add an authorisation test pattern for every endpoint that takes an id, a CI grep for Redirect( with request data and string-built SQL, and a short checklist in the PR template.

Production example

Applying the same review checklist to a billing service's 60 endpoints found 4 IDOR-style handlers and 2 string-built queries; per-endpoint authorisation tests (about 120 small tests running in under 20 seconds with WebApplicationFactory) have caught 3 regressions since.

🔍 What the interviewer is checking

Checks that the candidate spots every security flaw, ranks them by real impact, writes a correct rewrite and turns the review into lasting guardrails.

Green flags

  • Ranks SQL injection and BOLA as blocking, above redirect and error disclosure
  • Allow-lists the sort column rather than escaping it
  • Scopes by caller and returns 404 rather than 403
  • Removes local catch-alls in favour of the global exception handler
  • Proposes tests, analysers and a checklist

Red flags

  • Misses the IDOR because [Authorize] is present
  • Fixes injection with string escaping
  • Treats every finding as an equal nit

📚 Learn in depth

1. Severity ranking for security reviews

Can one request...                         -> severity
  run arbitrary SQL / code?                -> Critical (injection)
  read or change another customer's data?  -> Critical (BOLA, missing authz)
  trick users into harm on our domain?     -> Medium (open redirect, clickjacking)
  learn how to attack us better?           -> Medium/Low (verbose errors, versions)
  degrade quality but not security?        -> Low (SELECT *, nullability)

Ranking matters because reviewers and teams have limited attention; a review that lists eight equal comments gets the easy ones fixed first.

2. Why each bug exists

  • Injection: data and code share one channel (SQL text). Parameters split them; identifiers can't be parameters, so they need an allow-list.
  • BOLA: [Authorize] checks who you are, not what you may touch. Object-level checks need the resource, so they live in the handler or in a query filter.
  • Open redirect: browsers follow Location anywhere. The server must decide which destinations are legitimate.
  • Verbose errors: exceptions carry internals (SQL text in SqlException, file paths, type names). They belong in logs with a correlation id, not responses.

3. Patterns that prevent the whole class

Class Pattern
Injection EF Core LINQ or FromSql interpolation; EF1002 as error; sort maps
BOLA Tenant/customer global query filters, or loading through a repository that always scopes by caller; resource-based authorisation handlers
Open redirect Only LocalRedirect in controllers; API endpoints never redirect
Error disclosure AddProblemDetails + UseExceptionHandler; no local catch-all blocks

4. 404 vs 403 for objects you don't own

Returning 403 confirms the id exists, letting attackers enumerate valid invoice numbers. Returning 404 for 'doesn't exist or isn't yours' leaks nothing. Log the attempt with the caller id, because repeated 404s across many ids are a signal.

5. Testing the fixes

  • Unit: the sort map rejects unknown fields.
  • Integration (WebApplicationFactory with a test auth handler): user A can't read or void user B's invoice; the response has no stack trace; returnUrl=//evil.example falls back to /.
  • DAST: OWASP ZAP active scan in staging for injection and redirects.

6. Making it stick

One-off fixes regress. The durable outcome of a review like this is a pattern (scoped queries), a guardrail (analysers, CI grep), and a test convention (authorisation test per id-taking endpoint).

Try it yourself

  1. Paste the code under review into a test project and write failing tests for each finding before fixing them.
  2. Add a test authentication handler that lets tests act as different customers.
  3. Turn on EF1002 and the CA security rules as errors and see what else in your codebase fails.
  4. Run OWASP ZAP against the original and fixed versions and compare alerts.
  5. Write a PR template checklist with one line per finding class.

💻 Code

The fixed controller: parameterised, allow-listed sorting with EF Core, caller-scoped loading (BOLA fix), no redirect from the API, and errors handled globally with ProblemDetails.

using System.Linq.Expressions;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Billing.Invoices;

public sealed record InvoiceSummary(int Id, string Number, string CustomerName, decimal Total, InvoiceStatus Status);

public interface ICurrentCustomer { int CustomerId { get; } }

public sealed class ClaimsCurrentCustomer(IHttpContextAccessor accessor) : ICurrentCustomer
{
    public int CustomerId => int.Parse(accessor.HttpContext!.User.FindFirstValue("customer_id")
        ?? throw new UnauthorizedAccessException("No customer claim."));
}

[ApiController]
[Route("api/invoices")]
[Authorize]
public sealed class InvoicesController(BillingDb db, ICurrentCustomer caller) : ControllerBase
{
    private static readonly Dictionary<string, Expression<Func<Invoice, object>>> SortFields =
        new(StringComparer.OrdinalIgnoreCase)
        {
            ["number"] = i => i.Number,
            ["total"] = i => i.Total,
            ["issued"] = i => i.IssuedUtc,
        };

    [HttpGet("search")]
    public async Task<ActionResult<IReadOnlyList<InvoiceSummary>>> Search(
        [FromQuery] string? customer, [FromQuery] string sort = "issued", CancellationToken ct = default)
    {
        if (!SortFields.TryGetValue(sort, out var orderBy))
            return ValidationProblem($"Unsupported sort field '{sort}'.");

        var query = db.Invoices.AsNoTracking()
            .Where(i => i.CustomerId == caller.CustomerId);            // scope first

        if (!string.IsNullOrWhiteSpace(customer))
            query = query.Where(i => EF.Functions.Like(i.CustomerName, $"%{customer}%"));  // parameterised

        var results = await query.OrderBy(orderBy)
            .Take(100)
            .Select(i => new InvoiceSummary(i.Id, i.Number, i.CustomerName, i.Total, i.Status))
            .ToListAsync(ct);
        return Ok(results);
    }

    [HttpPost("{id:int}/void")]
    public async Task<IActionResult> Void(int id, CancellationToken ct)
    {
        // BOLA fix: only the caller's own invoices are visible; 404 avoids confirming the id exists
        var invoice = await db.Invoices
            .SingleOrDefaultAsync(i => i.Id == id && i.CustomerId == caller.CustomerId, ct);
        if (invoice is null) return NotFound();

        invoice.Void();            // domain rule: e.g. can't void a paid invoice
        await db.SaveChangesAsync(ct);
        return NoContent();        // the client decides where to navigate: no redirect from an API
    }
}
// Program.cs: no local try/catch; one place turns exceptions into safe ProblemDetails
builder.Services.AddProblemDetails();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentCustomer, ClaimsCurrentCustomer>();

var app = builder.Build();
app.UseExceptionHandler();       // 500 + ProblemDetails with traceId; details only in logs
app.UseStatusCodePages();
// Integration test: user A cannot void user B's invoice
[Fact]
public async Task Void_other_customers_invoice_returns_404()
{
    var client = factory.CreateClientFor(customerId: 1);
    var response = await client.PostAsync("/api/invoices/2001/void", null);   // invoice belongs to customer 2
    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

⚠ Common mistakes

  • Mistake: Listing all findings as equal comments. Why it is wrong: breach-level issues get the same attention as style nits. Instead: rank by impact and mark blocking vs suggested.
  • Mistake: Fixing SQL injection by escaping quotes in customer. Why it is wrong: the sort identifier is still injectable and escaping is fragile. Instead: parameterise values and allow-list identifiers.
  • Mistake: Believing [Authorize] on the controller covers Void. Why it is wrong: it checks authentication, not ownership of invoice id. Instead: scope the query or use resource-based authorisation.
  • Mistake: Returning 403 for invoices the caller doesn't own. Why it is wrong: it confirms the id exists and enables enumeration. Instead: return 404 and log the attempt.
  • Mistake: Replacing ex.ToString() with ex.Message. Why it is wrong: messages still leak SQL and internals (SqlException messages include object names). Instead: generic ProblemDetails with a trace id; details in logs.
  • Mistake: Keeping the redirect and adding a StartsWith("/") check. Why it is wrong: //evil.example passes. Instead: Url.IsLocalUrl + LocalRedirect, or remove redirects from APIs.
  • Mistake: Fixing only this controller. Why it is wrong: the same patterns exist elsewhere. Instead: add analysers, a CI grep and an authorisation-test convention for every id-taking endpoint.

🏛 Senior insight: trade-offs

A senior security review has two outputs: fixes for this PR and a guardrail for the codebase. The individual bugs are textbook; what distinguishes the review is ranking them, proving each with a test, and turning the lesson into something automatic so the next PR can't repeat it.

Guardrail When it fits Cost Limitation
Analysers as errors (EF1002, CA security rules) Every repo Initial clean-up Doesn't catch logic flaws like BOLA
Tenant/customer global query filters Multi-tenant data Care with IgnoreQueryFilters and background jobs Not for cross-tenant admin queries
Authorisation test per id-taking endpoint APIs with object ids Test setup with a fake auth handler Must be maintained
PR template security checklist Teams of any size Minutes per PR Only as good as reviewers' attention
DAST in staging (ZAP) Public apps and APIs Pipeline time, triage Misses authorisation logic

Measure: security findings per pen test trending down, time from finding to fix, and the count of endpoints without an authorisation test.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate flags the missing ownership check in Void Why: Checks they can fix broken object-level authorisation across a whole codebase
    How to answer

    Broken object-level authorisation (BOLA, also called IDOR) is API1:2023 in the OWASP API Security Top 10: the API checks who you are but not whether this object is yours.

    • Fix the endpoint: scope the query by the caller, with callerId read from the token's claims, never from the request (Where(o => o.Id == id && o.CustomerId == callerId)), or load and call IAuthorizationService.AuthorizeAsync when roles or teams are involved; return 404, not 403.
    • Fix the codebase: enumerate every endpoint that takes an id, including child resources and exports; add tenant query filters and optionally row-level security as a safety net.
    • Prevent: cross-user integration tests in CI, a load-and-authorise helper, scheduled access-control reviews and logging that detects enumeration.

    The trade-off: random ids slow attackers down, but they are not authorisation; only a server-side ownership check is.

  2. When: Candidate flags SQL injection and the dynamic ORDER BY Why: Checks depth on parameterisation and identifiers that can't be parameters
    How to answer

    SQL injection happens when untrusted input is concatenated into SQL text, so the database parses part of the data as code. The fix is parameterisation: the SQL text is fixed and values travel separately as typed parameters (SqlParameter in ADO.NET, an anonymous object in Dapper, LINQ or FromSql($"...") in EF Core).

    In EF Core 7 and later, FromSql, ExecuteSql and SqlQuery<T> take a FormattableString and turn every interpolation hole into a DbParameter; they are the current names for the older FromSqlInterpolated/ExecuteSqlInterpolated. The trap is FromSqlRaw($"... {input}") or ExecuteSqlRaw: they take a plain string, so interpolation happens before EF sees it and it's concatenation. Things that can't be parameters (column names, sort direction) must come from an allow-list. Stored procedures aren't automatically safe if they build dynamic SQL. Add a least-privilege login so a bug can't drop tables.

  3. When: Candidate flags Redirect(returnUrl) Why: Checks they know LocalRedirect, Url.IsLocalUrl and the // and /\ bypasses
    How to answer

    An open redirect is an endpoint that redirects to a URL from the request (?returnUrl=...) without checking it, so a link on your trusted domain sends users to a phishing site, or an attacker chains it to leak OAuth codes or tokens. In ASP.NET Core use LocalRedirect (throws for non-local URLs) or Url.IsLocalUrl (rejects //evil and /\evil), and allow-list any external destinations.

    Clickjacking loads your page in an invisible iframe on the attacker's site, so the user's click lands on your 'Delete' or 'Approve' button. Prevent framing with Content-Security-Policy: frame-ancestors 'none' (or 'self'), plus X-Frame-Options: DENY for older clients, set globally in middleware. Both bugs are cheap to fix and common in pen-test reports.

🛠 Real-world problems: how you handle them

A customer voids another customer's invoices through an internal-looking API
Situation
A B2B billing portal on ASP.NET Core and Azure SQL serves [number] business customers. A customer's finance officer reports that invoices they never touched show as voided, and another customer emails support with screenshots of invoice numbers that aren't theirs.
Signals
Support tickets; audit table shows Void operations by a user from customer [A] on invoices of customer [B]; Application Insights shows sequential ids being called on POST /api/invoices/{id}/void; no alerts because all requests returned 302.
Investigation
Reviewed the controller: `FindAsync(id)` with no ownership check, plus string-built SQL in Search and `ex.ToString()` in responses. Queried the audit log and Application Insights (KQL) for cross-customer operations over the past [90] days to scope impact. Checked whether the search injection had been exploited by looking for SQL keywords in request logs and Azure SQL auditing.
Resolution
Immediate: hotfix scoping `Void` and `Search` to the caller's customer and returning 404, deployed within [hours]; reverted the wrongly voided invoices from the audit trail; assessed the incident under the Notifiable Data Breaches scheme with [the privacy officer] since invoice data crossed customers. Long term: parameterised the search with an allow-listed sort, removed local catch blocks in favour of ProblemDetails, introduced a customer global query filter and per-endpoint authorisation tests.
Prevention
Authorisation integration test for every id-taking endpoint, EF1002 and security analysers as errors, a PR template checklist (ownership, parameterisation, redirects, errors), an alert on 404 spikes per user, and a pen test scoped to object-level authorisation.

How to tell it (STAR)

**S:** At [company] a customer reported invoices voided that they'd never touched, and another could see invoice numbers that weren't theirs. **T:** I led the response: stop it, fix it, and work out the impact. **A:** The Void action loaded any invoice by id with no ownership check, and the search built SQL by concatenation. I hotfixed both to scope by the caller's customer and return 404, used the audit log and Application Insights to find every cross-customer action in [90] days, restored the invoices and worked with [the privacy officer] on the NDB assessment. Then I added a customer query filter, parameterised the search and wrote authorisation tests for every endpoint. **R:** The hole was closed in [hours], [number] affected invoices were restored, the tests caught [two] more endpoints with the same flaw, and the next pen test found no object-level authorisation issues.

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me