Skip to content

Bug fixes#833

Open
mshriver wants to merge 7 commits into
ibutsu:mainfrom
mshriver:bug-fixes
Open

Bug fixes#833
mshriver wants to merge 7 commits into
ibutsu:mainfrom
mshriver:bug-fixes

Conversation

@mshriver
Copy link
Copy Markdown
Contributor

@mshriver mshriver commented Apr 14, 2026

Summary by Sourcery

Fix artifact and project access control edge cases and improve robustness around user/project lookups.

Bug Fixes:

  • Ensure artifact access checks correctly handle artifacts linked via either results or runs and deny access to orphaned artifacts.
  • Prevent errors when project_has_user is called with None or a non-existent project ID by explicitly returning False in those cases.
  • Correct project permission checking during import to use the resolved project object instead of the raw identifier.
  • Fix password recovery activation_code to be stored as a string rather than bytes.

Enhancements:

  • Refactor artifact access validation into a shared helper to centralize project-based permission logic.

Tests:

  • Add tests covering project_has_user behavior when given None or string IDs that do not resolve to a project.

mshriver and others added 3 commits April 14, 2026 14:02
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings April 14, 2026 12:12
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Apr 14, 2026

Reviewer's Guide

Refines project-based access control for artifacts and imports, hardens project_has_user against None and invalid IDs, and ensures password recovery activation codes are stored as strings instead of bytes, with regression tests added for the new project_has_user behavior.

Sequence diagram for updated artifact access control

sequenceDiagram
    actor Client
    participant ArtifactController as ArtifactController
    participant DB as Database
    participant Util as Util_projects
    participant Artifact as Artifact
    participant Result as Result
    participant Run as Run
    participant Project as Project
    participant User as User

    Client->>ArtifactController: view_artifact(id_, token_info, user)
    ArtifactController->>DB: _build_artifact_response(id_)
    DB-->>ArtifactController: artifact_or_error, response

    alt artifact is not instance of Artifact
        ArtifactController-->>Client: error_body, error_status
    else artifact is Artifact
        ArtifactController->>Util: _user_has_artifact_access(artifact, user)
        alt artifact has result
            Util->>Result: get project from artifact.result
            Result-->>Util: project
            Util->>Util: project_has_user(project, user)
        else artifact has run
            Util->>Run: get project from artifact.run
            Run-->>Util: project
            Util->>Util: project_has_user(project, user)
        else artifact has neither result nor run
            Util-->>ArtifactController: False
        end

        alt access denied
            ArtifactController-->>Client: 403 FORBIDDEN
        else access granted
            ArtifactController-->>Client: artifact response (file or JSON)
        end
    end
Loading

Sequence diagram for password recovery activation code generation

sequenceDiagram
    actor UserActor as User
    participant Client as Client
    participant LoginController as LoginController
    participant DB as Database
    participant UserModel as UserModel

    UserActor->>Client: Submit recover request (email)
    Client->>LoginController: POST /recover (body)

    LoginController->>DB: lookup user by email
    DB-->>LoginController: UserModel or None

    alt user not found
        LoginController-->>Client: 400 BAD_REQUEST
    else user found
        LoginController->>LoginController: generate uuid4()
        LoginController->>LoginController: urlsafe_b64encode(uuid_bytes).strip(b"=")
        LoginController->>LoginController: decode() to str
        LoginController->>UserModel: set activation_code (string)
        LoginController->>DB: session.add(user)
        LoginController->>DB: session.commit()
        LoginController-->>Client: 201 CREATED, {}
    end
Loading

Class diagram for updated artifact access and project_has_user

classDiagram
    class Artifact {
      +id
      +result_id
      +run_id
      +filename
      +result Result
      +run Run
      +to_dict()
    }

    class Result {
      +id
      +project Project
    }

    class Run {
      +id
      +project Project
    }

    class Project {
      +id
      +owner User
      +users list~User~
    }

    class User {
      +id
      +email
      +activation_code str
    }

    class ArtifactController {
      +view_artifact(id_, token_info, user)
      +download_artifact(id_, token_info, user)
      +get_artifact(id_, token_info, user)
      +get_artifact_list(page, page_size, filter_, sort, result_id, run_id, user)
      +delete_artifact(id_, token_info, user)
      +_build_artifact_response(id_)
    }

    class ImportController {
      +add_import(body, token_info, user)
    }

    class LoginController {
      +recover(body)
    }

    class UtilProjects {
      +project_has_user(project, user) bool
      +get_project(project_id_or_name) Project
      +_user_has_artifact_access(artifact, user) bool
    }

    ArtifactController --> Artifact : uses
    Artifact --> Result : optional
    Artifact --> Run : optional
    Result --> Project : belongs_to
    Run --> Project : belongs_to
    Project --> User : owner
    Project "1" --> "*" User : users

    ImportController --> UtilProjects : calls project_has_user
    ArtifactController --> UtilProjects : calls _user_has_artifact_access
    UtilProjects --> Project : queries
    UtilProjects --> User : checks membership

    LoginController --> User : sets activation_code
Loading

File-Level Changes

