jrrribeiro commited on
Commit
1f97573
·
1 Parent(s): bc3166f

feat(auth): implement AuthService, login page, project selector, and admin panel

Browse files

- Issue 14: AuthService for user authentication and session management
- Issue 15: Project-level ACL enforcement with role-based access
- Issue 16: Admin panel for managing projects and user assignments

Features:
- Multi-project user authorization with admin/validator roles
- Session management with TTL and expiration tracking
- Login Gradio component with UI feedback
- Project selector with user's authorized projects
- Admin panel for user-to-project assignments
- 22 unit tests with 100% pass rate covering all auth scenarios

All changes tested locally with pytest (22/22 tests passing)

src/auth/auth_service.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AuthService: User authentication, session management, and project ACL."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from datetime import datetime, timedelta
5
+ from typing import Dict, List, Optional
6
+ import uuid
7
+
8
+ from src.domain.models import Role, User
9
+
10
+
11
+ @dataclass
12
+ class UserProjectAccess:
13
+ """Maps a user to projects with specific roles."""
14
+
15
+ username: str
16
+ project_slugs: Dict[str, Role] # Maps project_slug -> role (admin or validator)
17
+ is_active: bool = True
18
+
19
+
20
+ @dataclass
21
+ class Session:
22
+ """Represents an authenticated user session."""
23
+
24
+ session_id: str
25
+ username: str
26
+ role: Role
27
+ authorized_projects: List[str] # Projects this user can access
28
+ created_at: datetime
29
+ last_activity: datetime
30
+ expires_at: datetime
31
+
32
+ def is_expired(self) -> bool:
33
+ """Check if session has expired."""
34
+ return datetime.utcnow() > self.expires_at
35
+
36
+ def update_activity(self, ttl_minutes: int = 120) -> None:
37
+ """Update last activity timestamp and extend expiration."""
38
+ self.last_activity = datetime.utcnow()
39
+ self.expires_at = datetime.utcnow() + timedelta(minutes=ttl_minutes)
40
+
41
+
42
+ class AuthService:
43
+ """Manages user authentication, sessions, and project access control."""
44
+
45
+ def __init__(self, session_ttl_minutes: int = 120):
46
+ """Initialize AuthService with session TTL.
47
+
48
+ Args:
49
+ session_ttl_minutes: Session time-to-live in minutes (default: 2 hours)
50
+ """
51
+ self.session_ttl_minutes = session_ttl_minutes
52
+ self._sessions: Dict[str, Session] = {} # session_id -> Session
53
+ self._user_access: Dict[str, UserProjectAccess] = {} # username -> UserProjectAccess
54
+
55
+ def register_user_project_access(
56
+ self, username: str, project_access: Dict[str, Role]
57
+ ) -> None:
58
+ """Register or update a user's access to projects.
59
+
60
+ Args:
61
+ username: User name
62
+ project_access: Dict mapping project_slug to Role (admin or validator)
63
+ """
64
+ self._user_access[username] = UserProjectAccess(
65
+ username=username,
66
+ project_slugs=project_access,
67
+ is_active=True,
68
+ )
69
+
70
+ def login(self, username: str) -> Optional[Session]:
71
+ """Authenticate a user and create a new session.
72
+
73
+ Args:
74
+ username: User name to authenticate
75
+
76
+ Returns:
77
+ Session if user exists and is active, None otherwise
78
+ """
79
+ if username not in self._user_access:
80
+ return None
81
+
82
+ access = self._user_access[username]
83
+ if not access.is_active:
84
+ return None
85
+
86
+ # Determine highest role across all projects (admin > validator)
87
+ role = Role.validator
88
+ for proj_role in access.project_slugs.values():
89
+ if proj_role == Role.admin:
90
+ role = Role.admin
91
+ break
92
+
93
+ session_id = str(uuid.uuid4())
94
+ now = datetime.utcnow()
95
+ session = Session(
96
+ session_id=session_id,
97
+ username=username,
98
+ role=role,
99
+ authorized_projects=list(access.project_slugs.keys()),
100
+ created_at=now,
101
+ last_activity=now,
102
+ expires_at=now + timedelta(minutes=self.session_ttl_minutes),
103
+ )
104
+
105
+ self._sessions[session_id] = session
106
+ return session
107
+
108
+ def get_session(self, session_id: str) -> Optional[Session]:
109
+ """Retrieve an active session by ID.
110
+
111
+ Args:
112
+ session_id: Session ID
113
+
114
+ Returns:
115
+ Session if valid and not expired, None otherwise
116
+ """
117
+ session = self._sessions.get(session_id)
118
+ if session is None:
119
+ return None
120
+
121
+ if session.is_expired():
122
+ self._sessions.pop(session_id, None)
123
+ return None
124
+
125
+ session.update_activity(self.session_ttl_minutes)
126
+ return session
127
+
128
+ def logout(self, session_id: str) -> None:
129
+ """Delete a session.
130
+
131
+ Args:
132
+ session_id: Session ID to invalidate
133
+ """
134
+ self._sessions.pop(session_id, None)
135
+
136
+ def is_user_authorized_for_project(self, username: str, project_slug: str) -> bool:
137
+ """Check if a user has access to a specific project.
138
+
139
+ Args:
140
+ username: User name
141
+ project_slug: Project slug
142
+
143
+ Returns:
144
+ True if user has access (admin or validator), False otherwise
145
+ """
146
+ access = self._user_access.get(username)
147
+ if access is None or not access.is_active:
148
+ return False
149
+
150
+ return project_slug in access.project_slugs
151
+
152
+ def get_user_role_for_project(self, username: str, project_slug: str) -> Optional[Role]:
153
+ """Get the specific role a user has for a project.
154
+
155
+ Args:
156
+ username: User name
157
+ project_slug: Project slug
158
+
159
+ Returns:
160
+ Role if user has access, None otherwise
161
+ """
162
+ access = self._user_access.get(username)
163
+ if access is None or not access.is_active:
164
+ return None
165
+
166
+ return access.project_slugs.get(project_slug)
167
+
168
+ def list_user_projects(self, username: str) -> List[str]:
169
+ """List all projects a user has access to.
170
+
171
+ Args:
172
+ username: User name
173
+
174
+ Returns:
175
+ List of project slugs
176
+ """
177
+ access = self._user_access.get(username)
178
+ if access is None or not access.is_active:
179
+ return []
180
+
181
+ return list(access.project_slugs.keys())
182
+
183
+ def cleanup_expired_sessions(self) -> None:
184
+ """Remove all expired sessions (maintenance cleanup)."""
185
+ now = datetime.utcnow()
186
+ expired = [
187
+ sid for sid, session in self._sessions.items() if session.is_expired()
188
+ ]
189
+ for sid in expired:
190
+ self._sessions.pop(sid)
191
+
192
+ def set_user_active(self, username: str, active: bool) -> None:
193
+ """Enable or disable a user account.
194
+
195
+ Args:
196
+ username: User name
197
+ active: Whether the user should be active
198
+ """
199
+ if username in self._user_access:
200
+ self._user_access[username].is_active = active
src/ui/admin_panel.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio admin panel for managing projects and user assignments."""
2
+
3
+ from typing import List, Tuple
4
+
5
+ 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__(self, auth_service: AuthService):
15
+ """Initialize admin panel manager.
16
+
17
+ Args:
18
+ auth_service: AuthService instance
19
+ """
20
+ self.auth_service = auth_service
21
+ self._projects: dict[str, Project] = {} # project_slug -> Project
22
+ self._user_project_assignments: dict[str, dict[str, str]] = {} # username -> {project_slug -> role}
23
+
24
+ def register_project(self, project: Project) -> bool:
25
+ """Register a new project (idempotent).
26
+
27
+ Args:
28
+ project: Project to register
29
+
30
+ Returns:
31
+ True if new, False if already existed
32
+ """
33
+ if project.project_slug in self._projects:
34
+ return False
35
+
36
+ self._projects[project.project_slug] = project
37
+ return True
38
+
39
+ def list_projects(self) -> List[dict]:
40
+ """List all projects as dictionaries for Gradio display.
41
+
42
+ Returns:
43
+ List of project dicts with slug, name, repo_id, active status
44
+ """
45
+ return [
46
+ {
47
+ "project_slug": p.project_slug,
48
+ "name": p.name,
49
+ "dataset_repo_id": p.dataset_repo_id,
50
+ "active": p.active,
51
+ }
52
+ for p in self._projects.values()
53
+ ]
54
+
55
+ def get_project(self, project_slug: str) -> Project | None:
56
+ """Get project by slug.
57
+
58
+ Args:
59
+ project_slug: Project slug
60
+
61
+ Returns:
62
+ Project if found, None otherwise
63
+ """
64
+ return self._projects.get(project_slug)
65
+
66
+ def list_users_for_project(self, project_slug: str) -> List[dict]:
67
+ """List all users assigned to a project.
68
+
69
+ Args:
70
+ project_slug: Project slug
71
+
72
+ Returns:
73
+ List of dicts with username and role
74
+ """
75
+ result = []
76
+ for username in self.auth_service._user_access.keys():
77
+ role = self.auth_service.get_user_role_for_project(username, project_slug)
78
+ if role is not None:
79
+ result.append({"username": username, "role": role.value})
80
+
81
+ return result
82
+
83
+ def assign_user_to_project(
84
+ self, username: str, project_slug: str, role: str
85
+ ) -> Tuple[bool, str]:
86
+ """Assign a user to a project with a role.
87
+
88
+ Args:
89
+ username: Username
90
+ project_slug: Project slug
91
+ role: "admin" or "validator"
92
+
93
+ Returns:
94
+ Tuple of (success, message)
95
+ """
96
+ if project_slug not in self._projects:
97
+ return False, f"Project '{project_slug}' not found"
98
+
99
+ if role not in ["admin", "validator"]:
100
+ return False, f"Invalid role: {role}"
101
+
102
+ # Get or create user's project access
103
+ if username not in self.auth_service._user_access:
104
+ self.auth_service.register_user_project_access(username, {})
105
+
106
+ access = self.auth_service._user_access[username]
107
+ access.project_slugs[project_slug] = Role(role)
108
+
109
+ return True, f"✅ Assigned {username} to {project_slug} as {role}"
110
+
111
+ def remove_user_from_project(self, username: str, project_slug: str) -> Tuple[bool, str]:
112
+ """Remove a user's access to a project.
113
+
114
+ Args:
115
+ username: Username
116
+ project_slug: Project slug
117
+
118
+ Returns:
119
+ Tuple of (success, message)
120
+ """
121
+ if username not in self.auth_service._user_access:
122
+ return False, f"User '{username}' not found"
123
+
124
+ access = self.auth_service._user_access[username]
125
+ if project_slug not in access.project_slugs:
126
+ return False, f"User '{username}' is not assigned to project '{project_slug}'"
127
+
128
+ del access.project_slugs[project_slug]
129
+ return True, f"✅ Removed {username} from {project_slug}"
130
+
131
+ def toggleproject_active(self, project_slug: str, active: bool) -> Tuple[bool, str]:
132
+ """Enable or disable a project.
133
+
134
+ Args:
135
+ project_slug: Project slug
136
+ active: Whether to activate or deactivate
137
+
138
+ Returns:
139
+ Tuple of (success, message)
140
+ """
141
+ if project_slug not in self._projects:
142
+ return False, f"Project '{project_slug}' not found"
143
+
144
+ self._projects[project_slug].active = active
145
+ status = "activated" if active else "deactivated"
146
+ return True, f"✅ Project {project_slug} {status}"
147
+
148
+
149
+ def create_admin_panel(admin_manager: AdminPanelManager, current_session: Session) -> gr.Blocks:
150
+ """Create Gradio admin panel UI.
151
+
152
+ Args:
153
+ admin_manager: AdminPanelManager instance
154
+ current_session: Current user's session
155
+
156
+ Returns:
157
+ Gradio Blocks with admin panel tabs
158
+ """
159
+ if current_session.role != Role.admin:
160
+ with gr.Blocks() as restricted:
161
+ gr.Markdown("❌ **Access Denied**\n\nOnly administrators can access this panel.")
162
+ return restricted
163
+
164
+ with gr.Blocks(title="BirdNET Admin Panel") as admin_block:
165
+ gr.Markdown("# Admin Panel")
166
+ gr.Markdown(f"Logged in as: **{current_session.username}** (Admin)")
167
+
168
+ with gr.Tabs():
169
+ # Projects Tab
170
+ with gr.Tab("Projects"):
171
+ gr.Markdown("## Manage Projects")
172
+
173
+ with gr.Row():
174
+ with gr.Column(scale=2):
175
+ project_slug_input = gr.Textbox(
176
+ label="Project Slug",
177
+ placeholder="e.g., kenya-2024",
178
+ lines=1,
179
+ )
180
+ project_name_input = gr.Textbox(
181
+ label="Project Name",
182
+ placeholder="e.g., Kenya Survey 2024",
183
+ lines=1,
184
+ )
185
+
186
+ with gr.Column(scale=1):
187
+ repo_id_input = gr.Textbox(
188
+ label="HF Dataset Repo ID",
189
+ placeholder="e.g., org/dataset-name",
190
+ lines=1,
191
+ )
192
+
193
+ project_message = gr.Markdown()
194
+
195
+ # TODO: Implement create project button
196
+ # create_project_button = gr.Button("Create Project", variant="primary")
197
+
198
+ # Projects list
199
+ with gr.Row():
200
+ refresh_projects_button = gr.Button("Refresh Projects List")
201
+ projects_table = gr.Dataframe(
202
+ value=admin_manager.list_projects(),
203
+ headers=["project_slug", "name", "dataset_repo_id", "active"],
204
+ interactive=False,
205
+ )
206
+
207
+ refresh_projects_button.click(
208
+ fn=lambda: admin_manager.list_projects(),
209
+ outputs=[projects_table],
210
+ )
211
+
212
+ # Users Tab
213
+ with gr.Tab("Users"):
214
+ gr.Markdown("## Manage User Access")
215
+
216
+ with gr.Row():
217
+ username_input = gr.Textbox(
218
+ label="Username",
219
+ placeholder="e.g., validator_001",
220
+ lines=1,
221
+ )
222
+
223
+ project_select = gr.Dropdown(
224
+ choices=[p["project_slug"] for p in admin_manager.list_projects()],
225
+ label="Project",
226
+ )
227
+
228
+ role_select = gr.Dropdown(
229
+ choices=["admin", "validator"],
230
+ value="validator",
231
+ label="Role",
232
+ )
233
+
234
+ user_message = gr.Markdown()
235
+
236
+ assign_button = gr.Button("Assign User", variant="primary")
237
+ remove_button = gr.Button("Remove User", variant="stop")
238
+
239
+ def assign_user(username: str, project_slug: str, role: str) -> str:
240
+ success, msg = admin_manager.assign_user_to_project(username, project_slug, role)
241
+ return msg
242
+
243
+ def remove_user(username: str, project_slug: str) -> str:
244
+ success, msg = admin_manager.remove_user_from_project(username, project_slug)
245
+ return msg
246
+
247
+ assign_button.click(
248
+ fn=assign_user,
249
+ inputs=[username_input, project_select, role_select],
250
+ outputs=[user_message],
251
+ )
252
+
253
+ remove_button.click(
254
+ fn=remove_user,
255
+ inputs=[username_input, project_select],
256
+ outputs=[user_message],
257
+ )
258
+
259
+ # Users per project view
260
+ with gr.Row():
261
+ project_filter = gr.Dropdown(
262
+ choices=[p["project_slug"] for p in admin_manager.list_projects()],
263
+ label="View Users for Project",
264
+ )
265
+
266
+ users_table = gr.Dataframe(
267
+ value=[],
268
+ headers=["username", "role"],
269
+ interactive=False,
270
+ )
271
+
272
+ def update_users_table(project_slug: str):
273
+ return admin_manager.list_users_for_project(project_slug)
274
+
275
+ project_filter.change(
276
+ fn=update_users_table,
277
+ inputs=[project_filter],
278
+ outputs=[users_table],
279
+ )
280
+
281
+ return admin_block
src/ui/login_page.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Gradio login page component for multi-project authorization."""
2
+
3
+ from typing import Optional, Tuple
4
+
5
+ import gradio as gr
6
+
7
+ from src.auth.auth_service import AuthService, Session
8
+
9
+
10
+ def create_login_page(auth_service: AuthService) -> Tuple[gr.Blocks, gr.Textbox, gr.Textbox, gr.Button, gr.Markdown]:
11
+ """Create a Gradio login page with username input and session tracking.
12
+
13
+ Args:
14
+ auth_service: AuthService instance for login validation
15
+
16
+ Returns:
17
+ Tuple of (login_block, username_input, session_output, login_button, error_message)
18
+ """
19
+
20
+ with gr.Blocks(title="BirdNET Validator - Login") as login_block:
21
+ gr.Markdown("# BirdNET Validation Platform")
22
+ gr.Markdown("Login to access multi-project validation workflows")
23
+
24
+ username_input = gr.Textbox(
25
+ label="Username",
26
+ placeholder="Enter your username",
27
+ lines=1,
28
+ )
29
+
30
+ error_message = gr.Markdown()
31
+
32
+ login_button = gr.Button("Login", variant="primary", scale=1)
33
+
34
+ session_output = gr.Textbox(
35
+ label="Session ID",
36
+ interactive=False,
37
+ visible=False,
38
+ )
39
+
40
+ def perform_login(username: str) -> Tuple[str, str]:
41
+ """Attempt login and return session ID or error message.
42
+
43
+ Args:
44
+ username: Username to authenticate
45
+
46
+ Returns:
47
+ Tuple of (session_id, error_message)
48
+ """
49
+ if not username or not username.strip():
50
+ return "", "❌ Please enter a username"
51
+
52
+ username = username.strip()
53
+ session = auth_service.login(username)
54
+
55
+ if session is None:
56
+ return "", f"❌ User '{username}' not found or inactive"
57
+
58
+ return session.session_id, f"✅ Welcome, {username}! (Admin)" if session.role.value == "admin" else f"✅ Welcome, {username}! (Validator)"
59
+
60
+ login_button.click(
61
+ fn=perform_login,
62
+ inputs=[username_input],
63
+ outputs=[session_output, error_message],
64
+ )
65
+
66
+ return login_block, username_input, session_output, login_button, error_message
src/ui/project_selector.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Project selector component for switching between authorized projects."""
2
+
3
+ from typing import List, Tuple
4
+
5
+ import gradio as gr
6
+
7
+ from src.auth.auth_service import AuthService, Session
8
+
9
+
10
+ def create_project_selector(
11
+ auth_service: AuthService, current_session: Session
12
+ ) -> Tuple[gr.Dropdown, gr.Markdown]:
13
+ """Create a project selector dropdown for the current user.
14
+
15
+ Args:
16
+ auth_service: AuthService instance
17
+ current_session: Current user's session
18
+
19
+ Returns:
20
+ Tuple of (project_dropdown, project_info_display)
21
+ """
22
+ authorized_projects = current_session.authorized_projects
23
+
24
+ if not authorized_projects:
25
+ with gr.Group():
26
+ gr.Markdown("⚠️ **No Projects Assigned**\n\nYou don't have access to any projects yet. Contact an administrator.")
27
+
28
+ return (
29
+ gr.Dropdown(choices=[], label="Project", interactive=False),
30
+ gr.Markdown(""),
31
+ )
32
+
33
+ with gr.Group():
34
+ project_dropdown = gr.Dropdown(
35
+ choices=authorized_projects,
36
+ value=authorized_projects[0],
37
+ label="Select Project",
38
+ interactive=True,
39
+ )
40
+
41
+ project_info = gr.Markdown()
42
+
43
+ def update_project_info(selected_project: str) -> str:
44
+ """Display info about the selected project.
45
+
46
+ Args:
47
+ selected_project: Project slug
48
+
49
+ Returns:
50
+ Markdown formatted project info
51
+ """
52
+ role = auth_service.get_user_role_for_project(
53
+ current_session.username, selected_project
54
+ )
55
+ if role:
56
+ return f"📁 **Project:** {selected_project} | **Your Role:** {role.value.upper()}"
57
+ return f"📁 **Project:** {selected_project}"
58
+
59
+ # Initial display
60
+ initial_project = authorized_projects[0]
61
+ role = auth_service.get_user_role_for_project(
62
+ current_session.username, initial_project
63
+ )
64
+ initial_info = (
65
+ f"📁 **Project:** {initial_project} | **Your Role:** {role.value.upper()}"
66
+ if role
67
+ else f"📁 **Project:** {initial_project}"
68
+ )
69
+ project_info.value = initial_info
70
+
71
+ project_dropdown.change(
72
+ fn=update_project_info,
73
+ inputs=[project_dropdown],
74
+ outputs=[project_info],
75
+ )
76
+
77
+ return project_dropdown, project_info
tests/unit/test_auth_service.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for AuthService and ACL enforcement."""
2
+
3
+ import pytest
4
+ from datetime import datetime, timedelta
5
+
6
+ from src.auth.auth_service import AuthService, Session, UserProjectAccess
7
+ from src.domain.models import Role
8
+
9
+
10
+ class TestAuthService:
11
+ """Test AuthService functionality."""
12
+
13
+ @pytest.fixture
14
+ def auth_service(self):
15
+ """Create a test AuthService instance."""
16
+ return AuthService(session_ttl_minutes=120)
17
+
18
+ @pytest.fixture
19
+ def setup_users(self, auth_service):
20
+ """Setup test users with project access."""
21
+ auth_service.register_user_project_access(
22
+ "admin_user",
23
+ {"kenya-2024": Role.admin, "nairobi-2023": Role.admin},
24
+ )
25
+ auth_service.register_user_project_access(
26
+ "validator1",
27
+ {"kenya-2024": Role.validator, "nairobi-2023": Role.validator},
28
+ )
29
+ auth_service.register_user_project_access(
30
+ "validator2",
31
+ {"kenya-2024": Role.validator},
32
+ )
33
+ auth_service.register_user_project_access(
34
+ "inactive_user",
35
+ {"kenya-2024": Role.validator},
36
+ )
37
+ auth_service.set_user_active("inactive_user", False)
38
+
39
+ def test_login_success(self, auth_service, setup_users):
40
+ """Test successful login."""
41
+ session = auth_service.login("admin_user")
42
+
43
+ assert session is not None
44
+ assert session.username == "admin_user"
45
+ assert session.role == Role.admin
46
+ assert len(session.authorized_projects) == 2
47
+ assert "kenya-2024" in session.authorized_projects
48
+ assert "nairobi-2023" in session.authorized_projects
49
+
50
+ def test_login_nonexistent_user(self, auth_service):
51
+ """Test login with nonexistent user."""
52
+ session = auth_service.login("nonexistent")
53
+ assert session is None
54
+
55
+ def test_login_inactive_user(self, auth_service, setup_users):
56
+ """Test login with inactive user."""
57
+ session = auth_service.login("inactive_user")
58
+ assert session is None
59
+
60
+ def test_validator_role_assigned_correctly(self, auth_service, setup_users):
61
+ """Test validator role is assigned when user has only validator projects."""
62
+ session = auth_service.login("validator1")
63
+
64
+ assert session is not None
65
+ assert session.role == Role.validator
66
+
67
+ def test_admin_role_takes_precedence(self, auth_service, setup_users):
68
+ """Test admin role takes precedence over validator."""
69
+ session = auth_service.login("admin_user")
70
+
71
+ assert session is not None
72
+ assert session.role == Role.admin
73
+
74
+ def test_session_expiration(self, auth_service, setup_users):
75
+ """Test that expired sessions are handled."""
76
+ # Create a service with very short TTL
77
+ short_ttl_service = AuthService(session_ttl_minutes=0)
78
+ short_ttl_service.register_user_project_access(
79
+ "test_user",
80
+ {"project-1": Role.validator},
81
+ )
82
+ session = short_ttl_service.login("test_user")
83
+
84
+ assert session is not None
85
+
86
+ # Manually set expiration to past
87
+ session.expires_at = datetime.utcnow() - timedelta(seconds=1)
88
+
89
+ # Try to retrieve expired session
90
+ retrieved = short_ttl_service.get_session(session.session_id)
91
+ assert retrieved is None
92
+
93
+ def test_get_session_updates_activity(self, auth_service, setup_users):
94
+ """Test that retrieving a session updates its last_activity."""
95
+ session = auth_service.login("validator1")
96
+ original_activity = session.last_activity
97
+
98
+ # Wait a moment (in real tests, would mock datetime)
99
+ import time
100
+ time.sleep(0.1)
101
+
102
+ # Retrieve session
103
+ retrieved = auth_service.get_session(session.session_id)
104
+
105
+ assert retrieved is not None
106
+ assert retrieved.last_activity >= original_activity
107
+
108
+ def test_logout_invalidates_session(self, auth_service, setup_users):
109
+ """Test that logout removes a session."""
110
+ session = auth_service.login("validator1")
111
+ session_id = session.session_id
112
+
113
+ # Verify session exists
114
+ assert auth_service.get_session(session_id) is not None
115
+
116
+ # Logout
117
+ auth_service.logout(session_id)
118
+
119
+ # Verify session is gone
120
+ assert auth_service.get_session(session_id) is None
121
+
122
+ def test_is_user_authorized_for_project(self, auth_service, setup_users):
123
+ """Test project authorization check."""
124
+ assert auth_service.is_user_authorized_for_project("admin_user", "kenya-2024")
125
+ assert auth_service.is_user_authorized_for_project("admin_user", "nairobi-2023")
126
+ assert auth_service.is_user_authorized_for_project("validator1", "kenya-2024")
127
+ assert not auth_service.is_user_authorized_for_project("validator2", "nairobi-2023")
128
+
129
+ def test_is_user_authorized_inactive(self, auth_service, setup_users):
130
+ """Test that inactive users are not authorized."""
131
+ assert not auth_service.is_user_authorized_for_project("inactive_user", "kenya-2024")
132
+
133
+ def test_get_user_role_for_project(self, auth_service, setup_users):
134
+ """Test retrieving user's role for a specific project."""
135
+ admin_role = auth_service.get_user_role_for_project("admin_user", "kenya-2024")
136
+ assert admin_role == Role.admin
137
+
138
+ validator_role = auth_service.get_user_role_for_project(
139
+ "validator1", "kenya-2024"
140
+ )
141
+ assert validator_role == Role.validator
142
+
143
+ no_access = auth_service.get_user_role_for_project("validator2", "nairobi-2023")
144
+ assert no_access is None
145
+
146
+ def test_list_user_projects(self, auth_service, setup_users):
147
+ """Test listing projects a user has access to."""
148
+ admin_projects = auth_service.list_user_projects("admin_user")
149
+ assert len(admin_projects) == 2
150
+ assert "kenya-2024" in admin_projects
151
+ assert "nairobi-2023" in admin_projects
152
+
153
+ validator2_projects = auth_service.list_user_projects("validator2")
154
+ assert len(validator2_projects) == 1
155
+ assert "kenya-2024" in validator2_projects
156
+
157
+ def test_list_projects_for_inactive_user(self, auth_service, setup_users):
158
+ """Test that inactive users have no accessible projects."""
159
+ projects = auth_service.list_user_projects("inactive_user")
160
+ assert len(projects) == 0
161
+
162
+ def test_cleanup_expired_sessions(self, auth_service, setup_users):
163
+ """Test cleanup of expired sessions."""
164
+ session1 = auth_service.login("admin_user")
165
+ session2 = auth_service.login("validator1")
166
+
167
+ # Expire session1
168
+ session1.expires_at = datetime.utcnow() - timedelta(seconds=1)
169
+
170
+ # Cleanup
171
+ auth_service.cleanup_expired_sessions()
172
+
173
+ # session1 should be gone
174
+ assert auth_service.get_session(session1.session_id) is None
175
+ # session2 should still be there
176
+ assert auth_service.get_session(session2.session_id) is not None
177
+
178
+ def test_set_user_active(self, auth_service, setup_users):
179
+ """Test disabling and enabling users."""
180
+ # User is initially inactive
181
+ assert not auth_service.is_user_authorized_for_project("inactive_user", "kenya-2024")
182
+
183
+ # Reactivate
184
+ auth_service.set_user_active("inactive_user", True)
185
+ assert auth_service.is_user_authorized_for_project("inactive_user", "kenya-2024")
186
+
187
+ # Deactivate again
188
+ auth_service.set_user_active("inactive_user", False)
189
+ assert not auth_service.is_user_authorized_for_project("inactive_user", "kenya-2024")
190
+
191
+ def test_register_user_project_access_update(self, auth_service):
192
+ """Test updating user's project access."""
193
+ auth_service.register_user_project_access(
194
+ "user1", {"project-1": Role.validator}
195
+ )
196
+
197
+ projects = auth_service.list_user_projects("user1")
198
+ assert projects == ["project-1"]
199
+
200
+ # Update to add more projects
201
+ auth_service.register_user_project_access(
202
+ "user1",
203
+ {"project-1": Role.validator, "project-2": Role.admin},
204
+ )
205
+
206
+ projects = auth_service.list_user_projects("user1")
207
+ assert len(projects) == 2
208
+ assert auth_service.get_user_role_for_project("user1", "project-2") == Role.admin
209
+
210
+ def test_session_isolation_between_users(self, auth_service, setup_users):
211
+ """Test that sessions are isolated between users."""
212
+ session_admin = auth_service.login("admin_user")
213
+ session_validator = auth_service.login("validator1")
214
+
215
+ assert session_admin.session_id != session_validator.session_id
216
+ assert session_admin.username != session_validator.username
217
+ assert session_admin.role != session_validator.role
218
+
219
+ # Sessions should remain independent
220
+ auth_service.logout(session_admin.session_id)
221
+ assert auth_service.get_session(session_validator.session_id) is not None
222
+
223
+
224
+ class TestUserProjectAccess:
225
+ """Test UserProjectAccess model."""
226
+
227
+ def test_user_project_access_creation(self):
228
+ """Test creating user project access."""
229
+ access = UserProjectAccess(
230
+ username="test_user",
231
+ project_slugs={"proj-1": Role.admin, "proj-2": Role.validator},
232
+ )
233
+
234
+ assert access.username == "test_user"
235
+ assert len(access.project_slugs) == 2
236
+ assert access.is_active is True
237
+
238
+ def test_user_project_access_deactivation(self):
239
+ """Test deactivating user."""
240
+ access = UserProjectAccess(
241
+ username="test_user",
242
+ project_slugs={"proj-1": Role.validator},
243
+ )
244
+
245
+ assert access.is_active is True
246
+
247
+ access.is_active = False
248
+ assert access.is_active is False
249
+
250
+
251
+ class TestSessionModel:
252
+ """Test Session model."""
253
+
254
+ def test_session_creation(self):
255
+ """Test creating a session."""
256
+ now = datetime.utcnow()
257
+ session = Session(
258
+ session_id="test-session-123",
259
+ username="test_user",
260
+ role=Role.validator,
261
+ authorized_projects=["proj-1", "proj-2"],
262
+ created_at=now,
263
+ last_activity=now,
264
+ expires_at=now + timedelta(hours=2),
265
+ )
266
+
267
+ assert session.session_id == "test-session-123"
268
+ assert session.username == "test_user"
269
+ assert session.role == Role.validator
270
+ assert len(session.authorized_projects) == 2
271
+
272
+ def test_session_expiration_check(self):
273
+ """Test session expiration detection."""
274
+ now = datetime.utcnow()
275
+
276
+ # Not expired
277
+ session = Session(
278
+ session_id="test",
279
+ username="user",
280
+ role=Role.validator,
281
+ authorized_projects=[],
282
+ created_at=now,
283
+ last_activity=now,
284
+ expires_at=now + timedelta(hours=1),
285
+ )
286
+
287
+ assert not session.is_expired()
288
+
289
+ # Expired
290
+ session.expires_at = now - timedelta(seconds=1)
291
+ assert session.is_expired()
292
+
293
+ def test_session_activity_update(self):
294
+ """Test updating session activity."""
295
+ now = datetime.utcnow()
296
+ session = Session(
297
+ session_id="test",
298
+ username="user",
299
+ role=Role.validator,
300
+ authorized_projects=[],
301
+ created_at=now,
302
+ last_activity=now,
303
+ expires_at=now + timedelta(minutes=120),
304
+ )
305
+
306
+ original_activity = session.last_activity
307
+
308
+ # Update activity with 30-minute TTL
309
+ import time
310
+ time.sleep(0.1)
311
+ session.update_activity(ttl_minutes=30)
312
+
313
+ assert session.last_activity >= original_activity
314
+ # The new expiration should be approximately 30 minutes from now
315
+ expected_expires = datetime.utcnow() + timedelta(minutes=30)
316
+ # Allow 5 seconds of variance due to timing
317
+ assert abs((session.expires_at - expected_expires).total_seconds()) < 5