Skip to content

feat(access-control)!: own tasks per user - #250

Merged
uniqueg merged 7 commits into
devfrom
feat/own-tasks-per-user
Oct 23, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/own-tasks-per-user

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Summary

With this PR, each task belongs to the user who created it, per the maintainer decisions for #215 (Q2, Q4 of the migration plan):

  • Owners: users with the role user may create tasks and become their owners. The owner is the sub of their own access token, stored as FOCA owner roles (g2 rules, via add_owner()) on the task and on its cancellation path. /tasks/{id}:cancel is not a sub-path of /tasks/{id} for FOCA. The owner is also stored as user_id in the task document.
  • Only owners: GET /tasks lists only the caller's own tasks (via FOCA's list_subject_roles()). GET /tasks/{id} and POST /tasks/{id}:cancel are allowed for owners only. Everyone else gets 403 as problem details, also for unknown tasks, so responses don't reveal which tasks exist.
  • No sharing: resource_roles: [owner].
  • Admins: admins no longer see tasks. The model has no admin bypass any more, and admins keep only FOCA's permissions API, via two named rules. Service info stays public.
  • Startup checks: proTES refuses to start without enabled and enforced access control, and with service clients (service_clients, on_behalf_of_header, client_mapping), which are not supported yet (Q4).
  • No reused identifiers: a new task never gets the identifier of a stored task, or one that roles are left on. Without this, a colliding identifier would give access to someone else's task, because the unique index doesn't cover task.id (fix: make task identifiers unique in the database #248). The owner role is granted before the insert and revoked if the insert fails.
  • Existing tasks: tasks of earlier versions have no owner, so they are visible to nobody, admins included. The docs (operations) describe how to find, assign (permissions API) and purge them, and how to stop abusive tasks without API access: at the TES backend, or by removing users from groups or backends from the service list.
  • Docs: access control (roles, task ownership, scaling), API errors, operations, upgrading (breaking changes).

Breaking:

  • admins lose access to tasks;
  • 404 becomes 403 for unknown tasks;
  • the rule users-get-cancel-tasks is replaced by owners-get-cancel-tasks;
  • the model changed;
  • proTES refuses to start without enforced access control or with service clients.

Closes #215
Closes #153

How it was verified

  • pytest with coverage: 326 passed, 1 skipped, 100% coverage (437 passed after merging origin/dev).
  • pytest against a real MongoDB 7.0 (MONGODB_TEST_URI): 326 passed, 1 skipped.
  • pre-commit run --all-files (ruff, mypy, semgrep, ast-grep, and the other hooks): passed.
  • mkdocs build --strict: passed.
  • The smoke test (tests/smoke/check.sh) is updated with a second user bob and an admin, who both get 403. It passed in CI ("Run app with Docker Compose").
  • CI: all checks passed. Tests ran with mongomock and with MongoDB 7.0, plus static analysis, docs, Compose smoke test and CodeQL.
  • Benchmark of FOCA rule loading with a real MongoDB: 1,000 rules take 0.02 s, 10,000 rules 0.11 s, 50,000 rules 0.41 s. Each task adds 2 rules, and listing and creating load the rules more than once.
  • Reviews: adversarial and quality subagents, 2 rounds. They found:
    • ID collision (high);
    • leftover roles, the disabled-access-control crash, and docstring and test issues (medium);
    • several lows.
      All are fixed, except those declined below.

Declined review findings

  • Group mapped to the role owner gets all tasks (low): FOCA's config validation already rejects group_mapping and client_mapping values that are in resource_roles.

  • Split the third commit, with ! on the startup refusal (medium, commit hygiene): the PR is squash-merged under a breaking title. The squash message and the upgrading notes list the startup refusal.

  • Concurrent creates sharing an identifier (Sourcery): a unique index on task.id is needed to close this race fully. It is tracked in fix: make task identifiers unique in the database #248, which changes the database configuration. The remaining window is negligible: both creates must draw the same 6-character identifier between the check and the grant.

  • Stale task-specific p rules (Sourcery): only admins can write such rules, and they can already grant themselves ownership. p rules are path patterns, so they can't be matched reliably against single identifiers.

Open questions

None blocking. Notes for the maintainer:

  • Scaling: FOCA loads all rules on each request, so request time grows linearly with the number of tasks (about 0.4 s at 25,000 tasks).
  • Admins can still grant themselves ownership: the permissions API accepts any rule, including g2 owner rules (documented). FOCA has no way to restrict which rules admins may write.
  • Owners without the role user: owners who lose the role user can still read and cancel their own tasks by ID, but can't create or list tasks (documented, tested).

🤖 Generated with Claude Code

uniqueg and others added 5 commits October 23, 2026 13:26
The user creating a task becomes its owner (the subject of the access
token), stored as FOCA owner roles (g2 rules) on the task and on its
cancellation path, and as user_id in the task document. Only owners may
get and cancel a task; GET /tasks lists only the caller's tasks.

Admins no longer may do everything: the model has no admin bypass, and
admins only keep the permissions API, via named rules. Tasks are not
shared (resource_roles: [owner]).

BREAKING CHANGE: admins can no longer list, read or cancel the tasks of
others; tasks of others and unknown tasks get 403 instead of 404; the
rule users-get-cancel-tasks is replaced by owners-get-cancel-tasks.
Tasks of earlier versions have no owner and are visible to nobody.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the roles user, owner and admin, task ownership, how operators
find, assign and purge tasks (also those without owner), how to stop
abusive tasks without API access, and the upgrade notes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Task identifiers were not unique (the unique index covers task_id and
worker_id, not task.id), so a new task could get the identifier of a
stored task, or of a deleted one whose owner roles are left, and its
creator, or the old owner, would get access to the other task. New
identifiers now skip stored tasks and identifiers with roles, and the
owner is granted before the task is stored.

Refuse to start without enabled and enforced access control (owners
would not be enforced, and the ownership helpers fail), and with
service clients, which are enforced as clients, not as their users.

Fix the docstrings, split and extend the access control tests (owners
without the role user, admins granting owners via the permissions API,
reused identifiers), and update the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Revoke the owner roles of a task again if it can't be stored, and
skip identifiers with roles of any subject (also of roles such as
user, or only on the cancellation). Run the ownership checks on
startup separately from the checks of the role groups.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This breaking change makes task ownership explicit and enforceable: tasks are assigned to their creating user in both MongoDB and FOCA resource-scoped roles, task APIs are owner-only with non-disclosing authorization errors, admins lose task access, unsafe startup configurations are rejected, and migration/operations guidance plus comprehensive tests are added.

Sequence diagram for owner-scoped task creation

sequenceDiagram
    actor User
    participant API as proTES API
    participant Ownership as ownership helpers
    participant FOCA
    participant MongoDB
    participant TES

    User->>API: POST /tasks
    API->>Ownership: get_owner()
    Ownership-->>API: caller subject
    API->>Ownership: task_has_roles()
    Ownership->>FOCA: list_resource_roles()
    API->>Ownership: add_task_owner()
    Ownership->>FOCA: add_owner(task path)
    Ownership->>FOCA: add_owner(cancel path)
    API->>MongoDB: insert_one(task with user_id)
    API->>TES: forward task
    API-->>User: task identifier
Loading

Sequence diagram for owner-only task access

sequenceDiagram
    actor User
    participant API as proTES API
    participant FOCA
    participant MongoDB
    participant TES

    User->>API: GET /tasks
    API->>FOCA: list_subject_roles()
    FOCA-->>API: caller owner roles
    API->>MongoDB: list_tasks(owned_tasks_filter())
    MongoDB-->>API: caller's tasks
    API-->>User: task list

    User->>API: GET /tasks/{id}
    API->>FOCA: authorize owner role
    alt owner
        FOCA-->>API: allow
        API->>MongoDB: get task
        API-->>User: task details
    else not owner or unknown task
        FOCA-->>API: deny
        API-->>User: 403 Forbidden
    end

    User->>API: POST /tasks/{id}:cancel
    API->>FOCA: authorize owner role on cancel path
    alt owner
        FOCA-->>API: allow
        API->>TES: cancel task
        API-->>User: cancellation result
    else not owner or unknown task
        FOCA-->>API: deny
        API-->>User: 403 Forbidden
    end
Loading

Flow diagram for task identifier reservation and owner rollback

flowchart TD
    A[Generate task identifier] --> B{Stored task or FOCA roles exist?}
    B -->|Yes| A
    B -->|No| C[add_task_owner]
    C --> D[insert_one]
    D -->|Success| E[Task stored with user_id]
    D -->|DuplicateKeyError or failure| F[remove_task_owner]
    F --> A
Loading

File-Level Changes

Change Details Files
Enforces per-task ownership through FOCA resource-scoped roles and persisted task owners.
  • Adds owner roles for task reads and cancellation, including cleanup on failed inserts.
  • Stores the creating user in user_id and filters listings to that user's owned task identifiers.
  • Prevents reuse of identifiers held by task documents or residual access-control roles.
pro_tes/ga4gh/tes/ownership.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/ga4gh/tes/models.py
pro_tes/access_control/model.conf
pro_tes/config.yaml
Restricts the API and changes authorization and error semantics for users, owners, and administrators.
  • Removes the admin task-access bypass; admins retain only explicitly configured permissions-API rules.
  • Returns 403 for other users and unknown tasks while preserving 404 for tasks deleted after ownership authorization.
  • Adds startup failures when access control is not enabled/enforced or unsupported service-client settings are configured.
pro_tes/access_control/model.conf
pro_tes/config.yaml
pro_tes/security.py
pro_tes/app.py
docs/api.md
Documents migration, operations, scaling, and breaking changes introduced by task ownership.
  • Documents ownership roles, stored owner metadata, permissions-API implications, and FOCA scaling costs.
  • Adds procedures for assigning or purging legacy ownerless tasks and stopping abusive tasks outside the API.
  • Updates upgrading guidance for renamed policies, admin behavior, startup requirements, and error changes.
docs/access-control.md
docs/api.md
docs/operations.md
docs/upgrading.md
docs/index.md
Expands automated coverage for ownership, authorization boundaries, identifier safety, and startup validation.
  • Tests owner-only listing, retrieval, cancellation, legacy tasks, deleted tasks, unknown-task responses, and owners losing the user role.
  • Tests residual-role identifier avoidance and rollback of roles when persistence fails.
  • Updates smoke coverage for other users and admins and adds service-client and enforced-access-control startup checks.
tests/ga4gh/tes/test_access_control.py
tests/ga4gh/tes/test_server.py
tests/test_app.py
tests/test_security.py
tests/smoke/check.sh
tests/smoke/fake_tes.py
tests/conftest.py

Assessment against linked issues

Issue Objective Addressed Explanation
#153 Restrict task listing, reading, and cancellation to users with access to each task, and let owners grant Owner, Maintainer, or Viewer access to other users. ❌ The PR limits task access to owners and filters listings to each user's own tasks, but explicitly implements no sharing. Owners cannot grant Maintainer or Viewer roles, or grant ownership through the task-access feature.
#153 Allow users in the designated group to create tasks and make the creating user the task owner. ✅
#153 Allow any authenticated user to access service info, regardless of group membership, while requiring authentication. ❌ The PR says service info stays public and tests access without a token, rather than requiring authentication.
#215 Enforce task ownership for listing, reading, and cancellation while preserving admin access to all tasks; hide other users’ tasks with 404 responses. ❌ The PR restricts listing, reading, and cancellation to owners, but explicitly denies admins access to others’ tasks and returns 403—not the issue’s specified 404—for tasks of others and unknown tasks.
#215 Support allow-listed service clients creating tasks on behalf of users, assigning ownership to the named user and rejecting unauthorized callers. ❌ The PR refuses to start when service clients, an on-behalf-of header, or client mappings are configured. It assigns ownership only from the caller’s own token.
#215 Handle pre-existing tasks without owners so they are visible only to admins. ❌ The PR makes ownerless legacy tasks invisible to everyone, including admins, and documents manual reassignment or purging instead.

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

@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e5c89ed) to head (732589d).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #250   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           24        25    +1     
  Lines         1180      1216   +36     
