Логотип Access Control Knowledge

Access Control Knowledge

Спільнота
dykyi-roman
access-control-knowledge

Access Control knowledge base. Provides ACL, RBAC, ABAC, ReBAC models, multi-tenancy patterns, and PHP implementations (Symfony Voters, Laravel Gates) for security audits and generation.

Огляд

Видавецьdykyi-roman
Репозиторійawesome-claude-code
Назва навичкиaccess-control-knowledge
Зірки
98
Форки
25
Файли в пакеті
2
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

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

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

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

  • Файлів у комплекті: 2

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

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

    Видавець на GitHub: dykyi-roman. Перед установленням перегляньте вихідні файли навички.

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

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

1

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

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

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/dykyi-roman/awesome-claude-code/tree/master/skills/access-control-knowledge
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

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

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

Claude Code — .claude/skills
git clone --depth 1 https://github.com/dykyi-roman/awesome-claude-code.git /tmp/awesome-claude-code
mkdir -p .claude/skills
cp -r /tmp/awesome-claude-code/skills/access-control-knowledge .claude/skills/access-control-knowledge
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

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

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

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

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

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

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

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

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

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

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

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

Access Control Knowledge Base

Quick reference for access control models, authorization patterns, and PHP implementations.

Access Control Models Comparison

ModelFull NameBasisGranularityScalabilityComplexity
ACLAccess Control ListPer-resource permissionsFinePoor at scaleLow
RBACRole-Based Access ControlRoles assigned to usersMediumGoodMedium
ABACAttribute-Based Access ControlPolicies over attributesVery fineExcellentHigh
ReBACRelationship-Based Access ControlObject relationshipsVery fineExcellentHigh

Decision Matrix: When to Use Which Model

ScenarioRecommendedWhy
Simple app, few resourcesACLDirect, easy to implement
Enterprise, department-based accessRBACMaps to organizational roles
Complex policies, dynamic rulesABACFlexible attribute evaluation
Social graphs, shared resourcesReBACNatural relationship modeling
Multi-tenant SaaSRBAC + tenant scopeRoles per tenant
Healthcare, finance (compliance)ABACFine-grained audit trail
Document sharing (Google Docs style)ReBACOwner/editor/viewer relations
Microservices with JWTRBAC (claims)Stateless, token-based

RBAC: Role-Based Access Control

Role Hierarchy

┌─────────────────────────────────────────────────────────────────────────────┐
│                         RBAC ROLE HIERARCHY                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│                        ┌──────────────┐                                      │
│                        │  SUPER_ADMIN │                                      │
│                        │  (all perms) │                                      │
│                        └──────┬───────┘                                      │
│                               │ inherits                                     │
│                        ┌──────▼───────┐                                      │
│                        │    ADMIN     │                                      │
│                        │  (manage)   │                                      │
│                        └──────┬───────┘                                      │
│                    ┌──────────┼──────────┐                                   │
│                    │ inherits │          │ inherits                           │
│             ┌──────▼───────┐  │  ┌───────▼──────┐                            │
│             │   MANAGER   │  │  │   EDITOR     │                            │
│             │ (approve)   │  │  │ (create/edit)│                            │
│             └──────┬───────┘  │  └───────┬──────┘                            │
│                    │          │          │                                    │
│                    └──────────┼──────────┘                                    │
│                        ┌──────▼───────┐                                      │
│                        │    USER      │                                      │
│                        │  (read)     │                                      │
│                        └──────┬───────┘                                      │
│                        ┌──────▼───────┐                                      │
│                        │    GUEST     │                                      │
│                        │  (limited)  │                                      │
│                        └──────────────┘                                      │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Permission Inheritance

RoleOwn PermissionsInherited FromTotal Permissions
GUESTview_public-1
USERview, createGUEST3
EDITORedit, publishUSER5
MANAGERapprove, assignUSER5
ADMINmanage_users, configureMANAGER, EDITOR10
SUPER_ADMINallADMINall

RBAC PHP Implementation

php
<?php

declare(strict_types=1);

namespace Domain\Authorization;

final readonly class Role
{
    /**
     * @param list<Permission> $permissions
     * @param list<self> $parents
     */
    public function __construct(
        private string $name,
        private array $permissions = [],
        private array $parents = [],
    ) {}

    public function hasPermission(Permission $permission): bool
    {
        if (in_array($permission, $this->permissions, true)) {
            return true;
        }

        foreach ($this->parents as $parent) {
            if ($parent->hasPermission($permission)) {
                return true;
            }
        }

        return false;
    }

    public function getName(): string
    {
        return $this->name;
    }

    /** @return list<Permission> */
    public function getAllPermissions(): array
    {
        $permissions = $this->permissions;

        foreach ($this->parents as $parent) {
            $permissions = array_merge($permissions, $parent->getAllPermissions());
        }

        return array_values(array_unique($permissions));
    }
}

ABAC: Attribute-Based Access Control

Core Concepts

ConceptDescriptionExample
SubjectWho is requesting accessUser with attributes (role, department, clearance)
ResourceWhat is being accessedDocument with attributes (classification, owner)
ActionOperation being performedread, write, delete, approve
EnvironmentContextual conditionsTime of day, IP range, MFA status

