A composite API page: authorize every section before reading data

Define a composite response contract: authorize the entire requested set before reading sections, preserve data scope, and distinguish authorization from a consistent snapshot.

A composed response has separate sections whose permissions are checked before their data is read.

An API home page often looks like a single operation: the client asks for a complete page and receives featured articles, recent content, and topics. Internally, this involves several reads that may require different permissions. Access to the route does not automatically authorize access to every section it contains.

A dangerous order is easy to overlook: read featured content, then check recent articles, and finally reject the request because topics are forbidden. No public response has been sent yet, but a protected read has already happened. It might have called another service, populated a cache, or entered a log.

Continue one article_demo on Symfony 8.1 and PHP 8.4+. The composite page reuses the existing Principal, token handler, and narrow access_demo firewall. It first selects the complete section set, checks every permission, and only then reads data. No second Security stack or application is created.

First define what a complete response means

Our model has three page sections: featured, latest, and topics. An absent sections parameter means all sections. An explicit sections=featured requests featured content alone. These are different requests with different sets of required permissions.

Section Required permission Representation
featured content.featured Published featured cards
latest content.latest A list of published cards
topics content.topics Topics from visible published cards

Our chosen rule is: authorize every requested section or reject the entire request. If the client requests the whole page but lacks content.topics, it receives 403, rather than two sections with the third silently omitted. If it only needs featured, lacking other permissions does not by itself prevent that separate request.

A contract allowing partial responses is also possible. It would need explicit section states, error rules, and an explanation of what a missing field means. This exercise has no such contract: the server does not silently turn a complete request into a partial one.

OWASP recommends denying access by default and checking permissions on every request. For a composite response, we apply that to the entire requested set. The principle itself does not determine our section names or the specific JSON shape; those are decisions for the teaching API.

Selecting sections does not grant control over their rules

The client can send sections=topics,featured. The server accepts known names, validates them, and normalizes the result to the stable order featured, latest, topics. The parameter does not contain class names, repository methods, or required permissions.

A closed server registry maps each section name to its permission. An unknown name does not trigger a fallback handler or gain an automatic grant. Duplicates, an empty value, an array instead of a string, unexpected query parameters, and an unsupported locale produce 400 before section reads in our contract. A length limit is also checked before splitting the string.

This strictness makes a request unambiguous. For example, sections=featured,featured must not mean a double read or a separate policy for the second occurrence. Adding a section requires a registry entry, an access rule, a reader implementation, and negative tests. A new response field alone is insufficient.

The language code uk identifies the Ukrainian representation. It does not change permissions or permit searching another site when a translation is missing. For an allowed locale with no content, the model returns empty lists.

Separate authorization from section reads

Authentication uses Symfony access tokens: the handler identifies a synthetic client from the Authorization header. The verified client has allowed sites and a list of permissions. The demonstration token registry is a local fixture, not a production credential store.

The route requires an authenticated identity. A separate service then checks site scope and all sections. Do not add several access_control entries for one route and assume that they sequentially check every condition: Symfony applies the first matching entry.

The central part of the teaching policy looks like this:

<?php

declare(strict_types=1);

namespace App\CompositeRead;

use App\AccessDemo\Security\Principal;

final class AccessPolicy
{
    public function assertAllowed(Principal $principal, string $site, Selection $selection): void
    {
        if (!in_array($site, $principal->sites, true)) {
            throw new OutsideScope();
        }

        foreach ($selection->sections as $section) {
            if (!in_array(Selection::PERMISSIONS[$section], $principal->operations, true)) {
                throw new CompositeForbidden();
            }
        }
    }
}

Selection already contains validated names only. The exceptions belong to this example. The policy may stop at the first forbidden item, but it must authorize the entire set before any section read. Enumerating all reasons for denial in public JSON is unnecessary here.

The composition service calls the policy once, before the read loop:

<?php

declare(strict_types=1);

namespace App\CompositeRead;

use App\AccessDemo\Security\Principal;

final class CompositeReader
{
    public function __construct(private AccessPolicy $policy, private SectionSource $source)
    {
    }

    public function read(Principal $principal, string $site, string $locale, Selection $selection): array
    {
        $this->policy->assertAllowed($principal, $site, $selection);

        $sections = [];

        foreach ($selection->sections as $section) {
            $sections[$section] = $this->source->read($section, $site, $locale);
        }

        return ['site' => $site, 'locale' => $locale, 'sections' => $sections];
    }
}

This structure exposes one boundary between authorization and accessing content. The source constructor performs no protected reads, and creating a Selection does not load articles. If those side effects are introduced later, the order of calls inside this method will no longer establish the intended property.

