This skill enforces architecture for the Prowler API by validating role-based access control and maintaining database tenant isolation.

Install

mkdir -p .claude/skills/prowler-api && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/7567" && unzip -o skill.zip -d .claude/skills/prowler-api && rm skill.zip

Installs to .claude/skills/prowler-api

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Prowler API patterns: RLS, RBAC, providers, Celery tasks. Trigger: When working in api/ on models/serializers/viewsets/filters/tasks involving tenant isolation (RLS), RBAC, or provider lifecycle.
195 chars · catalog description✓ has a “when” trigger
Advanced

Key capabilities

  • →Enforce tenant isolation via rls_transaction
  • →Validate role access control with get_role
  • →Execute database routing for 4-database architecture
  • →Apply decorators for tenant and provider lifecycle
  • →Manage through-models for M2M relationships

How it works

It wraps database access within an RLS transaction block and applies specific routing logic based on the 4-database schema.

Inputs & outputs

You give it
API model or viewset file path
You get back
Code snippet with security decorators and routing

When to use prowler-api

  • →Implement Row-Level Security
  • →Validate RBAC role checks
  • →Manage tenant-aware Celery tasks

About this skill

When to Use

Use this skill for Prowler-specific patterns:

  • Row-Level Security (RLS) / tenant isolation
  • RBAC permissions and role checks
  • Provider lifecycle and validation
  • Celery tasks with tenant context
  • Multi-database architecture (primary, replica, admin)
  • Server-Sent Events (SSE) endpoints

For generic DRF patterns (ViewSets, Serializers, Filters, JSON:API), use django-drf skill.

All paths below are relative to api/src/backend/ unless they start with api/.


Critical Rules

  • ALWAYS use rls_transaction(tenant_id) when querying tenant data outside a ViewSet (tasks, jobs, management commands)
  • ALWAYS take tenant_id from the auth token (request.tenant_id), NEVER from request.data
  • ALWAYS pass tenant_id to get_role(user, tenant_id); inside BaseRLSViewSet use the cached self.user_role
  • ALWAYS use explicit through models (inheriting RowLevelSecurityProtectedModel) for M2M relationships
  • ALWAYS give Celery tasks a name=; route with queue= (omitted = default celery queue)
  • ALWAYS call tasks with keyword arguments (tenant_id=...): the decorators read kwargs
  • NEVER access Provider.objects (or any tenant model) in Celery without RLS context
  • NEVER combine plain @set_tenant with @handle_provider_deletion: @set_tenant pops tenant_id, which @handle_provider_deletion needs. Use @set_tenant(keep_tenant=True)
  • NEVER use MainRouter.admin_db unless it is an auth or cross-tenant admin operation (it bypasses RLS)

rls_transaction(value, parameter=POSTGRES_TENANT_VAR, using=None, retry_on_replica=True) validates that value is a UUID (UUID objects and strings both work) and raises ValidationError otherwise.


Architecture Overview

Databases (config/django/{devel,production,testing}.py)

AliasDB userPurposeRLS
defaultPOSTGRES_USER (default = the prowler_user entry)Standard API queriesYes
adminPOSTGRES_ADMIN_USERMigrations, auth lookups, Django internal tablesNo
replicaPOSTGRES_REPLICA_USERRead-only queriesYes
admin_replicaPOSTGRES_ADMIN_USERAdmin reads on replicaNo
neo4jNEO4J_USERGraph DB for Attack Paths (not routed by Django)-
from api.db_router import MainRouter, READ_REPLICA_ALIAS

User.objects.using(MainRouter.admin_db).get(id=user_id)  # Auth lookups (bypasses RLS)

with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS):  # Read-heavy task code
    Finding.objects.filter(scan_id=scan_id).count()
  • MainRouter.allow_migrate() only allows admin: run manage.py migrate --database admin.
  • READ_REPLICA_ALIAS is None without a replica; rls_transaction then uses default.
  • Replica failures retry (POSTGRES_REPLICA_MAX_ATTEMPTS, default 3) and then fall back to primary.

RLS Request Flow (api/base_views.py)

Request -> BaseRLSViewSet.dispatch()  replica for SAFE_METHODS (if configured), transaction.atomic
        -> BaseRLSViewSet.initial()   tenant_id from request.auth (JWT or API key)
                                      rls_transaction(tenant_id) -> set_config('api.tenant_id', ...)
        -> queries are tenant-scoped; serializer context gets tenant_id

Other bases in the same file: BaseTenantViewset (tenant CRUD), BaseUserViewset (user endpoints), BaseViewSet (no RLS).


Implementation Checklist

#PatternReferenceKey Points
1RLS Modelsapi/rls.pyInherit RowLevelSecurityProtectedModel, add RowLevelSecurityConstraint
2RLS Transactionsapi/db_utils.pyrls_transaction(tenant_id) context manager
3RBAC Permissionsapi/rbac/permissions.pyPermissions enum, HasPermissions, get_role(), get_providers()
4Provider Validationapi/models.pyvalidate_<provider>_uid() staticmethods on Provider
5Celery Taskstasks/tasks.py, api/decorators.py, config/celery.py@shared_task(base=RLSTask, name=...), @set_tenant, @handle_provider_deletion
6Task business logictasks/jobs/*.pyKeep tasks.py thin; logic lives in jobs/
7RLS Serializersapi/v1/serializers.pyInherit RLSSerializer to auto-inject tenant_id
8Base ViewSetsapi/base_views.pyBaseRLSViewSet for tenant-scoped resources
9SSE endpointsapi/sse/Subclass BaseSSEViewSet, build channels with make_channel_name()
10Changelogapi/changelog.d/Add a towncrier fragment, never edit CHANGELOG.md (see prowler-changelog)

Full file paths: See references/file-locations.md


Decision Trees

Which Base Model?

Tenant-scoped data           -> RowLevelSecurityProtectedModel
Global/shared data           -> models.Model + BaseSecurityConstraint (rare)
Partitioned time-series      -> PostgresPartitionedModel + RowLevelSecurityProtectedModel
Hide data of deleted providers -> objects = ActiveProviderManager(); all_objects = models.Manager()

Which Manager?

Normal queries           -> Model.objects (ActiveProviderManager filters out deleted providers)
Include deleted records  -> Model.all_objects
Celery task context      -> Must be inside rls_transaction() first

Which Database?

Standard API queries     -> default (automatic via ViewSet)
Read-only API requests   -> replica (automatic for SAFE_METHODS in BaseRLSViewSet)
Heavy reads in tasks     -> rls_transaction(tenant_id, using=READ_REPLICA_ALIAS)
Auth/admin operations    -> MainRouter.admin_db
Cross-tenant lookups     -> MainRouter.admin_db (use sparingly!)

Which Celery Decorators?

@set_tenant sets api.tenant_id on the default connection inside transaction.atomic.

Task needsPattern (real example in tasks/tasks.py)
RLS context, no tenant_id param@set_tenant (check_provider_connection_task)
RLS context + tenant_id param + deletion handling@set_tenant(keep_tenant=True) then @handle_provider_deletion (generate_outputs_task)
Job opens its own rls_transaction + deletion handling@handle_provider_deletion only (perform_scan_task, perform_scan_summary_task)
@shared_task(base=RLSTask, name="scan-report", queue="scan-reports")
@set_tenant(keep_tenant=True)
@handle_provider_deletion
def generate_outputs_task(scan_id: str, provider_id: str, tenant_id: str):
    ...

@handle_provider_deletion converts DB errors into ProviderDeletedException when the provider (looked up via provider_id or scan_id kwarg) was deleted mid-task.


RLS Model Pattern

from api.rls import RowLevelSecurityConstraint, RowLevelSecurityProtectedModel

class MyModel(RowLevelSecurityProtectedModel):
    # tenant FK inherited from parent
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    name = models.CharField(max_length=255)
    inserted_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True, editable=False)

    class Meta(RowLevelSecurityProtectedModel.Meta):
        db_table = "my_models"
        constraints = [
            RowLevelSecurityConstraint(
                field="tenant_id",
                name="rls_on_%(class)s",
                statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
            ),
        ]

    class JSONAPIMeta:
        resource_name = "my-models"

M2M Relationships (MUST use through models)

class Resource(RowLevelSecurityProtectedModel):
    tags = models.ManyToManyField(ResourceTag, through="ResourceTagMapping")

class ResourceTagMapping(RowLevelSecurityProtectedModel):
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE)
    tag = models.ForeignKey(ResourceTag, on_delete=models.CASCADE)

    class Meta(RowLevelSecurityProtectedModel.Meta):
        constraints = [
            RowLevelSecurityConstraint(
                field="tenant_id",
                name="rls_on_%(class)s",
                statements=["SELECT", "INSERT", "UPDATE", "DELETE"],
            ),
        ]

Async Task Response Pattern (202 Accepted)

Real code: ProviderViewSet.connection in api/v1/views.py.

@action(detail=True, methods=["post"], url_name="connection")
def connection(self, request, pk=None):
    self.get_object()  # visibility check before queuing
    with transaction.atomic():
        task = check_provider_connection_task.delay(
            provider_id=pk, tenant_id=self.request.tenant_id
        )
    prowler_task = Task.objects.get(id=task.id)  # created by RLSTask.apply_async
    serializer = TaskSerializer(prowler_task)
    return Response(
        data=serializer.data,
        status=status.HTTP_202_ACCEPTED,
        headers={"Content-Location": reverse("task-detail", kwargs={"pk": prowler_task.id})},
    )

Providers (16 in Provider.ProviderChoices)

ProviderValueUID Format
AWSaws12 digits
AzureazureUUID v4
GCPgcp6-30 chars, lowercase, letter start (legacy domain:project allowed)
Kuberneteskubernetes2-251 chars (context name or cluster ARN)
M365m365Valid domain
GitHubgithub1-39 chars, alphanumeric + hyphens
MongoDB Atlasmongodbatlas24-char hex
IaCiacRepository URL
Oracle CloudoraclecloudTenancy OCID (ocid1.…)
Alibaba Cloudalibabacloud16 digits
Cloudflarecloudflare32-char lowercase hex
OpenStackopenstackProject ID or name
ImageimageContainer image reference
Google WorkspacegoogleworkspaceC + alphanumerics
Vercelvercelteam_ + 16-32 alphanumerics
OktaoktaOkta-manag

Content truncated.

When not to use it

  • →Generic Django Rest Framework viewsets
  • →Standard ORM queries not involving tenant context

Prerequisites

Prowler API codebase

Limitations

  • →Manual enforcement of rls_transaction required outside views
  • →Strict decorator order requirement

How it compares

It enforces strict database-level security and multi-tenancy rules rather than relying on standard application-layer checks.

Compared to similar skills

prowler-api side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
prowler-api (this skill)15moReviewAdvanced
security-header-generator51yCautionIntermediate
backend-security-coder247moNo flagsIntermediate
detecting-sql-injection-vulnerabilities34moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

security-header-generator

Dexploarer

Generates security HTTP headers (CSP, HSTS, CORS, etc.) for web applications to prevent common attacks. Use when user asks to "add security headers", "setup CSP", "configure CORS", "secure headers", or "HSTS setup".

599

backend-security-coder

sickn33

Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.

2446

detecting-sql-injection-vulnerabilities

jeremylongshore

Detect and analyze SQL injection vulnerabilities in application code and database queries. Use when you need to scan code for SQL injection risks, review query construction, validate input sanitization, or implement secure query patterns. Trigger with phrases like "detect SQL injection", "scan for SQLi vulnerabilities", "review database queries", or "check SQL security".

35

dependency-auditor

moshesham

Dependency and license review for Python projects. Use when: auditing requirements.txt, checking for vulnerabilities, reviewing licenses, updating dependencies, managing version constraints.

00

django-pro

sickn33

Master Django 5.x with async views, DRF, Celery, and Django Channels. Build scalable web applications with proper architecture, testing, and deployment. Use PROACTIVELY for Django development, ORM optimization, or complex Django patterns.

2066

senior-backend

davila7

Comprehensive backend development skill for building scalable backend systems using NodeJS, Express, Go, Python, Postgres, GraphQL, REST APIs. Includes API scaffolding, database optimization, security implementation, and performance tuning. Use when designing APIs, optimizing database queries, implementing business logic, handling authentication/authorization, or reviewing backend code.

1446

Search skills

Search the agent skills registry