By clicking “Accept”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.
18px_cookie
e-remove
Blog

Detecting Business Logic Flaws and IDOR with AI SAST

Published on
November 17, 2026
Updated on
November 17, 2026
Topics

A user logs in, changes /api/invoices/1041 to /api/invoices/1042, and downloads another customer's invoice. Your SAST scan on that code came back clean. No injection, no unsafe deserialization, no tainted string reaching a dangerous function. The code did exactly what the developer wanted. It just never asked whether invoice 1042 belonged to the person requesting it.

This post covers that class of bug: business logic flaws, broken access control, and insecure direct object references (IDOR). 

We'll also look at how AI SAST reasons about authorization across a full repository, as well as how to triage the findings and where AI SAST sits next to DAST, pentesting, and code review.

What are business logic flaws, broken access control, and IDOR?

Business logic flaws, broken access control, and IDOR are flaws where valid code makes the wrong decision about who can access or change what. The code compiles, passes tests, and calls no dangerous APIs. The bug lives in a missing or incorrect authorization decision.

Each term maps to a specific OWASP or MITRE entry:

  • Broken access control covers any failure to enforce what a user may do. It sits at the top of the OWASP Top 10:2025 as A01 Broken Access Control, and OWASP reports that 100% of the applications it tested had some form of it.
  • IDOR is one specific form of broken access control. The application takes an object identifier from the request and uses it to fetch or modify data without checking that the caller may touch that object. MITRE tracks this as CWE-639: Authorization Bypass Through User-Controlled Key.
  • Missing authorization is the broader case where a sensitive action has no permission check at all, such as an admin endpoint any logged-in user can call. That's CWE-862: Missing Authorization.
  • Business logic flaws violate the rules of the application's workflow: skipping a payment step, applying a discount twice, or moving an order into a state it shouldn't reach. MITRE groups these under CWE-840: Business Logic Errors, and the OWASP Business Logic Security Cheat Sheet describes the same workflow and state bypass patterns.

Authentication and authorization are separate controls. Authentication answers who the caller is. Authorization answers whether that caller may perform this action on this object. A logged-in user reading another user's record has passed authentication and slipped past authorization. Most IDOR bugs live in that gap, behind a perfectly working login.

What IDOR and missing authorization look like in code

IDOR and missing authorization look like ordinary, working handlers that fetch or change data without checking whether the caller is allowed to. These examples use JavaScript with Express and Prisma, but the shape is the same in Spring, Django, Rails, or Go. IDOR: loading an invoice by ID

// JavaScript (Express + Prisma)
// Vulnerable: any authenticated user can read any invoice
app.get('/api/invoices/:id', requireAuth, async (req, res) => {
  const invoice = await prisma.invoice.findFirst({
    where: { id: req.params.id },
  });
  if (!invoice) return res.status(404).end();
  res.json(invoice);
});
// JavaScript (Express + Prisma)
// Fixed: the query is scoped to the caller's tenant
app.get('/api/invoices/:id', requireAuth, async (req, res) => {
  const invoice = await prisma.invoice.findFirst({
    where: { id: req.params.id, tenantId: req.user.tenantId },
  });
  if (!invoice) return res.status(404).end();
  res.json(invoice);
});

Why the fix is safe: the ownership predicate is part of the query, so another tenant's invoice returns 404 instead of data.

Why no pattern rule flags the vulnerable version: findFirst with a request parameter in where is the most common line in any CRUD app, and it's correct whenever the resource is public.

The OWASP Insecure Direct Object Reference Prevention Cheat Sheet recommends this approach: enforce access control on every object lookup, and treat hard-to-guess IDs as an extra layer on top.

Missing authorization: an admin action without a role check

// JavaScript (Express + Prisma)
// Vulnerable: any logged-in user can disable any account
app.post('/api/users/:id/disable', requireAuth, async (req, res) => {
  await prisma.user.update({
    where: { id: req.params.id },
    data: { disabled: true },
  });
  res.status(204).end();
});
// JavaScript (Express + Prisma)
// Fixed: an explicit guard runs before the handler
const requireRole = (role) => (req, res, next) =>
  req.user.roles.includes(role) ? next() : res.status(403).end();

