Skip to content

Auth with jwt#780

Merged
whikernel merged 10 commits intodevelopfrom
auth_with_jwt
Apr 23, 2025
Merged

Auth with jwt#780
whikernel merged 10 commits intodevelopfrom
auth_with_jwt

Conversation

@whikernel
Copy link
Contributor

@whikernel whikernel commented Apr 23, 2025

This pull request introduces changes to support token-based authentication alongside session-based authentication, enhances permission handling, and replaces references to current_user with iris_current_user for better compatibility. Additionally, it updates the Content Security Policy (CSP) and Cross-Origin Resource Sharing (CORS) configurations to include new origins.

Authentication Updates:

  • Added token-based authentication by implementing _token_authentication_process and integrating it into the is_user_authenticated function. This includes caching user permissions and creating a compatibility layer for token-based authentication. (source/app/blueprints/access_controls.py, [1] [2] [3] [4]

Permission Handling Enhancements:

  • Updated _user_has_at_least_a_required_permission to support both session-based and token-based authentication, with lazy loading and caching of permissions for token-based users. (source/app/blueprints/access_controls.py, source/app/blueprints/access_controls.pyL58-R90)
  • Replaced current_user with iris_current_user in permission checks and user-related logic across multiple files for consistency and compatibility. (source/app/blueprints/access_controls.py, [1] [2] [3] [4] [5] [6]

CSP and CORS Configuration Updates:

Code Refactoring:

  • Removed imports of current_user from files where it was replaced with iris_current_user. (source/app/blueprints/graphql/graphql_route.py, [1]; source/app/blueprints/pages/alerts/alerts_routes.py, [2]; source/app/blueprints/pages/case/case_tasks_routes.py, [3]; source/app/blueprints/pages/dashboard/dashboard_routes.py, [4]

These changes improve the flexibility of the authentication system, enhance security, and ensure compatibility with both session and token-based workflows.

Summary by CodeRabbit

  • New Features

    • Added support for token-based authentication (JWT), including access and refresh tokens, enabling API authentication via bearer tokens.
    • Introduced a unified user context for both token and session authentication, improving user identity handling across the application.
    • Added a dedicated endpoint for refreshing authentication tokens.
    • Updated Content Security Policy and CORS settings to support new authentication flows and additional origins.
  • Bug Fixes

    • Unified user identity handling in all user-related actions, ensuring consistent behavior regardless of authentication method.
  • Refactor

    • Replaced all usage of the previous session-based user context with the new unified user context throughout the application.
    • Improved formatting and removed unnecessary whitespace in test files and string handling.
  • Chores

    • Added configuration options for token expiration durations.
    • Updated documentation and code comments to reflect authentication and user context changes.

@whikernel whikernel requested a review from Copilot April 23, 2025 06:48
@coderabbitai
Copy link

coderabbitai bot commented Apr 23, 2025

Walkthrough

This update introduces unified user identity management across the application by abstracting all references to Flask-Login's current_user behind a new iris_current_user proxy, supporting both session-based and token-based authentication. Token-based authentication is integrated into the access control flow, including JWT token generation, validation, and refresh endpoints. All access checks, ownership assignments, and audit trails now use iris_current_user. The configuration is extended to support token expiration settings. CORS and Content Security Policy settings are updated to allow new origins. Numerous modules, blueprints, and business logic files are refactored to use the new user abstraction.

Changes

File(s) / Path(s) Change Summary
source/app/iris_engine/access_control/iris_user.py New module providing iris_current_user proxy and TokenUser class for unified user identity abstraction.
source/app/blueprints/access_controls.py
source/app/business/auth.py
source/app/configuration.py
Added/updated JWT token generation, validation, and refresh logic; integrated token-based authentication into access control; added token expiration config.
source/app/__init__.py
docker/nginx/nginx-newui.conf
CORS is always enabled; new origins added; CSP updated to allow http://app:8000.
source/app/blueprints/rest/v2/auth.py Added /refresh-token endpoint for JWT refresh; switched to iris_current_user for user context.
source/app/iris_engine/access_control/utils.py
source/app/iris_engine/demo_builder.py
source/app/iris_engine/module_handler/module_handler.py
source/app/iris_engine/reporter/reporter.py
source/app/iris_engine/tasker/tasks.py
source/app/iris_engine/utils/tracker.py
Switched all internal user references from current_user to iris_current_user.
source/app/blueprints/graphql/*
source/app/blueprints/pages/*
source/app/blueprints/rest/*
source/app/blueprints/socket_io_event_handlers/*
source/app/business/*
source/app/datamgmt/*
source/app/models/cases.py
source/app/schema/marshables.py
source/app/util.py
All user identity, permission, and audit logic refactored to use iris_current_user instead of current_user.
tests/tests_auth.py
tests/tests_graphql.py
tests/tests_rest_alerts.py
tests/tests_rest_iocs.py
tests/tests_rest_permissions.py
tests/tests_rest_tasks.py
Minor formatting, whitespace, or string literal cleanups in tests.
upgrades/upgrade_to_2.0.0.py Removed unnecessary f-string formatting in environment variable handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Nginx
    participant FlaskApp
    participant AuthModule
    participant iris_current_user

    Client->>Nginx: Sends request with (optional) Bearer token
    Nginx->>FlaskApp: Forwards request
    FlaskApp->>AuthModule: Checks for Bearer token
    alt Token present and valid
        AuthModule->>iris_current_user: Set as TokenUser
    else No token or invalid
        AuthModule->>iris_current_user: Use session-based user
    end
    FlaskApp->>iris_current_user: Use for all access checks and user context
    iris_current_user-->>FlaskApp: Provides user info (id, name, permissions)
    FlaskApp->>Client: Returns response (with tokens if login/refresh)
Loading
sequenceDiagram
    participant Client
    participant FlaskApp
    participant AuthModule

    Client->>FlaskApp: POST /refresh-token with refresh token
    FlaskApp->>AuthModule: Validate refresh token
    alt Valid and type=refresh
        AuthModule->>FlaskApp: Return new access & refresh tokens
        FlaskApp->>Client: Respond with new tokens
    else Invalid or expired
        AuthModule->>FlaskApp: Return error
        FlaskApp->>Client: Respond with error
    end
Loading

Possibly related PRs

  • dfir-iris/iris-web#773: Both PRs modify event update handling in the case timeline and business logic, including event update functions and socket.io event handling, indicating a direct code-level relationship.

Poem

A warren of users, now unified and clear,
Token or session, all rabbits appear.
With JWT in paw and a proxy in tow,
The fields of access control gracefully grow.
No more confusion—just one bunny to trust,
In the meadow of IRIS, fair and robust!

((\
( -.-)
o_(")(") 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces token-based authentication support and enhances permission handling by replacing instances of current_user with iris_current_user, while also updating security configurations such as CSP and CORS for new origins.

  • Implements _token_authentication_process to verify bearer tokens and integrate token-based auth.
  • Replaces current_user with iris_current_user across REST, GraphQL, and page routes to ensure compatibility.
  • Updates CORS and CSP configurations to include http://app:8000 and http://frontend:5173.

Reviewed Changes

Copilot reviewed 82 out of 83 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
source/app/blueprints/rest/* Updated API routes replacing current_user with iris_current_user for user ID retrieval.
source/app/blueprints/pages/* Adjusted user authentication checks in page routes to use iris_current_user.
source/app/blueprints/graphql/* Modified GraphQL endpoints to reference iris_current_user in permission checks.
source/app/blueprints/access_controls.py Added token-based authentication and updated permission checking logic.
source/app/init.py Revised CORS configuration to support new origins.
Files not reviewed (1)
  • docker/nginx/nginx-newui.conf: Language not supported
Comments suppressed due to low confidence (1)

source/app/blueprints/access_controls.py:89

  • For consistency with the recent changes, consider replacing 'current_user' with 'iris_current_user' in the session-based authentication branch of _user_has_at_least_a_required_permission.
session['permissions'] = ac_get_effective_permissions_of_user(current_user)

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@whikernel
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Apr 23, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@whikernel whikernel merged commit 97fbb15 into develop Apr 23, 2025
18 of 19 checks passed
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (7)
tests/tests_rest_alerts.py (1)

43-43: Simplified string literals by removing unnecessary f-strings.

The API endpoint paths have been converted from f-strings to regular string literals since they don't contain any variables to interpolate. This is a minor syntactic improvement.

Also applies to: 53-53, 63-63, 73-73, 83-83, 92-92, 103-103, 113-113

source/app/iris_engine/demo_builder.py (1)

59-62: Consider simplifying conditional return

The function can be simplified by returning the condition directly.

-    if iris_current_user.id != 1 and group.group_id in [1, 2]:
-        return True
-
-    return False
+    return iris_current_user.id != 1 and group.group_id in [1, 2]
🧰 Tools
🪛 Ruff (0.8.2)

59-62: Return the condition directly

Inline condition

(SIM103)

source/app/business/cases.py (1)

147-149: Client access permission check updated

The client access permission check now uses iris_current_user.id instead of current_user.id, correctly integrating with the new authentication system.

Consider simplifying the nested conditional

The static analysis tool suggests using a single if statement instead of nested conditionals for improved readability.

- if request_data.get('case_customer') and request_data.get('case_customer') != case_i.client_id:
-     if not user_has_client_access(iris_current_user.id, request_data.get('case_customer')):
-         raise BusinessProcessingError('Invalid customer ID. Permission denied.')
+ if (request_data.get('case_customer') and 
+     request_data.get('case_customer') != case_i.client_id and 
+     not user_has_client_access(iris_current_user.id, request_data.get('case_customer'))):
+     raise BusinessProcessingError('Invalid customer ID. Permission denied.')
🧰 Tools
🪛 Ruff (0.8.2)

147-148: Use a single if statement instead of nested if statements

(SIM102)

source/app/datamgmt/filters/filters_db.py (1)

19-20: Maintained proper access control for private filters.

Updated the private filter access control check to use iris_current_user.id instead of current_user.id, ensuring the same security model works with both authentication methods.

Consider simplifying the nested if statements for better readability:

-    if saved_filter:
-        if saved_filter.filter_is_private and saved_filter.created_by != iris_current_user.id:
-            return None
+    if saved_filter and saved_filter.filter_is_private and saved_filter.created_by != iris_current_user.id:
+        return None
source/app/blueprints/rest/alerts_routes.py (1)

415-417: Use direct attribute access instead of getattr.

The getattr function with a constant attribute is unnecessary and not any safer than direct attribute access.

-            if getattr(alert, 'alert_owner_id') is None:
+            if alert.alert_owner_id is None:
                 updates['alert_owner_id'] = iris_current_user.id
🧰 Tools
🪛 Ruff (0.8.2)

415-415: Do not call getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with attribute access

(B009)

source/app/business/auth.py (1)

195-203: Duplicated / ambiguous identity fields in JWT payload

Both username (= user.name ?) and user_login (= user.user) are embedded. Down‑stream code only uses username.
To avoid confusion (and shrink token size) keep a single canonical field, e.g.:

-        'username': user.name,
-        'user_email': user.email,
-        'user_login': user.user,
+        'username': user.user,           # existing “login” value
+        'email': user.email,

Propagate the same change to refresh_token_payload and validate_auth_token().

source/app/blueprints/access_controls.py (1)

68-86: Leverage any() for cleaner & faster permission checks

The explicit loop can be replaced with a short‑circuiting comprehension, matching Ruff’s hint and improving readability:

-        for permission in permissions:
-            if user_permissions & permission.value:
-                return True
-        return False
+        return any(user_permissions & p.value for p in permissions)

Same refactor applies to the session branch below.

🧰 Tools
🪛 Ruff (0.8.2)

82-85: Use return any(user_permissions & permission.value for permission in permissions) instead of for loop

Replace with return any(user_permissions & permission.value for permission in permissions)

(SIM110)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d8a973 and da0ca83.

📒 Files selected for processing (83)
  • docker/nginx/nginx-newui.conf (1 hunks)
  • source/app/__init__.py (1 hunks)
  • source/app/blueprints/access_controls.py (13 hunks)
  • source/app/blueprints/graphql/graphql_route.py (2 hunks)
  • source/app/blueprints/graphql/permissions.py (2 hunks)
  • source/app/blueprints/pages/alerts/alerts_routes.py (2 hunks)
  • source/app/blueprints/pages/case/case_tasks_routes.py (2 hunks)
  • source/app/blueprints/pages/dashboard/dashboard_routes.py (3 hunks)
  • source/app/blueprints/pages/login/login_routes.py (3 hunks)
  • source/app/blueprints/pages/manage/manage_cases_routes.py (3 hunks)
  • source/app/blueprints/pages/manage/manage_groups_routes.py (2 hunks)
  • source/app/blueprints/pages/manage/manage_users.py (3 hunks)
  • source/app/blueprints/rest/alerts_routes.py (20 hunks)
  • source/app/blueprints/rest/case/case_assets_routes.py (5 hunks)
  • source/app/blueprints/rest/case/case_evidences_routes.py (2 hunks)
  • source/app/blueprints/rest/case/case_graphs_routes.py (2 hunks)
  • source/app/blueprints/rest/case/case_ioc_routes.py (3 hunks)
  • source/app/blueprints/rest/case/case_notes_routes.py (2 hunks)
  • source/app/blueprints/rest/case/case_routes.py (3 hunks)
  • source/app/blueprints/rest/case/case_tasks_routes.py (2 hunks)
  • source/app/blueprints/rest/case/case_timeline_routes.py (4 hunks)
  • source/app/blueprints/rest/context_routes.py (4 hunks)
  • source/app/blueprints/rest/dashboard_routes.py (5 hunks)
  • source/app/blueprints/rest/datastore_routes.py (2 hunks)
  • source/app/blueprints/rest/filters_routes.py (2 hunks)
  • source/app/blueprints/rest/manage/manage_case_templates_routes.py (2 hunks)
  • source/app/blueprints/rest/manage/manage_cases_routes.py (3 hunks)
  • source/app/blueprints/rest/manage/manage_customers_routes.py (3 hunks)
  • source/app/blueprints/rest/manage/manage_groups.py (3 hunks)
  • source/app/blueprints/rest/manage/manage_templates_routes.py (2 hunks)
  • source/app/blueprints/rest/manage/manage_users.py (2 hunks)
  • source/app/blueprints/rest/overview_routes.py (2 hunks)
  • source/app/blueprints/rest/profile_routes.py (8 hunks)
  • source/app/blueprints/rest/v2/alerts.py (2 hunks)
  • source/app/blueprints/rest/v2/auth.py (5 hunks)
  • source/app/blueprints/rest/v2/cases.py (2 hunks)
  • source/app/blueprints/rest/v2/context/api_v2_context_routes.py (4 hunks)
  • source/app/blueprints/socket_io_event_handlers/case_event_handlers.py (2 hunks)
  • source/app/blueprints/socket_io_event_handlers/case_notes_event_handlers.py (3 hunks)
  • source/app/blueprints/socket_io_event_handlers/update_event_handlers.py (1 hunks)
  • source/app/business/alerts.py (2 hunks)
  • source/app/business/assets.py (2 hunks)
  • source/app/business/auth.py (5 hunks)
  • source/app/business/case_comments.py (2 hunks)
  • source/app/business/cases.py (3 hunks)
  • source/app/business/events.py (2 hunks)
  • source/app/business/evidences.py (3 hunks)
  • source/app/business/iocs.py (3 hunks)
  • source/app/business/notes.py (4 hunks)
  • source/app/business/tasks.py (3 hunks)
  • source/app/configuration.py (1 hunks)
  • source/app/datamgmt/alerts/alerts_db.py (18 hunks)
  • source/app/datamgmt/case/case_assets_db.py (2 hunks)
  • source/app/datamgmt/case/case_events_db.py (2 hunks)
  • source/app/datamgmt/case/case_iocs_db.py (3 hunks)
  • source/app/datamgmt/case/case_notes_db.py (2 hunks)
  • source/app/datamgmt/case/case_rfiles_db.py (2 hunks)
  • source/app/datamgmt/case/case_tasks_db.py (2 hunks)
  • source/app/datamgmt/dashboard/dashboard_db.py (4 hunks)
  • source/app/datamgmt/datastore/datastore_db.py (3 hunks)
  • source/app/datamgmt/filters/filters_db.py (3 hunks)
  • source/app/datamgmt/iris_engine/modules_db.py (2 hunks)
  • source/app/datamgmt/manage/manage_assets_db.py (2 hunks)
  • source/app/datamgmt/manage/manage_groups_db.py (2 hunks)
  • source/app/datamgmt/manage/manage_users_db.py (2 hunks)
  • source/app/datamgmt/states.py (2 hunks)
  • source/app/iris_engine/access_control/iris_user.py (1 hunks)
  • source/app/iris_engine/access_control/utils.py (7 hunks)
  • source/app/iris_engine/demo_builder.py (3 hunks)
  • source/app/iris_engine/module_handler/module_handler.py (2 hunks)
  • source/app/iris_engine/reporter/reporter.py (5 hunks)
  • source/app/iris_engine/tasker/tasks.py (3 hunks)
  • source/app/iris_engine/utils/tracker.py (3 hunks)
  • source/app/models/cases.py (2 hunks)
  • source/app/schema/marshables.py (2 hunks)
  • source/app/util.py (3 hunks)
  • tests/tests_auth.py (1 hunks)
  • tests/tests_graphql.py (22 hunks)
  • tests/tests_rest_alerts.py (5 hunks)
  • tests/tests_rest_iocs.py (2 hunks)
  • tests/tests_rest_permissions.py (1 hunks)
  • tests/tests_rest_tasks.py (3 hunks)
  • upgrades/upgrade_to_2.0.0.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (35)
source/app/blueprints/pages/manage/manage_users.py (2)
source/app/datamgmt/client/client_db.py (1)
  • get_client_list (33-56)
source/app/datamgmt/manage/manage_cases_db.py (1)
  • list_cases_dict (116-168)
source/app/blueprints/rest/overview_routes.py (1)
source/app/datamgmt/overview/overview_db.py (1)
  • get_overview_db (27-66)
source/app/datamgmt/manage/manage_users_db.py (1)
source/app/iris_engine/access_control/utils.py (1)
  • ac_ldp_group_removal (173-202)
source/app/blueprints/graphql/permissions.py (1)
source/app/iris_engine/access_control/utils.py (1)
  • ac_get_effective_permissions_of_user (153-170)
source/app/blueprints/pages/alerts/alerts_routes.py (1)
source/app/datamgmt/manage/manage_access_control_db.py (1)
  • user_has_client_access (141-159)
source/app/datamgmt/case/case_tasks_db.py (1)
source/app/models/models.py (1)
  • Comments (765-780)
source/app/datamgmt/case/case_rfiles_db.py (1)
source/app/models/models.py (1)
  • Comments (765-780)
source/app/datamgmt/manage/manage_assets_db.py (2)
source/app/models/models.py (1)
  • CaseAssets (170-198)
source/app/datamgmt/manage/manage_cases_db.py (1)
  • user_list_cases_view (171-179)
source/app/blueprints/pages/manage/manage_cases_routes.py (1)
source/app/datamgmt/client/client_db.py (1)
  • get_client_list (33-56)
source/app/blueprints/rest/case/case_ioc_routes.py (1)
source/app/datamgmt/case/case_iocs_db.py (1)
  • add_ioc (150-156)
source/app/business/alerts.py (1)
source/app/datamgmt/manage/manage_access_control_db.py (1)
  • user_has_client_access (141-159)
source/app/business/evidences.py (1)
source/app/datamgmt/case/case_rfiles_db.py (2)
  • add_rfile (63-77)
  • update_rfile (84-90)
source/app/datamgmt/case/case_events_db.py (1)
source/app/models/models.py (1)
  • Comments (765-780)
source/app/datamgmt/manage/manage_groups_db.py (1)
source/app/iris_engine/access_control/utils.py (1)
  • ac_ldp_group_removal (173-202)
source/app/datamgmt/case/case_notes_db.py (1)
source/app/models/models.py (1)
  • Comments (765-780)
source/app/datamgmt/dashboard/dashboard_db.py (2)
source/app/models/cases.py (1)
  • Cases (50-159)
source/app/models/models.py (1)
  • TaskAssignee (694-704)
source/app/blueprints/pages/manage/manage_groups_routes.py (1)
source/app/datamgmt/manage/manage_cases_db.py (1)
  • list_cases_dict (116-168)
source/app/business/iocs.py (1)
source/app/datamgmt/case/case_iocs_db.py (1)
  • add_ioc (150-156)
source/app/blueprints/pages/dashboard/dashboard_routes.py (1)
source/app/iris_engine/access_control/utils.py (1)
  • ac_get_user_case_counts (622-639)
source/app/blueprints/socket_io_event_handlers/case_event_handlers.py (2)
source/app/models/authorization.py (1)
  • CaseAccessLevel (38-45)
source/app/blueprints/access_controls.py (1)
  • ac_socket_requires (398-419)
source/app/datamgmt/alerts/alerts_db.py (2)
source/app/datamgmt/case/case_iocs_db.py (1)
  • add_ioc (150-156)
source/app/models/models.py (1)
  • Comments (765-780)
source/app/blueprints/rest/v2/context/api_v2_context_routes.py (1)
source/app/datamgmt/context/context_db.py (1)
  • ctx_search_user_cases (70-119)
source/app/datamgmt/filters/filters_db.py (1)
source/app/models/models.py (1)
  • SavedFilter (937-948)
source/app/blueprints/rest/dashboard_routes.py (1)
source/app/iris_engine/utils/tracker.py (1)
  • track_activity (30-66)
source/app/blueprints/rest/manage/manage_groups.py (2)
source/app/iris_engine/access_control/utils.py (3)
  • ac_flag_match_mask (23-24)
  • ac_ldp_group_update (205-234)
  • ac_ldp_group_removal (173-202)
source/app/models/authorization.py (1)
  • Permissions (48-65)
tests/tests_rest_iocs.py (2)
tests/iris.py (1)
  • get (50-51)
tests/rest_api.py (1)
  • get (48-53)
source/app/blueprints/socket_io_event_handlers/case_notes_event_handlers.py (2)
source/app/models/authorization.py (1)
  • CaseAccessLevel (38-45)
source/app/blueprints/access_controls.py (1)
  • ac_socket_requires (398-419)
source/app/blueprints/rest/case/case_assets_routes.py (1)
source/app/datamgmt/manage/manage_users_db.py (1)
  • get_user_cases_fast (398-407)
source/app/iris_engine/access_control/utils.py (1)
source/app/models/authorization.py (2)
  • UserCaseAccess (129-140)
  • CaseAccessLevel (38-45)
source/app/business/cases.py (1)
source/app/datamgmt/manage/manage_access_control_db.py (1)
  • user_has_client_access (141-159)
source/app/blueprints/rest/manage/manage_cases_routes.py (1)
source/app/datamgmt/manage/manage_cases_db.py (1)
  • list_cases_dict (116-168)
source/app/blueprints/rest/manage/manage_customers_routes.py (2)
source/app/datamgmt/client/client_db.py (1)
  • get_client_list (33-56)
source/app/datamgmt/manage/manage_users_db.py (1)
  • add_user_to_customer (139-158)
source/app/datamgmt/case/case_assets_db.py (1)
source/app/models/models.py (1)
  • Comments (765-780)
source/app/business/auth.py (1)
source/app/schema/marshables.py (1)
  • UserSchema (232-389)
source/app/blueprints/rest/alerts_routes.py (3)
source/app/datamgmt/manage/manage_access_control_db.py (2)
  • user_has_client_access (141-159)
  • check_ua_case_client (79-104)
source/app/blueprints/responses.py (1)
  • response_error (48-54)
source/app/schema/marshables.py (1)
  • CommentSchema (392-405)
🪛 Ruff (0.8.2)
source/app/business/case_comments.py

34-35: Use a single if statement instead of nested if statements

(SIM102)

source/app/iris_engine/demo_builder.py

59-62: Return the condition directly

Inline condition

(SIM103)

source/app/datamgmt/filters/filters_db.py

18-19: Use a single if statement instead of nested if statements

(SIM102)

source/app/business/cases.py

147-148: Use a single if statement instead of nested if statements

(SIM102)

source/app/blueprints/rest/alerts_routes.py

415-415: Do not call getattr with a constant attribute value. It is not any safer than normal property access.

Replace getattr with attribute access

(B009)

source/app/blueprints/access_controls.py

82-85: Use return any(user_permissions & permission.value for permission in permissions) instead of for loop

Replace with return any(user_permissions & permission.value for permission in permissions)

(SIM110)

🔇 Additional comments (196)
tests/tests_rest_permissions.py (1)

152-152: LGTM: Simple formatting fix.

This change removes an extra space between URL and body in the function call, improving code formatting consistency.

tests/tests_auth.py (1)

95-96: LGTM: Added newline at end of file.

This change follows the standard practice of ensuring files end with a newline character.

source/app/business/assets.py (2)

23-24: LGTM: Updated import for unified user identity handling.

This change replaces the Flask-Login current_user import with the new iris_current_user that supports both token and session-based authentication.


58-58: LGTM: Updated user reference to use the unified identity system.

This changes the reference to use iris_current_user.id instead of current_user.id, maintaining the same function semantics while supporting the new authentication approach.

source/app/blueprints/rest/v2/alerts.py (2)

28-28: LGTM: Updated import for unified user identity handling.

This change replaces the Flask-Login current_user import with the new iris_current_user that supports both token and session-based authentication.


115-115: LGTM: Updated user reference to use the unified identity system.

This changes the reference to use iris_current_user.id instead of current_user.id, maintaining the same function semantics while supporting the new authentication approach.

source/app/blueprints/pages/case/case_tasks_routes.py (2)

25-25: Import replacement looks good.

The change from importing current_user from Flask-Login to iris_current_user from custom module aligns with the PR objective of supporting both session and token-based authentication.


68-68: User identity reference update is correct.

Replacing current_user.id with iris_current_user.id properly implements the abstraction layer for user identity handling.

source/app/business/events.py (2)

22-22: Import replacement looks good.

The change from importing current_user to iris_current_user maintains consistency with the PR's authentication abstraction approach.


42-42: User attribution update is correct.

Replacing current_user.id with iris_current_user.id ensures proper user attribution when creating events and maintains compatibility with both authentication methods.

source/app/blueprints/rest/v2/cases.py (2)

38-38: Import replacement looks good.

The change from importing current_user to iris_current_user is consistent with the PR objective of unifying user identity handling.


107-107: User filtering parameter update is correct.

Replacing current_user.id with iris_current_user.id in the get_filtered_cases call ensures proper case filtering based on user permissions, regardless of authentication method.

source/app/blueprints/rest/case/case_tasks_routes.py (2)

28-28: Import replacement looks good.

The change from importing current_user to iris_current_user aligns with the authentication abstraction approach implemented across the codebase.


192-192: User attribution update is correct.

Replacing current_user.id with iris_current_user.id ensures proper user attribution when adding comments to tasks and maintains compatibility with both authentication methods.

source/app/business/iocs.py (3)

22-22: Refactored import to use iris_current_user

This change replaces the Flask-Login's current_user import with the new iris_current_user from the custom access control module, supporting the PR's objective to provide a unified authentication system.


69-69: Updated user identification for IOC creation

The reference to current_user.id has been correctly replaced with iris_current_user.id, ensuring proper user attribution when creating IOCs in the context of the new unified authentication system.


97-97: Updated user identification for IOC updates

The reference to current_user.id has been correctly replaced with iris_current_user.id, ensuring the IOC update operation properly attributes changes to the authenticated user, whether using session or token-based authentication.

tests/tests_rest_tasks.py (3)

86-86: Fixed spacing in function call

Removed unnecessary whitespace between the URL string and the body parameter in the create method call, improving code formatting consistency.


95-95: Fixed spacing in function call

Removed unnecessary whitespace between the URL string and the body parameter in the create method call, improving code formatting consistency.


104-104: Fixed spacing in function call

Removed unnecessary whitespace between the URL string and the body parameter in the create method call, improving code formatting consistency.

source/app/blueprints/socket_io_event_handlers/update_event_handlers.py (2)

23-23: Refactored import to use iris_current_user

This change replaces the Flask-Login's current_user import with the new iris_current_user from the custom access control module, supporting the unified authentication system.


30-31: Updated user reference in socket message

The socket event now correctly uses iris_current_user.user instead of current_user.user when emitting join messages, maintaining consistent user identity handling across the application.

source/app/blueprints/pages/manage/manage_users.py (3)

24-24: Refactored import to use iris_current_user

This change replaces the Flask-Login's current_user import with the new iris_current_user from the custom access control module, supporting the unified authentication system.


106-107: Updated user identification for client list access

The reference to current_user.id has been correctly replaced with iris_current_user.id when retrieving the client list, ensuring proper access control regardless of authentication method.


123-123: Updated user identification for case list access

The reference to current_user.id has been correctly replaced with iris_current_user.id when retrieving the case list, ensuring proper access control with the unified authentication system.

source/app/business/evidences.py (3)

22-22: Clean replacement of user identity import.

The import change is part of the broader refactoring to support both token-based and session-based authentication.


50-50: User ID reference properly updated.

The iris_current_user.id reference correctly replaces the previous current_user.id to ensure user identification works with both authentication methods.


71-71: User ID reference properly updated.

The iris_current_user.id reference correctly replaces the previous current_user.id in the update operation, maintaining consistent user tracking.

source/app/blueprints/rest/case/case_graphs_routes.py (2)

23-23: Clean replacement of user identity import.

The import change is part of the broader refactoring to support both token-based and session-based authentication.


90-90: User preference reference properly updated.

The iris_current_user.in_dark_mode reference correctly replaces the previous current_user.in_dark_mode to ensure UI preferences work with both authentication methods.

source/app/blueprints/rest/filters_routes.py (2)

23-23: Clean replacement of user identity import.

The import change is part of the broader refactoring to support both token-based and session-based authentication.


52-52: User ID reference properly updated.

The iris_current_user.id reference correctly replaces the previous current_user.id when setting the filter creator, maintaining consistent user attribution.

source/app/datamgmt/datastore/datastore_db.py (3)

29-29: Clean replacement of user identity import.

The import change is part of the broader refactoring to support both token-based and session-based authentication.


371-371: User ID reference properly updated.

The iris_current_user.id reference correctly replaces the previous current_user.id when creating IOC records, maintaining consistent user attribution.


390-390: User ID reference properly updated.

The iris_current_user.id reference correctly replaces the previous current_user.id when creating evidence records, maintaining consistent user attribution.

source/app/datamgmt/states.py (1)

23-23: Authentication abstraction looks good

The change from current_user to iris_current_user aligns with the unified authentication approach, properly supporting both session and token-based authentication.

Also applies to: 40-40

source/app/blueprints/rest/manage/manage_templates_routes.py (1)

32-32: Authentication abstraction looks good

The change from current_user to iris_current_user aligns with the unified authentication approach, properly supporting both session and token-based authentication when creating templates.

Also applies to: 99-99

source/app/blueprints/rest/datastore_routes.py (1)

31-31: Authentication abstraction looks good

The change from current_user to iris_current_user aligns with the unified authentication approach, properly supporting both session and token-based authentication when adding files to the datastore.

Also applies to: 242-242

source/app/blueprints/pages/manage/manage_groups_routes.py (1)

22-22: Authentication abstraction looks good

The change from current_user to iris_current_user correctly implements the unified authentication model, allowing the group management interface to work with both session and token-based authentication.

Also applies to: 98-98

source/app/blueprints/pages/alerts/alerts_routes.py (1)

32-32: Good implementation of user abstraction.

The code correctly replaces Flask-Login's current_user with the custom iris_current_user abstraction, supporting the new dual-authentication system (session and token-based) while maintaining the same authorization flow.

Also applies to: 81-81

source/app/blueprints/rest/manage/manage_case_templates_routes.py (1)

25-25: Correct integration of user identity abstraction.

The code properly replaces current_user with iris_current_user to maintain the same behavior for assigning case template creation ownership while supporting both authentication methods.

Also applies to: 81-81

source/app/blueprints/rest/case/case_evidences_routes.py (1)

28-28: Authentication abstraction properly implemented.

The evidence commenting system now correctly records the user ID from the unified authentication system, supporting both session and token-based authentication while maintaining the same functional behavior.

Also applies to: 166-166

source/app/datamgmt/manage/manage_users_db.py (1)

25-25: Security check maintained with new authentication abstraction.

The change correctly replaces current_user with iris_current_user in the condition that prevents users from removing their only admin group, preserving this important security feature while supporting the new dual-authentication system.

Also applies to: 126-126

source/app/datamgmt/manage/manage_groups_db.py (2)

20-20: Import updated to use iris_current_user instead of current_user.

The import has been changed to use the new unified user identity abstraction from the application's custom access control module.


179-181: User authentication check now uses the iris_current_user abstraction.

The code now uses iris_current_user.id instead of current_user.id when checking if the current user is trying to remove themselves from a group. This change properly aligns with the new unified authentication system that supports both token and session-based authentication.

source/app/blueprints/rest/case/case_notes_routes.py (2)

30-30: Import updated to use iris_current_user instead of current_user.

The import has been changed to use the new unified user identity abstraction that supports both token and session-based authentication.


401-401: User assignment updated to use the iris_current_user abstraction.

The code now assigns iris_current_user.id to comment.comment_user_id when creating a new comment, ensuring proper user identity handling regardless of authentication method.

source/app/datamgmt/case/case_notes_db.py (2)

21-21: Import updated to use iris_current_user instead of current_user.

The import has been changed to use the new unified user identity abstraction from the application's custom access control module.


371-371: User permission check now uses the iris_current_user abstraction.

The code now uses iris_current_user.id instead of current_user.id when filtering comments by user ID to ensure the current user is only deleting their own comments. This change properly supports both token and session-based authentication methods.

source/app/blueprints/graphql/graphql_route.py (2)

53-53: Import updated to use iris_current_user instead of current_user.

The import has been changed to use the new unified user identity abstraction that supports both token and session-based authentication.


73-73: GraphQL resolver now uses the iris_current_user abstraction.

The resolve_cases method now correctly passes iris_current_user.id to the build_filter_case_query function, ensuring proper user context handling regardless of authentication method.

source/app/datamgmt/case/case_rfiles_db.py (2)

24-24: Updated dependency to use iris_current_user abstraction.

This change replaces the direct import of current_user from flask_login with iris_current_user from the custom abstraction layer, supporting the new unified authentication system.


167-167: Authorization check updated to use the unified user abstraction.

Replacing current_user.id with iris_current_user.id ensures that comment deletion permission checks work correctly for both session-based and token-based authentication methods.

source/app/blueprints/rest/overview_routes.py (2)

25-25: Updated import to use iris_current_user abstraction.

This change supports the implementation of the unified user identity access that works with both session-based and token-based authentication.


35-35: Updated user identification to use the unified abstraction.

Replacing current_user.id with iris_current_user.id ensures that the overview filter works correctly regardless of the authentication method used.

source/app/blueprints/pages/manage/manage_cases_routes.py (3)

27-27: Properly migrating from current_user to the new iris_current_user abstraction.

The import change is part of the broader refactoring to unify user identity handling across the application, supporting both session-based and token-based authentication.


87-88: Good replacement of current_user.id with iris_current_user.id.

The function properly updates the user identifier to work with the new unified authentication system. This maintains the same functionality while extending support for token-based authentication.


121-122: Consistent application of iris_current_user in client list filtering.

This change correctly replaces current_user.id with iris_current_user.id to ensure the client list is filtered based on the current user's permissions regardless of authentication method.

source/app/business/notes.py (4)

23-23: Properly importing the new iris_current_user abstraction.

The import change successfully replaces the Flask-Login dependency with the new unified user identity abstraction.


63-63: Correctly updating note ownership assignment.

The code now properly assigns note ownership using iris_current_user.id instead of current_user.id, supporting both authentication methods.


128-128: Correctly updating note revision ownership.

This change ensures that note revisions are properly attributed to the current user regardless of the authentication method used.


137-137: Properly updating user ID assignment for note updates.

The code now correctly assigns user_id using the iris_current_user abstraction, maintaining consistent user identity handling across the application.

source/app/__init__.py (1)

119-129:

Details

❓ Verification inconclusive

CORS configuration updated to support new authentication flows.

The changes:

  1. Make CORS unconditionally enabled (removing the development-only restriction)
  2. Add two new allowed origins: http://app:8000 and http://frontend:5173

While these changes support the new authentication system, unconditionally enabling CORS could potentially increase the attack surface in production environments.

Verify that unconditionally enabling CORS is intentional and appropriate for both development and production environments:


🏁 Script executed:

#!/bin/bash
# Check if there are additional security measures in place

# Look for potential environment-based configurations
echo "Checking for environment-specific configurations..."
fd -t f "config" --exec grep -l "CORS" {} \;

# Check if there are restrictions in Nginx configuration
echo "Checking Nginx configurations..."
fd -t f "nginx.*\.conf" --exec grep -l "Access-Control-Allow-Origin" {} \;

Length of output: 311


Verify unconditional CORS enablement in production

I didn’t find any environment‑specific configurations or reverse‑proxy rules that scope CORS to development, so the call in source/app/__init__.py (lines 119–129) now applies in all environments. Please confirm:

  • Allowing these origins unconditionally is safe for your production deployment.
  • You have alternative controls (e.g. auth checks, firewall rules) or want to reintroduce an environment guard.
  • Documentation and deployment configs reflect this change.
source/app/datamgmt/case/case_events_db.py (2)

21-21: Properly importing the new iris_current_user abstraction.

The import change correctly replaces the Flask-Login dependency with the unified user identity abstraction.


161-161: Comment ownership check updated to support both authentication methods.

The code now correctly verifies comment ownership using iris_current_user.id instead of current_user.id, ensuring the permission check works with both session-based and token-based authentication.

source/app/business/alerts.py (1)

25-25: Clean user authentication abstraction switch

The change from current_user to iris_current_user successfully implements the unified user identity abstraction that supports both session-based and token-based authentication as intended.

Also applies to: 59-59

source/app/iris_engine/utils/tracker.py (1)

24-24: Proper migration to iris_current_user abstraction

All references to Flask-Login's current_user have been correctly replaced with the unified iris_current_user abstraction, ensuring consistent user identity handling for both session and token-based authentication.

Also applies to: 40-40, 53-54

source/app/iris_engine/module_handler/module_handler.py (1)

30-30: Consistent application of user identity abstraction

The replacement of current_user with iris_current_user in the task hook wrapper ensures the module handler correctly passes the user context regardless of authentication method.

Also applies to: 545-545

source/app/blueprints/rest/manage/manage_users.py (1)

28-28: Successful implementation of authentication abstraction

The import of iris_current_user and its usage in the self-deactivation check correctly maintains the existing security guard while supporting the new unified authentication approach.

Also applies to: 319-319

source/app/iris_engine/demo_builder.py (2)

24-24: Standardizing user identity with iris_current_user

The code now uses the new iris_current_user abstraction instead of Flask-Login's current_user. This change supports the new authentication system that works with both session-based and token-based authentication.


46-46: Updated to use iris_current_user

User identity reference updated to use the new abstraction layer.

source/app/datamgmt/case/case_iocs_db.py (3)

22-22: Standardizing user identity with iris_current_user

Replacing Flask-Login's current_user with the new abstraction layer that supports both token and session-based authentication.


127-127: Updated to use iris_current_user

User identity check updated to use the new abstraction layer. This ensures that case access limitations work for both token and session-based authentication.


271-271: Updated to use iris_current_user

Comment ownership verification now uses the new user identity abstraction, maintaining the same access control behavior but supporting both authentication methods.

source/app/datamgmt/iris_engine/modules_db.py (2)

22-22: Standardizing user identity with iris_current_user

Replacing Flask-Login's current_user with the new abstraction layer that supports both token and session-based authentication.


54-54: Updated to use iris_current_user with fallback

This maintains the existing functionality (falling back to the first user if no current user) while supporting the new unified authentication approach.

tests/tests_rest_iocs.py (2)

104-104: Improved code formatting

Removed an extra space in the query parameters argument for consistency with other API calls.


171-171: Removed unnecessary whitespace line

Eliminating trailing whitespace improves code cleanliness.

source/app/datamgmt/case/case_tasks_db.py (2)

23-24: Authentication system update implemented correctly.

The import change from flask_login import current_user to app.iris_engine.access_control.iris_user import iris_current_user properly supports the new unified authentication system that handles both token-based and session-based authentication.


300-304: User authorization check maintained with new authentication context.

The authorization check for comment deletion now uses iris_current_user.id instead of current_user.id, maintaining the security constraint that only comment authors can delete their own comments while adapting to the new unified authentication system.

source/app/business/case_comments.py (1)

21-22: Authentication system update implemented correctly.

The import change from flask_login import current_user to app.iris_engine.access_control.iris_user import iris_current_user properly supports the new unified authentication system.

source/app/blueprints/graphql/permissions.py (2)

26-27: Authentication system update implemented correctly.

The import change from flask_login import current_user to app.iris_engine.access_control.iris_user import iris_current_user properly supports the new unified authentication system.


68-70: Permission system properly updated to use the new authentication context.

The function now correctly uses iris_current_user to retrieve user permissions, maintaining the security model while adapting to the new authentication system.

source/app/datamgmt/manage/manage_assets_db.py (2)

4-6: Authentication system update implemented correctly.

The import change from flask_login import current_user to app.iris_engine.access_control.iris_user import iris_current_user properly supports the new unified authentication system.


52-53: Security filtering maintained with new authentication context.

This line correctly restricts asset visibility to only cases the current user has access to, using the new iris_current_user abstraction while maintaining the same security constraints.

source/app/configuration.py (1)

263-264: Well-designed token expiration settings

The addition of token expiration configuration parameters follows security best practices with a short-lived access token (15 minutes) and a longer-lived refresh token (14 days). This supports the new JWT token-based authentication system being implemented across the application.

source/app/iris_engine/tasker/tasks.py (3)

24-24: Appropriate replacement for user context

The import change from Flask-Login's current_user to a custom iris_current_user aligns with the goal of abstracting user identity management to support both session and token-based authentication.


62-64: Consistent user context replacement

The task arguments now correctly use the new iris_current_user abstraction, maintaining the same user identification functionality while enabling support for both session and token-based authentication.


76-76: Consistent user initialization

The pipeline initialization correctly uses the new user abstraction, ensuring that background tasks have the proper user context regardless of authentication method.

tests/tests_graphql.py (1)

262-263: Cleanup of trailing whitespace in GraphQL queries

The removal of trailing whitespace in GraphQL query strings is a good formatting cleanup that improves code readability without affecting functionality.

Also applies to: 286-287, 373-374, 390-391, 429-433, 457-458, 498-500, 519-520, 729-730, 736-737, 766-768, 780-782, 796-797, 809-811, 823-825, 837-839, 915-917, 934-936, 951-952

source/app/blueprints/rest/case/case_ioc_routes.py (3)

30-31: Appropriate import for unified user identity

The import change from Flask-Login's current_user to a custom iris_current_user aligns with the goal of abstracting user identity management to support both session and token-based authentication.


184-184: Consistent user identity in IOC creation

The user ID for new IOCs now correctly comes from the abstracted user identity source, supporting both session and token authentication methods while maintaining the same functionality.


271-271: Consistent user identity in comment creation

The user ID for new comments now correctly comes from the abstracted user identity source, supporting both session and token authentication methods while maintaining the same audit trail functionality.

source/app/datamgmt/case/case_assets_db.py (2)

26-26: Standardizing on iris_current_user for unified authentication handling.

The change from importing current_user from Flask-Login to using the custom iris_current_user supports the unified authentication approach that handles both session-based and token-based authentication.


388-388: User identity check updated to use iris_current_user.

The change ensures comment deletion authorization works consistently across both session-based and token-based authentication methods.

upgrades/upgrade_to_2.0.0.py (2)

84-84: String concatenation improved by removing unnecessary f-string.

The code now uses a simpler, more direct string concatenation which is more readable for a static string without any variables.


100-100: Simplified string replacement for environment variable.

Similarly, this change removes an unnecessary f-string usage when performing a string replacement operation.

source/app/blueprints/pages/login/login_routes.py (3)

48-48: Import updated to use iris_current_user from custom module.

This change aligns with the broader refactoring to unify user identity handling across the application, supporting both session and token-based authentication.


116-116: Authentication check updated to use iris_current_user.

This change ensures that the authentication verification works with both session and token-based authentication in the standard login flow.


141-141: Authentication check for OIDC login route updated.

The change ensures consistent authentication verification for the OpenID Connect login flow, working with both session and token-based approaches.

source/app/datamgmt/dashboard/dashboard_db.py (4)

22-22: Import updated to use iris_current_user from custom module.

This change is part of the broader authentication refactoring to support both session and token-based authentication.


95-95: User review filtering updated for unified authentication.

The change ensures that the user reviews are filtered correctly regardless of the authentication method used (session or token-based).


126-126: Task assignment filtering updated for unified authentication.

Updates the task filtering to work with the new unified user identity approach, ensuring tasks are correctly associated with users regardless of authentication method.


178-182: Case ownership filtering updated for unified authentication.

Both instances of case filtering by owner are updated to use the new user identity approach, maintaining consistency across authentication methods.

source/app/blueprints/pages/dashboard/dashboard_routes.py (3)

26-26: Import updated for user context abstraction.

The import of iris_current_user from the access control module aligns with the new unified authentication approach that supports both session and token-based authentication.


63-63: User identity source updated appropriately.

The reference to current_user.id has been correctly replaced with iris_current_user.id for the case counts function, maintaining the same logic while supporting the new authentication model.


90-90: User identity source updated appropriately in template context.

The user ID passed to the template has been correctly updated to use iris_current_user.id instead of current_user.id, maintaining the same functionality while supporting the new authentication model.

source/app/business/tasks.py (3)

24-24: Import updated for user context abstraction.

The import of iris_current_user replaces the previous import of current_user from Flask-Login, supporting the new unified authentication approach.


71-71: User identity source updated appropriately in task creation.

The user ID passed to add_task has been correctly updated to use iris_current_user.id, maintaining the same functionality while supporting both authentication methods.


107-107: User identity source updated appropriately in task update.

The assignment to task.task_userid_update now correctly uses iris_current_user.id instead of current_user.id, preserving the audit trail functionality while supporting the new authentication model.

source/app/blueprints/rest/manage/manage_groups.py (3)

27-27: Import updated for user context abstraction.

The import of iris_current_user aligns with the new unified authentication approach, supporting both session and token-based authentication.


120-120: User identity source updated appropriately in permissions check.

The user ID passed to ac_ldp_group_update has been correctly updated to use iris_current_user.id, maintaining the lockdown prevention check while supporting the new authentication model.


143-143: User identity source updated appropriately in group removal check.

The user ID passed to ac_ldp_group_removal has been correctly updated to use iris_current_user.id, preserving the security check that prevents users from locking themselves out while supporting both authentication methods.

source/app/blueprints/rest/case/case_timeline_routes.py (4)

33-33: Import updated for user context abstraction.

The import of iris_current_user replaces the previous import of current_user from Flask-Login, supporting the new unified authentication approach.


139-139: User identity source updated appropriately in comment creation.

The user ID assigned to comment.comment_user_id now correctly uses iris_current_user.id instead of current_user.id, maintaining proper audit trails while supporting the new authentication model.


776-776: User identity source updated appropriately in event duplication.

The user ID assigned to event.user_id now correctly uses iris_current_user.id instead of current_user.id, preserving proper attribution for duplicated events while supporting both authentication methods.


964-964: User identity source updated appropriately in CSV upload.

The user ID assigned to event.user_id now correctly uses iris_current_user.id instead of current_user.id, maintaining proper attribution for events created from CSV uploads while supporting the new authentication model.

source/app/business/cases.py (2)

24-24: Import updated to use iris_current_user

The import has been correctly updated to use iris_current_user from app.iris_engine.access_control.iris_user instead of current_user from Flask-Login, supporting the new unified authentication system.


81-81: Owner ID assignment updated to use iris_current_user

The case ownership assignment now uses iris_current_user.id instead of current_user.id, maintaining consistency with the authentication system refactoring.

source/app/util.py (3)

33-33: Import updated to use iris_current_user

The import has been correctly updated to use iris_current_user from app.iris_engine.access_control.iris_user instead of current_user from Flask-Login, supporting the new unified authentication system.


54-60: User references updated in history tracking

The modification history now correctly uses iris_current_user.user and iris_current_user.id instead of the Flask-Login equivalents, maintaining proper user context tracking in the history entries.


64-70: User references updated in history initialization

The modification history initialization now correctly uses iris_current_user.user and iris_current_user.id instead of the Flask-Login equivalents, ensuring consistent user attribution in the history entries.

source/app/blueprints/socket_io_event_handlers/case_event_handlers.py (4)

25-25: Import updated to use iris_current_user

The import has been correctly updated to use iris_current_user from app.iris_engine.access_control.iris_user instead of current_user from Flask-Login, supporting the new unified authentication system.


32-32: Socket event user attribution updated

The socket change event now correctly uses iris_current_user.user for user attribution in the event data.


39-39: Socket save event user attribution updated

The socket save event now correctly uses iris_current_user.user for user attribution in the event data.


54-54: Socket join notification message updated

The join notification message now correctly uses iris_current_user.user for user identification in room notifications.

source/app/iris_engine/reporter/reporter.py (5)

24-25: Import updated to use iris_current_user

The import has been correctly updated to use iris_current_user from app.iris_engine.access_control.iris_user instead of current_user from Flask-Login, supporting the new unified authentication system.


96-96: Report generation user attribution updated

The activity report generation now correctly uses iris_current_user.name for user attribution in the gen_user field.


116-116: Case info user attribution updated

The case information now correctly uses iris_current_user.name for user attribution in report metadata.


339-339: Document report user attribution updated

The document report generation now correctly uses iris_current_user.name for user attribution in the gen_user field.


359-359: Document case info user attribution updated

The document case information now correctly uses iris_current_user.name for user attribution in report metadata.

source/app/blueprints/rest/case/case_assets_routes.py (5)

33-33: Proper import of the iris_current_user abstraction

The import of the new iris_current_user abstraction is correctly added, supporting the transition from Flask-Login's current_user to this unified user identity system.


89-89: Consistent replacement of current_user with iris_current_user

The replacement of current_user.id with iris_current_user.id ensures proper user identification when fetching accessible cases, maintaining the functionality while leveraging the new authentication abstraction.


132-132: Appropriate update for case access validation

Correctly updated to use iris_current_user.id for retrieving user cases, maintaining consistency with the authentication abstraction changes.


249-249: Properly updated user identification for asset creation

The asset creation now uses iris_current_user.id as the user identifier, ensuring proper ownership attribution regardless of authentication method.


348-348: Updated comment ownership assignment

User identification for comment creation correctly updated to use iris_current_user.id, ensuring proper attribution in the audit trail.

source/app/blueprints/rest/manage/manage_customers_routes.py (3)

27-27: Appropriate import of iris_current_user abstraction

The import correctly adds the iris_current_user abstraction, supporting the unified authentication system.


57-58: Proper user identification for customer listing

The call to get_client_list now correctly uses iris_current_user.id, ensuring users see only the customers they have access to, regardless of authentication method.


258-258: Updated user assignment for customer association

The customer creation process now correctly associates with iris_current_user.id, ensuring proper ownership relationships regardless of authentication method.

source/app/blueprints/rest/case/case_routes.py (3)

32-32: Correctly imported iris_current_user abstraction

The import properly adds the unified user identity abstraction to support both session and token authentication methods.


95-96: Updated user reference in socket message

The socket message now correctly uses iris_current_user.user for the "last_saved" field, ensuring proper attribution in real-time collaboration.


230-231: Updated access control check

The security check preventing users from modifying their own access level now correctly compares against iris_current_user.id, maintaining the same protection across both authentication methods.

source/app/blueprints/rest/manage/manage_cases_routes.py (3)

31-31: Proper import of the unified user abstraction

The import correctly adds the iris_current_user abstraction to support the unified authentication system.


114-129: Updated user reference for case filtering

The case filtering now correctly uses iris_current_user.id, ensuring that access control is properly applied regardless of authentication method. This allows consistent filtering of cases whether using session or token-based authentication.


257-257: Updated user reference for listing cases

The case listing now correctly uses iris_current_user.id as the filter criterion, ensuring consistent access control across authentication methods.

source/app/blueprints/rest/v2/context/api_v2_context_routes.py (4)

24-24: Migration to iris_current_user abstraction looks good.

The addition of this import supports the refactoring to use the unified user identity abstraction that works with both session-based and token-based authentication.


40-40: Access to user ID consistently migrated to new abstraction.

This change correctly updates the code to use the unified user identity abstraction, maintaining the same functionality while adding support for token-based authentication.


55-56: Context attributes appropriately migrated to iris_current_user.

The update to use iris_current_user for context management is consistent with the application-wide migration to the unified user identity abstraction.


77-84: User context validation correctly migrated to use iris_current_user.

The user context validation logic has been properly updated to use the unified user abstraction while maintaining the same functionality.

source/app/blueprints/rest/dashboard_routes.py (7)

35-35: Migration to iris_current_user abstraction looks good.

The addition of this import supports the refactoring to use the unified user identity abstraction that works with both session-based and token-based authentication.


77-78: Context attributes appropriately migrated to iris_current_user.

The update to use iris_current_user for session context management is consistent with the application-wide migration to the unified user identity abstraction.


88-88: User tracking correctly migrated to use iris_current_user.

The activity tracking has been properly updated to reference the user through the unified abstraction.


94-95: Error handling for OIDC properly migrated to use iris_current_user.

The error handling in the logout process has been properly updated to reference the user through the unified abstraction.


99-100: Logout tracking correctly migrated to use iris_current_user.

The activity tracking for the standard logout flow has been properly updated to reference the user through the unified abstraction.


216-216: Task attribution appropriately migrated to use iris_current_user.

The code now correctly associates tasks with the current user through the unified user abstraction.


257-257: Task update attribution appropriately migrated to use iris_current_user.

Task modifications are now correctly associated with the current user through the unified user abstraction.

source/app/iris_engine/access_control/utils.py (6)

6-6: Migration to iris_current_user abstraction looks good.

The addition of this import supports the refactoring to use the unified user identity abstraction across the access control utilities.


177-177: Group removal check correctly migrated to use iris_current_user.

The access control lockdown prevention logic for group removal has been properly updated to reference the user through the unified abstraction.


209-209: Group update check correctly migrated to use iris_current_user.

The access control lockdown prevention logic for group updates has been properly updated to reference the user through the unified abstraction.


321-321: Case access check correctly migrated to use iris_current_user.

The fast case access check function has been properly updated to reference the current user through the unified abstraction.


414-436: Case access initialization correctly migrated to use iris_current_user.

The function for setting up new case access correctly references the current user through the unified abstraction, updating all occurrences consistently including the check for the current user, deletion of existing records, and creation of new access records.


568-568: User case access exclusion check correctly migrated to use iris_current_user.

The check to exclude the current user from mass-updates to case access has been properly updated to reference the user through the unified abstraction.

source/app/models/cases.py (3)

40-40: Migration to iris_current_user abstraction looks good.

The replacement of the Flask-Login import with the new unified user abstraction supports both session and token-based authentication.


105-105: Case ownership attribution correctly migrated to use iris_current_user.

The case initialization logic now correctly assigns the user ID using the unified abstraction while maintaining the fallback to the provided user parameter.


107-107: Case authorship attribution correctly migrated to use iris_current_user.

The case author assignment now correctly uses the unified abstraction while maintaining the fallback to the provided user parameter.

source/app/schema/marshables.py (2)

47-49: Clean abstraction of user identity source.

The replacement of Flask-Login's current_user with a custom iris_current_user allows for a unified approach to user identity management across different authentication methods.


1357-1357: Updated user reference to use the new identity abstraction.

Correctly updated the user ID assignment to use the new iris_current_user proxy, maintaining consistent user identity handling.

source/app/blueprints/rest/profile_routes.py (2)

26-26: Adopted unified user identity abstraction.

Replaced the Flask-Login's current_user import with the new iris_current_user from the custom iris_user module, enabling support for both token and session-based authentication.


49-49: Systematically updated all user identity references.

All references to the user's identity have been consistently updated to use iris_current_user instead of current_user. This ensures the profile routes work correctly with both session-based and token-based authentication.

Also applies to: 85-85, 92-93, 119-119, 136-136, 153-153, 167-167, 171-171, 182-182

source/app/datamgmt/alerts/alerts_db.py (4)

40-40: Adopted unified user identity abstraction.

Updated import to use the new iris_current_user proxy which supports both token and session-based authentication.


366-367: Updated user identity references in case and alert creation flows.

Consistently replaced all references to current_user with iris_current_user in case creation, alert escalation, and event creation flows. This ensures proper user attribution regardless of authentication method.

Also applies to: 370-371, 396-396, 407-408, 434-435, 491-492, 497-498, 544-545, 552-553, 577-578, 606-607, 652-652, 678-679, 701-702, 730-731


1134-1134: Maintained UI customization based on user preferences.

Updated dark mode detection to use iris_current_user.in_dark_mode for the visualization components. This ensures UI preferences remain consistent across both authentication methods.

Also applies to: 1147-1148, 1166-1167, 1169-1170, 1249-1250


1312-1314: Ensured proper comment ownership verification.

Updated the user identification in the comment deletion authorization check to use iris_current_user.id, maintaining security across both authentication methods.

source/app/datamgmt/filters/filters_db.py (2)

3-3: Updated import to use unified user identity abstraction.

Replaced the import of Flask-Login's current_user with the custom iris_current_user which supports both token and session-based authentication.


43-44: Updated user filtering for private filters.

Correctly updated the query to filter private filters by the current user's ID using iris_current_user.id, maintaining consistent behavior across authentication methods.

source/app/blueprints/socket_io_event_handlers/case_notes_event_handlers.py (4)

25-25: Properly integrates with the new authentication system.

The import change from current_user to iris_current_user correctly aligns with the new authentication abstraction layer that supports both session-based and token-based authentication.


32-33: Data attribution correctly updated to use the new user abstraction.

The socket event handler now correctly uses iris_current_user.user to assign ownership of note changes.


56-58: User identification properly updated in socket response payload.

Both message formatting and user attribution in the socket response now correctly reference iris_current_user properties.


64-64: Consistently updated all socket message payloads.

All references to user identity in socket message payloads have been properly updated to use iris_current_user, ensuring consistent user context throughout the socket communication system.

Also applies to: 70-70, 76-76, 86-88, 93-93

source/app/blueprints/rest/alerts_routes.py (5)

31-31: Import updated to use the new authentication abstraction.

The import change from current_user to iris_current_user correctly aligns with the new unified authentication approach.


157-158: User ID reference properly updated for filtered alerts.

The current_user_id parameter now correctly uses iris_current_user.id when retrieving filtered alerts.


332-333: Ownership assignments properly updated.

Alert ownership and comment attribution now correctly use iris_current_user.id, ensuring proper tracking of user actions in the audit trail.

Also applies to: 1019-1020


222-223: Client access verification consistently updated.

All access control checks related to client permissions now correctly use iris_current_user.id, maintaining security boundaries while supporting both authentication methods.

Also applies to: 253-254, 296-297, 472-473, 508-509, 566-567, 641-642, 701-702, 774-775, 842-843, 897-898, 926-927, 959-960, 987-988, 1012-1013


705-706: Case access verification consistently updated.

All access control checks for case permissions now correctly use iris_current_user.id, ensuring proper authorization regardless of authentication method.

Also applies to: 762-763

source/app/blueprints/rest/v2/auth.py (6)

18-30: Properly integrates JWT handling and imports for the new auth system.

The updated imports correctly include JWT for token handling, appropriate database access functions, and the new user abstraction, while removing the direct import of current_user.


36-37: Business logic import updated to include token generation.

The import from app.business.auth now includes generate_auth_tokens, which is necessary for the new token refresh endpoint.


50-54: Login flow properly updated to use the new user abstraction.

Authentication checks and user information retrieval now correctly use iris_current_user instead of current_user.


85-88: Logout flow consistently updated.

All references to the user context in the logout process now use iris_current_user, ensuring proper session cleanup and activity tracking.

Also applies to: 97-105, 109-110


125-131: Whoami endpoint properly updated.

The endpoint now correctly uses iris_current_user for authentication checks and user information retrieval.


134-168: Well-implemented token refresh endpoint.

The new endpoint follows security best practices by:

  1. Validating the presence of the refresh token
  2. Verifying it's the correct token type
  3. Checking if the associated user exists and is active
  4. Handling various error conditions appropriately

The implementation aligns well with standard JWT refresh flows.

source/app/blueprints/rest/context_routes.py (5)

26-27: Import updated to use the new authentication abstraction.

The import change from current_user to iris_current_user correctly aligns with the unified authentication approach.


43-44: User ID reference properly updated for case search.

Case context search now correctly uses iris_current_user.id to retrieve user-specific cases.


55-56: Authentication check properly updated.

The authentication verification now correctly uses iris_current_user.is_authenticated.


61-63: Context setting properly updated.

The context attributes are now correctly set on iris_current_user instead of current_user.


105-120: Context validation and clearing properly updated.

The validation and potential clearing of the user's case context now correctly references iris_current_user.

source/app/blueprints/access_controls.py (1)

351-353: CSRF bypass relies solely on g.auth_token_user_id

If _token_authentication_process() fails after g.auth_token_user_id was set (e.g. race condition or later validation error), the request might still circumvent CSRF.
Advise double‑checking the authentication success flag, or simply reuse _token_authentication_process()’s return value instead of the side‑effect.

http {
map $request_uri $csp_header {
default "default-src 'self' https://analytics.dfir-iris.org https://127.0.0.1; script-src 'self' 'unsafe-inline' https://analytics.dfir-iris.org; style-src 'self' 'unsafe-inline'; img-src 'self' data:;";
default "default-src 'self' https://analytics.dfir-iris.org https://127.0.0.1 http://app:8000; script-src 'self' 'unsafe-inline' https://analytics.dfir-iris.org; style-src 'self' 'unsafe-inline'; img-src 'self' data:;";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Updated Content Security Policy to allow connections from the app server.

Adding http://app:8000 to the CSP default-src directive ensures that resources from this origin can be loaded, which is necessary for the token-based authentication functionality.


🌐 Web query:

What are the security implications of adding an HTTP (non-HTTPS) origin to a Content Security Policy?

💡 Result:

Security Implications of Adding an HTTP (Non-HTTPS) Origin to a Content Security Policy

Adding an HTTP (non-HTTPS) origin to a Content Security Policy (CSP) significantly weakens the security protections CSP is meant to provide. Below are the main security implications:

1. Exposure to Man-in-the-Middle (MitM) Attacks

  • HTTP traffic is not encrypted. If your CSP allows resources (like scripts, images, or stylesheets) to load from non-HTTPS origins, attackers can intercept or modify these resources in transit. This enables attackers to inject malicious code or manipulate site behavior, potentially bypassing the very protections CSP is designed to enforce[10].
  • Any data or script loaded over HTTP can be tampered with by anyone able to intercept the network traffic (such as a compromised Wi-Fi network, malicious ISP, or anyone with access to the network path).

2. Mixed Content Weakens HTTPS Guarantees

  • If your main site is served over HTTPS but includes resources from HTTP sources (mixed content), browsers categorize these resources as either "blockable" (e.g., scripts, styles) or "upgradable." Blockable insecure content is typically blocked by modern browsers, but if not, it creates serious vulnerabilities, undermining the integrity and confidentiality guarantees of HTTPS[10].
  • Mixed content can also lead to inconsistent user experiences, as some resources may load (or fail to load) depending on browser security settings.

3. Increased XSS (Cross-Site Scripting) Risk

  • One of CSP’s main goals is to mitigate XSS attacks by controlling script sources[2][3]. Allowing HTTP origins opens a vector for attackers to inject compromised scripts if they are able to tamper with the HTTP traffic. This undermines CSP's effectiveness in protecting against XSS and related attacks.

4. Invalidation of Defense-in-Depth

  • CSP works best when you strictly whitelist secure, trusted origins, preferably over HTTPS[3][5][6]. By adding HTTP origins, you lose the defense-in-depth benefit because the trust boundary is no longer secure.
  • Attackers can exploit the weak link (the HTTP resource) to execute script injections or data exfiltration.

5. Modern Browser Behavior and Best Practices

  • Modern browsers and security guidelines strongly recommend (and often require) that all resources be loaded over HTTPS. Some browsers will block HTTP resources on an HTTPS page, but relying on this behavior rather than strict HTTPS sourcing in your CSP is risky and can lead to unexpected breakage or gaps in protection[10].

Summary Table

Security Implication Description
Susceptible to MitM Attacks HTTP resources can be intercepted and modified by attackers
Mixed Content Weakens HTTPS Compromises confidentiality and integrity of HTTPS pages
Increased XSS Risk Attackers can inject malicious scripts if HTTP resource is hijacked
Loss of Defense-in-Depth Weakens CSP’s effectiveness as a security boundary
Potential Broken Functionality Browsers may block or fail to upgrade HTTP content, causing issues

Best Practice:
Always use HTTPS origins in your CSP directives. If you have legacy content over HTTP, use the upgrade-insecure-requests directive to instruct browsers to upgrade HTTP requests to HTTPS where possible[10].

“Web developers are strongly encouraged to serve all their content over HTTPS... The ultimate solution to mixed content is for developers to load all resources over HTTPS.”[10]

Allowing HTTP origins in a CSP should be avoided, as it defeats the purpose of using CSP for robust web security.

Citations:


Avoid HTTP in CSP: serve the app backend over HTTPS or proxy through Nginx

File: docker/nginx/nginx-newui.conf
Lines: 29-29

Snippet showing the final state at these lines:

        default "default-src 'self' https://analytics.dfir-iris.org https://127.0.0.1 http://app:8000; script-src 'self' 'unsafe-inline' https://analytics.dfir-iris.org; style-src 'self' 'unsafe-inline'; img-src 'self' data:;";

Comment
Adding a non‑HTTPS origin (http://app:8000) to default-src weakens your CSP by introducing mixed‑content, Man‑in‑the‑Middle, and XSS risks[10]. To maintain strong security:

  • Secure your backend with TLS (e.g. https://app:8000) and whitelist that in your CSP instead.
  • Or proxy all API calls through the same HTTPS domain (e.g., under /api), then drop the HTTP origin from your CSP.
  • Optionally, use the upgrade-insecure-requests directive to enforce HTTPS requests.

Please update the CSP directive accordingly.

Comment on lines +34 to 36
if hasattr(iris_current_user, 'id') and iris_current_user.id is not None:
if comment.comment_user_id != iris_current_user.id:
raise BusinessProcessingError('Permission denied')
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Potential security vulnerability in permission check.

The current nested if statements could allow unauthorized comment edits if iris_current_user.id is None or if the attribute doesn't exist. Additionally, the static analyzer suggests simplifying nested conditions.

Consider rewriting this logic to explicitly deny access by default:

-if hasattr(iris_current_user, 'id') and iris_current_user.id is not None:
-    if comment.comment_user_id != iris_current_user.id:
-        raise BusinessProcessingError('Permission denied')
+if not hasattr(iris_current_user, 'id') or iris_current_user.id is None or comment.comment_user_id != iris_current_user.id:
+    raise BusinessProcessingError('Permission denied')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if hasattr(iris_current_user, 'id') and iris_current_user.id is not None:
if comment.comment_user_id != iris_current_user.id:
raise BusinessProcessingError('Permission denied')
if not hasattr(iris_current_user, 'id') or iris_current_user.id is None or comment.comment_user_id != iris_current_user.id:
raise BusinessProcessingError('Permission denied')
🧰 Tools
🪛 Ruff (0.8.2)

34-35: Use a single if statement instead of nested if statements

(SIM102)

Comment on lines +8 to +13
def __init__(self, user_data):
self.id = user_data['user_id']
self.user = user_data['username']
self.name = user_data['name']
self.email = user_data['email']
self.is_authenticated = True
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

TokenUser will raise KeyError for missing name/email fields

_token_authentication_process() only injects user_id and username into g.auth_user.
If those optional keys are absent, indexing with [] will blow up the first time iris_current_user is accessed, breaking every request that relies on the proxy.

-        self.id = user_data['user_id']
-        self.user = user_data['username']
-        self.name = user_data['name']
-        self.email = user_data['email']
+        # Use `.get()` to avoid KeyError when the field is missing
+        self.id = user_data.get('user_id')
+        self.user = user_data.get('username')
+        self.name = user_data.get('name')
+        self.email = user_data.get('email')

At minimum fall back to None; ideally enrich the token payload (or lazy‑load the full DB record) so callers can rely on these attributes.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def __init__(self, user_data):
self.id = user_data['user_id']
self.user = user_data['username']
self.name = user_data['name']
self.email = user_data['email']
self.is_authenticated = True
def __init__(self, user_data):
# Use `.get()` to avoid KeyError when the field is missing
self.id = user_data.get('user_id')
self.user = user_data.get('username')
self.name = user_data.get('name')
self.email = user_data.get('email')
self.is_authenticated = True

Comment on lines +6 to +16
class TokenUser:
"""A class that mimics the Flask-Login current_user interface for token auth"""
def __init__(self, user_data):
self.id = user_data['user_id']
self.user = user_data['username']
self.name = user_data['name']
self.email = user_data['email']
self.is_authenticated = True
self.is_active = True
self.is_anonymous = False

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Expose get_id() to fully emulate Flask‑Login users

Some parts of Flask‑Login (and several project utilities) call current_user.get_id().
Adding a trivial method keeps the surrogate indistinguishable from the real model:

 class TokenUser:
@@
     def __init__(...):
         ...
         self.is_anonymous = False
+
+    # Flask‑Login compatibility -------------------------------------------------
+    def get_id(self):
+        return str(self.id) if self.id is not None else None

Without this, any helper expecting get_id() will raise AttributeError.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
class TokenUser:
"""A class that mimics the Flask-Login current_user interface for token auth"""
def __init__(self, user_data):
self.id = user_data['user_id']
self.user = user_data['username']
self.name = user_data['name']
self.email = user_data['email']
self.is_authenticated = True
self.is_active = True
self.is_anonymous = False
class TokenUser:
"""A class that mimics the Flask-Login current_user interface for token auth"""
def __init__(self, user_data):
self.id = user_data['user_id']
self.user = user_data['username']
self.name = user_data['name']
self.email = user_data['email']
self.is_authenticated = True
self.is_active = True
self.is_anonymous = False
# Flask-Login compatibility -------------------------------------------------
def get_id(self):
return str(self.id) if self.id is not None else None

Comment on lines +186 to +191
access_token_expiry = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
minutes=app.config.get('ACCESS_TOKEN_EXPIRES_MINUTES', 15)
)
refresh_token_expiry = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
days=app.config.get('REFRESH_TOKEN_EXPIRES_DAYS', 14)
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

datetime.UTC only exists from Python 3.11 – breaks on current LTS versions

access_token_expiry = datetime.datetime.now(datetime.UTC)

On 3.10/3.9 this raises AttributeError: module 'datetime' has no attribute 'UTC'.

-import datetime
+import datetime
+from datetime import timezone
@@
-    access_token_expiry = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
+    access_token_expiry = datetime.datetime.now(timezone.utc) + datetime.timedelta(
 ...
-    refresh_token_expiry = datetime.datetime.now(datetime.UTC) + datetime.timedelta(
+    refresh_token_expiry = datetime.datetime.now(timezone.utc) + datetime.timedelta(

Repeat the change wherever datetime.UTC appears.

Comment on lines +238 to +246
payload = jwt.decode(token, app.config.get('SECRET_KEY'), algorithms=['HS256'])
return {
'user_id': payload.get('user_id'),
'username': payload.get('username')
}
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

validate_auth_token() returns too little information for TokenUser

TokenUser expects user_id, username, name, and email; only the first two are returned.
Either:

  1. Expand the return dict, or
  2. Change TokenUser to load the missing fields itself.
-        return {
-            'user_id': payload.get('user_id'),
-            'username': payload.get('username')
-        }
+        return {
+            'user_id': payload.get('user_id'),
+            'username': payload.get('username'),
+            'name': payload.get('email', payload.get('username')),
+            'email': payload.get('email')
+        }

Failing to do so causes the KeyError noted in iris_user.py.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
payload = jwt.decode(token, app.config.get('SECRET_KEY'), algorithms=['HS256'])
return {
'user_id': payload.get('user_id'),
'username': payload.get('username')
}
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
payload = jwt.decode(token, app.config.get('SECRET_KEY'), algorithms=['HS256'])
return {
'user_id': payload.get('user_id'),
'username': payload.get('username'),
'name': payload.get('email', payload.get('username')),
'email': payload.get('email')
}
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None

Comment on lines +88 to +90
if 'permissions' not in session:
session['permissions'] = ac_get_effective_permissions_of_user(current_user)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use iris_current_user consistently in the session path

The token path already switched to iris_current_user.
Retaining current_user here introduces two code‑paths and increases the risk of diverging behaviour.

-        session['permissions'] = ac_get_effective_permissions_of_user(current_user)
+        session['permissions'] = ac_get_effective_permissions_of_user(iris_current_user)

Keeps the logic unified and future‑proof.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if 'permissions' not in session:
session['permissions'] = ac_get_effective_permissions_of_user(current_user)
if 'permissions' not in session:
session['permissions'] = ac_get_effective_permissions_of_user(iris_current_user)

Comment on lines +548 to +569
def _token_authentication_process(incoming_request: Request):
"""
Process authentication using an Authorization header with Bearer token
"""
auth_header = incoming_request.headers.get('Authorization', '')
if not auth_header.startswith('Bearer '):
return False

parts = auth_header.split(' ')
if len(parts) < 2:
return False

token = parts[1]
user_data = validate_auth_token(token)

if not user_data:
return False

# Store user data for later use
g.auth_user = user_data
g.auth_token_user_id = user_data['user_id']

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Refresh tokens accepted as access tokens – add type check

validate_auth_token() is invoked blindly; a valid refresh token will happily authenticate an API request because its payload structure matches.
Validate the type claim (or use separate decoding functions):

-    user_data = validate_auth_token(token)
+    user_data = validate_auth_token(token)
+    if user_data and user_data.get('type') == 'refresh':
+        # Prevent privilege escalation with long‑lived refresh tokens
+        return False

Also consider propagating the token’s exp claim into g.auth_token_expires_at for rate‑limiting / analytics.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _token_authentication_process(incoming_request: Request):
"""
Process authentication using an Authorization header with Bearer token
"""
auth_header = incoming_request.headers.get('Authorization', '')
if not auth_header.startswith('Bearer '):
return False
parts = auth_header.split(' ')
if len(parts) < 2:
return False
token = parts[1]
user_data = validate_auth_token(token)
if not user_data:
return False
# Store user data for later use
g.auth_user = user_data
g.auth_token_user_id = user_data['user_id']
def _token_authentication_process(incoming_request: Request):
"""
Process authentication using an Authorization header with Bearer token
"""
auth_header = incoming_request.headers.get('Authorization', '')
if not auth_header.startswith('Bearer '):
return False
parts = auth_header.split(' ')
if len(parts) < 2:
return False
token = parts[1]
user_data = validate_auth_token(token)
if user_data and user_data.get('type') == 'refresh':
# Prevent privilege escalation with long‑lived refresh tokens
return False
if not user_data:
return False
# Store user data for later use
g.auth_user = user_data
g.auth_token_user_id = user_data['user_id']

@c8y3 c8y3 deleted the auth_with_jwt branch June 25, 2025 05:36
@coderabbitai coderabbitai bot mentioned this pull request Oct 24, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments