API backend
Overview
The backend under api/ is Prowler's Django/DRF JSON API plus Celery task runner. api/README.md names the runtime pieces: the DRF API, Celery workers, PostgreSQL for persistence, and Valkey/Redis-compatible broker storage. The Docker image in api/Dockerfile builds a Python 3.12 runtime, installs the Prowler SDK dependency from api/pyproject.toml, copies api/src/backend/, and launches through api/docker-entrypoint.sh; the entrypoint runs migrations on prod/dev, optionally manages partitions, starts Gunicorn against config.asgi:application, or starts Celery worker/beat commands.
Configuration starts in api/…/base.py. It installs the local api app, DRF JSON:API renderers/parsers, django-celery-results/beat, allauth/social login, API keys, and django_eventstream. The default API authentication is api.authentication.CombinedJWTOrAPIKeyAuthentication, which chooses JWT for Authorization: Bearer ... or tenant API key auth for Authorization: Api-Key ...; API key validation deliberately uses the admin database alias in api/…/authentication.py so authentication can happen before tenant RLS is set. api/…/production.py defines the database aliases (default/prowler_user, admin, replica, admin_replica, plus graph settings for Neo4j/Neptune), and api/…/db_router.py sends Django/allauth tables to the admin connection while normal API reads/writes use the current alias. Request-scoped tenant isolation is in api/…/base_views.py: BaseRLSViewSet wraps dispatch in a transaction, selects the replica for safe methods when configured, then calls api.db_utils.rls_transaction() to set the Postgres tenant GUC that powers the row-level-security constraints from api/…/rls.py.
HTTP routing is narrow at the top level: api/…/urls.py exposes /api/v1/, /health/live, and /health/ready. api/…/urls.py registers JSON:API resources without trailing slashes for users, tenants, providers, scans, attack-paths-scans, tasks, resources, findings, compliance/overview, schedules, integrations, processors, SAML config, Lighthouse config, API keys, and mute rules. It also defines special routes for tokens (/tokens, /tokens/refresh, /tokens/switch, SAML/Google/GitHub token routes), provider secrets, invitations, JSON:API relationship mutation routes, /schema, and /docs.
The persistence model is concentrated in api/…/models.py. Tenant is defined in api/…/rls.py; tenant-owned models inherit RowLevelSecurityProtectedModel, and many add RowLevelSecurityConstraint policies. Providers (Provider) store the cloud/security-provider type, UID validation, credentials relationship, soft-deletion behavior, and connection state. Scans (Scan) belong to providers, hold state/progress/timing, scanner args, output location, and a link to an API Task. Resources (Resource) are unique by (tenant_id, provider_id, uid), carry denormalized searchable cloud metadata and tags. Findings (Finding) and ResourceFindingMapping are django-postgres-extra range-partitioned tables keyed by UUIDv7 IDs/finding IDs; findings store status, severity, check metadata, compliance, mute fields, denormalized resource facets, and links to scans/resources. Task bridges tenant-visible API task rows to django_celery_results.TaskResult rows. AttackPathsScan stores attack-path graph scan state, graph readiness, provider/scan/task links, Cartography update metadata, schema-migration state, and sink backend.
Core API behavior lives in api/…/views.py. ProviderViewSet lists visible providers based on RBAC/provider groups, creates/updates providers with dedicated serializers, starts a provider connection check via check_provider_connection_task, and soft-deletes providers before queueing delete_provider_task. ScanViewSet.create() is the manual scan entry point: it validates a provider, locks the provider row, checks for an active/queued scan, creates the Scan, pre-creates a tenant-visible Task/TaskResult via tasks.tasks.create_scan_task_record(), pre-creates an Attack Paths scan row where supported, and publishes scan-perform on transaction commit unless another scan for that provider is active. Report download actions on ScanViewSet read Scan.output_location and return local files or S3 presigned redirects for ZIP reports, compliance CSV/OCSF artifacts, and PDF reports (CIS, threatscore, ENS, NIS2, CSA). TaskViewSet exposes Celery task status and guarded revocation. ResourceViewSet and FindingViewSet are read-only, RBAC-filtered, use keyset pagination helpers, and expose latest and metadata endpoints built from latest scans and summary tables. AttackPathsScanViewSet lists the latest scan per provider for the active graph sink and runs built-in/custom graph queries or schema inspection only when graph_data_ready is true.
The scan/task flow is orchestrated by api/…/tasks.py. Celery is configured in api/…/celery.py with Valkey broker settings from api/…/celery.py, django-db results, durable delivery defaults (task_acks_late, worker prefetch 1, worker-lost rejection), task time limits, task autodiscovery, and RLSTask.apply_async(), which creates/updates the tenant-visible api.models.Task row after Celery creates a TaskResult. Worker queues are fixed in api/docker-entrypoint.sh: celery,scans,scan-reports,deletion,backfill,overview,integrations,compliance,attack-paths-scans.
For manual scans, ScanViewSet.create() defers perform_scan_task publication with transaction.on_commit() so the worker cannot see an uncommitted Scan. perform_scan_task() runs tasks.jobs.scan.perform_prowler_scan(), reconciles mute rules, dispatches post-scan work, and then tries to dispatch the next queued scan for the same provider. perform_prowler_scan() in api/…/scan.py sets the scan executing, initializes the Prowler SDK provider from the API provider, streams SDK findings in bounded micro-batches, bulk upserts resources/tags/findings/mappings, computes deltas and failed counts, updates throttled progress, then marks the scan completed/failed and writes ResourceScanSummary rows. After a successful scan, _perform_scan_complete_tasks() queues compliance requirement creation, provider compliance score updates, scan summaries, daily severity/finding group/resource group/category aggregations, output/report generation, integration checks, ephemeral resource reset, and attack-path scanning when supported.
Scheduled scans are created by api/…/beat.py: schedule_provider_scan() creates a daily django_celery_beat.PeriodicTask, an initial scheduled Scan, a supported Attack Paths row, and immediately queues perform_scheduled_scan_task() with a short countdown. The scheduled task deduplicates by Celery task id, queues runs instead of overlapping another scan for the same provider, creates the next scheduled scan row, and also dispatches post-scan tasks when the Prowler scan completes. Orphan task recovery is documented in api/…/orphan-task-recovery.md; its Celery task is reconcile-orphan-tasks in api/…/tasks.py and the feature flags are in config.django.base.
Attack Paths uses both Postgres and graph storage. api/…/scan.py documents the lifecycle: resolve provider credentials from the Prowler scan, create a temporary Neo4j database, run Cartography ingestion, add Prowler finding nodes from Postgres findings, sync the provider subgraph into the tenant graph database or configured sink, then drop the temp DB and mark AttackPathsScan complete. The API query side in AttackPathsScanViewSet executes catalog or custom OpenCypher queries through api.attack_paths.views_helpers against the tenant graph database only after the scan row indicates graph data is ready.
Tests are split between Django app tests under api/src/backend/api/tests/ and api/src/backend/tasks/tests/, plus higher-level/performance tests under api/tests/. api/…/pytest.ini sets DJANGO_SETTINGS_MODULE=config.django.testing; api/…/testing.py disables routers, uses a single test Postgres database, sets a deterministic encryption key, switches JWT signing to HS256 for tests, and lowers password hashing cost.
Coupling
- If adding or renaming an API route in api/…/urls.py, also update the owning
ViewSetaction/schema annotations in api/…/views.py and serializers in api/…/serializers.py; DRF JSON:API query validation is strict, andScanViewSet._serve_compliance_artifact()explicitly keeps artifact format selection in the path because arbitrary query parameters would be rejected. - If changing task names, queues, or kwargs in api/…/tasks.py, update all producers in api/…/views.py, scheduled task creation in api/…/beat.py, Celery annotations in api/…/celery.py, worker queue names in api/docker-entrypoint.sh, and task visibility/revocation logic in
TaskViewSet/serializers. The API exposes task state throughapi.models.Tasklinked todjango_celery_results.TaskResult, so missingtenant_idkwargs also breaksRLSTaskrow creation. - If changing scan state semantics in api/…/models.py, check manual scan queuing in
ScanViewSet.create(), active/queued scan helpers in api/…/tasks.py, scheduled scan deduplication inperform_scheduled_scan_task(), latest-resource/finding selectors inScanQuerySet, and report actions that return 202 while scan/report tasks are executing. - If changing
Provider,Resource,Finding, or summary fields in api/…/models.py, checktasks.jobs.scan.perform_prowler_scan()and its micro-batch persistence code; resource/finding metadata endpoints inResourceViewSetandFindingViewSetread denormalized arrays andResourceScanSummary/ScanCategorySummary/ScanGroupSummaryrows rather than recomputing everything from raw findings. - If changing row-level security or database aliases in api/…/rls.py, api/…/db_utils.py, or api/…/db_router.py, verify
BaseRLSViewSet/BaseTenantViewsetin api/…/base_views.py, API key authentication in api/…/authentication.py, Celery decorators/tasks in api/…/tasks.py, and migrations. Migrations must run with--database adminbecauseMainRouter.allow_migrate()only allows the admin alias. - If changing findings partitioning in api/…/models.py, also update api/…/partitions.md, api/…/partitions.py, and migration workflow;
FindingandResourceFindingMappingusedjango-postgres-extrapartitioning, and the docs requirepgpartition --using adminfor managed partitions. - If changing report output paths or S3 configuration in api/…/export.py or report jobs, verify every
ScanViewSetreport downloader in api/…/views.py; the API assumesScan.output_locationis either a local glob-compatible path or ans3://<DJANGO_OUTPUT_S3_AWS_OUTPUT_BUCKET>/...key prefix. - If changing Attack Paths scan storage in
api/src/backend/tasks/jobs/attack_paths/*orapi/src/backend/api/attack_paths/*, verify theAttackPathsScanfields in api/…/models.py, the pre-created scan rows inScanViewSet.create()and tasks/beat.py, post-scan dispatch in_perform_scan_complete_tasks(), and query gating inAttackPathsScanViewSet.
Risks
- api/…/tasks.py intentionally sets
acks_late=Falseforscan-performandscan-perform-scheduledbecause redelivery can duplicate findings. If a worker dies during one of these scans, the broker drops the task and the scan may remain failed/incomplete rather than automatically rerunning; recovery behavior is deliberately limited as described in api/…/orphan-task-recovery.md. - api/…/views.py and api/…/export.py are tightly coupled through report filenames/directories. If generation writes a different directory or suffix without changing the downloader glob patterns, report endpoints return 404 even though the scan completed.
- api/…/db_utils.py replica failover only intercepts cursor
execute()for single safe SELECT statements and explicitly does not cover server-side cursor.iterator()fetches. New large read paths using.iterator()underrls_transaction(..., using=READ_REPLICA_ALIAS)can still fail mid-stream instead of falling back to primary.