Change Details Files
Centralize and tighten artifact access checks based on associated result or run projects, and ensure handlers gracefully handle non-Artifact responses from the builder.
  • Introduce a private helper _user_has_artifact_access that checks access via artifact.result.project or artifact.run.project and denies access when neither is present.
  • Update view_artifact and download_artifact to return early if _build_artifact_response does not return an Artifact, and to rely on _user_has_artifact_access for authorization decisions.
  • Update get_artifact and delete_artifact to use _user_has_artifact_access instead of directly referencing artifact.result.project for permission checks.
  • Simplify artifact list query construction by relying on function arguments for result_id and run_id instead of reading result_id directly from request.args.
backend/ibutsu_server/controllers/artifact_controller.py
Fix project_has_user to safely handle None or invalid project identifiers and adjust its callers and tests accordingly.
  • Extend project_has_user to return False when the project is None after resolving string IDs, preventing attribute access errors.
  • Add regression tests asserting project_has_user returns False for None projects and non-existent string project IDs, and retains behavior for valid string IDs.
  • Update add_import to resolve the project string to a project object once, then use that object both for permission checks and when setting data["project_id"].
backend/ibutsu_server/util/projects.py
backend/tests/test_util.py
backend/ibutsu_server/controllers/import_controller.py
Ensure password recovery activation codes are stored as text strings instead of raw bytes.
  • Change recover in login_controller to decode the base64-encoded UUID before assigning it to user.activation_code, matching expected string storage semantics.
backend/ibutsu_server/controllers/login_controller.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • The repeated access-control condition for artifacts (checking both result and run projects) appears three times; consider extracting this into a small helper (e.g., user_has_artifact_access(artifact, user)) to avoid duplication and keep the authorization logic consistent.
  • For artifacts that are not associated with either a result or a run, the new condition will skip the access check and implicitly allow access; if that is unintended, consider explicitly handling the "no project" case (e.g., by returning FORBIDDEN or NOT_FOUND).
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The repeated access-control condition for artifacts (checking both result and run projects) appears three times; consider extracting this into a small helper (e.g., `user_has_artifact_access(artifact, user)`) to avoid duplication and keep the authorization logic consistent.
- For artifacts that are not associated with either a result or a run, the new condition will skip the access check and implicitly allow access; if that is unintended, consider explicitly handling the "no project" case (e.g., by returning FORBIDDEN or NOT_FOUND).

## Individual Comments

### Comment 1
<location path="backend/tests/test_util.py" line_range="563-566" />
<code_context>
     assert result is expected_result


+def test_project_has_user_none_project(make_user):
+    """Test project_has_user returns False when project is None (data integrity issue)."""
+    user = make_user(email="user@test.com")
+    assert project_has_user(None, user) is False
+
+
</code_context>
<issue_to_address>
**suggestion (testing):** Add a test for `project_has_user` when a string project ID resolves to `None`

The updated logic also returns `False` when `project` is a string and `get_project(project)` returns `None` (e.g., invalid or deleted ID) instead of raising. Please add a regression test for this path, for example:

```python
def test_project_has_user_invalid_string_project_id(make_user):
    user = make_user(email="user@test.com")
    assert project_has_user("non-existent-project-id", user) is False
```

This will cover the string-ID case and protect against regressions in the `get_project`/`project_has_user` interaction.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread backend/tests/test_util.py
Co-authored-by: Claude <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

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 delivers several backend bug fixes related to project permission checks, artifact authorization behavior, and login recovery activation code handling.

Changes:

  • Add a None guard to project_has_user() and a corresponding unit test.
  • Ensure recover() stores activation_code as a string (not bytes).
  • Update artifact authorization checks to support artifacts attached to either a result or a run.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 5 comments.

File Description
backend/tests/test_util.py Adds a unit test asserting project_has_user(None, user) returns False.
backend/ibutsu_server/util/projects.py Returns False when the resolved project is None in project_has_user().
backend/ibutsu_server/controllers/login_controller.py Decodes generated recovery activation_code to str before persisting.
backend/ibutsu_server/controllers/artifact_controller.py Expands authorization checks to handle run-attached artifacts (and avoid None dereferences).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/ibutsu_server/controllers/artifact_controller.py
Comment thread backend/ibutsu_server/controllers/artifact_controller.py Outdated
Comment thread backend/ibutsu_server/controllers/artifact_controller.py Outdated
Comment thread backend/ibutsu_server/controllers/artifact_controller.py Outdated
Comment thread backend/ibutsu_server/controllers/artifact_controller.py Outdated
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 14, 2026

Codecov Report

❌ Patch coverage is 38.88889% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.42%. Comparing base (32dcf39) to head (3f4a3ae).

Files with missing lines Patch % Lines
...d/ibutsu_server/controllers/artifact_controller.py 28.57% 3 Missing and 7 partials ⚠️
...end/ibutsu_server/controllers/import_controller.py 0.00% 0 Missing and 1 partial ⚠️