app.post('/api/users/:id/disable', requireAuth, requireRole('admin'),
  async (req, res) => {
    await prisma.user.update({
      where: { id: req.params.id },
      data: { disabled: true },
    });
    res.status(204).end();
  });

Why the fix is safe: the route refuses the request with a 403 unless the caller holds the admin role.

Why no pattern rule flags the vulnerable version: the handler has authentication middleware, and a rule can't know that disabling users is an admin-only operation in this particular app.

Workflow bypass: fulfilling an order the client says is paid

// JavaScript (Express + Prisma)
// Vulnerable: the client decides whether payment happened
app.post('/api/orders/:id/fulfill', requireAuth, async (req, res) => {
  const order = await prisma.order.findFirst({
    where: { id: req.params.id, userId: req.user.id },
  });
  if (!order) return res.status(404).end();
  if (req.body.paymentStatus === 'paid') {
    await prisma.order.update({
      where: { id: order.id },
      data: { status: 'FULFILLED' },
    });
  }
  res.json({ ok: true });
});
// JavaScript (Express + Prisma)
// Fixed: the server checks and transitions state in one atomic update
app.post('/api/orders/:id/fulfill', requireAuth, async (req, res) => {
  const result = await prisma.order.updateMany({
    where: { id: req.params.id, userId: req.user.id, status: 'PAID' },
    data: { status: 'FULFILLED' },
  });
  if (result.count === 0) return res.status(409).end();
  res.json({ ok: true });
});

Why the fix is safe: the order moves to FULFILLED only if the database already records it as PAID, and the conditional update blocks replays and races. The same pattern stops a client from reapplying a discount: store the applied state server-side and make the transition conditional on it.

Why no pattern rule flags the vulnerable version: this endpoint checks ownership. The flaw is that it trusts a request field to stand in for the order's state machine, and every app's state machine is different.

Why does rule-based SAST miss these flaws?

Rule-based SAST matches known dangerous patterns, and a missing ownership check is an absence with no pattern to match. Injection rules work because the sink is fixed: a SQL string built from user input looks roughly the same in every codebase. Authorization has no fixed sink. The correct check depends on each application's data model, roles, and tenancy rules.

Here is what happens when you try to write a rule for the invoice IDOR:

  1. First attempt: flag any database lookup by ID where the where clause has no user or tenant field. This fires on every public product page, blog post, docs article, and feature flag lookup. Developers mute it within a week.
  2. Second attempt: suppress the finding when the route has an authorization decorator or middleware. Now the rule trusts requireAuth, which only proves the caller logged in. It also misses the version where the controller is clean and the ownership check is supposed to live in InvoiceService.get() two files away.
  3. Third attempt: look for a specific field name like userId in the query. One team calls it ownerId, another uses accountId, a third uses orgId, and a fourth scopes through a join on memberships. You end up writing a custom rule per app, per resource.
  4. Fourth attempt: track whether some authorization function gets called on the path. The rule can see that canAccess(user, invoice) ran. It can't tell whether canAccess checks the right relationship or returns true on a missing record.

Multi-layer applications make it harder: data passes through routers, middleware, controllers, services, and repositories, and pattern matching loses context between source and sink.

For the broader set of blind spots, including how they show up in AI-written code, see what static analysis catches and misses in AI-generated code.

Why AI coding assistants make access control flaws more common

AI coding assistants make access control flaws more common because they generate working endpoints without knowing your application's ownership or tenancy model. Ask a coding assistant to "add an endpoint to fetch an order by ID" and you'll get something close to the vulnerable invoice handler above. It's clean, idiomatic, and correct for the prompt. The model doesn't know your tenancy model unless that model is in its context, and most prompts don't include it.

The assistant will often write a test too:

// JavaScript (Jest + Supertest)
// Vulnerable: the suite only tests the owner, so it passes on the IDOR
test('GET /api/orders/:id returns the order', async () => {
  const res = await request(app)
    .get(`/api/orders/${aliceOrder.id}`)
    .set(authHeaderFor(alice));
  expect(res.status).toBe(200);
});

Nobody asked for the test where Bob requests Alice's order, so nobody wrote it. The endpoint is functionally correct and insecure at the same time. Adding the cross-account case makes the gap visible:

