Spaces:
Sleeping
Sleeping
File size: 27,005 Bytes
1f97573 3038fe7 1f97573 7a8349e 1f97573 3038fe7 1f97573 3038fe7 1f97573 e37709f b734a17 e37709f b734a17 e37709f b734a17 e37709f 5e463e3 1f97573 e37709f 1f97573 e37709f 1f97573 e37709f 5e463e3 e37709f 1f97573 3038fe7 5e463e3 3038fe7 5e463e3 3038fe7 1f97573 e37709f 7a8349e e37709f 1f97573 e37709f 1f97573 e37709f 1f97573 3038fe7 1f97573 7a8349e 1f97573 4b6e3ab 7a8349e 4b6e3ab 5e463e3 e37709f 4b6e3ab e37709f 7a8349e e37709f 4b6e3ab e37709f 4b6e3ab e37709f 4b6e3ab e37709f 1f97573 3038fe7 1f97573 e37709f 1f97573 5e463e3 e37709f ee30873 e37709f b734a17 e37709f b734a17 e37709f b734a17 e37709f b734a17 e37709f b734a17 e37709f b734a17 661a924 b734a17 e37709f ee30873 e37709f ee30873 e37709f ee30873 661a924 e37709f ee30873 e37709f ee30873 661a924 e37709f ee30873 e37709f ee30873 e37709f ee30873 661a924 e37709f 22198e9 e37709f 22198e9 e37709f 22198e9 e37709f 652c203 | 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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | """AuthService: User authentication, session management, and project ACL."""
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from typing import Dict, List, Optional
import uuid
from src.domain.models import Role, User
@dataclass
class UserProjectAccess:
"""Maps a user to projects with specific roles."""
username: str
project_slugs: Dict[str, Role] # Maps project_slug -> role (admin or validator)
is_active: bool = True
@dataclass
class Session:
"""Represents an authenticated user session."""
session_id: str
username: str
role: Role
authorized_projects: List[str] # Projects this user can access
created_at: datetime
last_activity: datetime
expires_at: datetime
authentication_method: str = "username"
def is_expired(self) -> bool:
"""Check if session has expired."""
return datetime.now(UTC) > self.expires_at
def update_activity(self, ttl_minutes: int = 120) -> None:
"""Update last activity timestamp and extend expiration."""
self.last_activity = datetime.now(UTC)
self.expires_at = datetime.now(UTC) + timedelta(minutes=ttl_minutes)
@dataclass
class ProjectInvite:
"""Represents an invitation to join a project.
Supports 3 scenarios:
1. Username only: internal app invite (no email notification)
2. Email only: external email-based invite (no prior HF account required)
3. Both: dual invite (internal + email notification)
"""
project_slug: str
role: Role
invited_by: str
created_at: datetime
expires_at: datetime
username: str | None = None # HF username (optional)
invitee_email: str | None = None # Email address (optional)
def __post_init__(self) -> None:
if not self.username and not self.invitee_email:
raise ValueError("At least one of username or invitee_email must be provided")
def is_expired(self) -> bool:
return datetime.now(UTC) > self.expires_at
@property
def invite_mode(self) -> str:
"""Return the invitation mode: 'username_only', 'email_only', or 'dual'."""
if self.username and self.invitee_email:
return "dual"
elif self.username:
return "username_only"
else:
return "email_only"
@dataclass
class UserProfile:
username: str
hf_email: str | None = None
class AuthService:
"""Manages user authentication, sessions, and project access control."""
def __init__(self, session_ttl_minutes: int = 120, invite_ttl_hours: int = 72):
"""Initialize AuthService with session TTL.
Args:
session_ttl_minutes: Session time-to-live in minutes (default: 2 hours)
"""
self.session_ttl_minutes = session_ttl_minutes
self.invite_ttl_hours = max(1, int(invite_ttl_hours))
self._sessions: Dict[str, Session] = {} # session_id -> Session
self._user_access: Dict[str, UserProjectAccess] = {} # username -> UserProjectAccess
self._pending_invites: Dict[str, Dict[str, ProjectInvite]] = {}
self._hf_tokens_by_username: Dict[str, str] = {}
self._user_profiles: Dict[str, UserProfile] = {}
def _refresh_or_revoke_sessions_for_username(self, username: str) -> None:
access = self._user_access.get(username)
session_ids = [sid for sid, session in self._sessions.items() if session.username == username]
if access is None or not access.is_active:
for session_id in session_ids:
self._sessions.pop(session_id, None)
return
projects = list(access.project_slugs.keys())
role = Role.admin if any(project_role == Role.admin for project_role in access.project_slugs.values()) else Role.validator
for session_id in session_ids:
session = self._sessions.get(session_id)
if session is None:
continue
session.authorized_projects = projects
session.role = role
session.update_activity(self.session_ttl_minutes)
def _prune_expired_invites(self) -> None:
expired_users: list[str] = []
for username, invites_by_project in self._pending_invites.items():
expired_projects = [project_slug for project_slug, invite in invites_by_project.items() if invite.is_expired()]
for project_slug in expired_projects:
del invites_by_project[project_slug]
if not invites_by_project:
expired_users.append(username)
for username in expired_users:
self._pending_invites.pop(username, None)
def register_user_project_access(
self, username: str, project_access: Dict[str, Role]
) -> None:
"""Register or update a user's access to projects.
Args:
username: User name
project_access: Dict mapping project_slug to Role (admin or validator)
"""
self._user_access[username] = UserProjectAccess(
username=username,
project_slugs=project_access,
is_active=True,
)
def list_usernames(self, include_inactive: bool = False) -> List[str]:
"""List registered usernames.
Args:
include_inactive: Include disabled users when True
Returns:
Sorted list of usernames
"""
usernames = []
for username, access in self._user_access.items():
if include_inactive or access.is_active:
usernames.append(username)
return sorted(usernames)
def upsert_user_project_role(self, username: str, project_slug: str, role: Role) -> None:
"""Create/update user assignment for a project.
Args:
username: User name
project_slug: Project slug
role: Role to apply for this project
"""
access = self._user_access.get(username)
if access is None:
access = UserProjectAccess(username=username, project_slugs={}, is_active=True)
self._user_access[username] = access
access.project_slugs[project_slug] = role
self._refresh_or_revoke_sessions_for_username(username)
def remove_user_project_role(self, username: str, project_slug: str) -> bool:
"""Remove a user assignment from a project.
Args:
username: User name
project_slug: Project slug
Returns:
True when assignment existed and was removed
"""
access = self._user_access.get(username)
if access is None:
return False
if project_slug not in access.project_slugs:
return False
del access.project_slugs[project_slug]
pending = self._pending_invites.get(username, {})
if project_slug in pending:
del pending[project_slug]
if not pending:
self._pending_invites.pop(username, None)
self._refresh_or_revoke_sessions_for_username(username)
return True
def login(self, username: str) -> Optional[Session]:
"""Authenticate a user and create a new session.
Args:
username: User name to authenticate
Returns:
Session if user exists and is active, None otherwise
"""
return self.login_internal(username=username)
def login_internal(
self,
username: str,
auto_promote_to_admin: bool = False,
authentication_method: str = "username",
) -> Optional[Session]:
if username not in self._user_access:
if not auto_promote_to_admin:
self._prune_expired_invites()
pending_for_user = self._pending_invites.get(username, {})
if not pending_for_user:
return None
self._user_access[username] = UserProjectAccess(
username=username,
project_slugs={},
is_active=True,
)
access = self._user_access[username]
if not access.is_active:
return None
# Determine highest role across all projects (admin > validator)
role = Role.admin if auto_promote_to_admin else Role.validator
if role != Role.admin:
for proj_role in access.project_slugs.values():
if proj_role == Role.admin:
role = Role.admin
break
session_id = str(uuid.uuid4())
now = datetime.now(UTC)
session = Session(
session_id=session_id,
username=username,
role=role,
authorized_projects=list(access.project_slugs.keys()),
created_at=now,
last_activity=now,
expires_at=now + timedelta(minutes=self.session_ttl_minutes),
authentication_method=authentication_method,
)
self._sessions[session_id] = session
return session
def login_with_verified_hf_identity(
self,
*,
username: str,
token: str,
email: str | None = None,
authentication_method: str = "oauth",
) -> tuple[Optional[Session], str]:
"""Create a session from an identity already verified by Hugging Face OAuth."""
username_value = (username or "").strip()
token_value = (token or "").strip()
if not username_value or not token_value:
return None, "Unable to authenticate with the verified Hugging Face identity"
email_value = (email or "").strip() or None
self._hf_tokens_by_username[username_value] = token_value
self._user_profiles[username_value] = UserProfile(username=username_value, hf_email=email_value)
is_first_user = len(self._user_access) == 0
session = self.login_internal(
username=username_value,
auto_promote_to_admin=is_first_user,
authentication_method=authentication_method,
)
if session is None:
return None, f"User '{username_value}' is not invited to any project yet"
if is_first_user:
return session, f"Welcome, {username_value}. Admin access enabled."
if session.role == Role.admin:
return session, f"Welcome, {username_value}. Admin access enabled."
return session, f"Welcome, {username_value}. Validator access enabled."
def get_session(self, session_id: str) -> Optional[Session]:
"""Retrieve an active session by ID.
Args:
session_id: Session ID
Returns:
Session if valid and not expired, None otherwise
"""
session = self._sessions.get(session_id)
if session is None:
return None
if session.is_expired():
self._sessions.pop(session_id, None)
return None
session.update_activity(self.session_ttl_minutes)
return session
def logout(self, session_id: str) -> None:
"""Delete a session.
Args:
session_id: Session ID to invalidate
"""
self._sessions.pop(session_id, None)
def is_user_authorized_for_project(self, username: str, project_slug: str) -> bool:
"""Check if a user has access to a specific project.
Args:
username: User name
project_slug: Project slug
Returns:
True if user has access (admin or validator), False otherwise
"""
access = self._user_access.get(username)
if access is None or not access.is_active:
return False
return project_slug in access.project_slugs
def get_user_role_for_project(self, username: str, project_slug: str) -> Optional[Role]:
"""Get the specific role a user has for a project.
Args:
username: User name
project_slug: Project slug
Returns:
Role if user has access, None otherwise
"""
access = self._user_access.get(username)
if access is None or not access.is_active:
return None
return access.project_slugs.get(project_slug)
def list_user_projects(self, username: str) -> List[str]:
"""List all projects a user has access to.
Args:
username: User name
Returns:
List of project slugs
"""
access = self._user_access.get(username)
if access is None or not access.is_active:
return []
return list(access.project_slugs.keys())
def cleanup_expired_sessions(self) -> None:
"""Remove all expired sessions (maintenance cleanup)."""
now = datetime.now(UTC)
expired = [
sid for sid, session in self._sessions.items() if session.is_expired()
]
for sid in expired:
self._sessions.pop(sid)
def refresh_session_authorizations(self, session_id: str) -> Optional[Session]:
"""Refresh a session with latest role and project assignments."""
session = self._sessions.get(session_id)
if session is None:
return None
if session.is_expired():
self._sessions.pop(session_id, None)
return None
access = self._user_access.get(session.username)
if access is None or not access.is_active:
self._sessions.pop(session_id, None)
return None
projects = list(access.project_slugs.keys())
session.authorized_projects = projects
session.role = Role.admin if any(role == Role.admin for role in access.project_slugs.values()) else Role.validator
session.update_activity(self.session_ttl_minutes)
return session
def set_user_active(self, username: str, active: bool) -> None:
"""Enable or disable a user account.
Args:
username: User name
active: Whether the user should be active
"""
if username in self._user_access:
self._user_access[username].is_active = active
if not active:
self._hf_tokens_by_username.pop(username, None)
self._refresh_or_revoke_sessions_for_username(username)
def get_hf_token_for_user(self, username: str) -> str | None:
token = (self._hf_tokens_by_username.get(username) or "").strip()
return token or None
def get_known_email_for_user(self, username: str) -> str | None:
profile = self._user_profiles.get(username)
if profile is None:
return None
email = (profile.hf_email or "").strip()
return email or None
def _pending_invite_keys_for_username(self, username: str) -> list[str]:
keys = [username]
known_email = self.get_known_email_for_user(username)
if known_email:
keys.insert(0, f"email:{known_email}")
return keys
def _find_pending_invite_bucket(self, username: str, project_slug: str) -> tuple[str | None, dict[str, ProjectInvite] | None, ProjectInvite | None]:
for invite_key in self._pending_invite_keys_for_username(username):
pending = self._pending_invites.get(invite_key, {})
invite = pending.get(project_slug)
if invite is not None:
return invite_key, pending, invite
return None, None, None
def create_project_invite(
self,
project_slug: str,
role: Role,
invited_by: str,
username: str | None = None,
invitee_email: str | None = None,
) -> tuple[bool, str]:
"""Create a project invite supporting 3 scenarios:
1. Username only: internal app invite (no email notification)
2. Email only: external email-based invite
3. Both: dual invite (internal + email notification)
Args:
project_slug: Target project
role: Role to assign
invited_by: Username of the inviter
username: (Optional) HF username of invitee
invitee_email: (Optional) Email address of invitee
Returns:
(success, message) tuple
"""
username = (username or "").strip() or None
invitee_email = (invitee_email or "").strip() or None
if not username and not invitee_email:
return False, "Please provide either a username or an email address"
self._prune_expired_invites()
# For username-based invites, check if already exists
if username:
user_invites = self._pending_invites.get(username, {})
if project_slug in user_invites:
return False, f"Invite for {username} to {project_slug} already exists"
now = datetime.now(UTC)
expires_at = now + timedelta(hours=self.invite_ttl_hours)
invite = ProjectInvite(
project_slug=project_slug,
role=role,
invited_by=invited_by,
created_at=now,
expires_at=expires_at,
username=username,
invitee_email=invitee_email,
)
# Store by username if available, otherwise by email (as temporary key)
if username:
self._pending_invites.setdefault(username, {})[project_slug] = invite
else:
# For email-only invites, use email as the storage key
# This allows the user to later link their username
email_key = f"email:{invitee_email}"
self._pending_invites.setdefault(email_key, {})[project_slug] = invite
mode = invite.invite_mode
summary = f"{mode.replace('_', ' ').title()} invite"
return True, summary
def list_pending_invites(self, username: str) -> List[ProjectInvite]:
self._prune_expired_invites()
invites: list[ProjectInvite] = []
seen_projects: set[str] = set()
for invite_key in self._pending_invite_keys_for_username(username):
for invite in self._pending_invites.get(invite_key, {}).values():
if invite.project_slug in seen_projects:
continue
seen_projects.add(invite.project_slug)
invites.append(invite)
invites.sort(key=lambda item: item.created_at)
return invites
def list_all_pending_invites(self) -> List[ProjectInvite]:
self._prune_expired_invites()
invites: list[ProjectInvite] = []
for invites_by_project in self._pending_invites.values():
invites.extend(invites_by_project.values())
invites.sort(key=lambda item: item.created_at)
return invites
def accept_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
self._prune_expired_invites()
invite_key, pending, invite = self._find_pending_invite_bucket(username, project_slug)
if invite_key is None or pending is None or invite is None:
return False, f"Invite not found for {username} in {project_slug}"
self.upsert_user_project_role(username, project_slug, invite.role)
del pending[project_slug]
if not pending:
self._pending_invites.pop(invite_key, None)
return True, f"Invite accepted for {project_slug} as {invite.role.value}"
def reject_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
self._prune_expired_invites()
invite_key, pending, invite = self._find_pending_invite_bucket(username, project_slug)
if invite_key is None or pending is None or invite is None:
return False, f"Invite not found for {username} in {project_slug}"
del pending[project_slug]
if not pending:
self._pending_invites.pop(invite_key, None)
return True, f"Invite rejected for {project_slug}"
def accept_all_project_invites(self, username: str) -> tuple[int, int, str]:
self._prune_expired_invites()
pending_keys = self._pending_invite_keys_for_username(username)
pending: dict[str, ProjectInvite] = {}
for invite_key in pending_keys:
pending.update(self._pending_invites.get(invite_key, {}))
if not pending:
return 0, 0, "No pending invites"
accepted = 0
failed = 0
for project_slug in list(pending.keys()):
ok, _ = self.accept_project_invite(username, project_slug)
if ok:
accepted += 1
else:
failed += 1
return accepted, failed, f"Accepted {accepted} invites" + (f", {failed} failed" if failed else "")
def revoke_project_invite(self, username: str, project_slug: str) -> tuple[bool, str]:
self._prune_expired_invites()
invite_key, pending, invite = self._find_pending_invite_bucket(username, project_slug)
if invite_key is None or pending is None or invite is None:
return False, f"Invite not found for {username} in {project_slug}"
del pending[project_slug]
if not pending:
self._pending_invites.pop(invite_key, None)
return True, f"Invite revoked for {username} in {project_slug}"
def export_user_access_map(self, include_inactive: bool = False) -> Dict[str, Dict[str, str]]:
"""Export user/project role mapping for persistence."""
exported: Dict[str, Dict[str, str]] = {}
for username in self.list_usernames(include_inactive=include_inactive):
access = self._user_access.get(username)
if access is None:
continue
exported[username] = {project_slug: role.value for project_slug, role in access.project_slugs.items()}
return exported
def export_pending_invites_map(self) -> Dict[str, Dict[str, Dict[str, str]]]:
self._prune_expired_invites()
payload: Dict[str, Dict[str, Dict[str, str]]] = {}
for username, invites_by_project in self._pending_invites.items():
payload[username] = {}
for project_slug, invite in invites_by_project.items():
payload[username][project_slug] = {
"role": invite.role.value,
"invited_by": invite.invited_by,
"created_at": invite.created_at.isoformat(),
"expires_at": invite.expires_at.isoformat(),
"username": invite.username or "",
"invitee_email": invite.invitee_email or "",
}
return payload
def load_pending_invites_map(self, payload: Dict[str, Dict[str, Dict[str, str]]]) -> None:
self._pending_invites = {}
for username, invites_by_project in (payload or {}).items():
if not isinstance(invites_by_project, dict):
continue
user_invites: Dict[str, ProjectInvite] = {}
for project_slug, invite_payload in invites_by_project.items():
if not isinstance(invite_payload, dict):
continue
role_text = str(invite_payload.get("role", "")).strip().lower()
if role_text not in {"admin", "validator"}:
continue
invited_by = str(invite_payload.get("invited_by", "")).strip() or "admin"
created_at_raw = str(invite_payload.get("created_at", "")).strip()
expires_at_raw = str(invite_payload.get("expires_at", "")).strip()
try:
created_at = datetime.fromisoformat(created_at_raw) if created_at_raw else datetime.now(UTC)
except Exception:
created_at = datetime.now(UTC)
try:
expires_at = datetime.fromisoformat(expires_at_raw) if expires_at_raw else (created_at + timedelta(hours=self.invite_ttl_hours))
except Exception:
expires_at = created_at + timedelta(hours=self.invite_ttl_hours)
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=UTC)
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=UTC)
stored_username = str(invite_payload.get("username", "")).strip()
stored_email = str(invite_payload.get("invitee_email", "")).strip()
if not stored_username and not stored_email:
if str(username).startswith("email:"):
stored_email = str(username)[len("email:") :]
else:
stored_username = str(username)
user_invites[str(project_slug)] = ProjectInvite(
username=stored_username or None,
invitee_email=stored_email or None,
project_slug=str(project_slug),
role=Role(role_text),
invited_by=invited_by,
created_at=created_at,
expires_at=expires_at,
)
if user_invites:
self._pending_invites[str(username)] = user_invites
self._prune_expired_invites()
def revoke_all_invites_for_project(self, project_slug: str) -> int:
"""Remove all pending invites for a project.
Returns:
Number of revoked invites
"""
self._prune_expired_invites()
revoked = 0
empty_users: list[str] = []
for username, invites_by_project in self._pending_invites.items():
if project_slug in invites_by_project:
del invites_by_project[project_slug]
revoked += 1
if not invites_by_project:
empty_users.append(username)
for username in empty_users:
self._pending_invites.pop(username, None)
return revoked
def remove_project_from_all_users(self, project_slug: str) -> int:
"""Remove a project assignment from all users and refresh active sessions.
Returns:
Number of user assignments removed
"""
removed = 0
for access in self._user_access.values():
if project_slug in access.project_slugs:
del access.project_slugs[project_slug]
removed += 1
for session in self._sessions.values():
if project_slug in session.authorized_projects:
session.authorized_projects = [slug for slug in session.authorized_projects if slug != project_slug]
access = self._user_access.get(session.username)
if access is None or not access.is_active:
continue
session.role = (
Role.admin
if any(role == Role.admin for role in access.project_slugs.values())
else Role.validator
)
return removed
|