An allowed section still needs a data boundary

The content.latest permission does not grant access to every record in storage. Each read receives the verified site and locale, selects published content, and builds the permitted representation. Both synthetic sites contain the same identifier, shared, which helps expose an accidental global lookup.

The topics section is derived only from visible published cards. Otherwise, the API could disclose a draft's topic without returning its text. Counts, suggestions, and related objects require equivalent boundaries. Authorizing the response container does not replace restrictions on each source.

A card contains only id, title, and locale. The internal internalNote field stays in the fixture. A different field set needs a separate contract or an additional access decision. Even a fully authorized composite page must not serialize every property of internal objects.

A complete response is not a transactional snapshot

Our chosen rule guarantees an order within the model: authorization for the complete set precedes protected reads, and successful JSON is built only after every section finishes. It does not create a shared transaction across a database, search system, and external service.

If data changes between reading featured and latest, the sections may reflect different moments. A consistent snapshot needs another mechanism: a transaction with suitable isolation, a projection version, or a document prepared in advance. The choice depends on the stores; the in-memory exercise provides none of these.

Similarly, checking permissions does not stop them from being revoked during a request. The model uses the authenticated context of the current request and checks updated permissions on the next one. If a product requires an in-progress read to stop immediately, it needs a separate mechanism for keeping access decisions current. A single preliminary check loop does not provide that mechanism.

Temporary unavailability of latest after a successful featured read produces only a 503 error; previously read data does not appear in a partial body. The earlier read is not rolled back, however. It remains in the call log. Streaming each section as soon as it is read would conflict with this contract and require a different response model.

Denials belong in the contract

Condition Status Protected section reads
Identity is not authenticated 401 None
Invalid section or locale selection 400 None
Site is outside the allowed scope 404 None
At least one requested section is forbidden 403 None
The complete set is allowed and sources respond 200 Requested sections only
A required source is temporarily unavailable 503 Some reads may have occurred

The statuses follow HTTP semantics, but choosing a complete response and the same page_unavailable error for foreign and unknown sites is this API's policy. A section denial returns composite_forbidden, without listing available permissions or including data from other sections.

“No reads” refers to sources of protected sections. Token verification, permission loading, and technical logging may have their own accesses. A test that does not distinguish those resources can easily verify a different property.

Exercise responses receive Cache-Control: no-store. RFC 9111 defines the directive; it replaces neither authorization nor transport protection. A separate composite-response cache would need a key accounting for data scope, locale, selected sections, and the applicability of the access decision. This exercise does not add caching.

Check the order, not only the final status

Three independent permissions have eight combinations. When all sections are requested, seven combinations must be denied with an empty read log. Only the complete permission set opens every source. This catches a bug that checking 403 alone would miss: allowed sections might have been read too early.

9 HTTP tests with 98 assertions were executed through the same Kernel. One check iterates all 8 permission masks; the others cover section selection, site scope, locale/field boundaries, a repeated request after a permission change, and source failure. This is not an audit of production credential revocation or all process I/O.

A separate case stops a source during composition. It should establish two different facts: the client receives no partial data, while the counter still records authorized reads that already happened. This keeps the contract honest about its boundaries: check the whole request before access, produce the permitted representation, and define source-consistency requirements separately.

Add src/CompositeRead and CompositeReadController alongside existing routes. Endpoint: GET /api/access-demo/sites/{site}/home/{locale}. It stays under the existing narrow ^/api/access-demo/ firewall; earlier routes remain available. Add the entries below under the existing services block, preserving the rest of the configuration:

services:
    App\CompositeRead\AccessPolicy: ~
    App\CompositeRead\SectionSource: ~
    App\CompositeRead\CompositeReader: ~
    App\Controller\CompositeReadController: ~

Extend the same registry in src/AccessDemo/Security/LabIdentityStore.php: retain demo-read-a/demo-read-b/demo-no-operation and add demo-a-0…demo-a-7 for every mask of three section operations on journal-a. demo-b-all has those operations only on journal-b. This is the complete chapter revision of the existing file rather than a second provider. Principal stores permissions in operations; HTTP parameters do not supply them. Every token is a synthetic fixture.

A request with a synthetic local token to the running article_demo:

curl -i -H 'Authorization: Bearer demo-a-7' 'http://127.0.0.1:8000/api/access-demo/sites/journal-a/home/uk'
  1. Caching The cache key as a contract: site, language, permissions and query parameters
  2. API Permission to act and permission to access data: two checks for one API request
  3. API API errors a client can handle