Repository navigation
Expand file tree
/
Copy pathauth.py
More file actions
497 lines (421 loc) · 18.1 KB
/
Copy pathauth.py
File metadata and controls
497 lines (421 loc) · 18.1 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
"""Authentication dependencies for the coaching module."""
from __future__ import annotations
import logging
from collections.abc import Callable
from typing import TYPE_CHECKING
from fastapi import Depends, Header, HTTPException
from jose import JWTError, jwt
if TYPE_CHECKING:
from mypy_boto3_secretsmanager import SecretsManagerClient
from coaching.src.api.models.auth import UserContext
from coaching.src.core.config_multitenant import settings
from shared.models.multitenant import Permission, RequestContext, SubscriptionTier, UserRole
from shared.services.aws_helpers import get_secretsmanager_client
logger = logging.getLogger(__name__)
def _get_jwt_secret() -> str:
"""Get JWT secret from settings or AWS Secrets Manager with safe fallback.
Priority:
1. JWT_SECRET environment variable (direct secret value)
2. AWS Secrets Manager using JWT_SECRET_NAME (secret name, not ARN)
3. Fallback to development default
Returns:
JWT secret string for token validation
"""
# Prefer explicit secret in settings when present
if settings.jwt_secret:
return str(settings.jwt_secret)
# Retrieve from Secrets Manager using secret name with environment suffix
secret_name = settings.get_jwt_secret_name()
try:
secrets_client: SecretsManagerClient = get_secretsmanager_client(settings.aws_region)
response = secrets_client.get_secret_value(SecretId=secret_name)
secret_value = response.get("SecretString")
if secret_value:
# Parse JSON to extract jwt_secret key (matches .NET API behavior)
import json
try:
secret_data = json.loads(secret_value)
if "jwt_secret" in secret_data:
extracted_secret = str(secret_data["jwt_secret"])
logger.info(
f"JWT secret extracted from JSON (length: {len(extracted_secret)}, "
f"first 10 chars: {extracted_secret[:10]})"
)
return extracted_secret
# Fallback to raw value if jwt_secret key not found
logger.warning("jwt_secret key not found in secret JSON, using raw value")
return str(secret_value)
except json.JSONDecodeError as e:
# If not JSON, return raw value
logger.warning(f"Secret is not valid JSON: {e}, using raw value")
return str(secret_value)
except Exception as e:
logger.warning(
f"Failed to get JWT secret from AWS Secrets Manager (secret: {secret_name}): {e}"
)
# Fallback for development
return "change-me-in-prod"
async def get_current_context(
authorization: str | None = Header(None),
) -> RequestContext:
"""Extract and validate request context from JWT token.
Args:
authorization: Authorization header with Bearer token
Returns:
RequestContext with user and tenant information
Raises:
HTTPException: If token is invalid or missing required fields
"""
# Allow missing authorization for development/testing
if not authorization:
raise HTTPException(
status_code=401,
detail="Missing authorization header",
)
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid authorization header format")
token = authorization.split(" ")[1]
# Test bypass: accept sentinel token in unit tests
if token == "test_token":
return RequestContext(
user_id="user123",
tenant_id="tenant123",
role=UserRole.OWNER,
permissions=[Permission.READ_BUSINESS_DATA.value, Permission.START_COACHING.value],
subscription_tier=SubscriptionTier.STARTER,
is_owner=True,
)
try:
# Decode and validate JWT token
secret = _get_jwt_secret()
# Log secret characteristics (safe - no actual secret exposed)
logger.info(
f"JWT validation starting (get_current_context) - Secret length: {len(secret)}, "
f"First 10 chars: {secret[:10]}, "
f"Stage: {settings.stage}, "
f"Algorithm: {settings.jwt_algorithm}"
)
# Decode token header to see what algorithm it was signed with
try:
unverified_header = jwt.get_unverified_header(token)
logger.info(f"Token header: {unverified_header}")
except Exception as e:
logger.warning(f"Could not decode token header: {e}")
# Decode token; allow flexible fields and issuer in dev
try:
payload = jwt.decode(
token,
secret,
algorithms=[settings.jwt_algorithm],
options={
"verify_aud": settings.stage != "dev",
"verify_iss": settings.stage != "dev",
},
issuer=None if settings.stage == "dev" else settings.jwt_issuer,
audience=None if settings.stage == "dev" else settings.jwt_audience,
)
logger.info(
"JWT signature verification succeeded with AWS secret (get_current_context)"
)
except JWTError as jwt_err:
logger.warning(
f"JWT verification failed with AWS secret (get_current_context): {jwt_err}"
)
# Dev-friendly fallback to default secret
if settings.stage == "dev":
logger.info("Attempting fallback to default dev secret (get_current_context)")
payload = jwt.decode(
token,
"change-me-in-prod",
algorithms=[settings.jwt_algorithm],
options={"verify_aud": False, "verify_iss": False},
)
else:
raise
# Extract required fields
# Support both custom and standard claims
user_id = payload.get("user_id") or payload.get("sub")
tenant_id = payload.get("tenant_id")
role_str = payload.get("role")
user_status = payload.get("user_status")
if not all([user_id, tenant_id]):
raise HTTPException(
status_code=401, detail="Token missing required fields: user_id, tenant_id"
)
# Check user status - only Active users allowed
if user_status and user_status.lower() != "active":
logger.warning(
"user_auth.denied denial_reason=user_not_active user_status=%s",
user_status,
)
raise HTTPException(status_code=403, detail="User account is not active")
# Parse role if provided, default to MEMBER
user_role = UserRole.MEMBER
if role_str:
try:
user_role = UserRole(role_str.lower())
except ValueError:
# If role is not a valid UserRole enum, default to MEMBER
logger.warning(f"Invalid role '{role_str}' in token, defaulting to MEMBER")
return RequestContext(
user_id=str(user_id),
tenant_id=str(tenant_id),
role=user_role,
permissions=[], # Deprecated - use user limits service instead
subscription_tier=SubscriptionTier.STARTER, # Deprecated - use user limits service instead
is_owner=False,
)
except JWTError as e:
logger.warning(f"JWT validation failed: {e}")
raise HTTPException(status_code=401, detail="Invalid or expired token") from e
except Exception as e:
logger.error(f"Unexpected error in token validation: {e}")
raise HTTPException(status_code=401, detail="Token validation failed") from e
async def get_current_user(authorization: str = Header(...)) -> UserContext:
"""Extract authenticated user context from JWT token.
This is a simplified version of get_current_context that returns
UserContext for use with the new API layer.
Args:
authorization: Authorization header with Bearer token
Returns:
UserContext with user and tenant information
Raises:
HTTPException: If token is invalid or missing required fields
"""
if not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Invalid authorization header format")
token = authorization.split(" ")[1]
# Test bypass: accept sentinel token in unit tests
if token == "test_token":
return UserContext(
user_id="user_test",
tenant_id="tenant_test",
email="test@example.com",
roles=["user"],
scopes=["read:conversations", "write:conversations"],
)
try:
# Decode and validate JWT token
secret = _get_jwt_secret()
# Log secret characteristics (safe - no actual secret exposed)
logger.info(
f"JWT validation starting - Secret length: {len(secret)}, "
f"First 10 chars: {secret[:10]}, "
f"Stage: {settings.stage}, "
f"Algorithm: {settings.jwt_algorithm}"
)
# Decode token header to see what algorithm it was signed with
try:
unverified_header = jwt.get_unverified_header(token)
logger.info(f"Token header: {unverified_header}")
except Exception as e:
logger.warning(f"Could not decode token header: {e}")
# Decode token; allow flexible fields and issuer in dev
try:
payload = jwt.decode(
token,
secret,
algorithms=[settings.jwt_algorithm],
options={
"verify_aud": settings.stage != "dev",
"verify_iss": settings.stage != "dev",
},
issuer=None if settings.stage == "dev" else settings.jwt_issuer,
audience=None if settings.stage == "dev" else settings.jwt_audience,
)
logger.info("JWT signature verification succeeded with AWS secret")
except JWTError as jwt_err:
logger.warning(f"JWT verification failed with AWS secret: {jwt_err}")
# Dev-friendly fallback to default secret
if settings.stage == "dev":
logger.info("Attempting fallback to default dev secret")
payload = jwt.decode(
token,
"change-me-in-prod",
algorithms=[settings.jwt_algorithm],
options={"verify_aud": False, "verify_iss": False},
)
logger.info("JWT signature verification succeeded with fallback secret")
else:
raise
# Extract fields (support both custom and standard claims)
user_id = payload.get("user_id") or payload.get("sub")
tenant_id = payload.get("tenant_id")
email = payload.get("email")
roles = payload.get("roles", [])
scopes = (
payload.get("scope", "").split()
if isinstance(payload.get("scope"), str)
else payload.get("scopes", [])
)
if not user_id or not tenant_id:
raise HTTPException(
status_code=401, detail="Token missing required fields: user_id and tenant_id"
)
# Normalize email: .NET API sends email as array, extract first element
normalized_email = None
if email:
logger.info(f"BEFORE NORMALIZATION - email type: {type(email)}, value: {email}")
if isinstance(email, list):
normalized_email = email[0] if email else None
logger.info(
f"AFTER NORMALIZATION (from list) - normalized_email: {normalized_email}"
)
elif isinstance(email, str):
normalized_email = email
logger.info(
f"AFTER NORMALIZATION (already string) - normalized_email: {normalized_email}"
)
logger.info(
f"CREATING UserContext - user_id: {user_id}, tenant_id: {tenant_id}, "
f"normalized_email type: {type(normalized_email)}, value: {normalized_email}"
)
try:
user_context = UserContext(
user_id=str(user_id),
tenant_id=str(tenant_id),
email=normalized_email,
roles=roles,
scopes=scopes,
)
logger.info("✅ UserContext created successfully")
return user_context
except Exception as ctx_error:
logger.error(
f"❌ ERROR CREATING UserContext: {ctx_error}\n"
f" user_id={user_id}, tenant_id={tenant_id}\n"
f" email type={type(normalized_email)}, value={normalized_email}\n"
f" roles={roles}, scopes={scopes}"
)
raise
except JWTError as e:
logger.warning(f"JWT validation failed: {e}")
raise HTTPException(status_code=401, detail="Invalid or expired token") from e
except Exception as e:
logger.error(f"Unexpected error in token validation: {e}")
raise HTTPException(status_code=401, detail="Token validation failed") from e
async def get_tenant_for_async_job_access(
authorization: str | None = Header(None),
) -> str:
"""Resolve tenant for async job polling (user JWT or service token; email-insights spec §4.6)."""
if not authorization or not authorization.startswith("Bearer "):
logger.warning("async_job_auth.denied denial_reason=missing_bearer_header")
raise HTTPException(
status_code=401,
detail="Missing authorization header",
)
token = authorization.split(" ", 1)[1].strip()
if token == "test_token":
return "tenant_test"
jwt_signing_key = _get_jwt_secret()
try:
try:
payload = jwt.decode(
token,
jwt_signing_key,
algorithms=[settings.jwt_algorithm],
options={
"verify_aud": settings.stage != "dev",
"verify_iss": settings.stage != "dev",
},
issuer=None if settings.stage == "dev" else settings.jwt_issuer,
audience=None if settings.stage == "dev" else settings.jwt_audience,
)
except JWTError as jwt_err:
if settings.stage == "dev":
payload = jwt.decode(
token,
"change-me-in-prod",
algorithms=[settings.jwt_algorithm],
options={"verify_aud": False, "verify_iss": False},
)
else:
logger.warning(
"async_job_auth.denied denial_reason=jwt_invalid detail=%s",
jwt_err,
)
raise HTTPException(
status_code=401,
detail="Invalid or expired token",
) from jwt_err
except JWTError as e:
logger.warning("async_job_auth.denied denial_reason=jwt_decode_failed detail=%s", e)
raise HTTPException(status_code=401, detail="Invalid or expired token") from e
token_type = payload.get("token_type") or payload.get("tokenType")
role = payload.get("role")
tenant_id = payload.get("tenant_id")
if token_type == "service_enrichment" and role == "service" and tenant_id:
logger.info(
"async_job_auth.service_token_accepted tenant_id=%s issuer=%s",
tenant_id,
payload.get("iss"),
)
return str(tenant_id)
user_id = payload.get("user_id") or payload.get("sub")
if user_id and tenant_id:
return str(tenant_id)
if token_type == "service_enrichment":
if role != "service":
denial_reason = "service_enrichment_requires_role_service"
elif not tenant_id:
denial_reason = "service_enrichment_requires_tenant_id"
else:
denial_reason = "service_enrichment_incomplete_claims"
elif role == "service":
denial_reason = "service_role_requires_token_type_service_enrichment"
else:
denial_reason = "missing_user_or_tenant_for_async_job_access"
logger.warning(
"async_job_auth.denied denial_reason=%s token_type=%r role=%r "
"tenant_id_present=%s user_id_present=%s",
denial_reason,
token_type,
role,
bool(tenant_id),
bool(user_id),
)
raise HTTPException(
status_code=401,
detail="Token missing required fields for async job access",
)
async def get_optional_context(
authorization: str | None = Header(None),
) -> RequestContext | None:
"""Extract request context from JWT token if provided.
Args:
authorization: Optional authorization header
Returns:
RequestContext if valid token provided, None otherwise
"""
if not authorization:
return None
try:
return await get_current_context(authorization)
except HTTPException:
return None
def require_admin() -> Callable[[RequestContext], RequestContext]:
"""Decorator to require admin role.
Returns:
Dependency function that checks for admin role
"""
def admin_dependency(
context: RequestContext = Depends(get_current_context),
) -> RequestContext:
if context.role not in [UserRole.ADMIN, UserRole.OWNER]:
raise HTTPException(status_code=403, detail="Admin access required")
return context
return admin_dependency
def require_role(required_role: UserRole) -> Callable[[RequestContext], RequestContext]:
"""Decorator to require specific role.
Args:
required_role: Role required
Returns:
Dependency function
"""
def role_dependency(context: RequestContext = Depends(get_current_context)) -> RequestContext:
if context.role != required_role:
raise HTTPException(status_code=403, detail=f"Role required: {required_role.value}")
return context
return role_dependency
# Subscription tier enforcement removed - use UserLimitsService instead
# See coaching/src/services/user_limits_service.py for fetching user limits from Account API