File size: 9,845 Bytes
d8c6e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Authentication and authorization utilities using Firebase Auth."""

import json
import secrets
from uuid import UUID

import firebase_admin
from firebase_admin import auth as firebase_auth, credentials
from fastapi import Depends, Header, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from passlib.context import CryptContext

from src.config import settings
from src.core.exceptions import UnauthorizedError

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
bearer_scheme = HTTPBearer(auto_error=False)

# ---------------------------------------------------------------------------
# Firebase initialization
# ---------------------------------------------------------------------------

_firebase_app = None


def _init_firebase():
    """Initialize Firebase Admin SDK (idempotent)."""
    global _firebase_app
    if _firebase_app is not None:
        return _firebase_app

    if firebase_admin._apps:
        _firebase_app = firebase_admin.get_app()
        return _firebase_app

    cred = None
    if settings.firebase_credentials_json:
        # Accept either a file path or a JSON string
        try:
            cred_data = json.loads(settings.firebase_credentials_json)
            cred = credentials.Certificate(cred_data)
        except (json.JSONDecodeError, ValueError):
            # Treat as file path
            cred = credentials.Certificate(settings.firebase_credentials_json)

    if cred:
        _firebase_app = firebase_admin.initialize_app(cred)
    elif settings.firebase_project_id:
        # Running on Cloud Run — uses default credentials (no key file needed)
        _firebase_app = firebase_admin.initialize_app(
            options={"projectId": settings.firebase_project_id}
        )
    else:
        # Local dev without Firebase — will use fallback JWT mode
        _firebase_app = None

    return _firebase_app


def is_firebase_enabled() -> bool:
    """Check if Firebase Auth is configured and available."""
    _init_firebase()
    return _firebase_app is not None


# ---------------------------------------------------------------------------
# Password hashing (still used for API keys)
# ---------------------------------------------------------------------------


def hash_password(password: str) -> str:
    """Hash a plaintext password using bcrypt."""
    return pwd_context.hash(password)


def verify_password(plain: str, hashed: str) -> bool:
    """Verify a plaintext password against a bcrypt hash."""
    return pwd_context.verify(plain, hashed)


# ---------------------------------------------------------------------------
# Firebase token verification
# ---------------------------------------------------------------------------


def verify_firebase_token(id_token: str) -> dict:
    """Verify a Firebase ID token and return the decoded claims.

    Returns:
        Dict with 'uid', 'email', 'name', etc.

    Raises:
        UnauthorizedError: If token is invalid or expired.
    """
    if not is_firebase_enabled():
        raise UnauthorizedError(detail="Firebase Auth not configured")

    try:
        decoded = firebase_auth.verify_id_token(id_token)
        return decoded
    except firebase_auth.InvalidIdTokenError:
        raise UnauthorizedError(detail="Invalid Firebase token")
    except firebase_auth.ExpiredIdTokenError:
        raise UnauthorizedError(detail="Firebase token expired")
    except firebase_auth.RevokedIdTokenError:
        raise UnauthorizedError(detail="Firebase token revoked")
    except Exception as exc:
        raise UnauthorizedError(detail=f"Firebase auth error: {exc}")


# ---------------------------------------------------------------------------
# Fallback JWT (for local dev / testing without Firebase)
# ---------------------------------------------------------------------------


def create_access_token(data: dict) -> str:
    """Create a signed JWT for local dev/testing (when Firebase is not configured).

    In production, Firebase Auth issues tokens — this is only used as a fallback.
    """
    from datetime import datetime, timedelta, timezone
    from jose import jwt

    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + timedelta(minutes=60)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, settings.secret_key, algorithm="HS256")


def decode_access_token(token: str) -> dict:
    """Decode a local JWT (fallback when Firebase is not configured)."""
    from jose import JWTError, jwt

    try:
        return jwt.decode(token, settings.secret_key, algorithms=["HS256"])
    except JWTError as exc:
        raise UnauthorizedError(detail="Invalid or expired token") from exc


# ---------------------------------------------------------------------------
# API key generation
# ---------------------------------------------------------------------------


def generate_api_key() -> str:
    """Generate a secure random API key prefixed with 'a2a_'."""
    return f"a2a_{secrets.token_hex(32)}"


# ---------------------------------------------------------------------------
# FastAPI auth dependency
# ---------------------------------------------------------------------------


async def get_current_user(
    request: Request,
    credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
    x_api_key: str | None = Header(None, alias="X-API-Key"),
) -> dict:
    """Extract the current user from a Firebase ID token, fallback JWT, API key, or httpOnly cookie.

    Priority: Bearer token → API key → httpOnly session cookie.

    Returns:
        dict with 'id' (UUID str or Firebase UID), 'email', and optionally 'firebase_uid'.
    """
    # 1. Try Bearer token first
    if credentials is not None:
        token = credentials.credentials

        if is_firebase_enabled():
            decoded = verify_firebase_token(token)
            return {
                "id": decoded.get("uid"),
                "email": decoded.get("email", ""),
                "name": decoded.get("name", ""),
                "firebase_uid": decoded.get("uid"),
            }
        else:
            payload = decode_access_token(token)
            user_id = payload.get("sub")
            if user_id is None:
                raise UnauthorizedError(detail="Token missing subject claim")
            return {"id": user_id, "email": payload.get("email", "")}

    # 2. Try API key
    if x_api_key is not None:
        try:
            from src.core._api_key_lookup import lookup_user_by_api_key
            user = await lookup_user_by_api_key(x_api_key)
            if user is not None:
                return user
        except ImportError:
            pass

    # 3. Try httpOnly session cookie (__session)
    session_token = request.cookies.get("__session") if request else None
    if session_token:
        # CSRF check: for cookie-authenticated mutations, verify Origin header
        if request.method not in ("GET", "HEAD", "OPTIONS"):
            origin = request.headers.get("origin", "")
            allowed_origins = {
                "https://crewhubai.com",
                "https://www.crewhubai.com",
                "https://staging.crewhubai.com",
                "https://marketplace-staging.aidigitalcrew.com",
                "http://localhost:3000",
                "http://localhost:5173",
            }
            if origin and origin not in allowed_origins:
                raise UnauthorizedError(detail="CSRF: origin not allowed")

        if is_firebase_enabled():
            decoded = verify_firebase_token(session_token)
            return {
                "id": decoded.get("uid"),
                "email": decoded.get("email", ""),
                "name": decoded.get("name", ""),
                "firebase_uid": decoded.get("uid"),
            }
        else:
            payload = decode_access_token(session_token)
            user_id = payload.get("sub")
            if user_id is None:
                raise UnauthorizedError(detail="Token missing subject claim")
            return {"id": user_id, "email": payload.get("email", "")}

    raise UnauthorizedError(detail="Authentication required")


async def get_current_user_id(
    current_user: dict = Depends(get_current_user),
) -> UUID:
    """FastAPI dependency that returns just the current user's UUID.

    WARNING: In Firebase mode, current_user["id"] is the Firebase UID (a
    string, not a UUID).  If the caller needs the *database* user UUID,
    use ``resolve_db_user_id`` instead.
    """
    return UUID(current_user["id"])


async def resolve_db_user_id(
    current_user: dict = Depends(get_current_user),
) -> UUID:
    """Resolve the authenticated user to their database UUID.

    In Firebase mode the Bearer token only contains the Firebase UID, which
    is *not* a valid UUID.  This dependency looks up the ``users`` table by
    ``firebase_uid`` (or by ``id`` in local-JWT mode) and returns the row's
    primary-key UUID so that downstream services can safely create FK
    references.
    """
    from sqlalchemy import select as sa_select
    from src.database import async_session
    from src.models.user import User

    firebase_uid = current_user.get("firebase_uid")

    async with async_session() as db:
        if firebase_uid:
            result = await db.execute(
                sa_select(User.id).where(User.firebase_uid == firebase_uid)
            )
        else:
            result = await db.execute(
                sa_select(User.id).where(User.id == UUID(current_user["id"]))
            )

        user_id = result.scalar_one_or_none()
        if user_id is None:
            raise UnauthorizedError(detail="User not found in database")
        return user_id