diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a773dfd..b265c743 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -903,19 +903,38 @@ jobs: working-directory: frontend run: npm ci --legacy-peer-deps - - name: Build frontend (Next.js static export) + # ===== Consumer Build (gen.nomadkaraoke.com) ===== + - name: Build frontend (consumer) working-directory: frontend env: NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com run: npm run build - - name: Deploy to Cloudflare Pages + - name: Deploy consumer to Cloudflare Pages uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} command: pages deploy frontend/out --project-name=karaoke-gen --branch=main + # ===== Tenant Portal Build (vocalstar.nomadkaraoke.com, singa.nomadkaraoke.com, etc.) ===== + # Separate build with NEXT_PUBLIC_TENANT_PORTAL=true which tree-shakes + # consumer marketing content and renders TenantLandingPage at root. + # The Cloudflare Pages Function (frontend/functions/) injects tenant config at the edge. + - name: Build frontend (tenant portal) + working-directory: frontend + env: + NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com + NEXT_PUBLIC_TENANT_PORTAL: "true" + run: npm run build + + - name: Deploy tenant portal to Cloudflare Pages + uses: cloudflare/wrangler-action@v3 + with: + apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} + accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + command: pages deploy frontend/out --project-name=karaoke-gen-tenant --branch=main + # NOTE: buy-site was consolidated into the main frontend (PR #122, Dec 2024) # Landing page and payment flow are now at gen.nomadkaraoke.com (root) # buy.nomadkaraoke.com subdomain has been deleted diff --git a/backend/api/dependencies.py b/backend/api/dependencies.py index 041c30c4..0439979c 100644 --- a/backend/api/dependencies.py +++ b/backend/api/dependencies.py @@ -113,6 +113,11 @@ async def require_auth( detail=f"Authentication failed: {auth_result.message}" ) + # If token has a tenant_id, override the hostname-based tenant detection. + # This allows tenant-scoped tokens to enforce tenant context regardless of domain. + if auth_result.tenant_id: + request.state.tenant_id = auth_result.tenant_id + # Log successful auth with request_id for correlation with request audit logger.info( "auth_success", @@ -122,6 +127,7 @@ async def require_auth( "user_type": auth_result.user_type.value if auth_result.user_type else None, "is_admin": auth_result.is_admin, "remaining_uses": auth_result.remaining_uses, + "tenant_id": auth_result.tenant_id, "audit_type": "auth_event", } ) diff --git a/backend/api/routes/users.py b/backend/api/routes/users.py index 207a05a6..6eb88f09 100644 --- a/backend/api/routes/users.py +++ b/backend/api/routes/users.py @@ -186,13 +186,23 @@ async def send_magic_link( tenant_id=tenant_id ) - # Get tenant-specific sender email + # Get tenant-specific email configuration sender_email = None + tenant_frontend_url = None + tenant_name = None if tenant_config: sender_email = tenant_config.get_sender_email() + tenant_frontend_url = tenant_config.get_frontend_url() + tenant_name = tenant_config.name - # Send email (with tenant-specific sender if configured) - sent = email_service.send_magic_link(email, magic_link.token, sender_email=sender_email) + # Send email (with tenant-specific sender, URL, and name if configured) + sent = email_service.send_magic_link( + email, + magic_link.token, + sender_email=sender_email, + tenant_frontend_url=tenant_frontend_url, + tenant_name=tenant_name, + ) if not sent: logger.error(f"Failed to send magic link email to {email}") @@ -269,11 +279,21 @@ async def verify_magic_link( tenant_id=user.tenant_id, ) + # Resolve tenant subdomain for cross-domain redirect safety + tenant_subdomain = None + if magic_link_tenant_id: + from backend.services.tenant_service import get_tenant_service + tenant_service = get_tenant_service() + tenant_cfg = tenant_service.get_tenant_config(magic_link_tenant_id) + if tenant_cfg: + tenant_subdomain = tenant_cfg.subdomain + return VerifyMagicLinkResponse( status="success", session_token=session.token, user=user_public, - message="Successfully signed in" + message="Successfully signed in", + tenant_subdomain=tenant_subdomain, ) diff --git a/backend/models/tenant.py b/backend/models/tenant.py index 199b2b89..7f4d52b3 100644 --- a/backend/models/tenant.py +++ b/backend/models/tenant.py @@ -139,6 +139,10 @@ class TenantConfig(BaseModel): created_at: Optional[datetime] = None updated_at: Optional[datetime] = None + def get_frontend_url(self) -> str: + """Get the frontend URL for this tenant's portal.""" + return f"https://{self.subdomain}" + def get_sender_email(self) -> str: """Get the email sender address for this tenant.""" if self.auth.sender_email: diff --git a/backend/models/user.py b/backend/models/user.py index 5de2cbff..bcac0c28 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -177,6 +177,7 @@ class VerifyMagicLinkResponse(BaseModel): session_token: str user: "UserPublic" message: str + tenant_subdomain: Optional[str] = None class UserPublic(BaseModel): diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index 42008772..9e9aff5a 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -49,6 +49,7 @@ class AuthResult: user_email: Optional[str] = None # Email if authenticated via session/API key is_admin: bool = False # True if admin token or admin email domain api_key_id: Optional[str] = None # API key ID if authenticated via API key + tenant_id: Optional[str] = None # Tenant scope from token or session def __iter__(self): """Allow unpacking as tuple for backward compatibility.""" @@ -284,6 +285,7 @@ class AuthService: # All auth_tokens must have an associated user_email for job ownership token_user_email = token_data.get("user_email") api_key_id = token_data.get("api_key_id") + token_tenant_id = token_data.get("tenant_id") # Require user_email on all auth_tokens (no anonymous token auth) if not token_user_email: @@ -307,7 +309,8 @@ class AuthService: message="Unlimited access granted", user_email=token_user_email, is_admin=token_is_admin, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) # LIMITED tokens: check usage count @@ -320,7 +323,8 @@ class AuthService: message="Limited token with unlimited uses", user_email=token_user_email, is_admin=token_is_admin, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) current_uses = token_data.get("usage_count", 0) @@ -333,7 +337,8 @@ class AuthService: remaining_uses=0, message="Token usage limit exceeded", user_email=token_user_email, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) return AuthResult( @@ -343,7 +348,8 @@ class AuthService: message=f"Limited token: {remaining} uses remaining", user_email=token_user_email, is_admin=token_is_admin, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) # STRIPE tokens: check expiration and usage @@ -357,7 +363,8 @@ class AuthService: remaining_uses=0, message="Token has expired", user_email=token_user_email, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) if max_uses > 0: @@ -371,7 +378,8 @@ class AuthService: remaining_uses=0, message="Token usage limit exceeded", user_email=token_user_email, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) return AuthResult( @@ -381,7 +389,8 @@ class AuthService: message=f"Stripe token: {remaining} uses remaining", user_email=token_user_email, is_admin=token_is_admin, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) return AuthResult( @@ -391,7 +400,8 @@ class AuthService: message="Stripe access granted", user_email=token_user_email, is_admin=token_is_admin, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) # API_KEY tokens @@ -406,7 +416,8 @@ class AuthService: remaining_uses=0, message="API key usage limit exceeded", user_email=token_user_email, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) return AuthResult( is_valid=True, @@ -415,7 +426,8 @@ class AuthService: message=f"API key valid: {remaining} uses remaining", user_email=token_user_email, is_admin=token_is_admin, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) return AuthResult( @@ -425,7 +437,8 @@ class AuthService: message="API key access granted", user_email=token_user_email, is_admin=token_is_admin, - api_key_id=api_key_id + api_key_id=api_key_id, + tenant_id=token_tenant_id ) return AuthResult( diff --git a/backend/services/email_service.py b/backend/services/email_service.py index a535fa0f..76478f80 100644 --- a/backend/services/email_service.py +++ b/backend/services/email_service.py @@ -247,6 +247,8 @@ class EmailService: email: str, token: str, sender_email: Optional[str] = None, + tenant_frontend_url: Optional[str] = None, + tenant_name: Optional[str] = None, ) -> bool: """ Send a magic link email for authentication. @@ -255,13 +257,17 @@ class EmailService: email: User's email address token: Magic link token sender_email: Override sender email address (for multi-tenant) + tenant_frontend_url: Override frontend URL for tenant portals (e.g., https://vocalstar.nomadkaraoke.com) + tenant_name: Override brand name for tenant portals (e.g., "Vocal Star") Returns: True if email was sent successfully """ - magic_link_url = f"{self.frontend_url}/auth/verify?token={token}" + base_url = tenant_frontend_url or self.frontend_url + magic_link_url = f"{base_url}/auth/verify?token={token}" - subject = "Sign in to Nomad Karaoke" + brand_name = tenant_name or "Nomad Karaoke" + subject = f"Sign in to {brand_name}" extra_styles = """ .warning { @@ -277,7 +283,7 @@ class EmailService: content = f"""
Hi there,
-Click the button below to sign in to Nomad Karaoke:
+Click the button below to sign in to {html.escape(brand_name)}:
Sign In @@ -298,7 +304,7 @@ class EmailService: html_content = self._build_email_html(content, extra_styles) text_content = f""" -Sign in to Nomad Karaoke +Sign in to {brand_name} ======================== Click this link to sign in: @@ -309,7 +315,7 @@ This link expires in 15 minutes and can only be used once. If you didn't request this email, you can safely ignore it. --- -© {self._get_year()} Nomad Karaoke +© {self._get_year()} {brand_name} """ return self.provider.send_email( diff --git a/backend/tests/test_tenant_separation.py b/backend/tests/test_tenant_separation.py new file mode 100644 index 00000000..cf2a23bf --- /dev/null +++ b/backend/tests/test_tenant_separation.py @@ -0,0 +1,310 @@ +""" +Tests for whitelabel tenant separation (magic link redirect fix, frontend URL, verify response, +tenant-scoped tokens). +""" + +import pytest +from unittest.mock import MagicMock, patch + +from backend.models.tenant import TenantConfig, TenantAuth, TenantBranding +from backend.models.user import VerifyMagicLinkResponse, UserPublic +from backend.services.auth_service import AuthResult, AuthService, UserType + + +class TestTenantConfigGetFrontendUrl: + """Tests for TenantConfig.get_frontend_url().""" + + def test_returns_https_url_with_subdomain(self): + config = TenantConfig( + id="vocalstar", + name="Vocal Star", + subdomain="vocalstar.nomadkaraoke.com", + ) + assert config.get_frontend_url() == "https://vocalstar.nomadkaraoke.com" + + def test_different_tenant(self): + config = TenantConfig( + id="singa", + name="Singa", + subdomain="singa.nomadkaraoke.com", + ) + assert config.get_frontend_url() == "https://singa.nomadkaraoke.com" + + +class TestSendMagicLinkTenantParams: + """Tests for EmailService.send_magic_link() with tenant parameters.""" + + @pytest.fixture + def email_service(self): + """Create an EmailService with a mock provider.""" + from backend.services.email_service import EmailService + service = EmailService() + service.provider = MagicMock() + service.provider.send_email = MagicMock(return_value=True) + return service + + def test_default_uses_nomad_karaoke_branding(self, email_service): + """Without tenant params, email uses default Nomad Karaoke branding.""" + email_service.send_magic_link("user@test.com", "abc123") + + call_args = email_service.provider.send_email.call_args + subject = call_args[0][1] + html_content = call_args[0][2] + text_content = call_args[0][3] + + assert subject == "Sign in to Nomad Karaoke" + assert "Nomad Karaoke" in html_content + assert "Nomad Karaoke" in text_content + # Default URL should be used + assert f"{email_service.frontend_url}/auth/verify" in html_content + + def test_tenant_url_used_in_magic_link(self, email_service): + """When tenant_frontend_url is provided, magic link points to tenant domain.""" + email_service.send_magic_link( + "user@vocal-star.com", + "abc123", + tenant_frontend_url="https://vocalstar.nomadkaraoke.com", + ) + + call_args = email_service.provider.send_email.call_args + html_content = call_args[0][2] + text_content = call_args[0][3] + + assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in html_content + assert "https://vocalstar.nomadkaraoke.com/auth/verify?token=abc123" in text_content + # Should NOT contain default URL + assert "gen.nomadkaraoke.com" not in html_content + + def test_tenant_name_used_in_subject_and_body(self, email_service): + """When tenant_name is provided, email uses tenant brand name.""" + email_service.send_magic_link( + "user@vocal-star.com", + "abc123", + tenant_name="Vocal Star", + ) + + call_args = email_service.provider.send_email.call_args + subject = call_args[0][1] + html_content = call_args[0][2] + text_content = call_args[0][3] + + assert subject == "Sign in to Vocal Star" + assert "Vocal Star" in html_content + assert "Vocal Star" in text_content + + def test_tenant_name_html_escaped(self, email_service): + """Tenant name is HTML-escaped to prevent XSS.""" + email_service.send_magic_link( + "user@test.com", + "abc123", + tenant_name='', + ) + + call_args = email_service.provider.send_email.call_args + html_content = call_args[0][2] + + # Should be escaped in HTML + assert " or