Policy Evaluation

┌─────────────────────────────────────────────────────────────────────────────┐
│                        ABAC POLICY EVALUATION                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   Request(subject, resource, action, environment)                            │
│       │                                                                      │
│       ▼                                                                      │
│   ┌──────────────────────┐                                                   │
│   │  Policy Decision     │                                                   │
│   │  Point (PDP)         │ ◀── Policy Store (rules)                         │
│   └──────────┬───────────┘                                                   │
│              │                                                               │
│       ┌──────┼──────┐                                                        │
│       ▼      ▼      ▼                                                        │
│   Policy1  Policy2  PolicyN                                                  │
│    ALLOW    DENY    ALLOW                                                    │
│       │      │      │                                                        │
│       └──────┼──────┘                                                        │
│              ▼                                                               │
│   ┌──────────────────┐                                                       │
│   │ Combining Algo   │                                                       │
│   │ (deny-overrides) │                                                       │
│   └────────┬─────────┘                                                       │
│            ▼                                                                 │
│         DENY                                                                 │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

ABAC Policy Implementation

php
<?php

declare(strict_types=1);

namespace Domain\Authorization;

final readonly class AbacPolicy
{
    public function __construct(
        private string $name,
        private string $description,
        /** @var list<callable(AuthorizationContext): ?bool> */
        private array $rules,
    ) {}

    public function evaluate(AuthorizationContext $context): ?bool
    {
        foreach ($this->rules as $rule) {
            $result = $rule($context);
            if ($result === false) {
                return false;
            }
        }

        return true;
    }

    public function getName(): string
    {
        return $this->name;
    }
}

final readonly class AuthorizationContext
{
    public function __construct(
        private array $subjectAttributes,
        private array $resourceAttributes,
        private string $action,
        private array $environmentAttributes = [],
    ) {}

    public function getSubjectAttribute(string $key): mixed
    {
        return $this->subjectAttributes[$key] ?? null;
    }

    public function getResourceAttribute(string $key): mixed
    {
        return $this->resourceAttributes[$key] ?? null;
    }

    public function getAction(): string
    {
        return $this->action;
    }

    public function getEnvironmentAttribute(string $key): mixed
    {
        return $this->environmentAttributes[$key] ?? null;
    }
}

ReBAC: Relationship-Based Access Control

Google Zanzibar Model

Relationships are stored as tuples: user:relation:object

TupleMeaning
user:123#viewer@document:456User 123 is a viewer of document 456
group:eng#member@user:123User 123 is a member of group eng
document:456#parent@folder:789Document 456 is in folder 789
folder:789#viewer@group:eng#memberMembers of eng group are viewers of folder 789

Relationship Graph

┌─────────────────────────────────────────────────────────────────────────────┐
│                    ReBAC RELATIONSHIP GRAPH                                   │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│   user:alice ──owner──▶ document:report                                     │
│       │                     │                                                │
│       │ member              │ parent                                         │
│       ▼                     ▼                                                │
│   group:engineering    folder:shared                                        │
│       │                     │                                                │
│       │ viewer              │ viewer                                         │
│       ▼                     ▼                                                │
│   folder:eng-docs      org:acme (all members can view)                     │
│                                                                              │
│   Check: Can alice view document:report?                                    │
│   Path:  alice ──owner──▶ document:report  ✓ (owner implies viewer)         │
│                                                                              │
│   Check: Can bob view folder:shared?                                        │
│   Path:  bob ──member──▶ org:acme ──viewer──▶ folder:shared  ✓             │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Multi-Tenancy Authorization

PatternDescriptionIsolation Level
Tenant-scoped rolesUser has different roles per tenantStrong
Shared roles, tenant filterGlobal roles, data filtered by tenantMedium
Tenant in JWT claimsTenant ID in authentication tokenMedium
Row-level securityDatabase enforces tenant isolationStrong
Separate schemasEach tenant has own DB schemaStrongest

Tenant-Scoped Authorization

php
<?php

declare(strict_types=1);

namespace Domain\Authorization;

final readonly class TenantPermissionChecker
{
    public function __construct(
        private TenantRoleRepositoryInterface $roleRepository,
    ) {}

    public function hasPermission(string $userId, string $tenantId, Permission $permission): bool
    {
        $roles = $this->roleRepository->findRolesForUserInTenant($userId, $tenantId);

        foreach ($roles as $role) {
            if ($role->hasPermission($permission)) {
                return true;
            }
        }

        return false;
    }

    public function assertPermission(string $userId, string $tenantId, Permission $permission): void
    {
        if (!$this->hasPermission($userId, $tenantId, $permission)) {
            throw new AccessDeniedException(
                sprintf('User %s lacks %s in tenant %s', $userId, $permission->value, $tenantId),
            );
        }
    }
}

Symfony Voter Implementation

php
<?php

declare(strict_types=1);

namespace Infrastructure\Security\Voter;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

final class DocumentVoter extends Voter
{
    public const string VIEW = 'DOCUMENT_VIEW';
    public const string EDIT = 'DOCUMENT_EDIT';
    public const string DELETE = 'DOCUMENT_DELETE';

    protected function supports(string $attribute, mixed $subject): bool
    {
        return in_array($attribute, [self::VIEW, self::EDIT, self::DELETE], true)
            && $subject instanceof Document;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();
        if (!$user instanceof User) {
            return false;
        }

        /** @var Document $document */
        $document = $subject;

        return match ($attribute) {
            self::VIEW => $this->canView($document, $user),
            self::EDIT => $this->canEdit($document, $user),
            self::DELETE => $this->canDelete($document, $user),
            default => false,
        };
    }

    private function canView(Document $document, User $user): bool
    {
        if ($document->isPublic()) {
            return true;
        }

        return $document->getOwnerId() === $user->getId()
            || $user->hasRole('ROLE_ADMIN');
    }

    private function canEdit(Document $document, User $user): bool
    {
        return $document->getOwnerId() === $user->getId()
            || $user->hasRole('ROLE_EDITOR');
    }

    private function canDelete(Document $document, User $user): bool
    {
        return $document->getOwnerId() === $user->getId()
            || $user->hasRole('ROLE_ADMIN');
    }
}

Laravel Gate/Policy

php
<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\Document;
use App\Models\User;

final class DocumentPolicy
{
    public function view(User $user, Document $document): bool
    {
        if ($document->is_public) {
            return true;
        }

        return $user->id === $document->owner_id
            || $user->hasRole('admin');
    }

    public function update(User $user, Document $document): bool
    {
        return $user->id === $document->owner_id
            || $user->hasRole('editor');
    }

    public function delete(User $user, Document $document): bool
    {
        return $user->id === $document->owner_id
            || $user->hasRole('admin');
    }
}

Anti-Patterns

Anti-PatternProblemSolution
Inline role checksif ($user->role === 'admin') scattered in codeUse Voter/Policy abstraction
Hardcoded permissionsPermissions compiled into codeStore in database/config
Missing deny-by-defaultForgetting to deny when no rule matchesDefault to DENY
Role explosionToo many roles (one per use case)Switch to ABAC or group permissions
Checking in views onlyNo server-side enforcementAlways check in backend
No audit loggingCannot trace who accessed whatLog every authorization decision
Caching without invalidationStale permission grantsEvent-driven cache invalidation
God roleSingle admin role with all permissionsGranular admin sub-roles

Common Violations Quick Reference

ViolationWhere to LookSeverity
No authorization on API endpointsControllers, routesCritical
Hardcoded role names in business logicDomain layer, servicesWarning
Missing tenant isolation in queriesRepositories, query buildersCritical
No CSRF protection on state-changing formsForm handlers, middlewareCritical
Permissions not cachedVoter/Policy implementationsWarning
No audit trail for access decisionsAuthorization layerWarning
Overly permissive default rolesRole configurationWarning

Detection Patterns

bash
# Authorization implementations
Grep: "Voter|VoterInterface|AbstractVoter" --glob "**/*.php"
Grep: "Gate::define|Gate::allows|Gate::denies|@can" --glob "**/*.php"
Grep: "Policy|AuthorizesRequests" --glob "**/*.php"

# Role checks
Grep: "hasRole|isGranted|->can\(|->cannot\(" --glob "**/*.php"
Grep: "ROLE_|Permission::|PermissionEnum" --glob "**/*.php"

# Inline role checks (anti-pattern)
Grep: "role\s*===?\s*['\"]admin|role\s*===?\s*['\"]user" --glob "**/*.php"

# Tenant isolation
Grep: "tenant_id|tenantId|getTenantId" --glob "**/*.php"
Grep: "TenantScope|MultiTenant|BelongsToTenant" --glob "**/*.php"

# Casbin
Grep: "Enforcer|casbin|model\.conf|policy\.csv" --glob "**/*.php"

# Security configuration
Grep: "security\.yaml|security\.php|access_control" --glob "**/*.{yaml,php}"
Grep: "#\[IsGranted|@IsGranted|@Security" --glob "**/*.php"

# Missing authorization
Grep: "class.*Controller" --glob "**/*.php"
Grep: "class.*Action" --glob "**/Action/**/*.php"

References

For detailed information, load these reference files:

  • references/models.md — Detailed ACL, RBAC, ABAC, ReBAC analysis with scalability comparisons and PHP examples
  • references/php-implementations.md — Symfony Voters, Laravel Gates/Policies, Casbin PHP, permission caching strategies

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

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

Що робить навичка ШІ Access Control Knowledge?

Access Control knowledge base. Provides ACL, RBAC, ABAC, ReBAC models, multi-tenancy patterns, and PHP implementations (Symfony Voters, Laravel Gates) for security audits and generation.

Навіщо використовувати Access Control Knowledge у TypingMind?

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

Як встановити Access Control Knowledge у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/dykyi-roman/awesome-claude-code/tree/master/skills/access-control-knowledge. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

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

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

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

Зі скількома забажаєте. У TypingMind ви можете використовувати Access Control Knowledge із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Access Control Knowledge?

Так. На GitHub цю навичку публікує dykyi-roman за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

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

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

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

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

Усі

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

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