Permission to act and permission to access data: two checks for one API request
An API key identifies a client, but article access requires a separate decision. Explore site scope, article visibility, 401/403/404 responses, and negative HTTP scenarios.
An API client receives a key and permission to read articles. It requests a card from its own site, receives a response, then changes the site name in the route. What should happen to the second request?
The AccessDemo module adds narrowly scoped /api/access-demo/ routes. Its stateless firewall covers that prefix; the earlier /api/cards behavior is preserved. Short fixture tokens exercise a local access model rather than a production key system.
The answer depends on two separate decisions: whether the client may perform the read operation, and which data that permission covers. Checking only the first can turn a valid key into a pass to someone else's content.
The key, the operation, and the specific article
Authentication establishes who made the request. Operation authorization determines whether that client may read cards. The data scope check determines whether it may read this particular article in the selected context.
In the example, reader-a has the article.read permission and access only to journal-a. The permission name contains no site, locale, or article state. Those constraints must be applied separately. Permission to read a published card also does not grant access to a draft.
OWASP describes Broken Object Level Authorization as a situation where an available operation lets a caller access an unauthorized object through its identifier. Replacing a sequential number with a UUID does not add an authorization check: the identifier's type does not determine the client's permissions.
For our endpoint, we choose this policy:
| Identity | article.read |
Requested site and article | Response |
|---|---|---|---|
| Not verified | Not checked | Any | 401, no article read |
| Verified | Missing | Any | 403, no article read |
| Verified | Present | Site outside the allowed scope | 404, no article read |
| Verified | Present | Allowed site, but no published card in this language | 404 |
| Verified | Present | Allowed site and available card | 200, allowed fields only |
Rejection without a read refers to article storage. Authentication may separately access a store of keys and permissions. Mixing these two kinds of reads would make the test criterion ambiguous.
A site in the route is not yet an authorized site
The route /api/access-demo/sites/journal-b/articles/shared/uk contains the client's selection. It cannot become trusted context merely because the value looks like a valid name.
Allowed sites come from the verified identity and its current grants. The controller passes the identity and requested parameters to a reader service; the service checks the operation first, then the site. Only then does it call article storage.
private function checkScope(Principal $principal, string $site): void
{
if (!in_array('article.read', $principal->operations, true)) {
throw new Forbidden();
}
if (!in_array($site, $principal->sites, true)) {
throw new NotFound();
}
}
Here, Principal is our teaching object holding a verified identity; Forbidden and NotFound are exceptions from the example. No JSON or query string field may add an entry to operations or sites.
For authentication, the prepared example uses Symfony's access token mechanism. It reads a token from the Authorization: Bearer … header, and the handler finds the teaching client. The short fixed tokens in this exercise are synthetic fixtures for local tests. A deployed service needs its own protected storage, validity checks, and key revocation; a successful lookup of a demonstration string does not provide those properties.
Search within the authorized scope from the start
Even after the site check, a risk remains: the repository might accidentally find an article globally by id. Its method therefore accepts the site, identifier, and locale, and returns only a published article matching those values.
Both sites have a synthetic article named shared, while journal-b also has only-b. These cases catch different mistakes. A request for journal-a/shared/uk must return the first site's card. A request for journal-a/only-b/uk must not find the second site's object, even though the requested site is allowed.
The exercise uses in-memory storage. A SQL adapter would need the corresponding predicates in its query:
SELECT public_id, title, locale
FROM article
WHERE site_id = :allowed_site
AND public_id = :article_id
AND locale = :locale
AND published = :published
Values are passed as parameters, and :allowed_site comes after the access check. These are illustrative names, not a deployed database schema. Scoping and parameterization solve different problems: the former determines which records are accessible; the latter separates data from query syntax.
A more complex model might also require ownership, group membership, a subscription, or a grant for a specific document. Those rules must be added to the decision. Site membership alone is sufficient only for the rule defined in our example.
Symfony voters let an application express a decision about an action and an object as a separate service. A voter does not automatically add SQL filters, however. If a voter checks some rules while a storage query checks others, both responsibilities must be explicit. This exercise keeps the rule in a reader service so that the path of a single request is easy to follow.
What a rejection actually means
For a missing article, a draft, an unavailable locale, and an unauthorized site, we return the same JSON:
{"error":"article_unavailable"}
The HTTP status in these cases is 404. RFC 9110, Sections 15.5.4–15.5.5 permits that response when a server does not wish to disclose the existence of an inaccessible resource. It is our choice for this card endpoint, not a requirement to conceal every rejection in every API.
Missing permission for the operation itself produces 403 before an object lookup. An unverified identity produces 401 with a WWW-Authenticate: Bearer header, following the Bearer challenge mechanism. Repeating the same request with the same key does not fix a missing permission.
The external error contains no foreign article title, owner name, or explanation that the record was found in another site. Reasons needed by an operator can be recorded in an internal log with its own access rules, excluding tokens and unnecessary data.
Identical JSON does not guarantee identical execution time, the size of every header, or intermediary cache behavior. Those properties need separate analysis. The teaching check compares the status and public response body without claiming to eliminate every side channel.
The access boundary also runs through the list
A detail card can be correct while a list's total counts articles from every site. That exposes information outside the set of permitted cards.
The list therefore uses the same scope: the allowed site, selected locale, and published state. In our example, total counts records that have already been filtered. Pagination, search suggestions, and related content need their own checks with equivalent rules.
A successful response has limits too. The teaching record contains internalNote, but only id, title, and locale leave the service. Permission to read a card does not authorize serialization of the entire entity. Different field sets require separate representation contracts.
A cache must not bypass permission checks. For the exercise, we choose Cache-Control: no-store on responses from these operations, including rejections. This simplifies the exercise; it is not a universal API caching strategy. A cache can later account for the site, locale, allowed representation, and current grants. In particular, a 404 should not be left to an intermediary's defaults: RFC 9110 explicitly describes it as heuristically cacheable.
An exercise where the negative cases matter
Start with two short requests: one without a key and one using a key without article.read. The expected statuses are 401 and 403, and the article repository's call counter must remain zero. Then cover an allowed card, a changed site, a foreign identifier inside an allowed site, a draft, and an unavailable locale.
For rejections, compare the public JSON; for success, compare the exact field set and correct title. A separate test checks the list and its count. Another keeps the same key, changes its permitted sites in the teaching grant store, and repeats the request: the next read must reflect the change. This tests the rule in our local store, not a deployed token revocation system.
Once the complete HTTP exercise has run, its results can be compared with this matrix. The test source currently describes expectations. The main decision is already explicit: a known identifier finds an article only within the authorized scope, and successful authorization opens a specific representation with specific fields.
Add the module to the same application
Install symfony/security-bundle:8.1.* through Composer/Flex in the existing article_demo. Sources live in src/AccessDemo and src/Controller/AccessDemoController.php. Merge the configuration below into config/packages/security.yaml: add the provider, place the narrow firewall before a broader main/API firewall and its access_control rule before broader rules. Preserve configuration for other routes.
The following extends the existing services block in config/services.yaml. Preserve earlier registrations, imports and _defaults; keep the rest of the file.
services:
App\AccessDemo\ArticleRepository: ~
App\AccessDemo\Reader: ~
App\AccessDemo\Security\LabIdentityStore: ~
App\AccessDemo\Security\LabAccessTokenHandler: ~
App\AccessDemo\Security\AuthenticationResponse: ~
App\Controller\AccessDemoController: ~
config/packages/security.yaml:
security:
providers:
access_demo_clients:
id: App\AccessDemo\Security\LabIdentityStore
firewalls:
access_demo:
pattern: ^/api/access-demo/
stateless: true
provider: access_demo_clients
entry_point: App\AccessDemo\Security\AuthenticationResponse
access_token:
token_handler: App\AccessDemo\Security\LabAccessTokenHandler
failure_handler: App\AccessDemo\Security\AuthenticationResponse
access_control:
- { path: ^/api/access-demo/, roles: ROLE_API }
Merge these definitions into the existing services block in config/services_test.yaml, preserving earlier test settings:
services:
App\AccessDemo\ArticleRepository:
autowire: true
public: true
App\AccessDemo\Security\LabIdentityStore:
autowire: true
public: true
composer require 'symfony/security-bundle:8.1.*'
php bin/console lint:container --env=test
APP_ENV=test php bin/phpunit tests/AccessDemo