=========================================
+ Hits          1180      1216   +36     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 23, 2026 12:06

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="474-476" />
<code_context>
                 charset=charset,
                 length=length,
             )
+            if self.db_client.count_documents(
+                {"task.id": task_id}, limit=1
+            ) or task_has_roles(collection=collection, task_id=task_id):
+                continue
+            document.task.id = task_id
</code_context>
<issue_to_address>
**Concurrent tasks share an identifier**

When two concurrent creates generate the same task ID and both pass the availability checks, `_write_doc_to_db` checks availability before inserting, but the checks do not reserve `task.id` and the configured unique index does not cover it. Both documents and owner roles can therefore be stored at the same path, letting either owner read or cancel the other’s task.

Reserve task IDs atomically, for example with a unique constraint on `task.id`.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="474-476" />
<code_context>
                 charset=charset,
                 length=length,
             )
+            if self.db_client.count_documents(
+                {"task.id": task_id}, limit=1
+            ) or task_has_roles(collection=collection, task_id=task_id):
+                continue
+            document.task.id = task_id
</code_context>
<issue_to_address>
**Stale policy rules can expose reused task IDs**

When a task-specific `p` allow rule remains after its task is deleted and a later task gets the same generated ID, `task_has_roles` checks resource-scoped roles, not stored permission (`p`) rules. Because the permissions API can add arbitrary rules, a path-specific allow rule left after a task is deleted is not detected; if that ID is generated again, the stale rule still grants access to the new task at the same path.

