Логотип Securing Collections

Securing Collections

Організація
api-platform
securing-collections

Secures API Platform collections with Doctrine extensions and link handlers. Use whenever the user mentions multi-tenant isolation, 'users must only see their own data', soft-delete filtering, scoping queries by organization or user, or validating parent ownership in nested URIs — even if they frame it as a security or privacy bug rather than a query concern.

Огляд

Видавецьapi-platform
Репозиторійskillset
Назва навичкиsecuring-collections
Зірки
29
Форки
1
Файли в пакеті
Лише інструкції
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем api-platform. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Securing Collections у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/api-platform/skillset/tree/main/skills/securing-collections
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/api-platform/skillset.git /tmp/skillset
mkdir -p .claude/skills
cp -r /tmp/skillset/skills/securing-collections .claude/skills/securing-collections
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Securing Collections в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Securing Collections, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Securing Collections не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Securing Collections

Two mechanisms restrict what data users can access at the query level.

Doctrine Extensions (Global Query Filters)

Extensions automatically modify every query for a resource class. Use them for:

  • Multi-tenant isolation (filter by organization/user)
  • Hiding soft-deleted records
  • Any filter that must apply to ALL queries (item + collection)

ORM Extension

php
<?php
namespace App\Extension;

use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use Doctrine\ORM\QueryBuilder;

final class AccountExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
    public function __construct(private UserHelper $userHelper) {}

    public function applyToCollection(QueryBuilder $qb, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
    {
        $this->addWhere($qb, $resourceClass);
    }

    public function applyToItem(QueryBuilder $qb, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, ?Operation $operation = null, array $context = []): void
    {
        $this->addWhere($qb, $resourceClass);
    }

    private function addWhere(QueryBuilder $qb, string $resourceClass): void
    {
        if (Account::class !== $resourceClass) {
            return;
        }

        $user = $this->userHelper->getUser();
        if (!$user) {
            return;
        }

        $rootAlias = $qb->getRootAliases()[0];
        $qb->andWhere(sprintf('%s.organization = :org', $rootAlias))
           ->andWhere(sprintf('%s.isDeleted = :deleted', $rootAlias))
           ->setParameter('org', $user->getCurrentOrganization())
           ->setParameter('deleted', false);
    }
}

Extensions are auto-registered by Symfony's autowiring. No service tag needed.

MongoDB ODM Extension

Same structure as the ORM version; only the interfaces, the apply-method signatures, and the query API differ. Implement AggregationCollectionExtensionInterface / AggregationItemExtensionInterface (from ApiPlatform\Doctrine\Odm\Extension), and build the filter on a Doctrine\ODM\MongoDB\Aggregation\Builder instead of a QueryBuilder:

php
public function applyToCollection(Builder $aggregationBuilder, string $resourceClass, ?Operation $operation = null, array &$context = []): void
{
    $this->applyFilters($aggregationBuilder, $resourceClass);
}

// applyToItem adds `array $identifiers` after $resourceClass; both delegate here:
private function applyFilters(Builder $aggregationBuilder, string $resourceClass): void
{
    if (Account::class !== $resourceClass) {
        return;
    }
    $user = $this->userHelper->getUser();
    if (!$user) {
        return;
    }

    $aggregationBuilder->match()
        ->field('isDeleted')->equals(false)
        ->field('organization')->equals($user->getCurrentOrganization()->getId());
}

The ODM apply methods take string $resourceClass directly (no QueryNameGenerator) and receive $context by reference.

Link Handlers (Nested Resource Security)

Link handlers validate parent resource ownership for nested URIs like /accounts/{accountId}/mailboxes/{mailboxId}/messages.

MongoDB ODM Link Handler

php
<?php
namespace App\Extension;

