A demonstration of using Open Policy Agent (OPA) as a sidecar with a Python Flask application for policy-driven authorization.
opa-python-sidecar/
├── app/
│ ├── __init__.py
│ ├── app.py # Flask application
│ └── opa_client.py # OPA client
├── policies/
│ ├── authz.rego # Authorization policies
│ └── authz_test.rego # Policy tests
├── tests/
│ └── integration/
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
└── README.md
-
Install Homebrew (if not already installed):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" -
Install Docker Desktop:
brew install --cask docker
-
Start Docker Desktop:
- Open Docker from your Applications folder
- Wait for Docker to fully start (whale icon in menu bar stops animating)
-
Verify installation:
docker --version docker compose version
docker compose up --buildThis starts:
- OPA server on port 8181
- Flask app on port 5001
Admin access (full access):
curl -X GET http://127.0.0.1:5001/api/resources/resource_1 \
-H "X-User-ID: admin_1" \
-H "X-User-Role: admin"User accessing own resource (allowed):
curl -X GET http://127.0.0.1:5001/api/resources/resource_1 \
-H "X-User-ID: user_123" \
-H "X-User-Role: user"User accessing another user's resource (denied):
curl -X GET http://127.0.0.1:5001/api/resources/resource_2 \
-H "X-User-ID: user_123" \
-H "X-User-Role: user"Manager accessing department resource (allowed):
curl -X GET http://127.0.0.1:5001/api/resources/resource_1 \
-H "X-User-ID: mgr_1" \
-H "X-User-Role: manager" \
-H "X-User-Department: engineering"Health check:
curl http://127.0.0.1:5001/healthdocker run --rm -v $(pwd)/policies:/policies openpolicyagent/opa:latest test /policies -vThe authorization policy (policies/authz.rego) implements:
- Default deny - All requests are denied by default
- Admin access - Admins can perform any action
- Owner access - Users can read/update their own resources
- Department access - Managers can read resources in their department
The application uses mock data for demonstration:
| Resource ID | Owner | Department |
|---|---|---|
| resource_1 | user_123 | engineering |
| resource_2 | user_456 | sales |
| resource_3 | user_123 | engineering |
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/resources/{id} | Get a resource |
| PUT | /api/resources/{id} | Update a resource |
| DELETE | /api/resources/{id} | Delete a resource |
| GET | /health | Health check |
-
Install dependencies:
pip install -r requirements.txt
-
Start OPA separately:
docker run -p 8181:8181 -v $(pwd)/policies:/policies openpolicyagent/opa:latest run --server /policies -
Run the Flask app:
cd app && python app.py