Prevent reuse of IDs referenced by any stored resource-specific permission rule, or ensure those rules are removed when the task is deleted.
</issue_to_address>

### Comment 3
<location path="pro_tes/ga4gh/tes/ownership.py" line_range="91-92" />
<code_context>
+        task_id: Identifier of the task.
+        owner: User identifier, without prefix (cf. :py:func:`get_owner`).
+    """
+    for resource in task_resources(collection=collection, task_id=task_id):
+        add_owner(resource=resource, subject=owner)
+
+
</code_context>
<issue_to_address>
**Partial grants leave stale owner rules**

When granting the second resource role fails or execution stops between the two writes, `add_task_owner` writes the roles sequentially, so the first role can remain even though no task is inserted. The stale rule reserves the ID and adds to the rules FOCA loads on requests.

Make the two role grants atomic so a partial grant cannot remain.

Also at `pro_tes/ga4gh/tes/task_runs.py:480-481`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and this changes the authorization boundary for every task: an incorrect ownership rule or grant could let a caller read another user's task data or cancel it. Any data exposed or action taken cannot be undone by reverting the code.

Blocking findings: pro_tes/ga4gh/tes/task_runs.py:476, pro_tes/ga4gh/tes/task_runs.py:476, pro_tes/ga4gh/tes/ownership.py:92


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/ga4gh/tes/ownership.py Resolved
uniqueg and others added 2 commits October 23, 2026 14:14
If granting the second owner role of a new task fails, revoke the
first one too, so that no rule is left without a task.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 9370b32 into dev Oct 23, 2026
13 checks passed
@uniqueg
uniqueg deleted the feat/own-tasks-per-user branch October 23, 2026 12:18
uniqueg added a commit that referenced this pull request Oct 23, 2026
Adapt the chart to task ownership (#250): as the app now refuses to
start unless access control is enabled and enforced, rendering fails
otherwise, instead of skipping the checks of groups and admins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

feat(access-control): own tasks per user Add Access Control

1 participant