feat(multitenancy): Implement white-label B2B portal infrastructure (#241)

## Summary

Adds multi-tenant white-label portal infrastructure for B2B customers.
Vocal Star is the first tenant at `vocalstar.nomadkaraoke.com`.

## Changes

### Backend
- **Tenant Models** (`backend/models/tenant.py`): Pydantic models for
TenantConfig with branding, features, defaults, and auth settings
- **Tenant Service** (`backend/services/tenant_service.py`): GCS-backed
config loading with 5-min cache, signed URL generation for logos
- **Tenant API** (`backend/api/routes/tenant.py`): `GET
/api/tenant/config` and `GET /api/tenant/config/{tenant_id}` endpoints
- **Tenant Middleware** (`backend/middleware/tenant.py`): Extracts
tenant from X-Tenant-ID header, query param (dev only), or Host
subdomain
- **Auth Updates**: Email domain validation for tenant-restricted auth,
sender email override
- **Feature Enforcement**: Audio search endpoint checks
`features.audio_search`, returns 403 if disabled
- **Job Scoping**: Added `tenant_id` field to JobCreate

### Frontend
- **Tenant Store** (`frontend/lib/tenant.ts`): Zustand store with tenant
state, `useTenant()` hook, CSS variable application
- **TenantProvider** (`frontend/components/tenant-provider.tsx`):
Hydration-safe initialization via useEffect
- **TenantLogo** (`frontend/components/tenant-logo.tsx`): Dynamic logo
with fallback to Nomad Karaoke
- **Feature-Flagged UI**: Tabs conditionally rendered based on tenant
features, active tab sync
- **Locked Themes**: `defaults.locked_theme` hides theme selector and
enforces specific theme
- **Output Links**: Filtered based on distribution features

### Security
- Query param tenant detection disabled in production (prevents
spoofing)
- Strict subdomain patterns: only `{tenant}.nomadkaraoke.com` or
`{tenant}.gen.nomadkaraoke.com`
- PII masking in logs (`an***@vo***.com`)
- `is_active` check prevents inactive tenants from being used

### Documentation
- ARCHITECTURE.md: New Multitenancy section
- API.md: Tenant Config endpoints
- LESSONS-LEARNED.md: 3 new lessons on multitenancy patterns
- Archive: Comprehensive implementation document

### Setup
- `scripts/setup-vocalstar-tenant.py`: Uploads theme assets, creates
tenant/theme configs in GCS

## Vocal Star Configuration

- **Subdomain**: `vocalstar.nomadkaraoke.com`
- **Features**: File upload only (no audio search, no YouTube URL)
- **Distribution**: Download only (no YouTube/Dropbox/GDrive)
- **Theme**: Locked to "vocalstar" (yellow/blue)
- **Auth**: Restricted to `@vocal-star.com` and `@vocalstarmusic.com`
emails

## Testing

- [x] Frontend TypeScript build passes
- [x] CodeRabbit CLI review completed (3 cycles, all issues fixed)
- [x] Manual testing with `?tenant=vocalstar` query param

## Next Steps (post-merge)

1. Configure DNS: CNAME for `vocalstar.nomadkaraoke.com`
2. Update Cloudflare Pages for subdomain
3. Run setup script to upload Vocal Star assets to GCS
4. Test at `https://vocalstar.nomadkaraoke.com`

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Andrew Beveridge ☄️andClaude Opus 4.5 authored and GitHub committed 2026-01-08 16:39:56 -05:00
1 parent b39f37610c
commit 42c304dcdf
39 files changed
+4778 -87

No files matched your search

+317
View File
@@ -0,0 +1,317 @@
# Plan: White Label B2B Karaoke Portals
**Created:** 2026-01-08
**Branch:** feat/sess-20260108-0358-white-label-portal
**Status:** Draft
## Overview
Add multi-tenant white label portal capability to karaoke-gen, enabling B2B customers like Vocal Star to access a customized version of the generator app on their own subdomain with their branding, theme, and restricted feature set.
**First customer: Vocal Star**
- Subdomain: `vocalstar.nomadkaraoke.com`
- Workflow: Upload original + instrumental audio (no audio search)
- Theme: Custom Vocal Star karaoke theme (already exists as JSON)
- Distribution: Download only (no Dropbox/GDrive/YouTube)
- Auth: Magic link for `@vocal-star.com` / `@vocalstarmusic.com` domains, plus fixed API token option
## Requirements
### Functional Requirements
- [ ] Tenant identification via subdomain (e.g., `vocalstar.nomadkaraoke.com`)
- [ ] Per-tenant frontend branding (logo, colors, metadata)
- [ ] Per-tenant feature flags (hide audio search, hide distribution options)
- [ ] Per-tenant default theme (always use Vocal Star theme)
- [ ] Per-tenant allowed email domains for magic link auth
- [ ] Per-tenant fixed API token support (for automation)
- [ ] Jobs scoped to tenant (Vocal Star users only see Vocal Star jobs)
- [ ] Users scoped to tenant
### Non-Functional Requirements
- [ ] Minimal code duplication - single codebase serves all tenants
- [ ] Easy to add new tenants via config, not code changes
- [ ] Graceful fallback - default to Nomad Karaoke if no tenant match
- [ ] No performance impact on existing single-tenant flow
## Technical Approach
### Architecture Decision: Config-Driven Multi-Tenancy
Rather than building a full tenant management system (overkill for ~1 customer/year), we'll use a **config-driven approach**:
1. **Tenant configs stored in GCS** at `tenants/{tenant_id}/config.json`
2. **Frontend detects subdomain** and fetches tenant config from API
3. **Backend middleware** extracts tenant from request and applies config
4. **Firestore collections** get `tenant_id` field for isolation
This approach:
- Requires no database migrations for new tenants
- Configs can be managed via simple JSON files
- Easy to test locally with query param override (`?tenant=vocalstar`)
- Can evolve to admin UI later if needed
### Tenant Config Schema
```json
{
"id": "vocalstar",
"name": "Vocal Star",
"subdomain": "vocalstar.nomadkaraoke.com",
"branding": {
"logo_url": "gs://karaoke-gen-storage/tenants/vocalstar/logo.png",
"primary_color": "#ffff00",
"secondary_color": "#006CF9",
"favicon_url": "gs://karaoke-gen-storage/tenants/vocalstar/favicon.ico",
"site_title": "Vocal Star Karaoke Generator"
},
"features": {
"audio_search": false,
"file_upload": true,
"youtube_upload": false,
"dropbox_upload": false,
"gdrive_upload": false,
"theme_selection": false
},
"defaults": {
"theme_id": "vocalstar",
"distribution_mode": "download_only"
},
"auth": {
"allowed_email_domains": ["vocal-star.com", "vocalstarmusic.com"],
"fixed_tokens": ["<will be in Secret Manager>"]
}
}
```
### Key Implementation Details
#### 1. Subdomain Detection (Frontend)
- Next.js middleware checks `request.headers.host`
- If subdomain matches tenant, store tenant ID in cookie/context
- Fetch `/api/tenant/config` to get branding/features
- Apply CSS variables dynamically for colors
- Swap logo component based on config
#### 2. Tenant Middleware (Backend)
- FastAPI middleware extracts tenant from:
- `X-Tenant-ID` header (set by frontend)
- Or subdomain from `Host` header
- Or query param `?tenant=` (dev only)
- Attaches `tenant_id` to request state
- Tenant config loaded from GCS (cached 5 min like themes)
#### 3. Auth Enhancement
- `AuthService.validate_token_full()` already returns `user_email`
- Add tenant validation: check if user's email domain is in tenant's allowed list
- Support fixed tokens per tenant (stored in `auth_tokens` with `tenant_id`)
- Magic links include tenant context for proper redirect
#### 4. Data Isolation
- Add `tenant_id: Optional[str]` to User and Job models
- Default to `None` for existing Nomad Karaoke users (backwards compatible)
- Query filters: `where('tenant_id', '==', tenant_id or None)`
- No schema migration needed - new field, optional
#### 5. Theme Integration
- Upload Vocal Star theme to `themes/vocalstar/` in GCS
- Upload assets (backgrounds, fonts) to `themes/vocalstar/assets/`
- Tenant config specifies `default_theme_id: "vocalstar"`
- When `theme_selection: false`, UI hides theme picker and uses default
## Implementation Steps
### Phase 1: Backend Tenant Foundation (Day 1-2)
1. [ ] **Create tenant model and config loader**
- Create `backend/models/tenant.py` with `TenantConfig`, `TenantBranding`, `TenantFeatures`
- Create `backend/services/tenant_service.py` with GCS config loading and caching
- Add `GET /api/tenant/config` endpoint (unauthenticated, returns public config)
- Add `GET /api/tenant/config/{tenant_id}` for explicit tenant fetch
2. [ ] **Add tenant middleware**
- Create `backend/api/middleware/tenant.py`
- Extract tenant from subdomain or header
- Attach to `request.state.tenant_id` and `request.state.tenant_config`
- Add `get_tenant()` dependency for routes
3. [ ] **Update data models**
- Add `tenant_id: Optional[str] = None` to `User` model
- Add `tenant_id: Optional[str] = None` to `Job` model
- Update Firestore indexes in Pulumi for tenant-scoped queries
4. [ ] **Update auth for tenant awareness**
- Modify `AuthService` to validate email domain against tenant config
- Add tenant context to magic link generation
- Support per-tenant fixed tokens in `auth_tokens` collection
### Phase 2: Upload Vocal Star Theme (Day 2)
5. [ ] **Prepare Vocal Star theme for GCS**
- Convert local paths in `karaoke-prep-styles-vocalstar.json` to GCS paths
- Upload background images to `themes/vocalstar/assets/`
- Upload Oswald font to `themes/vocalstar/assets/`
- Upload `style_params.json` to `themes/vocalstar/`
- Create preview image and upload to `themes/vocalstar/preview.png`
- Add Vocal Star to `themes/_metadata.json`
6. [ ] **Create Vocal Star tenant config**
- Create `tenants/vocalstar/config.json` in GCS
- Upload Vocal Star logo to `tenants/vocalstar/logo.png`
- Upload favicon to `tenants/vocalstar/favicon.ico`
### Phase 3: Frontend Tenant Support (Day 3-4)
7. [ ] **Add tenant context provider**
- Create `frontend/lib/tenant.ts` with tenant config types
- Create `frontend/hooks/useTenant.ts` for tenant state
- Create `TenantProvider` component that fetches config on mount
- Detect subdomain in `_app.tsx` or middleware
8. [ ] **Dynamic branding**
- Create `TenantLogo` component that renders tenant or default logo
- Update `globals.css` to support CSS variable overrides
- Add `applyTenantColors()` function to set CSS variables from config
- Update page metadata (title, favicon) from tenant config
9. [ ] **Feature-flagged UI**
- Wrap audio search in `{tenant.features.audio_search && ...}`
- Wrap theme selector in `{tenant.features.theme_selection && ...}`
- Wrap distribution options based on tenant features
- Show simplified form for Vocal Star (just file upload fields)
10. [ ] **Update magic link flow**
- Pass tenant context when requesting magic link
- Magic link redirect goes to tenant subdomain
- Verify endpoint extracts tenant from link context
### Phase 4: Backend Feature Enforcement (Day 4-5)
11. [ ] **Enforce tenant features in API**
- Audio search endpoint: return 403 if `audio_search: false`
- File upload: check `file_upload: true`
- Distribution settings: ignore/error if disabled features requested
- Theme selection: use default if `theme_selection: false`
12. [ ] **Job creation with tenant context**
- `JobCreate` handler sets `tenant_id` from request state
- Distribution config respects tenant defaults
- Theme defaults to tenant's default theme
13. [ ] **Query scoping**
- Update `JobManager.get_jobs()` to filter by tenant_id
- Update `UserService` queries to include tenant_id
- Admin endpoints bypass tenant filter (see all tenants)
### Phase 5: Infrastructure & Deployment (Day 5-6)
14. [ ] **DNS setup**
- Add `vocalstar.nomadkaraoke.com` CNAME to Cloudflare
- Configure Cloudflare Pages to accept wildcard subdomain
- Add SSL certificate for subdomain
15. [ ] **Backend CORS update**
- Add `vocalstar.nomadkaraoke.com` to allowed origins
- Or use pattern matching for `*.nomadkaraoke.com`
16. [ ] **Pulumi updates**
- Add Firestore indexes for tenant_id queries
- Add any new secrets (tenant fixed tokens)
### Phase 6: Testing & Documentation (Day 6-7)
17. [ ] **Testing**
- Unit tests for TenantService config loading
- Unit tests for tenant middleware
- E2E test for Vocal Star flow (upload audio, generate, download)
- Test magic link works for @vocal-star.com email
18. [ ] **Documentation**
- Update CLAUDE.md with tenant info
- Create `docs/WHITE-LABEL.md` with tenant setup guide
- Document how to add new tenants
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/models/tenant.py` | Create | Tenant config models |
| `backend/services/tenant_service.py` | Create | Tenant config loading/caching |
| `backend/api/routes/tenant.py` | Create | Tenant config API endpoint |
| `backend/api/middleware/tenant.py` | Create | Tenant extraction middleware |
| `backend/api/dependencies.py` | Modify | Add `get_tenant()` dependency |
| `backend/models/user.py` | Modify | Add `tenant_id` field |
| `backend/models/job.py` | Modify | Add `tenant_id` field |
| `backend/services/auth_service.py` | Modify | Tenant email domain validation |
| `backend/services/user_service.py` | Modify | Tenant-aware user queries |
| `backend/services/job_manager.py` | Modify | Tenant-aware job queries |
| `backend/api/routes/file_upload.py` | Modify | Tenant feature enforcement |
| `backend/api/routes/audio_search.py` | Modify | Tenant feature enforcement |
| `backend/main.py` | Modify | Add tenant middleware |
| `frontend/lib/tenant.ts` | Create | Tenant types and API |
| `frontend/hooks/useTenant.ts` | Create | Tenant context hook |
| `frontend/components/TenantProvider.tsx` | Create | Tenant context provider |
| `frontend/components/TenantLogo.tsx` | Create | Dynamic logo component |
| `frontend/app/layout.tsx` | Modify | Add TenantProvider |
| `frontend/app/globals.css` | Modify | CSS variable support for tenant colors |
| `frontend/app/app/page.tsx` | Modify | Feature-flag UI sections |
| `infrastructure/__main__.py` | Modify | Add tenant Firestore indexes |
| `docs/WHITE-LABEL.md` | Create | Tenant setup documentation |
## Testing Strategy
### Unit Tests
- `TenantService`: Config loading, caching, validation
- `TenantMiddleware`: Subdomain extraction, header extraction
- `AuthService`: Tenant email domain validation
- `JobManager`: Tenant-scoped queries
### Integration Tests (Emulator)
- Create job with tenant context
- Query jobs filtered by tenant
- Auth with tenant-allowed email domain
- Auth rejection for wrong email domain
### E2E Tests
- Vocal Star happy path: Upload audio files, review lyrics, download video
- Auth flow: Magic link for @vocal-star.com, verify redirect to subdomain
- Feature hiding: Verify audio search not shown on Vocal Star portal
## Open Questions
- [x] **Q: Should tenant configs be in GCS or Firestore?**
A: GCS - simpler, matches theme pattern, easy to edit JSON directly
- [x] **Q: How to handle localhost development for specific tenant?**
A: Query param override `?tenant=vocalstar` for local testing
- [x] **Q: Should admin portal be tenant-aware?**
A: No - admins see all tenants. Admin routes bypass tenant filter.
- [x] **Q: Do we need tenant-specific email sender identity?**
A: Yes - use `{tenant}@nomadkaraoke.com` (e.g., `vocalstar@nomadkaraoke.com`). Catchall is configured.
- [x] **Q: Vocal Star logo and favicon - do you have these assets?**
A: Logo provided as `vocalstar-logo.jpg` - yellow star, white text on black. Will convert to PNG with transparency for web use.
## Rollback Plan
Since this is additive (new optional `tenant_id` field), rollback is straightforward:
1. Revert frontend to not check tenant
2. Revert backend middleware to not extract tenant
3. Existing data unaffected (tenant_id = null = Nomad Karaoke)
4. No schema migration to reverse
For DNS: Simply remove CNAME record if needed.
## Success Criteria
- [ ] Vocal Star user can access `vocalstar.nomadkaraoke.com`
- [ ] Portal shows Vocal Star branding (logo, colors)
- [ ] Audio search is hidden; only file upload available
- [ ] Theme is locked to Vocal Star style
- [ ] Distribution options hidden; download only
- [ ] Magic link works for @vocal-star.com emails
- [ ] Fixed API token works for automation
- [ ] Generated videos use Vocal Star theme
- [ ] Nomad Karaoke portal unchanged at gen.nomadkaraoke.com
+13 -2
View File
@@ -38,6 +38,7 @@ from backend.config import get_settings
from backend.version import VERSION
from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType, AuthResult
from backend.middleware.tenant import get_tenant_config_from_request
from pathlib import Path
logger = logging.getLogger(__name__)
@@ -479,17 +480,25 @@ async def search_audio(
):
"""
Search for audio by artist and title, creating a new job.
This endpoint:
1. Creates a job in PENDING state
2. Searches for audio using flacfetch
3. Either returns search results for user selection, or
4. If auto_download=True, automatically selects best and starts processing
Use cases:
- Interactive mode (default): Returns results, user calls /select endpoint
- Auto mode (auto_download=True): Automatically selects and downloads best
"""
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(
status_code=403,
detail="Audio search is not available for this portal"
)
try:
# Apply default distribution settings
settings = get_settings()
@@ -585,6 +594,8 @@ async def search_audio(
auto_download=body.auto_download,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
+42 -1
View File
@@ -34,6 +34,7 @@ from backend.version import VERSION
from backend.services.metrics import metrics
from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType, AuthResult
from backend.middleware.tenant import get_tenant_config_from_request
logger = logging.getLogger(__name__)
router = APIRouter(tags=["jobs"])
@@ -446,6 +447,14 @@ async def upload_and_create_job(
The style_params JSON can reference the uploaded images/fonts by their original
filenames, and the backend will update the paths to GCS locations.
"""
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
raise HTTPException(
status_code=403,
detail="File upload is not available for this portal"
)
try:
# Validate main audio file type
file_ext = Path(file.filename).suffix.lower()
@@ -632,10 +641,12 @@ async def upload_and_create_job(
request_metadata=request_metadata,
# Non-interactive mode
non_interactive=non_interactive,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
# Record job creation metric
metrics.record_job_created(job_id, source="upload")
@@ -1029,6 +1040,14 @@ async def create_job_with_upload_urls(
- Works with any HTTP client (no HTTP/2 required)
- Resumable uploads possible with GCS
"""
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
raise HTTPException(
status_code=403,
detail="File upload is not available for this portal"
)
try:
# Validate files list
if not body.files:
@@ -1153,6 +1172,8 @@ async def create_job_with_upload_urls(
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
@@ -1481,6 +1502,14 @@ async def create_job_from_url(
Note: YouTube rate limiting may cause occasional download failures.
The backend will retry automatically.
"""
# Check tenant feature flag
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.youtube_url:
raise HTTPException(
status_code=403,
detail="URL-based job creation is not available for this portal"
)
try:
# Validate URL
if not _validate_url(body.url):
@@ -1583,6 +1612,8 @@ async def create_job_from_url(
other_stems_models=body.other_stems_models,
request_metadata=request_metadata,
non_interactive=body.non_interactive,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
@@ -1703,6 +1734,14 @@ async def create_finalise_only_job(
The endpoint returns signed URLs for uploading all the prep files.
"""
# Check tenant feature flag - finalise-only requires file upload capability
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.file_upload:
raise HTTPException(
status_code=403,
detail="File upload is not available for this portal"
)
try:
# Validate files list
if not body.files:
@@ -1834,6 +1873,8 @@ async def create_finalise_only_job(
finalise_only=True,
keep_brand_code=body.keep_brand_code,
request_metadata=request_metadata,
# Tenant scoping
tenant_id=tenant_config.id if tenant_config else None,
)
job = job_manager.create_job(job_create)
job_id = job.job_id
+9 -1
View File
@@ -11,7 +11,7 @@ import asyncio
import logging
import httpx
from typing import List, Optional, Dict, Any, Tuple
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
@@ -30,6 +30,7 @@ from backend.config import get_settings
from backend.api.dependencies import require_admin, require_auth, require_instrumental_auth
from backend.services.auth_service import UserType, AuthResult
from backend.services.metrics import metrics
from backend.middleware.tenant import get_tenant_from_request
from backend.utils.test_data import is_test_email
@@ -190,6 +191,7 @@ def _check_job_ownership(job: Job, auth_result: AuthResult) -> bool:
@router.get("", response_model=List[Job])
async def list_jobs(
request: Request,
status: Optional[JobStatus] = None,
environment: Optional[str] = None,
client_id: Optional[str] = None,
@@ -203,6 +205,7 @@ async def list_jobs(
List jobs with optional filters.
Regular users only see their own jobs. Admins see all jobs.
Users on tenant portals only see jobs from their tenant.
Args:
status: Filter by job status (pending, complete, failed, etc.)
@@ -247,6 +250,10 @@ async def list_jobs(
logger.warning("Non-admin auth without user_email, returning empty job list")
return []
# Get tenant_id from request for portal scoping
# Tenant users only see jobs from their tenant
tenant_id = get_tenant_from_request(request)
jobs = job_manager.list_jobs(
status=status,
environment=environment,
@@ -254,6 +261,7 @@ async def list_jobs(
created_after=created_after_dt,
created_before=created_before_dt,
user_email=user_email_filter,
tenant_id=tenant_id,
limit=limit
)
+120
View File
@@ -0,0 +1,120 @@
"""
Tenant API routes for white-label portal configuration.
These endpoints are public (no auth required) since the frontend needs
to fetch tenant branding before the user logs in.
"""
import logging
from typing import Optional
from fastapi import APIRouter, Query, Request
from backend.models.tenant import TenantConfigResponse, TenantPublicConfig
from backend.services.tenant_service import get_tenant_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/tenant", tags=["tenant"])
@router.get("/config", response_model=TenantConfigResponse)
async def get_tenant_config(
request: Request,
tenant: Optional[str] = Query(
None,
description="Tenant ID override (for development). If not provided, detected from subdomain.",
),
):
"""
Get tenant configuration for the current portal.
This endpoint detects the tenant from:
1. Query parameter `tenant` (for development/testing)
2. X-Tenant-ID header (set by frontend)
3. Host header subdomain
Returns the public tenant configuration (branding, features, defaults)
or indicates this is the default Nomad Karaoke portal.
"""
tenant_service = get_tenant_service()
# Priority 1: Query parameter (for dev/testing)
tenant_id = tenant
# Priority 2: X-Tenant-ID header
if not tenant_id:
tenant_id = request.headers.get("X-Tenant-ID")
# Priority 3: Detect from Host header
if not tenant_id:
host = request.headers.get("Host", "")
# Check if this is a tenant subdomain
# Pattern: {tenant}.nomadkaraoke.com or {tenant}.gen.nomadkaraoke.com
if host and "nomadkaraoke.com" in host.lower():
parts = host.lower().split(".")
# Skip known non-tenant subdomains
if parts[0] not in ["gen", "api", "www", "buy", "admin"]:
potential_tenant = parts[0]
if tenant_service.tenant_exists(potential_tenant):
tenant_id = potential_tenant
# If no tenant detected, return default config
if not tenant_id:
logger.debug("No tenant detected, returning default config")
return TenantConfigResponse(tenant=None, is_default=True)
# Load tenant config
public_config = tenant_service.get_public_config(tenant_id)
if not public_config:
logger.warning(f"Tenant not found: {tenant_id}")
return TenantConfigResponse(tenant=None, is_default=True)
if not public_config.is_active:
logger.warning(f"Tenant is inactive: {tenant_id}")
return TenantConfigResponse(tenant=None, is_default=True)
logger.info(f"Returning config for tenant: {tenant_id}")
return TenantConfigResponse(tenant=public_config, is_default=False)
@router.get("/config/{tenant_id}", response_model=TenantConfigResponse)
async def get_tenant_config_by_id(tenant_id: str):
"""
Get tenant configuration by explicit tenant ID.
This is useful for admin tools or debugging.
"""
tenant_service = get_tenant_service()
public_config = tenant_service.get_public_config(tenant_id)
if not public_config:
return TenantConfigResponse(tenant=None, is_default=True)
# Check if tenant is active
if not public_config.is_active:
logger.warning(f"Tenant is inactive: {tenant_id}")
return TenantConfigResponse(tenant=None, is_default=True)
return TenantConfigResponse(tenant=public_config, is_default=False)
@router.get("/asset/{tenant_id}/{asset_name}")
async def get_tenant_asset(tenant_id: str, asset_name: str):
"""
Get a signed URL for a tenant asset (logo, favicon, etc.).
This redirects to the signed GCS URL for the asset.
"""
from fastapi.responses import RedirectResponse
tenant_service = get_tenant_service()
url = tenant_service.get_asset_url(tenant_id, asset_name)
if not url:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Asset not found")
return RedirectResponse(url=url)
+57 -7
View File
@@ -8,8 +8,28 @@ Handles:
- Stripe checkout and webhooks
- Admin user management
"""
import hashlib
import logging
from typing import Optional, Tuple
def _mask_email(email: str) -> str:
"""Mask email for logging to avoid PII exposure.
Example: test@example.com -> te***@ex***.com
"""
if not email or "@" not in email:
return "***"
local, domain = email.split("@", 1)
masked_local = local[:2] + "***" if len(local) > 2 else "***"
domain_parts = domain.split(".")
if len(domain_parts) >= 2:
masked_domain = domain_parts[0][:2] + "***." + domain_parts[-1]
else:
masked_domain = "***"
return f"{masked_local}@{masked_domain}"
from fastapi import APIRouter, HTTPException, Depends, Request, Header
from pydantic import BaseModel, EmailStr
@@ -112,7 +132,11 @@ async def send_magic_link(
The user will receive an email with a link that logs them in.
Links expire after 15 minutes and can only be used once.
For white-label tenants, validates email domain against tenant config.
"""
from backend.middleware.tenant import get_tenant_from_request, get_tenant_config_from_request
# Check if email service is configured
if not email_service.is_configured():
logger.error("Email service not configured - cannot send magic links")
@@ -123,19 +147,39 @@ async def send_magic_link(
email = request.email.lower()
# Get tenant context from middleware
tenant_id = get_tenant_from_request(http_request)
tenant_config = get_tenant_config_from_request(http_request)
# Validate email domain for tenant if configured
if tenant_config and tenant_config.auth.allowed_email_domains:
if not tenant_config.is_email_allowed(email):
logger.warning(f"Email domain not allowed for tenant {tenant_id}: {_mask_email(email)}")
# Return success anyway to prevent email enumeration
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
)
# Get client info for security logging
ip_address = http_request.client.host if http_request.client else None
user_agent = http_request.headers.get("user-agent")
# Create magic link token
# Create magic link token with tenant context
magic_link = user_service.create_magic_link(
email,
ip_address=ip_address,
user_agent=user_agent
user_agent=user_agent,
tenant_id=tenant_id
)
# Send email
sent = email_service.send_magic_link(email, magic_link.token)
# Get tenant-specific sender email
sender_email = None
if tenant_config:
sender_email = tenant_config.get_sender_email()
# Send email (with tenant-specific sender if configured)
sent = email_service.send_magic_link(email, magic_link.token, sender_email=sender_email)
if not sent:
logger.error(f"Failed to send magic link email to {email}")
@@ -159,6 +203,7 @@ async def verify_magic_link(
Verify a magic link token and create a session.
Returns a session token that should be stored and used for subsequent requests.
The session will be associated with the tenant from the magic link.
"""
# Get client info
ip_address = http_request.client.host if http_request.client else None
@@ -166,11 +211,14 @@ async def verify_magic_link(
# Check if this is a first login BEFORE verification (which sets last_login_at)
# We need to get the user's state before verify_magic_link updates it
# Also extract tenant_id from the magic link for session creation
from backend.services.user_service import MAGIC_LINKS_COLLECTION
magic_link_doc = user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).get()
is_first_login = False
magic_link_tenant_id = None
if magic_link_doc.exists:
magic_link_data = magic_link_doc.to_dict()
magic_link_tenant_id = magic_link_data.get('tenant_id')
pre_verify_user = user_service.get_user(magic_link_data.get('email', ''))
if pre_verify_user:
is_first_login = pre_verify_user.total_jobs_created == 0 and not pre_verify_user.last_login_at
@@ -181,18 +229,19 @@ async def verify_magic_link(
if not success or not user:
raise HTTPException(status_code=401, detail=message)
# Create session
# Create session with tenant context from the magic link
session = user_service.create_session(
user.email,
ip_address=ip_address,
user_agent=user_agent
user_agent=user_agent,
tenant_id=magic_link_tenant_id
)
# Send welcome email to first-time users
if is_first_login:
email_service.send_welcome_email(user.email, user.credits)
# Return user info
# Return user info with tenant_id
user_public = UserPublic(
email=user.email,
role=user.role,
@@ -200,6 +249,7 @@ async def verify_magic_link(
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
tenant_id=user.tenant_id,
)
return VerifyMagicLinkResponse(
+6 -1
View File
@@ -7,13 +7,14 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
from backend.services.spacy_preloader import preload_spacy_model
from backend.services.nltk_preloader import preload_all_nltk_resources
from backend.services.langfuse_preloader import preload_langfuse_handler
from backend.middleware.audit_logging import AuditLoggingMiddleware
from backend.middleware.tenant import TenantMiddleware
from backend.version import VERSION
@@ -128,6 +129,9 @@ app.add_middleware(
# Add audit logging middleware (captures all requests with request_id for correlation)
app.add_middleware(AuditLoggingMiddleware)
# Add tenant detection middleware (extracts tenant from subdomain/headers)
app.add_middleware(TenantMiddleware)
# Include routers
app.include_router(health.router, prefix="/api")
app.include_router(jobs.router, prefix="/api")
@@ -139,6 +143,7 @@ app.include_router(audio_search.router, prefix="/api") # Audio search (artist+t
app.include_router(themes.router, prefix="/api") # Theme selection for styles
app.include_router(users.router, prefix="/api") # User auth, credits, and Stripe webhooks
app.include_router(admin.router, prefix="/api") # Admin dashboard and management
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
@app.get("/")
+7 -1
View File
@@ -1,5 +1,11 @@
"""Middleware package for FastAPI application."""
from backend.middleware.audit_logging import AuditLoggingMiddleware
from backend.middleware.tenant import TenantMiddleware, get_tenant_from_request, get_tenant_config_from_request
__all__ = ["AuditLoggingMiddleware"]
__all__ = [
"AuditLoggingMiddleware",
"TenantMiddleware",
"get_tenant_from_request",
"get_tenant_config_from_request",
]
+192
View File
@@ -0,0 +1,192 @@
"""
Tenant detection middleware for white-label B2B portals.
This middleware extracts the tenant ID from incoming requests and attaches
the tenant configuration to the request state for use by downstream handlers.
Tenant detection priority:
1. X-Tenant-ID header (explicitly set by frontend)
2. `tenant` query parameter (for development/testing)
3. Host header subdomain detection (production flow)
The middleware is non-blocking - if no tenant is detected, the request
proceeds as a default Nomad Karaoke request (tenant_id = None).
"""
import logging
import os
from typing import Optional
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from backend.services.tenant_service import get_tenant_service
from backend.models.tenant import TenantConfig
logger = logging.getLogger(__name__)
# Only allow query param tenant override in non-production environments
IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production" or \
os.environ.get("ENVIRONMENT", "").lower() == "production"
# Known non-tenant subdomains that should be treated as default Nomad Karaoke
NON_TENANT_SUBDOMAINS = {"gen", "api", "www", "buy", "admin", "app", "beta"}
class TenantMiddleware(BaseHTTPMiddleware):
"""
Middleware that detects tenant from request and attaches config to state.
After this middleware runs, routes can access:
- request.state.tenant_id: str or None
- request.state.tenant_config: TenantConfig or None
Usage in route handlers:
```python
@router.get("/something")
async def handler(request: Request):
tenant_id = getattr(request.state, "tenant_id", None)
tenant_config = getattr(request.state, "tenant_config", None)
```
"""
async def dispatch(self, request: Request, call_next) -> Response:
# Extract tenant ID from request
tenant_id = self._extract_tenant_id(request)
# Load tenant config if tenant detected
tenant_config: Optional[TenantConfig] = None
if tenant_id:
tenant_service = get_tenant_service()
tenant_config = tenant_service.get_tenant_config(tenant_id)
if tenant_config and not tenant_config.is_active:
# Tenant exists but is inactive - treat as default
logger.warning(f"Inactive tenant requested: {tenant_id}")
tenant_id = None
tenant_config = None
# Attach to request state
request.state.tenant_id = tenant_id
request.state.tenant_config = tenant_config
# Log tenant detection for debugging
if tenant_id:
logger.debug(f"Request tenant: {tenant_id} (path: {request.url.path})")
# Process request
response = await call_next(request)
# Add tenant ID to response headers for debugging
if tenant_id:
response.headers["X-Tenant-ID"] = tenant_id
return response
def _extract_tenant_id(self, request: Request) -> Optional[str]:
"""
Extract tenant ID from request using priority-based detection.
Returns:
Tenant ID if detected, None for default Nomad Karaoke
"""
# Priority 1: X-Tenant-ID header (explicitly set by frontend)
header_tenant = request.headers.get("X-Tenant-ID")
if header_tenant:
return header_tenant.lower().strip()
# Priority 2: Query parameter (for development/testing only)
# Disabled in production to prevent tenant spoofing
if not IS_PRODUCTION:
query_tenant = request.query_params.get("tenant")
if query_tenant:
return query_tenant.lower().strip()
# Priority 3: Host header subdomain detection
host = request.headers.get("Host", "")
return self._extract_tenant_from_host(host)
def _extract_tenant_from_host(self, host: str) -> Optional[str]:
"""
Extract tenant ID from Host header subdomain.
Patterns handled:
- vocalstar.nomadkaraoke.com -> vocalstar
- vocalstar.gen.nomadkaraoke.com -> vocalstar
- localhost:3000 -> None (local dev)
- gen.nomadkaraoke.com -> None (main app)
- api.nomadkaraoke.com -> None (API)
Returns:
Tenant ID if subdomain matches tenant, None otherwise
"""
if not host:
return None
# Normalize
host_lower = host.lower()
# Remove port if present
if ":" in host_lower:
host_lower = host_lower.split(":")[0]
# Check if this is a nomadkaraoke.com domain
if "nomadkaraoke.com" not in host_lower:
return None
# Split into parts
parts = host_lower.split(".")
# Need at least 3 parts: subdomain.nomadkaraoke.com
if len(parts) < 3:
return None
# First part is the potential tenant ID
potential_tenant = parts[0]
# Skip known non-tenant subdomains
if potential_tenant in NON_TENANT_SUBDOMAINS:
return None
# Verify tenant exists in GCS
tenant_service = get_tenant_service()
if tenant_service.tenant_exists(potential_tenant):
return potential_tenant
return None
def get_tenant_from_request(request: Request) -> Optional[str]:
"""
Helper function to get tenant ID from request state.
Usage in route handlers:
```python
from backend.middleware.tenant import get_tenant_from_request
@router.get("/something")
async def handler(request: Request):
tenant_id = get_tenant_from_request(request)
```
"""
return getattr(request.state, "tenant_id", None)
def get_tenant_config_from_request(request: Request) -> Optional[TenantConfig]:
"""
Helper function to get tenant config from request state.
Usage in route handlers:
```python
from backend.middleware.tenant import get_tenant_config_from_request
@router.get("/something")
async def handler(request: Request):
config = get_tenant_config_from_request(request)
if config and not config.features.audio_search:
raise HTTPException(403, "Audio search not available")
```
"""
return getattr(request.state, "tenant_config", None)
+7 -1
View File
@@ -207,6 +207,9 @@ class Job(BaseModel):
webhook_url: Optional[str] = None # Webhook for notifications
user_email: Optional[str] = None # Email for notifications
non_interactive: bool = False # Skip interactive steps (lyrics review, instrumental selection)
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None # Tenant ID for white-label portal scoping
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
@@ -486,7 +489,10 @@ class JobCreate(BaseModel):
- server_version: Current server version
- custom_headers: All X-* headers
"""
# Tenant scoping for white-label portals
tenant_id: Optional[str] = None # Tenant ID for job scoping
@validator('url')
def validate_url(cls, v):
"""Validate URL is not empty."""
+208
View File
@@ -0,0 +1,208 @@
"""
Tenant data models for white-label B2B portals.
Tenants are B2B customers who get their own branded portal with custom
configuration. Each tenant has:
- Custom branding (logo, colors, site title)
- Feature flags (enable/disable audio search, distribution, etc.)
- Default settings (theme, distribution mode)
- Auth configuration (allowed email domains, fixed tokens)
Tenant configs are stored in GCS at tenants/{tenant_id}/config.json
"""
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class TenantBranding(BaseModel):
"""Branding configuration for a tenant's portal."""
logo_url: Optional[str] = Field(
None, description="URL to tenant's logo image (PNG with transparency preferred)"
)
logo_height: int = Field(40, description="Logo height in pixels for header display")
primary_color: str = Field(
"#ff5bb8", description="Primary brand color (hex format)"
)
secondary_color: str = Field(
"#8b5cf6", description="Secondary brand color (hex format)"
)
accent_color: Optional[str] = Field(
None, description="Accent color for highlights (hex format)"
)
background_color: Optional[str] = Field(
None, description="Custom background color (defaults to dark theme)"
)
favicon_url: Optional[str] = Field(None, description="URL to custom favicon")
site_title: str = Field(
"Karaoke Generator", description="Browser tab title"
)
tagline: Optional[str] = Field(
None, description="Optional tagline shown below logo"
)
class TenantFeatures(BaseModel):
"""Feature flags controlling what's available in the tenant's portal."""
# Audio input methods
audio_search: bool = Field(
True, description="Enable audio search (flacfetch integration)"
)
file_upload: bool = Field(True, description="Enable direct file upload")
youtube_url: bool = Field(True, description="Enable YouTube URL input")
# Distribution options
youtube_upload: bool = Field(True, description="Enable YouTube upload option")
dropbox_upload: bool = Field(True, description="Enable Dropbox upload option")
gdrive_upload: bool = Field(True, description="Enable Google Drive upload option")
# Customization options
theme_selection: bool = Field(
True, description="Allow user to select theme (false = use default)"
)
color_overrides: bool = Field(
True, description="Allow user to customize colors"
)
# Output formats
enable_cdg: bool = Field(True, description="Generate CDG format output")
enable_4k: bool = Field(True, description="Generate 4K video output")
# Advanced features
admin_access: bool = Field(
False, description="Allow access to admin dashboard"
)
class TenantDefaults(BaseModel):
"""Default settings applied to all jobs for this tenant."""
theme_id: Optional[str] = Field(
None, description="Default theme ID (required if theme_selection=false)"
)
locked_theme: Optional[str] = Field(
None,
description="If set, users cannot change theme - always uses this theme ID"
)
distribution_mode: str = Field(
"all",
description="Distribution mode: 'all', 'download_only', or 'cloud_only'"
)
brand_prefix: Optional[str] = Field(
None, description="Prefix for output filenames (e.g., 'VSTAR')"
)
youtube_description_template: Optional[str] = Field(
None, description="Default YouTube description template"
)
class TenantAuth(BaseModel):
"""Authentication configuration for a tenant."""
allowed_email_domains: List[str] = Field(
default_factory=list,
description="Email domains allowed for magic link auth (e.g., ['vocal-star.com'])"
)
require_email_domain: bool = Field(
True,
description="If true, only allowed domains can sign up. If false, domains get auto-approved."
)
fixed_token_ids: List[str] = Field(
default_factory=list,
description="IDs of fixed API tokens for this tenant (tokens stored in auth_tokens)"
)
sender_email: Optional[str] = Field(
None,
description="Email sender address for this tenant (e.g., 'vocalstar@nomadkaraoke.com')"
)
class TenantConfig(BaseModel):
"""Complete configuration for a white-label tenant."""
id: str = Field(..., description="Unique tenant identifier (e.g., 'vocalstar')")
name: str = Field(..., description="Display name (e.g., 'Vocal Star')")
subdomain: str = Field(
..., description="Full subdomain (e.g., 'vocalstar.nomadkaraoke.com')"
)
is_active: bool = Field(True, description="Whether tenant portal is active")
branding: TenantBranding = Field(default_factory=TenantBranding)
features: TenantFeatures = Field(default_factory=TenantFeatures)
defaults: TenantDefaults = Field(default_factory=TenantDefaults)
auth: TenantAuth = Field(default_factory=TenantAuth)
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
def get_sender_email(self) -> str:
"""Get the email sender address for this tenant."""
if self.auth.sender_email:
return self.auth.sender_email
# Default pattern: {tenant_id}@nomadkaraoke.com
return f"{self.id}@nomadkaraoke.com"
def is_email_allowed(self, email: str) -> bool:
"""Check if an email address is allowed for this tenant."""
if not self.auth.allowed_email_domains:
# No domain restrictions
return True
email_lower = email.lower()
for domain in self.auth.allowed_email_domains:
if email_lower.endswith(f"@{domain.lower()}"):
return True
return not self.auth.require_email_domain
class TenantPublicConfig(BaseModel):
"""
Public tenant configuration returned to frontend.
This excludes sensitive auth details like token IDs.
"""
id: str
name: str
subdomain: str
is_active: bool
branding: TenantBranding
features: TenantFeatures
defaults: TenantDefaults
# Auth info limited to what frontend needs
allowed_email_domains: List[str] = Field(default_factory=list)
@classmethod
def from_config(cls, config: TenantConfig) -> "TenantPublicConfig":
"""Create public config from full config."""
return cls(
id=config.id,
name=config.name,
subdomain=config.subdomain,
is_active=config.is_active,
branding=config.branding,
features=config.features,
defaults=TenantDefaults(
theme_id=config.defaults.theme_id,
locked_theme=config.defaults.locked_theme,
distribution_mode=config.defaults.distribution_mode,
# Don't expose brand_prefix or youtube_description_template
),
allowed_email_domains=config.auth.allowed_email_domains,
)
class TenantConfigResponse(BaseModel):
"""Response from GET /api/tenant/config endpoint."""
tenant: Optional[TenantPublicConfig] = Field(
None, description="Tenant config if found, null for default Nomad Karaoke"
)
is_default: bool = Field(
True, description="True if using default Nomad Karaoke config"
)
+18
View File
@@ -45,11 +45,17 @@ class User(BaseModel):
Users are identified by email address. Authentication is via magic links
(no passwords). Credits are consumed when creating karaoke jobs.
For multi-tenant white-label portals, users are scoped to a tenant.
Users with tenant_id=None are default Nomad Karaoke users.
"""
email: str # Primary identifier
role: UserRole = UserRole.USER
credits: int = 0
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Stripe integration
stripe_customer_id: Optional[str] = None
@@ -87,6 +93,9 @@ class MagicLinkToken(BaseModel):
Tokens are short-lived (15 minutes) and single-use.
Stored in Firestore with automatic TTL.
For multi-tenant portals, the tenant_id determines which portal
the user will be redirected to after verification.
"""
token: str # Secure random token
email: str
@@ -97,6 +106,9 @@ class MagicLinkToken(BaseModel):
ip_address: Optional[str] = None
user_agent: Optional[str] = None
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
class Session(BaseModel):
"""
@@ -104,6 +116,8 @@ class Session(BaseModel):
Sessions are created after successful magic link verification.
Sessions expire after 7 days of inactivity or 30 days absolute.
For multi-tenant portals, sessions are scoped to a tenant.
"""
token: str # Secure random session token
user_email: str
@@ -114,6 +128,9 @@ class Session(BaseModel):
user_agent: Optional[str] = None
is_active: bool = True
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Pydantic models for API requests/responses
@@ -149,6 +166,7 @@ class UserPublic(BaseModel):
display_name: Optional[str] = None
total_jobs_created: int = 0
total_jobs_completed: int = 0
tenant_id: Optional[str] = None
class AddCreditsRequest(BaseModel):
+31 -4
View File
@@ -34,8 +34,19 @@ class EmailProvider(ABC):
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
"""Send an email. Returns True if successful."""
"""
Send an email. Returns True if successful.
Args:
to_email: Recipient email address
subject: Email subject
html_content: HTML content
text_content: Plain text content (optional)
cc_emails: CC recipients (optional)
from_email_override: Override the default sender email (optional, for multi-tenant)
"""
pass
@@ -53,8 +64,11 @@ class ConsoleEmailProvider(EmailProvider):
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
logger.info("=" * 60)
if from_email_override:
logger.info(f"FROM: {from_email_override}")
logger.info(f"EMAIL TO: {to_email}")
if cc_emails:
logger.info(f"CC: {', '.join(cc_emails)}")
@@ -85,6 +99,7 @@ class PreviewEmailProvider(EmailProvider):
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
self.last_to_email = to_email
self.last_subject = subject
@@ -115,6 +130,7 @@ class SendGridEmailProvider(EmailProvider):
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
try:
# Import here to avoid requiring sendgrid in all environments
@@ -123,8 +139,11 @@ class SendGridEmailProvider(EmailProvider):
sg = SendGridAPIClient(api_key=self.api_key)
# Use override sender if provided (for multi-tenant)
sender_email = from_email_override or self.from_email
message = Mail(
from_email=Email(self.from_email, self.from_name),
from_email=Email(sender_email, self.from_name),
to_emails=To(to_email),
subject=subject,
html_content=Content("text/html", html_content)
@@ -200,13 +219,19 @@ class EmailService:
"""Check if a real email provider is configured (not just console logging)."""
return isinstance(self.provider, SendGridEmailProvider)
def send_magic_link(self, email: str, token: str) -> bool:
def send_magic_link(
self,
email: str,
token: str,
sender_email: Optional[str] = None,
) -> bool:
"""
Send a magic link email for authentication.
Args:
email: User's email address
token: Magic link token
sender_email: Override sender email address (for multi-tenant)
Returns:
True if email was sent successfully
@@ -264,7 +289,9 @@ If you didn't request this email, you can safely ignore it.
© {self._get_year()} Nomad Karaoke
"""
return self.provider.send_email(email, subject, html_content, text_content)
return self.provider.send_email(
email, subject, html_content, text_content, from_email_override=sender_email
)
def send_credits_added(self, email: str, credits: int, total_credits: int) -> bool:
"""
+6
View File
@@ -116,6 +116,7 @@ class FirestoreService:
created_after: Optional[datetime] = None,
created_before: Optional[datetime] = None,
user_email: Optional[str] = None,
tenant_id: Optional[str] = None,
limit: int = 100
) -> List[Job]:
"""
@@ -128,6 +129,7 @@ class FirestoreService:
created_after: Filter jobs created after this datetime
created_before: Filter jobs created before this datetime
user_email: Filter by user_email (owner of the job)
tenant_id: Filter by tenant_id (white-label portal scoping)
limit: Maximum number of jobs to return
Returns:
@@ -150,6 +152,10 @@ class FirestoreService:
if user_email:
query = query.where(filter=FieldFilter('user_email', '==', user_email.lower()))
# Filter by tenant_id (white-label portal scoping)
if tenant_id:
query = query.where(filter=FieldFilter('tenant_id', '==', tenant_id))
# Date range filters
if created_after:
query = query.where(filter=FieldFilter('created_at', '>=', created_after))
+5
View File
@@ -85,6 +85,8 @@ class JobManager:
keep_brand_code=job_create.keep_brand_code,
# Request metadata (for tracking and filtering)
request_metadata=job_create.request_metadata,
# Tenant scoping
tenant_id=job_create.tenant_id,
)
self.firestore.create_job(job)
@@ -125,6 +127,7 @@ class JobManager:
created_after: Optional[datetime] = None,
created_before: Optional[datetime] = None,
user_email: Optional[str] = None,
tenant_id: Optional[str] = None,
limit: int = 100
) -> List[Job]:
"""
@@ -137,6 +140,7 @@ class JobManager:
created_after: Filter jobs created after this datetime
created_before: Filter jobs created before this datetime
user_email: Filter by user_email (job owner)
tenant_id: Filter by tenant_id (white-label portal scoping)
limit: Maximum number of jobs to return
Returns:
@@ -149,6 +153,7 @@ class JobManager:
created_after=created_after,
created_before=created_before,
user_email=user_email,
tenant_id=tenant_id,
limit=limit
)
+285
View File
@@ -0,0 +1,285 @@
"""
Tenant service for managing white-label B2B portal configurations.
Tenant configs are stored in GCS at tenants/{tenant_id}/config.json.
The service provides:
- Tenant config loading with caching
- Subdomain to tenant ID resolution
- Tenant validation
Similar to ThemeService, configs are cached for 5 minutes to reduce GCS reads.
"""
import logging
import threading
from datetime import datetime
from typing import Dict, Optional
from backend.models.tenant import TenantConfig, TenantPublicConfig
from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
# GCS paths for tenant configs
TENANTS_PREFIX = "tenants"
# Default sender email (shared with EmailService for consistency)
DEFAULT_SENDER_EMAIL = "gen@nomadkaraoke.com"
class TenantService:
"""Service for managing tenant configurations from GCS."""
def __init__(self, storage: Optional[StorageService] = None):
"""
Initialize the tenant service.
Args:
storage: StorageService instance (creates new one if not provided)
"""
self.storage = storage or StorageService()
self._config_cache: Dict[str, TenantConfig] = {}
self._cache_times: Dict[str, datetime] = {}
self._subdomain_map: Dict[str, str] = {} # subdomain -> tenant_id
self._subdomain_map_time: Optional[datetime] = None
self.CACHE_TTL_SECONDS = 300 # 5 minute cache
def _get_config_path(self, tenant_id: str) -> str:
"""Get the GCS path for a tenant's config file."""
return f"{TENANTS_PREFIX}/{tenant_id}/config.json"
def _is_cache_valid(self, tenant_id: str) -> bool:
"""Check if the config cache for a tenant is still valid."""
if tenant_id not in self._config_cache or tenant_id not in self._cache_times:
return False
age = datetime.now() - self._cache_times[tenant_id]
return age.total_seconds() < self.CACHE_TTL_SECONDS
def _is_subdomain_map_valid(self) -> bool:
"""Check if the subdomain map cache is still valid."""
if not self._subdomain_map or self._subdomain_map_time is None:
return False
age = datetime.now() - self._subdomain_map_time
return age.total_seconds() < self.CACHE_TTL_SECONDS
def get_tenant_config(
self, tenant_id: str, force_refresh: bool = False
) -> Optional[TenantConfig]:
"""
Load tenant configuration from GCS with caching.
Args:
tenant_id: The tenant identifier
force_refresh: Force reload from GCS even if cache is valid
Returns:
TenantConfig if found, None otherwise
"""
if not force_refresh and self._is_cache_valid(tenant_id):
return self._config_cache[tenant_id]
try:
config_path = self._get_config_path(tenant_id)
if not self.storage.file_exists(config_path):
logger.debug(f"Tenant config not found: {tenant_id}")
return None
data = self.storage.download_json(config_path)
config = TenantConfig(**data)
# Update cache
self._config_cache[tenant_id] = config
self._cache_times[tenant_id] = datetime.now()
# Update subdomain map and its timestamp
self._subdomain_map[config.subdomain.lower()] = tenant_id
self._subdomain_map_time = datetime.now()
logger.info(f"Loaded tenant config: {tenant_id}")
return config
except Exception as e:
logger.error(f"Failed to load tenant config {tenant_id}: {e}")
return None
def get_tenant_by_subdomain(self, subdomain: str) -> Optional[TenantConfig]:
"""
Get tenant config by subdomain.
Args:
subdomain: Full subdomain (e.g., 'vocalstar.nomadkaraoke.com')
Returns:
TenantConfig if found, None otherwise
"""
subdomain_lower = subdomain.lower()
# Check cache first
if subdomain_lower in self._subdomain_map:
tenant_id = self._subdomain_map[subdomain_lower]
return self.get_tenant_config(tenant_id)
# Try to find tenant by listing all configs
# This is a fallback for when we don't have the subdomain cached
tenant_id = self._resolve_subdomain_to_tenant_id(subdomain_lower)
if tenant_id:
return self.get_tenant_config(tenant_id)
return None
def _resolve_subdomain_to_tenant_id(self, subdomain: str) -> Optional[str]:
"""
Resolve a subdomain to tenant ID by checking GCS.
This extracts the tenant ID from the subdomain pattern:
- 'vocalstar.nomadkaraoke.com' -> 'vocalstar'
- 'vocalstar.gen.nomadkaraoke.com' -> 'vocalstar'
"""
# Extract potential tenant ID from subdomain
# Pattern: {tenant}.nomadkaraoke.com or {tenant}.gen.nomadkaraoke.com
parts = subdomain.split(".")
if len(parts) >= 3:
# First part is likely the tenant ID
potential_tenant_id = parts[0]
# Check if config exists
config_path = self._get_config_path(potential_tenant_id)
if self.storage.file_exists(config_path):
return potential_tenant_id
return None
def get_public_config(self, tenant_id: str) -> Optional[TenantPublicConfig]:
"""
Get the public (frontend-safe) tenant configuration.
Args:
tenant_id: The tenant identifier
Returns:
TenantPublicConfig if found, None otherwise
"""
config = self.get_tenant_config(tenant_id)
if config:
return TenantPublicConfig.from_config(config)
return None
def get_public_config_by_subdomain(
self, subdomain: str
) -> Optional[TenantPublicConfig]:
"""
Get the public tenant configuration by subdomain.
Args:
subdomain: Full subdomain
Returns:
TenantPublicConfig if found, None otherwise
"""
config = self.get_tenant_by_subdomain(subdomain)
if config:
return TenantPublicConfig.from_config(config)
return None
def tenant_exists(self, tenant_id: str) -> bool:
"""
Check if a tenant exists.
Args:
tenant_id: The tenant identifier
Returns:
True if tenant config exists, False otherwise
"""
config_path = self._get_config_path(tenant_id)
return self.storage.file_exists(config_path)
def is_email_allowed_for_tenant(self, tenant_id: str, email: str) -> bool:
"""
Check if an email is allowed for a specific tenant.
Args:
tenant_id: The tenant identifier
email: Email address to check
Returns:
True if email is allowed, False otherwise
"""
config = self.get_tenant_config(tenant_id)
if not config:
return False
return config.is_email_allowed(email)
def get_tenant_sender_email(self, tenant_id: str) -> str:
"""
Get the email sender address for a tenant.
Args:
tenant_id: The tenant identifier
Returns:
Sender email address
"""
config = self.get_tenant_config(tenant_id)
if config:
return config.get_sender_email()
# Default fallback (consistent with EmailService)
return DEFAULT_SENDER_EMAIL
def invalidate_cache(self, tenant_id: Optional[str] = None) -> None:
"""
Invalidate tenant config cache.
Args:
tenant_id: Specific tenant to invalidate, or None for all
"""
if tenant_id:
self._config_cache.pop(tenant_id, None)
self._cache_times.pop(tenant_id, None)
# Also remove any subdomain map entries pointing to this tenant
subdomains_to_remove = [
subdomain
for subdomain, tid in self._subdomain_map.items()
if tid == tenant_id
]
for subdomain in subdomains_to_remove:
self._subdomain_map.pop(subdomain, None)
logger.info(f"Tenant config cache invalidated: {tenant_id}")
else:
self._config_cache.clear()
self._cache_times.clear()
self._subdomain_map.clear()
self._subdomain_map_time = None
logger.info("All tenant config caches invalidated")
def get_asset_url(self, tenant_id: str, asset_name: str) -> Optional[str]:
"""
Get a signed URL for a tenant asset (logo, favicon, etc.).
Args:
tenant_id: The tenant identifier
asset_name: Asset filename (e.g., 'logo.png')
Returns:
Signed URL if asset exists, None otherwise
"""
asset_path = f"{TENANTS_PREFIX}/{tenant_id}/{asset_name}"
if self.storage.file_exists(asset_path):
return self.storage.generate_signed_url(asset_path, expiration_minutes=60)
return None
# Singleton instance with thread-safe initialization
_tenant_service: Optional[TenantService] = None
_tenant_service_lock = threading.Lock()
def get_tenant_service() -> TenantService:
"""Get or create the singleton TenantService instance (thread-safe)."""
global _tenant_service
if _tenant_service is None:
with _tenant_service_lock:
# Double-check after acquiring lock
if _tenant_service is None:
_tenant_service = TenantService()
return _tenant_service
+37 -7
View File
@@ -73,16 +73,26 @@ class UserService:
logger.exception(f"Error getting user {email}")
return None
def get_or_create_user(self, email: str) -> User:
def get_or_create_user(self, email: str, tenant_id: Optional[str] = None) -> User:
"""
Get existing user or create a new one.
New users receive a welcome credit to try the service.
Args:
email: User's email address
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
Note: If user exists but has a different tenant_id, the existing user is returned.
Users are uniquely identified by email, not email+tenant.
"""
email = email.lower()
user = self.get_user(email)
if user:
# If user exists but tenant_id differs, we still return the user
# This allows users to access multiple tenants with one account
# (though features may be restricted per-tenant)
return user
# Create new user with welcome credit
@@ -97,9 +107,10 @@ class UserService:
email=email,
credits=welcome_credit,
credit_transactions=[welcome_transaction],
tenant_id=tenant_id, # Associate with tenant on creation
)
self._save_user(user)
logger.info(f"Created new user: {email} with {welcome_credit} welcome credit(s)")
logger.info(f"Created new user: {email} with {welcome_credit} welcome credit(s) (tenant: {tenant_id or 'default'})")
return user
def _save_user(self, user: User) -> None:
@@ -153,6 +164,7 @@ class UserService:
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
tenant_id=user.tenant_id,
)
# =========================================================================
@@ -163,18 +175,25 @@ class UserService:
self,
email: str,
ip_address: Optional[str] = None,
user_agent: Optional[str] = None
user_agent: Optional[str] = None,
tenant_id: Optional[str] = None
) -> MagicLinkToken:
"""
Create a magic link token for email authentication.
Returns the token object. The actual sending of the email
should be handled by the caller (or an email service).
Args:
email: User's email address
ip_address: Client IP for auditing
user_agent: Client user agent for auditing
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
"""
email = email.lower()
# Ensure user exists
self.get_or_create_user(email)
# Ensure user exists (with tenant association)
self.get_or_create_user(email, tenant_id=tenant_id)
# Generate secure token
token = secrets.token_urlsafe(32)
@@ -185,6 +204,7 @@ class UserService:
expires_at=datetime.utcnow() + timedelta(minutes=MAGIC_LINK_EXPIRY_MINUTES),
ip_address=ip_address,
user_agent=user_agent,
tenant_id=tenant_id,
)
# Save to Firestore
@@ -262,9 +282,18 @@ class UserService:
self,
user_email: str,
ip_address: Optional[str] = None,
user_agent: Optional[str] = None
user_agent: Optional[str] = None,
tenant_id: Optional[str] = None
) -> Session:
"""Create a new session for an authenticated user."""
"""
Create a new session for an authenticated user.
Args:
user_email: User's email address
ip_address: Client IP for auditing
user_agent: Client user agent for auditing
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
"""
token = secrets.token_urlsafe(32)
token_prefix = token[:12]
@@ -274,6 +303,7 @@ class UserService:
expires_at=datetime.utcnow() + timedelta(days=SESSION_ABSOLUTE_EXPIRY_DAYS),
ip_address=ip_address,
user_agent=user_agent,
tenant_id=tenant_id,
)
# Serialize and write to Firestore
@@ -128,6 +128,8 @@ class TestUserEmailExtraction:
mock_request.headers = {}
mock_request.client = Mock(host="127.0.0.1")
mock_request.url = Mock(path="/api/jobs/create-from-url")
# Mock tenant state (no tenant = default Nomad Karaoke)
mock_request.state.tenant_config = None
mock_background_tasks = Mock()
body = CreateJobFromUrlRequest(
@@ -168,6 +170,8 @@ class TestUserEmailExtraction:
mock_request.headers = {}
mock_request.client = Mock(host="127.0.0.1")
mock_request.url = Mock(path="/api/audio-search/search")
# Mock tenant state (no tenant = default Nomad Karaoke)
mock_request.state.tenant_config = None
mock_background_tasks = Mock()
body = AudioSearchRequest(
+350
View File
@@ -0,0 +1,350 @@
"""
Unit tests for tenant API routes.
Tests the /api/tenant/config endpoints.
Note: We need to patch get_tenant_service in both the routes module AND the
middleware module since the middleware runs first and also calls get_tenant_service.
"""
import pytest
from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient
from backend.models.tenant import (
TenantConfig,
TenantBranding,
TenantFeatures,
TenantDefaults,
TenantAuth,
TenantPublicConfig,
)
# Sample tenant config for mocking
SAMPLE_VOCALSTAR_CONFIG = TenantConfig(
id="vocalstar",
name="Vocal Star",
subdomain="vocalstar.nomadkaraoke.com",
is_active=True,
branding=TenantBranding(
logo_url="https://example.com/logo.png",
primary_color="#ffff00",
secondary_color="#006CF9",
site_title="Vocal Star Karaoke Generator",
),
features=TenantFeatures(
audio_search=False,
youtube_url=False,
youtube_upload=False,
dropbox_upload=False,
gdrive_upload=False,
theme_selection=False,
),
defaults=TenantDefaults(
theme_id="vocalstar",
locked_theme="vocalstar",
distribution_mode="download_only",
),
auth=TenantAuth(
allowed_email_domains=["vocal-star.com", "vocalstarmusic.com"],
require_email_domain=True,
sender_email="vocalstar@nomadkaraoke.com",
),
)
INACTIVE_CONFIG = TenantConfig(
id="inactive",
name="Inactive Tenant",
subdomain="inactive.nomadkaraoke.com",
is_active=False,
)
class TestTenantConfigEndpoint:
"""Tests for GET /api/tenant/config endpoint."""
@pytest.fixture
def mock_tenant_service(self):
"""Mock the tenant service in both routes and middleware."""
service = MagicMock()
# Patch in both places: routes AND middleware
with patch("backend.api.routes.tenant.get_tenant_service", return_value=service), \
patch("backend.middleware.tenant.get_tenant_service", return_value=service):
yield service
@pytest.fixture
def client(self, mock_tenant_service):
"""Create test client with mocked tenant service."""
from backend.main import app
return TestClient(app)
def test_get_config_default(self, client, mock_tenant_service):
"""Test returns default config when no tenant detected."""
mock_tenant_service.tenant_exists.return_value = False
response = client.get("/api/tenant/config")
assert response.status_code == 200
data = response.json()
assert data["tenant"] is None
assert data["is_default"] is True
def test_get_config_with_query_param(self, client, mock_tenant_service):
"""Test tenant detection via query parameter."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get("/api/tenant/config?tenant=vocalstar")
assert response.status_code == 200
data = response.json()
assert data["tenant"]["id"] == "vocalstar"
assert data["tenant"]["name"] == "Vocal Star"
assert data["is_default"] is False
def test_get_config_with_header(self, client, mock_tenant_service):
"""Test tenant detection via X-Tenant-ID header."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get(
"/api/tenant/config",
headers={"X-Tenant-ID": "vocalstar"},
)
assert response.status_code == 200
data = response.json()
assert data["tenant"]["id"] == "vocalstar"
assert data["is_default"] is False
def test_get_config_query_param_takes_priority(self, client, mock_tenant_service):
"""Test query param takes priority over header."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get(
"/api/tenant/config?tenant=vocalstar",
headers={"X-Tenant-ID": "other"},
)
assert response.status_code == 200
# Should use vocalstar from query param
mock_tenant_service.get_public_config.assert_called_with("vocalstar")
def test_get_config_tenant_not_found(self, client, mock_tenant_service):
"""Test returns default when tenant not found."""
mock_tenant_service.get_public_config.return_value = None
response = client.get("/api/tenant/config?tenant=nonexistent")
assert response.status_code == 200
data = response.json()
assert data["tenant"] is None
assert data["is_default"] is True
def test_get_config_inactive_tenant(self, client, mock_tenant_service):
"""Test returns default when tenant is inactive."""
inactive_public = TenantPublicConfig.from_config(INACTIVE_CONFIG)
mock_tenant_service.get_public_config.return_value = inactive_public
response = client.get("/api/tenant/config?tenant=inactive")
assert response.status_code == 200
data = response.json()
assert data["tenant"] is None
assert data["is_default"] is True
def test_get_config_includes_branding(self, client, mock_tenant_service):
"""Test response includes full branding config."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get("/api/tenant/config?tenant=vocalstar")
assert response.status_code == 200
data = response.json()
branding = data["tenant"]["branding"]
assert branding["primary_color"] == "#ffff00"
assert branding["secondary_color"] == "#006CF9"
assert branding["site_title"] == "Vocal Star Karaoke Generator"
def test_get_config_includes_features(self, client, mock_tenant_service):
"""Test response includes feature flags."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get("/api/tenant/config?tenant=vocalstar")
assert response.status_code == 200
data = response.json()
features = data["tenant"]["features"]
assert features["audio_search"] is False
assert features["file_upload"] is True
assert features["youtube_upload"] is False
def test_get_config_includes_defaults(self, client, mock_tenant_service):
"""Test response includes default settings."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get("/api/tenant/config?tenant=vocalstar")
assert response.status_code == 200
data = response.json()
defaults = data["tenant"]["defaults"]
assert defaults["theme_id"] == "vocalstar"
assert defaults["locked_theme"] == "vocalstar"
assert defaults["distribution_mode"] == "download_only"
def test_get_config_includes_allowed_domains(self, client, mock_tenant_service):
"""Test response includes allowed email domains."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get("/api/tenant/config?tenant=vocalstar")
assert response.status_code == 200
data = response.json()
assert "vocal-star.com" in data["tenant"]["allowed_email_domains"]
assert "vocalstarmusic.com" in data["tenant"]["allowed_email_domains"]
class TestTenantConfigByIdEndpoint:
"""Tests for GET /api/tenant/config/{tenant_id} endpoint."""
@pytest.fixture
def mock_tenant_service(self):
"""Mock the tenant service in both routes and middleware."""
service = MagicMock()
with patch("backend.api.routes.tenant.get_tenant_service", return_value=service), \
patch("backend.middleware.tenant.get_tenant_service", return_value=service):
yield service
@pytest.fixture
def client(self, mock_tenant_service):
"""Create test client with mocked tenant service."""
from backend.main import app
return TestClient(app)
def test_get_config_by_id_success(self, client, mock_tenant_service):
"""Test getting config by explicit ID."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get("/api/tenant/config/vocalstar")
assert response.status_code == 200
data = response.json()
assert data["tenant"]["id"] == "vocalstar"
assert data["is_default"] is False
def test_get_config_by_id_not_found(self, client, mock_tenant_service):
"""Test returns default when tenant ID not found."""
mock_tenant_service.get_public_config.return_value = None
response = client.get("/api/tenant/config/nonexistent")
assert response.status_code == 200
data = response.json()
assert data["tenant"] is None
assert data["is_default"] is True
def test_get_config_by_id_inactive(self, client, mock_tenant_service):
"""Test returns default when tenant is inactive."""
inactive_public = TenantPublicConfig.from_config(INACTIVE_CONFIG)
mock_tenant_service.get_public_config.return_value = inactive_public
response = client.get("/api/tenant/config/inactive")
assert response.status_code == 200
data = response.json()
assert data["tenant"] is None
assert data["is_default"] is True
class TestTenantAssetEndpoint:
"""Tests for GET /api/tenant/asset/{tenant_id}/{asset_name} endpoint."""
@pytest.fixture
def mock_tenant_service(self):
"""Mock the tenant service in both routes and middleware."""
service = MagicMock()
with patch("backend.api.routes.tenant.get_tenant_service", return_value=service), \
patch("backend.middleware.tenant.get_tenant_service", return_value=service):
yield service
@pytest.fixture
def client(self, mock_tenant_service):
"""Create test client with mocked tenant service."""
from backend.main import app
return TestClient(app)
def test_get_asset_redirects(self, client, mock_tenant_service):
"""Test asset endpoint redirects to signed URL."""
mock_tenant_service.get_asset_url.return_value = "https://storage.googleapis.com/signed-url"
response = client.get(
"/api/tenant/asset/vocalstar/logo.png",
follow_redirects=False,
)
# Should redirect (307 Temporary Redirect is FastAPI default)
assert response.status_code == 307
assert "storage.googleapis.com" in response.headers["location"]
def test_get_asset_not_found(self, client, mock_tenant_service):
"""Test returns 404 when asset not found."""
mock_tenant_service.get_asset_url.return_value = None
response = client.get("/api/tenant/asset/vocalstar/missing.png")
assert response.status_code == 404
assert "not found" in response.json()["detail"].lower()
class TestTenantConfigResponseSchema:
"""Tests for response schema validation."""
@pytest.fixture
def mock_tenant_service(self):
"""Mock the tenant service in both routes and middleware."""
service = MagicMock()
with patch("backend.api.routes.tenant.get_tenant_service", return_value=service), \
patch("backend.middleware.tenant.get_tenant_service", return_value=service):
yield service
@pytest.fixture
def client(self, mock_tenant_service):
"""Create test client with mocked tenant service."""
from backend.main import app
return TestClient(app)
def test_response_has_required_fields(self, client, mock_tenant_service):
"""Test response always has required fields."""
mock_tenant_service.tenant_exists.return_value = False
response = client.get("/api/tenant/config")
assert response.status_code == 200
data = response.json()
assert "tenant" in data
assert "is_default" in data
def test_tenant_config_excludes_sensitive_fields(self, client, mock_tenant_service):
"""Test public config doesn't include sensitive auth data."""
public_config = TenantPublicConfig.from_config(SAMPLE_VOCALSTAR_CONFIG)
mock_tenant_service.get_public_config.return_value = public_config
response = client.get("/api/tenant/config?tenant=vocalstar")
assert response.status_code == 200
data = response.json()
tenant = data["tenant"]
# Should NOT have full auth object
assert "auth" not in tenant
# Should NOT have sensitive defaults
assert tenant["defaults"].get("brand_prefix") is None
# Should have allowed_email_domains at top level
assert "allowed_email_domains" in tenant
+345
View File
@@ -0,0 +1,345 @@
"""
Unit tests for TenantMiddleware.
Tests tenant detection from headers, query params, and subdomains,
as well as request state attachment.
"""
import pytest
from unittest.mock import MagicMock, patch, AsyncMock
import os
from starlette.requests import Request
from starlette.datastructures import Headers
from starlette.responses import Response
from backend.middleware.tenant import (
TenantMiddleware,
get_tenant_from_request,
get_tenant_config_from_request,
NON_TENANT_SUBDOMAINS,
)
from backend.models.tenant import TenantConfig, TenantFeatures
# Sample tenant config for mocking
SAMPLE_CONFIG = TenantConfig(
id="vocalstar",
name="Vocal Star",
subdomain="vocalstar.nomadkaraoke.com",
is_active=True,
features=TenantFeatures(audio_search=False),
)
INACTIVE_CONFIG = TenantConfig(
id="inactive",
name="Inactive",
subdomain="inactive.nomadkaraoke.com",
is_active=False,
)
class MockRequest:
"""Mock Request object for testing."""
def __init__(self, headers=None, query_params=None):
self.headers = headers or {}
self.query_params = query_params or {}
self.url = MagicMock()
self.url.path = "/api/test"
self.state = MagicMock()
class TestTenantMiddleware:
"""Tests for TenantMiddleware class."""
@pytest.fixture
def middleware(self):
"""Create middleware instance."""
app = MagicMock()
return TenantMiddleware(app)
@pytest.fixture
def mock_tenant_service(self):
"""Create mock tenant service."""
with patch("backend.middleware.tenant.get_tenant_service") as mock:
service = MagicMock()
mock.return_value = service
yield service
# Tests for _extract_tenant_from_host()
def test_extract_tenant_from_host_standard_subdomain(self, middleware, mock_tenant_service):
"""Test extracting tenant from vocalstar.nomadkaraoke.com."""
mock_tenant_service.tenant_exists.return_value = True
tenant_id = middleware._extract_tenant_from_host("vocalstar.nomadkaraoke.com")
assert tenant_id == "vocalstar"
def test_extract_tenant_from_host_gen_subdomain(self, middleware, mock_tenant_service):
"""Test extracting tenant from vocalstar.gen.nomadkaraoke.com."""
mock_tenant_service.tenant_exists.return_value = True
tenant_id = middleware._extract_tenant_from_host("vocalstar.gen.nomadkaraoke.com")
assert tenant_id == "vocalstar"
def test_extract_tenant_from_host_with_port(self, middleware, mock_tenant_service):
"""Test extracting tenant when host includes port."""
mock_tenant_service.tenant_exists.return_value = True
tenant_id = middleware._extract_tenant_from_host("vocalstar.nomadkaraoke.com:443")
assert tenant_id == "vocalstar"
def test_extract_tenant_from_host_case_insensitive(self, middleware, mock_tenant_service):
"""Test host parsing is case insensitive."""
mock_tenant_service.tenant_exists.return_value = True
tenant_id = middleware._extract_tenant_from_host("VOCALSTAR.NomadKaraoke.COM")
assert tenant_id == "vocalstar"
def test_extract_tenant_from_host_empty(self, middleware):
"""Test returns None for empty host."""
tenant_id = middleware._extract_tenant_from_host("")
assert tenant_id is None
def test_extract_tenant_from_host_localhost(self, middleware):
"""Test returns None for localhost."""
tenant_id = middleware._extract_tenant_from_host("localhost:3000")
assert tenant_id is None
def test_extract_tenant_from_host_non_nomad_domain(self, middleware):
"""Test returns None for non-nomadkaraoke.com domains."""
tenant_id = middleware._extract_tenant_from_host("example.com")
assert tenant_id is None
def test_extract_tenant_from_host_base_domain(self, middleware):
"""Test returns None for nomadkaraoke.com without subdomain."""
tenant_id = middleware._extract_tenant_from_host("nomadkaraoke.com")
assert tenant_id is None
@pytest.mark.parametrize("subdomain", NON_TENANT_SUBDOMAINS)
def test_extract_tenant_from_host_non_tenant_subdomains(self, middleware, subdomain):
"""Test returns None for known non-tenant subdomains."""
host = f"{subdomain}.nomadkaraoke.com"
tenant_id = middleware._extract_tenant_from_host(host)
assert tenant_id is None
def test_extract_tenant_from_host_tenant_not_exists(self, middleware, mock_tenant_service):
"""Test returns None when tenant doesn't exist in GCS."""
mock_tenant_service.tenant_exists.return_value = False
tenant_id = middleware._extract_tenant_from_host("nonexistent.nomadkaraoke.com")
assert tenant_id is None
# Tests for _extract_tenant_id()
def test_extract_tenant_id_from_header(self, middleware):
"""Test X-Tenant-ID header takes priority."""
request = MockRequest(
headers={"X-Tenant-ID": "vocalstar", "Host": "other.nomadkaraoke.com"},
query_params={"tenant": "different"},
)
tenant_id = middleware._extract_tenant_id(request)
assert tenant_id == "vocalstar"
def test_extract_tenant_id_header_normalized(self, middleware):
"""Test header value is normalized (lowercased, stripped)."""
request = MockRequest(headers={"X-Tenant-ID": " VOCALSTAR "})
tenant_id = middleware._extract_tenant_id(request)
assert tenant_id == "vocalstar"
@patch.dict(os.environ, {"ENV": ""})
def test_extract_tenant_id_from_query_param_dev(self, middleware):
"""Test query param works in non-production."""
request = MockRequest(query_params={"tenant": "vocalstar"})
tenant_id = middleware._extract_tenant_id(request)
assert tenant_id == "vocalstar"
@patch.dict(os.environ, {"ENV": "production"})
def test_extract_tenant_id_query_param_disabled_in_prod(self, middleware, mock_tenant_service):
"""Test query param is ignored in production."""
# Need to reimport to pick up new env value
import importlib
import backend.middleware.tenant as tenant_module
# Save original value
original_is_prod = tenant_module.IS_PRODUCTION
# Temporarily set to True for this test
tenant_module.IS_PRODUCTION = True
try:
mock_tenant_service.tenant_exists.return_value = False
request = MockRequest(
query_params={"tenant": "vocalstar"},
headers={"Host": "gen.nomadkaraoke.com"},
)
tenant_id = middleware._extract_tenant_id(request)
# Should not use query param, and gen subdomain is non-tenant
assert tenant_id is None
finally:
# Restore
tenant_module.IS_PRODUCTION = original_is_prod
def test_extract_tenant_id_from_host(self, middleware, mock_tenant_service):
"""Test falls back to host header subdomain detection."""
mock_tenant_service.tenant_exists.return_value = True
request = MockRequest(headers={"Host": "vocalstar.nomadkaraoke.com"})
tenant_id = middleware._extract_tenant_id(request)
assert tenant_id == "vocalstar"
def test_extract_tenant_id_no_tenant(self, middleware, mock_tenant_service):
"""Test returns None when no tenant detected."""
mock_tenant_service.tenant_exists.return_value = False
request = MockRequest(headers={"Host": "gen.nomadkaraoke.com"})
tenant_id = middleware._extract_tenant_id(request)
assert tenant_id is None
# Tests for dispatch()
@pytest.mark.asyncio
async def test_dispatch_attaches_tenant_to_state(self, middleware, mock_tenant_service):
"""Test middleware attaches tenant info to request.state."""
mock_tenant_service.get_tenant_config.return_value = SAMPLE_CONFIG
mock_tenant_service.tenant_exists.return_value = True
request = MockRequest(headers={"X-Tenant-ID": "vocalstar"})
response = Response(content="OK")
call_next = AsyncMock(return_value=response)
result = await middleware.dispatch(request, call_next)
assert request.state.tenant_id == "vocalstar"
assert request.state.tenant_config == SAMPLE_CONFIG
@pytest.mark.asyncio
async def test_dispatch_adds_header_to_response(self, middleware, mock_tenant_service):
"""Test middleware adds X-Tenant-ID header to response."""
mock_tenant_service.get_tenant_config.return_value = SAMPLE_CONFIG
mock_tenant_service.tenant_exists.return_value = True
request = MockRequest(headers={"X-Tenant-ID": "vocalstar"})
response = Response(content="OK")
call_next = AsyncMock(return_value=response)
result = await middleware.dispatch(request, call_next)
assert result.headers.get("X-Tenant-ID") == "vocalstar"
@pytest.mark.asyncio
async def test_dispatch_no_tenant(self, middleware, mock_tenant_service):
"""Test middleware handles no tenant gracefully."""
mock_tenant_service.tenant_exists.return_value = False
request = MockRequest(headers={"Host": "gen.nomadkaraoke.com"})
response = Response(content="OK")
call_next = AsyncMock(return_value=response)
result = await middleware.dispatch(request, call_next)
assert request.state.tenant_id is None
assert request.state.tenant_config is None
assert "X-Tenant-ID" not in result.headers
@pytest.mark.asyncio
async def test_dispatch_inactive_tenant(self, middleware, mock_tenant_service):
"""Test middleware treats inactive tenant as no tenant."""
mock_tenant_service.get_tenant_config.return_value = INACTIVE_CONFIG
request = MockRequest(headers={"X-Tenant-ID": "inactive"})
response = Response(content="OK")
call_next = AsyncMock(return_value=response)
result = await middleware.dispatch(request, call_next)
# Inactive tenant should be treated as default
assert request.state.tenant_id is None
assert request.state.tenant_config is None
@pytest.mark.asyncio
async def test_dispatch_calls_next(self, middleware, mock_tenant_service):
"""Test middleware calls the next handler."""
mock_tenant_service.tenant_exists.return_value = False
request = MockRequest(headers={"Host": "gen.nomadkaraoke.com"})
response = Response(content="OK")
call_next = AsyncMock(return_value=response)
await middleware.dispatch(request, call_next)
call_next.assert_called_once_with(request)
class TestHelperFunctions:
"""Tests for helper functions."""
def test_get_tenant_from_request(self):
"""Test get_tenant_from_request helper."""
request = MagicMock()
request.state.tenant_id = "vocalstar"
assert get_tenant_from_request(request) == "vocalstar"
def test_get_tenant_from_request_none(self):
"""Test get_tenant_from_request when no tenant."""
request = MagicMock()
del request.state.tenant_id # Simulate missing attribute
assert get_tenant_from_request(request) is None
def test_get_tenant_config_from_request(self):
"""Test get_tenant_config_from_request helper."""
request = MagicMock()
request.state.tenant_config = SAMPLE_CONFIG
config = get_tenant_config_from_request(request)
assert config == SAMPLE_CONFIG
assert config.features.audio_search is False
def test_get_tenant_config_from_request_none(self):
"""Test get_tenant_config_from_request when no config."""
request = MagicMock()
del request.state.tenant_config
assert get_tenant_config_from_request(request) is None
class TestNonTenantSubdomains:
"""Tests for NON_TENANT_SUBDOMAINS constant."""
def test_gen_is_non_tenant(self):
"""Test 'gen' is in non-tenant subdomains."""
assert "gen" in NON_TENANT_SUBDOMAINS
def test_api_is_non_tenant(self):
"""Test 'api' is in non-tenant subdomains."""
assert "api" in NON_TENANT_SUBDOMAINS
def test_www_is_non_tenant(self):
"""Test 'www' is in non-tenant subdomains."""
assert "www" in NON_TENANT_SUBDOMAINS
def test_admin_is_non_tenant(self):
"""Test 'admin' is in non-tenant subdomains."""
assert "admin" in NON_TENANT_SUBDOMAINS
+406
View File
@@ -0,0 +1,406 @@
"""
Unit tests for tenant data models.
Tests the TenantConfig, TenantBranding, TenantFeatures, TenantDefaults,
TenantAuth, and TenantPublicConfig models.
"""
import pytest
from datetime import datetime
from backend.models.tenant import (
TenantConfig,
TenantBranding,
TenantFeatures,
TenantDefaults,
TenantAuth,
TenantPublicConfig,
TenantConfigResponse,
)
class TestTenantBranding:
"""Tests for TenantBranding model."""
def test_default_values(self):
"""Test that TenantBranding has sensible defaults."""
branding = TenantBranding()
assert branding.logo_url is None
assert branding.logo_height == 40
assert branding.primary_color == "#ff5bb8"
assert branding.secondary_color == "#8b5cf6"
assert branding.accent_color is None
assert branding.background_color is None
assert branding.favicon_url is None
assert branding.site_title == "Karaoke Generator"
assert branding.tagline is None
def test_custom_values(self):
"""Test TenantBranding with custom values."""
branding = TenantBranding(
logo_url="https://example.com/logo.png",
logo_height=60,
primary_color="#ffff00",
secondary_color="#0000ff",
accent_color="#ff0000",
background_color="#000000",
favicon_url="https://example.com/favicon.ico",
site_title="Custom Karaoke",
tagline="Make music magic",
)
assert branding.logo_url == "https://example.com/logo.png"
assert branding.logo_height == 60
assert branding.primary_color == "#ffff00"
assert branding.site_title == "Custom Karaoke"
class TestTenantFeatures:
"""Tests for TenantFeatures model."""
def test_default_features_enabled(self):
"""Test that most features are enabled by default."""
features = TenantFeatures()
# Input methods
assert features.audio_search is True
assert features.file_upload is True
assert features.youtube_url is True
# Distribution
assert features.youtube_upload is True
assert features.dropbox_upload is True
assert features.gdrive_upload is True
# Customization
assert features.theme_selection is True
assert features.color_overrides is True
# Output formats
assert features.enable_cdg is True
assert features.enable_4k is True
# Admin is disabled by default
assert features.admin_access is False
def test_restricted_features(self):
"""Test a restricted feature set like Vocal Star would have."""
features = TenantFeatures(
audio_search=False,
youtube_url=False,
youtube_upload=False,
dropbox_upload=False,
gdrive_upload=False,
theme_selection=False,
color_overrides=False,
)
assert features.audio_search is False
assert features.file_upload is True # Still allowed
assert features.youtube_url is False
assert features.youtube_upload is False
class TestTenantDefaults:
"""Tests for TenantDefaults model."""
def test_default_values(self):
"""Test TenantDefaults has sensible defaults."""
defaults = TenantDefaults()
assert defaults.theme_id is None
assert defaults.locked_theme is None
assert defaults.distribution_mode == "all"
assert defaults.brand_prefix is None
assert defaults.youtube_description_template is None
def test_locked_theme(self):
"""Test locked_theme setting."""
defaults = TenantDefaults(
theme_id="vocalstar",
locked_theme="vocalstar",
distribution_mode="download_only",
brand_prefix="VSTAR",
)
assert defaults.locked_theme == "vocalstar"
assert defaults.distribution_mode == "download_only"
assert defaults.brand_prefix == "VSTAR"
class TestTenantAuth:
"""Tests for TenantAuth model."""
def test_default_values(self):
"""Test TenantAuth defaults."""
auth = TenantAuth()
assert auth.allowed_email_domains == []
assert auth.require_email_domain is True
assert auth.fixed_token_ids == []
assert auth.sender_email is None
def test_restricted_domains(self):
"""Test restricted email domains configuration."""
auth = TenantAuth(
allowed_email_domains=["vocal-star.com", "vocalstarmusic.com"],
require_email_domain=True,
sender_email="vocalstar@nomadkaraoke.com",
)
assert "vocal-star.com" in auth.allowed_email_domains
assert auth.require_email_domain is True
assert auth.sender_email == "vocalstar@nomadkaraoke.com"
class TestTenantConfig:
"""Tests for TenantConfig model."""
@pytest.fixture
def basic_config(self):
"""Create a basic tenant config for testing."""
return TenantConfig(
id="vocalstar",
name="Vocal Star",
subdomain="vocalstar.nomadkaraoke.com",
)
@pytest.fixture
def full_config(self):
"""Create a fully configured tenant."""
return TenantConfig(
id="vocalstar",
name="Vocal Star",
subdomain="vocalstar.nomadkaraoke.com",
is_active=True,
branding=TenantBranding(
logo_url="https://example.com/logo.png",
primary_color="#ffff00",
secondary_color="#006CF9",
site_title="Vocal Star Karaoke Generator",
),
features=TenantFeatures(
audio_search=False,
youtube_url=False,
youtube_upload=False,
dropbox_upload=False,
gdrive_upload=False,
theme_selection=False,
),
defaults=TenantDefaults(
theme_id="vocalstar",
locked_theme="vocalstar",
distribution_mode="download_only",
),
auth=TenantAuth(
allowed_email_domains=["vocal-star.com", "vocalstarmusic.com"],
require_email_domain=True,
sender_email="vocalstar@nomadkaraoke.com",
),
)
def test_required_fields(self):
"""Test that id, name, and subdomain are required."""
config = TenantConfig(
id="test",
name="Test Tenant",
subdomain="test.nomadkaraoke.com",
)
assert config.id == "test"
assert config.name == "Test Tenant"
assert config.subdomain == "test.nomadkaraoke.com"
def test_default_is_active(self, basic_config):
"""Test that tenants are active by default."""
assert basic_config.is_active is True
def test_nested_models_have_defaults(self, basic_config):
"""Test that nested models are created with defaults."""
assert basic_config.branding is not None
assert basic_config.features is not None
assert basic_config.defaults is not None
assert basic_config.auth is not None
# Tests for get_sender_email()
def test_get_sender_email_custom(self, full_config):
"""Test get_sender_email returns custom sender when configured."""
assert full_config.get_sender_email() == "vocalstar@nomadkaraoke.com"
def test_get_sender_email_default_pattern(self, basic_config):
"""Test get_sender_email returns default pattern when not configured."""
# basic_config has no custom sender_email
assert basic_config.get_sender_email() == "vocalstar@nomadkaraoke.com"
def test_get_sender_email_different_tenant(self):
"""Test sender email follows tenant ID pattern."""
config = TenantConfig(
id="customtenant",
name="Custom",
subdomain="custom.nomadkaraoke.com",
)
assert config.get_sender_email() == "customtenant@nomadkaraoke.com"
# Tests for is_email_allowed()
def test_is_email_allowed_matching_domain(self, full_config):
"""Test email is allowed when domain matches."""
assert full_config.is_email_allowed("user@vocal-star.com") is True
assert full_config.is_email_allowed("user@vocalstarmusic.com") is True
def test_is_email_allowed_non_matching_domain(self, full_config):
"""Test email is rejected when domain doesn't match and require_email_domain=True."""
assert full_config.is_email_allowed("user@gmail.com") is False
assert full_config.is_email_allowed("user@other.com") is False
def test_is_email_allowed_case_insensitive(self, full_config):
"""Test email domain matching is case insensitive."""
assert full_config.is_email_allowed("User@VOCAL-STAR.COM") is True
assert full_config.is_email_allowed("User@VocalStarMusic.com") is True
def test_is_email_allowed_no_domain_restrictions(self, basic_config):
"""Test any email allowed when no domain restrictions."""
# basic_config has empty allowed_email_domains
assert basic_config.is_email_allowed("anyone@gmail.com") is True
assert basic_config.is_email_allowed("user@anything.com") is True
def test_is_email_allowed_require_domain_false(self):
"""Test non-matching emails allowed when require_email_domain=False."""
config = TenantConfig(
id="flexible",
name="Flexible Tenant",
subdomain="flexible.nomadkaraoke.com",
auth=TenantAuth(
allowed_email_domains=["preferred.com"],
require_email_domain=False, # Don't require matching
),
)
# Matching domain still works
assert config.is_email_allowed("user@preferred.com") is True
# Non-matching also allowed since require_email_domain=False
assert config.is_email_allowed("user@other.com") is True
def test_is_email_allowed_partial_domain_no_match(self, full_config):
"""Test partial domain matches don't work (must be exact suffix)."""
# "star.com" should not match "vocal-star.com"
assert full_config.is_email_allowed("user@star.com") is False
# Subdomain of allowed domain should work
assert full_config.is_email_allowed("user@sub.vocal-star.com") is False
class TestTenantPublicConfig:
"""Tests for TenantPublicConfig model."""
@pytest.fixture
def full_config(self):
"""Create a fully configured tenant for conversion testing."""
return TenantConfig(
id="vocalstar",
name="Vocal Star",
subdomain="vocalstar.nomadkaraoke.com",
is_active=True,
branding=TenantBranding(
logo_url="https://example.com/logo.png",
primary_color="#ffff00",
),
features=TenantFeatures(
audio_search=False,
admin_access=True, # This should be included in public config
),
defaults=TenantDefaults(
theme_id="vocalstar",
locked_theme="vocalstar",
distribution_mode="download_only",
brand_prefix="VSTAR", # This should NOT be in public config
youtube_description_template="Custom template", # This should NOT be in public config
),
auth=TenantAuth(
allowed_email_domains=["vocal-star.com"],
require_email_domain=True,
fixed_token_ids=["secret-token-123"], # This should NOT be in public config
sender_email="vocalstar@nomadkaraoke.com", # This should NOT be in public config
),
)
def test_from_config_basic_fields(self, full_config):
"""Test that basic fields are copied correctly."""
public = TenantPublicConfig.from_config(full_config)
assert public.id == "vocalstar"
assert public.name == "Vocal Star"
assert public.subdomain == "vocalstar.nomadkaraoke.com"
assert public.is_active is True
def test_from_config_branding_included(self, full_config):
"""Test that branding is fully included."""
public = TenantPublicConfig.from_config(full_config)
assert public.branding.logo_url == "https://example.com/logo.png"
assert public.branding.primary_color == "#ffff00"
def test_from_config_features_included(self, full_config):
"""Test that features are fully included."""
public = TenantPublicConfig.from_config(full_config)
assert public.features.audio_search is False
assert public.features.admin_access is True
def test_from_config_allowed_email_domains_included(self, full_config):
"""Test that allowed_email_domains is included for frontend validation."""
public = TenantPublicConfig.from_config(full_config)
assert "vocal-star.com" in public.allowed_email_domains
def test_from_config_sensitive_auth_excluded(self, full_config):
"""Test that sensitive auth fields are not in public config."""
public = TenantPublicConfig.from_config(full_config)
# TenantPublicConfig only has allowed_email_domains from auth
# It should NOT have fixed_token_ids or sender_email
assert not hasattr(public, 'auth')
# allowed_email_domains is a top-level field
assert hasattr(public, 'allowed_email_domains')
def test_from_config_defaults_partially_included(self, full_config):
"""Test that only safe defaults are included."""
public = TenantPublicConfig.from_config(full_config)
# These should be included
assert public.defaults.theme_id == "vocalstar"
assert public.defaults.locked_theme == "vocalstar"
assert public.defaults.distribution_mode == "download_only"
# brand_prefix and youtube_description_template should NOT be included
# The from_config method creates a new TenantDefaults without these
assert public.defaults.brand_prefix is None
assert public.defaults.youtube_description_template is None
class TestTenantConfigResponse:
"""Tests for TenantConfigResponse model."""
def test_default_response(self):
"""Test default response indicates no tenant."""
response = TenantConfigResponse()
assert response.tenant is None
assert response.is_default is True
def test_tenant_response(self):
"""Test response with tenant config."""
public_config = TenantPublicConfig(
id="vocalstar",
name="Vocal Star",
subdomain="vocalstar.nomadkaraoke.com",
is_active=True,
branding=TenantBranding(),
features=TenantFeatures(),
defaults=TenantDefaults(),
)
response = TenantConfigResponse(tenant=public_config, is_default=False)
assert response.tenant is not None
assert response.tenant.id == "vocalstar"
assert response.is_default is False
+418
View File
@@ -0,0 +1,418 @@
"""
Unit tests for TenantService.
Tests config loading from GCS, caching behavior, subdomain resolution,
and email domain validation.
"""
import pytest
from datetime import datetime, timedelta
from unittest.mock import MagicMock, patch
from backend.services.tenant_service import TenantService, get_tenant_service
from backend.models.tenant import TenantConfig, TenantPublicConfig
# Sample tenant config data that would come from GCS
SAMPLE_VOCALSTAR_CONFIG = {
"id": "vocalstar",
"name": "Vocal Star",
"subdomain": "vocalstar.nomadkaraoke.com",
"is_active": True,
"branding": {
"logo_url": "https://example.com/logo.png",
"logo_height": 50,
"primary_color": "#ffff00",
"secondary_color": "#006CF9",
"site_title": "Vocal Star Karaoke Generator",
},
"features": {
"audio_search": False,
"file_upload": True,
"youtube_url": False,
"youtube_upload": False,
"dropbox_upload": False,
"gdrive_upload": False,
"theme_selection": False,
},
"defaults": {
"theme_id": "vocalstar",
"locked_theme": "vocalstar",
"distribution_mode": "download_only",
},
"auth": {
"allowed_email_domains": ["vocal-star.com", "vocalstarmusic.com"],
"require_email_domain": True,
"sender_email": "vocalstar@nomadkaraoke.com",
},
}
SAMPLE_INACTIVE_CONFIG = {
"id": "inactive",
"name": "Inactive Tenant",
"subdomain": "inactive.nomadkaraoke.com",
"is_active": False,
"branding": {},
"features": {},
"defaults": {},
"auth": {},
}
class TestTenantService:
"""Tests for TenantService class."""
@pytest.fixture
def mock_storage(self):
"""Create a mock StorageService."""
storage = MagicMock()
storage.file_exists.return_value = False
storage.download_json.return_value = {}
storage.generate_signed_url.return_value = "https://signed-url.example.com"
return storage
@pytest.fixture
def tenant_service(self, mock_storage):
"""Create a TenantService with mock storage."""
return TenantService(storage=mock_storage)
# Tests for get_tenant_config()
def test_get_tenant_config_success(self, tenant_service, mock_storage):
"""Test successful config loading from GCS."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
config = tenant_service.get_tenant_config("vocalstar")
assert config is not None
assert config.id == "vocalstar"
assert config.name == "Vocal Star"
assert config.features.audio_search is False
mock_storage.download_json.assert_called_once_with("tenants/vocalstar/config.json")
def test_get_tenant_config_not_found(self, tenant_service, mock_storage):
"""Test returns None when tenant config doesn't exist."""
mock_storage.file_exists.return_value = False
config = tenant_service.get_tenant_config("nonexistent")
assert config is None
mock_storage.download_json.assert_not_called()
def test_get_tenant_config_gcs_error(self, tenant_service, mock_storage):
"""Test handles GCS errors gracefully."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.side_effect = Exception("GCS error")
config = tenant_service.get_tenant_config("vocalstar")
assert config is None
# Tests for caching behavior
def test_config_is_cached(self, tenant_service, mock_storage):
"""Test that configs are cached after first load."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# First call loads from GCS
config1 = tenant_service.get_tenant_config("vocalstar")
# Second call should use cache
config2 = tenant_service.get_tenant_config("vocalstar")
assert config1 is config2
# download_json should only be called once
assert mock_storage.download_json.call_count == 1
def test_force_refresh_bypasses_cache(self, tenant_service, mock_storage):
"""Test that force_refresh reloads from GCS."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# First call
tenant_service.get_tenant_config("vocalstar")
# Force refresh
tenant_service.get_tenant_config("vocalstar", force_refresh=True)
# download_json should be called twice
assert mock_storage.download_json.call_count == 2
def test_cache_expires_after_ttl(self, tenant_service, mock_storage):
"""Test that cache expires after TTL."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# Load config
tenant_service.get_tenant_config("vocalstar")
# Simulate cache expiration by manipulating cache time
tenant_service._cache_times["vocalstar"] = datetime.now() - timedelta(seconds=400)
# Next call should reload
tenant_service.get_tenant_config("vocalstar")
assert mock_storage.download_json.call_count == 2
# Tests for get_tenant_by_subdomain()
def test_get_tenant_by_subdomain_cached(self, tenant_service, mock_storage):
"""Test subdomain lookup uses cache."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# First load by ID to populate cache
tenant_service.get_tenant_config("vocalstar")
# Now lookup by subdomain should use cached mapping
config = tenant_service.get_tenant_by_subdomain("vocalstar.nomadkaraoke.com")
assert config is not None
assert config.id == "vocalstar"
def test_get_tenant_by_subdomain_fallback_resolution(self, tenant_service, mock_storage):
"""Test subdomain resolution when not in cache."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# Lookup by subdomain without prior cache
config = tenant_service.get_tenant_by_subdomain("vocalstar.nomadkaraoke.com")
assert config is not None
assert config.id == "vocalstar"
def test_get_tenant_by_subdomain_not_found(self, tenant_service, mock_storage):
"""Test returns None for unknown subdomain."""
mock_storage.file_exists.return_value = False
config = tenant_service.get_tenant_by_subdomain("unknown.nomadkaraoke.com")
assert config is None
def test_get_tenant_by_subdomain_case_insensitive(self, tenant_service, mock_storage):
"""Test subdomain lookup is case insensitive."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
config = tenant_service.get_tenant_by_subdomain("VOCALSTAR.NomadKaraoke.COM")
assert config is not None
assert config.id == "vocalstar"
# Tests for _resolve_subdomain_to_tenant_id()
def test_resolve_subdomain_3_parts(self, tenant_service, mock_storage):
"""Test resolving tenant.nomadkaraoke.com pattern."""
mock_storage.file_exists.return_value = True
tenant_id = tenant_service._resolve_subdomain_to_tenant_id("vocalstar.nomadkaraoke.com")
assert tenant_id == "vocalstar"
def test_resolve_subdomain_4_parts(self, tenant_service, mock_storage):
"""Test resolving tenant.gen.nomadkaraoke.com pattern."""
mock_storage.file_exists.return_value = True
tenant_id = tenant_service._resolve_subdomain_to_tenant_id("vocalstar.gen.nomadkaraoke.com")
assert tenant_id == "vocalstar"
def test_resolve_subdomain_too_short(self, tenant_service, mock_storage):
"""Test returns None for subdomains with fewer than 3 parts."""
tenant_id = tenant_service._resolve_subdomain_to_tenant_id("nomadkaraoke.com")
assert tenant_id is None
def test_resolve_subdomain_tenant_not_exists(self, tenant_service, mock_storage):
"""Test returns None when tenant config doesn't exist in GCS."""
mock_storage.file_exists.return_value = False
tenant_id = tenant_service._resolve_subdomain_to_tenant_id("nonexistent.nomadkaraoke.com")
assert tenant_id is None
# Tests for get_public_config()
def test_get_public_config_success(self, tenant_service, mock_storage):
"""Test getting public config."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
public_config = tenant_service.get_public_config("vocalstar")
assert public_config is not None
assert isinstance(public_config, TenantPublicConfig)
assert public_config.id == "vocalstar"
def test_get_public_config_not_found(self, tenant_service, mock_storage):
"""Test returns None when tenant not found."""
mock_storage.file_exists.return_value = False
public_config = tenant_service.get_public_config("nonexistent")
assert public_config is None
def test_get_public_config_by_subdomain(self, tenant_service, mock_storage):
"""Test getting public config by subdomain."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
public_config = tenant_service.get_public_config_by_subdomain("vocalstar.nomadkaraoke.com")
assert public_config is not None
assert public_config.id == "vocalstar"
# Tests for tenant_exists()
def test_tenant_exists_true(self, tenant_service, mock_storage):
"""Test returns True when config exists."""
mock_storage.file_exists.return_value = True
assert tenant_service.tenant_exists("vocalstar") is True
mock_storage.file_exists.assert_called_with("tenants/vocalstar/config.json")
def test_tenant_exists_false(self, tenant_service, mock_storage):
"""Test returns False when config doesn't exist."""
mock_storage.file_exists.return_value = False
assert tenant_service.tenant_exists("nonexistent") is False
# Tests for is_email_allowed_for_tenant()
def test_is_email_allowed_for_tenant_valid(self, tenant_service, mock_storage):
"""Test email allowed for valid domain."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
assert tenant_service.is_email_allowed_for_tenant("vocalstar", "user@vocal-star.com") is True
def test_is_email_allowed_for_tenant_invalid(self, tenant_service, mock_storage):
"""Test email not allowed for invalid domain."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
assert tenant_service.is_email_allowed_for_tenant("vocalstar", "user@gmail.com") is False
def test_is_email_allowed_for_tenant_not_found(self, tenant_service, mock_storage):
"""Test returns False when tenant not found."""
mock_storage.file_exists.return_value = False
assert tenant_service.is_email_allowed_for_tenant("nonexistent", "user@any.com") is False
# Tests for get_tenant_sender_email()
def test_get_tenant_sender_email_custom(self, tenant_service, mock_storage):
"""Test returns custom sender email when configured."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
sender = tenant_service.get_tenant_sender_email("vocalstar")
assert sender == "vocalstar@nomadkaraoke.com"
def test_get_tenant_sender_email_default(self, tenant_service, mock_storage):
"""Test returns default sender when tenant not found."""
mock_storage.file_exists.return_value = False
sender = tenant_service.get_tenant_sender_email("nonexistent")
# Should match DEFAULT_SENDER_EMAIL constant (consistent with EmailService)
assert sender == "gen@nomadkaraoke.com"
# Tests for invalidate_cache()
def test_invalidate_cache_specific_tenant(self, tenant_service, mock_storage):
"""Test invalidating cache for specific tenant."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# Load into cache
tenant_service.get_tenant_config("vocalstar")
assert "vocalstar" in tenant_service._config_cache
# Invalidate
tenant_service.invalidate_cache("vocalstar")
assert "vocalstar" not in tenant_service._config_cache
assert "vocalstar" not in tenant_service._cache_times
def test_invalidate_cache_specific_tenant_clears_subdomain_map(self, tenant_service, mock_storage):
"""Test invalidating specific tenant also clears its subdomain map entry."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# Load into cache (this also populates subdomain map)
tenant_service.get_tenant_config("vocalstar")
assert "vocalstar.nomadkaraoke.com" in tenant_service._subdomain_map
assert tenant_service._subdomain_map["vocalstar.nomadkaraoke.com"] == "vocalstar"
# Invalidate specific tenant
tenant_service.invalidate_cache("vocalstar")
# Subdomain map entry should also be removed
assert "vocalstar.nomadkaraoke.com" not in tenant_service._subdomain_map
def test_invalidate_cache_all(self, tenant_service, mock_storage):
"""Test invalidating all caches."""
mock_storage.file_exists.return_value = True
mock_storage.download_json.return_value = SAMPLE_VOCALSTAR_CONFIG
# Load into cache
tenant_service.get_tenant_config("vocalstar")
# Invalidate all
tenant_service.invalidate_cache()
assert len(tenant_service._config_cache) == 0
assert len(tenant_service._cache_times) == 0
assert len(tenant_service._subdomain_map) == 0
# Tests for get_asset_url()
def test_get_asset_url_success(self, tenant_service, mock_storage):
"""Test getting signed URL for existing asset."""
mock_storage.file_exists.return_value = True
url = tenant_service.get_asset_url("vocalstar", "logo.png")
assert url == "https://signed-url.example.com"
mock_storage.file_exists.assert_called_with("tenants/vocalstar/logo.png")
mock_storage.generate_signed_url.assert_called_with("tenants/vocalstar/logo.png", expiration_minutes=60)
def test_get_asset_url_not_found(self, tenant_service, mock_storage):
"""Test returns None when asset doesn't exist."""
mock_storage.file_exists.return_value = False
url = tenant_service.get_asset_url("vocalstar", "missing.png")
assert url is None
mock_storage.generate_signed_url.assert_not_called()
class TestGetTenantServiceSingleton:
"""Tests for the get_tenant_service() singleton function."""
def test_returns_same_instance(self):
"""Test that get_tenant_service returns singleton."""
# Reset the singleton
import backend.services.tenant_service as module
module._tenant_service = None
with patch.object(TenantService, '__init__', return_value=None):
service1 = get_tenant_service()
service2 = get_tenant_service()
assert service1 is service2
def test_thread_safe_initialization(self):
"""Test that singleton initialization is thread-safe."""
import threading
import backend.services.tenant_service as module
# Reset the singleton
module._tenant_service = None
instances = []
def get_instance():
with patch.object(TenantService, '__init__', return_value=None):
instances.append(get_tenant_service())
threads = [threading.Thread(target=get_instance) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
# All instances should be the same
assert all(i is instances[0] for i in instances)
+64
View File
@@ -199,6 +199,70 @@ GET /api/themes
No auth required. Returns available video themes.
### Tenant Config
```http
GET /api/tenant/config
GET /api/tenant/config?tenant=vocalstar
```
No auth required. Returns tenant configuration for white-label portals.
**Detection priority**:
1. `X-Tenant-ID` header (explicitly set by frontend)
2. `tenant` query parameter (development/testing only, disabled in production)
3. Host header subdomain detection (e.g., `vocalstar.nomadkaraoke.com`)
Response:
```json
{
"tenant": {
"id": "vocalstar",
"name": "Vocal Star",
"subdomain": "vocalstar.nomadkaraoke.com",
"is_active": true,
"branding": {
"logo_url": "https://storage.googleapis.com/...",
"logo_height": 60,
"primary_color": "#ffff00",
"secondary_color": "#006CF9",
"accent_color": "#ffffff",
"background_color": "#000000",
"favicon_url": null,
"site_title": "Vocal Star Karaoke Generator",
"tagline": "Whoever You Are, Be a Vocal Star!"
},
"features": {
"audio_search": false,
"file_upload": true,
"youtube_url": false,
"youtube_upload": false,
"dropbox_upload": false,
"gdrive_upload": false,
"theme_selection": false,
"color_overrides": false,
"enable_cdg": true,
"enable_4k": true,
"admin_access": false
},
"defaults": {
"theme_id": "vocalstar",
"locked_theme": "vocalstar",
"distribution_mode": "download_only"
}
},
"is_default": false
}
```
When no tenant is detected, returns `tenant: null` with `is_default: true` and the default Nomad Karaoke configuration is used.
```http
GET /api/tenant/config/{tenant_id}
```
Get specific tenant config by ID. Returns 404 if tenant not found or inactive.
### Internal (Admin Only)
These endpoints are used by workers and require admin tokens.
+120
View File
@@ -217,6 +217,126 @@ The Video Worker uses an orchestrator pattern to ensure all features work regard
| `template_service.py` | GCS-backed email templates |
| `job_notification_service.py` | Email orchestration (completion, reminders) |
## Multitenancy
The platform supports white-label B2B portals where business customers get their own branded karaoke generation experience.
### Architecture
```text
┌─────────────────────────────────────────────────────────────────┐
│ Tenant Detection Flow │
│ │
│ Request arrives at vocalstar.nomadkaraoke.com │
│ │ │
│ ▼ │
│ Frontend: detectTenantFromUrl() │
│ - Extracts subdomain from hostname │
│ - Calls GET /api/tenant/config?tenant=vocalstar │
│ │ │
│ ▼ │
│ Backend: TenantMiddleware │
│ 1. X-Tenant-ID header (from frontend) │
│ 2. Query param (dev only, disabled in production) │
│ 3. Host header subdomain detection │
│ │ │
│ ▼ │
│ TenantService.get_tenant_config() │
│ - Loads from GCS: tenants/{tenant_id}/config.json │
│ - Caches in memory (5 min TTL) │
│ │ │
│ ▼ │
│ Request proceeds with tenant context │
│ - request.state.tenant_id │
│ - request.state.tenant_config │
└─────────────────────────────────────────────────────────────────┘
```
### GCS Storage Layout
```text
tenants/{tenant_id}/
├── config.json # TenantConfig with branding, features, defaults
└── logo.jpg # Tenant logo (optional)
themes/{theme_id}/
├── style_params.json # Full theme configuration
└── assets/
├── intro_background.png
├── karaoke_background.jpg
├── end_background.png
├── font.ttf
└── cdg_*.gif
```
### Tenant Config Schema
```python
TenantConfig:
id: str # e.g., "vocalstar"
name: str # Display name: "Vocal Star"
subdomain: str # e.g., "vocalstar.nomadkaraoke.com"
is_active: bool # Enable/disable tenant
branding:
logo_url: str | None # GCS path to logo
logo_height: int # Pixels
primary_color: str # Hex color
secondary_color: str
accent_color: str | None
background_color: str | None
favicon_url: str | None
site_title: str
tagline: str | None
features:
audio_search: bool # Enable audio search (vs file upload only)
file_upload: bool
youtube_url: bool
youtube_upload: bool # YouTube distribution
dropbox_upload: bool
gdrive_upload: bool
theme_selection: bool # Allow user to pick theme
color_overrides: bool
enable_cdg: bool
enable_4k: bool
admin_access: bool
defaults:
theme_id: str | None # Default theme if not locked
locked_theme: str | None # Force this theme (user cannot change)
distribution_mode: str # "all", "download_only", etc.
auth:
allowed_email_domains: list[str] # e.g., ["vocal-star.com"]
require_email_domain: bool
sender_email: str | None # Override email sender
```
### Feature Enforcement
**Frontend**: The `useTenant()` hook provides `features` object. UI components conditionally render based on enabled features:
```typescript
const { features } = useTenant()
if (!features.audio_search) {
// Hide audio search tab
}
```
**Backend**: Routes check tenant config from request state:
```python
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(403, "Audio search not enabled for this tenant")
```
### First Tenant: Vocal Star
- Subdomain: `vocalstar.nomadkaraoke.com`
- Features: File upload only (no audio search, no YouTube URL)
- Distribution: Download only (no YouTube/Dropbox/GDrive)
- Theme: Locked to "vocalstar" theme (yellow/blue)
- Auth: Restricted to `@vocal-star.com` and `@vocalstarmusic.com` emails
- Setup: `python scripts/setup-vocalstar-tenant.py`
## Tech Stack
- **Backend**: FastAPI, Python 3.12, Cloud Run
+131
View File
@@ -2069,6 +2069,137 @@ NOMAD-XXXX - Artist - Title/
**Lesson**: When building distribution packages from cloud storage, the organization code must replicate the exact structure users expect from local execution. Track ALL intermediate files in `job.files` even if they're "optional" - users may rely on them.
### Multitenancy: Config-Driven Feature Flags
**Problem**: Adding B2B white-label support required tenant-specific feature restrictions (e.g., Vocal Star can't use audio search) without creating separate codebases or hardcoding tenant checks throughout the code.
**Solution**: Config-driven multitenancy with feature flags:
1. **GCS-backed config**: Each tenant has `tenants/{tenant_id}/config.json` in GCS containing branding, features, and defaults. Changes don't require deployment.
2. **Middleware-based detection**: `TenantMiddleware` extracts tenant from X-Tenant-ID header, query param (dev only), or Host subdomain, then loads config and attaches to request state.
3. **Feature flags in config**:
```json
"features": {
"audio_search": false,
"youtube_upload": false,
"theme_selection": false
}
```
4. **Frontend checks via Zustand store**:
```typescript
const { features } = useTenant()
// Conditionally render UI based on features.audio_search
```
5. **Backend enforcement**:
```python
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(403, "Feature not enabled")
```
**Key decisions**:
- **Query param disabled in production**: Prevents tenant spoofing via URL manipulation
- **Strict subdomain patterns**: Only accept `{tenant}.nomadkaraoke.com` or `{tenant}.gen.nomadkaraoke.com`
- **PII protection**: Mask emails in logs (`an***@vo***.com`)
- **Locked themes**: `locked_theme` field prevents users from changing theme even if `theme_selection` is enabled elsewhere
- **CSS variables for branding**: Dynamic colors via `--tenant-primary`, `--tenant-secondary` etc.
**Lesson**: Config-driven multitenancy scales better than code branches. New tenants require only a JSON file in GCS, not code changes. Feature flags belong in config, not environment variables.
### Frontend Tab State Sync with Feature Flags
**Problem**: When tenant config changes which tabs are available (e.g., audio_search disabled), the active tab state could point to a tab that no longer exists, causing UI to show nothing.
**Solution**: Add useEffect to sync activeTab with available tabs:
```typescript
useEffect(() => {
if (!availableTabs.includes(activeTab)) {
setActiveTab(availableTabs[0])
}
}, [availableTabs, activeTab])
```
**Lesson**: When feature flags control UI visibility, derived state (like "which tab is selected") must react to flag changes. Initialize state to valid values AND keep it valid as context changes.
### Hydration-Safe Initialization in Next.js
**Problem**: Module-level auto-initialization (e.g., `setTimeout(fetchTenantConfig, 0)`) in a Zustand store caused hydration mismatches in Next.js. Server renders with default state, client starts fetching immediately, causing React hydration errors.
**Solution**: Remove module-level auto-init. Use explicit `TenantProvider` component that calls `fetchTenantConfig()` in useEffect:
```typescript
// TenantProvider.tsx
useEffect(() => {
if (!isInitialized) {
fetchTenantConfig()
}
}, [isInitialized, fetchTenantConfig])
```
**Lesson**: In Next.js with SSR, never auto-initialize async state at module load time. Use React lifecycle (useEffect) to trigger client-side fetches after hydration completes.
### Zustand Getters Don't Work with Direct setState
**Problem**: Unit tests for Zustand stores that use JavaScript getter properties (`get branding() {}`) fail when using `useTenant.setState()` to set up test state.
```typescript
// Store definition
const useTenant = create<TenantStore>()((set, get) => ({
tenant: null,
get branding() {
const { tenant } = get()
return tenant?.branding ?? DEFAULT_BRANDING
},
// ...
}))
// Test that FAILS
useTenant.setState({ tenant: SAMPLE_CONFIG })
const state = useTenant.getState()
expect(state.branding.primary_color).toBe("#ffff00") // Gets default instead!
```
**Why**: Zustand's `setState` merges state using object spread, which evaluates getters once and stores static values. The getter function isn't preserved - its current value is copied.
**Solution**: Use the store's action methods (like `setTenant()`) instead of direct `setState()`, or access the raw data (`state.tenant?.branding`) rather than computed properties:
```typescript
// Working test - use the store's action
useTenant.getState().setTenant(SAMPLE_CONFIG, false)
const state = useTenant.getState()
expect(state.tenant?.branding.primary_color).toBe("#ffff00") // Works!
```
**Lesson**: For Zustand stores with computed properties (getters), test through the store's actions rather than direct `setState()`. The actions update the internal state that the getters reference.
### Middleware Mocking Requires Patching Multiple Locations
**Problem**: API route unit tests fail with real service calls despite mocking `get_tenant_service` in the routes module.
```python
# Test that FAILS
with patch("backend.api.routes.tenant.get_tenant_service", return_value=mock_service):
response = client.get("/api/tenant/config")
# Still calls real TenantService!
```
**Why**: FastAPI middleware runs BEFORE routes. `TenantMiddleware` also calls `get_tenant_service()` to load tenant config. The route mock doesn't affect the middleware.
**Solution**: Patch in BOTH the routes AND middleware modules:
```python
# Working test
with patch("backend.api.routes.tenant.get_tenant_service", return_value=mock_service), \
patch("backend.middleware.tenant.get_tenant_service", return_value=mock_service):
response = client.get("/api/tenant/config")
# Now properly mocked!
```
**Lesson**: When mocking singleton/factory functions in FastAPI, trace all call sites. Middleware often shares services with routes - mock both locations.
## What We'd Do Differently
1. **Add Pydantic model fields test first** - Would have caught the silent field issue immediately
+3
View File
@@ -29,6 +29,7 @@
| Admin dashboard | Working |
| CI/CD self-hosted runner | Working (GCP) |
| E2E happy path test | Working (~20-25 min full pipeline) |
| **White-label B2B portals** | Working (Vocal Star first tenant) |
## Known Issues
@@ -40,6 +41,8 @@
## Recent Changes
- **White-Label B2B Portal Infrastructure** (2026-01-08): Added multi-tenant support for white-label karaoke portals. Vocal Star is the first tenant at `vocalstar.nomadkaraoke.com`. Features: subdomain-based tenant detection (frontend and backend), GCS-backed tenant config storage, per-tenant feature flags (audio search, file upload, YouTube, theme selection, etc.), dynamic branding (logo, colors, site title via CSS variables), locked themes per tenant, email domain restrictions for auth, and tenant-scoped jobs/users in Firestore. Backend: `TenantMiddleware` extracts tenant from X-Tenant-ID header, query param (dev only), or Host subdomain; `TenantService` loads config from GCS with caching. Frontend: Zustand store for tenant state, `TenantProvider` for initialization, `TenantLogo` component. Setup script: `scripts/setup-vocalstar-tenant.py`. See [ARCHITECTURE.md](ARCHITECTURE.md#multitenancy) and [API.md](API.md#tenant-config).
- **Encoding Worker Infrastructure Upgrade** (2026-01-08): Upgraded GCE encoding worker from c4-standard-8 (Intel) to c4d-highcpu-32 (AMD EPYC 9B45 Turin). Benchmarking showed **4.92x faster encoding** (135s vs 666s total). Key improvements: With Vocals 4K rendering 6x faster (54s vs 324s), 720p downscale 4.6x faster (11s vs 50s). Reduces total encoding time from ~11 min to ~2.3 min per job. See [archive/2026-01-08-performance-investigation.md](archive/2026-01-08-performance-investigation.md) for full benchmark methodology and results.
- **Theme Enforcement & Encoding Resilience** (2026-01-08): Added defense-in-depth theme enforcement - jobs without theme_id are now rejected at creation (JobManager) with a safety net at processing time (screens_worker). Fixed done-for-you webhook to apply default theme. Added retry logic with exponential backoff (3 retries, 2s→4s→8s) to GCE encoding service for transient connection failures during worker restarts. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#defense-in-depth-enforce-critical-requirements-at-multiple-layers).
@@ -0,0 +1,271 @@
# White-Label B2B Portal Implementation
**Date**: 2026-01-08
**Status**: Complete
**First Tenant**: Vocal Star
## Overview
Implemented multi-tenant white-label portal infrastructure allowing B2B customers to have their own branded karaoke generation experience at custom subdomains.
## First Customer: Vocal Star
**Requirements**:
- Subdomain: `vocalstar.nomadkaraoke.com`
- File upload only (no audio search, no YouTube URL input)
- Download only distribution (no YouTube/Dropbox/GDrive upload)
- Theme locked to "vocalstar" (yellow/blue color scheme)
- Auth restricted to `@vocal-star.com` and `@vocalstarmusic.com` email domains
- Custom branding: logo, colors, site title, tagline
## Architecture
### Tenant Detection Flow
```
Request → Frontend detectTenantFromUrl() → Backend TenantMiddleware → TenantService → GCS Config
```
**Frontend** (`frontend/lib/tenant.ts`):
- Zustand store for tenant state
- `detectTenantFromUrl()` extracts subdomain from hostname
- Strict patterns: `{tenant}.nomadkaraoke.com` or `{tenant}.gen.nomadkaraoke.com`
- Query param `?tenant=X` for local development only
**Backend** (`backend/middleware/tenant.py`):
- `TenantMiddleware` extracts tenant from:
1. `X-Tenant-ID` header (from frontend)
2. Query param (dev only - disabled in production via `IS_PRODUCTION` check)
3. Host header subdomain
- Attaches `tenant_id` and `tenant_config` to `request.state`
**Config Storage** (`backend/services/tenant_service.py`):
- Loads from GCS: `tenants/{tenant_id}/config.json`
- In-memory cache with 5-minute TTL
- Signed URL generation for logos
### GCS Structure
```
tenants/{tenant_id}/
├── config.json # TenantConfig
└── logo.jpg # Tenant logo
themes/{theme_id}/
├── style_params.json # Theme configuration
└── assets/
├── intro_background.png
├── karaoke_background.jpg
├── end_background.png
├── Oswald-SemiBold.ttf
├── cdg_instrumental_background.gif
└── cdg_title_background.gif
```
### Config Schema
```python
TenantConfig:
id: str
name: str
subdomain: str
is_active: bool
branding: TenantBranding
logo_url: str | None
logo_height: int
primary_color: str
secondary_color: str
accent_color: str | None
background_color: str | None
favicon_url: str | None
site_title: str
tagline: str | None
features: TenantFeatures
audio_search: bool
file_upload: bool
youtube_url: bool
youtube_upload: bool
dropbox_upload: bool
gdrive_upload: bool
theme_selection: bool
color_overrides: bool
enable_cdg: bool
enable_4k: bool
admin_access: bool
defaults: TenantDefaults
theme_id: str | None
locked_theme: str | None
distribution_mode: str
auth: TenantAuth
allowed_email_domains: list[str]
require_email_domain: bool
sender_email: str | None
```
## Implementation Details
### Backend Changes
1. **Tenant Models** (`backend/models/tenant.py`):
- Pydantic models for config schema
- `locked_theme` field for forcing specific theme
2. **Tenant Service** (`backend/services/tenant_service.py`):
- GCS config loading with caching
- Logo signed URL generation
- `tenant_exists()` check for subdomain validation
3. **Tenant API** (`backend/api/routes/tenant.py`):
- `GET /api/tenant/config` - auto-detect or explicit tenant
- `GET /api/tenant/config/{tenant_id}` - specific tenant lookup
4. **Middleware** (`backend/middleware/tenant.py`):
- Priority-based tenant detection
- Production security: query param disabled
- `get_tenant_from_request()` helper
5. **Auth Updates** (`backend/services/auth_service.py`):
- Email domain validation for tenant-restricted auth
- Sender email override from tenant config
6. **Feature Enforcement**:
- Audio search endpoint checks `features.audio_search`
- Returns 403 if feature disabled for tenant
7. **Job/User Scoping**:
- `tenant_id` field added to `JobCreate`
- Jobs created with tenant context from request
### Frontend Changes
1. **Tenant Store** (`frontend/lib/tenant.ts`):
- Zustand store with tenant state
- `useTenant()` hook for components
- Default Nomad Karaoke branding fallback
- CSS variable application via `applyTenantBranding()`
2. **TenantProvider** (`frontend/components/tenant-provider.tsx`):
- Wraps app in layout
- Fetches config on mount
- Prevents hydration issues (no module-level init)
3. **TenantLogo** (`frontend/components/tenant-logo.tsx`):
- Dynamic logo based on tenant
- Falls back to Nomad Karaoke logo
- Supports GCS signed URLs for tenant logos
4. **Feature-Flagged UI** (`frontend/components/job/JobSubmission.tsx`):
- Tabs conditionally rendered based on `features`
- Active tab sync when features change
- `useMemo` for available tabs list
5. **Locked Themes**:
- `defaults.locked_theme` hides theme selector
- Uses locked theme for all jobs
6. **Output Links**:
- Filtered based on `features.youtube_upload`, `features.dropbox_upload`, etc.
### Security Measures
1. **Query param disabled in production**:
```python
IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production"
if not IS_PRODUCTION:
query_tenant = request.query_params.get("tenant")
```
2. **Strict subdomain patterns**:
```typescript
const isValidPattern =
parts.length === 3 ||
(parts.length === 4 && parts[1] === "gen")
```
3. **PII protection in logs**:
```python
def _mask_email(email: str) -> str:
# "andrew@vocal-star.com" → "an***@vo***.com"
```
4. **is_active check**: Inactive tenants treated as default
## Setup Script
`scripts/setup-vocalstar-tenant.py`:
- Uploads theme assets to GCS
- Creates theme config (`style_params.json`)
- Uploads tenant logo
- Creates tenant config (`config.json`)
- Updates theme registry
**Usage**:
```bash
# Set resources path (or pass as argument)
export VOCALSTAR_RESOURCES=/path/to/VocalStar/Resources
python scripts/setup-vocalstar-tenant.py
# Or with argument
python scripts/setup-vocalstar-tenant.py /path/to/VocalStar/Resources
```
## Files Changed
### Backend
- `backend/models/tenant.py` - New
- `backend/services/tenant_service.py` - New
- `backend/api/routes/tenant.py` - New
- `backend/middleware/tenant.py` - New
- `backend/main.py` - Added middleware and routes
- `backend/models/job.py` - Added tenant_id field
- `backend/services/auth_service.py` - Email domain validation
- `backend/api/routes/users.py` - PII masking in logs
- `backend/api/routes/audio_search.py` - Feature check
### Frontend
- `frontend/lib/tenant.ts` - New
- `frontend/components/tenant-provider.tsx` - New
- `frontend/components/tenant-logo.tsx` - New
- `frontend/components/app-layout.tsx` - TenantProvider wrapper
- `frontend/components/job/JobSubmission.tsx` - Feature flags
- `frontend/components/job/OutputLinks.tsx` - Distribution filtering
### Scripts
- `scripts/setup-vocalstar-tenant.py` - New
## Testing
- Frontend build verified (TypeScript compilation)
- CodeRabbit review: 3 cycles, all issues fixed
- Manual testing with `?tenant=vocalstar` query param
### Unit Tests Added
**Backend tests (110 tests)**:
- `test_tenant_models.py` - 28 tests for Pydantic models (TenantConfig, branding, features, defaults, auth, public config, `is_email_allowed()`, `get_sender_email()`, `from_config()`)
- `test_tenant_service.py` - 30 tests for TenantService (config loading, caching, subdomain resolution)
- `test_tenant_middleware.py` - 35 tests for TenantMiddleware (header/query param/subdomain detection, NON_TENANT_SUBDOMAINS filtering)
- `test_tenant_api.py` - 17 tests for `/api/tenant/config` endpoints
**Frontend tests (22 tests)**:
- `tenant.test.ts` - Tests for Zustand store, `getTenantHeaders()`, `isFeatureEnabled()`
**Key testing patterns**:
- API route tests must patch `get_tenant_service` in BOTH routes AND middleware modules since middleware runs first
- Zustand tests use `useTenant.getState().setTenant()` instead of direct `setState()` to properly handle computed properties
- `test_job_creation_regression.py` fixed to mock `request.state.tenant_config = None`
## Next Steps
1. Configure DNS: CNAME for `vocalstar.nomadkaraoke.com`
2. Update Cloudflare Pages for subdomain
3. Run setup script to upload Vocal Star assets
4. Test at `https://vocalstar.nomadkaraoke.com`
## Lessons Learned
1. **Config-driven multitenancy** scales better than code branches
2. **Query params for dev, headers for prod** prevents spoofing
3. **Feature flags belong in config**, not environment variables
4. **Zustand + Next.js**: Don't auto-init at module level, use useEffect
5. **Tab state must react to feature changes** - sync active tab with available tabs
+12 -3
View File
@@ -19,6 +19,15 @@
--brand-blue: #3b82f6;
--brand-soft-pink: #ec4899;
/* ===========================================
Tenant Branding Colors (set dynamically by JS)
These are overridden by TenantProvider for white-label portals
=========================================== */
--tenant-primary: var(--brand-pink);
--tenant-secondary: var(--brand-purple);
--tenant-accent: var(--brand-gold);
--tenant-background: #0f0f0f;
/* Dark theme (default) */
--bg: #0f0f0f;
--card: #1a1a1a;
@@ -28,9 +37,9 @@
--text-muted: #888888;
--text-subtle: #666666;
/* Primary now uses brand pink */
--primary: var(--brand-pink);
--primary-hover: var(--brand-pink-hover);
/* Primary uses tenant color (defaults to brand pink) */
--primary: var(--tenant-primary);
--primary-hover: color-mix(in srgb, var(--tenant-primary) 80%, white 20%);
--secondary: #252525;
--secondary-hover: #333333;
+4 -1
View File
@@ -1,6 +1,7 @@
import type React from "react"
import type { Metadata } from "next"
import { ThemeProvider } from "@/components/theme-provider"
import { TenantProvider } from "@/components/tenant-provider"
import "./globals.css"
export const metadata: Metadata = {
@@ -30,7 +31,9 @@ export default function RootLayout({
enableSystem
disableTransitionOnChange
>
{children}
<TenantProvider>
{children}
</TenantProvider>
</ThemeProvider>
</body>
</html>
+90 -48
View File
@@ -1,8 +1,9 @@
"use client"
import { useState } from "react"
import { useState, useEffect, useMemo } from "react"
import { api, ApiError } from "@/lib/api"
import { useAuth } from "@/lib/auth"
import { useTenant } from "@/lib/tenant"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
@@ -15,9 +16,30 @@ interface JobSubmissionProps {
export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
const { user } = useAuth()
const { features, isDefault, tenant } = useTenant()
const isAdmin = user?.role === "admin"
const [activeTab, setActiveTab] = useState("search")
// Determine which tabs are available based on tenant features
const availableTabs = useMemo(() => {
const tabs: string[] = []
if (features.audio_search) tabs.push("search")
if (features.file_upload) tabs.push("upload")
if (features.youtube_url) tabs.push("url")
// Fallback: at least show upload if no tabs enabled
if (tabs.length === 0) tabs.push("upload")
return tabs
}, [features])
// Default to first available tab
const [activeTab, setActiveTab] = useState(availableTabs[0])
// Keep activeTab in sync with availableTabs when features change
useEffect(() => {
if (!availableTabs.includes(activeTab)) {
setActiveTab(availableTabs[0])
}
}, [availableTabs, activeTab])
const [error, setError] = useState("")
const [isSubmitting, setIsSubmitting] = useState(false)
@@ -156,37 +178,52 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
return (
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-3 h-auto rounded-lg p-1" style={{ backgroundColor: 'var(--secondary)' }}>
<TabsTrigger
value="search"
className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm rounded-md data-[state=active]:!bg-[var(--brand-pink)] data-[state=active]:!text-white data-[state=active]:shadow-md data-[state=inactive]:hover:bg-[var(--brand-pink)]/10"
style={{ color: activeTab === 'search' ? 'white' : 'var(--text-muted)' }}
{/* Only show tabs bar when there are multiple options */}
{availableTabs.length > 1 && (
<TabsList
className={`grid w-full h-auto rounded-lg p-1 ${
availableTabs.length === 2 ? 'grid-cols-2' : 'grid-cols-3'
}`}
style={{ backgroundColor: 'var(--secondary)' }}
>
<Music className="w-4 h-4 shrink-0" />
<span className="truncate">Search</span>
</TabsTrigger>
<TabsTrigger
value="upload"
className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm rounded-md data-[state=active]:!bg-[var(--brand-pink)] data-[state=active]:!text-white data-[state=active]:shadow-md data-[state=inactive]:hover:bg-[var(--brand-pink)]/10"
style={{ color: activeTab === 'upload' ? 'white' : 'var(--text-muted)' }}
>
<Upload className="w-4 h-4 shrink-0" />
<span className="truncate">Upload</span>
</TabsTrigger>
<TabsTrigger
value="url"
className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm rounded-md data-[state=active]:!bg-[var(--brand-pink)] data-[state=active]:!text-white data-[state=active]:shadow-md data-[state=inactive]:hover:bg-[var(--brand-pink)]/10"
style={{ color: activeTab === 'url' ? 'white' : 'var(--text-muted)' }}
>
<Youtube className="w-4 h-4 shrink-0" />
<span className="truncate">URL</span>
</TabsTrigger>
</TabsList>
{availableTabs.includes("search") && (
<TabsTrigger
value="search"
className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm rounded-md data-[state=active]:!bg-[var(--brand-pink)] data-[state=active]:!text-white data-[state=active]:shadow-md data-[state=inactive]:hover:bg-[var(--brand-pink)]/10"
style={{ color: activeTab === 'search' ? 'white' : 'var(--text-muted)' }}
>
<Music className="w-4 h-4 shrink-0" />
<span className="truncate">Search</span>
</TabsTrigger>
)}
{availableTabs.includes("upload") && (
<TabsTrigger
value="upload"
className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm rounded-md data-[state=active]:!bg-[var(--brand-pink)] data-[state=active]:!text-white data-[state=active]:shadow-md data-[state=inactive]:hover:bg-[var(--brand-pink)]/10"
style={{ color: activeTab === 'upload' ? 'white' : 'var(--text-muted)' }}
>
<Upload className="w-4 h-4 shrink-0" />
<span className="truncate">Upload</span>
</TabsTrigger>
)}
{availableTabs.includes("url") && (
<TabsTrigger
value="url"
className="gap-1.5 sm:gap-2 py-3 min-h-[44px] text-xs sm:text-sm rounded-md data-[state=active]:!bg-[var(--brand-pink)] data-[state=active]:!text-white data-[state=active]:shadow-md data-[state=inactive]:hover:bg-[var(--brand-pink)]/10"
style={{ color: activeTab === 'url' ? 'white' : 'var(--text-muted)' }}
>
<Youtube className="w-4 h-4 shrink-0" />
<span className="truncate">URL</span>
</TabsTrigger>
)}
</TabsList>
)}
<TabsContent value="upload" className="mt-4">
<form onSubmit={handleUploadSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="audio-file" style={{ color: 'var(--text)' }}>Audio File</Label>
{availableTabs.includes("upload") && (
<TabsContent value="upload" className={availableTabs.length === 1 ? "" : "mt-4"}>
<form onSubmit={handleUploadSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="audio-file" style={{ color: 'var(--text)' }}>Audio File</Label>
<div
className="relative border-2 border-dashed rounded-lg p-6 text-center transition-colors cursor-pointer"
style={{
@@ -288,13 +325,15 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
"Create Karaoke Video"
)}
</Button>
</form>
</TabsContent>
</form>
</TabsContent>
)}
<TabsContent value="url" className="mt-4">
<form onSubmit={handleUrlSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="youtube-url" style={{ color: 'var(--text)' }}>YouTube URL</Label>
{availableTabs.includes("url") && (
<TabsContent value="url" className={availableTabs.length === 1 ? "" : "mt-4"}>
<form onSubmit={handleUrlSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="youtube-url" style={{ color: 'var(--text)' }}>YouTube URL</Label>
<div className="relative">
<Youtube className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4" style={{ color: 'var(--text-muted)' }} />
<Input
@@ -380,15 +419,17 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
) : (
"Create Karaoke Video"
)}
</Button>
</form>
</TabsContent>
</Button>
</form>
</TabsContent>
)}
<TabsContent value="search" className="mt-4">
<form onSubmit={handleSearchSubmit} className="space-y-4">
{/* Search For section */}
<div className="space-y-2">
<Label style={{ color: 'var(--text)' }}>Search For Audio Online</Label>
{availableTabs.includes("search") && (
<TabsContent value="search" className={availableTabs.length === 1 ? "" : "mt-4"}>
<form onSubmit={handleSearchSubmit} className="space-y-4">
{/* Search For section */}
<div className="space-y-2">
<Label style={{ color: 'var(--text)' }}>Search For Audio Online</Label>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
<div className="space-y-2">
<Label htmlFor="search-artist" className="text-xs" style={{ color: 'var(--text-muted)' }}>Artist</Label>
@@ -511,9 +552,10 @@ export function JobSubmission({ onJobCreated }: JobSubmissionProps) {
) : (
"Search & Create Job"
)}
</Button>
</form>
</TabsContent>
</Button>
</form>
</TabsContent>
)}
</Tabs>
)
}
+12 -6
View File
@@ -2,6 +2,7 @@
import { useEffect, useState, useRef, useCallback } from "react"
import { api, adminApi } from "@/lib/api"
import { useTenant } from "@/lib/tenant"
import { Button } from "@/components/ui/button"
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, MessageSquare } from "lucide-react"
import { useAuth } from "@/lib/auth"
@@ -37,8 +38,13 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
const emailTimeoutRef = useRef<NodeJS.Timeout | null>(null)
const { user } = useAuth()
const { features } = useTenant()
const isAdmin = user?.role === 'admin'
// Filter external links based on tenant features
const showYoutubeLink = features.youtube_upload && youtubeUrl
const showDropboxLink = features.dropbox_upload && dropboxUrl
useEffect(() => {
loadOutputLinks()
}, [jobId])
@@ -167,7 +173,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
)
}
const hasOutputs = youtubeUrl || dropboxUrl || (downloadUrls && Object.keys(downloadUrls).length > 0)
const hasOutputs = showYoutubeLink || showDropboxLink || (downloadUrls && Object.keys(downloadUrls).length > 0)
// Check if we have any downloads
const hasDownloads = downloadUrls && (
@@ -178,8 +184,8 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
downloadUrls?.packages?.txt_zip
)
// Check if we have any external links
const hasExternalLinks = youtubeUrl || dropboxUrl
// Check if we have any external links (filtered by tenant features)
const hasExternalLinks = showYoutubeLink || showDropboxLink
return (
<div className="space-y-3">
@@ -242,12 +248,12 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
</div>
)}
{/* Actions Section */}
{/* Actions Section - only show links enabled for tenant */}
{hasExternalLinks && (
<div className="space-y-1.5">
<p className="text-xs font-medium" style={{ color: 'var(--text-muted)' }}>Links</p>
<div className="flex flex-wrap gap-1.5">
{youtubeUrl && (
{showYoutubeLink && youtubeUrl && (
<div className="flex">
<a
href={youtubeUrl}
@@ -270,7 +276,7 @@ export function OutputLinks({ jobId }: OutputLinksProps) {
</button>
</div>
)}
{dropboxUrl && (
{showDropboxLink && dropboxUrl && (
<div className="flex">
<a
href={dropboxUrl}
+43 -3
View File
@@ -2,12 +2,13 @@
import { useState, useEffect } from "react"
import { api } from "@/lib/api"
import { useTenant } from "@/lib/tenant"
import type { VideoThemeSummary } from "@/lib/video-themes"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Button } from "@/components/ui/button"
import { Palette, AlertCircle, Eye, EyeOff } from "lucide-react"
import { Palette, AlertCircle, Eye, EyeOff, Lock } from "lucide-react"
interface ThemeSelectorProps {
value?: string
@@ -16,11 +17,15 @@ interface ThemeSelectorProps {
}
export function ThemeSelector({ value, onChange, disabled }: ThemeSelectorProps) {
const { defaults, isDefault: isDefaultTenant } = useTenant()
const [themes, setThemes] = useState<VideoThemeSummary[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [showPreview, setShowPreview] = useState(false)
// Check if theme is locked by tenant config
const lockedTheme = defaults.locked_theme
useEffect(() => {
async function loadThemes() {
try {
@@ -29,6 +34,12 @@ export function ThemeSelector({ value, onChange, disabled }: ThemeSelectorProps)
const themeList = await api.listThemes()
setThemes(themeList)
// If theme is locked by tenant, always use that
if (lockedTheme) {
onChange(lockedTheme)
return
}
// If no value is set and there's a default theme, select it
if (!value && themeList.length > 0) {
const defaultTheme = themeList.find(t => t.is_default)
@@ -47,7 +58,7 @@ export function ThemeSelector({ value, onChange, disabled }: ThemeSelectorProps)
}
loadThemes()
}, []) // Only run once on mount
}, [lockedTheme]) // Re-run if locked theme changes
const selectedTheme = themes.find(t => t.id === value)
@@ -78,6 +89,35 @@ export function ThemeSelector({ value, onChange, disabled }: ThemeSelectorProps)
)
}
// If theme is locked by tenant, show read-only display
if (lockedTheme && selectedTheme) {
return (
<div className="space-y-2">
<Label className="flex items-center gap-2" style={{ color: 'var(--text)' }}>
<Palette className="w-4 h-4" />
Video Theme
</Label>
<div
className="flex items-center gap-2 px-3 py-2 rounded-md border"
style={{ backgroundColor: 'var(--secondary)', borderColor: 'var(--card-border)', color: 'var(--text)' }}
>
<Lock className="w-4 h-4" style={{ color: 'var(--text-muted)' }} />
<span>{selectedTheme.name}</span>
</div>
{/* Optional: Show theme preview for locked themes */}
{selectedTheme.thumbnail_url && (
<div className="mt-2 relative w-full aspect-video max-w-xs rounded-lg overflow-hidden border" style={{ borderColor: 'var(--card-border)' }}>
<img
src={selectedTheme.thumbnail_url}
alt={`${selectedTheme.name} preview`}
className="w-full h-full object-cover"
/>
</div>
)}
</div>
)
}
return (
<div className="space-y-2">
<Label htmlFor="theme-select" className="flex items-center gap-2" style={{ color: 'var(--text)' }}>
@@ -88,7 +128,7 @@ export function ThemeSelector({ value, onChange, disabled }: ThemeSelectorProps)
<Select
value={value || ""}
onValueChange={(val) => onChange(val || undefined)}
disabled={disabled}
disabled={disabled || !!lockedTheme}
>
<SelectTrigger
id="theme-select"
+74
View File
@@ -0,0 +1,74 @@
"use client"
import Image from "next/image"
import { useTenant } from "@/lib/tenant"
// Default Nomad Karaoke logo URL
const DEFAULT_LOGO_URL =
"https://nomadkaraoke.com/wp-content/uploads/2024/07/Nomad-Karaoke-Logo-TextOnly-Cropped-FromSVG-HQ-2048x1088.png"
interface TenantLogoProps {
className?: string
size?: "sm" | "lg"
}
/**
* Logo component that displays either the tenant's logo or the default Nomad Karaoke logo.
* Automatically adapts based on the current tenant configuration.
*/
export function TenantLogo({ className = "", size = "sm" }: TenantLogoProps) {
const { tenant, branding, isDefault } = useTenant()
// Determine logo URL and dimensions
const logoUrl = branding.logo_url || DEFAULT_LOGO_URL
const logoHeight = branding.logo_height || 40
// Size classes based on size prop - use static Tailwind classes only
// Dynamic height is applied via inline style
const sizeClasses =
size === "lg"
? "max-w-[600px]"
: "max-w-[200px]"
// Compute max height for inline style
const maxHeight = size === "lg" ? 120 : logoHeight
// For tenant logos, use img tag since they come from GCS signed URLs
// For default logo, use Next.js Image for optimization
if (!isDefault && branding.logo_url) {
return (
<div className={`flex items-center ${className}`}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={logoUrl}
alt={tenant?.name || "Logo"}
className={`w-auto h-auto ${sizeClasses} object-contain`}
style={{ maxHeight }}
/>
</div>
)
}
// Default Nomad Karaoke logo with Next.js Image optimization
return (
<div className={`flex items-center ${className}`}>
<Image
src={DEFAULT_LOGO_URL}
alt="Nomad Karaoke"
width={200}
height={106}
className={`w-auto h-auto ${sizeClasses} object-contain`}
style={{ maxHeight }}
priority
/>
</div>
)
}
/**
* Standalone Logo component for backward compatibility.
* Simply wraps TenantLogo.
*/
export function Logo({ className = "", size = "sm" }: TenantLogoProps) {
return <TenantLogo className={className} size={size} />
}
+66
View File
@@ -0,0 +1,66 @@
"use client"
import { useEffect, type ReactNode } from "react"
import { useTenant } from "@/lib/tenant"
interface TenantProviderProps {
children: ReactNode
}
/**
* Provider component that initializes tenant configuration on mount.
* Wrap your app with this component to enable multi-tenant support.
*
* The provider:
* 1. Detects tenant from URL subdomain or query param
* 2. Fetches tenant configuration from API
* 3. Applies tenant branding (colors, logo, title)
*
* Usage:
* ```tsx
* <TenantProvider>
* <YourApp />
* </TenantProvider>
* ```
*/
export function TenantProvider({ children }: TenantProviderProps) {
const { fetchTenantConfig, isInitialized } = useTenant()
useEffect(() => {
// Fetch tenant config on mount if not already initialized
if (!isInitialized) {
fetchTenantConfig()
}
}, [fetchTenantConfig, isInitialized])
return <>{children}</>
}
/**
* Hook to check if tenant is ready (initialized and not loading).
* Use this to conditionally render content that depends on tenant config.
*/
export function useTenantReady(): boolean {
const { isInitialized, isLoading } = useTenant()
return isInitialized && !isLoading
}
/**
* Component that only renders children when tenant is ready.
* Shows a loading state while tenant config is being fetched.
*/
export function TenantReady({
children,
fallback,
}: {
children: ReactNode
fallback?: ReactNode
}) {
const isReady = useTenantReady()
if (!isReady) {
return fallback ?? null
}
return <>{children}</>
}
+323
View File
@@ -0,0 +1,323 @@
/**
* Tests for tenant store and utilities
*
* These tests verify the tenant configuration system for white-label portals.
* They test the Zustand store, helper functions, and URL detection logic.
*/
import {
useTenant,
getTenantHeaders,
isFeatureEnabled,
TenantConfig,
} from "../tenant"
// Mock fetch globally
global.fetch = jest.fn()
// Mock document for applyTenantBranding tests
const mockSetProperty = jest.fn()
Object.defineProperty(document, "documentElement", {
value: {
style: {
setProperty: mockSetProperty,
},
},
writable: true,
})
// Sample tenant config for testing
const SAMPLE_VOCALSTAR_CONFIG: TenantConfig = {
id: "vocalstar",
name: "Vocal Star",
subdomain: "vocalstar.nomadkaraoke.com",
is_active: true,
branding: {
logo_url: "https://example.com/logo.png",
logo_height: 50,
primary_color: "#ffff00",
secondary_color: "#006CF9",
accent_color: "#ff0000",
background_color: "#000000",
favicon_url: "https://example.com/favicon.ico",
site_title: "Vocal Star Karaoke Generator",
tagline: "Professional Karaoke",
},
features: {
audio_search: false,
file_upload: true,
youtube_url: false,
youtube_upload: false,
dropbox_upload: false,
gdrive_upload: false,
theme_selection: false,
color_overrides: false,
enable_cdg: true,
enable_4k: true,
admin_access: false,
},
defaults: {
theme_id: "vocalstar",
locked_theme: "vocalstar",
distribution_mode: "download_only",
},
allowed_email_domains: ["vocal-star.com", "vocalstarmusic.com"],
}
// Helper to reset store state
function resetStore() {
useTenant.setState({
tenant: null,
isDefault: true,
isLoading: false,
error: null,
isInitialized: false,
})
}
describe("useTenant store", () => {
beforeEach(() => {
jest.clearAllMocks()
resetStore()
mockSetProperty.mockClear()
})
describe("initial state", () => {
it("should have null tenant initially", () => {
const state = useTenant.getState()
expect(state.tenant).toBeNull()
expect(state.isDefault).toBe(true)
expect(state.isLoading).toBe(false)
expect(state.error).toBeNull()
expect(state.isInitialized).toBe(false)
})
})
describe("computed values", () => {
it("should return default branding when no tenant", () => {
const state = useTenant.getState()
expect(state.branding.primary_color).toBe("#ff5bb8")
expect(state.branding.secondary_color).toBe("#8b5cf6")
expect(state.branding.site_title).toBe("Nomad Karaoke Generator")
})
it("should return tenant branding when tenant is set via setTenant", () => {
// Use setTenant action (not direct setState) to properly update state
useTenant.getState().setTenant(SAMPLE_VOCALSTAR_CONFIG, false)
const state = useTenant.getState()
expect(state.tenant?.branding.primary_color).toBe("#ffff00")
expect(state.tenant?.branding.site_title).toBe("Vocal Star Karaoke Generator")
})
it("should return default features when no tenant", () => {
const state = useTenant.getState()
expect(state.features.audio_search).toBe(true)
expect(state.features.file_upload).toBe(true)
expect(state.features.youtube_upload).toBe(true)
})
it("should return tenant features when tenant is set via setTenant", () => {
useTenant.getState().setTenant(SAMPLE_VOCALSTAR_CONFIG, false)
const state = useTenant.getState()
expect(state.tenant?.features.audio_search).toBe(false)
expect(state.tenant?.features.youtube_upload).toBe(false)
expect(state.tenant?.features.file_upload).toBe(true)
})
it("should return tenantId when tenant is set via setTenant", () => {
useTenant.getState().setTenant(SAMPLE_VOCALSTAR_CONFIG, false)
const state = useTenant.getState()
expect(state.tenant?.id).toBe("vocalstar")
})
it("should return null tenantId when no tenant", () => {
const state = useTenant.getState()
expect(state.tenantId).toBeNull()
})
})
describe("fetchTenantConfig", () => {
it("should fetch and set tenant config", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({
tenant: SAMPLE_VOCALSTAR_CONFIG,
is_default: false,
}),
})
await useTenant.getState().fetchTenantConfig()
const state = useTenant.getState()
expect(state.tenant?.id).toBe("vocalstar")
expect(state.isDefault).toBe(false)
expect(state.isInitialized).toBe(true)
})
it("should apply branding CSS variables on fetch", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({
tenant: SAMPLE_VOCALSTAR_CONFIG,
is_default: false,
}),
})
await useTenant.getState().fetchTenantConfig()
expect(mockSetProperty).toHaveBeenCalledWith("--tenant-primary", "#ffff00")
expect(mockSetProperty).toHaveBeenCalledWith("--tenant-secondary", "#006CF9")
})
it("should handle fetch error gracefully", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: false,
status: 500,
})
await useTenant.getState().fetchTenantConfig()
const state = useTenant.getState()
expect(state.tenant).toBeNull()
expect(state.isDefault).toBe(true)
expect(state.error).toBeTruthy()
expect(state.isInitialized).toBe(true)
})
it("should handle network error gracefully", async () => {
;(global.fetch as jest.Mock).mockRejectedValueOnce(new Error("Network error"))
await useTenant.getState().fetchTenantConfig()
const state = useTenant.getState()
expect(state.tenant).toBeNull()
expect(state.error).toBe("Network error")
expect(state.isInitialized).toBe(true)
})
it("should not fetch if already loading", async () => {
useTenant.setState({ isLoading: true })
await useTenant.getState().fetchTenantConfig()
expect(global.fetch).not.toHaveBeenCalled()
})
it("should set default config when no tenant returned", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({
tenant: null,
is_default: true,
}),
})
await useTenant.getState().fetchTenantConfig()
const state = useTenant.getState()
expect(state.tenant).toBeNull()
expect(state.isDefault).toBe(true)
expect(state.isInitialized).toBe(true)
})
})
describe("setTenant", () => {
it("should set tenant directly", () => {
useTenant.getState().setTenant(SAMPLE_VOCALSTAR_CONFIG, false)
const state = useTenant.getState()
expect(state.tenant?.id).toBe("vocalstar")
expect(state.isDefault).toBe(false)
expect(state.isInitialized).toBe(true)
})
it("should apply branding when setting tenant", () => {
useTenant.getState().setTenant(SAMPLE_VOCALSTAR_CONFIG, false)
expect(mockSetProperty).toHaveBeenCalledWith("--tenant-primary", "#ffff00")
})
it("should handle null tenant", () => {
useTenant.setState({ tenant: SAMPLE_VOCALSTAR_CONFIG })
useTenant.getState().setTenant(null, true)
const state = useTenant.getState()
expect(state.tenant).toBeNull()
expect(state.isDefault).toBe(true)
})
})
describe("clearError", () => {
it("should clear error", () => {
useTenant.setState({ error: "Some error" })
expect(useTenant.getState().error).toBe("Some error")
useTenant.getState().clearError()
expect(useTenant.getState().error).toBeNull()
})
})
})
describe("getTenantHeaders", () => {
beforeEach(() => {
resetStore()
})
it("should return empty object when no tenant", () => {
const headers = getTenantHeaders()
expect(headers).toEqual({})
})
it("should return X-Tenant-ID header when tenant is set via setTenant", () => {
useTenant.getState().setTenant(SAMPLE_VOCALSTAR_CONFIG, false)
const headers = getTenantHeaders()
expect(headers).toEqual({ "X-Tenant-ID": "vocalstar" })
})
})
describe("isFeatureEnabled", () => {
beforeEach(() => {
resetStore()
})
it("should return default feature values when no tenant", () => {
expect(isFeatureEnabled("audio_search")).toBe(true)
expect(isFeatureEnabled("file_upload")).toBe(true)
expect(isFeatureEnabled("youtube_upload")).toBe(true)
// admin_access defaults to true on frontend (for Nomad Karaoke default experience)
expect(isFeatureEnabled("admin_access")).toBe(true)
})
it("should return tenant feature values when tenant is set via setTenant", () => {
useTenant.getState().setTenant(SAMPLE_VOCALSTAR_CONFIG, false)
expect(isFeatureEnabled("audio_search")).toBe(false)
expect(isFeatureEnabled("youtube_upload")).toBe(false)
expect(isFeatureEnabled("file_upload")).toBe(true)
expect(isFeatureEnabled("enable_cdg")).toBe(true)
})
})
describe("API fetch behavior", () => {
beforeEach(() => {
jest.clearAllMocks()
resetStore()
})
it("should call API endpoint when fetching tenant config", async () => {
;(global.fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
json: async () => ({ tenant: null, is_default: true }),
})
await useTenant.getState().fetchTenantConfig()
expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining("/api/tenant/config"),
expect.any(Object)
)
})
})
+1 -1
View File
@@ -7,7 +7,7 @@ import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse }
// In development, use relative URLs to go through Next.js proxy (avoids CORS)
// In production (static export), use the full backend URL
const API_BASE_URL = typeof window !== 'undefined' && window.location.hostname === 'localhost'
export const API_BASE_URL = typeof window !== 'undefined' && window.location.hostname === 'localhost'
? '' // Relative URL - goes through Next.js proxy
: (process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com');
+296
View File
@@ -0,0 +1,296 @@
"use client"
import { create } from "zustand"
import { API_BASE_URL } from "./api"
// Types for tenant configuration
export interface TenantBranding {
logo_url: string | null
logo_height: number
primary_color: string
secondary_color: string
accent_color: string | null
background_color: string | null
favicon_url: string | null
site_title: string
tagline: string | null
}
export interface TenantFeatures {
audio_search: boolean
file_upload: boolean
youtube_url: boolean
youtube_upload: boolean
dropbox_upload: boolean
gdrive_upload: boolean
theme_selection: boolean
color_overrides: boolean
enable_cdg: boolean
enable_4k: boolean
admin_access: boolean
}
export interface TenantDefaults {
theme_id: string | null
locked_theme: string | null
distribution_mode: string
}
export interface TenantConfig {
id: string
name: string
subdomain: string
is_active: boolean
branding: TenantBranding
features: TenantFeatures
defaults: TenantDefaults
allowed_email_domains: string[]
}
export interface TenantConfigResponse {
tenant: TenantConfig | null
is_default: boolean
}
// Default Nomad Karaoke configuration (used when no tenant detected)
const DEFAULT_BRANDING: TenantBranding = {
logo_url: null, // Will use default Nomad Karaoke logo
logo_height: 40,
primary_color: "#ff5bb8", // Pink
secondary_color: "#8b5cf6", // Purple
accent_color: "#ffdf6b", // Yellow
background_color: null,
favicon_url: null,
site_title: "Nomad Karaoke Generator",
tagline: null,
}
const DEFAULT_FEATURES: TenantFeatures = {
audio_search: true,
file_upload: true,
youtube_url: true,
youtube_upload: true,
dropbox_upload: true,
gdrive_upload: true,
theme_selection: true,
color_overrides: true,
enable_cdg: true,
enable_4k: true,
admin_access: true,
}
const DEFAULT_DEFAULTS: TenantDefaults = {
theme_id: null,
locked_theme: null,
distribution_mode: "all",
}
// Zustand store for tenant state
interface TenantStore {
// State
tenant: TenantConfig | null
isDefault: boolean
isLoading: boolean
error: string | null
isInitialized: boolean
// Computed values (convenience accessors)
branding: TenantBranding
features: TenantFeatures
defaults: TenantDefaults
tenantId: string | null
// Actions
fetchTenantConfig: () => Promise<void>
setTenant: (tenant: TenantConfig | null, isDefault: boolean) => void
clearError: () => void
}
/**
* Detect tenant from current URL subdomain.
* Returns tenant ID if on a tenant subdomain, null otherwise.
*/
function detectTenantFromUrl(): string | null {
if (typeof window === "undefined") return null
const hostname = window.location.hostname.toLowerCase()
// Local development - check for tenant query param
if (hostname === "localhost" || hostname === "127.0.0.1") {
const params = new URLSearchParams(window.location.search)
return params.get("tenant")
}
// Production - check for subdomain
// Strict patterns:
// - {tenant}.nomadkaraoke.com (3 parts)
// - {tenant}.gen.nomadkaraoke.com (4 parts with "gen" as second)
if (hostname.includes("nomadkaraoke.com")) {
const parts = hostname.split(".")
// Skip known non-tenant subdomains
const nonTenantSubdomains = ["gen", "api", "www", "buy", "admin", "app", "beta"]
// Accept exactly 3 parts (tenant.nomadkaraoke.com)
// or exactly 4 parts where second is "gen" (tenant.gen.nomadkaraoke.com)
const isValidPattern =
parts.length === 3 ||
(parts.length === 4 && parts[1] === "gen")
if (isValidPattern && !nonTenantSubdomains.includes(parts[0])) {
return parts[0]
}
}
return null
}
export const useTenant = create<TenantStore>()((set, get) => ({
// Initial state
tenant: null,
isDefault: true,
isLoading: false,
error: null,
isInitialized: false,
// Computed values
get branding() {
const { tenant } = get()
return tenant?.branding ?? DEFAULT_BRANDING
},
get features() {
const { tenant } = get()
return tenant?.features ?? DEFAULT_FEATURES
},
get defaults() {
const { tenant } = get()
return tenant?.defaults ?? DEFAULT_DEFAULTS
},
get tenantId() {
const { tenant } = get()
return tenant?.id ?? null
},
// Actions
fetchTenantConfig: async () => {
const state = get()
if (state.isLoading) return // Already loading
set({ isLoading: true, error: null })
try {
// Detect tenant from URL
const tenantId = detectTenantFromUrl()
// Build URL with optional tenant query param
let url = `${API_BASE_URL}/api/tenant/config`
if (tenantId) {
url += `?tenant=${encodeURIComponent(tenantId)}`
}
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
// Include X-Tenant-ID header for backend detection
...(tenantId ? { "X-Tenant-ID": tenantId } : {}),
},
})
if (!response.ok) {
throw new Error("Failed to fetch tenant configuration")
}
const data: TenantConfigResponse = await response.json()
set({
tenant: data.tenant,
isDefault: data.is_default,
isLoading: false,
isInitialized: true,
})
// Apply tenant branding to CSS variables
if (data.tenant) {
applyTenantBranding(data.tenant.branding)
}
} catch (err) {
console.error("Failed to fetch tenant config:", err)
set({
tenant: null,
isDefault: true,
isLoading: false,
error: err instanceof Error ? err.message : "Failed to load tenant configuration",
isInitialized: true,
})
}
},
setTenant: (tenant, isDefault) => {
set({ tenant, isDefault, isInitialized: true })
if (tenant) {
applyTenantBranding(tenant.branding)
}
},
clearError: () => set({ error: null }),
}))
/**
* Apply tenant branding by setting CSS custom properties.
* This allows dynamic theming without changing the stylesheet.
*/
function applyTenantBranding(branding: TenantBranding) {
if (typeof document === "undefined") return
const root = document.documentElement
// Set CSS custom properties for tenant colors
root.style.setProperty("--tenant-primary", branding.primary_color)
root.style.setProperty("--tenant-secondary", branding.secondary_color)
if (branding.accent_color) {
root.style.setProperty("--tenant-accent", branding.accent_color)
}
if (branding.background_color) {
root.style.setProperty("--tenant-background", branding.background_color)
}
// Update document title
if (branding.site_title) {
document.title = branding.site_title
}
// Update favicon if provided
if (branding.favicon_url) {
const link = document.querySelector<HTMLLinkElement>("link[rel~='icon']")
if (link) {
link.href = branding.favicon_url
}
}
}
/**
* Hook to get tenant-aware API headers.
* Use this when making API calls that need tenant context.
*/
export function getTenantHeaders(): Record<string, string> {
const state = useTenant.getState()
if (state.tenant?.id) {
return { "X-Tenant-ID": state.tenant.id }
}
return {}
}
/**
* Check if a feature is enabled for the current tenant.
*/
export function isFeatureEnabled(feature: keyof TenantFeatures): boolean {
const state = useTenant.getState()
const features = state.tenant?.features ?? DEFAULT_FEATURES
return features[feature]
}
// NOTE: Tenant initialization is handled by TenantProvider component
// to avoid hydration race conditions and duplicate fetches.
// Do not auto-initialize here at module load time.
+385
View File
@@ -0,0 +1,385 @@
#!/usr/bin/env python3
"""
Setup script for Vocal Star white-label tenant.
This script:
1. Uploads Vocal Star theme assets to GCS
2. Creates the theme configuration
3. Creates the tenant configuration
4. Uploads the logo
Usage:
# Set environment variable for resources path (optional)
export VOCALSTAR_RESOURCES=/path/to/VocalStar/Resources
# Run from the project root
python scripts/setup-vocalstar-tenant.py
# Or pass path as argument
python scripts/setup-vocalstar-tenant.py /path/to/VocalStar/Resources
Environment Variables:
VOCALSTAR_RESOURCES: Path to VocalStar resource files (images, fonts)
Expected resource layout:
- vocal-star-title-background-black.4k.png
- blk-YT-background-wall3.fw-upscaled.jpg
- vocal-star-end-card-black.4k.png
- OswaldFont/static/Oswald-SemiBold.ttf
- cdg-instrumental-background-vocalstar.gif
- cdg-title-screen-background-vocalstar-simple.gif
"""
import argparse
import json
import os
import sys
from pathlib import Path
# Add parent to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))
from google.cloud import storage
# Configuration
GCS_BUCKET = "karaoke-gen-storage-nomadkaraoke"
TENANT_ID = "vocalstar"
THEME_ID = "vocalstar"
# Default path (developer-specific, override via env var or CLI arg)
DEFAULT_RESOURCES_PATH = (
"/Users/andrew/AB Dropbox/Andrew Beveridge/MediaUnsynced/Karaoke/"
"Tracks-NonPublished/VocalStar/Resources"
)
def get_resources_path() -> Path:
"""Get the VocalStar resources path from env var, CLI arg, or default."""
# Check CLI argument first
parser = argparse.ArgumentParser(description="Setup Vocal Star tenant")
parser.add_argument(
"resources_path",
nargs="?",
help="Path to VocalStar resource files"
)
args, _ = parser.parse_known_args()
if args.resources_path:
return Path(args.resources_path)
# Check environment variable
env_path = os.environ.get("VOCALSTAR_RESOURCES")
if env_path:
return Path(env_path)
# Fall back to default
return Path(DEFAULT_RESOURCES_PATH)
# Source paths for Vocal Star assets (resolved at runtime)
VOCALSTAR_RESOURCES = get_resources_path()
# Asset mappings: source filename -> GCS destination
THEME_ASSETS = {
"vocal-star-title-background-black.4k.png": "intro_background.png",
"blk-YT-background-wall3.fw-upscaled.jpg": "karaoke_background.jpg",
"vocal-star-end-card-black.4k.png": "end_background.png",
"OswaldFont/static/Oswald-SemiBold.ttf": "Oswald-SemiBold.ttf",
"cdg-instrumental-background-vocalstar.gif": "cdg_instrumental_background.gif",
"cdg-title-screen-background-vocalstar-simple.gif": "cdg_title_background.gif",
}
# Logo path (in worktree)
LOGO_SOURCE = Path(__file__).parent.parent / "vocalstar-logo.jpg"
def upload_file(bucket, source_path: Path, dest_path: str) -> str:
"""Upload a file to GCS and return the gs:// URL."""
blob = bucket.blob(dest_path)
blob.upload_from_filename(str(source_path))
print(f" Uploaded: {source_path.name} -> gs://{GCS_BUCKET}/{dest_path}")
return f"gs://{GCS_BUCKET}/{dest_path}"
def create_theme_config() -> dict:
"""Create the Vocal Star theme configuration."""
return {
"intro": {
"video_duration": 5,
"existing_image": None,
"background_color": "#000000",
"background_image": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/intro_background.png",
"font": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/Oswald-SemiBold.ttf",
"title_region": "370,450,3100,480",
"title_text_transform": None,
"title_color": "#ffff00",
"title_gradient": {
"color1": "#ffffff",
"color2": "#ffff00",
"direction": "vertical",
"start": 0.4,
"stop": 0.8
},
"artist_region": "370,1200,3100,480",
"artist_text_transform": None,
"artist_color": "#ffff00",
"artist_gradient": {
"color1": "#ffffff",
"color2": "#ffff00",
"direction": "vertical",
"start": 0.3,
"stop": 0.6
},
"extra_text": None,
"extra_text_color": "#ffffff",
"extra_text_region": None,
"extra_text_gradient": None
},
"karaoke": {
"background_color": "#000000",
"background_image": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/karaoke_background.jpg",
"font": "Oswald SemiBold",
"font_path": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/Oswald-SemiBold.ttf",
"font_size": 420,
"top_padding": 100,
"ass_name": "VocalStar",
"primary_color": "0, 108, 249, 255",
"secondary_color": "252, 223, 1, 255",
"outline_color": "26, 58, 235, 255",
"back_color": "0, 255, 0, 255",
"bold": False,
"italic": False,
"underline": False,
"strike_out": False,
"scale_x": 100,
"scale_y": 100,
"spacing": 0,
"angle": 0.0,
"border_style": 1,
"outline": 1,
"shadow": 0,
"margin_l": 0,
"margin_r": 0,
"margin_v": 0,
"encoding": 0
},
"end": {
"video_duration": 5,
"existing_image": None,
"background_color": "#000000",
"background_image": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/end_background.png",
"font": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/Oswald-SemiBold.ttf",
"title_region": None,
"title_text_transform": "none",
"title_color": "#ffff00",
"title_gradient": None,
"artist_region": None,
"artist_text_transform": "none",
"artist_color": "#ffff00",
"artist_gradient": None,
"extra_text": None,
"extra_text_color": None,
"extra_text_region": None,
"extra_text_gradient": None
},
"cdg": {
"clear_mode": "eager",
"sync_offset": 0,
"lead_in_threshold": 300,
"lead_in_duration": 30,
"lead_in_total": 200,
"lead_in_symbols": ["/>", ">", ">"],
"row": 4,
"line_tile_height": 3,
"lines_per_page": 4,
"background_color": "#000000",
"border_color": "#ffff00",
"title_color": "#ffff00",
"artist_color": "#ffff00",
"outro_line1_color": "#ffff00",
"outro_line2_color": "#ffff00",
"active_fill": "#006CF9",
"active_stroke": "#000000",
"inactive_fill": "#ffff00",
"inactive_stroke": "#000000",
"instrumental_font_color": "#ffff00",
"font_path": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/Oswald-SemiBold.ttf",
"font_size": 18,
"stroke_width": 0,
"stroke_style": "octagon",
"instrumental_gap_threshold": 1500,
"instrumental_text": "INSTRUMENTAL",
"instrumental_background": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/cdg_instrumental_background.gif",
"instrumental_transition": "topleftmusicalnotes",
"title_screen_background": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/cdg_title_background.gif",
"title_screen_transition": "centertexttoplogobottomtext",
"title_artist_gap": 30,
"intro_duration_seconds": 10.0,
"first_syllable_buffer_seconds": 3.0,
"outro_background": f"gs://{GCS_BUCKET}/themes/{THEME_ID}/assets/cdg_title_background.gif",
"outro_transition": "centertexttoplogobottomtext",
"outro_text_line1": "$title",
"outro_text_line2": "$artist",
"outro_line1_line2_gap": 30
}
}
def create_tenant_config() -> dict:
"""Create the Vocal Star tenant configuration."""
return {
"id": TENANT_ID,
"name": "Vocal Star",
"subdomain": "vocalstar.nomadkaraoke.com",
"is_active": True,
"branding": {
"logo_url": f"gs://{GCS_BUCKET}/tenants/{TENANT_ID}/logo.jpg",
"logo_height": 60,
"primary_color": "#ffff00", # Yellow
"secondary_color": "#006CF9", # Blue
"accent_color": "#ffffff", # White
"background_color": "#000000", # Black
"favicon_url": None, # TODO: Create favicon
"site_title": "Vocal Star Karaoke Generator",
"tagline": "Whoever You Are, Be a Vocal Star!"
},
"features": {
"audio_search": False, # Vocal Star provides their own audio
"file_upload": True,
"youtube_url": False,
"youtube_upload": False, # Download only
"dropbox_upload": False,
"gdrive_upload": False,
"theme_selection": False, # Always use Vocal Star theme
"color_overrides": False,
"enable_cdg": True,
"enable_4k": True,
"admin_access": False
},
"defaults": {
"theme_id": THEME_ID,
"locked_theme": THEME_ID, # Lock to Vocal Star theme - users cannot change
"distribution_mode": "download_only",
"brand_prefix": "VSTAR",
"youtube_description_template": None
},
"auth": {
"allowed_email_domains": ["vocal-star.com", "vocalstarmusic.com"],
"require_email_domain": True,
"fixed_token_ids": [], # Will be populated when tokens are created
"sender_email": "vocalstar@nomadkaraoke.com"
}
}
def create_theme_metadata() -> dict:
"""Create the theme metadata entry for the registry."""
return {
"id": THEME_ID,
"name": "Vocal Star",
"description": "Official Vocal Star karaoke style with yellow/blue color scheme",
"is_default": False
}
def main():
print("=" * 60)
print("Vocal Star Tenant Setup")
print("=" * 60)
# Verify source files exist
print("\n1. Verifying source files...")
missing_files = []
for source_file in THEME_ASSETS.keys():
source_path = VOCALSTAR_RESOURCES / source_file
if not source_path.exists():
missing_files.append(str(source_path))
print(f" MISSING: {source_path}")
else:
print(f" OK: {source_file}")
if not LOGO_SOURCE.exists():
missing_files.append(str(LOGO_SOURCE))
print(f" MISSING: {LOGO_SOURCE}")
else:
print(f" OK: {LOGO_SOURCE.name}")
if missing_files:
print(f"\nERROR: {len(missing_files)} files missing. Cannot continue.")
sys.exit(1)
# Initialize GCS client
print("\n2. Connecting to GCS...")
try:
client = storage.Client()
bucket = client.bucket(GCS_BUCKET)
print(f" Connected to bucket: {GCS_BUCKET}")
except Exception as e:
print(f" ERROR: Failed to connect to GCS: {e}")
sys.exit(1)
# Upload theme assets
print(f"\n3. Uploading theme assets to themes/{THEME_ID}/assets/...")
for source_file, dest_file in THEME_ASSETS.items():
source_path = VOCALSTAR_RESOURCES / source_file
dest_path = f"themes/{THEME_ID}/assets/{dest_file}"
upload_file(bucket, source_path, dest_path)
# Upload theme config
print(f"\n4. Creating theme configuration...")
theme_config = create_theme_config()
theme_blob = bucket.blob(f"themes/{THEME_ID}/style_params.json")
theme_blob.upload_from_string(
json.dumps(theme_config, indent=2),
content_type="application/json"
)
print(f" Created: gs://{GCS_BUCKET}/themes/{THEME_ID}/style_params.json")
# Upload tenant logo
print(f"\n5. Uploading tenant logo...")
upload_file(bucket, LOGO_SOURCE, f"tenants/{TENANT_ID}/logo.jpg")
# Upload tenant config
print(f"\n6. Creating tenant configuration...")
tenant_config = create_tenant_config()
tenant_blob = bucket.blob(f"tenants/{TENANT_ID}/config.json")
tenant_blob.upload_from_string(
json.dumps(tenant_config, indent=2),
content_type="application/json"
)
print(f" Created: gs://{GCS_BUCKET}/tenants/{TENANT_ID}/config.json")
# Update theme registry (add Vocal Star theme)
print(f"\n7. Updating theme registry...")
registry_blob = bucket.blob("themes/_metadata.json")
try:
registry_data = json.loads(registry_blob.download_as_string())
except Exception:
print(" Creating new registry...")
registry_data = {"version": 1, "themes": []}
# Check if theme already exists
existing_ids = [t["id"] for t in registry_data.get("themes", [])]
if THEME_ID not in existing_ids:
registry_data["themes"].append(create_theme_metadata())
registry_blob.upload_from_string(
json.dumps(registry_data, indent=2),
content_type="application/json"
)
print(f" Added {THEME_ID} to theme registry")
else:
print(f" Theme {THEME_ID} already in registry")
print("\n" + "=" * 60)
print("Setup complete!")
print("=" * 60)
print(f"\nTenant: {TENANT_ID}")
print(f"Subdomain: vocalstar.nomadkaraoke.com")
print(f"Theme: {THEME_ID}")
print(f"\nNext steps:")
print("1. Configure DNS: Add CNAME for vocalstar.nomadkaraoke.com")
print("2. Update Cloudflare Pages to accept the subdomain")
print("3. Test the portal at https://vocalstar.nomadkaraoke.com")
if __name__ == "__main__":
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB