Skip to content

Commit 946eaf0

Browse files
Merge pull request #539 from components-web-app/feat/531-usage-admin-only
GET {component}/usage is ROLE_ADMIN only (#531)
2 parents c8d3f33 + 577e145 commit 946eaf0

9 files changed

Lines changed: 31 additions & 88 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio
55
## Unreleased
66

77
### Breaking
8+
- `GET {component}/usage` is `ROLE_ADMIN` only: anonymous callers get 401 and other users 403, where anyone who could read the component used to get the counts ([#539](https://github.com/components-web-app/api-components-bundle/pull/539))
89
- A `route_security` `route` pattern matches the whole path, with `*` as its only wildcard, in `RouteVoter` and the route list alike: a pattern without a leading `*` no longer matches mid-path (add one to keep the old behaviour, e.g. `*/user-area*`), `%` and `_` are literal in the list too, and ASCII letters match regardless of case ([#538](https://github.com/components-web-app/api-components-bundle/pull/538))
910

1011
### Added

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ Resources are fetched and cached **individually**. Never embed related data outs
319319
- `ComponentPosition.component` is `ON DELETE SET NULL`, deliberately, so dynamic positions survive their fallback. Static positions are removed by `ComponentPositionRemovalStateProcessor` on an API delete only.
320320
- **Nothing stores a reference to a draft that has a published version; a never-published draft is stored as it is** (#520). Publishing a draft of a published component deletes its row, so a reference to it would be emptied by `ON DELETE SET NULL` (or lose its join rows); a never-published draft's first publish keeps the row, so a reference to it becomes live in place. `EventListener\Doctrine\DraftComponentReferenceListener` is the one place this is enforced, on `onFlush` (priority 100, before `PropagateUpdatesListener`), so the API in both modes, fixtures, CLI and direct Doctrine writes all agree, and validation (which judges the class, the cycle detector counting the pair as one) sees the draft unchanged. **Single-join-column associations:** on every inserted entity of any class, and every updated one whose association changed, an owning single-join-column association to an `AbstractComponent` (a position's `component`, a page data component property, a component field such as `related`, an application entity's) holding a draft of a published component is re-pointed at the published component and the change set recomputed. A publishable class's own `associationName` is never re-pointed. **Group owners:** for every scheduled update of a component's `componentGroups`, each group in the insert diff of a draft of a published component that the published component does not already own is moved to the published component (removed from the draft, added to the published component, `computeChangeSet()` on it, the group's `components` updated only when that collection is already dirty, so a clean one is never scheduled). A group the published component owns stays co-owned by the draft: `createDraft()` clones the collection, and that co-ownership is what the admin's draft view reads. So a group is never owned only by a draft of a published component, and naming a draft as the owner resolves exactly as naming its published component. **Watch:** an admin's IRI for a published component that has a draft can resolve to the draft on denormalization, so the module's own published IRI reaches the bundle as the draft; that is the case this listener exists for. The inverse `componentPositions` collections are not maintained.
321321
- **Publishing a draft gives the published component the union of both components' groups** (#520). `PublishableDraftMerger::mergeDraftIntoPublished()` copies properties by reflection on the published class, which never sees a parent's private property, so `AbstractComponent::$componentGroups` is not copied; it is merged explicitly with `addComponentGroup()` for each of the draft's groups. Never replace the published collection with the draft's: a group the published component gained after the draft was made would lose its only owner when the draft row is deleted.
322-
- **`GET {component}/usage` lists `locations` only for `ROLE_ADMIN`** (#531, `ComponentUsageMetadataFactory::createWithLocations()`); everyone who may read the component still gets the counts from `create()`, and the key is absent for them. The operation is `private, no-store` for every caller (`cacheHeaders` on the operation), because nothing purges it when a placement changes. **The counts are the definition of a use**: one location per counted position (a dynamic position whose fallback is the component included, flagged by `pageDataProperty`) and per page data property, from the same `findByComponent()` rows and `findPageDataComponentMetadata()` matches the counts come from, so the two can never disagree. Never compute the list from a second lookup.
322+
- **`GET {component}/usage` is `ROLE_ADMIN` only** (#531, the operation's `security`, like the orphan report and purge endpoints): anonymous is the firewall's 401, any other user 403, a draft included, before any lookup. It always returns the counts with `locations` (`ComponentUsageMetadataFactory::createWithLocations()`); `create()`, counts only, is for the delete cascade (`OrphanedResourceHelper`). The operation is `private, no-store` (`cacheHeaders` on the operation), because nothing purges it when a placement changes. **The counts are the definition of a use**: one location per counted position (a dynamic position whose fallback is the component included, flagged by `pageDataProperty`) and per page data property, from the same `findByComponent()` rows and `findPageDataComponentMetadata()` matches the counts come from, so the two can never disagree. Never compute the list from a second lookup.
323323
- **`Helper\ComponentUsage\ComponentUsageLocator` answers `renderedOn` in a fixed number of queries, whatever the depth**: it loads the component-owned subgraph as ids (group owners with each draft's published id, positions holding a group owner or a group-owning draft's published component), walks it in PHP with `ComponentUsageGraph` (visited set, a draft owner climbing through its published component), then fetches page owners, layout owners, template page data and page data holding a reached component with one `IN` list each, sized by the answer. Add a step to the walk as data in the graph, never as a query per level. `ComponentUsageLocations` is the one place for order and caps (layouts first by reference, then routed by path, then unrouted by title, untitled last; 50 locations, 20 `renderedOn`, counts exact).
324324
- **A list inside a DTO that is not an API resource is normalized as a Hydra `Collection`** unless its property carries `#[Context(normalizationContext: ['api_sub_level' => true])]`, as `ComponentUsageMetadata::$locations` does.
325325
- **A component matches a page data property by class hierarchy, never by short name** (#345). `PageDataMetadata::findPropertiesByComponentClass()` uses `is_a()` against the property's Doctrine target, so a property typed `AbstractComponent` or a parent component class holds any subclass. `PageDataProvider::findPageDataComponentMetadata()` is the one lookup behind usage counts (`/usage` and the cascade on delete), `ComponentVoter`'s page data reachability and `PropagateUpdatesListener`'s purge and Mercure fan-out, so a component held only by such a property is used, public only when the page data is on a live route, and propagates to the page data on edit.

‎src/ApiPlatform/Metadata/Resource/ComponentResourceMetadataFactory.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public function create(string $resourceClass): ResourceMetadataCollection
6767
}
6868
if ($copyOperation) {
6969
$usageOperationName = '_api_' . $usagePath . '_get_usage';
70-
$operations->add($usageOperationName, $copyOperation->withUriTemplate($usagePath)->withName($usageOperationName)->withCacheHeaders(['public' => false, 'no_store' => true]));
70+
$operations->add($usageOperationName, $copyOperation->withUriTemplate($usagePath)->withName($usageOperationName)->withCacheHeaders(['public' => false, 'no_store' => true])->withSecurity("is_granted('ROLE_ADMIN')"));
7171

7272
$movePath = \sprintf('/%s/{id}/move', $pathSegmentName);
7373
$moveOperationName = '_api_' . $movePath . '_post_move';

‎src/DataProvider/StateProvider/ComponentUsageStateProvider.php‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
use Silverback\ApiComponentsBundle\Entity\Core\ComponentInterface;
1717
use Silverback\ApiComponentsBundle\Metadata\Factory\ComponentUsageMetadataFactory;
1818
use Symfony\Component\HttpFoundation\Request;
19-
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
2019

2120
/**
2221
* @implements ProviderInterface<object>
@@ -31,7 +30,6 @@
3130
public function __construct(
3231
private ProviderInterface $decorated,
3332
private ComponentUsageMetadataFactory $metadataFactory,
34-
private AuthorizationCheckerInterface $authorizationChecker,
3533
) {
3634
}
3735

@@ -43,7 +41,7 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
4341
return $data;
4442
}
4543

46-
$usage = $this->authorizationChecker->isGranted('ROLE_ADMIN') ? $this->metadataFactory->createWithLocations($data) : $this->metadataFactory->create($data);
44+
$usage = $this->metadataFactory->createWithLocations($data);
4745
$request = $context['request'] ?? null;
4846
if ($request instanceof Request) {
4947
$request->attributes->set('data', $usage);

‎src/Resources/config/services.php‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2093,7 +2093,6 @@
20932093
[
20942094
new Reference('silverback.api_components.api_platform.state_provider.component_usage.inner'),
20952095
new Reference('silverback.metadata_factory.component_usage'),
2096-
new Reference('security.authorization_checker'),
20972096
]
20982097
);
20992098
$services->alias(ComponentUsageStateProvider::class, 'silverback.api_components.api_platform.state_provider.component_usage');

‎tests/ApiPlatform/Metadata/Resource/StateOperationMetadataTest.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ public function test_the_usage_operation_is_named_after_its_key_so_providers_can
4646
self::assertSame('/dummy_components/{id}/usage', $operation->getUriTemplate());
4747
self::assertSame(['public' => false, 'no_store' => true], $operation->getCacheHeaders());
4848
self::assertSame('main_controller', $operation->getController());
49+
self::assertSame("is_granted('ROLE_ADMIN')", $operation->getSecurity());
4950
}
5051

5152
public function test_the_move_operation_is_a_post_of_a_move_under_the_components_iri_through_the_main_controller(): void

‎tests/DataProvider/StateProvider/ComponentUsageStateProviderTest.php‎

Lines changed: 10 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,16 @@
2020
use Silverback\ApiComponentsBundle\Metadata\Factory\ComponentUsageMetadataFactory;
2121
use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyComponent;
2222
use Symfony\Component\HttpFoundation\Request;
23-
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
2423

2524
class ComponentUsageStateProviderTest extends TestCase
2625
{
2726
public function test_the_usage_operation_returns_the_usage_metadata_of_the_component_and_sets_it_as_the_request_data(): void
2827
{
2928
$component = new DummyComponent();
30-
$usage = new ComponentUsageMetadata(2, 1);
29+
$usage = new ComponentUsageMetadata(2, 1, []);
3130
$factory = $this->createMock(ComponentUsageMetadataFactory::class);
32-
$factory->expects(self::once())->method('create')->with($component)->willReturn($usage);
31+
$factory->expects(self::never())->method('create');
32+
$factory->expects(self::once())->method('createWithLocations')->with($component)->willReturn($usage);
3333
$request = new Request();
3434
$request->attributes->set('data', $component);
3535

@@ -39,34 +39,12 @@ public function test_the_usage_operation_returns_the_usage_metadata_of_the_compo
3939
self::assertSame($usage, $request->attributes->get('data'));
4040
}
4141

42-
public function test_an_admin_gets_the_usage_with_its_locations(): void
43-
{
44-
$component = new DummyComponent();
45-
$usage = new ComponentUsageMetadata(0, 0, []);
46-
$factory = $this->createMock(ComponentUsageMetadataFactory::class);
47-
$factory->expects(self::never())->method('create');
48-
$factory->expects(self::once())->method('createWithLocations')->with($component)->willReturn($usage);
49-
50-
self::assertSame($usage, $this->provider($component, $factory, $this->authorizationChecker(true))->provide(new Get(name: 'x_get_usage')));
51-
}
52-
53-
public function test_anyone_else_gets_the_usage_without_locations(): void
54-
{
55-
$component = new DummyComponent();
56-
$usage = new ComponentUsageMetadata(0, 0);
57-
$factory = $this->createMock(ComponentUsageMetadataFactory::class);
58-
$factory->expects(self::never())->method('createWithLocations');
59-
$factory->expects(self::once())->method('create')->with($component)->willReturn($usage);
60-
61-
self::assertSame($usage, $this->provider($component, $factory, $this->authorizationChecker(false))->provide(new Get(name: 'x_get_usage')));
62-
}
63-
6442
public function test_the_usage_operation_without_a_request_still_returns_the_usage_metadata(): void
6543
{
6644
$component = new DummyComponent();
67-
$usage = new ComponentUsageMetadata(0, 0);
45+
$usage = new ComponentUsageMetadata(0, 0, []);
6846
$factory = $this->createStub(ComponentUsageMetadataFactory::class);
69-
$factory->method('create')->willReturn($usage);
47+
$factory->method('createWithLocations')->willReturn($usage);
7048

7149
self::assertSame($usage, $this->provider($component, $factory)->provide(new Get(name: 'x_get_usage')));
7250
}
@@ -75,7 +53,7 @@ public function test_another_operation_on_a_component_returns_the_component(): v
7553
{
7654
$component = new DummyComponent();
7755
$factory = $this->createMock(ComponentUsageMetadataFactory::class);
78-
$factory->expects(self::never())->method('create');
56+
$factory->expects(self::never())->method('createWithLocations');
7957
$request = new Request();
8058

8159
self::assertSame($component, $this->provider($component, $factory)->provide(new Get(name: '_api_/component/dummy_components/{id}_get'), [], ['request' => $request]));
@@ -86,7 +64,7 @@ public function test_the_usage_operation_name_on_something_that_is_not_a_compone
8664
{
8765
$route = new Route();
8866
$factory = $this->createMock(ComponentUsageMetadataFactory::class);
89-
$factory->expects(self::never())->method('create');
67+
$factory->expects(self::never())->method('createWithLocations');
9068

9169
self::assertSame($route, $this->provider($route, $factory)->provide(new Get(name: 'x_get_usage')));
9270
self::assertNull($this->provider(null, $factory)->provide(new Get(name: 'x_get_usage')));
@@ -98,22 +76,14 @@ public function test_the_inner_provider_receives_the_operation_uri_variables_and
9876
$inner = $this->createMock(ProviderInterface::class);
9977
$inner->expects(self::once())->method('provide')->with($operation, ['id' => 1], ['resource_class' => Route::class])->willReturn(null);
10078

101-
(new ComponentUsageStateProvider($inner, $this->createStub(ComponentUsageMetadataFactory::class), $this->createStub(AuthorizationCheckerInterface::class)))->provide($operation, ['id' => 1], ['resource_class' => Route::class]);
102-
}
103-
104-
private function authorizationChecker(bool $isAdmin): AuthorizationCheckerInterface
105-
{
106-
$authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
107-
$authorizationChecker->expects(self::once())->method('isGranted')->with('ROLE_ADMIN')->willReturn($isAdmin);
108-
109-
return $authorizationChecker;
79+
(new ComponentUsageStateProvider($inner, $this->createStub(ComponentUsageMetadataFactory::class)))->provide($operation, ['id' => 1], ['resource_class' => Route::class]);
11080
}
11181

112-
private function provider(?object $data, ComponentUsageMetadataFactory $factory, ?AuthorizationCheckerInterface $authorizationChecker = null): ComponentUsageStateProvider
82+
private function provider(?object $data, ComponentUsageMetadataFactory $factory): ComponentUsageStateProvider
11383
{
11484
$inner = $this->createStub(ProviderInterface::class);
11585
$inner->method('provide')->willReturn($data);
11686

117-
return new ComponentUsageStateProvider($inner, $factory, $authorizationChecker ?? $this->createStub(AuthorizationCheckerInterface::class));
87+
return new ComponentUsageStateProvider($inner, $factory);
11888
}
11989
}

‎tests/Functional/Component/ComponentUsageLocationsTest.php‎

Lines changed: 2 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -310,44 +310,13 @@ public function test_rendered_on_is_capped_at_20_with_the_exact_count(): void
310310
self::assertJsonNodeSame('locations[0].renderedOn[19].routePath', '/posts/29');
311311
}
312312

313-
public function test_an_anonymous_caller_reading_the_usage_of_a_public_component_gets_the_counts_without_locations(): void
314-
{
315-
$component = new DummyComponent();
316-
self::place($component, self::groupOf(self::routedPage('Live', '/live')));
317-
self::saveSite();
318-
319-
self::requestJsonLd(static::createClient(), 'GET', self::iriOf($component) . '/usage');
320-
321-
self::assertResponseStatusCodeSame(200);
322-
self::assertJsonNodeSame('total', 1);
323-
self::assertArrayNotHasKey('locations', self::lastJson());
324-
}
325-
326-
public function test_a_user_who_is_not_an_admin_gets_the_counts_without_locations(): void
313+
public function test_the_usage_is_never_stored_by_a_shared_cache(): void
327314
{
328315
$component = new DummyComponent();
329316
self::place($component, self::groupOf(self::routedPage('Live', '/live')));
330317
self::saveSite();
331318
$client = static::createClient();
332-
self::loginAsUser($client);
333-
334-
self::requestJsonLd($client, 'GET', self::iriOf($component) . '/usage');
335-
336-
self::assertResponseStatusCodeSame(200);
337-
self::assertJsonNodeSame('total', 1);
338-
self::assertArrayNotHasKey('locations', self::lastJson());
339-
}
340-
341-
#[DataProvider('callers')]
342-
public function test_the_usage_is_never_stored_by_a_shared_cache(string $caller): void
343-
{
344-
$component = new DummyComponent();
345-
self::place($component, self::groupOf(self::routedPage('Live', '/live')));
346-
self::saveSite();
347-
$client = static::createClient();
348-
if ('admin' === $caller) {
349-
self::loginAsAdmin($client);
350-
}
319+
self::loginAsAdmin($client);
351320

352321
self::requestJsonLd($client, 'GET', self::iriOf($component) . '/usage');
353322

@@ -358,12 +327,6 @@ public function test_the_usage_is_never_stored_by_a_shared_cache(string $caller)
358327
self::assertStringNotContainsString('s-maxage', $cacheControl);
359328
}
360329

361-
public static function callers(): iterable
362-
{
363-
yield 'an anonymous caller' => ['anonymous'];
364-
yield 'an admin' => ['admin'];
365-
}
366-
367330
public function test_the_number_of_queries_does_not_grow_with_the_depth_of_the_component_chain(): void
368331
{
369332
$shallow = self::componentAtDepth(1, 'shallow');

‎tests/Functional/Component/ComponentUsageTest.php‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,14 +104,25 @@ public static function publishedOrDraft(): iterable
104104
yield 'the draft' => ['draft'];
105105
}
106106

107-
public function test_the_usage_is_as_readable_as_the_component_so_an_anonymous_caller_reads_it_for_a_component_on_a_live_route(): void
107+
public function test_an_anonymous_caller_cannot_read_the_usage_of_a_component_on_a_live_route(): void
108108
{
109109
$client = static::createClient();
110110
$site = self::createComponentInRoute('/live');
111111

112112
self::requestJsonLd($client, 'GET', self::iriOf($site['component']) . '/usage');
113113

114-
self::assertUsage(1, 0);
114+
self::assertResponseStatusCodeSame(401);
115+
}
116+
117+
public function test_a_user_who_is_not_an_admin_cannot_read_the_usage_of_a_component_on_a_live_route(): void
118+
{
119+
$client = static::createClient();
120+
self::loginAsUser($client);
121+
$site = self::createComponentInRoute('/live');
122+
123+
self::requestJsonLd($client, 'GET', self::iriOf($site['component']) . '/usage');
124+
125+
self::assertResponseStatusCodeSame(403);
115126
}
116127

117128
public function test_an_anonymous_caller_cannot_read_the_usage_of_a_component_on_a_page_no_route_reaches(): void
@@ -144,7 +155,7 @@ public function test_a_user_who_is_not_an_admin_cannot_read_the_usage_of_a_draft
144155

145156
self::requestJsonLd($client, 'GET', $pair['draft'] . '/usage');
146157

147-
self::assertResponseStatusCodeSame(404);
158+
self::assertResponseStatusCodeSame(403);
148159
}
149160

150161
private static function adminClient(): Client

0 commit comments

Comments
 (0)