Dev.to Security 🔐 Cybersecurity 👁 0 📖 6 min read

Your API Tests Pass. Did You Try Someone Else's ID?

A request is authenticated. The JWT signature is valid. The endpoint requires a logged-in user. And the user can still read another customer's invoice by changing one ID. That is the uncomfortable part of API authoriza

A request is authenticated. The JWT signature is valid. The endpoint requires a logged-in user.

And the user can still read another customer's invoice by changing one ID.

That is the uncomfortable part of API authorization: proving who is calling your API is not the same as proving they may access the specific object they requested.

This bug is commonly called Broken Object Level Authorization (BOLA) or, in many discussions, IDOR (Insecure Direct Object Reference). OWASP lists it as API1:2023 because it is easy to introduce when an API accepts object IDs from a client and forgets to check access to the object itself.

Let's turn that risk into something you can test.

1. Authentication answers the wrong question

Imagine this endpoint:

GET /api/invoices/4812

Your authentication middleware verifies the access token and attaches a trusted user context to the request. Great.

But what happens next?

A route that does this is incomplete:

const invoice = await db.invoice.findUnique({
  where: { id: req.params.invoiceId },
});

return res.json(invoice);

The code proves only that invoice 4812 exists. It does not prove that the caller is allowed to see it.

A valid token does not make every object ID in the request trustworthy. The ID may come from a URL, query parameter, request body, nested GraphQL argument, or a list of IDs.

The authorization question is:

May this authenticated principal perform this action on this exact object, in this exact context?

That is an object-level check.

2. Scope the database lookup to the trusted caller

For a multi-tenant application, a useful first boundary is the tenant associated with the authenticated request.

The active tenant must come from trusted server-side context. If users can switch organizations, the middleware must verify that the user is actually a member of the selected tenant. Do not simply trust a tenantId supplied in a header or request body.

For example:

app.get("/api/invoices/:invoiceId", requireAuth, async (req, res) => {
  const invoice = await db.invoice.findFirst({
    where: {
      id: req.params.invoiceId,
      tenantId: req.auth.activeTenantId,
    },
  });

  if (!invoice) {
    return res.sendStatus(404);
  }

  if (!(await policy.can(req.auth, "invoice:read", invoice))) {
    return res.sendStatus(404);
  }

  return res.json(invoice);
});

There are two checks here:

  • The database lookup limits the object to the caller's verified tenant.
  • The policy check evaluates the actual action against the actual object.

The second check matters when access is more nuanced than tenant membership. Perhaps an invoice is private to its owner, shared with a project team, or visible to a finance role. A tenant match alone cannot express every permission rule.

Also decide deliberately whether a denied request should return 403 Forbidden or 404 Not Found. A 404 can avoid revealing that another tenant's record exists. Consistency matters more than choosing one status code for every application.

3. UUIDs do not fix authorization

Replacing sequential IDs with UUIDs is useful for reducing easy enumeration. It is not an access-control system.

An identifier can leak through:

  • A shared link
  • An email notification
  • A browser history entry
  • An export or audit log
  • Another endpoint that returns related records

Once someone has a valid object ID, the server must still check permission.

Treat IDs as references, not secrets.

4. Test with two identities, not just two records

This is where many API test suites are weaker than they look.

A test that creates an invoice and reads it back with the same user proves the happy path. It does not prove tenant isolation.

Create fixtures for at least two tenants:

  • User A belongs to Tenant A.
  • User B belongs to Tenant B.
  • Invoice A belongs to Tenant A.
  • Invoice B belongs to Tenant B.

Then test the boundary explicitly. Here is a small example using Jest and Supertest:

describe("GET /api/invoices/:id", () => {
  it("allows an authorized user to read their invoice", async () => {
    const response = await request(app)
      .get(`/api/invoices/${invoiceA.id}`)
      .set("Authorization", `Bearer ${tokenA}`);

    expect(response.status).toBe(200);
  });

  it("does not expose another tenant's invoice", async () => {
    const response = await request(app)
      .get(`/api/invoices/${invoiceB.id}`)
      .set("Authorization", `Bearer ${tokenA}`);

    expect(response.status).toBe(404);
  });
});

The important part is not the test framework. It is the identity/object mismatch: Tenant A's token requests Tenant B's object.

Add a mutation test too. A denied update should not change the other tenant's record:

it("does not update an invoice from another tenant", async () => {
  const before = await db.invoice.findUniqueOrThrow({
    where: { id: invoiceB.id },
  });

  const response = await request(app)
    .patch(`/api/invoices/${invoiceB.id}`)
    .set("Authorization", `Bearer ${tokenA}`)
    .send({ status: "paid" });

  expect(response.status).toBe(404);

  const after = await db.invoice.findUniqueOrThrow({
    where: { id: invoiceB.id },
  });

  expect(after.status).toBe(before.status);
});

Run these against an isolated test database with deterministic fixtures. Never use a real customer record as a security-test target.

5. Build an authorization matrix

A compact matrix makes missing cases visible before they become production bugs.

Caller Requested object Expected result
Owner in Tenant A Own invoice Allow
Unrelated member in Tenant A Private invoice Deny
User in Tenant A Invoice in Tenant B Deny
Tenant admin in Tenant A Invoice in Tenant A Allow within admin scope
Tenant admin in Tenant A Invoice in Tenant B Deny
Unauthenticated caller Private invoice Reject authentication

If your product has shared resources, support roles, or platform administrators, add those cases explicitly. A tenant admin is not automatically a platform admin.

6. Check the paths that are easy to forget

Teams often protect the obvious GET /invoices/:id route and miss another path to the same data.

Include these in your review:

  • Updates and deletes: test every mutation, not only reads.
  • Nested resources: /invoices/:id/attachments/:attachmentId must verify access to both the parent and child relationship.
  • Bulk endpoints: test mixed lists containing IDs from different tenants. Define whether the whole request fails or unauthorized items are filtered, and never leak their contents.
  • Exports and downloads: a separate PDF, CSV, or file endpoint still needs the same policy.
  • GraphQL: every resolver that loads an object by ID needs an authorization decision.
  • Background jobs and webhooks: preserve the tenant and principal context when work moves outside the original HTTP request.
  • Caches: make sure cached responses cannot cross user or tenant boundaries. A cache key based only on the object ID may be insufficient.

A useful rule: search the codebase for every place an object ID enters a data-access function, then trace the authorization decision before the object is returned or changed.

7. A practical pre-release checklist

Before shipping an API that accepts object IDs, ask:

  • [ ] Is the caller authenticated before private data is accessed?
  • [ ] Is the active tenant or workspace verified server-side?
  • [ ] Is permission checked for the specific object and action?
  • [ ] Do tests cover another user and another tenant?
  • [ ] Are read, update, delete, export, bulk and nested paths covered?
  • [ ] Do denied mutation tests prove that no state changed?
  • [ ] Are role scopes explicit, especially for tenant admins and platform admins?
  • [ ] Are cache keys and background jobs scoped correctly?

You do not need a large security platform to start. Two tenants, two users, a few carefully chosen fixtures, and negative tests will catch many mistakes that happy-path tests never see.

For the deeper model, read the OWASP API Security Top 10 entry on Broken Object Level Authorization and the OWASP Authorization Cheat Sheet.

Which path is easiest for your team to forget when testing authorization: exports, bulk endpoints, nested resources, or GraphQL resolvers?

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.