use ApiPlatform\Doctrine\Odm\State\LinksHandlerInterface;
use Doctrine\ODM\MongoDB\Aggregation\Builder;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class MessageLinkHandler implements LinksHandlerInterface
{
    public function __construct(
        private readonly UserHelper $userHelper,
        private readonly MailboxRepository $mailboxRepository,
    ) {}

    public function handleLinks(Builder $aggregationBuilder, array $uriVariables, array $context): void
    {
        $user = $this->userHelper->getUser() ?? throw new AccessDeniedHttpException();

        // Validate parent resource exists
        $mailbox = $this->mailboxRepository->find($uriVariables['mailboxId'])
            ?? throw new NotFoundHttpException();

        // Validate parent belongs to correct account
        if ($mailbox->account->getId() !== ($uriVariables['accountId'] ?? null)) {
            throw new NotFoundHttpException();
        }

        // Validate user has access to this resource tree
        if ($mailbox->organization?->getId() !== $user->getCurrentOrganization()?->getId()) {
            throw new AccessDeniedHttpException();
        }

        // Apply query filters
        $aggregationBuilder->match()
            ->field('isDeleted')->equals(false)
            ->field('mailbox')->equals($mailbox);

        // Filter individual item if ID provided
        if (isset($uriVariables['id'])) {
            $aggregationBuilder->match()
                ->field('id')->equals($uriVariables['id']);
        }
    }
}

Assigning to Resource

php
use ApiPlatform\Doctrine\Odm\State\Options;

#[ApiResource(
    operations: [
        new Get(
            uriTemplate: '/accounts/{accountId}/mailboxes/{mailboxId}/messages/{id}',
            uriVariables: ['accountId', 'mailboxId', 'id'],
            stateOptions: new Options(
                handleLinks: MessageLinkHandler::class,
                documentClass: Message::class,
            ),
        ),
    ]
)]

When to Use Which

PatternUse Case
ExtensionGlobal filters: multi-tenant isolation, soft-delete, applies to ALL queries for a resource
Link HandlerNested resources: validate parent ownership, scope child queries to parent
security attributePer-operation checks on already-fetched objects: security: 'object.user == user'

These mechanisms stack: an extension filters the query, a link handler scopes it to the parent, and security validates the final object.

Laravel (Eloquent)

The two mechanisms exist on Laravel too, but there are no Doctrine extensions. The global-query-filter equivalent is ApiPlatform\Laravel\Eloquent\Extension\QueryExtensionInterface — one apply() method covering both item and collection (the Eloquent providers run it for every query):

php
<?php
namespace App\Extension;

use ApiPlatform\Laravel\Eloquent\Extension\QueryExtensionInterface;
use ApiPlatform\Metadata\Operation;
use Illuminate\Database\Eloquent\Builder;

final class AccountExtension implements QueryExtensionInterface
{
    public function __construct(private readonly UserHelper $userHelper) {}

    public function apply(Builder $builder, array $uriVariables, Operation $operation, $context = []): Builder
    {
        if (Account::class !== $operation->getClass() || !($user = $this->userHelper->getUser())) {
            return $builder;
        }

        return $builder
            ->where('organization_id', $user->getCurrentOrganization()->id)
            ->where('is_deleted', false);
    }
}

Tag it so the providers pick it up by binding to the QueryExtensionInterface tag in a service provider ($this->app->tag([AccountExtension::class], QueryExtensionInterface::class)); there is no Symfony autowiring.

For nested-resource ownership, implement ApiPlatform\Laravel\Eloquent\State\LinksHandlerInterface — handleLinks(Builder $builder, array $uriVariables, array $context): Builder — returning the scoped builder (it operates on an Eloquent Builder, not an aggregation pipeline). Assign it with the Eloquent Options:

php
use ApiPlatform\Laravel\Eloquent\State\Options;

new Get(
    uriTemplate: '/accounts/{accountId}/messages/{id}',
    uriVariables: ['accountId', 'id'],
    stateOptions: new Options(handleLinks: MessageLinkHandler::class, modelClass: Message::class),
)

Note Eloquent Options uses modelClass: (not documentClass:/entityClass:). Per-operation security expressions and Laravel policies (viewAny/view/ create/update/delete, or an explicit policy: on an operation) layer on top — see the operations skill's Laravel section.

Поширені запитання

Що робить навичка ШІ Securing Collections?

Secures API Platform collections with Doctrine extensions and link handlers. Use whenever the user mentions multi-tenant isolation, 'users must only see their own data', soft-delete filtering, scoping queries by organization or user, or validating parent ownership in nested URIs — even if they frame it as a security or privacy bug rather than a query concern.

Навіщо використовувати Securing Collections у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Securing Collections — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Securing Collections у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/api-platform/skillset/tree/main/skills/securing-collections. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Securing Collections?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Securing Collections?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Securing Collections — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Securing Collections?

Навичку опубліковано на GitHub: api-platform. Умови ліцензування дивіться в репозиторії. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