❌ Your patch check has failed because the patch coverage (38.88%) is below the target coverage (85.00%). You can increase the patch coverage or adjust the target coverage.
❌ Your project check has failed because the head coverage (73.42%) is below the target coverage (85.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #833      +/-   ##
==========================================
- Coverage   73.44%   73.42%   -0.02%     
==========================================
  Files         154      154              
  Lines        7562     7572      +10     
  Branches      662      666       +4     
==========================================
+ Hits         5554     5560       +6     
- Misses       1788     1790       +2     
- Partials      220      222       +2     
Files with missing lines Coverage Δ
...kend/ibutsu_server/controllers/login_controller.py 80.72% <100.00%> (ø)
backend/ibutsu_server/util/projects.py 96.66% <100.00%> (+0.23%) ⬆️
...end/ibutsu_server/controllers/import_controller.py 80.59% <0.00%> (ø)
...d/ibutsu_server/controllers/artifact_controller.py 69.82% <28.57%> (-0.99%) ⬇️

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 32dcf39...3f4a3ae. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

mshriver and others added 3 commits April 14, 2026 14:28
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
@mshriver
Copy link
Copy Markdown
Contributor Author

@sourcery-ai review

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • The repeated isinstance(artifact, Artifact) + early return pattern in view_artifact and download_artifact suggests _build_artifact_response’s return contract is unclear; consider tightening that helper’s interface (e.g., always returning a valid Artifact or raising/returning a standardized error type) so the controller functions can be simpler and not need type checks.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The repeated `isinstance(artifact, Artifact)` + early return pattern in `view_artifact` and `download_artifact` suggests `_build_artifact_response`’s return contract is unclear; consider tightening that helper’s interface (e.g., always returning a valid `Artifact` or raising/returning a standardized error type) so the controller functions can be simpler and not need type checks.

## Individual Comments

### Comment 1
<location path="backend/ibutsu_server/controllers/artifact_controller.py" line_range="30-39" />
<code_context>
         self.status = status


+def _user_has_artifact_access(artifact, user):
+    """Check whether the user has access to the artifact's project.
+
+    Access is determined by the project associated with the artifact's result or run.
+    If the artifact is not linked to either a result or a run, access is denied
+    to avoid silently granting access to orphaned artifacts.
+    """
+    if artifact.result:
+        return project_has_user(artifact.result.project, user)
+    if artifact.run:
+        return project_has_user(artifact.run.project, user)
+    return False
</code_context>
<issue_to_address>
**🚨 question (security):** Clarify behavior when an artifact is linked to both a result and a run with potentially different projects.

Because the helper prefers `artifact.result` over `artifact.run`, if both are set and belong to different projects, access is determined only by the result’s project. If that precedence isn’t intentional, consider either enforcing that both projects match or explicitly denying access when they differ to avoid authorization inconsistencies.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +30 to +39
def _user_has_artifact_access(artifact, user):
"""Check whether the user has access to the artifact's project.

Access is determined by the project associated with the artifact's result or run.
If the artifact is not linked to either a result or a run, access is denied
to avoid silently granting access to orphaned artifacts.
"""
if artifact.result:
return project_has_user(artifact.result.project, user)
if artifact.run:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🚨 question (security): Clarify behavior when an artifact is linked to both a result and a run with potentially different projects.

Because the helper prefers artifact.result over artifact.run, if both are set and belong to different projects, access is determined only by the result’s project. If that precedence isn’t intentional, consider either enforcing that both projects match or explicitly denying access when they differ to avoid authorization inconsistencies.

Copy link
Copy Markdown
Contributor

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 tightens backend authorization and robustness around project membership checks, artifact access control, and password recovery activation code storage.

Changes:

  • Make project_has_user() return False when the project lookup yields None, and add regression tests for None/invalid project inputs.
  • Centralize artifact access authorization so artifact view/download/get/delete deny access unless the caller has project access via the associated result or run.
  • Store password recovery activation codes as str (not bytes) to avoid type mismatches during lookup.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
backend/tests/test_util.py Adds regression tests for project_has_user() handling of None/invalid project inputs.
backend/ibutsu_server/util/projects.py Makes project_has_user() safely return False when project is None.
backend/ibutsu_server/controllers/login_controller.py Ensures recovery activation codes are stored as strings (decoded base64).
backend/ibutsu_server/controllers/import_controller.py Avoids redundant project lookup by passing project_obj into project_has_user().
backend/ibutsu_server/controllers/artifact_controller.py Adds centralized artifact access logic and applies it across artifact endpoints.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +87 to 88
if not _user_has_artifact_access(artifact, user):
return HTTPStatus.FORBIDDEN.phrase, HTTPStatus.FORBIDDEN
Comment on lines +34 to +40
If the artifact is not linked to either a result or a run, access is denied
to avoid silently granting access to orphaned artifacts.
"""
if artifact.result:
return project_has_user(artifact.result.project, user)
if artifact.run:
return project_has_user(artifact.run.project, user)
Comment on lines 25 to 28
if isinstance(user, str):
user = db.session.get(User, user)
if user.is_superadmin:
return True
Comment on lines +570 to +572
"""Test project_has_user returns False when a string project ID resolves to None."""
user = make_user(email="user@test.com")
assert project_has_user("non-existent-project-id", user) is False
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.

2 participants