Convert web service from FastAPI to Django 6.1 #2
@@ -10,3 +10,7 @@ storage/
|
||||
__pycache__/
|
||||
|
||||
*.db
|
||||
|
||||
db.sqlite3
|
||||
privatestudio/settings/local.py
|
||||
static/
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
# Private Studio - Video Transcoding Web Service
|
||||
|
||||
A FastAPI-based video transcoding management service with S3-compatible file uploads, API key authentication, and per-user resource isolation.
|
||||
A Django video transcoding management service. It provides S3-compatible file storage, API key authentication, and studio-based access control.
|
||||
|
||||
## Features
|
||||
|
||||
- **S3-Compatible Interface**: Upload, download, delete, and list files using S3-compatible HTTP endpoints
|
||||
- **API Key Authentication**: Secure bearer token authentication with per-user isolation
|
||||
- **YAML-Based Transcode API**: Request transcode jobs and manage encoding profiles via YAML
|
||||
- **SQLite Database**: Lightweight file-based database with SQLAlchemy ORM
|
||||
- **User Management**: Create users and API keys via CLI
|
||||
- **Studios**: each studio owns one S3 bucket. Members of the studio's Django group can access it.
|
||||
- **S3-compatible interface**: upload, download, delete and list objects with bearer tokens or AWS v4 signatures (works with boto3).
|
||||
- **JSON API** ([Django Ninja](https://django-ninja.dev/)): manage API keys, temporary S3 credentials, transcode profiles and transcode jobs. Interactive docs are at `/api/docs`.
|
||||
- **Django admin** for managing users, groups, studios and jobs.
|
||||
|
||||
## Installation
|
||||
|
||||
Install the package with all dependencies:
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
Or install development dependencies:
|
||||
Requires Python 3.12+.
|
||||
|
||||
```bash
|
||||
pip install -e ".[dev]"
|
||||
@@ -26,329 +19,124 @@ pip install -e ".[dev]"
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Initialize Database
|
||||
|
||||
```bash
|
||||
ps-serve init
|
||||
python manage.py migrate
|
||||
python manage.py createsuperuser
|
||||
python manage.py create_studio demo --name "Demo Studio" --group demo-team --add-user <username>
|
||||
python manage.py create_key <username>
|
||||
python manage.py runserver
|
||||
```
|
||||
|
||||
This creates a `transcoding.db` file in the current directory.
|
||||
`create_key` prints the API key once. Keep it secret.
|
||||
|
||||
### 2. Create a User
|
||||
To grant someone access to a studio, add them to the studio's group, either in the admin (`/admin/`) or with `create_studio --add-user` when the studio is created.
|
||||
|
||||
```bash
|
||||
ps-serve create-user myuser
|
||||
```
|
||||
See [README_SERVE.md](README_SERVE.md) for the full command guide.
|
||||
|
||||
### 3. Create an API Key
|
||||
|
||||
```bash
|
||||
ps-serve create-key 1
|
||||
```
|
||||
|
||||
This outputs an API key that should be kept secret:
|
||||
## Project Layout
|
||||
|
||||
```
|
||||
API key created for user 1
|
||||
Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM
|
||||
Keep this key safe - you won't be able to see it again!
|
||||
manage.py
|
||||
privatestudio/
|
||||
settings/base.py # shared settings
|
||||
settings/dev.py # default (DJANGO_SETTINGS_MODULE=privatestudio.settings.dev)
|
||||
settings/production.py # env-driven production settings
|
||||
urls.py, wsgi.py, asgi.py
|
||||
studio/ # Django app: models, API routers, S3 views, management commands
|
||||
transcode.py # ps-transcode CLI (ffmpeg wrapper)
|
||||
```
|
||||
|
||||
### 4. Start the Server
|
||||
|
||||
```bash
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
The server will start at `http://localhost:8000`
|
||||
|
||||
## Configuration
|
||||
|
||||
Environment variables:
|
||||
Settings live in the `privatestudio.settings` package. Choose one with `DJANGO_SETTINGS_MODULE`:
|
||||
- `privatestudio.settings.dev` is the default. You can add overrides in an optional, git-ignored `privatestudio/settings/local.py`.
|
||||
- `privatestudio.settings.production` is configured from the environment variables below.
|
||||
|
||||
- `DATABASE_URL`: SQLite database path (default: `./transcoding.db`)
|
||||
- `STORAGE_PATH`: File storage directory (default: `./storage`)
|
||||
- `SERVER_HOST`: Server host address (default: `0.0.0.0`)
|
||||
- `SERVER_PORT`: Server port (default: `8000`)
|
||||
- `SQL_ECHO`: Enable SQL query logging (default: `false`)
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
export DATABASE_URL="sqlite:///./my_transcoding.db"
|
||||
export STORAGE_PATH="./media"
|
||||
ps-serve serve --host 127.0.0.1 --port 8080
|
||||
```
|
||||
| Variable | Used by | Description |
|
||||
|---|---|---|
|
||||
| `STORAGE_PATH` | all | File storage root (default `<repo>/storage`) |
|
||||
| `S3_CREDENTIAL_TTL_HOURS` | all | Lifetime of `/api/s3keys` credentials (default `1`) |
|
||||
| `DJANGO_TIME_ZONE` | all | Time zone (default `UTC`) |
|
||||
| `SECRET_KEY` | production | Django secret key |
|
||||
| `ALLOWED_HOSTS` | production | Comma-separated host names |
|
||||
| `DATABASE_URL` | production | Database URL parsed by `dj-database-url` (default SQLite `db.sqlite3`) |
|
||||
| `CORS_ALLOWED_ORIGINS` | production | Comma-separated allowed CORS origins |
|
||||
| `SECURE_PROXY_SSL_HEADER` | production | Set to trust `X-Forwarded-Proto` from a proxy |
|
||||
|
||||
## API Usage
|
||||
|
||||
### Authentication
|
||||
All endpoints except `/health` need `Authorization: Bearer <API_KEY>`. The S3 endpoints also accept AWS v4 signatures made with credentials from `/api/s3keys`.
|
||||
|
||||
All endpoints require an API key via Bearer token:
|
||||
### Account
|
||||
|
||||
| Method | Path | Description |
|
||||
|---|---|---|
|
||||
| GET | `/api/userinfo` | User id, username, and the studios (buckets) the user can access |
|
||||
| POST | `/api/keys` | Create an API key |
|
||||
| GET | `/api/keys` | List your API keys |
|
||||
| DELETE | `/api/keys/{id}` | Revoke an API key |
|
||||
| POST | `/api/s3keys` | Create temporary S3 access/secret keys |
|
||||
|
||||
### S3-compatible storage
|
||||
|
||||
| Method | Path | Description |
|
||||
|---|---|---|
|
||||
| PUT | `/s3/{bucket}/{key}` | Upload: either a raw body, or multipart with a `file` field |
|
||||
| GET | `/s3/{bucket}/{key}` | Download |
|
||||
| HEAD | `/s3/{bucket}/{key}` | Object size |
|
||||
| DELETE | `/s3/{bucket}/{key}` | Delete |
|
||||
| GET | `/s3/{bucket}?prefix=&delimiter=` | List objects |
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost:8000/api/keys
|
||||
curl -X PUT -H "Authorization: Bearer $KEY" --data-binary @video.mp4 \
|
||||
http://localhost:8000/s3/demo/videos/video.mp4
|
||||
```
|
||||
|
||||
### S3-Compatible File Operations
|
||||
With boto3 (AWS v4 signatures):
|
||||
|
||||
Upload a file:
|
||||
```python
|
||||
import boto3, requests
|
||||
from botocore.config import Config
|
||||
|
||||
```bash
|
||||
curl -X PUT \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-F "file=@video.mp4" \
|
||||
http://localhost:8000/s3/1/videos/video.mp4
|
||||
creds = requests.post("http://localhost:8000/api/s3keys",
|
||||
headers={"Authorization": f"Bearer {KEY}"}).json()
|
||||
s3 = boto3.client("s3", endpoint_url="http://localhost:8000/s3",
|
||||
aws_access_key_id=creds["access_key"],
|
||||
aws_secret_access_key=creds["secret_key"],
|
||||
region_name="us-east-1",
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}))
|
||||
s3.upload_file("video.mp4", "demo", "videos/video.mp4")
|
||||
```
|
||||
|
||||
Download a file:
|
||||
### Transcode profiles and jobs (per studio)
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1/videos/video.mp4 \
|
||||
-o video.mp4
|
||||
```
|
||||
| Method | Path | Body |
|
||||
|---|---|---|
|
||||
| POST | `/api/studios/{bucket}/profiles?name=<name>` | YAML profile definition (must contain `profiles:`) |
|
||||
| GET | `/api/studios/{bucket}/profiles` | |
|
||||
| GET | `/api/studios/{bucket}/profiles/{id}` | |
|
||||
| POST | `/api/studios/{bucket}/transcode` | YAML job request |
|
||||
| GET | `/api/studios/{bucket}/transcode?status=pending` | |
|
||||
| GET | `/api/studios/{bucket}/transcode/{id}` | |
|
||||
|
||||
List files:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1
|
||||
```
|
||||
|
||||
Delete a file:
|
||||
|
||||
```bash
|
||||
curl -X DELETE \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1/videos/video.mp4
|
||||
```
|
||||
|
||||
### Transcode Profile Management
|
||||
|
||||
Create a profile:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-H "Content-Type: application/yaml" \
|
||||
-d @profile.yaml \
|
||||
http://localhost:8000/api/profiles?name=my-profile
|
||||
```
|
||||
|
||||
Where `profile.yaml`:
|
||||
The asset in a job request can be given as its key, its filename or its ID. The profile can be a profile name or an inline definition:
|
||||
|
||||
```yaml
|
||||
profiles:
|
||||
hd:
|
||||
resolution: "1280x720"
|
||||
bitrate: "2500k"
|
||||
fps: 30
|
||||
sd:
|
||||
resolution: "854x480"
|
||||
bitrate: "1000k"
|
||||
fps: 30
|
||||
asset: videos/video.mp4
|
||||
profile: hd-profile
|
||||
```
|
||||
|
||||
List profiles:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/profiles
|
||||
curl -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/yaml" \
|
||||
--data-binary @job.yaml http://localhost:8000/api/studios/demo/transcode
|
||||
```
|
||||
|
||||
### Transcode Job Requests
|
||||
## Storage
|
||||
|
||||
Request a transcode job with a stored profile:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-H "Content-Type: application/yaml" \
|
||||
-d 'asset: video.mp4
|
||||
profile: my-profile' \
|
||||
http://localhost:8000/api/transcode
|
||||
```
|
||||
|
||||
Or with an inline profile:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-H "Content-Type: application/yaml" \
|
||||
-d 'asset: video.mp4
|
||||
profile:
|
||||
profiles:
|
||||
hd:
|
||||
resolution: "1280x720"
|
||||
bitrate: "2500k"' \
|
||||
http://localhost:8000/api/transcode
|
||||
```
|
||||
|
||||
Get job status:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/transcode/1
|
||||
```
|
||||
|
||||
List jobs:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/transcode
|
||||
```
|
||||
|
||||
List jobs by status:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/transcode?status=pending
|
||||
```
|
||||
|
||||
### API Key Management
|
||||
|
||||
Create an API key:
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/keys
|
||||
```
|
||||
|
||||
List keys:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/keys
|
||||
```
|
||||
|
||||
Revoke a key:
|
||||
|
||||
```bash
|
||||
curl -X DELETE \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/api/keys/KEY_ID
|
||||
```
|
||||
Files are stored under `STORAGE_PATH/<bucket_name>/<key>`. Keys that resolve outside the bucket directory are rejected.
|
||||
|
||||
## Testing
|
||||
|
||||
Run the test suite:
|
||||
|
||||
```bash
|
||||
pytest tests/test_web.py -v
|
||||
```
|
||||
|
||||
## Database Schema
|
||||
|
||||
### Users
|
||||
|
||||
- `id`: Primary key
|
||||
- `username`: Unique username
|
||||
- `created_at`: Creation timestamp
|
||||
|
||||
### API Keys
|
||||
|
||||
- `id`: Primary key
|
||||
- `key_hash`: SHA256 hash of the API key
|
||||
- `user_id`: Foreign key to users
|
||||
- `created_at`: Creation timestamp
|
||||
- `is_active`: Whether the key is active
|
||||
|
||||
### Uploaded Assets
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `filename`: Original filename
|
||||
- `size`: File size in bytes
|
||||
- `s3_path`: Path relative to storage root
|
||||
- `upload_timestamp`: Upload time
|
||||
|
||||
### Transcode Profiles
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `name`: Profile name
|
||||
- `profile_definition`: YAML definition as string
|
||||
- `created_at`: Creation timestamp
|
||||
|
||||
### Transcode Jobs
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `asset_id`: Foreign key to uploaded_assets
|
||||
- `profile_id`: Foreign key to transcode_profiles (nullable for inline profiles)
|
||||
- `status`: Job status (pending, in_progress, completed, failed)
|
||||
- `requested_at`: Request timestamp
|
||||
- `completed_at`: Completion timestamp (nullable)
|
||||
|
||||
### Packaging Jobs
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `transcode_job_id`: Foreign key to transcode_jobs
|
||||
- `status`: Job status (pending, in_progress, completed, failed)
|
||||
- `requested_at`: Request timestamp
|
||||
- `completed_at`: Completion timestamp (nullable)
|
||||
|
||||
### Transcoded Assets
|
||||
|
||||
- `id`: Primary key
|
||||
- `user_id`: Foreign key to users
|
||||
- `transcode_job_id`: Foreign key to transcode_jobs
|
||||
- `filename`: Output filename
|
||||
- `s3_path`: Path relative to storage root
|
||||
- `format`: Output format (e.g., "mp4", "audio")
|
||||
- `created_at`: Creation timestamp
|
||||
|
||||
## Architecture
|
||||
|
||||
### Authentication
|
||||
|
||||
API keys are stored as SHA256 hashes in the database and validated via FastAPI's HTTPBearer security scheme. Each authenticated endpoint receives the user context automatically.
|
||||
|
||||
### Per-User Isolation
|
||||
|
||||
All resources (assets, profiles, jobs) are scoped to the authenticated user. Users can only access their own resources, enforced at the database query level.
|
||||
|
||||
### File Storage
|
||||
|
||||
Files are stored on disk in user-specific directories under `STORAGE_PATH`:
|
||||
|
||||
```
|
||||
storage/
|
||||
├── 1/ (user 1)
|
||||
│ ├── video1.mp4
|
||||
│ └── video2.mp4
|
||||
└── 2/ (user 2)
|
||||
└── presentation.mp4
|
||||
```
|
||||
|
||||
Symlink traversal attacks are prevented by validating file paths.
|
||||
|
||||
## Development
|
||||
|
||||
### Enable Auto-Reload
|
||||
|
||||
```bash
|
||||
ps-serve serve --reload
|
||||
```
|
||||
|
||||
### View SQL Queries
|
||||
|
||||
```bash
|
||||
export SQL_ECHO=true
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
### Run Tests
|
||||
|
||||
```bash
|
||||
pytest tests/test_web.py -v
|
||||
```
|
||||
|
||||
With coverage:
|
||||
|
||||
```bash
|
||||
pytest tests/test_web.py --cov=privatestudio.web --cov-report=html
|
||||
pytest
|
||||
```
|
||||
|
||||
+44
-502
@@ -1,541 +1,83 @@
|
||||
# ps-serve Command Guide
|
||||
# Running and Managing Private Studio
|
||||
|
||||
A comprehensive guide to using the `ps-serve` command-line interface for managing the Private Studio video transcoding service.
|
||||
Private Studio is a standard Django project. All administration goes through `manage.py`, which uses `privatestudio.settings.dev` unless `DJANGO_SETTINGS_MODULE` is set.
|
||||
|
||||
## Overview
|
||||
|
||||
`ps-serve` is the command-line tool for Private Studio. It provides commands to:
|
||||
- Initialize the database
|
||||
- Create and manage user accounts
|
||||
- Generate and manage API keys
|
||||
- Start the web server
|
||||
|
||||
## Installation for Testing
|
||||
|
||||
### Quick Setup in a Virtual Environment
|
||||
|
||||
If you want to test the web service locally, here's the fastest way to get started:
|
||||
|
||||
#### 1. Clone the Repository
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yourusername/privatestudio.git
|
||||
cd privatestudio
|
||||
```
|
||||
|
||||
#### 2. Create a Virtual Environment
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
```
|
||||
|
||||
#### 3. Install in Development Mode
|
||||
|
||||
```bash
|
||||
pip install -e ".[dev]"
|
||||
```
|
||||
|
||||
This installs the package in "editable" mode, which means:
|
||||
- Changes to the code are immediately reflected
|
||||
- All dependencies (FastAPI, SQLAlchemy, etc.) are installed
|
||||
- Development tools (pytest, httpx) are also installed
|
||||
|
||||
#### 4. Verify Installation
|
||||
|
||||
```bash
|
||||
ps-serve --help
|
||||
```
|
||||
|
||||
You should see the help output showing all available commands.
|
||||
|
||||
### Virtual Environment Location
|
||||
|
||||
Keep your virtual environment separate from the source code:
|
||||
|
||||
```bash
|
||||
# Recommended structure
|
||||
~/projects/privatestudio/
|
||||
├── venv/ # Virtual environment (git-ignored)
|
||||
├── privatestudio/ # Source code
|
||||
├── tests/
|
||||
├── pyproject.toml
|
||||
└── README.md
|
||||
```
|
||||
|
||||
### Updating Your Installation
|
||||
|
||||
When you pull new changes from git:
|
||||
|
||||
```bash
|
||||
# Activate your virtual environment
|
||||
source venv/bin/activate
|
||||
|
||||
# Reinstall to pick up new dependencies
|
||||
pip install -e ".[dev]"
|
||||
|
||||
# Run tests to verify everything works
|
||||
pytest tests/test_web.py -v
|
||||
python manage.py migrate
|
||||
```
|
||||
|
||||
## Commands Reference
|
||||
## Access Model
|
||||
|
||||
### ps-serve init
|
||||
- **Users** are standard `django.contrib.auth` users.
|
||||
- **Studios** each own one unique `bucket_name` and point to one Django **Group**.
|
||||
- A user can access a studio (its S3 bucket, profiles and jobs) when they are in that studio's group. Superusers can access every studio.
|
||||
- **API keys** belong to a user and authenticate as that user. Only a SHA256 hash of each key is stored.
|
||||
|
||||
Initialize the database for a new installation.
|
||||
## Commands
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve init
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
- Creates a `transcoding.db` SQLite database file in the current directory
|
||||
- Creates all tables (users, api_keys, assets, jobs, profiles, etc.)
|
||||
- Safe to run multiple times (idempotent)
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
$ mkdir ~/transcoding-server && cd ~/transcoding-server
|
||||
$ ps-serve init
|
||||
Database initialized
|
||||
$ ls
|
||||
transcoding.db
|
||||
```
|
||||
|
||||
**Environment Variable:**
|
||||
- `DATABASE_URL`: Path to database (default: `./transcoding.db`)
|
||||
### Create users
|
||||
|
||||
```bash
|
||||
DATABASE_URL="sqlite:///var/lib/privatestudio/transcoding.db" ps-serve init
|
||||
python manage.py createsuperuser # admin user
|
||||
python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_user('alice')"
|
||||
```
|
||||
|
||||
---
|
||||
You can also create users in the admin at `/admin/`.
|
||||
|
||||
### ps-serve create-user
|
||||
|
||||
Create a new user account for API access.
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve create-user <username>
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
- `<username>`: The username for the new account (must be unique)
|
||||
|
||||
**What it does:**
|
||||
- Creates a new user in the database
|
||||
- Returns the user ID (needed for creating API keys)
|
||||
- Users can have multiple API keys
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
$ ps-serve create-user alice
|
||||
User created: alice (ID: 1)
|
||||
|
||||
$ ps-serve create-user bob
|
||||
User created: bob (ID: 2)
|
||||
```
|
||||
|
||||
**Error Handling:**
|
||||
```bash
|
||||
$ ps-serve create-user alice
|
||||
Error: User 'alice' already exists
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
The command prints the username and user ID, which you'll need for the next step.
|
||||
|
||||
---
|
||||
|
||||
### ps-serve create-key
|
||||
|
||||
Generate a new API key for a user.
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve create-key <user_name>
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
- `<user_name>`: The username of the user (obtained from `create-user` output)
|
||||
|
||||
**What it does:**
|
||||
- Generates a random 32-character API key
|
||||
- Stores the SHA256 hash in the database
|
||||
- Prints the plain key (save this somewhere safe!)
|
||||
- The key cannot be recovered later—users must create a new one if lost
|
||||
|
||||
**Example:**
|
||||
```bash
|
||||
$ ps-serve create-key alice
|
||||
API key created for user alice
|
||||
Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM
|
||||
Keep this key safe - you won't be able to see it again!
|
||||
```
|
||||
|
||||
**Security Notes:**
|
||||
- The key is only displayed once
|
||||
- Store it securely (environment variable, secret manager, encrypted file)
|
||||
- Never commit it to version control
|
||||
- Users can have multiple active keys (useful for key rotation)
|
||||
|
||||
**Example Workflow:**
|
||||
```bash
|
||||
# Create two keys for the same user (one for testing, one for production)
|
||||
$ ps-serve create-key alice
|
||||
Key: test_key_abc123...
|
||||
|
||||
$ ps-serve create-key alice
|
||||
Key: prod_key_xyz789...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### ps-serve serve
|
||||
|
||||
Start the FastAPI web server.
|
||||
|
||||
**Syntax:**
|
||||
```bash
|
||||
ps-serve serve [OPTIONS]
|
||||
```
|
||||
|
||||
**Options:**
|
||||
```
|
||||
--host HOST Server host address (default: 0.0.0.0)
|
||||
--port PORT Server port (default: 8000)
|
||||
--reload Enable auto-reload on code changes (for development)
|
||||
--log-level LEVEL Log level: debug, info, warning, error (default: info)
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
- Starts the FastAPI server
|
||||
- Initializes the database if it doesn't exist
|
||||
- Listens for HTTP requests
|
||||
- Logs all requests and errors
|
||||
|
||||
**Examples:**
|
||||
|
||||
**Start with defaults:**
|
||||
```bash
|
||||
$ ps-serve serve
|
||||
INFO: Application startup complete
|
||||
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
|
||||
```
|
||||
|
||||
**Development mode with auto-reload:**
|
||||
```bash
|
||||
ps-serve serve --reload
|
||||
```
|
||||
|
||||
Changes to Python files will automatically restart the server.
|
||||
|
||||
**Custom host and port:**
|
||||
```bash
|
||||
ps-serve serve --host 127.0.0.1 --port 5000
|
||||
```
|
||||
|
||||
Now the server is only accessible locally at `http://127.0.0.1:5000`
|
||||
|
||||
**Detailed logging:**
|
||||
```bash
|
||||
ps-serve serve --log-level debug
|
||||
```
|
||||
|
||||
**All options together:**
|
||||
```bash
|
||||
ps-serve serve --host localhost --port 8080 --reload --log-level debug
|
||||
```
|
||||
|
||||
**Environment Variables:**
|
||||
These can also be set via environment variables:
|
||||
- `SERVER_HOST`: Server host (default: `0.0.0.0`)
|
||||
- `SERVER_PORT`: Server port (default: `8000`)
|
||||
- `DATABASE_URL`: Database path (default: `./transcoding.db`)
|
||||
- `STORAGE_PATH`: File storage directory (default: `./storage`)
|
||||
- `SQL_ECHO`: Log all SQL queries (true/false)
|
||||
|
||||
Example:
|
||||
```bash
|
||||
export SERVER_HOST=localhost
|
||||
export SERVER_PORT=9000
|
||||
export STORAGE_PATH=/media/transcoding
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Complete Workflow
|
||||
|
||||
Here's a typical setup workflow from start to finish:
|
||||
|
||||
### 1. Initialize Database
|
||||
### create_studio
|
||||
|
||||
```bash
|
||||
mkdir ~/my-transcoding-server
|
||||
cd ~/my-transcoding-server
|
||||
ps-serve init
|
||||
python manage.py create_studio <bucket_name> --group <group> [--name "Display Name"] [--add-user USER ...]
|
||||
```
|
||||
|
||||
### 2. Create Users
|
||||
This creates the group if it doesn't exist, adds the given users to it, and creates the studio. Bucket names must be lowercase letters, digits and hyphens.
|
||||
|
||||
### create_key
|
||||
|
||||
```bash
|
||||
ps-serve create-user alice
|
||||
ps-serve create-user bob
|
||||
python manage.py create_key <username>
|
||||
```
|
||||
|
||||
### 3. Create API Keys
|
||||
This prints a new API key. The key is shown only once. Users can also create and revoke their own keys through `/api/keys`.
|
||||
|
||||
### Run the server
|
||||
|
||||
```bash
|
||||
ps-serve create-key alice # For alice
|
||||
# Save this key somewhere secure
|
||||
ps-serve create-key bob # For bob
|
||||
python manage.py runserver 0.0.0.0:8000
|
||||
```
|
||||
|
||||
### 4. Start the Server
|
||||
In production, set `DJANGO_SETTINGS_MODULE=privatestudio.settings.production` and serve `privatestudio.wsgi:application` or `privatestudio.asgi:application` with your WSGI/ASGI server of choice. See the configuration table in [README.md](README.md).
|
||||
|
||||
## Typical Workflow
|
||||
|
||||
```bash
|
||||
ps-serve serve
|
||||
python manage.py migrate
|
||||
python manage.py createsuperuser --username admin
|
||||
python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_user('alice')"
|
||||
python manage.py create_studio demo --name "Demo Studio" --group demo-team --add-user alice
|
||||
python manage.py create_key alice
|
||||
python manage.py runserver
|
||||
|
||||
curl -H "Authorization: Bearer $KEY" http://localhost:8000/api/userinfo
|
||||
curl -X PUT -H "Authorization: Bearer $KEY" --data-binary @video.mp4 http://localhost:8000/s3/demo/video.mp4
|
||||
curl -H "Authorization: Bearer $KEY" http://localhost:8000/s3/demo
|
||||
```
|
||||
|
||||
### 5. Use the API
|
||||
|
||||
In another terminal:
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
# Upload a video
|
||||
curl -X PUT \
|
||||
-H "Authorization: Bearer YOUR_API_KEY" \
|
||||
-F "file=@myvideo.mp4" \
|
||||
http://localhost:8000/s3/1/videos/myvideo.mp4
|
||||
|
||||
# List uploaded files
|
||||
curl -H "Authorization: Bearer YOUR_API_KEY" \
|
||||
http://localhost:8000/s3/1
|
||||
pytest # all tests
|
||||
pytest privatestudio/studio/tests/test_s3.py -k signature
|
||||
pytest --cov=privatestudio
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Command not found: ps-serve
|
||||
|
||||
**Problem:** `ps-serve: command not found`
|
||||
|
||||
**Solution:** Make sure you've activated the virtual environment and installed the package:
|
||||
|
||||
```bash
|
||||
source venv/bin/activate
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
### Database locked error
|
||||
|
||||
**Problem:** `sqlite3.OperationalError: database is locked`
|
||||
|
||||
**Solution:** SQLite doesn't handle concurrent writes well. For production:
|
||||
1. Stop any running servers
|
||||
2. Use PostgreSQL instead (change `DATABASE_URL`)
|
||||
3. Reduce concurrency
|
||||
|
||||
### Port already in use
|
||||
|
||||
**Problem:** `OSError: [Errno 48] Address already in use`
|
||||
|
||||
**Solution:** Use a different port:
|
||||
|
||||
```bash
|
||||
ps-serve serve --port 8001
|
||||
```
|
||||
|
||||
Or kill the existing process:
|
||||
|
||||
```bash
|
||||
# Find the process
|
||||
lsof -i :8000
|
||||
# Kill it
|
||||
kill -9 <PID>
|
||||
```
|
||||
|
||||
### API key not working
|
||||
|
||||
**Problem:** `401 Unauthorized: Invalid API key`
|
||||
|
||||
**Possible causes:**
|
||||
1. Wrong API key
|
||||
2. API key was revoked
|
||||
3. Key header is malformed (must be `Authorization: Bearer KEY`)
|
||||
|
||||
**Debug:**
|
||||
```bash
|
||||
# List all keys for a user
|
||||
curl -H "Authorization: Bearer YOUR_KEY" \
|
||||
http://localhost:8000/api/keys
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Running Tests
|
||||
|
||||
After making changes, run the test suite to ensure everything works:
|
||||
|
||||
```bash
|
||||
# Activate virtual environment
|
||||
source venv/bin/activate
|
||||
|
||||
# Run all tests
|
||||
pytest tests/test_web.py -v
|
||||
|
||||
# Run a specific test
|
||||
pytest tests/test_web.py::test_upload_file -v
|
||||
|
||||
# Run with coverage
|
||||
pytest tests/test_web.py --cov=privatestudio.web --cov-report=html
|
||||
```
|
||||
|
||||
Coverage report is generated in `htmlcov/index.html`
|
||||
|
||||
---
|
||||
|
||||
## Development Tips
|
||||
|
||||
### 1. Auto-reload During Development
|
||||
|
||||
```bash
|
||||
ps-serve serve --reload
|
||||
```
|
||||
|
||||
Every time you save a Python file, the server will restart automatically.
|
||||
|
||||
### 2. View SQL Queries
|
||||
|
||||
```bash
|
||||
export SQL_ECHO=true
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
This logs all database queries to stdout for debugging.
|
||||
|
||||
### 3. Use a Specific Database
|
||||
|
||||
```bash
|
||||
export DATABASE_URL="sqlite:///./test_db.db"
|
||||
ps-serve init
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
Useful for keeping multiple database instances (dev, test, prod).
|
||||
|
||||
### 4. Store Configuration in .env
|
||||
|
||||
Create a `.env` file:
|
||||
|
||||
```bash
|
||||
# .env
|
||||
DATABASE_URL=sqlite:///./transcoding.db
|
||||
STORAGE_PATH=./media
|
||||
SERVER_HOST=localhost
|
||||
SERVER_PORT=8000
|
||||
SQL_ECHO=false
|
||||
```
|
||||
|
||||
Then source it before running commands:
|
||||
|
||||
```bash
|
||||
source .env
|
||||
ps-serve serve
|
||||
```
|
||||
|
||||
Or use a tool like `python-dotenv`:
|
||||
|
||||
```bash
|
||||
pip install python-dotenv
|
||||
```
|
||||
|
||||
Then in your code or shell initialization.
|
||||
|
||||
---
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Protect API Keys**
|
||||
- Never commit keys to version control
|
||||
- Store in environment variables or secure vaults
|
||||
- Rotate keys regularly
|
||||
|
||||
2. **Database Security**
|
||||
- Use PostgreSQL for production (not SQLite)
|
||||
- Enable database backups
|
||||
- Run database on a separate server
|
||||
|
||||
3. **Network Security**
|
||||
- Use HTTPS in production (behind a reverse proxy like nginx)
|
||||
- Bind to localhost if only local access is needed
|
||||
- Implement rate limiting and authentication
|
||||
|
||||
4. **File Storage**
|
||||
- Keep storage directory outside the web root
|
||||
- Use a dedicated disk or object storage (S3, MinIO) for production
|
||||
- Implement backup strategy
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
After getting `ps-serve` running:
|
||||
|
||||
1. **Upload Your First Video**
|
||||
- See DEPLOYMENT.md for S3 API examples
|
||||
|
||||
2. **Create a Transcode Profile**
|
||||
- Define encoding profiles in YAML
|
||||
- Request transcode jobs
|
||||
|
||||
3. **Integrate with Your Application**
|
||||
- Use the REST API from your application
|
||||
- Handle job status polling
|
||||
|
||||
4. **Deploy to Production**
|
||||
- Use a real database (PostgreSQL)
|
||||
- Run behind nginx or similar proxy
|
||||
- Set up monitoring and backups
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
For more detailed information:
|
||||
|
||||
- **API Documentation**: Start the server and visit `http://localhost:8000/docs`
|
||||
- **Deployment Guide**: See `README.md`
|
||||
- **Source Code**: Check `privatestudio/web/` for implementation details
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference Cheat Sheet
|
||||
|
||||
```bash
|
||||
# Setup
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -e ".[dev]"
|
||||
|
||||
# First time
|
||||
ps-serve init
|
||||
ps-serve create-user myuser
|
||||
ps-serve create-key 1
|
||||
|
||||
# Development
|
||||
ps-serve serve --reload --log-level debug
|
||||
|
||||
# Testing
|
||||
pytest tests/test_web.py -v
|
||||
|
||||
# Production
|
||||
DATABASE_URL="postgresql://user:pass@localhost/psdb" \
|
||||
SERVER_HOST=0.0.0.0 \
|
||||
SERVER_PORT=8000 \
|
||||
ps-serve serve
|
||||
```
|
||||
- **401 Unauthorized**: the API key is wrong or revoked, or the S3 credentials have expired (by default they last 1 hour, set by `S3_CREDENTIAL_TTL_HOURS`).
|
||||
- **403 on a bucket**: the user isn't in the studio's group. Add them in the admin.
|
||||
- **404 on a bucket**: no studio has that `bucket_name`.
|
||||
|
||||
-149
@@ -1,149 +0,0 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts.
|
||||
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||
# format, relative to the token %(here)s which refers to the location of this
|
||||
# ini file
|
||||
script_location = %(here)s/privatestudio/migrations
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory. for multiple paths, the path separator
|
||||
# is defined by "path_separator" below.
|
||||
prepend_sys_path = .
|
||||
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the tzdata library which can be installed by adding
|
||||
# `alembic[tz]` to the pip requirements.
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to <script_location>/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "path_separator"
|
||||
# below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||
|
||||
# path_separator; This indicates what character is used to split lists of file
|
||||
# paths, including version_locations and prepend_sys_path within configparser
|
||||
# files such as alembic.ini.
|
||||
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||
# to provide os-dependent path splitting.
|
||||
#
|
||||
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||
# take place if path_separator is not present in alembic.ini. If this
|
||||
# option is omitted entirely, fallback logic is as follows:
|
||||
#
|
||||
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||
# behavior of splitting on spaces and/or commas.
|
||||
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||
# behavior of splitting on spaces, commas, or colons.
|
||||
#
|
||||
# Valid values for path_separator are:
|
||||
#
|
||||
# path_separator = :
|
||||
# path_separator = ;
|
||||
# path_separator = space
|
||||
# path_separator = newline
|
||||
#
|
||||
# Use os.pathsep. Default configuration used for new projects.
|
||||
path_separator = os
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# database URL. This is consumed by the user-maintained env.py script only.
|
||||
# other means of configuring database URLs may be customized within the env.py
|
||||
# file.
|
||||
sqlalchemy.url = sqlite:///./transcoding.db
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||
# hooks = ruff
|
||||
# ruff.type = module
|
||||
# ruff.module = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration. This is also consumed by the user-maintained
|
||||
# env.py script only.
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "privatestudio.settings.dev")
|
||||
|
||||
from django.core.management import execute_from_command_line
|
||||
|
||||
execute_from_command_line(sys.argv)
|
||||
@@ -0,0 +1,8 @@
|
||||
"""ASGI config for the privatestudio project."""
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "privatestudio.settings.dev")
|
||||
|
||||
application = get_asgi_application()
|
||||
@@ -1,86 +0,0 @@
|
||||
from logging.config import fileConfig
|
||||
import os
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# Import your models
|
||||
from privatestudio.web.models import Base
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# Use DATABASE_URL from environment or alembic.ini
|
||||
target_metadata = Base.metadata
|
||||
|
||||
def get_sqlalchemy_url():
|
||||
"""Get SQLAlchemy database URL from environment or config."""
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if url:
|
||||
return url
|
||||
return config.get_main_option("sqlalchemy.url")
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = get_sqlalchemy_url()
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
def run(connection):
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
connection = config.attributes.get("connection")
|
||||
if connection is not None:
|
||||
run(connection)
|
||||
return
|
||||
|
||||
configuration = config.get_section(config.config_ini_section, {})
|
||||
configuration["sqlalchemy.url"] = get_sqlalchemy_url()
|
||||
connectable = engine_from_config(
|
||||
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool
|
||||
)
|
||||
try:
|
||||
with connectable.connect() as connection:
|
||||
run(connection)
|
||||
finally:
|
||||
connectable.dispose()
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -1,29 +0,0 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import privatestudio.web.models
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -1,147 +0,0 @@
|
||||
"""Initial schema
|
||||
|
||||
Revision ID: 25cc5ed29873
|
||||
Revises:
|
||||
Create Date: 2026-11-22 16:57:27.821705
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import privatestudio.web.models
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '25cc5ed29873'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('bucket_name', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||
op.create_table('api_keys',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('key_hash', sa.Text(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('is_active', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_api_keys_key_hash'), 'api_keys', ['key_hash'], unique=True)
|
||||
op.create_table('s3_credentials',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('access_key', sa.Text(), nullable=False),
|
||||
sa.Column('secret_key', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('expires_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('authorized_key', sa.Text(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_s3_credentials_access_key'), 's3_credentials', ['access_key'], unique=True)
|
||||
op.create_index(op.f('ix_s3_credentials_user_id'), 's3_credentials', ['user_id'], unique=False)
|
||||
op.create_table('transcode_profiles',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.Text(), nullable=False),
|
||||
sa.Column('profile_definition', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_transcode_profiles_user_id'), 'transcode_profiles', ['user_id'], unique=False)
|
||||
op.create_table('uploaded_assets',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('filename', sa.Text(), nullable=False),
|
||||
sa.Column('size', sa.Integer(), nullable=False),
|
||||
sa.Column('s3_path', sa.Text(), nullable=False),
|
||||
sa.Column('upload_timestamp', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_uploaded_assets_user_id'), 'uploaded_assets', ['user_id'], unique=False)
|
||||
op.create_table('transcode_jobs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('asset_id', sa.Integer(), nullable=False),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=True),
|
||||
sa.Column('status', sa.Text(), nullable=False),
|
||||
sa.Column('requested_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('completed_at', privatestudio.web.models.TextDateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['asset_id'], ['uploaded_assets.id'], ),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['transcode_profiles.id'], ),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_transcode_jobs_user_id'), 'transcode_jobs', ['user_id'], unique=False)
|
||||
op.create_table('packaging_jobs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('transcode_job_id', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.Text(), nullable=False),
|
||||
sa.Column('requested_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.Column('completed_at', privatestudio.web.models.TextDateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['transcode_job_id'], ['transcode_jobs.id'], ),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_packaging_jobs_user_id'), 'packaging_jobs', ['user_id'], unique=False)
|
||||
op.create_table('transcoded_assets',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('transcode_job_id', sa.Integer(), nullable=False),
|
||||
sa.Column('filename', sa.Text(), nullable=False),
|
||||
sa.Column('s3_path', sa.Text(), nullable=False),
|
||||
sa.Column('format', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['transcode_job_id'], ['transcode_jobs.id'], ),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sqlite_strict=True
|
||||
)
|
||||
op.create_index(op.f('ix_transcoded_assets_user_id'), 'transcoded_assets', ['user_id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_transcoded_assets_user_id'), table_name='transcoded_assets')
|
||||
op.drop_table('transcoded_assets')
|
||||
op.drop_index(op.f('ix_packaging_jobs_user_id'), table_name='packaging_jobs')
|
||||
op.drop_table('packaging_jobs')
|
||||
op.drop_index(op.f('ix_transcode_jobs_user_id'), table_name='transcode_jobs')
|
||||
op.drop_table('transcode_jobs')
|
||||
op.drop_index(op.f('ix_uploaded_assets_user_id'), table_name='uploaded_assets')
|
||||
op.drop_table('uploaded_assets')
|
||||
op.drop_index(op.f('ix_transcode_profiles_user_id'), table_name='transcode_profiles')
|
||||
op.drop_table('transcode_profiles')
|
||||
op.drop_index(op.f('ix_s3_credentials_user_id'), table_name='s3_credentials')
|
||||
op.drop_index(op.f('ix_s3_credentials_access_key'), table_name='s3_credentials')
|
||||
op.drop_table('s3_credentials')
|
||||
op.drop_index(op.f('ix_api_keys_key_hash'), table_name='api_keys')
|
||||
op.drop_table('api_keys')
|
||||
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||
op.drop_table('users')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
Base Django settings for the privatestudio project.
|
||||
|
||||
Environment specific settings live in dev.py and production.py.
|
||||
"""
|
||||
import os
|
||||
|
||||
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
BASE_DIR = os.path.dirname(PROJECT_DIR)
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
"privatestudio.studio.app.StudioConfig",
|
||||
"corsheaders",
|
||||
"ninja",
|
||||
"django.contrib.admin",
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
"django.contrib.sessions",
|
||||
"django.contrib.messages",
|
||||
"django.contrib.staticfiles",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
"corsheaders.middleware.CorsMiddleware",
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"django.middleware.common.CommonMiddleware",
|
||||
"django.middleware.csrf.CsrfViewMiddleware",
|
||||
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
||||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = "privatestudio.urls"
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [
|
||||
os.path.join(PROJECT_DIR, "templates"),
|
||||
],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
"context_processors": [
|
||||
"django.template.context_processors.debug",
|
||||
"django.template.context_processors.request",
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = "privatestudio.wsgi.application"
|
||||
ASGI_APPLICATION = "privatestudio.asgi.application"
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
},
|
||||
},
|
||||
"loggers": {
|
||||
"privatestudio": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# Database
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.sqlite3",
|
||||
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
|
||||
}
|
||||
}
|
||||
|
||||
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
|
||||
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
|
||||
LANGUAGE_CODE = "en-us"
|
||||
TIME_ZONE = os.environ.get("DJANGO_TIME_ZONE", "UTC")
|
||||
USE_I18N = True
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files
|
||||
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, "static")
|
||||
STATIC_URL = "/static/"
|
||||
|
||||
|
||||
# Uploads: S3 PUT requests read the full raw request body (video files), so
|
||||
# don't cap the in-memory body size.
|
||||
DATA_UPLOAD_MAX_MEMORY_SIZE = None
|
||||
|
||||
|
||||
# Private Studio configuration
|
||||
|
||||
PRIVATESTUDIO_STORAGE_PATH = os.environ.get("STORAGE_PATH", os.path.join(BASE_DIR, "storage"))
|
||||
PRIVATESTUDIO_S3_CREDENTIAL_TTL_HOURS = int(os.environ.get("S3_CREDENTIAL_TTL_HOURS", "1"))
|
||||
@@ -0,0 +1,17 @@
|
||||
from .base import * # noqa: F401,F403
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = "django-insecure-privatestudio-dev-key-change-me"
|
||||
|
||||
# SECURITY WARNING: define the correct hosts in production!
|
||||
ALLOWED_HOSTS = ["*"]
|
||||
|
||||
CORS_ALLOW_ALL_ORIGINS = True
|
||||
|
||||
try:
|
||||
from .local import * # noqa: F401,F403
|
||||
except ImportError:
|
||||
pass
|
||||
@@ -0,0 +1,51 @@
|
||||
import os
|
||||
|
||||
import dj_database_url
|
||||
|
||||
from .base import * # noqa: F401,F403
|
||||
|
||||
DEBUG = False
|
||||
|
||||
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "*").split(",")
|
||||
|
||||
SECRET_KEY = os.environ.get("SECRET_KEY", "This isn't a good secret key default value, you should set one in the environment")
|
||||
|
||||
if os.environ.get("DATABASE_URL"):
|
||||
DATABASES = {
|
||||
"default": dj_database_url.config(),
|
||||
}
|
||||
|
||||
CORS_ALLOWED_ORIGINS = [o for o in os.environ.get("CORS_ALLOWED_ORIGINS", "").split(",") if o]
|
||||
|
||||
CSRF_TRUSTED_ORIGINS = [f"https://{h}" for h in ALLOWED_HOSTS if h != "*"]
|
||||
|
||||
if os.environ.get("SECURE_PROXY_SSL_HEADER"):
|
||||
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
||||
|
||||
LOGGING = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"handlers": {
|
||||
"console": {
|
||||
"class": "logging.StreamHandler",
|
||||
"level": "INFO",
|
||||
},
|
||||
},
|
||||
"loggers": {
|
||||
"root": {
|
||||
"handlers": ["console"],
|
||||
"level": "WARNING",
|
||||
"propagate": True,
|
||||
},
|
||||
"privatestudio": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
from local_settings import * # noqa: F401,F403
|
||||
except ImportError:
|
||||
pass
|
||||
@@ -0,0 +1,52 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from privatestudio.studio import models
|
||||
|
||||
|
||||
@admin.register(models.Studio)
|
||||
class StudioAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "bucket_name", "group", "created_at")
|
||||
search_fields = ("name", "bucket_name")
|
||||
|
||||
|
||||
@admin.register(models.APIKey)
|
||||
class APIKeyAdmin(admin.ModelAdmin):
|
||||
list_display = ("id", "user", "created_at", "is_active")
|
||||
list_filter = ("is_active",)
|
||||
readonly_fields = ("key_hash",)
|
||||
|
||||
|
||||
@admin.register(models.S3Credential)
|
||||
class S3CredentialAdmin(admin.ModelAdmin):
|
||||
list_display = ("access_key", "user", "created_at", "expires_at")
|
||||
exclude = ("secret_key",)
|
||||
|
||||
|
||||
@admin.register(models.UploadedAsset)
|
||||
class UploadedAssetAdmin(admin.ModelAdmin):
|
||||
list_display = ("s3_path", "studio", "size", "uploaded_by", "upload_timestamp")
|
||||
list_filter = ("studio",)
|
||||
|
||||
|
||||
@admin.register(models.TranscodeProfile)
|
||||
class TranscodeProfileAdmin(admin.ModelAdmin):
|
||||
list_display = ("name", "studio", "created_by", "created_at")
|
||||
list_filter = ("studio",)
|
||||
|
||||
|
||||
@admin.register(models.TranscodeJob)
|
||||
class TranscodeJobAdmin(admin.ModelAdmin):
|
||||
list_display = ("id", "studio", "asset", "profile", "status", "requested_at", "completed_at")
|
||||
list_filter = ("studio", "status")
|
||||
|
||||
|
||||
@admin.register(models.PackagingJob)
|
||||
class PackagingJobAdmin(admin.ModelAdmin):
|
||||
list_display = ("id", "studio", "transcode_job", "status", "requested_at", "completed_at")
|
||||
list_filter = ("studio", "status")
|
||||
|
||||
|
||||
@admin.register(models.TranscodedAsset)
|
||||
class TranscodedAssetAdmin(admin.ModelAdmin):
|
||||
list_display = ("s3_path", "studio", "transcode_job", "format", "created_at")
|
||||
list_filter = ("studio", "format")
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Django Ninja API wiring."""
|
||||
from ninja import NinjaAPI
|
||||
|
||||
from privatestudio.studio.auth import ApiKeyAuth
|
||||
from privatestudio.studio.routers import keys, profiles, s3_keys, transcode, userinfo
|
||||
|
||||
api = NinjaAPI(
|
||||
title="Private Studio",
|
||||
description="Video transcoding web service with S3-compatible interface",
|
||||
version="0.1.0",
|
||||
auth=ApiKeyAuth(),
|
||||
urls_namespace="api",
|
||||
)
|
||||
|
||||
|
||||
@api.exception_handler(ValueError)
|
||||
def value_error_handler(request, exc):
|
||||
return api.create_response(request, {"detail": str(exc)}, status=400)
|
||||
|
||||
|
||||
api.add_router("", keys.router, tags=["Keys"])
|
||||
api.add_router("", s3_keys.router, tags=["S3 Keys"])
|
||||
api.add_router("", userinfo.router, tags=["UserInfo"])
|
||||
api.add_router("", profiles.router, tags=["Profiles"])
|
||||
api.add_router("", transcode.router, tags=["Transcode"])
|
||||
@@ -0,0 +1,8 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class StudioConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "privatestudio.studio"
|
||||
label = "studio"
|
||||
verbose_name = "Private Studio"
|
||||
@@ -0,0 +1,122 @@
|
||||
"""API key authentication helpers."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import secrets
|
||||
from typing import Optional
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from ninja.security import HttpBearer
|
||||
|
||||
from privatestudio.studio.models import APIKey
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def hash_api_key(key: str) -> str:
|
||||
"""Hash an API key using SHA256."""
|
||||
return hashlib.sha256(key.encode()).hexdigest()
|
||||
|
||||
|
||||
def verify_api_key(plain_key: str, hashed_key: str) -> bool:
|
||||
"""Verify a plain API key against its hash."""
|
||||
return hmac.compare_digest(hash_api_key(plain_key), hashed_key)
|
||||
|
||||
|
||||
def generate_api_key() -> str:
|
||||
"""Generate a random API key."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def create_api_key(user) -> tuple[str, APIKey]:
|
||||
"""
|
||||
Create a new API key for a user.
|
||||
|
||||
Returns (plain_key, api_key_record). The plain key is only returned here;
|
||||
only its hash is stored.
|
||||
"""
|
||||
plain_key = generate_api_key()
|
||||
api_key = APIKey.objects.create(user=user, key_hash=hash_api_key(plain_key), is_active=True)
|
||||
return plain_key, api_key
|
||||
|
||||
|
||||
def revoke_api_key(api_key: APIKey) -> None:
|
||||
"""Revoke an API key by marking it inactive."""
|
||||
api_key.is_active = False
|
||||
api_key.save(update_fields=["is_active"])
|
||||
|
||||
|
||||
def user_for_api_key(token: str):
|
||||
"""Return the active user owning ``token`` or None."""
|
||||
if not token:
|
||||
return None
|
||||
api_key = (
|
||||
APIKey.objects.select_related("user")
|
||||
.filter(key_hash=hash_api_key(token), is_active=True)
|
||||
.first()
|
||||
)
|
||||
if api_key is None or not api_key.user.is_active:
|
||||
return None
|
||||
return api_key.user
|
||||
|
||||
|
||||
class ApiKeyAuth(HttpBearer):
|
||||
"""Django Ninja bearer token authentication backed by APIKey."""
|
||||
|
||||
def authenticate(self, request, token):
|
||||
user = user_for_api_key(token)
|
||||
if user is not None:
|
||||
request.user = user
|
||||
return user
|
||||
|
||||
|
||||
def _bearer_token(request) -> Optional[str]:
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
scheme, _, token = auth_header.partition(" ")
|
||||
if scheme.lower() != "bearer":
|
||||
return None
|
||||
return token.strip() or None
|
||||
|
||||
|
||||
def is_s3_v4_request(request) -> bool:
|
||||
return request.headers.get("Authorization", "").startswith("AWS4-HMAC-SHA256")
|
||||
|
||||
|
||||
def authenticate_s3_request(request):
|
||||
"""
|
||||
Hybrid auth for S3 endpoints: AWS v4 signatures first, then bearer tokens.
|
||||
|
||||
Returns the authenticated user or None.
|
||||
"""
|
||||
from privatestudio.studio.s3_credentials import get_s3_credential, verify_aws_v4_signature
|
||||
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
|
||||
if auth_header.startswith("AWS4-HMAC-SHA256"):
|
||||
try:
|
||||
cred_part = auth_header.split("Credential=")[1].split(",")[0]
|
||||
access_key = cred_part.split("/")[0]
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
credential = get_s3_credential(access_key)
|
||||
if credential is None:
|
||||
return None
|
||||
|
||||
headers = dict(request.headers)
|
||||
headers.setdefault("Host", request.get_host())
|
||||
|
||||
if verify_aws_v4_signature(
|
||||
auth_header,
|
||||
request.method,
|
||||
request.path,
|
||||
request.META.get("QUERY_STRING", ""),
|
||||
headers,
|
||||
request.body,
|
||||
credential.secret_key,
|
||||
):
|
||||
user = get_user_model().objects.filter(pk=credential.user_id, is_active=True).first()
|
||||
return user
|
||||
return None
|
||||
|
||||
return user_for_api_key(_bearer_token(request))
|
||||
@@ -0,0 +1,23 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Create an API key for a user. The key is printed once and cannot be recovered."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("username", help="Username to create the key for")
|
||||
|
||||
def handle(self, *args, **options):
|
||||
User = get_user_model()
|
||||
try:
|
||||
user = User.objects.get_by_natural_key(options["username"])
|
||||
except User.DoesNotExist:
|
||||
raise CommandError(f"User '{options['username']}' not found")
|
||||
|
||||
plain_key, api_key = create_api_key(user)
|
||||
self.stdout.write(self.style.SUCCESS(f"API key {api_key.id} created for user {user.get_username()}"))
|
||||
self.stdout.write(f"Key: {plain_key}")
|
||||
self.stdout.write("Keep this key safe - you won't be able to see it again!")
|
||||
@@ -0,0 +1,42 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Group
|
||||
from django.core.management.base import BaseCommand, CommandError
|
||||
from django.utils.text import slugify
|
||||
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Create a studio (S3 bucket) whose access is granted by membership in a group."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("bucket_name", help="Unique bucket name for the studio")
|
||||
parser.add_argument("--name", help="Display name (defaults to the bucket name)")
|
||||
parser.add_argument("--group", required=True, help="Group granting access (created if missing)")
|
||||
parser.add_argument("--add-user", action="append", default=[], metavar="USERNAME",
|
||||
help="Add a user to the group (may be repeated)")
|
||||
|
||||
def handle(self, *args, **options):
|
||||
bucket_name = options["bucket_name"]
|
||||
if slugify(bucket_name) != bucket_name:
|
||||
raise CommandError(f"Invalid bucket name '{bucket_name}': use lowercase letters, digits and hyphens")
|
||||
if Studio.objects.filter(bucket_name=bucket_name).exists():
|
||||
raise CommandError(f"Studio with bucket '{bucket_name}' already exists")
|
||||
|
||||
User = get_user_model()
|
||||
users = []
|
||||
for username in options["add_user"]:
|
||||
try:
|
||||
users.append(User.objects.get_by_natural_key(username))
|
||||
except User.DoesNotExist:
|
||||
raise CommandError(f"User '{username}' not found")
|
||||
|
||||
group, created = Group.objects.get_or_create(name=options["group"])
|
||||
if created:
|
||||
self.stdout.write(f"Created group '{group.name}'")
|
||||
for user in users:
|
||||
user.groups.add(group)
|
||||
self.stdout.write(f"Added {user.get_username()} to group '{group.name}'")
|
||||
|
||||
studio = Studio.objects.create(name=options["name"] or bucket_name, bucket_name=bucket_name, group=group)
|
||||
self.stdout.write(self.style.SUCCESS(f"Studio created: {studio}"))
|
||||
@@ -0,0 +1,131 @@
|
||||
# Generated by Django 6.1.3 on 2026-11-29 22:51
|
||||
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('auth', '0012_alter_user_first_name_max_length'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='APIKey',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('key_hash', models.CharField(max_length=64, unique=True)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='api_keys', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='S3Credential',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('access_key', models.CharField(max_length=64, unique=True)),
|
||||
('secret_key', models.CharField(max_length=128)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('expires_at', models.DateTimeField()),
|
||||
('authorized_key', models.TextField(blank=True, null=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='s3_credentials', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Studio',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255)),
|
||||
('bucket_name', models.SlugField(max_length=63, unique=True)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('group', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='studios', to='auth.group')),
|
||||
],
|
||||
options={
|
||||
'ordering': ['bucket_name'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TranscodeJob',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('profile_definition', models.TextField(blank=True, default='')),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20)),
|
||||
('requested_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('completed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('requested_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_jobs', to=settings.AUTH_USER_MODEL)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcode_jobs', to='studio.studio')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TranscodedAsset',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('filename', models.TextField()),
|
||||
('s3_path', models.TextField()),
|
||||
('format', models.CharField(max_length=32)),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcoded_assets', to='studio.studio')),
|
||||
('transcode_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcoded_assets', to='studio.transcodejob')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='PackagingJob',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('in_progress', 'In progress'), ('completed', 'Completed'), ('failed', 'Failed')], default='pending', max_length=20)),
|
||||
('requested_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('completed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('requested_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='packaging_jobs', to=settings.AUTH_USER_MODEL)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='packaging_jobs', to='studio.studio')),
|
||||
('transcode_job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='packaging_jobs', to='studio.transcodejob')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TranscodeProfile',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255)),
|
||||
('profile_definition', models.TextField()),
|
||||
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_profiles', to=settings.AUTH_USER_MODEL)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcode_profiles', to='studio.studio')),
|
||||
],
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='transcodejob',
|
||||
name='profile',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='transcode_jobs', to='studio.transcodeprofile'),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UploadedAsset',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('filename', models.TextField()),
|
||||
('size', models.BigIntegerField()),
|
||||
('s3_path', models.TextField()),
|
||||
('upload_timestamp', models.DateTimeField(default=django.utils.timezone.now)),
|
||||
('studio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='uploaded_assets', to='studio.studio')),
|
||||
('uploaded_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='uploaded_assets', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='transcodejob',
|
||||
name='asset',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transcode_jobs', to='studio.uploadedasset'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='transcodeprofile',
|
||||
constraint=models.UniqueConstraint(fields=('studio', 'name'), name='unique_profile_name_per_studio'),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='uploadedasset',
|
||||
constraint=models.UniqueConstraint(fields=('studio', 's3_path'), name='unique_asset_path_per_studio'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Django models for the video transcoding service."""
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import Group
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
class JobStatus(models.TextChoices):
|
||||
PENDING = "pending", "Pending"
|
||||
IN_PROGRESS = "in_progress", "In progress"
|
||||
COMPLETED = "completed", "Completed"
|
||||
FAILED = "failed", "Failed"
|
||||
|
||||
|
||||
class StudioQuerySet(models.QuerySet):
|
||||
def for_user(self, user):
|
||||
"""Studios the given user may access through group membership."""
|
||||
if user.is_superuser:
|
||||
return self.all()
|
||||
return self.filter(group__user=user).distinct()
|
||||
|
||||
|
||||
class Studio(models.Model):
|
||||
"""A studio owns an S3 bucket. Members of ``group`` may access it."""
|
||||
name = models.CharField(max_length=255)
|
||||
bucket_name = models.SlugField(max_length=63, unique=True)
|
||||
group = models.ForeignKey(Group, on_delete=models.PROTECT, related_name="studios")
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
objects = StudioQuerySet.as_manager()
|
||||
|
||||
class Meta:
|
||||
ordering = ["bucket_name"]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.name} ({self.bucket_name})"
|
||||
|
||||
def user_has_access(self, user) -> bool:
|
||||
if not user or not user.is_active:
|
||||
return False
|
||||
if user.is_superuser:
|
||||
return True
|
||||
return user.groups.filter(pk=self.group_id).exists()
|
||||
|
||||
|
||||
class APIKey(models.Model):
|
||||
"""API key for bearer token authentication. Only the hash is stored."""
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="api_keys")
|
||||
key_hash = models.CharField(max_length=64, unique=True)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
is_active = models.BooleanField(default=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"API key {self.pk} for {self.user}"
|
||||
|
||||
|
||||
class S3Credential(models.Model):
|
||||
"""Temporary AWS v4 signature credentials for S3 access."""
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="s3_credentials")
|
||||
access_key = models.CharField(max_length=64, unique=True)
|
||||
secret_key = models.CharField(max_length=128)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
expires_at = models.DateTimeField()
|
||||
authorized_key = models.TextField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return self.access_key
|
||||
|
||||
@property
|
||||
def is_expired(self) -> bool:
|
||||
return timezone.now() >= self.expires_at
|
||||
|
||||
|
||||
class UploadedAsset(models.Model):
|
||||
"""Uploaded video file stored in a studio's bucket."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="uploaded_assets")
|
||||
uploaded_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="uploaded_assets",
|
||||
)
|
||||
filename = models.TextField()
|
||||
size = models.BigIntegerField()
|
||||
s3_path = models.TextField()
|
||||
upload_timestamp = models.DateTimeField(default=timezone.now)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["studio", "s3_path"], name="unique_asset_path_per_studio"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.studio.bucket_name}/{self.s3_path}"
|
||||
|
||||
|
||||
class TranscodeProfile(models.Model):
|
||||
"""Named encoding profile (YAML definition) belonging to a studio."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcode_profiles")
|
||||
created_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_profiles",
|
||||
)
|
||||
name = models.CharField(max_length=255)
|
||||
profile_definition = models.TextField()
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["studio", "name"], name="unique_profile_name_per_studio"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
class TranscodeJob(models.Model):
|
||||
"""Requested transcode operation."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcode_jobs")
|
||||
requested_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_jobs",
|
||||
)
|
||||
asset = models.ForeignKey(UploadedAsset, on_delete=models.CASCADE, related_name="transcode_jobs")
|
||||
profile = models.ForeignKey(
|
||||
TranscodeProfile, on_delete=models.SET_NULL, null=True, blank=True, related_name="transcode_jobs",
|
||||
)
|
||||
# Inline profile definitions (or a snapshot of the named profile) used for this job.
|
||||
profile_definition = models.TextField(blank=True, default="")
|
||||
status = models.CharField(max_length=20, choices=JobStatus.choices, default=JobStatus.PENDING)
|
||||
requested_at = models.DateTimeField(default=timezone.now)
|
||||
completed_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"Transcode job {self.pk} ({self.status})"
|
||||
|
||||
|
||||
class PackagingJob(models.Model):
|
||||
"""Requested packaging operation."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="packaging_jobs")
|
||||
requested_by = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="packaging_jobs",
|
||||
)
|
||||
transcode_job = models.ForeignKey(TranscodeJob, on_delete=models.CASCADE, related_name="packaging_jobs")
|
||||
status = models.CharField(max_length=20, choices=JobStatus.choices, default=JobStatus.PENDING)
|
||||
requested_at = models.DateTimeField(default=timezone.now)
|
||||
completed_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"Packaging job {self.pk} ({self.status})"
|
||||
|
||||
|
||||
class TranscodedAsset(models.Model):
|
||||
"""Output file from a transcode job."""
|
||||
studio = models.ForeignKey(Studio, on_delete=models.CASCADE, related_name="transcoded_assets")
|
||||
transcode_job = models.ForeignKey(TranscodeJob, on_delete=models.CASCADE, related_name="transcoded_assets")
|
||||
filename = models.TextField()
|
||||
s3_path = models.TextField()
|
||||
format = models.CharField(max_length=32) # e.g. "mp4", "audio"
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.studio.bucket_name}/{self.s3_path}"
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Shared helpers for API routers."""
|
||||
import yaml
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
|
||||
def get_studio_for_user(user, bucket: str) -> Studio:
|
||||
"""Resolve a bucket name to a Studio the user may access (404/403 otherwise)."""
|
||||
studio = Studio.objects.filter(bucket_name=bucket).first()
|
||||
if studio is None:
|
||||
raise HttpError(404, f"Studio '{bucket}' not found")
|
||||
if not studio.user_has_access(user):
|
||||
raise HttpError(403, f"No access to studio '{bucket}'")
|
||||
return studio
|
||||
|
||||
|
||||
def parse_yaml_body(request) -> dict:
|
||||
"""Parse the raw request body as a YAML mapping (400 on failure)."""
|
||||
try:
|
||||
data = yaml.safe_load(request.body.decode("utf-8") or "")
|
||||
except (yaml.YAMLError, UnicodeDecodeError) as e:
|
||||
raise HttpError(400, f"Invalid YAML: {e}")
|
||||
if not isinstance(data, dict):
|
||||
raise HttpError(400, "Request body must be a YAML mapping")
|
||||
return data
|
||||
@@ -0,0 +1,51 @@
|
||||
"""API key management endpoints."""
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.auth import create_api_key, revoke_api_key
|
||||
from privatestudio.studio.models import APIKey
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class APIKeyCreateResponse(Schema):
|
||||
id: int
|
||||
key: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class APIKeyListItem(Schema):
|
||||
id: int
|
||||
created_at: str
|
||||
is_active: bool
|
||||
|
||||
|
||||
class MessageResponse(Schema):
|
||||
message: str
|
||||
|
||||
|
||||
@router.post("/keys", response=APIKeyCreateResponse)
|
||||
def create_api_key_endpoint(request):
|
||||
"""Create a new API key for the authenticated user."""
|
||||
plain_key, api_key = create_api_key(request.auth)
|
||||
return {"id": api_key.id, "key": plain_key, "created_at": api_key.created_at.isoformat()}
|
||||
|
||||
|
||||
@router.get("/keys", response=list[APIKeyListItem])
|
||||
def list_api_keys(request):
|
||||
"""List all API keys for the authenticated user."""
|
||||
return [
|
||||
{"id": key.id, "created_at": key.created_at.isoformat(), "is_active": key.is_active}
|
||||
for key in APIKey.objects.filter(user=request.auth).order_by("id")
|
||||
]
|
||||
|
||||
|
||||
@router.delete("/keys/{key_id}", response=MessageResponse)
|
||||
def revoke_api_key_endpoint(request, key_id: int):
|
||||
"""Revoke an API key (mark it as inactive)."""
|
||||
api_key = get_object_or_404(APIKey, pk=key_id)
|
||||
if api_key.user_id != request.auth.id:
|
||||
raise HttpError(403, "Cannot revoke someone else's API key")
|
||||
revoke_api_key(api_key)
|
||||
return {"message": "API key revoked"}
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Transcode profile management endpoints (scoped to a studio)."""
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.models import TranscodeProfile
|
||||
from privatestudio.studio.routers.common import get_studio_for_user, parse_yaml_body
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class ProfileResponse(Schema):
|
||||
id: int
|
||||
name: str
|
||||
profile_definition: str
|
||||
created_at: str
|
||||
|
||||
|
||||
def _profile_response(profile: TranscodeProfile) -> dict:
|
||||
return {
|
||||
"id": profile.id,
|
||||
"name": profile.name,
|
||||
"profile_definition": profile.profile_definition,
|
||||
"created_at": profile.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/studios/{bucket}/profiles", response=ProfileResponse)
|
||||
def create_profile(request, bucket: str, name: str):
|
||||
"""
|
||||
Create a new transcode profile.
|
||||
|
||||
The request body must contain the YAML profile definition.
|
||||
"""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
profile_data = parse_yaml_body(request)
|
||||
if "profiles" not in profile_data:
|
||||
raise HttpError(400, "Profile definition must contain a 'profiles' section")
|
||||
|
||||
if TranscodeProfile.objects.filter(studio=studio, name=name).exists():
|
||||
raise HttpError(409, f"Profile '{name}' already exists")
|
||||
|
||||
profile = TranscodeProfile.objects.create(
|
||||
studio=studio,
|
||||
created_by=request.auth,
|
||||
name=name,
|
||||
profile_definition=request.body.decode("utf-8"),
|
||||
)
|
||||
return _profile_response(profile)
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/profiles", response=list[ProfileResponse])
|
||||
def list_profiles(request, bucket: str):
|
||||
"""List all transcode profiles for the studio."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
return [_profile_response(p) for p in studio.transcode_profiles.order_by("id")]
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/profiles/{profile_id}", response=ProfileResponse)
|
||||
def get_profile(request, bucket: str, profile_id: int):
|
||||
"""Get a specific transcode profile."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
return _profile_response(get_object_or_404(TranscodeProfile, pk=profile_id, studio=studio))
|
||||
@@ -0,0 +1,27 @@
|
||||
"""S3 credential generation endpoint."""
|
||||
from ninja import Router, Schema
|
||||
|
||||
from privatestudio.studio.s3_credentials import create_s3_credential
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class S3KeyResponse(Schema):
|
||||
access_key: str
|
||||
secret_key: str
|
||||
expires_at: str
|
||||
|
||||
|
||||
@router.post("/s3keys", response=S3KeyResponse)
|
||||
def generate_s3_keys(request):
|
||||
"""
|
||||
Generate temporary AWS v4 signature credentials for S3 access.
|
||||
|
||||
The secret key is only returned here.
|
||||
"""
|
||||
credential = create_s3_credential(request.auth)
|
||||
return {
|
||||
"access_key": credential.access_key,
|
||||
"secret_key": credential.secret_key,
|
||||
"expires_at": credential.expires_at.isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
"""YAML-based transcode job request endpoints (scoped to a studio)."""
|
||||
from typing import Optional
|
||||
|
||||
import yaml
|
||||
from django.shortcuts import get_object_or_404
|
||||
from ninja import Router, Schema
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from privatestudio.studio.models import TranscodeJob, TranscodeProfile, UploadedAsset
|
||||
from privatestudio.studio.routers.common import get_studio_for_user, parse_yaml_body
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class TranscodeJobResponse(Schema):
|
||||
id: int
|
||||
asset_id: int
|
||||
profile_id: Optional[int]
|
||||
status: str
|
||||
requested_at: str
|
||||
|
||||
|
||||
def _job_response(job: TranscodeJob) -> dict:
|
||||
return {
|
||||
"id": job.id,
|
||||
"asset_id": job.asset_id,
|
||||
"profile_id": job.profile_id,
|
||||
"status": job.status,
|
||||
"requested_at": job.requested_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/studios/{bucket}/transcode", response=TranscodeJobResponse)
|
||||
def request_transcode(request, bucket: str):
|
||||
"""
|
||||
Request a transcode job with a YAML definition in the request body.
|
||||
|
||||
```yaml
|
||||
asset: "video.mp4" # Asset key, filename or ID
|
||||
profile: "hd-profile" # Profile name, or an inline profile definition
|
||||
```
|
||||
"""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
request_data = parse_yaml_body(request)
|
||||
|
||||
asset_ref = request_data.get("asset")
|
||||
if not asset_ref:
|
||||
raise HttpError(400, "Request must specify 'asset'")
|
||||
|
||||
assets = UploadedAsset.objects.filter(studio=studio)
|
||||
if isinstance(asset_ref, int):
|
||||
asset = assets.filter(pk=asset_ref).first()
|
||||
else:
|
||||
asset_ref = str(asset_ref)
|
||||
asset = assets.filter(s3_path=asset_ref).first() or assets.filter(filename=asset_ref).first()
|
||||
if asset is None:
|
||||
raise HttpError(404, f"Asset '{asset_ref}' not found")
|
||||
|
||||
profile_ref = request_data.get("profile")
|
||||
if not profile_ref:
|
||||
raise HttpError(400, "Request must specify 'profile'")
|
||||
|
||||
profile = None
|
||||
if isinstance(profile_ref, str):
|
||||
profile = TranscodeProfile.objects.filter(studio=studio, name=profile_ref).first()
|
||||
if profile is None:
|
||||
raise HttpError(404, f"Profile '{profile_ref}' not found")
|
||||
profile_definition = profile.profile_definition
|
||||
elif isinstance(profile_ref, dict):
|
||||
if "profiles" not in profile_ref:
|
||||
raise HttpError(400, "Inline profile must contain a 'profiles' section")
|
||||
profile_definition = yaml.safe_dump(profile_ref)
|
||||
else:
|
||||
raise HttpError(400, "Profile must be a string (name) or object (definition)")
|
||||
|
||||
job = TranscodeJob.objects.create(
|
||||
studio=studio,
|
||||
requested_by=request.auth,
|
||||
asset=asset,
|
||||
profile=profile,
|
||||
profile_definition=profile_definition,
|
||||
)
|
||||
return _job_response(job)
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/transcode/{job_id}", response=TranscodeJobResponse)
|
||||
def get_transcode_job(request, bucket: str, job_id: int):
|
||||
"""Get the status of a transcode job."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
return _job_response(get_object_or_404(TranscodeJob, pk=job_id, studio=studio))
|
||||
|
||||
|
||||
@router.get("/studios/{bucket}/transcode", response=list[TranscodeJobResponse])
|
||||
def list_transcode_jobs(request, bucket: str, status: Optional[str] = None):
|
||||
"""List transcode jobs for the studio."""
|
||||
studio = get_studio_for_user(request.auth, bucket)
|
||||
jobs = studio.transcode_jobs.order_by("id")
|
||||
if status:
|
||||
jobs = jobs.filter(status=status)
|
||||
return [_job_response(job) for job in jobs]
|
||||
@@ -0,0 +1,28 @@
|
||||
"""User information endpoint."""
|
||||
from ninja import Router, Schema
|
||||
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
class StudioInfo(Schema):
|
||||
name: str
|
||||
bucket: str
|
||||
|
||||
|
||||
class UserInfoResponse(Schema):
|
||||
user_id: int
|
||||
username: str
|
||||
studios: list[StudioInfo]
|
||||
|
||||
|
||||
@router.get("/userinfo", response=UserInfoResponse)
|
||||
def get_user_info(request):
|
||||
"""Get information about the current user and the studios they can access."""
|
||||
user = request.auth
|
||||
return {
|
||||
"user_id": user.id,
|
||||
"username": user.get_username(),
|
||||
"studios": [{"name": s.name, "bucket": s.bucket_name} for s in Studio.objects.for_user(user)],
|
||||
}
|
||||
@@ -1,12 +1,17 @@
|
||||
"""AWS v4 signature verification and credential management."""
|
||||
import secrets
|
||||
import hashlib
|
||||
import hmac
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from privatestudio.web.models import S3Credential
|
||||
from django.conf import settings
|
||||
from django.utils import timezone
|
||||
|
||||
from privatestudio.studio.models import S3Credential
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def generate_access_key() -> str:
|
||||
@@ -22,55 +27,34 @@ def generate_secret_key() -> str:
|
||||
return secrets.token_urlsafe(32).replace("-", "").replace("_", "")[:40]
|
||||
|
||||
|
||||
def create_s3_credential(db: Session, user_id: int, ttl_hours: int = 1) -> tuple[str, str]:
|
||||
def create_s3_credential(user, ttl_hours: Optional[int] = None) -> S3Credential:
|
||||
"""
|
||||
Create temporary S3 credentials for a user.
|
||||
|
||||
Returns: (access_key, secret_key)
|
||||
|
||||
The returned credential carries the secret key; it is only shown to the
|
||||
user once, at creation time.
|
||||
"""
|
||||
access_key = generate_access_key()
|
||||
secret_key = generate_secret_key()
|
||||
|
||||
now = datetime.utcnow()
|
||||
expires_at = now + timedelta(hours=ttl_hours)
|
||||
|
||||
credential = S3Credential(
|
||||
user_id=user_id,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
if ttl_hours is None:
|
||||
ttl_hours = settings.PRIVATESTUDIO_S3_CREDENTIAL_TTL_HOURS
|
||||
now = timezone.now()
|
||||
return S3Credential.objects.create(
|
||||
user=user,
|
||||
access_key=generate_access_key(),
|
||||
secret_key=generate_secret_key(),
|
||||
created_at=now,
|
||||
expires_at=expires_at,
|
||||
expires_at=now + timedelta(hours=ttl_hours),
|
||||
)
|
||||
db.add(credential)
|
||||
db.commit()
|
||||
db.refresh(credential)
|
||||
|
||||
return access_key, secret_key
|
||||
|
||||
|
||||
def get_s3_credential(db: Session, access_key: str) -> Optional[S3Credential]:
|
||||
def get_s3_credential(access_key: str) -> Optional[S3Credential]:
|
||||
"""Retrieve a non-expired S3 credential by access key."""
|
||||
credential = db.query(S3Credential).filter(
|
||||
S3Credential.access_key == access_key
|
||||
).first()
|
||||
|
||||
if not credential:
|
||||
return None
|
||||
|
||||
# Check if expired
|
||||
if datetime.utcnow() > credential.expires_at:
|
||||
return None
|
||||
|
||||
return credential
|
||||
return S3Credential.objects.filter(access_key=access_key, expires_at__gt=timezone.now()).first()
|
||||
|
||||
|
||||
def cleanup_expired_credentials(db: Session) -> int:
|
||||
def cleanup_expired_credentials() -> int:
|
||||
"""Delete all expired S3 credentials. Returns count of deleted credentials."""
|
||||
result = db.query(S3Credential).filter(
|
||||
S3Credential.expires_at <= datetime.utcnow()
|
||||
).delete()
|
||||
db.commit()
|
||||
return result
|
||||
deleted, _ = S3Credential.objects.filter(expires_at__lte=timezone.now()).delete()
|
||||
return deleted
|
||||
|
||||
|
||||
def sign_string(key: str, msg: str) -> str:
|
||||
@@ -169,8 +153,7 @@ def verify_aws_v4_signature(
|
||||
return hmac.compare_digest(calculated_signature, signature)
|
||||
|
||||
except Exception as e:
|
||||
import logging
|
||||
logging.getLogger(__name__).exception(f"Error verifying v4 signature: {e}")
|
||||
logger.exception(f"Error verifying v4 signature: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""S3-compatible object upload/download/delete/list views."""
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.utils import timezone
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views import View
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
from privatestudio.studio.auth import authenticate_s3_request, is_s3_v4_request
|
||||
from privatestudio.studio.models import Studio, UploadedAsset
|
||||
from privatestudio.studio.storage import get_storage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _error(status: int, detail: str, **headers) -> JsonResponse:
|
||||
response = JsonResponse({"detail": detail}, status=status)
|
||||
for name, value in headers.items():
|
||||
response[name] = value
|
||||
return response
|
||||
|
||||
|
||||
@method_decorator(csrf_exempt, name="dispatch")
|
||||
class S3BaseView(View):
|
||||
"""Authenticate the request and resolve the bucket to a Studio the user can access."""
|
||||
|
||||
http_method_names = ["get", "put", "delete", "head"]
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if request.method.lower() not in self.http_method_names:
|
||||
return self.http_method_not_allowed(request, *args, **kwargs)
|
||||
|
||||
user = authenticate_s3_request(request)
|
||||
if user is None:
|
||||
return _error(401, "Invalid or missing credentials", **{"WWW-Authenticate": "Bearer"})
|
||||
self.user = user
|
||||
|
||||
self.studio = Studio.objects.filter(bucket_name=kwargs["bucket"]).first()
|
||||
if self.studio is None:
|
||||
return _error(404, "Bucket not found")
|
||||
if not self.studio.user_has_access(user):
|
||||
return _error(403, "Access to this bucket is denied")
|
||||
|
||||
self.storage = get_storage()
|
||||
try:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
except ValueError as e:
|
||||
return _error(400, str(e))
|
||||
|
||||
|
||||
class ObjectView(S3BaseView):
|
||||
"""PUT/GET/DELETE a single object: /s3/<bucket>/<key>."""
|
||||
|
||||
def put(self, request, bucket, key):
|
||||
upload = None
|
||||
if request.content_type == "multipart/form-data":
|
||||
# Django only parses multipart bodies for POST, so parse PUT bodies here.
|
||||
_, files = request.parse_file_upload(request.META, io.BytesIO(request.body))
|
||||
upload = files.get("file")
|
||||
if upload is not None:
|
||||
# Multipart form upload (backward compatibility)
|
||||
content = upload.read()
|
||||
filename = upload.name or key.split("/")[-1]
|
||||
else:
|
||||
# Raw binary upload (boto3 / AWS v4 signature compatibility)
|
||||
content = request.body
|
||||
filename = key.split("/")[-1]
|
||||
|
||||
self.storage.put_object(self.studio.bucket_name, key, content)
|
||||
|
||||
asset, _ = UploadedAsset.objects.update_or_create(
|
||||
studio=self.studio,
|
||||
s3_path=key,
|
||||
defaults={
|
||||
"uploaded_by": self.user,
|
||||
"filename": filename,
|
||||
"size": len(content),
|
||||
"upload_timestamp": timezone.now(),
|
||||
},
|
||||
)
|
||||
|
||||
if is_s3_v4_request(request):
|
||||
# S3 PutObject response: 200 with ETag header and an empty body
|
||||
response = HttpResponse(status=200)
|
||||
response["ETag"] = f'"{hashlib.md5(content).hexdigest()}"'
|
||||
response["x-amz-version-id"] = str(asset.id)
|
||||
return response
|
||||
|
||||
return JsonResponse({
|
||||
"object_id": asset.id,
|
||||
"key": key,
|
||||
"size": len(content),
|
||||
"filename": asset.filename,
|
||||
})
|
||||
|
||||
def get(self, request, bucket, key):
|
||||
content = self.storage.get_object(self.studio.bucket_name, key)
|
||||
if content is None:
|
||||
return _error(404, "Object not found")
|
||||
return HttpResponse(content, content_type="application/octet-stream")
|
||||
|
||||
def head(self, request, bucket, key):
|
||||
size = self.storage.get_object_size(self.studio.bucket_name, key)
|
||||
if size is None:
|
||||
return HttpResponse(status=404)
|
||||
response = HttpResponse(content_type="application/octet-stream")
|
||||
response["Content-Length"] = str(size)
|
||||
return response
|
||||
|
||||
def delete(self, request, bucket, key):
|
||||
if not self.storage.delete_object(self.studio.bucket_name, key):
|
||||
return _error(404, "Object not found")
|
||||
UploadedAsset.objects.filter(studio=self.studio, s3_path=key).delete()
|
||||
return JsonResponse({"message": "Object deleted"})
|
||||
|
||||
|
||||
class BucketView(S3BaseView):
|
||||
"""List objects in a bucket: /s3/<bucket>."""
|
||||
|
||||
http_method_names = ["get"]
|
||||
|
||||
def get(self, request, bucket):
|
||||
prefix = request.GET.get("prefix", "")
|
||||
delimiter = request.GET.get("delimiter", "")
|
||||
objects = self.storage.list_objects(self.studio.bucket_name, prefix, delimiter)
|
||||
return JsonResponse({
|
||||
"bucket": self.studio.bucket_name,
|
||||
"prefix": prefix,
|
||||
"contents": [{"key": key} for key in objects],
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
"""S3-compatible local file storage, organised per studio bucket."""
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
class S3FileStorage:
|
||||
"""Local file storage backend with an S3-like interface."""
|
||||
|
||||
def __init__(self, base_path):
|
||||
self.base_path = Path(base_path)
|
||||
self.base_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _get_bucket_path(self, bucket: str) -> Path:
|
||||
bucket_path = self.base_path / bucket
|
||||
bucket_path.mkdir(parents=True, exist_ok=True)
|
||||
return bucket_path
|
||||
|
||||
def _get_file_path(self, bucket: str, key: str) -> Path:
|
||||
"""Resolve the path for a key, ensuring it stays inside the bucket directory."""
|
||||
bucket_path = self._get_bucket_path(bucket).resolve()
|
||||
file_path = (bucket_path / key).resolve()
|
||||
if file_path != bucket_path and bucket_path not in file_path.parents:
|
||||
raise ValueError(f"Invalid key: {key}")
|
||||
return file_path
|
||||
|
||||
def put_object(self, bucket: str, key: str, data: bytes) -> None:
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
file_path.write_bytes(data)
|
||||
|
||||
def get_object(self, bucket: str, key: str) -> Optional[bytes]:
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
if file_path.is_file():
|
||||
return file_path.read_bytes()
|
||||
return None
|
||||
|
||||
def delete_object(self, bucket: str, key: str) -> bool:
|
||||
"""Delete a file. Returns True if deleted, False if not found."""
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
if file_path.is_file():
|
||||
file_path.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
def list_objects(self, bucket: str, prefix: str = "", delimiter: str = "") -> list[str]:
|
||||
"""List objects in a bucket, optionally with prefix/delimiter."""
|
||||
bucket_path = self._get_bucket_path(bucket)
|
||||
items = []
|
||||
if delimiter == "/":
|
||||
# Return only direct children
|
||||
for item in bucket_path.iterdir():
|
||||
rel_path = item.relative_to(bucket_path).as_posix()
|
||||
if item.is_dir():
|
||||
rel_path += "/"
|
||||
if not prefix or rel_path.startswith(prefix):
|
||||
items.append(rel_path)
|
||||
else:
|
||||
for item in bucket_path.rglob("*"):
|
||||
if item.is_file():
|
||||
rel_path = item.relative_to(bucket_path).as_posix()
|
||||
if not prefix or rel_path.startswith(prefix):
|
||||
items.append(rel_path)
|
||||
return sorted(items)
|
||||
|
||||
def get_object_size(self, bucket: str, key: str) -> Optional[int]:
|
||||
file_path = self._get_file_path(bucket, key)
|
||||
if file_path.is_file():
|
||||
return file_path.stat().st_size
|
||||
return None
|
||||
|
||||
def object_exists(self, bucket: str, key: str) -> bool:
|
||||
return self._get_file_path(bucket, key).is_file()
|
||||
|
||||
|
||||
def get_storage() -> S3FileStorage:
|
||||
"""Return a storage instance rooted at settings.PRIVATESTUDIO_STORAGE_PATH."""
|
||||
return S3FileStorage(settings.PRIVATESTUDIO_STORAGE_PATH)
|
||||
@@ -0,0 +1,28 @@
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
from django.contrib.auth.models import Group, User
|
||||
from django.test import TestCase, override_settings
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
from privatestudio.studio.models import Studio
|
||||
|
||||
|
||||
class StudioTestCase(TestCase):
|
||||
"""Creates a user in a group that grants access to the 'demo' studio, plus an API key."""
|
||||
|
||||
def setUp(self):
|
||||
self.storage_dir = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, self.storage_dir, ignore_errors=True)
|
||||
settings_override = override_settings(PRIVATESTUDIO_STORAGE_PATH=self.storage_dir)
|
||||
settings_override.enable()
|
||||
self.addCleanup(settings_override.disable)
|
||||
|
||||
self.group = Group.objects.create(name="demo-team")
|
||||
self.studio = Studio.objects.create(name="Demo", bucket_name="demo", group=self.group)
|
||||
self.user = User.objects.create_user("testuser")
|
||||
self.user.groups.add(self.group)
|
||||
self.key, _ = create_api_key(self.user)
|
||||
|
||||
def auth(self, key=None):
|
||||
return {"Authorization": f"Bearer {key or self.key}"}
|
||||
@@ -0,0 +1,154 @@
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
from privatestudio.studio.models import TranscodeJob, UploadedAsset
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
|
||||
PROFILE_YAML = "profiles:\n hd:\n resolution: 1280x720\n bitrate: 2500k\n"
|
||||
|
||||
|
||||
class HealthTests(StudioTestCase):
|
||||
def test_health_check(self):
|
||||
response = self.client.get("/health")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"status": "ok"})
|
||||
|
||||
|
||||
class APIKeyTests(StudioTestCase):
|
||||
def test_create_api_key(self):
|
||||
response = self.client.post("/api/keys", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertIn("id", data)
|
||||
self.assertIn("key", data)
|
||||
self.assertIn("created_at", data)
|
||||
|
||||
def test_list_api_keys(self):
|
||||
response = self.client.get("/api/keys", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertEqual(len(data), 1)
|
||||
self.assertIs(data[0]["is_active"], True)
|
||||
|
||||
def test_authentication_required(self):
|
||||
self.assertEqual(self.client.get("/api/keys").status_code, 401)
|
||||
|
||||
def test_invalid_api_key(self):
|
||||
self.assertEqual(self.client.get("/api/keys", headers=self.auth("invalid_key")).status_code, 401)
|
||||
|
||||
def test_revoke_api_key(self):
|
||||
key_id = self.client.get("/api/keys", headers=self.auth()).json()[0]["id"]
|
||||
response = self.client.delete(f"/api/keys/{key_id}", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(self.client.get("/api/keys", headers=self.auth()).status_code, 401)
|
||||
|
||||
def test_cannot_revoke_other_users_key(self):
|
||||
other = User.objects.create_user("other")
|
||||
_, other_key = create_api_key(other)
|
||||
response = self.client.delete(f"/api/keys/{other_key.id}", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
|
||||
class S3KeyTests(StudioTestCase):
|
||||
def test_generate_s3_credentials(self):
|
||||
response = self.client.post("/api/s3keys", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.json()
|
||||
self.assertTrue(data["access_key"].startswith("AKIA"))
|
||||
self.assertGreaterEqual(len(data["secret_key"]), 30)
|
||||
self.assertIn("T", data["expires_at"])
|
||||
|
||||
data2 = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
self.assertNotEqual(data["access_key"], data2["access_key"])
|
||||
self.assertNotEqual(data["secret_key"], data2["secret_key"])
|
||||
|
||||
|
||||
class UserInfoTests(StudioTestCase):
|
||||
def test_userinfo_lists_studios(self):
|
||||
response = self.client.get("/api/userinfo", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {
|
||||
"user_id": self.user.id,
|
||||
"username": "testuser",
|
||||
"studios": [{"name": "Demo", "bucket": "demo"}],
|
||||
})
|
||||
|
||||
|
||||
class ProfileTests(StudioTestCase):
|
||||
def create_profile(self, name="hd-profile", body=PROFILE_YAML, key=None):
|
||||
return self.client.post(
|
||||
f"/api/studios/demo/profiles?name={name}", data=body,
|
||||
content_type="application/yaml", headers=self.auth(key),
|
||||
)
|
||||
|
||||
def test_create_list_get_profile(self):
|
||||
response = self.create_profile()
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
profile_id = response.json()["id"]
|
||||
|
||||
listing = self.client.get("/api/studios/demo/profiles", headers=self.auth()).json()
|
||||
self.assertEqual([p["name"] for p in listing], ["hd-profile"])
|
||||
|
||||
detail = self.client.get(f"/api/studios/demo/profiles/{profile_id}", headers=self.auth())
|
||||
self.assertEqual(detail.status_code, 200)
|
||||
self.assertEqual(detail.json()["profile_definition"], PROFILE_YAML)
|
||||
|
||||
def test_duplicate_profile_conflicts(self):
|
||||
self.create_profile()
|
||||
self.assertEqual(self.create_profile().status_code, 409)
|
||||
|
||||
def test_invalid_profile_yaml(self):
|
||||
self.assertEqual(self.create_profile(body="not: [valid").status_code, 400)
|
||||
self.assertEqual(self.create_profile(body="foo: bar\n").status_code, 400)
|
||||
|
||||
def test_non_member_forbidden(self):
|
||||
outsider = User.objects.create_user("outsider")
|
||||
outsider_key, _ = create_api_key(outsider)
|
||||
self.assertEqual(self.create_profile(key=outsider_key).status_code, 403)
|
||||
|
||||
def test_unknown_studio(self):
|
||||
response = self.client.get("/api/studios/nope/profiles", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 404)
|
||||
|
||||
|
||||
class TranscodeTests(StudioTestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.asset = UploadedAsset.objects.create(
|
||||
studio=self.studio, uploaded_by=self.user, filename="video.mp4", size=10, s3_path="raw/video.mp4",
|
||||
)
|
||||
|
||||
def request_transcode(self, body):
|
||||
return self.client.post(
|
||||
"/api/studios/demo/transcode", data=body, content_type="application/yaml", headers=self.auth(),
|
||||
)
|
||||
|
||||
def test_transcode_with_named_profile(self):
|
||||
self.client.post(
|
||||
"/api/studios/demo/profiles?name=hd", data=PROFILE_YAML,
|
||||
content_type="application/yaml", headers=self.auth(),
|
||||
)
|
||||
response = self.request_transcode("asset: raw/video.mp4\nprofile: hd\n")
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
data = response.json()
|
||||
self.assertEqual(data["asset_id"], self.asset.id)
|
||||
self.assertIsNotNone(data["profile_id"])
|
||||
self.assertEqual(data["status"], "pending")
|
||||
|
||||
job_id = data["id"]
|
||||
self.assertEqual(self.client.get(f"/api/studios/demo/transcode/{job_id}", headers=self.auth()).status_code, 200)
|
||||
listing = self.client.get("/api/studios/demo/transcode?status=pending", headers=self.auth()).json()
|
||||
self.assertEqual([j["id"] for j in listing], [job_id])
|
||||
|
||||
def test_transcode_with_inline_profile_by_filename(self):
|
||||
response = self.request_transcode("asset: video.mp4\nprofile:\n profiles:\n sd:\n bitrate: 800k\n")
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
self.assertIsNone(response.json()["profile_id"])
|
||||
job = TranscodeJob.objects.get()
|
||||
self.assertIn("800k", job.profile_definition)
|
||||
|
||||
def test_transcode_errors(self):
|
||||
self.assertEqual(self.request_transcode("profile: hd\n").status_code, 400)
|
||||
self.assertEqual(self.request_transcode("asset: missing.mp4\nprofile: hd\n").status_code, 404)
|
||||
self.assertEqual(self.request_transcode("asset: video.mp4\nprofile: missing\n").status_code, 404)
|
||||
self.assertEqual(self.request_transcode("asset: video.mp4\nprofile: [1]\n").status_code, 400)
|
||||
@@ -0,0 +1,114 @@
|
||||
from django.contrib.auth.models import Group, User
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY
|
||||
|
||||
from privatestudio.studio.auth import create_api_key
|
||||
from privatestudio.studio.models import Studio, UploadedAsset
|
||||
from privatestudio.studio.tests.base import StudioTestCase
|
||||
|
||||
|
||||
class S3InterfaceTests(StudioTestCase):
|
||||
def upload(self, key, content=b"test file content", bucket="demo", api_key=None):
|
||||
body = encode_multipart(BOUNDARY, {"file": SimpleUploadedFile(key.split("/")[-1], content, "video/mp4")})
|
||||
return self.client.put(f"/s3/{bucket}/{key}", data=body, content_type=MULTIPART_CONTENT,
|
||||
headers=self.auth(api_key))
|
||||
|
||||
def test_upload_file(self):
|
||||
response = self.upload("test.mp4")
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
data = response.json()
|
||||
self.assertEqual(data["key"], "test.mp4")
|
||||
self.assertEqual(data["size"], len(b"test file content"))
|
||||
self.assertEqual(UploadedAsset.objects.get().uploaded_by, self.user)
|
||||
|
||||
def test_raw_upload_and_reupload_updates_asset(self):
|
||||
for content in (b"first", b"second version"):
|
||||
response = self.client.put("/s3/demo/dir/raw.bin", data=content,
|
||||
content_type="application/octet-stream", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
asset = UploadedAsset.objects.get()
|
||||
self.assertEqual(asset.size, len(b"second version"))
|
||||
self.assertEqual(asset.filename, "raw.bin")
|
||||
|
||||
def test_download_file(self):
|
||||
self.upload("test.mp4")
|
||||
response = self.client.get("/s3/demo/test.mp4", headers=self.auth())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.content, b"test file content")
|
||||
|
||||
def test_delete_file(self):
|
||||
self.upload("test.mp4")
|
||||
self.assertEqual(self.client.delete("/s3/demo/test.mp4", headers=self.auth()).status_code, 200)
|
||||
self.assertEqual(self.client.get("/s3/demo/test.mp4", headers=self.auth()).status_code, 404)
|
||||
self.assertFalse(UploadedAsset.objects.exists())
|
||||
|
||||
def test_list_objects(self):
|
||||
self.upload("test1.mp4", b"content1")
|
||||
self.upload("sub/test2.mp4", b"content2")
|
||||
data = self.client.get("/s3/demo", headers=self.auth()).json()
|
||||
self.assertEqual([c["key"] for c in data["contents"]], ["sub/test2.mp4", "test1.mp4"])
|
||||
data = self.client.get("/s3/demo/?delimiter=/", headers=self.auth()).json()
|
||||
self.assertEqual([c["key"] for c in data["contents"]], ["sub/", "test1.mp4"])
|
||||
|
||||
def test_authentication_required(self):
|
||||
self.assertEqual(self.client.get("/s3/demo").status_code, 401)
|
||||
|
||||
def test_unknown_bucket(self):
|
||||
self.assertEqual(self.client.get("/s3/nope", headers=self.auth()).status_code, 404)
|
||||
|
||||
def test_path_traversal_rejected(self):
|
||||
response = self.client.put("/s3/demo/../escape.bin", data=b"x",
|
||||
content_type="application/octet-stream", headers=self.auth())
|
||||
self.assertIn(response.status_code, (400, 404))
|
||||
|
||||
def test_per_studio_isolation(self):
|
||||
self.upload("private.mp4", b"studio content")
|
||||
|
||||
outsider = User.objects.create_user("testuser2")
|
||||
other_group = Group.objects.create(name="other-team")
|
||||
outsider.groups.add(other_group)
|
||||
Studio.objects.create(name="Other", bucket_name="other", group=other_group)
|
||||
outsider_key, _ = create_api_key(outsider)
|
||||
|
||||
self.assertEqual(self.client.get("/s3/demo/private.mp4", headers=self.auth(outsider_key)).status_code, 403)
|
||||
self.assertEqual(self.upload("x.mp4", bucket="other").status_code, 403)
|
||||
self.assertEqual(self.upload("x.mp4", bucket="other", api_key=outsider_key).status_code, 200)
|
||||
|
||||
def test_group_membership_grants_access(self):
|
||||
member = User.objects.create_user("member")
|
||||
member.groups.add(self.group)
|
||||
member_key, _ = create_api_key(member)
|
||||
self.upload("shared.mp4")
|
||||
response = self.client.get("/s3/demo/shared.mp4", headers=self.auth(member_key))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
|
||||
class S3SignatureTests(StudioTestCase):
|
||||
def signed_put(self, url_path, data, access_key, secret_key):
|
||||
from botocore.auth import SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
|
||||
request = AWSRequest(method="PUT", url=f"http://testserver{url_path}", data=data)
|
||||
SigV4Auth(Credentials(access_key, secret_key), "s3", "us-east-1").add_auth(request)
|
||||
return self.client.put(
|
||||
url_path, data=data, content_type="",
|
||||
headers={
|
||||
"Authorization": request.headers["Authorization"],
|
||||
"X-Amz-Date": request.headers["X-Amz-Date"],
|
||||
"X-Amz-Content-Sha256": request.headers["X-Amz-Content-Sha256"],
|
||||
},
|
||||
)
|
||||
|
||||
def test_upload_with_v4_signature(self):
|
||||
creds = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
response = self.signed_put("/s3/demo/boto3-test.mp4", b"test file content from boto3",
|
||||
creds["access_key"], creds["secret_key"])
|
||||
self.assertEqual(response.status_code, 200, response.content)
|
||||
self.assertIn("ETag", response.headers)
|
||||
self.assertEqual(response.content, b"")
|
||||
|
||||
def test_bad_signature_rejected(self):
|
||||
creds = self.client.post("/api/s3keys", headers=self.auth()).json()
|
||||
response = self.signed_put("/s3/demo/boto3-test.mp4", b"data", creds["access_key"], "wrong-secret")
|
||||
self.assertEqual(response.status_code, 401)
|
||||
@@ -0,0 +1,10 @@
|
||||
from django.urls import re_path
|
||||
|
||||
from privatestudio.studio import s3_views
|
||||
|
||||
# re_path without trailing-slash requirements so APPEND_SLASH never redirects
|
||||
# (a redirect would invalidate AWS v4 signatures).
|
||||
urlpatterns = [
|
||||
re_path(r"^s3/(?P<bucket>[^/]+)/?$", s3_views.BucketView.as_view(), name="s3_bucket"),
|
||||
re_path(r"^s3/(?P<bucket>[^/]+)/(?P<key>.+)$", s3_views.ObjectView.as_view(), name="s3_object"),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
from django.contrib import admin
|
||||
from django.http import JsonResponse
|
||||
from django.urls import include, path
|
||||
|
||||
from privatestudio.studio.api import api
|
||||
|
||||
|
||||
def health_check(request):
|
||||
"""Unauthenticated health check endpoint."""
|
||||
return JsonResponse({"status": "ok"})
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path("health", health_check, name="health"),
|
||||
path("admin/", admin.site.urls),
|
||||
path("api/", api.urls),
|
||||
path("", include("privatestudio.studio.urls")),
|
||||
]
|
||||
@@ -1 +0,0 @@
|
||||
"""Web service for video transcoding management."""
|
||||
@@ -1,3 +0,0 @@
|
||||
from privatestudio.web.cli import main
|
||||
|
||||
raise SystemExit(main())
|
||||
@@ -1,78 +0,0 @@
|
||||
"""FastAPI application setup and configuration."""
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from privatestudio.web.database import upgrade_db
|
||||
from privatestudio.web.routes import assets, transcode, profiles, keys, userinfo, s3_keys
|
||||
|
||||
|
||||
class CacheBodyMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware to cache request body for multiple reads."""
|
||||
|
||||
async def dispatch(self, request, call_next):
|
||||
body = await request.body()
|
||||
request.state._body = body
|
||||
|
||||
async def receive():
|
||||
return {"type": "http.request", "body": body, "more_body": False}
|
||||
|
||||
request._receive = receive
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Lifespan context manager to initialize the database on startup."""
|
||||
upgrade_db()
|
||||
yield
|
||||
|
||||
# Create FastAPI app
|
||||
app = FastAPI(
|
||||
title="Private Studio",
|
||||
description="Video transcoding web service with S3-compatible interface",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# Add middleware to cache request body (must be before CORS)
|
||||
app.add_middleware(CacheBodyMiddleware)
|
||||
|
||||
# Add CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # Configure in production
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint."""
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# Include routes
|
||||
app.include_router(keys.router, prefix="/api", tags=["Keys"])
|
||||
app.include_router(s3_keys.router, prefix="/api", tags=["S3 Keys"])
|
||||
app.include_router(assets.router, prefix="/s3", tags=["S3"])
|
||||
app.include_router(transcode.router, prefix="/api", tags=["Transcode"])
|
||||
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
|
||||
app.include_router(userinfo.router, prefix="/api", tags=["UserInfo"])
|
||||
|
||||
|
||||
@app.exception_handler(ValueError)
|
||||
async def value_error_handler(request, exc):
|
||||
"""Handle ValueError exceptions."""
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
||||
@@ -1,218 +0,0 @@
|
||||
"""API key authentication and user management."""
|
||||
import secrets
|
||||
import hashlib
|
||||
import hmac
|
||||
from datetime import datetime
|
||||
from fastapi import Depends, HTTPException, status, Request
|
||||
from fastapi.security import HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from privatestudio.web.models import User, APIKey
|
||||
from privatestudio.web.database import get_db
|
||||
|
||||
|
||||
def hash_api_key(key: str) -> str:
|
||||
"""Hash an API key using SHA256."""
|
||||
return hashlib.sha256(key.encode()).hexdigest()
|
||||
|
||||
|
||||
def verify_api_key(plain_key: str, hashed_key: str) -> bool:
|
||||
"""Verify a plain API key against its hash."""
|
||||
return hmac.compare_digest(hash_api_key(plain_key), hashed_key)
|
||||
|
||||
|
||||
def generate_api_key() -> str:
|
||||
"""Generate a random API key."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def create_user(db: Session, username: str) -> User:
|
||||
"""Create a new user account."""
|
||||
# Check if user already exists
|
||||
existing_user = db.query(User).filter(User.username == username).first()
|
||||
if existing_user:
|
||||
raise ValueError(f"User '{username}' already exists")
|
||||
|
||||
user = User(username=username)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def create_api_key(db: Session, user_id: int) -> tuple[str, APIKey]:
|
||||
"""
|
||||
Create a new API key for a user.
|
||||
|
||||
Returns: (plain_key, api_key_record)
|
||||
The plain key should be given to the user and never stored. Only the hash is saved.
|
||||
"""
|
||||
plain_key = generate_api_key()
|
||||
key_hash = hash_api_key(plain_key)
|
||||
|
||||
api_key = APIKey(key_hash=key_hash, user_id=user_id, is_active=True)
|
||||
db.add(api_key)
|
||||
db.commit()
|
||||
db.refresh(api_key)
|
||||
|
||||
return plain_key, api_key
|
||||
|
||||
|
||||
def revoke_api_key(db: Session, key_id: int):
|
||||
"""Revoke an API key by marking it inactive."""
|
||||
api_key = db.query(APIKey).filter(APIKey.id == key_id).first()
|
||||
if not api_key:
|
||||
raise ValueError(f"API key {key_id} not found")
|
||||
|
||||
api_key.is_active = False
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPBearer = Depends(HTTPBearer()),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""
|
||||
FastAPI dependency to validate API key and return authenticated user.
|
||||
|
||||
Usage:
|
||||
@app.get("/api/assets")
|
||||
def list_assets(current_user: User = Depends(get_current_user)):
|
||||
...
|
||||
"""
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Missing credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
# Find the API key in the database
|
||||
api_keys = db.query(APIKey).all()
|
||||
|
||||
# Verify the token against each key's hash
|
||||
matching_key = None
|
||||
for key in api_keys:
|
||||
if verify_api_key(token, key.key_hash):
|
||||
matching_key = key
|
||||
break
|
||||
|
||||
if not matching_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid API key",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
if not matching_key.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="API key is revoked",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Get the user
|
||||
user = db.query(User).filter(User.id == matching_key.user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_current_user_s3(
|
||||
request: Request,
|
||||
credentials: HTTPBearer = Depends(HTTPBearer(auto_error=False)),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""
|
||||
Hybrid auth for S3 endpoints - supports both bearer tokens and AWS v4 signatures.
|
||||
|
||||
Tries v4 signature first, falls back to bearer token.
|
||||
"""
|
||||
from privatestudio.web.s3_credentials import get_s3_credential, verify_aws_v4_signature
|
||||
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
|
||||
# Try v4 signature first
|
||||
if auth_header and auth_header.startswith("AWS4-HMAC-SHA256"):
|
||||
try:
|
||||
# Extract access key from Authorization header
|
||||
cred_part = auth_header.split("Credential=")[1].split(",")[0]
|
||||
access_key = cred_part.split("/")[0]
|
||||
|
||||
# Get the credential
|
||||
credential = get_s3_credential(db, access_key)
|
||||
if credential:
|
||||
# Verify the signature
|
||||
method = request.method
|
||||
path = request.url.path
|
||||
query_string = request.url.query or ""
|
||||
headers = dict(request.headers)
|
||||
body = getattr(request.state, "_body", b"")
|
||||
|
||||
if verify_aws_v4_signature(
|
||||
auth_header,
|
||||
method,
|
||||
path,
|
||||
query_string,
|
||||
headers,
|
||||
body,
|
||||
credential.secret_key,
|
||||
):
|
||||
# Return the user
|
||||
user = db.query(User).filter(User.id == credential.user_id).first()
|
||||
if user:
|
||||
return user
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
|
||||
# Fall back to bearer token auth
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Missing credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
# Find the API key in the database
|
||||
api_keys = db.query(APIKey).all()
|
||||
|
||||
# Verify the token against each key's hash
|
||||
matching_key = None
|
||||
for key in api_keys:
|
||||
if verify_api_key(token, key.key_hash):
|
||||
matching_key = key
|
||||
break
|
||||
|
||||
if not matching_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid API key",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
if not matching_key.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="API key is revoked",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Get the user
|
||||
user = db.query(User).filter(User.id == matching_key.user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
return user
|
||||
@@ -1,104 +0,0 @@
|
||||
"""CLI entry point for the video transcoding web service."""
|
||||
import argparse
|
||||
import os
|
||||
import uvicorn
|
||||
|
||||
from privatestudio.web.database import upgrade_db, get_db, SessionLocal
|
||||
from privatestudio.web.auth import create_user, create_api_key
|
||||
from privatestudio.web.models import User
|
||||
|
||||
|
||||
def migrate_command(args):
|
||||
"""Migrate the database."""
|
||||
upgrade_db()
|
||||
print("Database migrated")
|
||||
|
||||
|
||||
def create_user_command(args):
|
||||
"""Create a new user account."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user = create_user(db, args.username)
|
||||
print(f"User created: {args.username} (ID: {user.id})")
|
||||
except ValueError as e:
|
||||
print(f"Error: {e}")
|
||||
return 1
|
||||
finally:
|
||||
db.close()
|
||||
return 0
|
||||
|
||||
|
||||
def create_key_command(args):
|
||||
"""Create an API key for a user."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
user = db.query(User).filter(User.username == args.user_name).first()
|
||||
if not user:
|
||||
raise ValueError(f"User '{args.user_name}' not found")
|
||||
plain_key, api_key = create_api_key(db, user.id)
|
||||
print(f"API key created for user {args.user_name}")
|
||||
print(f"Key: {plain_key}")
|
||||
print(f"Keep this key safe - you won't be able to see it again!")
|
||||
except ValueError as e:
|
||||
print(f"Error: {e}")
|
||||
return 1
|
||||
finally:
|
||||
db.close()
|
||||
return 0
|
||||
|
||||
|
||||
def serve_command(args):
|
||||
"""Start the web server."""
|
||||
host = args.host or os.environ.get("SERVER_HOST", "0.0.0.0")
|
||||
port = args.port or int(os.environ.get("SERVER_PORT", "8000"))
|
||||
|
||||
print(f"Starting server at {host}:{port}")
|
||||
uvicorn.run(
|
||||
"privatestudio.web.app:app",
|
||||
host=host,
|
||||
port=port,
|
||||
reload=args.reload,
|
||||
log_level=args.log_level,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point for CLI."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Private Studio - Video transcoding web service",
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest="command", help="Command to run")
|
||||
|
||||
# Init command
|
||||
init_parser = subparsers.add_parser("migrate", help="Migrate the database")
|
||||
init_parser.set_defaults(func=migrate_command)
|
||||
|
||||
# Create user command
|
||||
user_parser = subparsers.add_parser("create-user", help="Create a new user")
|
||||
user_parser.add_argument("username", help="Username for the new account")
|
||||
user_parser.set_defaults(func=create_user_command)
|
||||
|
||||
# Create key command
|
||||
key_parser = subparsers.add_parser("create-key", help="Create an API key for a user")
|
||||
key_parser.add_argument("user_name", type=str, help="User name")
|
||||
key_parser.set_defaults(func=create_key_command)
|
||||
|
||||
# Serve command
|
||||
serve_parser = subparsers.add_parser("serve", help="Start the web server")
|
||||
serve_parser.add_argument("--host", default=None, help="Server host (default: 0.0.0.0)")
|
||||
serve_parser.add_argument("--port", type=int, default=None, help="Server port (default: 8000)")
|
||||
serve_parser.add_argument("--reload", action="store_true", help="Enable auto-reload on code changes")
|
||||
serve_parser.add_argument("--log-level", default="info", help="Log level (default: info)")
|
||||
serve_parser.set_defaults(func=serve_command)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not hasattr(args, "func"):
|
||||
parser.print_help()
|
||||
return 1
|
||||
|
||||
return args.func(args) or 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,54 +0,0 @@
|
||||
"""SQLAlchemy database configuration and session management."""
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from pathlib import Path
|
||||
|
||||
from privatestudio.web.models import Base
|
||||
|
||||
# Get database path from environment, default to ./transcoding.db
|
||||
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./transcoding.db")
|
||||
|
||||
# Create engine with appropriate settings for SQLite
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
connect_args={"check_same_thread": False} if "sqlite" in DATABASE_URL else {},
|
||||
poolclass=StaticPool if "sqlite" in DATABASE_URL else None,
|
||||
echo=os.environ.get("SQL_ECHO", "false").lower() == "true",
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Session:
|
||||
"""Dependency for FastAPI to get database session."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# def init_db():
|
||||
# """Initialize database tables."""
|
||||
# Base.metadata.create_all(bind=engine)
|
||||
#
|
||||
#
|
||||
# def drop_db():
|
||||
# """Drop all database tables (for testing)."""
|
||||
# Base.metadata.drop_all(bind=engine)
|
||||
|
||||
|
||||
def upgrade_db():
|
||||
config = Config()
|
||||
config.set_main_option(
|
||||
"script_location",
|
||||
str(Path(__file__).resolve().parent.parent / "migrations"),
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
config.attributes["connection"] = connection
|
||||
command.upgrade(config, "head")
|
||||
@@ -1,177 +0,0 @@
|
||||
"""SQLAlchemy ORM models for video transcoding service."""
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.types import TypeDecorator
|
||||
from sqlalchemy import Column, Integer, ForeignKey, Text
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class TextDateTime(TypeDecorator):
|
||||
"""Custom SQLAlchemy type to store datetime as text in SQLite."""
|
||||
impl = Text
|
||||
|
||||
def process_bind_param(self, value, dialect):
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, datetime) or value.utcoffset() is None:
|
||||
raise ValueError("Expected a timezone-aware datetime")
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds")
|
||||
|
||||
def process_result_value(self, value, dialect):
|
||||
if value is None:
|
||||
return None
|
||||
result = datetime.fromisoformat(value)
|
||||
if result.utcoffset() is None:
|
||||
raise ValueError("Stored datetime has no timezone")
|
||||
return result.astimezone(timezone.utc)
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""User account for API access."""
|
||||
__tablename__ = "users"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
username = Column(Text(), unique=True, nullable=False, index=True)
|
||||
created_at = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
bucket_name = Column(Text(), nullable=True) # Optional S3 bucket name for user
|
||||
|
||||
# Relationships
|
||||
api_keys = relationship("APIKey", back_populates="user", cascade="all, delete-orphan")
|
||||
uploaded_assets = relationship("UploadedAsset", back_populates="user", cascade="all, delete-orphan")
|
||||
transcode_profiles = relationship("TranscodeProfile", back_populates="user", cascade="all, delete-orphan")
|
||||
transcode_jobs = relationship("TranscodeJob", back_populates="user", cascade="all, delete-orphan")
|
||||
packaging_jobs = relationship("PackagingJob", back_populates="user", cascade="all, delete-orphan")
|
||||
transcoded_assets = relationship("TranscodedAsset", back_populates="user", cascade="all, delete-orphan")
|
||||
s3_credentials = relationship("S3Credential", back_populates="user", cascade="all, delete-orphan")
|
||||
|
||||
def get_bucket_name(self) -> str:
|
||||
"""Return the S3 bucket name for the user, generating one if not set."""
|
||||
if self.bucket_name:
|
||||
return self.bucket_name
|
||||
# Generate a default bucket name based on user ID
|
||||
return f"user-{self.id}"
|
||||
|
||||
|
||||
class APIKey(Base):
|
||||
"""API key for authentication."""
|
||||
__tablename__ = "api_keys"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
key_hash = Column(Text(), unique=True, nullable=False, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
created_at = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
is_active = Column(Integer, default=1, nullable=False)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="api_keys")
|
||||
|
||||
|
||||
class UploadedAsset(Base):
|
||||
"""Uploaded video file."""
|
||||
__tablename__ = "uploaded_assets"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
filename = Column(Text(), nullable=False)
|
||||
size = Column(Integer, nullable=False) # File size in bytes
|
||||
s3_path = Column(Text(), nullable=False) # Path relative to storage root
|
||||
upload_timestamp = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="uploaded_assets")
|
||||
transcode_jobs = relationship("TranscodeJob", back_populates="uploaded_asset", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class TranscodeProfile(Base):
|
||||
"""Predefined encoding profile."""
|
||||
__tablename__ = "transcode_profiles"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
name = Column(Text(), nullable=False)
|
||||
profile_definition = Column(Text, nullable=False) # YAML definition as string
|
||||
created_at = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="transcode_profiles")
|
||||
transcode_jobs = relationship("TranscodeJob", back_populates="transcode_profile")
|
||||
|
||||
|
||||
class TranscodeJob(Base):
|
||||
"""Requested transcode operation."""
|
||||
__tablename__ = "transcode_jobs"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
asset_id = Column(Integer, ForeignKey("uploaded_assets.id"), nullable=False)
|
||||
profile_id = Column(Integer, ForeignKey("transcode_profiles.id"), nullable=True) # Null if inline profile used
|
||||
status = Column(Text(), nullable=False, default="pending") # pending, in_progress, completed, failed
|
||||
requested_at = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
completed_at = Column(TextDateTime, nullable=True)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="transcode_jobs")
|
||||
uploaded_asset = relationship("UploadedAsset", back_populates="transcode_jobs")
|
||||
transcode_profile = relationship("TranscodeProfile", back_populates="transcode_jobs")
|
||||
transcoded_assets = relationship("TranscodedAsset", back_populates="transcode_job", cascade="all, delete-orphan")
|
||||
packaging_jobs = relationship("PackagingJob", back_populates="transcode_job", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class PackagingJob(Base):
|
||||
"""Requested packaging operation."""
|
||||
__tablename__ = "packaging_jobs"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
transcode_job_id = Column(Integer, ForeignKey("transcode_jobs.id"), nullable=False)
|
||||
status = Column(Text(), nullable=False, default="pending") # pending, in_progress, completed, failed
|
||||
requested_at = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
completed_at = Column(TextDateTime, nullable=True)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="packaging_jobs")
|
||||
transcode_job = relationship("TranscodeJob", back_populates="packaging_jobs")
|
||||
|
||||
|
||||
class TranscodedAsset(Base):
|
||||
"""Output file from transcode job."""
|
||||
__tablename__ = "transcoded_assets"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
transcode_job_id = Column(Integer, ForeignKey("transcode_jobs.id"), nullable=False)
|
||||
filename = Column(Text(), nullable=False)
|
||||
s3_path = Column(Text(), nullable=False) # Path relative to storage root
|
||||
format = Column(Text(), nullable=False) # e.g., "mp4", "audio"
|
||||
created_at = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="transcoded_assets")
|
||||
transcode_job = relationship("TranscodeJob", back_populates="transcoded_assets")
|
||||
|
||||
|
||||
class S3Credential(Base):
|
||||
"""Temporary AWS v4 signature credentials for S3 access."""
|
||||
__tablename__ = "s3_credentials"
|
||||
__table_args__ = {"sqlite_strict": True}
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
|
||||
access_key = Column(Text(), unique=True, nullable=False, index=True)
|
||||
secret_key = Column(Text(), nullable=False)
|
||||
created_at = Column(TextDateTime, nullable=False, default=datetime.utcnow)
|
||||
expires_at = Column(TextDateTime, nullable=False) # 1 hour from creation
|
||||
|
||||
authorized_key = Column(Text(), nullable=True)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="s3_credentials")
|
||||
@@ -1 +0,0 @@
|
||||
"""API route handlers."""
|
||||
@@ -1,183 +0,0 @@
|
||||
"""S3-compatible file upload/download/delete/list endpoints."""
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile, Request
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy.orm import Session
|
||||
import logging
|
||||
import hashlib
|
||||
|
||||
from privatestudio.web.database import get_db
|
||||
from privatestudio.web.models import User, UploadedAsset
|
||||
from privatestudio.web.auth import get_current_user_s3
|
||||
from privatestudio.web.s3_interface import get_storage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _parse_bucket_to_user_id(db: Session, bucket: str) -> int:
|
||||
"""
|
||||
Parse bucket name (user-{id}) to user ID.
|
||||
Also handles username for backward compatibility.
|
||||
"""
|
||||
from privatestudio.web.models import User
|
||||
|
||||
# Try parsing as user-{id} format
|
||||
if bucket.startswith("user-"):
|
||||
try:
|
||||
user_id = int(bucket.split("-")[1])
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user:
|
||||
return user_id
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
# Try as username
|
||||
user = db.query(User).filter(User.username == bucket).first()
|
||||
if user:
|
||||
return user.id
|
||||
|
||||
raise ValueError(f"Invalid bucket or username: {bucket}")
|
||||
|
||||
|
||||
def _is_s3_v4_request(request: Request) -> bool:
|
||||
"""Check if this is an S3 v4 signature request."""
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
return auth_header.startswith("AWS4-HMAC-SHA256")
|
||||
|
||||
|
||||
@router.put("/{bucket}/{key:path}")
|
||||
async def upload_file(
|
||||
bucket: str,
|
||||
key: str,
|
||||
file: UploadFile = File(None),
|
||||
request: Request = None,
|
||||
current_user: User = Depends(get_current_user_s3),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
# Verify user is uploading to their own bucket
|
||||
if bucket != current_user.get_bucket_name():
|
||||
raise HTTPException(status_code=403, detail="Cannot upload to another user's bucket")
|
||||
|
||||
# Handle both form data (file field) and raw binary uploads
|
||||
if file is not None:
|
||||
# Form data upload (backward compatibility)
|
||||
content = await file.read()
|
||||
filename = file.filename or key.split("/")[-1]
|
||||
else:
|
||||
# Raw binary upload (boto3/AWS v4 signature compatibility)
|
||||
content = getattr(request.state, "_body", b"")
|
||||
if not content:
|
||||
content = await request.body()
|
||||
filename = key.split("/")[-1]
|
||||
|
||||
# Store file
|
||||
storage = get_storage()
|
||||
storage.put_object(current_user.id, key, content)
|
||||
|
||||
# Record in database
|
||||
asset = UploadedAsset(
|
||||
user_id=current_user.id,
|
||||
filename=filename,
|
||||
size=len(content),
|
||||
s3_path=key,
|
||||
)
|
||||
db.add(asset)
|
||||
db.commit()
|
||||
db.refresh(asset)
|
||||
|
||||
# Check if this is an S3 v4 request - if so, return S3-compatible response
|
||||
if _is_s3_v4_request(request):
|
||||
# S3 PutObject response: return 200 with ETag header and empty body
|
||||
# ETag should be the MD5 hash of the object
|
||||
etag = hashlib.md5(content).hexdigest()
|
||||
|
||||
return Response(
|
||||
status_code=200,
|
||||
headers={
|
||||
"ETag": f'"{etag}"',
|
||||
"x-amz-version-id": str(asset.id),
|
||||
}
|
||||
)
|
||||
else:
|
||||
# Legacy JSON response for bearer token requests
|
||||
return {
|
||||
"object_id": asset.id,
|
||||
"key": key,
|
||||
"size": len(content),
|
||||
"filename": asset.filename,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{bucket}/{key:path}")
|
||||
async def download_file(
|
||||
bucket: str,
|
||||
key: str,
|
||||
request: Request = None,
|
||||
current_user: User = Depends(get_current_user_s3),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
# Verify user is uploading to their own bucket
|
||||
if bucket != current_user.get_bucket_name():
|
||||
raise HTTPException(status_code=403, detail="Cannot upload to another user's bucket")
|
||||
|
||||
# Retrieve file
|
||||
storage = get_storage()
|
||||
content = storage.get_object(current_user.id, key)
|
||||
|
||||
if content is None:
|
||||
raise HTTPException(status_code=404, detail="Object not found")
|
||||
|
||||
# Return as binary content
|
||||
from fastapi.responses import Response
|
||||
return Response(content=content, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.delete("/{bucket}/{key:path}")
|
||||
async def delete_file(
|
||||
bucket: str,
|
||||
key: str,
|
||||
request: Request = None,
|
||||
current_user: User = Depends(get_current_user_s3),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
# Verify user is uploading to their own bucket
|
||||
if bucket != current_user.get_bucket_name():
|
||||
raise HTTPException(status_code=403, detail="Cannot upload to another user's bucket")
|
||||
|
||||
# Delete from storage
|
||||
storage = get_storage()
|
||||
if not storage.delete_object(current_user.id, key):
|
||||
raise HTTPException(status_code=404, detail="Object not found")
|
||||
|
||||
# Delete from database
|
||||
db.query(UploadedAsset).filter(
|
||||
UploadedAsset.user_id == current_user.id,
|
||||
UploadedAsset.s3_path == key,
|
||||
).delete()
|
||||
db.commit()
|
||||
|
||||
return {"message": "Object deleted"}
|
||||
|
||||
|
||||
@router.get("/{bucket}")
|
||||
async def list_objects(
|
||||
bucket: str,
|
||||
prefix: str = Query(""),
|
||||
delimiter: str = Query(""),
|
||||
request: Request = None,
|
||||
current_user: User = Depends(get_current_user_s3),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
# Verify user is uploading to their own bucket
|
||||
if bucket != current_user.get_bucket_name():
|
||||
raise HTTPException(status_code=403, detail="Cannot upload to another user's bucket")
|
||||
|
||||
# List objects
|
||||
storage = get_storage()
|
||||
objects = storage.list_objects(current_user.id, prefix, delimiter)
|
||||
|
||||
return {
|
||||
"bucket": current_user.get_bucket_name(),
|
||||
"prefix": prefix,
|
||||
"contents": [{"key": key} for key in objects],
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
"""API key management endpoints."""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
|
||||
from privatestudio.web.database import get_db
|
||||
from privatestudio.web.models import User, APIKey
|
||||
from privatestudio.web.auth import get_current_user, create_api_key, revoke_api_key
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class APIKeyCreate(BaseModel):
|
||||
"""Request model for creating an API key."""
|
||||
pass # No parameters needed
|
||||
|
||||
|
||||
class APIKeyResponse(BaseModel):
|
||||
"""Response model for API key."""
|
||||
id: int
|
||||
created_at: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class APIKeyCreateResponse(APIKeyResponse):
|
||||
"""Response model for creating an API key (includes the plain key)."""
|
||||
key: str
|
||||
|
||||
|
||||
class APIKeyList(BaseModel):
|
||||
"""Response model for listing API keys."""
|
||||
id: int
|
||||
created_at: str
|
||||
is_active: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
@router.post("/keys", response_model=APIKeyCreateResponse)
|
||||
def create_api_key_endpoint(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Create a new API key for the authenticated user."""
|
||||
plain_key, api_key_record = create_api_key(db, current_user.id)
|
||||
return APIKeyCreateResponse(
|
||||
id=api_key_record.id,
|
||||
key=plain_key,
|
||||
created_at=api_key_record.created_at.isoformat(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/keys", response_model=list[APIKeyList])
|
||||
def list_api_keys(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all API keys for the authenticated user."""
|
||||
keys = db.query(APIKey).filter(APIKey.user_id == current_user.id).all()
|
||||
return [
|
||||
APIKeyList(
|
||||
id=key.id,
|
||||
created_at=key.created_at.isoformat(),
|
||||
is_active=key.is_active,
|
||||
)
|
||||
for key in keys
|
||||
]
|
||||
|
||||
|
||||
@router.delete("/keys/{key_id}")
|
||||
def revoke_api_key_endpoint(
|
||||
key_id: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Revoke an API key (mark it as inactive)."""
|
||||
# Verify the key belongs to the current user
|
||||
api_key = db.query(APIKey).filter(APIKey.id == key_id).first()
|
||||
if not api_key:
|
||||
raise HTTPException(status_code=404, detail="API key not found")
|
||||
|
||||
if api_key.user_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="Cannot revoke someone else's API key")
|
||||
|
||||
revoke_api_key(db, key_id)
|
||||
return {"message": "API key revoked"}
|
||||
@@ -1,118 +0,0 @@
|
||||
"""Transcode profile management endpoints."""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
import yaml
|
||||
|
||||
from privatestudio.web.database import get_db
|
||||
from privatestudio.web.models import User, TranscodeProfile
|
||||
from privatestudio.web.auth import get_current_user
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class ProfileResponse(BaseModel):
|
||||
"""Response model for transcode profile."""
|
||||
id: int
|
||||
name: str
|
||||
profile_definition: str
|
||||
created_at: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
@router.post("/profiles")
|
||||
def create_profile(
|
||||
name: str,
|
||||
body: str, # Raw YAML body
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Create a new transcode profile.
|
||||
|
||||
The request body should contain the YAML profile definition.
|
||||
"""
|
||||
# Validate YAML
|
||||
try:
|
||||
profile_data = yaml.safe_load(body)
|
||||
if not isinstance(profile_data, dict):
|
||||
raise ValueError("Profile definition must be a YAML mapping")
|
||||
if "profiles" not in profile_data:
|
||||
raise ValueError("Profile definition must contain a 'profiles' section")
|
||||
except yaml.YAMLError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid YAML: {e}")
|
||||
|
||||
# Check if profile name already exists for this user
|
||||
existing = db.query(TranscodeProfile).filter(
|
||||
TranscodeProfile.user_id == current_user.id,
|
||||
TranscodeProfile.name == name,
|
||||
).first()
|
||||
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"Profile '{name}' already exists",
|
||||
)
|
||||
|
||||
# Create profile
|
||||
profile = TranscodeProfile(
|
||||
user_id=current_user.id,
|
||||
name=name,
|
||||
profile_definition=body,
|
||||
)
|
||||
db.add(profile)
|
||||
db.commit()
|
||||
db.refresh(profile)
|
||||
|
||||
return ProfileResponse(
|
||||
id=profile.id,
|
||||
name=profile.name,
|
||||
profile_definition=profile.profile_definition,
|
||||
created_at=profile.created_at.isoformat(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/profiles", response_model=list[ProfileResponse])
|
||||
def list_profiles(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all transcode profiles for the current user."""
|
||||
profiles = db.query(TranscodeProfile).filter(
|
||||
TranscodeProfile.user_id == current_user.id
|
||||
).all()
|
||||
|
||||
return [
|
||||
ProfileResponse(
|
||||
id=p.id,
|
||||
name=p.name,
|
||||
profile_definition=p.profile_definition,
|
||||
created_at=p.created_at.isoformat(),
|
||||
)
|
||||
for p in profiles
|
||||
]
|
||||
|
||||
|
||||
@router.get("/profiles/{profile_id}", response_model=ProfileResponse)
|
||||
def get_profile(
|
||||
profile_id: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get a specific transcode profile."""
|
||||
profile = db.query(TranscodeProfile).filter(
|
||||
TranscodeProfile.id == profile_id,
|
||||
TranscodeProfile.user_id == current_user.id,
|
||||
).first()
|
||||
|
||||
if not profile:
|
||||
raise HTTPException(status_code=404, detail="Profile not found")
|
||||
|
||||
return ProfileResponse(
|
||||
id=profile.id,
|
||||
name=profile.name,
|
||||
profile_definition=profile.profile_definition,
|
||||
created_at=profile.created_at.isoformat(),
|
||||
)
|
||||
@@ -1,41 +0,0 @@
|
||||
"""S3 credential generation endpoint."""
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from privatestudio.web.database import get_db
|
||||
from privatestudio.web.models import User
|
||||
from privatestudio.web.auth import get_current_user
|
||||
from privatestudio.web.s3_credentials import create_s3_credential
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/s3keys")
|
||||
async def generate_s3_keys(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Generate temporary AWS v4 signature credentials for S3 access.
|
||||
|
||||
Credentials expire after 1 hour.
|
||||
Requires authentication via bearer token.
|
||||
|
||||
Returns:
|
||||
access_key: AWS-like access key for signing requests
|
||||
secret_key: Secret key for signing requests (only returned here)
|
||||
expires_at: ISO 8601 timestamp when credentials expire
|
||||
"""
|
||||
access_key, secret_key = create_s3_credential(db, current_user.id, ttl_hours=1)
|
||||
|
||||
# Get the credential to access expires_at
|
||||
from privatestudio.web.models import S3Credential
|
||||
credential = db.query(S3Credential).filter(
|
||||
S3Credential.access_key == access_key
|
||||
).first()
|
||||
|
||||
return {
|
||||
"access_key": access_key,
|
||||
"secret_key": secret_key,
|
||||
"expires_at": credential.expires_at.isoformat(),
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
"""YAML-based transcode job request endpoints."""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
import yaml
|
||||
|
||||
from privatestudio.web.database import get_db
|
||||
from privatestudio.web.models import User, TranscodeJob, UploadedAsset, TranscodeProfile
|
||||
from privatestudio.web.auth import get_current_user
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class TranscodeJobResponse(BaseModel):
|
||||
"""Response model for transcode job."""
|
||||
id: int
|
||||
asset_id: int
|
||||
profile_id: int | None
|
||||
status: str
|
||||
requested_at: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
@router.post("/transcode")
|
||||
def request_transcode(
|
||||
body: str, # Raw YAML body
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Request a transcode job with YAML definition.
|
||||
|
||||
The request body should contain YAML like:
|
||||
```yaml
|
||||
asset: "video.mp4" # Asset name or ID
|
||||
profile: "hd-profile" # Profile name, or inline profile definition
|
||||
```
|
||||
|
||||
Or with inline profile:
|
||||
```yaml
|
||||
asset: "video.mp4"
|
||||
profile:
|
||||
profiles:
|
||||
hd:
|
||||
resolution: "1280x720"
|
||||
bitrate: "2500k"
|
||||
```
|
||||
"""
|
||||
# Parse YAML
|
||||
try:
|
||||
request_data = yaml.safe_load(body)
|
||||
if not isinstance(request_data, dict):
|
||||
raise ValueError("Request must be a YAML mapping")
|
||||
except yaml.YAMLError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid YAML: {e}")
|
||||
|
||||
# Get asset
|
||||
asset_ref = request_data.get("asset")
|
||||
if not asset_ref:
|
||||
raise HTTPException(status_code=400, detail="Request must specify 'asset'")
|
||||
|
||||
# Try to find asset by name or ID
|
||||
asset = None
|
||||
try:
|
||||
asset_id = int(asset_ref)
|
||||
asset = db.query(UploadedAsset).filter(
|
||||
UploadedAsset.id == asset_id,
|
||||
UploadedAsset.user_id == current_user.id,
|
||||
).first()
|
||||
except ValueError:
|
||||
# Not an ID, try as filename
|
||||
asset = db.query(UploadedAsset).filter(
|
||||
UploadedAsset.filename == asset_ref,
|
||||
UploadedAsset.user_id == current_user.id,
|
||||
).first()
|
||||
|
||||
if not asset:
|
||||
raise HTTPException(status_code=404, detail=f"Asset '{asset_ref}' not found")
|
||||
|
||||
# Get or validate profile
|
||||
profile_ref = request_data.get("profile")
|
||||
if not profile_ref:
|
||||
raise HTTPException(status_code=400, detail="Request must specify 'profile'")
|
||||
|
||||
profile_id = None
|
||||
profile_definition = None
|
||||
|
||||
if isinstance(profile_ref, str):
|
||||
# Profile name reference
|
||||
profile = db.query(TranscodeProfile).filter(
|
||||
TranscodeProfile.name == profile_ref,
|
||||
TranscodeProfile.user_id == current_user.id,
|
||||
).first()
|
||||
|
||||
if not profile:
|
||||
raise HTTPException(status_code=404, detail=f"Profile '{profile_ref}' not found")
|
||||
|
||||
profile_id = profile.id
|
||||
profile_definition = profile.profile_definition
|
||||
elif isinstance(profile_ref, dict):
|
||||
# Inline profile definition
|
||||
try:
|
||||
# Validate it has a 'profiles' section
|
||||
if "profiles" not in profile_ref:
|
||||
raise ValueError("Inline profile must contain a 'profiles' section")
|
||||
profile_definition = yaml.dump(profile_ref)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid profile definition: {e}")
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="Profile must be a string (name) or object (definition)")
|
||||
|
||||
# Create transcode job
|
||||
job = TranscodeJob(
|
||||
user_id=current_user.id,
|
||||
asset_id=asset.id,
|
||||
profile_id=profile_id,
|
||||
status="pending",
|
||||
)
|
||||
db.add(job)
|
||||
db.commit()
|
||||
db.refresh(job)
|
||||
|
||||
return TranscodeJobResponse(
|
||||
id=job.id,
|
||||
asset_id=job.asset_id,
|
||||
profile_id=job.profile_id,
|
||||
status=job.status,
|
||||
requested_at=job.requested_at.isoformat(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/transcode/{job_id}", response_model=TranscodeJobResponse)
|
||||
def get_transcode_job(
|
||||
job_id: int,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get status of a transcode job."""
|
||||
job = db.query(TranscodeJob).filter(
|
||||
TranscodeJob.id == job_id,
|
||||
TranscodeJob.user_id == current_user.id,
|
||||
).first()
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found")
|
||||
|
||||
return TranscodeJobResponse(
|
||||
id=job.id,
|
||||
asset_id=job.asset_id,
|
||||
profile_id=job.profile_id,
|
||||
status=job.status,
|
||||
requested_at=job.requested_at.isoformat(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/transcode", response_model=list[TranscodeJobResponse])
|
||||
def list_transcode_jobs(
|
||||
status: str | None = None,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List transcode jobs for the current user."""
|
||||
query = db.query(TranscodeJob).filter(TranscodeJob.user_id == current_user.id)
|
||||
|
||||
if status:
|
||||
query = query.filter(TranscodeJob.status == status)
|
||||
|
||||
jobs = query.all()
|
||||
|
||||
return [
|
||||
TranscodeJobResponse(
|
||||
id=job.id,
|
||||
asset_id=job.asset_id,
|
||||
profile_id=job.profile_id,
|
||||
status=job.status,
|
||||
requested_at=job.requested_at.isoformat(),
|
||||
)
|
||||
for job in jobs
|
||||
]
|
||||
@@ -1,28 +0,0 @@
|
||||
"""User information routes."""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
import yaml
|
||||
|
||||
from privatestudio.web.database import get_db
|
||||
from privatestudio.web.models import User, TranscodeJob, UploadedAsset, TranscodeProfile
|
||||
from privatestudio.web.auth import get_current_user
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/userinfo")
|
||||
async def get_user_info(
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Get user information for the current user."""
|
||||
user_id = current_user.id
|
||||
bucket_name = f"user-{user_id}"
|
||||
|
||||
return {
|
||||
"bucket": bucket_name,
|
||||
"user_id": user_id,
|
||||
"username": current_user.username,
|
||||
}
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
"""S3-compatible file storage handler."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class S3FileStorage:
|
||||
"""Local file storage backend with S3-compatible interface."""
|
||||
|
||||
def __init__(self, base_path: str = "./storage"):
|
||||
"""Initialize storage with base path."""
|
||||
self.base_path = Path(base_path)
|
||||
self.base_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _get_user_path(self, user_id: int) -> Path:
|
||||
"""Get the storage path for a user."""
|
||||
user_path = self.base_path / str(user_id)
|
||||
user_path.mkdir(parents=True, exist_ok=True)
|
||||
return user_path
|
||||
|
||||
def _get_file_path(self, user_id: int, key: str) -> Path:
|
||||
"""Get the full file path for a key, ensuring it's within user directory."""
|
||||
user_path = self._get_user_path(user_id)
|
||||
user_path_resolved = user_path.resolve()
|
||||
file_path = (user_path / key).resolve()
|
||||
|
||||
# Security check: ensure file is within user directory
|
||||
if not str(file_path).startswith(str(user_path_resolved)):
|
||||
raise ValueError(f"Invalid key: {key}")
|
||||
|
||||
return file_path
|
||||
|
||||
def put_object(self, user_id: int, key: str, data: bytes) -> None:
|
||||
"""Store a file."""
|
||||
file_path = self._get_file_path(user_id, key)
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
file_path.write_bytes(data)
|
||||
|
||||
def get_object(self, user_id: int, key: str) -> Optional[bytes]:
|
||||
"""Retrieve a file."""
|
||||
file_path = self._get_file_path(user_id, key)
|
||||
if file_path.exists():
|
||||
return file_path.read_bytes()
|
||||
return None
|
||||
|
||||
def delete_object(self, user_id: int, key: str) -> bool:
|
||||
"""Delete a file. Returns True if deleted, False if not found."""
|
||||
file_path = self._get_file_path(user_id, key)
|
||||
if file_path.exists():
|
||||
file_path.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
def list_objects(self, user_id: int, prefix: str = "", delimiter: str = "") -> list[str]:
|
||||
"""List objects for a user, optionally with prefix/delimiter."""
|
||||
user_path = self._get_user_path(user_id)
|
||||
|
||||
if delimiter == "/":
|
||||
# Return only direct children
|
||||
items = []
|
||||
for item in user_path.iterdir():
|
||||
rel_path = item.relative_to(user_path).as_posix()
|
||||
if item.is_dir():
|
||||
rel_path += "/"
|
||||
if not prefix or rel_path.startswith(prefix):
|
||||
items.append(rel_path)
|
||||
return sorted(items)
|
||||
else:
|
||||
# Recursively list all files
|
||||
items = []
|
||||
for item in user_path.rglob("*"):
|
||||
if item.is_file():
|
||||
rel_path = item.relative_to(user_path).as_posix()
|
||||
if not prefix or rel_path.startswith(prefix):
|
||||
items.append(rel_path)
|
||||
return sorted(items)
|
||||
|
||||
def get_object_size(self, user_id: int, key: str) -> Optional[int]:
|
||||
"""Get the size of a file in bytes."""
|
||||
file_path = self._get_file_path(user_id, key)
|
||||
if file_path.exists():
|
||||
return file_path.stat().st_size
|
||||
return None
|
||||
|
||||
def object_exists(self, user_id: int, key: str) -> bool:
|
||||
"""Check if an object exists."""
|
||||
file_path = self._get_file_path(user_id, key)
|
||||
return file_path.exists()
|
||||
|
||||
|
||||
# Global storage instance
|
||||
_storage_instance: Optional[S3FileStorage] = None
|
||||
|
||||
|
||||
def get_storage() -> S3FileStorage:
|
||||
"""Get or create the global storage instance."""
|
||||
global _storage_instance
|
||||
if _storage_instance is None:
|
||||
base_path = os.environ.get("STORAGE_PATH", "./storage")
|
||||
_storage_instance = S3FileStorage(base_path)
|
||||
return _storage_instance
|
||||
@@ -0,0 +1,8 @@
|
||||
"""WSGI config for the privatestudio project."""
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "privatestudio.settings.dev")
|
||||
|
||||
application = get_wsgi_application()
|
||||
+10
-11
@@ -6,14 +6,13 @@ build-backend = "setuptools.build_meta"
|
||||
name = "privatestudio"
|
||||
description = "Video transcoding tools with multi-profile H.264 encoding support"
|
||||
readme = "notes.md"
|
||||
requires-python = ">=3.8"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"PyYAML>=6.0",
|
||||
"FastAPI>=0.100.0",
|
||||
"uvicorn[standard]>=0.23.0",
|
||||
"SQLAlchemy>=2.0.0",
|
||||
"Alembic>=1.13.0",
|
||||
"python-multipart>=0.0.5",
|
||||
"Django~=6.1.0",
|
||||
"django-ninja~=1.8",
|
||||
"django-cors-headers~=4.9",
|
||||
"dj-database-url~=3.1",
|
||||
]
|
||||
dynamic = ["version"]
|
||||
|
||||
@@ -21,20 +20,20 @@ dynamic = ["version"]
|
||||
dev = [
|
||||
"pytest>=7.0",
|
||||
"pytest-cov>=4.0",
|
||||
"httpx>=0.27.0",
|
||||
"pytest-django>=4.14",
|
||||
"boto3",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
ps-transcode = "privatestudio.transcode:main"
|
||||
ps-serve = "privatestudio.web.cli:main"
|
||||
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["privatestudio*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"privatestudio.migrations" = ["script.py.mako"]
|
||||
|
||||
[tool.setuptools_scm]
|
||||
write_to = "privatestudio/_version.py"
|
||||
fallback_version = "0.1.0-dev"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
DJANGO_SETTINGS_MODULE = "privatestudio.settings.dev"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
"""Tests for privatestudio."""
|
||||
@@ -1,357 +0,0 @@
|
||||
"""Integration tests for the video transcoding web service."""
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from privatestudio.web.app import app
|
||||
from privatestudio.web.database import get_db
|
||||
from privatestudio.web.models import Base
|
||||
from privatestudio.web.auth import create_user, create_api_key
|
||||
|
||||
|
||||
# Use in-memory SQLite for testing with StaticPool
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:",
|
||||
connect_args={"check_same_thread": False},
|
||||
poolclass=StaticPool,
|
||||
)
|
||||
|
||||
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def override_get_db():
|
||||
try:
|
||||
db = TestingSessionLocal()
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function", autouse=True)
|
||||
def reset_db():
|
||||
"""Reset database before each test and clean up storage."""
|
||||
import shutil
|
||||
import os
|
||||
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Clean up storage directory
|
||||
storage_path = "./storage"
|
||||
if os.path.exists(storage_path):
|
||||
shutil.rmtree(storage_path)
|
||||
|
||||
yield
|
||||
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
|
||||
# Clean up storage directory after test
|
||||
if os.path.exists(storage_path):
|
||||
shutil.rmtree(storage_path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_user_and_key():
|
||||
"""Create a test user and API key."""
|
||||
db = TestingSessionLocal()
|
||||
try:
|
||||
user = create_user(db, "testuser")
|
||||
plain_key, api_key = create_api_key(db, user.id)
|
||||
user_id = user.id # Store before closing session
|
||||
username = user.username # Store before closing session
|
||||
return user_id, username, plain_key
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def test_health_check():
|
||||
"""Test health check endpoint."""
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_create_api_key(test_user_and_key):
|
||||
"""Test creating an API key via endpoint."""
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
response = client.post(
|
||||
"/api/keys",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "id" in data
|
||||
assert "key" in data
|
||||
assert "created_at" in data
|
||||
|
||||
|
||||
def test_list_api_keys(test_user_and_key):
|
||||
"""Test listing API keys."""
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
response = client.get(
|
||||
"/api/keys",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert len(data) > 0
|
||||
assert data[0]["is_active"] is True
|
||||
|
||||
|
||||
def test_authentication_required():
|
||||
"""Test that endpoints require authentication."""
|
||||
response = client.get("/api/keys")
|
||||
assert response.status_code in [401, 403] # Accept both
|
||||
|
||||
|
||||
def test_invalid_api_key():
|
||||
"""Test invalid API key."""
|
||||
response = client.get(
|
||||
"/api/keys",
|
||||
headers={"Authorization": "Bearer invalid_key"},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_upload_file(test_user_and_key):
|
||||
"""Test file upload to S3 interface."""
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
# Upload a file
|
||||
response = client.put(
|
||||
f"/s3/{username}/test.mp4",
|
||||
files={"file": ("test.mp4", b"test file content", "video/mp4")},
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["key"] == "test.mp4"
|
||||
assert data["size"] == len(b"test file content")
|
||||
|
||||
|
||||
def test_download_file(test_user_and_key):
|
||||
"""Test file download from S3 interface."""
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
# Upload a file first
|
||||
client.put(
|
||||
f"/s3/{username}/test.mp4",
|
||||
files={"file": ("test.mp4", b"test file content", "video/mp4")},
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
|
||||
# Download it
|
||||
response = client.get(
|
||||
f"/s3/{username}/test.mp4",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.content == b"test file content"
|
||||
|
||||
|
||||
def test_delete_file(test_user_and_key):
|
||||
"""Test file deletion from S3 interface."""
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
# Upload a file first
|
||||
client.put(
|
||||
f"/s3/{username}/test.mp4",
|
||||
files={"file": ("test.mp4", b"test file content", "video/mp4")},
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
|
||||
# Delete it
|
||||
response = client.delete(
|
||||
f"/s3/{username}/test.mp4",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
# Verify it's gone
|
||||
response = client.get(
|
||||
f"/s3/{username}/test.mp4",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_list_objects(test_user_and_key):
|
||||
"""Test listing objects in S3 bucket."""
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
# Upload a couple files
|
||||
client.put(
|
||||
f"/s3/{username}/test1.mp4",
|
||||
files={"file": ("test1.mp4", b"content1", "video/mp4")},
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
client.put(
|
||||
f"/s3/{username}/test2.mp4",
|
||||
files={"file": ("test2.mp4", b"content2", "video/mp4")},
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
|
||||
# List objects
|
||||
response = client.get(
|
||||
f"/s3/{username}",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["contents"]) == 2
|
||||
|
||||
|
||||
def test_per_user_isolation(test_user_and_key):
|
||||
"""Test that users can't access each other's resources."""
|
||||
user1_id, username1, key1 = test_user_and_key
|
||||
|
||||
# Create second user
|
||||
db = TestingSessionLocal()
|
||||
try:
|
||||
user2 = create_user(db, "testuser2")
|
||||
plain_key2, _ = create_api_key(db, user2.id)
|
||||
user2_id = user2.id
|
||||
username2 = user2.username
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# User1 uploads a file
|
||||
client.put(
|
||||
f"/s3/{username1}/private.mp4",
|
||||
files={"file": ("private.mp4", b"user1 content", "video/mp4")},
|
||||
headers={"Authorization": f"Bearer {key1}"},
|
||||
)
|
||||
|
||||
# User2 tries to download user1's file
|
||||
response = client.get(
|
||||
f"/s3/{username1}/private.mp4",
|
||||
headers={"Authorization": f"Bearer {plain_key2}"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
|
||||
|
||||
def test_generate_s3_credentials(test_user_and_key):
|
||||
"""Test S3 credential generation endpoint."""
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
# Request S3 credentials
|
||||
response = client.post(
|
||||
"/api/s3keys",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
# Verify response contains credentials
|
||||
assert "access_key" in data
|
||||
assert "secret_key" in data
|
||||
assert "expires_at" in data
|
||||
|
||||
# Verify credentials are valid format
|
||||
assert data["access_key"].startswith("AKIA")
|
||||
assert len(data["secret_key"]) >= 30 # AWS secret keys are 40 chars
|
||||
assert "T" in data["expires_at"] # ISO 8601 timestamp
|
||||
|
||||
# Verify different calls generate different credentials
|
||||
response2 = client.post(
|
||||
"/api/s3keys",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response2.status_code == 200
|
||||
data2 = response2.json()
|
||||
assert data["access_key"] != data2["access_key"]
|
||||
assert data["secret_key"] != data2["secret_key"]
|
||||
|
||||
|
||||
def test_upload_with_boto3_style_signature(test_user_and_key):
|
||||
"""Test S3 upload with boto3-style v4 signatures."""
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from privatestudio.web.models import S3Credential
|
||||
|
||||
user_id, username, plain_key = test_user_and_key
|
||||
|
||||
# Generate S3 credentials
|
||||
response = client.post(
|
||||
"/api/s3keys",
|
||||
headers={"Authorization": f"Bearer {plain_key}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
s3_creds = response.json()
|
||||
access_key = s3_creds["access_key"]
|
||||
secret_key = s3_creds["secret_key"]
|
||||
|
||||
# Create boto3 client configured for S3-compatible API
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url="http://testserver/s3",
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
region_name="us-east-1",
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
# Use boto3 to upload a file (this will sign the request with v4 signature)
|
||||
try:
|
||||
# Note: boto3 will make a PUT request to /s3/user-{id}/test.mp4
|
||||
# with an AWS v4 signature header
|
||||
with client:
|
||||
# Mock the S3 PUT request through our app
|
||||
bucket_name = f"user-{user_id}"
|
||||
test_data = b"test file content from boto3"
|
||||
|
||||
# Manually create a signed request to test
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.auth import SigV4Auth
|
||||
|
||||
url = f"http://testserver/s3/{bucket_name}/boto3-test.mp4"
|
||||
request = AWSRequest(method="PUT", url=url, data=test_data)
|
||||
|
||||
# Get credentials for signing
|
||||
from botocore.credentials import Credentials
|
||||
credentials = Credentials(access_key, secret_key)
|
||||
|
||||
# Sign the request
|
||||
SigV4Auth(credentials, 's3', 'us-east-1').add_auth(request)
|
||||
|
||||
# Extract the Authorization header
|
||||
auth_header = request.headers.get('Authorization', '')
|
||||
|
||||
# Make the actual request through our test client
|
||||
response = client.put(
|
||||
f"/s3/{bucket_name}/boto3-test.mp4",
|
||||
content=test_data,
|
||||
headers={
|
||||
"Authorization": auth_header,
|
||||
"X-Amz-Date": request.headers.get('X-Amz-Date', ''),
|
||||
"X-Amz-Content-Sha256": request.headers.get('X-Amz-Content-Sha256', ''),
|
||||
"Host": request.headers.get('Host', 'testserver'),
|
||||
},
|
||||
)
|
||||
|
||||
# Should succeed with v4 signature (S3 compatible response: just headers, no JSON body)
|
||||
assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"
|
||||
# S3 v4 response includes ETag header instead of JSON body
|
||||
assert "ETag" in response.headers or len(response.text) > 0, "Response should have ETag header or JSON body"
|
||||
|
||||
except Exception as e:
|
||||
# If boto3 is not available or there's an error, skip gracefully
|
||||
import pytest
|
||||
pytest.skip(f"Boto3 integration test skipped: {e}")
|
||||
Reference in New Issue
Block a user