// JavaScript (Jest + Supertest)
// Fixed: the suite also asserts that another user is refused
test('GET /api/orders/:id returns the order to its owner', async () => {
  const res = await request(app)
    .get(`/api/orders/${aliceOrder.id}`)
    .set(authHeaderFor(alice));
  expect(res.status).toBe(200);
});

test('GET /api/orders/:id hides the order from other users', async () => {
  const res = await request(app)
    .get(`/api/orders/${aliceOrder.id}`)
    .set(authHeaderFor(bob));
  expect(res.status).toBe(404);
});

The second test fails against the unscoped endpoint and passes once the query filters by owner. Benchmark testing shows the same gap at scale: only 10.5% of an AI coding agent's solutions came back secure, even when 61% were functionally correct.

Volume compounds the problem. Almost half of companies now have codebases that are at least 50% AI-generated, up from 20% at the start of 2025. CRUD and API code is where assistants are most productive, and it's also where object-level authorization decisions live. More generated endpoints means more chances for a missing ownership predicate, arriving faster than human review can handle. For the full category breakdown beyond access control, see the most common security vulnerabilities in AI-generated code.

How AI SAST finds IDOR and business logic flaws

Endor Labs AI SAST orchestrates specialized AI agents that analyze code the way a security engineer would, combining rule-based pattern matching, dataflow tracing, and multi-pass LLM reasoning. Detection agents trace user-controlled data from source to sink across multi-file architectures. Triage agents classify every finding as true positive, false positive, or unknown. Remediation agents propose context-aware fixes. The whitepaper explains how the engine combines agents, program analysis, and rules.

The agents work from the Endor Labs patented code context graph, which uses deterministic program analysis to model application behavior with line-level detail, including call graphs and dataflow. That gives the LLM reasoning repeatable grounding: the call path and data flow are facts the agent reads, and its job is to reason about what those facts mean for authorization.

Here's how the AI SAST detection agent works through a realistic version of the invoice IDOR, where the request path spans several files:

GET /api/invoices/:id
  routes/invoices.js        requireAuth -> invoiceController.show
  controllers/invoice.js    show(req) -> invoiceService.get(req.params.id)
  services/invoice.js       get(id) -> invoiceRepo.findById(id)
  repos/invoice.js          prisma.invoice.findFirst({ where: { id } })
  1. Map the endpoint. The agent identifies the route, its HTTP method, and the middleware chain. It sees requireAuth and records that the route is authenticated.
  2. Identify the user-controlled key. req.params.id comes straight from the URL, so the caller controls which invoice is requested.
  3. Trace the key to data access. Using the code context graph, the agent follows id from the controller through the service and repository into the Prisma query, across all four files.
  4. Search the path for an ownership predicate. The agent checks every hop for a constraint tying the invoice to the caller: a tenantId or userId in the query, a policy call in the service, a guard in middleware, or a post-fetch comparison. It also looks at how other invoice endpoints in the repo scope their queries, which tells it what this app's ownership field is called.
  5. Hand off with evidence. Finding no predicate, the agent passes a finding to the triage agent with the route, the data flow from req.params.id to findFirst, the call path, and the specific missing check: "invoice lookup is not scoped to req.user.tenantId, unlike listInvoices and updateInvoice."

Step 4 is where rules break and reasoning works. The agent doesn't need someone to tell it the ownership field is tenantId. It infers the convention from the codebase and spots the endpoint that breaks it. The same approach applies to the role check and the checkout flow: compare the sensitive action against how the rest of the application protects similar actions and data, then trace whether that protection exists on this path.

\In the June 2026 GA benchmark across 8 real-world projects containing 192 real vulnerabilities, Endor Labs AI SAST:

  • Found 3x more real vulnerabilities than frontier models.
  • Found 4x more high-severity findings than the strongest traditional tool (72 vs 17).
  • Produced ~60% fewer false positives than pattern-based SAST.
  • Surfaced 63 unique findings no other tool found.

How to triage AI SAST findings and keep false positives low

To triage an access-control finding, check the evidence attached to it against a short set of authorization questions. A credible finding shows you the route, the data flow, the call path, and the predicate it expected and didn't find. If it can't show you those, it isn't ready for a developer.

Run through this checklist:

  • Is the route authenticated? If it isn't, you may be looking at a missing authentication bug, which is a different fix.
  • Is the object ID user-controlled? Path parameters, query strings, request bodies, and headers all count.
  • Is the data access scoped by owner, tenant, or role anywhere on the call path? Check middleware, decorators, policy layers, service methods, and the query itself, not only the handler.
  • Should the  resource be public? Product listings and published articles don't need ownership checks.
  • Can a two-account test reproduce it? Log in as user A, request user B's object, and compare the response.

Most findings resolve at the third question. If the evidence shows the full path and the absent predicate, a reviewer can confirm or dismiss it in a couple of minutes.

Endor Labs triage agents run the first pass of this process, classifying each finding  as true positive, false positive, or unknown, with the data flow, call paths, and reachability proof attached. Developers can confirm issues instead of noise. By combining agentic reasoning, program analysis, and rules, Endor Labs AI SAST eliminates up to 92% of false positives.

Where AI SAST fits with DAST, pentesting, and code review

AI SAST is the control that runs on every change, and DAST, pentesting, and code review each add something it complements. Here's how the four compare for authorization and logic flaws.

Method When it runs What it needs to find IDOR What it tends to miss Cost per change
AI SAST Every pull request Source code and the repository context around the endpoint Little on the code path, since it traces middleware, policies, and services across files Low, automated per PR
DAST Against a running build, often nightly or pre-release At least two authenticated test identities and knowledge of valid object IDs for each resource Endpoints the crawler never reaches and states that need multi-step setup Medium, someone must maintain test identities and data
Pentesting Periodically, often yearly or per major release Skilled testers, scoped access, and time Code that changed after the engagement ended High, scheduled engagements
Code review Every pull request A reviewer who knows the app's ownership and tenancy model Subtle gaps across files, and anything that slips through at high PR volume High, human time that grows with AI-generated volume

DAST can find IDOR, but only with deliberate setup. The OWASP Authorization Testing Automation Cheat Sheet describes building an authorization matrix of roles and resources, then automating requests for each combination. That works, and it means every new endpoint needs new matrix entries and test data. Pentesters dig into chained, multi-step logic flaws, and they run on a calendar. Code reviewers catch intent problems, but a reviewer skimming forty AI-generated PRs a day won't trace an ID through four files every time.

The practical setup: let AI SAST check every pull request for missing ownership and role checks, and feed its confirmed findings into pentest scoping and your authorization test matrix. Reviewers then spend their attention on design questions instead of hunting for missing where clauses.

Catch access control flaws in every pull request with Endor Labs

Endor Labs AI Security Review runs the AI SAST engine on every pull request. A PR scan takes about a minute. Each confirmed finding ships with a context-aware fix, such as the scoped query or the role guard from the examples above, which cuts the 4+ hours of researching a single SAST result down to minutes. 

If you want to see how detection and triage agents handle authorization in your own stack, start with Endor Labs AI SAST, or take a tour of AI SAST to watch the agents trace a finding from route to query.

Frequently asked questions

Do UUIDs or random IDs prevent IDOR?

Random IDs make object references harder to guess and leave the authorization gap in place. IDs leak through URLs, logs, shared links, browser history, and API responses that list related objects. Once an attacker has a valid ID, nothing stops the request. Use random IDs as an extra layer, and keep the ownership predicate on every lookup.

Is AI SAST deterministic enough to give consistent results on the same code?

Endor Labs AI SAST builds its evidence with deterministic program analysis, so the same code produces the same call paths and data flows on every scan. The LLM reasoning runs against that fixed evidence instead of free-form reading of source files. Triage classification and the attached evidence let you verify each result yourself rather than trusting the model's word.

Can AI SAST find authorization flaws when the check lives in an API gateway or external policy service?

Yes, AI SAST finds these flaws by tracing each request path and flagging any object lookup that reaches data access without an in-code ownership predicate, with evidence a reviewer can check against the gateway or policy service. It analyzes the authorization logic in the repository, including middleware, decorators, policy code, and service layers in other files. Gateways usually enforce authentication and route-level rules rather than object ownership, so an object-level check in the service is good practice either way. In multi-tenant SaaS, a missing tenant filter exposes every customer's data at once, which makes that in-code check worth having even behind a gateway.