Spaces:
Sleeping
Sleeping
Commit ·
5e463e3
1
Parent(s): 1249068
feat(security): harden project ACL, durable state, and email invite flow
Browse files- README.md +30 -1
- src/auth/auth_service.py +51 -4
- src/config/runtime_config.py +48 -1
- src/services/invite_email_notifier.py +83 -0
- src/ui/admin_panel.py +91 -9
- src/ui/app_factory.py +83 -26
- tests/unit/test_admin_panel_manager.py +114 -0
- tests/unit/test_app_factory_audio_helpers.py +27 -0
- tests/unit/test_auth_service.py +53 -0
README.md
CHANGED
|
@@ -59,8 +59,22 @@ Optional runtime configuration:
|
|
| 59 |
- `BIRDNET_PAGE_SIZE`: queue page size (default: `25`).
|
| 60 |
- `BIRDNET_PROJECTS_FILE`: JSON file with project catalog used at app startup.
|
| 61 |
- `BIRDNET_USER_ACCESS_FILE`: JSON file mapping users to project roles (`admin`/`validator`).
|
|
|
|
|
|
|
|
|
|
| 62 |
- `BIRDNET_ENABLE_DEMO_BOOTSTRAP`: set to `true` only for local/demo mode to load built-in sample users/projects.
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
JSON seed format examples:
|
| 65 |
|
| 66 |
```json
|
|
@@ -210,10 +224,23 @@ Required for production bootstrap:
|
|
| 210 |
|
| 211 |
Optional runtime settings:
|
| 212 |
- `BIRDNET_DETECTIONS_FILE` (seed detections JSON)
|
| 213 |
-
- `BIRDNET_VALIDATIONS_DIR` (
|
|
|
|
|
|
|
|
|
|
| 214 |
- `BIRDNET_PAGE_SIZE` (default `25`)
|
| 215 |
- `BIRDNET_ENABLE_DEMO_BOOTSTRAP` (`false` in production)
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
4. For first smoke test only, you may temporarily set:
|
| 218 |
- `BIRDNET_ENABLE_DEMO_BOOTSTRAP=true`
|
| 219 |
|
|
@@ -229,6 +256,8 @@ Then log in with one of the demo users:
|
|
| 229 |
Notes:
|
| 230 |
- The app entrypoint reads `PORT` automatically in Spaces.
|
| 231 |
- Keep user/project bootstrap files private if they contain sensitive assignments.
|
|
|
|
|
|
|
| 232 |
|
| 233 |
## Troubleshooting
|
| 234 |
|
|
|
|
| 59 |
- `BIRDNET_PAGE_SIZE`: queue page size (default: `25`).
|
| 60 |
- `BIRDNET_PROJECTS_FILE`: JSON file with project catalog used at app startup.
|
| 61 |
- `BIRDNET_USER_ACCESS_FILE`: JSON file mapping users to project roles (`admin`/`validator`).
|
| 62 |
+
- `BIRDNET_INVITES_FILE`: JSON file storing pending invites.
|
| 63 |
+
- `BIRDNET_INVITE_TTL_HOURS`: invite expiration in hours (default: `72`).
|
| 64 |
+
- `BIRDNET_BOOTSTRAP_DIR`: base directory for bootstrap state files (`projects.json`, `user_access.json`, `invites.json`).
|
| 65 |
- `BIRDNET_ENABLE_DEMO_BOOTSTRAP`: set to `true` only for local/demo mode to load built-in sample users/projects.
|
| 66 |
|
| 67 |
+
Invite email settings (SMTP):
|
| 68 |
+
|
| 69 |
+
- `BIRDNET_INVITE_EMAIL_ENABLED`: set to `true` to send invite emails.
|
| 70 |
+
- `BIRDNET_INVITE_EMAIL_SENDER`: sender email used for project invitations.
|
| 71 |
+
- `BIRDNET_INVITE_EMAIL_LOGIN_URL`: login URL included in invitation instructions.
|
| 72 |
+
- `BIRDNET_SMTP_HOST`: SMTP server host.
|
| 73 |
+
- `BIRDNET_SMTP_PORT`: SMTP server port (default: `587`).
|
| 74 |
+
- `BIRDNET_SMTP_USERNAME`: SMTP username (optional).
|
| 75 |
+
- `BIRDNET_SMTP_PASSWORD`: SMTP password or app token.
|
| 76 |
+
- `BIRDNET_SMTP_USE_TLS`: set to `false` only when TLS is not available.
|
| 77 |
+
|
| 78 |
JSON seed format examples:
|
| 79 |
|
| 80 |
```json
|
|
|
|
| 224 |
|
| 225 |
Optional runtime settings:
|
| 226 |
- `BIRDNET_DETECTIONS_FILE` (seed detections JSON)
|
| 227 |
+
- `BIRDNET_VALIDATIONS_DIR` (recommended: `/data/validations`)
|
| 228 |
+
- `BIRDNET_BOOTSTRAP_DIR` (recommended: `/data/bootstrap`)
|
| 229 |
+
- `BIRDNET_INVITES_FILE` (recommended: `/data/bootstrap/invites.json`)
|
| 230 |
+
- `BIRDNET_INVITE_TTL_HOURS` (default `72`)
|
| 231 |
- `BIRDNET_PAGE_SIZE` (default `25`)
|
| 232 |
- `BIRDNET_ENABLE_DEMO_BOOTSTRAP` (`false` in production)
|
| 233 |
|
| 234 |
+
Optional invite email settings:
|
| 235 |
+
- `BIRDNET_INVITE_EMAIL_ENABLED=true`
|
| 236 |
+
- `BIRDNET_INVITE_EMAIL_SENDER`
|
| 237 |
+
- `BIRDNET_INVITE_EMAIL_LOGIN_URL`
|
| 238 |
+
- `BIRDNET_SMTP_HOST`
|
| 239 |
+
- `BIRDNET_SMTP_PORT`
|
| 240 |
+
- `BIRDNET_SMTP_USERNAME`
|
| 241 |
+
- `BIRDNET_SMTP_PASSWORD`
|
| 242 |
+
- `BIRDNET_SMTP_USE_TLS`
|
| 243 |
+
|
| 244 |
4. For first smoke test only, you may temporarily set:
|
| 245 |
- `BIRDNET_ENABLE_DEMO_BOOTSTRAP=true`
|
| 246 |
|
|
|
|
| 256 |
Notes:
|
| 257 |
- The app entrypoint reads `PORT` automatically in Spaces.
|
| 258 |
- Keep user/project bootstrap files private if they contain sensitive assignments.
|
| 259 |
+
- Use `/data` paths in Spaces to keep projects, invites, ACL, and validations across redeploys.
|
| 260 |
+
- Collaborative access is token-per-user: each collaborator logs in with their own Hugging Face token.
|
| 261 |
|
| 262 |
## Troubleshooting
|
| 263 |
|
src/auth/auth_service.py
CHANGED
|
@@ -30,7 +30,6 @@ class Session:
|
|
| 30 |
created_at: datetime
|
| 31 |
last_activity: datetime
|
| 32 |
expires_at: datetime
|
| 33 |
-
hf_token: str | None = None
|
| 34 |
|
| 35 |
def is_expired(self) -> bool:
|
| 36 |
"""Check if session has expired."""
|
|
@@ -55,6 +54,12 @@ class ProjectInvite:
|
|
| 55 |
return datetime.now(UTC) > self.expires_at
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
class AuthService:
|
| 59 |
"""Manages user authentication, sessions, and project access control."""
|
| 60 |
|
|
@@ -69,6 +74,26 @@ class AuthService:
|
|
| 69 |
self._sessions: Dict[str, Session] = {} # session_id -> Session
|
| 70 |
self._user_access: Dict[str, UserProjectAccess] = {} # username -> UserProjectAccess
|
| 71 |
self._pending_invites: Dict[str, Dict[str, ProjectInvite]] = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
def _prune_expired_invites(self) -> None:
|
| 74 |
expired_users: list[str] = []
|
|
@@ -126,6 +151,7 @@ class AuthService:
|
|
| 126 |
self._user_access[username] = access
|
| 127 |
|
| 128 |
access.project_slugs[project_slug] = role
|
|
|
|
| 129 |
|
| 130 |
def remove_user_project_role(self, username: str, project_slug: str) -> bool:
|
| 131 |
"""Remove a user assignment from a project.
|
|
@@ -145,6 +171,12 @@ class AuthService:
|
|
| 145 |
return False
|
| 146 |
|
| 147 |
del access.project_slugs[project_slug]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
return True
|
| 149 |
|
| 150 |
def login(self, username: str) -> Optional[Session]:
|
|
@@ -161,7 +193,6 @@ class AuthService:
|
|
| 161 |
def login_internal(
|
| 162 |
self,
|
| 163 |
username: str,
|
| 164 |
-
hf_token: str | None = None,
|
| 165 |
auto_promote_to_admin: bool = False,
|
| 166 |
) -> Optional[Session]:
|
| 167 |
if username not in self._user_access:
|
|
@@ -198,7 +229,6 @@ class AuthService:
|
|
| 198 |
created_at=now,
|
| 199 |
last_activity=now,
|
| 200 |
expires_at=now + timedelta(minutes=self.session_ttl_minutes),
|
| 201 |
-
hf_token=hf_token,
|
| 202 |
)
|
| 203 |
|
| 204 |
self._sessions[session_id] = session
|
|
@@ -219,10 +249,13 @@ class AuthService:
|
|
| 219 |
if not username:
|
| 220 |
return None, "❌ Unable to resolve Hugging Face username from token"
|
| 221 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
is_first_user = len(self._user_access) == 0
|
| 223 |
session = self.login_internal(
|
| 224 |
username=username,
|
| 225 |
-
hf_token=token_value,
|
| 226 |
auto_promote_to_admin=is_first_user,
|
| 227 |
)
|
| 228 |
if session is None:
|
|
@@ -347,6 +380,20 @@ class AuthService:
|
|
| 347 |
"""
|
| 348 |
if username in self._user_access:
|
| 349 |
self._user_access[username].is_active = active
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
|
| 351 |
def create_project_invite(
|
| 352 |
self,
|
|
|
|
| 30 |
created_at: datetime
|
| 31 |
last_activity: datetime
|
| 32 |
expires_at: datetime
|
|
|
|
| 33 |
|
| 34 |
def is_expired(self) -> bool:
|
| 35 |
"""Check if session has expired."""
|
|
|
|
| 54 |
return datetime.now(UTC) > self.expires_at
|
| 55 |
|
| 56 |
|
| 57 |
+
@dataclass
|
| 58 |
+
class UserProfile:
|
| 59 |
+
username: str
|
| 60 |
+
hf_email: str | None = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
class AuthService:
|
| 64 |
"""Manages user authentication, sessions, and project access control."""
|
| 65 |
|
|
|
|
| 74 |
self._sessions: Dict[str, Session] = {} # session_id -> Session
|
| 75 |
self._user_access: Dict[str, UserProjectAccess] = {} # username -> UserProjectAccess
|
| 76 |
self._pending_invites: Dict[str, Dict[str, ProjectInvite]] = {}
|
| 77 |
+
self._hf_tokens_by_username: Dict[str, str] = {}
|
| 78 |
+
self._user_profiles: Dict[str, UserProfile] = {}
|
| 79 |
+
|
| 80 |
+
def _refresh_or_revoke_sessions_for_username(self, username: str) -> None:
|
| 81 |
+
access = self._user_access.get(username)
|
| 82 |
+
session_ids = [sid for sid, session in self._sessions.items() if session.username == username]
|
| 83 |
+
if access is None or not access.is_active:
|
| 84 |
+
for session_id in session_ids:
|
| 85 |
+
self._sessions.pop(session_id, None)
|
| 86 |
+
return
|
| 87 |
+
|
| 88 |
+
projects = list(access.project_slugs.keys())
|
| 89 |
+
role = Role.admin if any(project_role == Role.admin for project_role in access.project_slugs.values()) else Role.validator
|
| 90 |
+
for session_id in session_ids:
|
| 91 |
+
session = self._sessions.get(session_id)
|
| 92 |
+
if session is None:
|
| 93 |
+
continue
|
| 94 |
+
session.authorized_projects = projects
|
| 95 |
+
session.role = role
|
| 96 |
+
session.update_activity(self.session_ttl_minutes)
|
| 97 |
|
| 98 |
def _prune_expired_invites(self) -> None:
|
| 99 |
expired_users: list[str] = []
|
|
|
|
| 151 |
self._user_access[username] = access
|
| 152 |
|
| 153 |
access.project_slugs[project_slug] = role
|
| 154 |
+
self._refresh_or_revoke_sessions_for_username(username)
|
| 155 |
|
| 156 |
def remove_user_project_role(self, username: str, project_slug: str) -> bool:
|
| 157 |
"""Remove a user assignment from a project.
|
|
|
|
| 171 |
return False
|
| 172 |
|
| 173 |
del access.project_slugs[project_slug]
|
| 174 |
+
pending = self._pending_invites.get(username, {})
|
| 175 |
+
if project_slug in pending:
|
| 176 |
+
del pending[project_slug]
|
| 177 |
+
if not pending:
|
| 178 |
+
self._pending_invites.pop(username, None)
|
| 179 |
+
self._refresh_or_revoke_sessions_for_username(username)
|
| 180 |
return True
|
| 181 |
|
| 182 |
def login(self, username: str) -> Optional[Session]:
|
|
|
|
| 193 |
def login_internal(
|
| 194 |
self,
|
| 195 |
username: str,
|
|
|
|
| 196 |
auto_promote_to_admin: bool = False,
|
| 197 |
) -> Optional[Session]:
|
| 198 |
if username not in self._user_access:
|
|
|
|
| 229 |
created_at=now,
|
| 230 |
last_activity=now,
|
| 231 |
expires_at=now + timedelta(minutes=self.session_ttl_minutes),
|
|
|
|
| 232 |
)
|
| 233 |
|
| 234 |
self._sessions[session_id] = session
|
|
|
|
| 249 |
if not username:
|
| 250 |
return None, "❌ Unable to resolve Hugging Face username from token"
|
| 251 |
|
| 252 |
+
email_value = str(whoami.get("email") or "").strip() or None
|
| 253 |
+
self._hf_tokens_by_username[username] = token_value
|
| 254 |
+
self._user_profiles[username] = UserProfile(username=username, hf_email=email_value)
|
| 255 |
+
|
| 256 |
is_first_user = len(self._user_access) == 0
|
| 257 |
session = self.login_internal(
|
| 258 |
username=username,
|
|
|
|
| 259 |
auto_promote_to_admin=is_first_user,
|
| 260 |
)
|
| 261 |
if session is None:
|
|
|
|
| 380 |
"""
|
| 381 |
if username in self._user_access:
|
| 382 |
self._user_access[username].is_active = active
|
| 383 |
+
if not active:
|
| 384 |
+
self._hf_tokens_by_username.pop(username, None)
|
| 385 |
+
self._refresh_or_revoke_sessions_for_username(username)
|
| 386 |
+
|
| 387 |
+
def get_hf_token_for_user(self, username: str) -> str | None:
|
| 388 |
+
token = (self._hf_tokens_by_username.get(username) or "").strip()
|
| 389 |
+
return token or None
|
| 390 |
+
|
| 391 |
+
def get_known_email_for_user(self, username: str) -> str | None:
|
| 392 |
+
profile = self._user_profiles.get(username)
|
| 393 |
+
if profile is None:
|
| 394 |
+
return None
|
| 395 |
+
email = (profile.hf_email or "").strip()
|
| 396 |
+
return email or None
|
| 397 |
|
| 398 |
def create_project_invite(
|
| 399 |
self,
|
src/config/runtime_config.py
CHANGED
|
@@ -8,20 +8,36 @@ from pathlib import Path
|
|
| 8 |
class RuntimeConfig:
|
| 9 |
detection_seed_path: str | None
|
| 10 |
validation_base_dir: str
|
|
|
|
| 11 |
page_size: int
|
| 12 |
projects_file_path: str | None
|
| 13 |
user_access_file_path: str | None
|
| 14 |
invites_file_path: str | None
|
| 15 |
invite_ttl_hours: int
|
| 16 |
enable_demo_bootstrap: bool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
@classmethod
|
| 19 |
def from_env(cls) -> "RuntimeConfig":
|
| 20 |
detection_seed_path = (os.getenv("BIRDNET_DETECTIONS_FILE") or "").strip() or None
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
validation_base_dir = (
|
| 23 |
os.getenv("BIRDNET_VALIDATIONS_DIR")
|
| 24 |
-
or str(
|
| 25 |
)
|
| 26 |
|
| 27 |
raw_page_size = (os.getenv("BIRDNET_PAGE_SIZE") or "").strip()
|
|
@@ -50,13 +66,44 @@ class RuntimeConfig:
|
|
| 50 |
raw_enable_demo_bootstrap = (os.getenv("BIRDNET_ENABLE_DEMO_BOOTSTRAP") or "").strip().lower()
|
| 51 |
enable_demo_bootstrap = raw_enable_demo_bootstrap in {"1", "true", "yes", "on"}
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
return cls(
|
| 54 |
detection_seed_path=detection_seed_path,
|
| 55 |
validation_base_dir=validation_base_dir,
|
|
|
|
| 56 |
page_size=page_size,
|
| 57 |
projects_file_path=projects_file_path,
|
| 58 |
user_access_file_path=user_access_file_path,
|
| 59 |
invites_file_path=invites_file_path,
|
| 60 |
invite_ttl_hours=invite_ttl_hours,
|
| 61 |
enable_demo_bootstrap=enable_demo_bootstrap,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
)
|
|
|
|
| 8 |
class RuntimeConfig:
|
| 9 |
detection_seed_path: str | None
|
| 10 |
validation_base_dir: str
|
| 11 |
+
bootstrap_base_dir: str
|
| 12 |
page_size: int
|
| 13 |
projects_file_path: str | None
|
| 14 |
user_access_file_path: str | None
|
| 15 |
invites_file_path: str | None
|
| 16 |
invite_ttl_hours: int
|
| 17 |
enable_demo_bootstrap: bool
|
| 18 |
+
invite_email_enabled: bool
|
| 19 |
+
invite_email_sender: str
|
| 20 |
+
invite_email_login_url: str
|
| 21 |
+
smtp_host: str | None
|
| 22 |
+
smtp_port: int
|
| 23 |
+
smtp_username: str | None
|
| 24 |
+
smtp_password: str | None
|
| 25 |
+
smtp_use_tls: bool
|
| 26 |
|
| 27 |
@classmethod
|
| 28 |
def from_env(cls) -> "RuntimeConfig":
|
| 29 |
detection_seed_path = (os.getenv("BIRDNET_DETECTIONS_FILE") or "").strip() or None
|
| 30 |
|
| 31 |
+
data_root = Path("/data") if Path("/data").exists() else (Path(tempfile.gettempdir()) / "birdnet-validator-data")
|
| 32 |
+
|
| 33 |
+
bootstrap_base_dir = (
|
| 34 |
+
os.getenv("BIRDNET_BOOTSTRAP_DIR")
|
| 35 |
+
or str(data_root / "bootstrap")
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
validation_base_dir = (
|
| 39 |
os.getenv("BIRDNET_VALIDATIONS_DIR")
|
| 40 |
+
or str(data_root / "validations")
|
| 41 |
)
|
| 42 |
|
| 43 |
raw_page_size = (os.getenv("BIRDNET_PAGE_SIZE") or "").strip()
|
|
|
|
| 66 |
raw_enable_demo_bootstrap = (os.getenv("BIRDNET_ENABLE_DEMO_BOOTSTRAP") or "").strip().lower()
|
| 67 |
enable_demo_bootstrap = raw_enable_demo_bootstrap in {"1", "true", "yes", "on"}
|
| 68 |
|
| 69 |
+
raw_invite_email_enabled = (os.getenv("BIRDNET_INVITE_EMAIL_ENABLED") or "").strip().lower()
|
| 70 |
+
invite_email_enabled = raw_invite_email_enabled in {"1", "true", "yes", "on"}
|
| 71 |
+
invite_email_sender = (os.getenv("BIRDNET_INVITE_EMAIL_SENDER") or "").strip()
|
| 72 |
+
invite_email_login_url = (os.getenv("BIRDNET_INVITE_EMAIL_LOGIN_URL") or "").strip() or ""
|
| 73 |
+
|
| 74 |
+
smtp_host = (os.getenv("BIRDNET_SMTP_HOST") or "").strip() or None
|
| 75 |
+
|
| 76 |
+
raw_smtp_port = (os.getenv("BIRDNET_SMTP_PORT") or "").strip()
|
| 77 |
+
smtp_port = 587
|
| 78 |
+
if raw_smtp_port:
|
| 79 |
+
try:
|
| 80 |
+
parsed = int(raw_smtp_port)
|
| 81 |
+
if parsed > 0:
|
| 82 |
+
smtp_port = parsed
|
| 83 |
+
except ValueError:
|
| 84 |
+
smtp_port = 587
|
| 85 |
+
|
| 86 |
+
smtp_username = (os.getenv("BIRDNET_SMTP_USERNAME") or "").strip() or None
|
| 87 |
+
smtp_password = (os.getenv("BIRDNET_SMTP_PASSWORD") or "").strip() or None
|
| 88 |
+
raw_smtp_use_tls = (os.getenv("BIRDNET_SMTP_USE_TLS") or "").strip().lower()
|
| 89 |
+
smtp_use_tls = raw_smtp_use_tls not in {"0", "false", "no", "off"}
|
| 90 |
+
|
| 91 |
return cls(
|
| 92 |
detection_seed_path=detection_seed_path,
|
| 93 |
validation_base_dir=validation_base_dir,
|
| 94 |
+
bootstrap_base_dir=bootstrap_base_dir,
|
| 95 |
page_size=page_size,
|
| 96 |
projects_file_path=projects_file_path,
|
| 97 |
user_access_file_path=user_access_file_path,
|
| 98 |
invites_file_path=invites_file_path,
|
| 99 |
invite_ttl_hours=invite_ttl_hours,
|
| 100 |
enable_demo_bootstrap=enable_demo_bootstrap,
|
| 101 |
+
invite_email_enabled=invite_email_enabled,
|
| 102 |
+
invite_email_sender=invite_email_sender,
|
| 103 |
+
invite_email_login_url=invite_email_login_url,
|
| 104 |
+
smtp_host=smtp_host,
|
| 105 |
+
smtp_port=smtp_port,
|
| 106 |
+
smtp_username=smtp_username,
|
| 107 |
+
smtp_password=smtp_password,
|
| 108 |
+
smtp_use_tls=smtp_use_tls,
|
| 109 |
)
|
src/services/invite_email_notifier.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Email delivery adapter for project collaboration invites."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import smtplib
|
| 6 |
+
from email.message import EmailMessage
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass(frozen=True)
|
| 10 |
+
class InviteEmailPayload:
|
| 11 |
+
invitee_username: str
|
| 12 |
+
invitee_email: str
|
| 13 |
+
project_slug: str
|
| 14 |
+
role: str
|
| 15 |
+
invited_by: str
|
| 16 |
+
expires_at: datetime
|
| 17 |
+
login_url: str
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class InviteEmailNotifier:
|
| 21 |
+
"""Abstract notifier used by admin flow to send invite emails."""
|
| 22 |
+
|
| 23 |
+
def send(self, payload: InviteEmailPayload) -> tuple[bool, str]:
|
| 24 |
+
raise NotImplementedError
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class NoopInviteEmailNotifier(InviteEmailNotifier):
|
| 28 |
+
"""Fallback notifier when SMTP is not configured."""
|
| 29 |
+
|
| 30 |
+
def send(self, payload: InviteEmailPayload) -> tuple[bool, str]:
|
| 31 |
+
return False, "Invite email not sent: email notifications are disabled"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SmtpInviteEmailNotifier(InviteEmailNotifier):
|
| 35 |
+
"""SMTP-based email notifier for project invites."""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
sender_email: str,
|
| 40 |
+
smtp_host: str,
|
| 41 |
+
smtp_port: int,
|
| 42 |
+
smtp_username: str | None = None,
|
| 43 |
+
smtp_password: str | None = None,
|
| 44 |
+
smtp_use_tls: bool = True,
|
| 45 |
+
):
|
| 46 |
+
self._sender_email = sender_email
|
| 47 |
+
self._smtp_host = smtp_host
|
| 48 |
+
self._smtp_port = smtp_port
|
| 49 |
+
self._smtp_username = smtp_username
|
| 50 |
+
self._smtp_password = smtp_password
|
| 51 |
+
self._smtp_use_tls = smtp_use_tls
|
| 52 |
+
|
| 53 |
+
def send(self, payload: InviteEmailPayload) -> tuple[bool, str]:
|
| 54 |
+
message = EmailMessage()
|
| 55 |
+
message["From"] = self._sender_email
|
| 56 |
+
message["To"] = payload.invitee_email
|
| 57 |
+
message["Subject"] = f"BirdNET project invite: {payload.project_slug}"
|
| 58 |
+
|
| 59 |
+
body = (
|
| 60 |
+
f"Hello {payload.invitee_username},\n\n"
|
| 61 |
+
f"You were invited by {payload.invited_by} to collaborate on project '{payload.project_slug}' "
|
| 62 |
+
f"with role '{payload.role}'.\n"
|
| 63 |
+
f"Invite expires at: {payload.expires_at.isoformat()}\n\n"
|
| 64 |
+
"How to join:\n"
|
| 65 |
+
"1) Open Hugging Face and create an Access Token in Settings -> Access Tokens.\n"
|
| 66 |
+
"2) Open BirdNET Validator login.\n"
|
| 67 |
+
"3) Login using your Hugging Face token.\n"
|
| 68 |
+
"4) Go to 'Select Project' and accept your invite.\n\n"
|
| 69 |
+
f"Login URL: {payload.login_url or '(configured by admin)'}\n\n"
|
| 70 |
+
"If you were not expecting this invitation, ignore this email.\n"
|
| 71 |
+
)
|
| 72 |
+
message.set_content(body)
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
with smtplib.SMTP(self._smtp_host, self._smtp_port, timeout=20) as server:
|
| 76 |
+
if self._smtp_use_tls:
|
| 77 |
+
server.starttls()
|
| 78 |
+
if self._smtp_username and self._smtp_password:
|
| 79 |
+
server.login(self._smtp_username, self._smtp_password)
|
| 80 |
+
server.send_message(message)
|
| 81 |
+
return True, f"Invite email sent to {payload.invitee_email}"
|
| 82 |
+
except Exception as exc:
|
| 83 |
+
return False, f"Invite created, but email delivery failed: {exc}"
|
src/ui/admin_panel.py
CHANGED
|
@@ -6,12 +6,18 @@ import gradio as gr
|
|
| 6 |
|
| 7 |
from src.auth.auth_service import AuthService, Session
|
| 8 |
from src.domain.models import Project, Role
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
class AdminPanelManager:
|
| 12 |
"""Management backend for the admin panel."""
|
| 13 |
|
| 14 |
-
def __init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
"""Initialize admin panel manager.
|
| 16 |
|
| 17 |
Args:
|
|
@@ -19,6 +25,11 @@ class AdminPanelManager:
|
|
| 19 |
"""
|
| 20 |
self.auth_service = auth_service
|
| 21 |
self._projects: dict[str, Project] = {} # project_slug -> Project
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def register_project(self, project: Project) -> bool:
|
| 24 |
"""Register a new project (idempotent).
|
|
@@ -48,6 +59,7 @@ class AdminPanelManager:
|
|
| 48 |
"dataset_repo_id": p.dataset_repo_id,
|
| 49 |
"visibility": p.visibility,
|
| 50 |
"owner_username": p.owner_username,
|
|
|
|
| 51 |
"dataset_token_set": bool((p.dataset_token or "").strip()),
|
| 52 |
"active": p.active,
|
| 53 |
}
|
|
@@ -83,7 +95,7 @@ class AdminPanelManager:
|
|
| 83 |
return result
|
| 84 |
|
| 85 |
def assign_user_to_project(
|
| 86 |
-
self, username: str, project_slug: str, role: str
|
| 87 |
) -> Tuple[bool, str]:
|
| 88 |
"""Assign a user to a project with a role.
|
| 89 |
|
|
@@ -98,12 +110,19 @@ class AdminPanelManager:
|
|
| 98 |
if project_slug not in self._projects:
|
| 99 |
return False, f"Project '{project_slug}' not found"
|
| 100 |
|
|
|
|
|
|
|
|
|
|
| 101 |
if role not in ["admin", "validator"]:
|
| 102 |
return False, f"Invalid role: {role}"
|
| 103 |
|
| 104 |
project = self._projects[project_slug]
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
self.auth_service.upsert_user_project_role(username, project_slug, Role(role))
|
| 109 |
|
|
@@ -111,14 +130,19 @@ class AdminPanelManager:
|
|
| 111 |
|
| 112 |
def invite_user_to_project(
|
| 113 |
self,
|
|
|
|
| 114 |
invited_by: str,
|
| 115 |
username: str,
|
|
|
|
| 116 |
project_slug: str,
|
| 117 |
role: str,
|
| 118 |
) -> Tuple[bool, str]:
|
| 119 |
if project_slug not in self._projects:
|
| 120 |
return False, f"Project '{project_slug}' not found"
|
| 121 |
|
|
|
|
|
|
|
|
|
|
| 122 |
if role not in ["admin", "validator"]:
|
| 123 |
return False, f"Invalid role: {role}"
|
| 124 |
|
|
@@ -126,12 +150,37 @@ class AdminPanelManager:
|
|
| 126 |
if project.visibility == "private":
|
| 127 |
return False, "Private projects do not accept collaborators"
|
| 128 |
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
username=username,
|
| 131 |
project_slug=project_slug,
|
| 132 |
role=Role(role),
|
| 133 |
invited_by=invited_by,
|
| 134 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
def list_pending_invites(self, project_slug: str | None = None) -> List[dict]:
|
| 137 |
invites = self.auth_service.list_all_pending_invites()
|
|
@@ -153,7 +202,7 @@ class AdminPanelManager:
|
|
| 153 |
def revoke_invite(self, username: str, project_slug: str) -> Tuple[bool, str]:
|
| 154 |
return self.auth_service.revoke_project_invite(username=username, project_slug=project_slug)
|
| 155 |
|
| 156 |
-
def delete_project(self, project_slug: str) -> Tuple[bool, str]:
|
| 157 |
"""Delete a project and remove all linked assignments/invites."""
|
| 158 |
slug = (project_slug or "").strip()
|
| 159 |
if not slug:
|
|
@@ -161,6 +210,17 @@ class AdminPanelManager:
|
|
| 161 |
if slug not in self._projects:
|
| 162 |
return False, f"Project '{slug}' not found"
|
| 163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
del self._projects[slug]
|
| 165 |
removed_assignments = self.auth_service.remove_project_from_all_users(slug)
|
| 166 |
revoked_invites = self.auth_service.revoke_all_invites_for_project(slug)
|
|
@@ -169,7 +229,7 @@ class AdminPanelManager:
|
|
| 169 |
f"✅ Project '{slug}' deleted (removed assignments: {removed_assignments}, revoked invites: {revoked_invites})",
|
| 170 |
)
|
| 171 |
|
| 172 |
-
def remove_user_from_project(self, username: str, project_slug: str) -> Tuple[bool, str]:
|
| 173 |
"""Remove a user's access to a project.
|
| 174 |
|
| 175 |
Args:
|
|
@@ -182,6 +242,19 @@ class AdminPanelManager:
|
|
| 182 |
if username not in self.auth_service.list_usernames(include_inactive=True):
|
| 183 |
return False, f"User '{username}' not found"
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
role = self.auth_service.get_user_role_for_project(username, project_slug)
|
| 186 |
if role is None:
|
| 187 |
return False, f"User '{username}' is not assigned to project '{project_slug}'"
|
|
@@ -295,11 +368,20 @@ def create_admin_panel(admin_manager: AdminPanelManager, current_session: Sessio
|
|
| 295 |
remove_button = gr.Button("Remove User", variant="stop")
|
| 296 |
|
| 297 |
def assign_user(username: str, project_slug: str, role: str) -> str:
|
| 298 |
-
success, msg = admin_manager.assign_user_to_project(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
return msg
|
| 300 |
|
| 301 |
def remove_user(username: str, project_slug: str) -> str:
|
| 302 |
-
success, msg = admin_manager.remove_user_from_project(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
return msg
|
| 304 |
|
| 305 |
assign_button.click(
|
|
|
|
| 6 |
|
| 7 |
from src.auth.auth_service import AuthService, Session
|
| 8 |
from src.domain.models import Project, Role
|
| 9 |
+
from src.services.invite_email_notifier import InviteEmailNotifier, InviteEmailPayload, NoopInviteEmailNotifier
|
| 10 |
|
| 11 |
|
| 12 |
class AdminPanelManager:
|
| 13 |
"""Management backend for the admin panel."""
|
| 14 |
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
auth_service: AuthService,
|
| 18 |
+
invite_notifier: InviteEmailNotifier | None = None,
|
| 19 |
+
invite_login_url: str = "",
|
| 20 |
+
):
|
| 21 |
"""Initialize admin panel manager.
|
| 22 |
|
| 23 |
Args:
|
|
|
|
| 25 |
"""
|
| 26 |
self.auth_service = auth_service
|
| 27 |
self._projects: dict[str, Project] = {} # project_slug -> Project
|
| 28 |
+
self.invite_notifier = invite_notifier or NoopInviteEmailNotifier()
|
| 29 |
+
self.invite_login_url = (invite_login_url or "").strip()
|
| 30 |
+
|
| 31 |
+
def _can_admin_project(self, actor_username: str, project_slug: str) -> bool:
|
| 32 |
+
return self.auth_service.get_user_role_for_project(actor_username, project_slug) == Role.admin
|
| 33 |
|
| 34 |
def register_project(self, project: Project) -> bool:
|
| 35 |
"""Register a new project (idempotent).
|
|
|
|
| 59 |
"dataset_repo_id": p.dataset_repo_id,
|
| 60 |
"visibility": p.visibility,
|
| 61 |
"owner_username": p.owner_username,
|
| 62 |
+
"dataset_token": p.dataset_token,
|
| 63 |
"dataset_token_set": bool((p.dataset_token or "").strip()),
|
| 64 |
"active": p.active,
|
| 65 |
}
|
|
|
|
| 95 |
return result
|
| 96 |
|
| 97 |
def assign_user_to_project(
|
| 98 |
+
self, actor_username: str, username: str, project_slug: str, role: str
|
| 99 |
) -> Tuple[bool, str]:
|
| 100 |
"""Assign a user to a project with a role.
|
| 101 |
|
|
|
|
| 110 |
if project_slug not in self._projects:
|
| 111 |
return False, f"Project '{project_slug}' not found"
|
| 112 |
|
| 113 |
+
if not self._can_admin_project(actor_username, project_slug):
|
| 114 |
+
return False, "Access denied: admin role required for this project"
|
| 115 |
+
|
| 116 |
if role not in ["admin", "validator"]:
|
| 117 |
return False, f"Invalid role: {role}"
|
| 118 |
|
| 119 |
project = self._projects[project_slug]
|
| 120 |
+
owner = (project.owner_username or "").strip()
|
| 121 |
+
if project.visibility == "private":
|
| 122 |
+
if not owner:
|
| 123 |
+
return False, "Private project is misconfigured: owner is required"
|
| 124 |
+
if username != owner:
|
| 125 |
+
return False, "Private projects only allow the owner"
|
| 126 |
|
| 127 |
self.auth_service.upsert_user_project_role(username, project_slug, Role(role))
|
| 128 |
|
|
|
|
| 130 |
|
| 131 |
def invite_user_to_project(
|
| 132 |
self,
|
| 133 |
+
actor_username: str,
|
| 134 |
invited_by: str,
|
| 135 |
username: str,
|
| 136 |
+
invitee_email: str,
|
| 137 |
project_slug: str,
|
| 138 |
role: str,
|
| 139 |
) -> Tuple[bool, str]:
|
| 140 |
if project_slug not in self._projects:
|
| 141 |
return False, f"Project '{project_slug}' not found"
|
| 142 |
|
| 143 |
+
if not self._can_admin_project(actor_username, project_slug):
|
| 144 |
+
return False, "Access denied: admin role required for this project"
|
| 145 |
+
|
| 146 |
if role not in ["admin", "validator"]:
|
| 147 |
return False, f"Invalid role: {role}"
|
| 148 |
|
|
|
|
| 150 |
if project.visibility == "private":
|
| 151 |
return False, "Private projects do not accept collaborators"
|
| 152 |
|
| 153 |
+
resolved_email = (invitee_email or "").strip() or (self.auth_service.get_known_email_for_user(username) or "").strip()
|
| 154 |
+
if not resolved_email:
|
| 155 |
+
return False, "Invitee email is required (username-only lookup not available yet)."
|
| 156 |
+
|
| 157 |
+
ok, message = self.auth_service.create_project_invite(
|
| 158 |
username=username,
|
| 159 |
project_slug=project_slug,
|
| 160 |
role=Role(role),
|
| 161 |
invited_by=invited_by,
|
| 162 |
)
|
| 163 |
+
if not ok:
|
| 164 |
+
return ok, message
|
| 165 |
+
|
| 166 |
+
invite = next((item for item in self.auth_service.list_pending_invites(username) if item.project_slug == project_slug), None)
|
| 167 |
+
if invite is None:
|
| 168 |
+
return True, message
|
| 169 |
+
|
| 170 |
+
email_ok, email_status = self.invite_notifier.send(
|
| 171 |
+
InviteEmailPayload(
|
| 172 |
+
invitee_username=username,
|
| 173 |
+
invitee_email=resolved_email,
|
| 174 |
+
project_slug=project_slug,
|
| 175 |
+
role=role,
|
| 176 |
+
invited_by=invited_by,
|
| 177 |
+
expires_at=invite.expires_at,
|
| 178 |
+
login_url=self.invite_login_url,
|
| 179 |
+
)
|
| 180 |
+
)
|
| 181 |
+
if email_ok:
|
| 182 |
+
return True, f"{message} | {email_status}"
|
| 183 |
+
return True, f"{message} | ⚠️ {email_status}"
|
| 184 |
|
| 185 |
def list_pending_invites(self, project_slug: str | None = None) -> List[dict]:
|
| 186 |
invites = self.auth_service.list_all_pending_invites()
|
|
|
|
| 202 |
def revoke_invite(self, username: str, project_slug: str) -> Tuple[bool, str]:
|
| 203 |
return self.auth_service.revoke_project_invite(username=username, project_slug=project_slug)
|
| 204 |
|
| 205 |
+
def delete_project(self, actor_username: str, project_slug: str) -> Tuple[bool, str]:
|
| 206 |
"""Delete a project and remove all linked assignments/invites."""
|
| 207 |
slug = (project_slug or "").strip()
|
| 208 |
if not slug:
|
|
|
|
| 210 |
if slug not in self._projects:
|
| 211 |
return False, f"Project '{slug}' not found"
|
| 212 |
|
| 213 |
+
if not self._can_admin_project(actor_username, slug):
|
| 214 |
+
return False, "Access denied: admin role required for this project"
|
| 215 |
+
|
| 216 |
+
project = self._projects[slug]
|
| 217 |
+
if project.visibility == "private":
|
| 218 |
+
owner = (project.owner_username or "").strip()
|
| 219 |
+
if not owner:
|
| 220 |
+
return False, "Private project is misconfigured: owner is required"
|
| 221 |
+
if actor_username != owner:
|
| 222 |
+
return False, "Only the private project owner can delete this project"
|
| 223 |
+
|
| 224 |
del self._projects[slug]
|
| 225 |
removed_assignments = self.auth_service.remove_project_from_all_users(slug)
|
| 226 |
revoked_invites = self.auth_service.revoke_all_invites_for_project(slug)
|
|
|
|
| 229 |
f"✅ Project '{slug}' deleted (removed assignments: {removed_assignments}, revoked invites: {revoked_invites})",
|
| 230 |
)
|
| 231 |
|
| 232 |
+
def remove_user_from_project(self, actor_username: str, username: str, project_slug: str) -> Tuple[bool, str]:
|
| 233 |
"""Remove a user's access to a project.
|
| 234 |
|
| 235 |
Args:
|
|
|
|
| 242 |
if username not in self.auth_service.list_usernames(include_inactive=True):
|
| 243 |
return False, f"User '{username}' not found"
|
| 244 |
|
| 245 |
+
if not self._can_admin_project(actor_username, project_slug):
|
| 246 |
+
return False, "Access denied: admin role required for this project"
|
| 247 |
+
|
| 248 |
+
project = self._projects.get(project_slug)
|
| 249 |
+
if project is None:
|
| 250 |
+
return False, f"Project '{project_slug}' not found"
|
| 251 |
+
if project.visibility == "private":
|
| 252 |
+
owner = (project.owner_username or "").strip()
|
| 253 |
+
if not owner:
|
| 254 |
+
return False, "Private project is misconfigured: owner is required"
|
| 255 |
+
if username != owner:
|
| 256 |
+
return False, "Private projects only allow the owner"
|
| 257 |
+
|
| 258 |
role = self.auth_service.get_user_role_for_project(username, project_slug)
|
| 259 |
if role is None:
|
| 260 |
return False, f"User '{username}' is not assigned to project '{project_slug}'"
|
|
|
|
| 368 |
remove_button = gr.Button("Remove User", variant="stop")
|
| 369 |
|
| 370 |
def assign_user(username: str, project_slug: str, role: str) -> str:
|
| 371 |
+
success, msg = admin_manager.assign_user_to_project(
|
| 372 |
+
current_session.username,
|
| 373 |
+
username,
|
| 374 |
+
project_slug,
|
| 375 |
+
role,
|
| 376 |
+
)
|
| 377 |
return msg
|
| 378 |
|
| 379 |
def remove_user(username: str, project_slug: str) -> str:
|
| 380 |
+
success, msg = admin_manager.remove_user_from_project(
|
| 381 |
+
current_session.username,
|
| 382 |
+
username,
|
| 383 |
+
project_slug,
|
| 384 |
+
)
|
| 385 |
return msg
|
| 386 |
|
| 387 |
assign_button.click(
|
src/ui/app_factory.py
CHANGED
|
@@ -2,6 +2,7 @@ import gradio as gr
|
|
| 2 |
import csv
|
| 3 |
import hashlib
|
| 4 |
import json
|
|
|
|
| 5 |
import re
|
| 6 |
import tempfile
|
| 7 |
import wave
|
|
@@ -21,6 +22,7 @@ from src.repositories.in_memory_detection_repository import InMemoryDetectionRep
|
|
| 21 |
from src.services.audio_fetch_service import AudioFetchService
|
| 22 |
from src.services.detection_queue_service import DetectionQueueService
|
| 23 |
from src.services.validation_service import ValidationService
|
|
|
|
| 24 |
from src.auth.auth_service import AuthService
|
| 25 |
from src.ui.login_page import create_login_page
|
| 26 |
from src.ui.admin_panel import AdminPanelManager
|
|
@@ -803,13 +805,20 @@ def _load_pending_invites_from_file(invites_file_path: str | None) -> dict[str,
|
|
| 803 |
|
| 804 |
|
| 805 |
def _resolve_bootstrap_file_paths(runtime_config: RuntimeConfig) -> tuple[Path, Path, Path]:
|
| 806 |
-
bootstrap_dir = Path(runtime_config.
|
| 807 |
projects_path = Path(runtime_config.projects_file_path) if runtime_config.projects_file_path else (bootstrap_dir / "projects.json")
|
| 808 |
user_access_path = Path(runtime_config.user_access_file_path) if runtime_config.user_access_file_path else (bootstrap_dir / "user_access.json")
|
| 809 |
invites_path = Path(runtime_config.invites_file_path) if runtime_config.invites_file_path else (bootstrap_dir / "invites.json")
|
| 810 |
return projects_path, user_access_path, invites_path
|
| 811 |
|
| 812 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 813 |
def _persist_bootstrap_state(
|
| 814 |
projects_path: Path,
|
| 815 |
user_access_path: Path,
|
|
@@ -817,10 +826,6 @@ def _persist_bootstrap_state(
|
|
| 817 |
admin_manager: AdminPanelManager,
|
| 818 |
auth_service: AuthService,
|
| 819 |
) -> None:
|
| 820 |
-
projects_path.parent.mkdir(parents=True, exist_ok=True)
|
| 821 |
-
user_access_path.parent.mkdir(parents=True, exist_ok=True)
|
| 822 |
-
invites_path.parent.mkdir(parents=True, exist_ok=True)
|
| 823 |
-
|
| 824 |
project_rows = admin_manager.list_projects()
|
| 825 |
projects_payload = [
|
| 826 |
{
|
|
@@ -834,13 +839,13 @@ def _persist_bootstrap_state(
|
|
| 834 |
}
|
| 835 |
for project in project_rows
|
| 836 |
]
|
| 837 |
-
|
| 838 |
|
| 839 |
access_payload = auth_service.export_user_access_map(include_inactive=True)
|
| 840 |
-
|
| 841 |
|
| 842 |
invites_payload = auth_service.export_pending_invites_map()
|
| 843 |
-
|
| 844 |
|
| 845 |
|
| 846 |
def _bootstrap_auth_and_projects(
|
|
@@ -861,7 +866,25 @@ def _bootstrap_auth_and_projects(
|
|
| 861 |
for username, access in user_access.items():
|
| 862 |
auth_service.register_user_project_access(username, access)
|
| 863 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 864 |
auth_service.load_pending_invites_map(pending_invites)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
|
| 866 |
emergency_admin_message = ""
|
| 867 |
has_admin = any(
|
|
@@ -2444,8 +2467,27 @@ def create_app() -> gr.Blocks:
|
|
| 2444 |
invite_ttl_hours=runtime_config.invite_ttl_hours,
|
| 2445 |
)
|
| 2446 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2447 |
# Initialize admin panel manager
|
| 2448 |
-
admin_manager = AdminPanelManager(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2449 |
|
| 2450 |
projects_file_path, user_access_file_path, invites_file_path = _resolve_bootstrap_file_paths(runtime_config)
|
| 2451 |
bootstrap_warning = _bootstrap_auth_and_projects(
|
|
@@ -2806,6 +2848,10 @@ def create_app() -> gr.Blocks:
|
|
| 2806 |
admin_username = gr.Textbox(
|
| 2807 |
label="Username", placeholder="validator_001"
|
| 2808 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2809 |
admin_project = gr.Dropdown(
|
| 2810 |
choices=_project_slugs(),
|
| 2811 |
label="Project",
|
|
@@ -2821,46 +2867,51 @@ def create_app() -> gr.Blocks:
|
|
| 2821 |
|
| 2822 |
def assign_user(session, username: str, project: str, role: str):
|
| 2823 |
if session is None:
|
| 2824 |
-
return "❌ Access denied. Login required.", gr.update(), gr.update(), gr.update()
|
| 2825 |
if not _is_admin_for_project(session, project):
|
| 2826 |
-
return "❌ Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update()
|
| 2827 |
success, msg = admin_manager.assign_user_to_project(
|
| 2828 |
-
username,
|
|
|
|
|
|
|
|
|
|
| 2829 |
)
|
| 2830 |
if success:
|
| 2831 |
persisted, persist_error = _persist_admin_state()
|
| 2832 |
final_message = msg if persisted else f"{msg} | ⚠️ Persistence failed: {persist_error}"
|
| 2833 |
-
return final_message, gr.update(value=""), gr.update(value=None), gr.update(value="validator")
|
| 2834 |
-
return msg, gr.update(), gr.update(), gr.update()
|
| 2835 |
|
| 2836 |
assign_btn = gr.Button("✅ Assign", variant="primary")
|
| 2837 |
assign_btn.click(
|
| 2838 |
fn=assign_user,
|
| 2839 |
inputs=[session_state, admin_username, admin_project, admin_role],
|
| 2840 |
-
outputs=[admin_message, admin_username, admin_project, admin_role],
|
| 2841 |
)
|
| 2842 |
|
| 2843 |
-
def invite_user(session, username: str, project: str, role: str):
|
| 2844 |
if session is None:
|
| 2845 |
-
return "❌ Access denied. Login required.", gr.update(), gr.update(), gr.update()
|
| 2846 |
if not _is_admin_for_project(session, project):
|
| 2847 |
-
return "❌ Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update()
|
| 2848 |
success, msg = admin_manager.invite_user_to_project(
|
|
|
|
| 2849 |
invited_by=session.username,
|
| 2850 |
username=username,
|
|
|
|
| 2851 |
project_slug=project,
|
| 2852 |
role=role,
|
| 2853 |
)
|
| 2854 |
if success:
|
| 2855 |
persisted, persist_error = _persist_admin_state()
|
| 2856 |
final_message = msg if persisted else f"{msg} | ⚠️ Persistence failed: {persist_error}"
|
| 2857 |
-
return final_message, gr.update(value=""), gr.update(value=None), gr.update(value="validator")
|
| 2858 |
-
return msg, gr.update(), gr.update(), gr.update()
|
| 2859 |
|
| 2860 |
invite_btn.click(
|
| 2861 |
fn=invite_user,
|
| 2862 |
-
inputs=[session_state, admin_username, admin_project, admin_role],
|
| 2863 |
-
outputs=[admin_message, admin_username, admin_project, admin_role],
|
| 2864 |
)
|
| 2865 |
|
| 2866 |
gr.Markdown("<div style='height:8px;'></div>")
|
|
@@ -2879,7 +2930,7 @@ def create_app() -> gr.Blocks:
|
|
| 2879 |
if not _is_admin_for_project(session, project_slug):
|
| 2880 |
return "❌ Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update()
|
| 2881 |
|
| 2882 |
-
success, msg = admin_manager.delete_project(project_slug)
|
| 2883 |
if not success:
|
| 2884 |
return msg, _project_rows(), gr.update(choices=_project_slugs()), gr.update(choices=_project_slugs()), session, gr.update(), gr.update()
|
| 2885 |
|
|
@@ -3477,15 +3528,21 @@ def create_app() -> gr.Blocks:
|
|
| 3477 |
def _session_hf_token(session) -> str | None:
|
| 3478 |
if session is None:
|
| 3479 |
return None
|
| 3480 |
-
return
|
| 3481 |
|
| 3482 |
def _project_fetch_token(project_slug: str, session) -> str | None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3483 |
project = admin_manager.get_project(project_slug) if project_slug else None
|
| 3484 |
-
if project is not None:
|
|
|
|
|
|
|
| 3485 |
project_token = (project.dataset_token or "").strip()
|
| 3486 |
if project_token:
|
| 3487 |
return project_token
|
| 3488 |
-
return
|
| 3489 |
|
| 3490 |
def refresh(
|
| 3491 |
project_slug: str,
|
|
|
|
| 2 |
import csv
|
| 3 |
import hashlib
|
| 4 |
import json
|
| 5 |
+
import os
|
| 6 |
import re
|
| 7 |
import tempfile
|
| 8 |
import wave
|
|
|
|
| 22 |
from src.services.audio_fetch_service import AudioFetchService
|
| 23 |
from src.services.detection_queue_service import DetectionQueueService
|
| 24 |
from src.services.validation_service import ValidationService
|
| 25 |
+
from src.services.invite_email_notifier import NoopInviteEmailNotifier, SmtpInviteEmailNotifier
|
| 26 |
from src.auth.auth_service import AuthService
|
| 27 |
from src.ui.login_page import create_login_page
|
| 28 |
from src.ui.admin_panel import AdminPanelManager
|
|
|
|
| 805 |
|
| 806 |
|
| 807 |
def _resolve_bootstrap_file_paths(runtime_config: RuntimeConfig) -> tuple[Path, Path, Path]:
|
| 808 |
+
bootstrap_dir = Path(runtime_config.bootstrap_base_dir)
|
| 809 |
projects_path = Path(runtime_config.projects_file_path) if runtime_config.projects_file_path else (bootstrap_dir / "projects.json")
|
| 810 |
user_access_path = Path(runtime_config.user_access_file_path) if runtime_config.user_access_file_path else (bootstrap_dir / "user_access.json")
|
| 811 |
invites_path = Path(runtime_config.invites_file_path) if runtime_config.invites_file_path else (bootstrap_dir / "invites.json")
|
| 812 |
return projects_path, user_access_path, invites_path
|
| 813 |
|
| 814 |
|
| 815 |
+
def _atomic_write_json(path: Path, payload: object) -> None:
|
| 816 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 817 |
+
tmp_path = path.parent / f".{path.name}.tmp.{os.getpid()}"
|
| 818 |
+
tmp_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
| 819 |
+
os.replace(tmp_path, path)
|
| 820 |
+
|
| 821 |
+
|
| 822 |
def _persist_bootstrap_state(
|
| 823 |
projects_path: Path,
|
| 824 |
user_access_path: Path,
|
|
|
|
| 826 |
admin_manager: AdminPanelManager,
|
| 827 |
auth_service: AuthService,
|
| 828 |
) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 829 |
project_rows = admin_manager.list_projects()
|
| 830 |
projects_payload = [
|
| 831 |
{
|
|
|
|
| 839 |
}
|
| 840 |
for project in project_rows
|
| 841 |
]
|
| 842 |
+
_atomic_write_json(projects_path, projects_payload)
|
| 843 |
|
| 844 |
access_payload = auth_service.export_user_access_map(include_inactive=True)
|
| 845 |
+
_atomic_write_json(user_access_path, access_payload)
|
| 846 |
|
| 847 |
invites_payload = auth_service.export_pending_invites_map()
|
| 848 |
+
_atomic_write_json(invites_path, invites_payload)
|
| 849 |
|
| 850 |
|
| 851 |
def _bootstrap_auth_and_projects(
|
|
|
|
| 866 |
for username, access in user_access.items():
|
| 867 |
auth_service.register_user_project_access(username, access)
|
| 868 |
|
| 869 |
+
# Enforce private-project owner-only ACL even if bootstrap files are malformed.
|
| 870 |
+
for username in auth_service.list_usernames(include_inactive=True):
|
| 871 |
+
for project_slug in list(auth_service.list_user_projects(username)):
|
| 872 |
+
project = admin_manager.get_project(project_slug)
|
| 873 |
+
if project is None:
|
| 874 |
+
continue
|
| 875 |
+
if project.visibility != "private":
|
| 876 |
+
continue
|
| 877 |
+
owner = (project.owner_username or "").strip()
|
| 878 |
+
if not owner or username != owner:
|
| 879 |
+
auth_service.remove_user_project_role(username, project_slug)
|
| 880 |
+
|
| 881 |
auth_service.load_pending_invites_map(pending_invites)
|
| 882 |
+
for invite in auth_service.list_all_pending_invites():
|
| 883 |
+
project = admin_manager.get_project(invite.project_slug)
|
| 884 |
+
if project is None:
|
| 885 |
+
continue
|
| 886 |
+
if project.visibility == "private":
|
| 887 |
+
auth_service.revoke_project_invite(invite.username, invite.project_slug)
|
| 888 |
|
| 889 |
emergency_admin_message = ""
|
| 890 |
has_admin = any(
|
|
|
|
| 2467 |
invite_ttl_hours=runtime_config.invite_ttl_hours,
|
| 2468 |
)
|
| 2469 |
|
| 2470 |
+
invite_notifier = NoopInviteEmailNotifier()
|
| 2471 |
+
if (
|
| 2472 |
+
runtime_config.invite_email_enabled
|
| 2473 |
+
and runtime_config.invite_email_sender
|
| 2474 |
+
and runtime_config.smtp_host
|
| 2475 |
+
):
|
| 2476 |
+
invite_notifier = SmtpInviteEmailNotifier(
|
| 2477 |
+
sender_email=runtime_config.invite_email_sender,
|
| 2478 |
+
smtp_host=runtime_config.smtp_host,
|
| 2479 |
+
smtp_port=runtime_config.smtp_port,
|
| 2480 |
+
smtp_username=runtime_config.smtp_username,
|
| 2481 |
+
smtp_password=runtime_config.smtp_password,
|
| 2482 |
+
smtp_use_tls=runtime_config.smtp_use_tls,
|
| 2483 |
+
)
|
| 2484 |
+
|
| 2485 |
# Initialize admin panel manager
|
| 2486 |
+
admin_manager = AdminPanelManager(
|
| 2487 |
+
auth_service,
|
| 2488 |
+
invite_notifier=invite_notifier,
|
| 2489 |
+
invite_login_url=runtime_config.invite_email_login_url,
|
| 2490 |
+
)
|
| 2491 |
|
| 2492 |
projects_file_path, user_access_file_path, invites_file_path = _resolve_bootstrap_file_paths(runtime_config)
|
| 2493 |
bootstrap_warning = _bootstrap_auth_and_projects(
|
|
|
|
| 2848 |
admin_username = gr.Textbox(
|
| 2849 |
label="Username", placeholder="validator_001"
|
| 2850 |
)
|
| 2851 |
+
admin_invite_email = gr.Textbox(
|
| 2852 |
+
label="Invite email",
|
| 2853 |
+
placeholder="validator@example.org",
|
| 2854 |
+
)
|
| 2855 |
admin_project = gr.Dropdown(
|
| 2856 |
choices=_project_slugs(),
|
| 2857 |
label="Project",
|
|
|
|
| 2867 |
|
| 2868 |
def assign_user(session, username: str, project: str, role: str):
|
| 2869 |
if session is None:
|
| 2870 |
+
return "❌ Access denied. Login required.", gr.update(), gr.update(), gr.update(), gr.update()
|
| 2871 |
if not _is_admin_for_project(session, project):
|
| 2872 |
+
return "❌ Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update(), gr.update()
|
| 2873 |
success, msg = admin_manager.assign_user_to_project(
|
| 2874 |
+
session.username,
|
| 2875 |
+
username,
|
| 2876 |
+
project,
|
| 2877 |
+
role,
|
| 2878 |
)
|
| 2879 |
if success:
|
| 2880 |
persisted, persist_error = _persist_admin_state()
|
| 2881 |
final_message = msg if persisted else f"{msg} | ⚠️ Persistence failed: {persist_error}"
|
| 2882 |
+
return final_message, gr.update(value=""), gr.update(value=""), gr.update(value=None), gr.update(value="validator")
|
| 2883 |
+
return msg, gr.update(), gr.update(), gr.update(), gr.update()
|
| 2884 |
|
| 2885 |
assign_btn = gr.Button("✅ Assign", variant="primary")
|
| 2886 |
assign_btn.click(
|
| 2887 |
fn=assign_user,
|
| 2888 |
inputs=[session_state, admin_username, admin_project, admin_role],
|
| 2889 |
+
outputs=[admin_message, admin_username, admin_invite_email, admin_project, admin_role],
|
| 2890 |
)
|
| 2891 |
|
| 2892 |
+
def invite_user(session, username: str, invite_email: str, project: str, role: str):
|
| 2893 |
if session is None:
|
| 2894 |
+
return "❌ Access denied. Login required.", gr.update(), gr.update(), gr.update(), gr.update()
|
| 2895 |
if not _is_admin_for_project(session, project):
|
| 2896 |
+
return "❌ Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update(), gr.update()
|
| 2897 |
success, msg = admin_manager.invite_user_to_project(
|
| 2898 |
+
actor_username=session.username,
|
| 2899 |
invited_by=session.username,
|
| 2900 |
username=username,
|
| 2901 |
+
invitee_email=invite_email,
|
| 2902 |
project_slug=project,
|
| 2903 |
role=role,
|
| 2904 |
)
|
| 2905 |
if success:
|
| 2906 |
persisted, persist_error = _persist_admin_state()
|
| 2907 |
final_message = msg if persisted else f"{msg} | ⚠️ Persistence failed: {persist_error}"
|
| 2908 |
+
return final_message, gr.update(value=""), gr.update(value=""), gr.update(value=None), gr.update(value="validator")
|
| 2909 |
+
return msg, gr.update(), gr.update(), gr.update(), gr.update()
|
| 2910 |
|
| 2911 |
invite_btn.click(
|
| 2912 |
fn=invite_user,
|
| 2913 |
+
inputs=[session_state, admin_username, admin_invite_email, admin_project, admin_role],
|
| 2914 |
+
outputs=[admin_message, admin_username, admin_invite_email, admin_project, admin_role],
|
| 2915 |
)
|
| 2916 |
|
| 2917 |
gr.Markdown("<div style='height:8px;'></div>")
|
|
|
|
| 2930 |
if not _is_admin_for_project(session, project_slug):
|
| 2931 |
return "❌ Access denied. You must be admin of the selected project.", gr.update(), gr.update(), gr.update(), session, gr.update(), gr.update()
|
| 2932 |
|
| 2933 |
+
success, msg = admin_manager.delete_project(session.username, project_slug)
|
| 2934 |
if not success:
|
| 2935 |
return msg, _project_rows(), gr.update(choices=_project_slugs()), gr.update(choices=_project_slugs()), session, gr.update(), gr.update()
|
| 2936 |
|
|
|
|
| 3528 |
def _session_hf_token(session) -> str | None:
|
| 3529 |
if session is None:
|
| 3530 |
return None
|
| 3531 |
+
return auth_service.get_hf_token_for_user(session.username)
|
| 3532 |
|
| 3533 |
def _project_fetch_token(project_slug: str, session) -> str | None:
|
| 3534 |
+
session_token = _session_hf_token(session)
|
| 3535 |
+
if session_token:
|
| 3536 |
+
return session_token
|
| 3537 |
+
|
| 3538 |
project = admin_manager.get_project(project_slug) if project_slug else None
|
| 3539 |
+
if project is not None and project.visibility == "private":
|
| 3540 |
+
if session is None or session.username != (project.owner_username or "").strip():
|
| 3541 |
+
return None
|
| 3542 |
project_token = (project.dataset_token or "").strip()
|
| 3543 |
if project_token:
|
| 3544 |
return project_token
|
| 3545 |
+
return None
|
| 3546 |
|
| 3547 |
def refresh(
|
| 3548 |
project_slug: str,
|
tests/unit/test_admin_panel_manager.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from datetime import UTC, datetime
|
| 3 |
+
|
| 4 |
+
from src.auth.auth_service import AuthService
|
| 5 |
+
from src.domain.models import Project, Role
|
| 6 |
+
from src.services.invite_email_notifier import InviteEmailNotifier, InviteEmailPayload
|
| 7 |
+
from src.ui.admin_panel import AdminPanelManager
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass
|
| 11 |
+
class _FakeNotifier(InviteEmailNotifier):
|
| 12 |
+
calls: int = 0
|
| 13 |
+
|
| 14 |
+
def send(self, payload: InviteEmailPayload) -> tuple[bool, str]:
|
| 15 |
+
self.calls += 1
|
| 16 |
+
assert payload.invitee_email
|
| 17 |
+
assert payload.project_slug
|
| 18 |
+
return True, "email-ok"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _make_project(slug: str, visibility: str, owner: str | None) -> Project:
|
| 22 |
+
return Project(
|
| 23 |
+
project_slug=slug,
|
| 24 |
+
name=slug,
|
| 25 |
+
dataset_repo_id=f"org/{slug}",
|
| 26 |
+
visibility=visibility,
|
| 27 |
+
owner_username=owner,
|
| 28 |
+
active=True,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_private_project_allows_only_owner_assignment() -> None:
|
| 33 |
+
auth = AuthService()
|
| 34 |
+
auth.register_user_project_access("owner", {"private-proj": Role.admin})
|
| 35 |
+
auth.register_user_project_access("intruder", {})
|
| 36 |
+
manager = AdminPanelManager(auth)
|
| 37 |
+
manager.register_project(_make_project("private-proj", "private", "owner"))
|
| 38 |
+
|
| 39 |
+
ok, message = manager.assign_user_to_project("owner", "intruder", "private-proj", "validator")
|
| 40 |
+
|
| 41 |
+
assert ok is False
|
| 42 |
+
assert "only allow the owner" in message
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_private_project_without_owner_is_rejected() -> None:
|
| 46 |
+
auth = AuthService()
|
| 47 |
+
auth.register_user_project_access("admin", {"broken-private": Role.admin})
|
| 48 |
+
manager = AdminPanelManager(auth)
|
| 49 |
+
manager.register_project(_make_project("broken-private", "private", None))
|
| 50 |
+
|
| 51 |
+
ok, message = manager.assign_user_to_project("admin", "admin", "broken-private", "admin")
|
| 52 |
+
|
| 53 |
+
assert ok is False
|
| 54 |
+
assert "owner is required" in message
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_invite_requires_project_admin_actor() -> None:
|
| 58 |
+
auth = AuthService()
|
| 59 |
+
auth.register_user_project_access("owner", {"collab-proj": Role.admin})
|
| 60 |
+
auth.register_user_project_access("viewer", {"collab-proj": Role.validator})
|
| 61 |
+
manager = AdminPanelManager(auth)
|
| 62 |
+
manager.register_project(_make_project("collab-proj", "collaborative", "owner"))
|
| 63 |
+
|
| 64 |
+
ok, message = manager.invite_user_to_project(
|
| 65 |
+
actor_username="viewer",
|
| 66 |
+
invited_by="viewer",
|
| 67 |
+
username="new_user",
|
| 68 |
+
invitee_email="new_user@example.org",
|
| 69 |
+
project_slug="collab-proj",
|
| 70 |
+
role="validator",
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
assert ok is False
|
| 74 |
+
assert "Access denied" in message
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_collaborative_invite_sends_email_when_address_present() -> None:
|
| 78 |
+
auth = AuthService()
|
| 79 |
+
auth.register_user_project_access("owner", {"collab-proj": Role.admin})
|
| 80 |
+
notifier = _FakeNotifier()
|
| 81 |
+
manager = AdminPanelManager(auth, invite_notifier=notifier)
|
| 82 |
+
manager.register_project(_make_project("collab-proj", "collaborative", "owner"))
|
| 83 |
+
|
| 84 |
+
ok, message = manager.invite_user_to_project(
|
| 85 |
+
actor_username="owner",
|
| 86 |
+
invited_by="owner",
|
| 87 |
+
username="new_user",
|
| 88 |
+
invitee_email="new_user@example.org",
|
| 89 |
+
project_slug="collab-proj",
|
| 90 |
+
role="validator",
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
assert ok is True
|
| 94 |
+
assert "Invite sent" in message
|
| 95 |
+
assert notifier.calls == 1
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_collaborative_invite_requires_email_if_unknown_username() -> None:
|
| 99 |
+
auth = AuthService()
|
| 100 |
+
auth.register_user_project_access("owner", {"collab-proj": Role.admin})
|
| 101 |
+
manager = AdminPanelManager(auth)
|
| 102 |
+
manager.register_project(_make_project("collab-proj", "collaborative", "owner"))
|
| 103 |
+
|
| 104 |
+
ok, message = manager.invite_user_to_project(
|
| 105 |
+
actor_username="owner",
|
| 106 |
+
invited_by="owner",
|
| 107 |
+
username="new_user",
|
| 108 |
+
invitee_email="",
|
| 109 |
+
project_slug="collab-proj",
|
| 110 |
+
role="validator",
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
assert ok is False
|
| 114 |
+
assert "email is required" in message.lower()
|
tests/unit/test_app_factory_audio_helpers.py
CHANGED
|
@@ -798,12 +798,21 @@ def test_bootstrap_auth_and_projects_uses_config_files_without_demo_fallback(tmp
|
|
| 798 |
runtime_config = RuntimeConfig(
|
| 799 |
detection_seed_path=None,
|
| 800 |
validation_base_dir=str(tmp_path / "validations"),
|
|
|
|
| 801 |
page_size=25,
|
| 802 |
projects_file_path=str(projects_file),
|
| 803 |
user_access_file_path=str(users_file),
|
| 804 |
invites_file_path=None,
|
| 805 |
invite_ttl_hours=72,
|
| 806 |
enable_demo_bootstrap=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 807 |
)
|
| 808 |
auth_service = AuthService()
|
| 809 |
admin_manager = AdminPanelManager(auth_service)
|
|
@@ -821,12 +830,21 @@ def test_bootstrap_auth_and_projects_warns_when_not_configured(tmp_path: Path) -
|
|
| 821 |
runtime_config = RuntimeConfig(
|
| 822 |
detection_seed_path=None,
|
| 823 |
validation_base_dir=str(tmp_path / "validations"),
|
|
|
|
| 824 |
page_size=25,
|
| 825 |
projects_file_path=None,
|
| 826 |
user_access_file_path=None,
|
| 827 |
invites_file_path=None,
|
| 828 |
invite_ttl_hours=72,
|
| 829 |
enable_demo_bootstrap=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 830 |
)
|
| 831 |
auth_service = AuthService()
|
| 832 |
admin_manager = AdminPanelManager(auth_service)
|
|
@@ -859,12 +877,21 @@ def test_bootstrap_auth_and_projects_recovers_emergency_admin_when_missing(tmp_p
|
|
| 859 |
runtime_config = RuntimeConfig(
|
| 860 |
detection_seed_path=None,
|
| 861 |
validation_base_dir=str(tmp_path / "validations"),
|
|
|
|
| 862 |
page_size=25,
|
| 863 |
projects_file_path=str(projects_file),
|
| 864 |
user_access_file_path=str(users_file),
|
| 865 |
invites_file_path=None,
|
| 866 |
invite_ttl_hours=72,
|
| 867 |
enable_demo_bootstrap=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 868 |
)
|
| 869 |
auth_service = AuthService()
|
| 870 |
admin_manager = AdminPanelManager(auth_service)
|
|
|
|
| 798 |
runtime_config = RuntimeConfig(
|
| 799 |
detection_seed_path=None,
|
| 800 |
validation_base_dir=str(tmp_path / "validations"),
|
| 801 |
+
bootstrap_base_dir=str(tmp_path / "bootstrap"),
|
| 802 |
page_size=25,
|
| 803 |
projects_file_path=str(projects_file),
|
| 804 |
user_access_file_path=str(users_file),
|
| 805 |
invites_file_path=None,
|
| 806 |
invite_ttl_hours=72,
|
| 807 |
enable_demo_bootstrap=False,
|
| 808 |
+
invite_email_enabled=False,
|
| 809 |
+
invite_email_sender="",
|
| 810 |
+
invite_email_login_url="",
|
| 811 |
+
smtp_host=None,
|
| 812 |
+
smtp_port=587,
|
| 813 |
+
smtp_username=None,
|
| 814 |
+
smtp_password=None,
|
| 815 |
+
smtp_use_tls=True,
|
| 816 |
)
|
| 817 |
auth_service = AuthService()
|
| 818 |
admin_manager = AdminPanelManager(auth_service)
|
|
|
|
| 830 |
runtime_config = RuntimeConfig(
|
| 831 |
detection_seed_path=None,
|
| 832 |
validation_base_dir=str(tmp_path / "validations"),
|
| 833 |
+
bootstrap_base_dir=str(tmp_path / "bootstrap"),
|
| 834 |
page_size=25,
|
| 835 |
projects_file_path=None,
|
| 836 |
user_access_file_path=None,
|
| 837 |
invites_file_path=None,
|
| 838 |
invite_ttl_hours=72,
|
| 839 |
enable_demo_bootstrap=False,
|
| 840 |
+
invite_email_enabled=False,
|
| 841 |
+
invite_email_sender="",
|
| 842 |
+
invite_email_login_url="",
|
| 843 |
+
smtp_host=None,
|
| 844 |
+
smtp_port=587,
|
| 845 |
+
smtp_username=None,
|
| 846 |
+
smtp_password=None,
|
| 847 |
+
smtp_use_tls=True,
|
| 848 |
)
|
| 849 |
auth_service = AuthService()
|
| 850 |
admin_manager = AdminPanelManager(auth_service)
|
|
|
|
| 877 |
runtime_config = RuntimeConfig(
|
| 878 |
detection_seed_path=None,
|
| 879 |
validation_base_dir=str(tmp_path / "validations"),
|
| 880 |
+
bootstrap_base_dir=str(tmp_path / "bootstrap"),
|
| 881 |
page_size=25,
|
| 882 |
projects_file_path=str(projects_file),
|
| 883 |
user_access_file_path=str(users_file),
|
| 884 |
invites_file_path=None,
|
| 885 |
invite_ttl_hours=72,
|
| 886 |
enable_demo_bootstrap=False,
|
| 887 |
+
invite_email_enabled=False,
|
| 888 |
+
invite_email_sender="",
|
| 889 |
+
invite_email_login_url="",
|
| 890 |
+
smtp_host=None,
|
| 891 |
+
smtp_port=587,
|
| 892 |
+
smtp_username=None,
|
| 893 |
+
smtp_password=None,
|
| 894 |
+
smtp_use_tls=True,
|
| 895 |
)
|
| 896 |
auth_service = AuthService()
|
| 897 |
admin_manager = AdminPanelManager(auth_service)
|
tests/unit/test_auth_service.py
CHANGED
|
@@ -189,6 +189,31 @@ class TestAuthService:
|
|
| 189 |
auth_service.set_user_active("inactive_user", False)
|
| 190 |
assert not auth_service.is_user_authorized_for_project("inactive_user", "kenya-2024")
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
def test_register_user_project_access_update(self, auth_service):
|
| 193 |
"""Test updating user's project access."""
|
| 194 |
auth_service.register_user_project_access(
|
|
@@ -225,6 +250,34 @@ class TestAuthService:
|
|
| 225 |
removed_again = auth_service.remove_user_project_role("temp_user", "project-1")
|
| 226 |
assert removed_again is False
|
| 227 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
def test_list_usernames_honors_active_filter(self, auth_service):
|
| 229 |
auth_service.register_user_project_access("active_user", {"project-1": Role.validator})
|
| 230 |
auth_service.register_user_project_access("inactive_user", {"project-1": Role.validator})
|
|
|
|
| 189 |
auth_service.set_user_active("inactive_user", False)
|
| 190 |
assert not auth_service.is_user_authorized_for_project("inactive_user", "kenya-2024")
|
| 191 |
|
| 192 |
+
def test_set_user_inactive_revokes_existing_sessions(self, auth_service):
|
| 193 |
+
auth_service.register_user_project_access("active_user", {"project-1": Role.validator})
|
| 194 |
+
session = auth_service.login("active_user")
|
| 195 |
+
assert session is not None
|
| 196 |
+
|
| 197 |
+
auth_service.set_user_active("active_user", False)
|
| 198 |
+
|
| 199 |
+
assert auth_service.get_session(session.session_id) is None
|
| 200 |
+
|
| 201 |
+
def test_login_with_hf_token_stores_user_token_and_email(self, monkeypatch):
|
| 202 |
+
class FakeApi:
|
| 203 |
+
def whoami(self, token: str):
|
| 204 |
+
assert token == "hf_test_token"
|
| 205 |
+
return {"name": "hf_user", "email": "hf_user@example.org"}
|
| 206 |
+
|
| 207 |
+
monkeypatch.setattr("src.auth.auth_service.HfApi", lambda: FakeApi())
|
| 208 |
+
|
| 209 |
+
service = AuthService()
|
| 210 |
+
session, message = service.login_with_hf_token("hf_test_token")
|
| 211 |
+
|
| 212 |
+
assert session is not None
|
| 213 |
+
assert "Welcome" in message
|
| 214 |
+
assert service.get_hf_token_for_user("hf_user") == "hf_test_token"
|
| 215 |
+
assert service.get_known_email_for_user("hf_user") == "hf_user@example.org"
|
| 216 |
+
|
| 217 |
def test_register_user_project_access_update(self, auth_service):
|
| 218 |
"""Test updating user's project access."""
|
| 219 |
auth_service.register_user_project_access(
|
|
|
|
| 250 |
removed_again = auth_service.remove_user_project_role("temp_user", "project-1")
|
| 251 |
assert removed_again is False
|
| 252 |
|
| 253 |
+
def test_remove_user_project_role_clears_matching_pending_invite(self, auth_service):
|
| 254 |
+
auth_service.register_user_project_access("temp_user", {"project-1": Role.validator})
|
| 255 |
+
ok, _ = auth_service.create_project_invite(
|
| 256 |
+
username="temp_user",
|
| 257 |
+
project_slug="project-1",
|
| 258 |
+
role=Role.validator,
|
| 259 |
+
invited_by="owner",
|
| 260 |
+
)
|
| 261 |
+
assert ok is True
|
| 262 |
+
|
| 263 |
+
removed = auth_service.remove_user_project_role("temp_user", "project-1")
|
| 264 |
+
assert removed is True
|
| 265 |
+
assert auth_service.list_pending_invites("temp_user") == []
|
| 266 |
+
|
| 267 |
+
def test_remove_user_project_role_refreshes_active_session(self, auth_service):
|
| 268 |
+
auth_service.register_user_project_access("temp_user", {"project-1": Role.validator, "project-2": Role.validator})
|
| 269 |
+
session = auth_service.login("temp_user")
|
| 270 |
+
assert session is not None
|
| 271 |
+
assert "project-1" in session.authorized_projects
|
| 272 |
+
|
| 273 |
+
removed = auth_service.remove_user_project_role("temp_user", "project-1")
|
| 274 |
+
assert removed is True
|
| 275 |
+
|
| 276 |
+
refreshed = auth_service.get_session(session.session_id)
|
| 277 |
+
assert refreshed is not None
|
| 278 |
+
assert "project-1" not in refreshed.authorized_projects
|
| 279 |
+
assert "project-2" in refreshed.authorized_projects
|
| 280 |
+
|
| 281 |
def test_list_usernames_honors_active_filter(self, auth_service):
|
| 282 |
auth_service.register_user_project_access("active_user", {"project-1": Role.validator})
|
| 283 |
auth_service.register_user_project_access("inactive_user", {"project-1": Role.validator})
|