From d4da0583a774b39163c2af2927fb4c1c138bffa8 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sat, 5 Dec 2026 22:40:11 +0100 Subject: [PATCH 1/9] fix!: provenance only for the task owner Admins no longer get the provenance of tasks they don't own: the rule `admins-get-provenance` is removed from the base config, so that `GET /tasks/{id}/provenance` answers only to the task's owner. Everyone else, admins included, gets `403 Forbidden`, also for unknown tasks, as for `GET /tasks/{id}`. Admins of a TES gateway must not see the details of other users' tasks. Tests cover the owner (200), other users, outsiders and admins (403 for existing and unknown tasks, GET and HEAD), no token (401), the base config's rules, and overlays that still remove the rule (startup stops with FOCA's error). Docs (API, access control, operations, OpenAPI) and the upgrade notes are updated. BREAKING CHANGE: admins get `403` for the provenance of tasks they don't own; overlays with `admins-get-provenance: null` must drop that entry. Closes #568 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- docs/access-control.md | 19 +++--- docs/api.md | 11 ++-- docs/operations.md | 2 +- docs/upgrading.md | 26 +++++++- pro_tes/access_control/model.conf | 4 +- pro_tes/api/additions.openapi.yaml | 8 +-- pro_tes/config.yaml | 14 ++-- pro_tes/ga4gh/tes/task_runs.py | 4 +- tests/ga4gh/tes/test_provenance_api.py | 76 +++++++++++++++------- tests/retention/test_retention_endpoint.py | 10 ++- 10 files changed, 111 insertions(+), 63 deletions(-) diff --git a/docs/access-control.md b/docs/access-control.md index fb45eeda..a22ac7bc 100644 --- a/docs/access-control.md +++ b/docs/access-control.md @@ -43,8 +43,8 @@ options](https://foca.readthedocs.io/en/latest/configuration/auth/)). | --- | --- | | `user` | create tasks (`POST /tasks`) | | any authenticated caller | list their own tasks (`GET /tasks`), also without a role | -| `owner` (of a task) | read and cancel the task (`GET /tasks/{id}`, `POST /tasks/{id}:cancel`) | -| `admin` | get the resources that tasks used per user ([Usage](api.md#usage)) and as execution reports ([Execution reports](api.md#execution-reports)), and the provenance of tasks ([Provenance](api.md#provenance)); not the tasks of others, nor the access control rules (see [Permissions API](#permissions-api)) | +| `owner` (of a task) | read and cancel the task (`GET /tasks/{id}`, `POST /tasks/{id}:cancel`) and get its provenance ([Provenance](api.md#provenance)) | +| `admin` | get the resources that tasks used per user ([Usage](api.md#usage)) and as execution reports ([Execution reports](api.md#execution-reports)); not the tasks of others nor their provenance, nor the access control rules (see [Permissions API](#permissions-api)) | Roles are given to groups of the identity provider: the values of the claim `security.access_control.claim_groups` (from the token, or from the user info @@ -58,8 +58,7 @@ The roles and their permissions are the policies of `security.access_control.policies` in the base config (see [FOCA's access control](https://foca.readthedocs.io/en/latest/access-control/)), named rules (`users-create-tasks`, `authenticated-list-tasks`, -`owners-get-cancel-tasks`, `owners-get-provenance`, `admins-get-provenance`, -`admins-get-usage`, `admins-get-usage-reports`, `users-list-plugins` and +`owners-get-cancel-tasks`, `owners-get-provenance`, `admins-get-usage`, `admins-get-usage-reports`, `users-list-plugins` and `users-get-plugins`): a config overlay adds, changes or removes (`null`) single rules by name, e.g., rules that let only users list their tasks, and owners only read them: @@ -97,12 +96,12 @@ claim set in `security.access_control.claim_identity`) becomes its owner: tasks, so that responses don't tell which tasks exist. The owner gets `404 Not Found` for a task that was deleted from the database. -- `GET /tasks/{id}/provenance` is allowed for the owner and for admins - (rules `owners-get-provenance` and `admins-get-provenance`); everyone else - gets `403 Forbidden`. The provenance holds no inputs or logs of the task, - only which plugins and TES instances processed it (see - [Provenance](api.md#provenance)); remove `admins-get-provenance` (`null` - in an overlay) to keep it from admins. +- `GET /tasks/{id}/provenance` is allowed for the owner only (rule + `owners-get-provenance`); everyone else gets `403 Forbidden`, also admins + and for unknown tasks, as for `GET /tasks/{id}`. The provenance holds no + inputs or logs of the task, but tells which plugins and TES instances + processed it and when, i.e., details of someone's task (see + [Provenance](api.md#provenance)). - `GET /plugins` and `GET /plugins/{plugin_id}` (what users may choose per task, see [Choices of clients](plugins.md#choices-of-clients)) are allowed diff --git a/docs/api.md b/docs/api.md index 4eb853af..adcb771f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -15,7 +15,7 @@ control](access-control.md)). | `POST /tasks` | Create a task: proTES forwards it to a TES instance (see [Tasks](#tasks)) and returns its own identifier of the task. | | `GET /tasks` | List the caller's tasks, newest first, one page at a time (`page_size`, at most `max_page_size` of the [config](configuration.md#tasks), and `max_page_size_full` tasks, of at most `max_page_bytes_full` bytes, for the view `FULL`; `page_token` from `next_page_token` of the previous page, which is empty on the last page), optionally only those whose name starts with `name_prefix` (taken literally; matched against the name of the task as submitted, before plugins may have renamed it), by `state`, or by tags (`tag_key` and `tag_value`, in pairs, taken literally: a key without a value, or with an empty one, matches any value of that tag; a task must match all pairs; more values than keys are rejected with `400 Bad Request`; needs MongoDB 5.0 or later). | | `GET /tasks/{id}` | Get a task of the caller, with its state as last tracked from the TES instance. | -| `GET /tasks/{id}/provenance` | proTES extension: get the provenance of a task, for its owner and for admins (see [Provenance](#provenance)). | +| `GET /tasks/{id}/provenance` | proTES extension: get the provenance of a task, for its owner only (see [Provenance](#provenance)). | | `GET /usage` | proTES extension: get the resources that the tasks of each user used, for admins, if accounting is enabled (see [Usage](#usage)). | | `GET /plugins` | proTES extension (FOCA's plugin listing): list the plugins and presets that the caller may choose for its tasks, and the limits, for users; the default pipeline only for callers who may choose pipelines (see [Choices of clients](plugins.md#choices-of-clients)). | | `GET /plugins/{plugin_id}` | proTES extension: describe a plugin that the caller may choose (`404 Not Found` otherwise). | @@ -179,11 +179,10 @@ resolved pipeline (`pipeline.resolved`), e.g., shortened: } ``` -The owner of the task and admins may get it; everyone else gets -`403 Forbidden`, also for unknown tasks (see [Access -control](access-control.md#task-ownership)); admins get `404 Not Found` for -unknown tasks. Tasks without provenance (e.g., -created by earlier versions) give `404 Not Found`. The record holds no +Only the owner of the task may get it; everyone else gets `403 +Forbidden`, also admins and for unknown tasks, as for `GET /tasks/{id}` +(see [Access control](access-control.md#task-ownership)). Tasks without +provenance (e.g., created by earlier versions) give `404 Not Found`. The record holds no inputs, logs, IP addresses, tokens, header values or claims: plugins' changes are recorded as paths and hashes only. diff --git a/docs/operations.md b/docs/operations.md index 67e4f12e..725efd4e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -422,7 +422,7 @@ outcome, reason, remote identifier, times) and the final reason, if no TES instance accepted the task. The record is stored with the task (after routing), and replaced, with the attempts, once a TES instance accepted the task (or may have, `SYSTEM_ERROR`). Records hold no IP addresses, tokens, -header values or claims, and take at most 1 MiB. Owners and admins get +header values or claims, and take at most 1 MiB. Owners (only) get them with `GET /tasks/{id}/provenance` (see [Provenance](api.md#provenance)), and tasks carry a summary in their tags (`gateway.*`, see [Gateway tags](api.md#gateway-tags)). Tasks created by earlier versions have none. diff --git a/docs/upgrading.md b/docs/upgrading.md index b9c59395..8b61fc3c 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -15,6 +15,25 @@ changes](#unreleased-changes)). ## Unreleased changes +**Provenance for owners only (breaking change, rule removed):** `GET +/tasks/{id}/provenance` is now allowed for the owner of the task only: +admins get `403 Forbidden`, like everyone else who doesn't own the task, +also for unknown tasks (before, admins got the provenance of any task, and +`404 Not Found` for unknown ones). The rule `admins-get-provenance` is +removed from the base config: the provenance tells which plugins and TES +instances processed a task and when, i.e., details of someone else's +task, which admins must not see (see [Task +ownership](access-control.md#task-ownership)). The stored rule is removed +on startup, with the other configured rules. Admins keep usage and usage +reports. Scripts or dashboards that read the provenance with an admin's +token must use the owner's token instead (e.g., a service that created the +tasks on its own client). Overlays that remove the rule +(`admins-get-provenance: null`, as these docs suggested before) stop the +start, with FOCA's error naming the unknown rule: drop that entry. An +overlay that still sets the rule adds it again, as a rule of your own; drop +it. During a rolling upgrade, instances of earlier versions that start +store the rule again, until the last of them is replaced. + **Stale polls fenced (behaviour change, new field):** each run of a poll claims the tracking of its task with a token of its own, stored in `tracking.claim`, and only the run that claimed it last stores unfinished @@ -1128,7 +1147,9 @@ empty. Owners and admins get the provenance with `GET /tasks/{id}/provenance` (rules `owners-get-provenance` and `admins-get-provenance` of the base -config; custom lists of `security.access_control.policies` must add them). +config; custom lists of `security.access_control.policies` must add them; +admins no longer get it since the [unreleased +changes](#unreleased-changes)). New tasks have the gateway tags of FOCA (`gateway.pipeline_source`, `gateway.backend`, ...; see [Gateway tags](api.md#gateway-tags)), served with the task: clients that submit a fetched task again must drop the tags @@ -1260,7 +1281,8 @@ API specifications (`api.specs`) and access control rules (`security.access_control.policies`) of the base config are named entries (the spec `tes`; rules `users-create-list-tasks` (split in 0.8.0, see [To version 0.8.0](#to-version-080)), -`owners-get-cancel-tasks`, `owners-get-provenance`, `admins-get-provenance`, +`owners-get-cancel-tasks`, `owners-get-provenance`, `admins-get-provenance` +(removed, see [Unreleased changes](#unreleased-changes)), `users-list-plugins`, `users-get-plugins`, `admins-list-add-permissions` and `admins-manage-permissions`; the last two removed in 0.8.0, see [To version 0.8.0](#to-version-080)), which overlays change by name (see diff --git a/pro_tes/access_control/model.conf b/pro_tes/access_control/model.conf index 4ddf2661..6428cfee 100644 --- a/pro_tes/access_control/model.conf +++ b/pro_tes/access_control/model.conf @@ -4,8 +4,8 @@ # # Unlike FOCA's reference model (`resource_role_model.conf`), the role `admin` # may not do everything: admins only have the rights that rules give them -# (provenance and usage, cf. `config.yaml`), so that nobody but the owner of -# a task can read or cancel it. +# (usage, cf. `config.yaml`), so that nobody but the owner of a task can read +# or cancel it, or get its provenance. # [request_definition] # sub - accessing entity (prefixed user identifier, or role from group claims) diff --git a/pro_tes/api/additions.openapi.yaml b/pro_tes/api/additions.openapi.yaml index 1747a23f..4b104003 100644 --- a/pro_tes/api/additions.openapi.yaml +++ b/pro_tes/api/additions.openapi.yaml @@ -53,7 +53,7 @@ paths: proTES extension: get the provenance of a task, as recorded by the plugin engine of FOCA when the task was created and forwarded, with the plugin builds and the pipeline that it refers to. For the owner - of the task and for admins. + of the task only, not for admins. operationId: GetTaskProvenance parameters: - name: id @@ -71,8 +71,8 @@ paths: $ref: '#/components/schemas/TaskProvenance' 403: description: >- - The caller is neither the owner of the task nor an admin (also - for unknown tasks, which admins get as 404). + The caller is not the owner of the task (also admins, and for + unknown tasks, as for GetTask). content: application/json: schema: @@ -80,7 +80,7 @@ paths: 404: description: >- The task has no provenance (e.g., created by an earlier version - of proTES), was deleted, or (for admins) doesn't exist. + of proTES) or was deleted. content: application/json: schema: diff --git a/pro_tes/config.yaml b/pro_tes/config.yaml index db79cfc3..52ce736b 100644 --- a/pro_tes/config.yaml +++ b/pro_tes/config.yaml @@ -61,11 +61,12 @@ security: issuers: [] # Access control: users (the role `user`) may create tasks; every # authenticated caller may list their own; the user creating a task becomes - # its owner, and only owners may read and cancel a task, also after losing - # the role `user`. Admins (the role `admin`) may only read the provenance - # of tasks and the usage per user, not the tasks of others. Roles are given - # to groups of the identity provider (values of the claim `claim_groups`) - # by `group_mapping`, e.g.: + # its owner, and only owners may read and cancel a task and get its + # provenance, also after losing the role `user`. Admins (the role `admin`) + # may only read the usage per user and the execution reports, not the + # tasks of others nor their provenance. Roles are given to groups of the + # identity provider (values of the claim `claim_groups`) by + # `group_mapping`, e.g.: # claim_groups: groups # group_mapping: # compute-users: user @@ -96,9 +97,8 @@ security: authenticated-list-tasks: [p, "*", /ga4gh/tes/v1/tasks, (GET)|(HEAD)] # `POST` is cancellation (`/tasks/{id}:cancel`) owners-get-cancel-tasks: [p, owner, "/ga4gh/tes/v1/tasks/:id", (GET)|(HEAD)|(POST)] - # the provenance of a task, also for admins (no inputs or logs) + # the provenance of a task, for its owner only (not for admins either) owners-get-provenance: [p, owner, "/ga4gh/tes/v1/tasks/:id/provenance", (GET)|(HEAD)] - admins-get-provenance: [p, admin, "/ga4gh/tes/v1/tasks/:id/provenance", (GET)|(HEAD)] # the resources that tasks used, per user (`custom.accounting`) admins-get-usage: [p, admin, /ga4gh/tes/v1/usage, (GET)|(HEAD)] # the same records as execution reports, without user identifiers diff --git a/pro_tes/ga4gh/tes/task_runs.py b/pro_tes/ga4gh/tes/task_runs.py index 6cd38b8e..d719070c 100644 --- a/pro_tes/ga4gh/tes/task_runs.py +++ b/pro_tes/ga4gh/tes/task_runs.py @@ -814,8 +814,8 @@ def _update_records(self, run: PipelineRun, db_document: DbDocument) -> None: def get_task_provenance(self, id: str) -> dict[str, Any]: """Get the provenance of a task, with its references expanded. - Only owners of the task and admins may get it (enforced by the - policies). The builds of the plugins that ran and default and + Only owners of the task may get it, not admins either (enforced by + the policies). The builds of the plugins that ran and default and preset pipelines are stored once, by hash (cf. :py:class:`foca.plugins.ProvenanceStore`); they are added to the record (`builds`, `pipeline.resolved`), unless it has them diff --git a/tests/ga4gh/tes/test_provenance_api.py b/tests/ga4gh/tes/test_provenance_api.py index c231cbaa..f867a7f5 100644 --- a/tests/ga4gh/tes/test_provenance_api.py +++ b/tests/ga4gh/tes/test_provenance_api.py @@ -2,7 +2,7 @@ `GET /tasks/{id}/provenance` serves the provenance stored with a task, with the plugin builds and pipelines that it refers to expanded, to the task's -owner and to admins; tasks have the gateway tags of FOCA (`gateway.*`) that +owner only, not to admins (#568); tasks have the gateway tags of FOCA (`gateway.*`) that summarize it (and replace `forwarded_to`, removed in 0.4.0, cf. #324). """ @@ -16,6 +16,7 @@ import tes import yaml +from pro_tes import app as app_module from pro_tes.app import init_app from pro_tes.exceptions import BackendOutcomeUnknown from pro_tes.ga4gh.tes import task_runs @@ -27,6 +28,7 @@ DB, OTHER_USER, OUTSIDER, + USER, make_headers, reset_gateway, set_overlays, @@ -40,6 +42,8 @@ stored, ) +BASE_CONFIG = Path(app_module.__file__).parent / "config.yaml" + def provenance_path(task_id: str) -> str: """Get the path of the provenance of a task. @@ -53,16 +57,13 @@ def provenance_path(task_id: str) -> str: return f"{BASE_PATH}/tasks/{task_id}/provenance" -@pytest.mark.parametrize("user", [None, ADMIN, ADMIN_USER]) def test_get_provenance( client: FlaskClient, task_id: str, mongo_client: MongoClient[dict[str, Any]], - user: str | None, ) -> None: - """Owners and admins get the provenance, with its references expanded.""" - headers = make_headers(user) if user else None - response = client.get(provenance_path(task_id), headers=headers) + """Owners get the provenance, with its references expanded.""" + response = client.get(provenance_path(task_id)) assert response.status_code == 200 provenance = response.get_json() record = stored(mongo_client, task_id)["provenance"] @@ -83,18 +84,35 @@ def test_head_provenance(client: FlaskClient, task_id: str) -> None: assert client.head(provenance_path(task_id)).status_code == 200 -@pytest.mark.parametrize("user", [OTHER_USER, OUTSIDER]) -def test_get_provenance_forbidden(client: FlaskClient, task_id: str, user: str) -> None: - """Other users than owners and admins get `403`.""" - response = client.get(provenance_path(task_id), headers=make_headers(user)) +@pytest.mark.parametrize("user", [OTHER_USER, OUTSIDER, ADMIN, ADMIN_USER]) +@pytest.mark.parametrize("method", ["get", "head"]) +def test_get_provenance_forbidden( + client: FlaskClient, task_id: str, user: str, method: str +) -> None: + """Everyone but the owner gets `403`, admins included (#568). + + The same response as `GET /tasks/{id}` gives them. + """ + headers = make_headers(user) + response = getattr(client, method)(provenance_path(task_id), headers=headers) assert response.status_code == 403 + task = client.get(f"{BASE_PATH}/tasks/{task_id}", headers=headers) + assert task.status_code == 403 -def test_get_provenance_not_found(client: FlaskClient) -> None: - """Admins get `404` for unknown tasks, users `403`.""" +@pytest.mark.parametrize("user", [USER, OTHER_USER, ADMIN, ADMIN_USER]) +def test_get_provenance_unknown(client: FlaskClient, user: str) -> None: + """Unknown tasks give `403` to everyone, admins included. + + So that responses don't tell which tasks exist, as for `GET /tasks/{id}`. + """ path = provenance_path("NOTASK") - assert client.get(path, headers=make_headers(ADMIN)).status_code == 404 - assert client.get(path).status_code == 403 + assert client.get(path, headers=make_headers(user)).status_code == 403 + + +def test_get_provenance_no_token(anonymous_client: FlaskClient, task_id: str) -> None: + """Requests without an access token get `401`.""" + assert anonymous_client.get(provenance_path(task_id)).status_code == 401 def test_get_provenance_none( @@ -245,13 +263,29 @@ def test_gateway_tags_tracked( assert document["task"]["tags"] == tags -def test_admins_provenance_removed( +def test_admins_provenance_not_configured() -> None: + """The base config gives admins no rule for the provenance (#568).""" + config = yaml.safe_load(BASE_CONFIG.read_text(encoding="utf-8")) + policies = config["security"]["access_control"]["policies"] + assert "admins-get-provenance" not in policies + provenance_rules = [ + rule for rule in policies.values() if rule[2].endswith("/provenance") + ] + assert provenance_rules == [ + ["p", "owner", "/ga4gh/tes/v1/tasks/:id/provenance", "(GET)|(HEAD)"] + ] + + +def test_admins_provenance_removed_null( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, app_env: None, - backend: type[FakeBackend], ) -> None: - """Without the rule `admins-get-provenance`, admins get `403`.""" + """Overlays that remove the former rule `admins-get-provenance` stop the start. + + The rule is no longer in the base config, and FOCA refuses to remove + unknown rules (see the upgrade notes). + """ overlay = tmp_path / "policies.yaml" overlay.write_text( yaml.safe_dump( @@ -265,12 +299,8 @@ def test_admins_provenance_removed( ) set_overlays(monkeypatch, overlay) reset_gateway() - client = init_app().app.test_client() - client.environ_base["HTTP_AUTHORIZATION"] = make_headers()["Authorization"] - task_id = client.post(f"{BASE_PATH}/tasks", json=TASK).get_json()["id"] - path = provenance_path(task_id) - assert client.get(path).status_code == 200 - assert client.get(path, headers=make_headers(ADMIN)).status_code == 403 + with pytest.raises(ValueError, match="admins-get-provenance"): + init_app() def test_gateway_tags_not_built( diff --git a/tests/retention/test_retention_endpoint.py b/tests/retention/test_retention_endpoint.py index 728e9938..72eda111 100644 --- a/tests/retention/test_retention_endpoint.py +++ b/tests/retention/test_retention_endpoint.py @@ -125,12 +125,10 @@ def test_tombstone_not_found(client: FlaskClient, tombstone: str, path: str) -> def test_tombstone_provenance(client: FlaskClient, tombstone: str) -> None: - """Tombstones have no provenance, also for admins.""" - for headers in ({}, make_headers(user=ADMIN)): - response = client.get( - f"{BASE_PATH}/tasks/{tombstone}/provenance", headers=headers - ) - assert response.status_code == 404 + """Tombstones have no provenance for owners; admins get `403` (#568).""" + path = f"{BASE_PATH}/tasks/{tombstone}/provenance" + assert client.get(path).status_code == 404 + assert client.get(path, headers=make_headers(user=ADMIN)).status_code == 403 def test_tombstone_not_listed(client: FlaskClient, tombstone: str) -> None: From 1dece9fef4be6fcabdd1de91a0673290889f05ee Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sat, 5 Dec 2026 23:04:03 +0100 Subject: [PATCH 2/9] test: cover provenance rule removal on upgrade Tests that the rule stored by earlier versions stops applying when the app starts without it, and that variants of the provenance path never give admins the provenance. The upgrade notes name custom lists of rules, which must drop the rule too; docs re-wrapped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- docs/access-control.md | 9 +-- docs/api.md | 6 +- docs/operations.md | 2 +- docs/upgrading.md | 9 ++- tests/ga4gh/tes/test_provenance_api.py | 86 +++++++++++++++++++++----- 5 files changed, 84 insertions(+), 28 deletions(-) diff --git a/docs/access-control.md b/docs/access-control.md index a22ac7bc..0cee8460 100644 --- a/docs/access-control.md +++ b/docs/access-control.md @@ -58,10 +58,11 @@ The roles and their permissions are the policies of `security.access_control.policies` in the base config (see [FOCA's access control](https://foca.readthedocs.io/en/latest/access-control/)), named rules (`users-create-tasks`, `authenticated-list-tasks`, -`owners-get-cancel-tasks`, `owners-get-provenance`, `admins-get-usage`, `admins-get-usage-reports`, `users-list-plugins` and -`users-get-plugins`): a config overlay adds, changes or removes (`null`) -single rules by name, e.g., rules that let only users list their tasks, and -owners only read them: +`owners-get-cancel-tasks`, `owners-get-provenance`, `admins-get-usage`, +`admins-get-usage-reports`, `users-list-plugins` and `users-get-plugins`): +a config overlay adds, changes or removes (`null`) single rules by name, +e.g., rules that let only users list their tasks, and owners only read +them: ```yaml security: diff --git a/docs/api.md b/docs/api.md index adcb771f..770406e6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -182,9 +182,9 @@ resolved pipeline (`pipeline.resolved`), e.g., shortened: Only the owner of the task may get it; everyone else gets `403 Forbidden`, also admins and for unknown tasks, as for `GET /tasks/{id}` (see [Access control](access-control.md#task-ownership)). Tasks without -provenance (e.g., created by earlier versions) give `404 Not Found`. The record holds no -inputs, logs, IP addresses, tokens, header values or claims: plugins' -changes are recorded as paths and hashes only. +provenance (e.g., created by earlier versions) give `404 Not Found`. The +record holds no inputs, logs, IP addresses, tokens, header values or +claims: plugins' changes are recorded as paths and hashes only. ## Usage diff --git a/docs/operations.md b/docs/operations.md index 725efd4e..bf979203 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -422,7 +422,7 @@ outcome, reason, remote identifier, times) and the final reason, if no TES instance accepted the task. The record is stored with the task (after routing), and replaced, with the attempts, once a TES instance accepted the task (or may have, `SYSTEM_ERROR`). Records hold no IP addresses, tokens, -header values or claims, and take at most 1 MiB. Owners (only) get +header values or claims, and take at most 1 MiB. Only owners get them with `GET /tasks/{id}/provenance` (see [Provenance](api.md#provenance)), and tasks carry a summary in their tags (`gateway.*`, see [Gateway tags](api.md#gateway-tags)). Tasks created by earlier versions have none. diff --git a/docs/upgrading.md b/docs/upgrading.md index 8b61fc3c..84090069 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -31,8 +31,10 @@ tasks on its own client). Overlays that remove the rule (`admins-get-provenance: null`, as these docs suggested before) stop the start, with FOCA's error naming the unknown rule: drop that entry. An overlay that still sets the rule adds it again, as a rule of your own; drop -it. During a rolling upgrade, instances of earlier versions that start -store the rule again, until the last of them is replaced. +it. Custom lists of `security.access_control.policies` (which replace the +rules of the base config) must drop it too, or admins keep the access. +During a rolling upgrade, instances of earlier versions that start store +the rule again, until the last of them is replaced. **Stale polls fenced (behaviour change, new field):** each run of a poll claims the tracking of its task with a token of its own, stored in @@ -888,7 +890,8 @@ Check each item; the sections below have the details. 5. **Access control rules:** custom lists of `security.access_control.policies` must add the new rules `users-list-plugins`, `users-get-plugins`, `owners-get-provenance` and - `admins-get-provenance`, or users get `403` (see [Task + `admins-get-provenance` (removed again, see [Unreleased + changes](#unreleased-changes)), or users get `403` (see [Task provenance](#task-provenance)); overlays that change rules by name keep them. 6. **Database:** proTES uses new collections in the database of the tasks: diff --git a/tests/ga4gh/tes/test_provenance_api.py b/tests/ga4gh/tes/test_provenance_api.py index f867a7f5..138d5e95 100644 --- a/tests/ga4gh/tes/test_provenance_api.py +++ b/tests/ga4gh/tes/test_provenance_api.py @@ -2,8 +2,9 @@ `GET /tasks/{id}/provenance` serves the provenance stored with a task, with the plugin builds and pipelines that it refers to expanded, to the task's -owner only, not to admins (#568); tasks have the gateway tags of FOCA (`gateway.*`) that -summarize it (and replace `forwarded_to`, removed in 0.4.0, cf. #324). +owner only, not to admins (#568); tasks have the gateway tags of FOCA +(`gateway.*`) that summarize it (and replace `forwarded_to`, removed in +0.4.0, cf. #324). """ import json @@ -276,31 +277,82 @@ def test_admins_provenance_not_configured() -> None: ] +def _app_with_policies( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, policies: dict[str, Any] +) -> FlaskClient: + """Start the app with an overlay of access control rules. + + Args: + monkeypatch: Pytest's monkeypatch fixture. + tmp_path: Directory for the overlay. + policies: Rules of the overlay, by name. + + Returns: + A test client of the app, with the token of the default user. + """ + overlay = tmp_path / "policies.yaml" + overlay.write_text( + yaml.safe_dump({"security": {"access_control": {"policies": policies}}}), + encoding="utf-8", + ) + set_overlays(monkeypatch, overlay) + reset_gateway() + client = init_app().app.test_client() + client.environ_base["HTTP_AUTHORIZATION"] = make_headers()["Authorization"] + return client + + +def test_admins_provenance_upgrade( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + app_env: None, + backend: type[FakeBackend], +) -> None: + """The stored rule of earlier versions stops applying on upgrade (#568). + + An app with the former rule `admins-get-provenance` (as stored by 0.8.0) + lets admins read the provenance; the app started next without it + replaces the stored rules, so that admins get `403`. + """ + old_rule = ["p", "admin", "/ga4gh/tes/v1/tasks/:id/provenance", "(GET)|(HEAD)"] + client = _app_with_policies( + monkeypatch, tmp_path, {"admins-get-provenance": old_rule} + ) + task_id = client.post(f"{BASE_PATH}/tasks", json=TASK).get_json()["id"] + path = provenance_path(task_id) + assert client.get(path, headers=make_headers(ADMIN)).status_code == 200 + client = _app_with_policies(monkeypatch, tmp_path, {}) + assert client.get(path).status_code == 200 + assert client.get(path, headers=make_headers(ADMIN)).status_code == 403 + + +@pytest.mark.parametrize( + "suffix", ["/provenance/", "//provenance", "%2Fprovenance", "/PROVENANCE"] +) +def test_get_provenance_path_variants( + client: FlaskClient, task_id: str, suffix: str +) -> None: + """Variants of the provenance path never give admins the provenance. + + Redirects (e.g., of double slashes) are followed. + """ + path = f"{BASE_PATH}/tasks/{task_id}{suffix}" + response = client.get(path, headers=make_headers(ADMIN), follow_redirects=True) + assert response.status_code in {403, 404} + + def test_admins_provenance_removed_null( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, app_env: None, ) -> None: - """Overlays that remove the former rule `admins-get-provenance` stop the start. + """Overlays removing the former rule `admins-get-provenance` stop the start. The rule is no longer in the base config, and FOCA refuses to remove unknown rules (see the upgrade notes). """ - overlay = tmp_path / "policies.yaml" - overlay.write_text( - yaml.safe_dump( - { - "security": { - "access_control": {"policies": {"admins-get-provenance": None}} - } - } - ), - encoding="utf-8", - ) - set_overlays(monkeypatch, overlay) - reset_gateway() with pytest.raises(ValueError, match="admins-get-provenance"): - init_app() + _app_with_policies(monkeypatch, tmp_path, {"admins-get-provenance": None}) def test_gateway_tags_not_built( From 7858cb31819edf0deaf367f6d961ae5e18ef735c Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sat, 5 Dec 2026 23:26:20 +0100 Subject: [PATCH 3/9] docs: clarify provenance upgrade and 401 The 0.4.0 upgrade checklist no longer tells custom rule lists to add `admins-get-provenance`, but to leave it out; the provenance docs say that requests without a valid token get `401`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- docs/access-control.md | 5 +++-- docs/api.md | 5 +++-- docs/upgrading.md | 11 ++++++----- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/access-control.md b/docs/access-control.md index 0cee8460..38b157f0 100644 --- a/docs/access-control.md +++ b/docs/access-control.md @@ -98,8 +98,9 @@ claim set in `security.access_control.claim_identity`) becomes its owner: `404 Not Found` for a task that was deleted from the database. - `GET /tasks/{id}/provenance` is allowed for the owner only (rule - `owners-get-provenance`); everyone else gets `403 Forbidden`, also admins - and for unknown tasks, as for `GET /tasks/{id}`. The provenance holds no + `owners-get-provenance`); every other caller gets `403 Forbidden`, also + admins and for unknown tasks, as for `GET /tasks/{id}` (requests without + a valid access token get `401 Unauthorized`). The provenance holds no inputs or logs of the task, but tells which plugins and TES instances processed it and when, i.e., details of someone's task (see [Provenance](api.md#provenance)). diff --git a/docs/api.md b/docs/api.md index 770406e6..6c09d34c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -179,9 +179,10 @@ resolved pipeline (`pipeline.resolved`), e.g., shortened: } ``` -Only the owner of the task may get it; everyone else gets `403 +Only the owner of the task may get it; every other caller gets `403 Forbidden`, also admins and for unknown tasks, as for `GET /tasks/{id}` -(see [Access control](access-control.md#task-ownership)). Tasks without +(see [Access control](access-control.md#task-ownership)); requests +without a valid access token get `401 Unauthorized`. Tasks without provenance (e.g., created by earlier versions) give `404 Not Found`. The record holds no inputs, logs, IP addresses, tokens, header values or claims: plugins' changes are recorded as paths and hashes only. diff --git a/docs/upgrading.md b/docs/upgrading.md index 84090069..0c60ca8c 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -889,11 +889,12 @@ Check each item; the sections below have the details. (see [TES instance list](#tes-instance-list)). 5. **Access control rules:** custom lists of `security.access_control.policies` must add the new rules - `users-list-plugins`, `users-get-plugins`, `owners-get-provenance` and - `admins-get-provenance` (removed again, see [Unreleased - changes](#unreleased-changes)), or users get `403` (see [Task - provenance](#task-provenance)); overlays that change rules by name keep - them. + `users-list-plugins`, `users-get-plugins` and `owners-get-provenance`, + or users get `403` (see [Task provenance](#task-provenance)); overlays + that change rules by name keep them. The rule `admins-get-provenance` + of 0.4.0 is removed again in later versions: leave it out, or admins + can read the provenance of any task (see [Unreleased + changes](#unreleased-changes)). 6. **Database:** proTES uses new collections in the database of the tasks: `plugin_builds`, `pipelines` and `failed_runs` (see [Task provenance](#task-provenance)) and `plugin_store` (see [Plugin From dc8ed1ab06c577ebba33e63887b0bb130db3b52a Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sun, 6 Dec 2026 00:09:06 +0100 Subject: [PATCH 4/9] docs: drop admin provenance from permissions The Permissions API section still listed the provenance of tasks among what admins see; it is for the task's owner only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- docs/access-control.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/access-control.md b/docs/access-control.md index 38b157f0..27b20252 100644 --- a/docs/access-control.md +++ b/docs/access-control.md @@ -397,9 +397,11 @@ Admins (the role `admin`) see no task content, only: - the resources that tasks used, per user, also per user that service clients ran tasks for (`GET /usage`, see [Usage](api.md#usage)); - the same as execution reports, without user identifiers (`GET - /usage/reports`, see [Execution reports](api.md#execution-reports)); -- the provenance of a task: which plugins and TES instances processed it - (`GET /tasks/{id}/provenance`, see [Provenance](api.md#provenance)). + /usage/reports`, see [Execution reports](api.md#execution-reports)). + +Not the provenance of the tasks of others either (`GET +/tasks/{id}/provenance`, see [Provenance](api.md#provenance)): it is for +the owner of the task only. To change rules, change the config (see [Roles](#roles)) and restart proTES. Rules stored earlier through the API stay in the database and in From 3a4d03cf5f844305e40b86e74a2ad05661eaecc8 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sun, 6 Dec 2026 00:07:11 +0100 Subject: [PATCH 5/9] feat!: anonymous usage aggregates for admins `GET /usage` no longer gives admins the totals of single users. Every authenticated caller gets the totals of their own tasks and of the tasks that service clients ran for them; service clients split theirs by named user (`group_by=acting_for`). Admins also get anonymous totals over all tasks (`aggregate`), withheld (`"withheld": true`) below `custom.accounting.min_aggregate_tasks` tasks (default 5, at least 1). `user_id` and `acting_for` may only name the caller (403 otherwise, also for admins). Execution reports are unchanged. The rule `admins-get-usage` is renamed to `authenticated-get-usage`; overlays that name the old rule stop the start. BREAKING CHANGE: admins get only anonymous totals at `GET /usage`; the rule `admins-get-usage` is renamed to `authenticated-get-usage`. Closes #569 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- deployment/values.yaml | 3 +- docs/access-control.md | 21 +- docs/api.md | 98 +++--- docs/configuration.md | 18 +- docs/operations.md | 5 +- docs/upgrading.md | 33 +- pro_tes/accounting/__init__.py | 27 +- pro_tes/accounting/config.py | 6 + pro_tes/accounting/report.py | 106 +++++- pro_tes/api/additions.openapi.yaml | 72 ++++- pro_tes/config.yaml | 18 +- pro_tes/exceptions.py | 16 + pro_tes/ga4gh/tes/server.py | 75 +++-- pro_tes/security.py | 1 + tests/accounting/test_usage_endpoint.py | 408 +++++++++++++++++------- tests/ga4gh/tes/test_service_clients.py | 8 +- 16 files changed, 696 insertions(+), 219 deletions(-) diff --git a/deployment/values.yaml b/deployment/values.yaml index 78964710..2ea817f1 100644 --- a/deployment/values.yaml +++ b/deployment/values.yaml @@ -65,7 +65,8 @@ config: # off; see docs/configuration.md, Retention of finished tasks) # retention: # finished_days: 90 - # Example: record the resources that tasks used, per user, for admins + # Example: record the resources that tasks used, for their owners and, + # as anonymous totals, for admins # (`GET /usage`; default: off; see docs/configuration.md, Accounting of # resource usage) # accounting: diff --git a/docs/access-control.md b/docs/access-control.md index 27b20252..56a862f1 100644 --- a/docs/access-control.md +++ b/docs/access-control.md @@ -44,7 +44,7 @@ options](https://foca.readthedocs.io/en/latest/configuration/auth/)). | `user` | create tasks (`POST /tasks`) | | any authenticated caller | list their own tasks (`GET /tasks`), also without a role | | `owner` (of a task) | read and cancel the task (`GET /tasks/{id}`, `POST /tasks/{id}:cancel`) and get its provenance ([Provenance](api.md#provenance)) | -| `admin` | get the resources that tasks used per user ([Usage](api.md#usage)) and as execution reports ([Execution reports](api.md#execution-reports)); not the tasks of others nor their provenance, nor the access control rules (see [Permissions API](#permissions-api)) | +| `admin` | get anonymous totals of the resources that all tasks used ([Usage](api.md#usage)) and the records as execution reports ([Execution reports](api.md#execution-reports)); not the tasks of others nor their provenance or usage, nor the access control rules (see [Permissions API](#permissions-api)) | Roles are given to groups of the identity provider: the values of the claim `security.access_control.claim_groups` (from the token, or from the user info @@ -58,8 +58,9 @@ The roles and their permissions are the policies of `security.access_control.policies` in the base config (see [FOCA's access control](https://foca.readthedocs.io/en/latest/access-control/)), named rules (`users-create-tasks`, `authenticated-list-tasks`, -`owners-get-cancel-tasks`, `owners-get-provenance`, `admins-get-usage`, -`admins-get-usage-reports`, `users-list-plugins` and `users-get-plugins`): +`owners-get-cancel-tasks`, `owners-get-provenance`, +`authenticated-get-usage`, `admins-get-usage-reports`, `users-list-plugins` +and `users-get-plugins`): a config overlay adds, changes or removes (`null`) single rules by name, e.g., rules that let only users list their tasks, and owners only read them: @@ -367,8 +368,9 @@ gets no access to the task, and doesn't see it in their list. With usage](configuration.md#accounting-of-resource-usage), the usage record of the task also holds the named user (`acting_for`), which is personal data as the owner is, and kept and deleted as the records are (see [Usage -records](operations.md#usage-records)): admins can get the totals per named -user (`GET /usage?group_by=acting_for`, see [Usage](api.md#usage)); +records](operations.md#usage-records)): the named user gets the totals of +those tasks, and the client can split its totals by named user (`GET +/usage`, see [Usage](api.md#usage)); admins get only anonymous totals, and execution reports leave it out. The header is read on `POST /tasks` only, and ignored on other requests. proTES checks nothing about the named user (that the user exists, may run tasks, or consented): the client is trusted @@ -394,10 +396,11 @@ startup. Admins (the role `admin`) see no task content, only: -- the resources that tasks used, per user, also per user that service - clients ran tasks for (`GET /usage`, see [Usage](api.md#usage)); -- the same as execution reports, without user identifiers (`GET - /usage/reports`, see [Execution reports](api.md#execution-reports)). +- anonymous totals of the resources that all tasks used, withheld below a + minimum number of tasks (`GET /usage`, see [Usage](api.md#usage)); +- the usage records as execution reports, without user identifiers + (`GET /usage/reports`, see [Execution + reports](api.md#execution-reports)). Not the provenance of the tasks of others either (`GET /tasks/{id}/provenance`, see [Provenance](api.md#provenance)): it is for diff --git a/docs/api.md b/docs/api.md index 6c09d34c..e461d5c6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -16,7 +16,7 @@ control](access-control.md)). | `GET /tasks` | List the caller's tasks, newest first, one page at a time (`page_size`, at most `max_page_size` of the [config](configuration.md#tasks), and `max_page_size_full` tasks, of at most `max_page_bytes_full` bytes, for the view `FULL`; `page_token` from `next_page_token` of the previous page, which is empty on the last page), optionally only those whose name starts with `name_prefix` (taken literally; matched against the name of the task as submitted, before plugins may have renamed it), by `state`, or by tags (`tag_key` and `tag_value`, in pairs, taken literally: a key without a value, or with an empty one, matches any value of that tag; a task must match all pairs; more values than keys are rejected with `400 Bad Request`; needs MongoDB 5.0 or later). | | `GET /tasks/{id}` | Get a task of the caller, with its state as last tracked from the TES instance. | | `GET /tasks/{id}/provenance` | proTES extension: get the provenance of a task, for its owner only (see [Provenance](#provenance)). | -| `GET /usage` | proTES extension: get the resources that the tasks of each user used, for admins, if accounting is enabled (see [Usage](#usage)). | +| `GET /usage` | proTES extension: get the resources that the caller's tasks used, and anonymous totals over all tasks for admins, if accounting is enabled (see [Usage](#usage)). | | `GET /plugins` | proTES extension (FOCA's plugin listing): list the plugins and presets that the caller may choose for its tasks, and the limits, for users; the default pipeline only for callers who may choose pipelines (see [Choices of clients](plugins.md#choices-of-clients)). | | `GET /plugins/{plugin_id}` | proTES extension: describe a plugin that the caller may choose (`404 Not Found` otherwise). | | `POST /tasks/{id}:cancel` | Cancel a task of the caller that has not finished yet (also in state `UNKNOWN`, e.g., not tracked yet), at the TES instance that runs it; the task is then in state `CANCELING` until the TES instance reports its final state (usually `CANCELED`), or answers that it no longer has the task (`404` or `410`; then `CANCELED`). Meanwhile, the task stays `CANCELING`, also while the TES instance is unavailable, until the first poll after `polling.max_cancel_time` seconds (default 3600; then `SYSTEM_ERROR`, and it is no longer tracked; see [Task tracking](operations.md#task-tracking)); finished tasks are left as they are, also tasks that finish while they are canceled (their final state is kept), and tasks that the TES instance refuses to cancel as they have finished there (`200`; proTES stores their final state with the next poll). If a TES instance refuses to cancel a task that it hasn't finished, the task stays as it is (`502 Bad Gateway`). Unfinished tasks whose identifier at their TES instance is unknown (e.g., while they are being forwarded, or if forwarding failed unexpectedly) can't be canceled (`409 Conflict`). | @@ -189,14 +189,14 @@ claims: plugins' changes are recorded as paths and hashes only. ## Usage -`GET /usage` (a proTES extension) returns the resources that the tasks of -each user used, as recorded when they finished, if [accounting of resource -usage](configuration.md#accounting-of-resource-usage) is enabled: per user -(`user_id`, the owner of the tasks, `client:` for [service -clients](access-control.md#service-clients); `null` for tasks without -owner), the -number of tasks, those without known run time (`untimed_tasks`), the run -time in seconds, and the requested resources times the run time: +`GET /usage` (a proTES extension) returns the resources that tasks used, as +recorded when they finished, if [accounting of resource +usage](configuration.md#accounting-of-resource-usage) is enabled. Every +authenticated caller gets the totals of their own tasks, and of the tasks +that service clients ran for them; admins get, besides, anonymous totals over +all tasks. Nobody gets the totals of anyone else, admins neither. Each total +holds the number of tasks, those without known run time (`untimed_tasks`), +the run time in seconds, and the requested resources times the run time: ```json { @@ -204,7 +204,8 @@ time in seconds, and the requested resources times the run time: "users": [ {"user_id": "alice", "tasks": 12, "untimed_tasks": 0, "wall_seconds": 5400.0, "cpu_core_seconds": 10800.0, - "ram_gb_seconds": 21600.0, "disk_gb_seconds": 54000.0} + "ram_gb_seconds": 21600.0, "disk_gb_seconds": 54000.0}, + {"user_id": "client:engine", "acting_for": "alice", "tasks": 3, ...} ] } ``` @@ -212,14 +213,37 @@ time in seconds, and the requested resources times the run time: `recording` tells whether finishing tasks are recorded (`custom.accounting.enabled`); stored records are served either way. A total too large for a 64-bit float is the largest one (`1.7976931348623157e+308`), -as JSON has no infinity. The -query parameters limit the totals: - -- `user_id`: the tasks of one user only; -- `acting_for`: the tasks that service clients ran for one user only (named - when they created the tasks, see [Acting for - users](access-control.md#acting-for-users); in the form of `user_id`), not - the tasks that the user owns; +as JSON has no infinity. + +`users` holds the caller's totals: first those of the tasks the caller owns +(`user_id`: the caller, as owners are stored, `client:` for +[service clients](access-control.md#service-clients)), then, per service +client, those of the tasks that it ran for the caller (`user_id`: the +client, `acting_for`: the caller; see [Acting for +users](access-control.md#acting-for-users)). The list is empty if the +caller has no recorded tasks. A service client splits the totals of its own +tasks by the users it ran them for with `group_by=acting_for` (the default +is `user_id`; other values give `400 Bad Request`): its totals are then per +named user, each with `acting_for` (`null` for tasks run for no one, also +for tasks recorded by earlier versions of proTES, which didn't record the +named users), in the order of the named users: + +```json +{ + "recording": true, + "users": [ + {"user_id": "client:engine", "acting_for": "alice", "tasks": 3, ...}, + {"user_id": "client:engine", "acting_for": "bob", "tasks": 1, ...} + ] +} +``` + +The query parameters limit the totals: + +- `user_id`: only the caller's own tasks, without those that service clients + ran for the caller; it must name the caller; +- `acting_for`: only the tasks that service clients ran for the caller; it + must name the caller (both together match no tasks); - `since` and `until`: the tasks that finished at or after `since` and before `until` (date-times of RFC 3339, e.g., `2026-11-01T00:00:00Z`; UTC without time zone), by the end of the task at its TES instance, or, if that @@ -227,33 +251,33 @@ query parameters limit the totals: ISO 8601 (e.g., a date without time) and leap seconds (`:60`), give `400 Bad Request`. -Tasks that a service client ran for a user it named count for the client -(`client:`). To split its totals by those users, set -`group_by=acting_for` (the default is `user_id`; other values give `400 Bad -Request`): the totals are then per owner and named user, each with -`acting_for` (`null` for tasks run for no one, e.g., those of users, and -for tasks recorded by earlier versions of proTES, which didn't record the -named users): +`user_id` or `acting_for` naming anyone else than the caller give `403 +Forbidden`, also for admins. + +Admins (the role `admin`) also get `aggregate`: the totals over all tasks +that finished in the time range (`since`, `until`), without user +identifiers. Totals over fewer tasks than +`custom.accounting.min_aggregate_tasks` (default `5`, see [Accounting of +resource usage](configuration.md#accounting-of-resource-usage)) are +withheld, so that a narrow time range doesn't tell what single users did: +`aggregate` then holds only `"withheld": true`. ```json { "recording": true, - "users": [ - {"user_id": "alice", "acting_for": null, "tasks": 12, ...}, - {"user_id": "client:engine", "acting_for": "bob", "tasks": 3, ...} - ] + "users": [], + "aggregate": {"withheld": false, "tasks": 132, "untimed_tasks": 2, + "wall_seconds": 480000.0, "cpu_core_seconds": 960000.0, + "ram_gb_seconds": 1920000.0, "disk_gb_seconds": 4800000.0} } ``` -E.g., `GET /usage?user_id=client:engine&group_by=acting_for` gives the -totals per user that the client `engine` ran tasks for. Without -`group_by=acting_for`, the totals have no `acting_for`, also with the -`acting_for` filter. +Repeated requests over overlapping time ranges can still be compared +(differencing): the minimum makes that harder, but doesn't rule it out. -Only admins may get it (rule `admins-get-usage`); everyone else gets `403 -Forbidden` (see [Access control](access-control.md#roles)). All users are -listed in one response, in the order of their identifiers (and then of the -named users). +Every authenticated caller may get it (rule `authenticated-get-usage`); +requests without a valid access token get `401 Unauthorized` (see [Access +control](access-control.md#roles)). ### Execution reports diff --git a/docs/configuration.md b/docs/configuration.md index 6503bf39..8543f83e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -818,9 +818,9 @@ The Celery workers delete the tasks: ## Accounting of resource usage -Deployments can record which resources the tasks of each user used, and -give admins the totals per user (see [Usage](api.md#usage)). Accounting is -off by default: +Deployments can record which resources the tasks of each user used: each +caller gets the totals of their own tasks, and admins anonymous totals over +all tasks (see [Usage](api.md#usage)). Accounting is off by default: ```yaml custom: @@ -877,6 +877,18 @@ tasks](#retention-of-finished-tasks), until operators delete them (see [Usage records](operations.md#usage-records)). Turning accounting off stops the recording; stored records are still served. +Admins get the totals over all tasks only if they cover at least +`min_aggregate_tasks` tasks (default `5`; at least `1`); totals over fewer +tasks, e.g., of a narrow time range with one user's tasks, are withheld, +so that they don't tell what single users did: + +```yaml +custom: + accounting: + enabled: true + min_aggregate_tasks: 20 +``` + ### Execution reports Admins get the records as execution reports of the Tool Execution Report diff --git a/docs/operations.md b/docs/operations.md index bf979203..d70551e3 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -319,8 +319,9 @@ finished at its TES instance has a record in the collection `usage` (by task identifier, `_id`), with its owner (`user_id`) and, for tasks that a service client ran for a user it named (see [Acting for users](access-control.md#acting-for-users)), that user (`acting_for`, in -the form of owners; `null` otherwise), and admins get the totals per user -at [`GET /usage`](api.md#usage), also per named user. The records hold the +the form of owners; `null` otherwise); each caller gets the totals of +their own tasks at [`GET /usage`](api.md#usage), admins also anonymous +totals over all tasks. The records hold the subject identifiers of the owner and the named user, which are personal data: they are kept until you delete them, also after their tasks are deleted (by the [retention of finished diff --git a/docs/upgrading.md b/docs/upgrading.md index 0c60ca8c..c589696b 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -15,6 +15,33 @@ changes](#unreleased-changes)). ## Unreleased changes +**Usage: own totals for everyone, anonymous totals for admins (breaking +change, rule renamed, new setting):** `GET /usage` no longer gives admins +the totals of single users. Every authenticated caller now gets the totals +of their own tasks and of the tasks that service clients ran for them +(`users`); service clients split theirs by named user with +`group_by=acting_for`. Admins get, besides, anonymous totals over all tasks +(`aggregate`), limited only by `since` and `until`, and withheld (`"withheld": +true`) if they cover fewer tasks than the new setting +`custom.accounting.min_aggregate_tasks` (default `5`, see [Accounting of +resource usage](configuration.md#accounting-of-resource-usage)). `user_id` +and `acting_for` may only name the caller: naming anyone else gives `403 +Forbidden`, also for admins. Before, only admins could get the usage, of +every user. Scripts that read per-user totals with an admin's token get +only the anonymous totals now; per-user accounting, e.g., for billing, +needs each user's own token. Execution reports (`GET /usage/reports`) are +unchanged. + +The rule `admins-get-usage` is renamed to `authenticated-get-usage` (any +authenticated caller; the controller decides what each caller gets). If a +config overlay of yours names `admins-get-usage`, proTES refuses to start: +rename the entry, or drop it (an overlay that removes it, `null`, stops the +start with FOCA's error naming the unknown rule). To keep the usage from +everyone, set `authenticated-get-usage: null`. Custom lists of +`security.access_control.policies` must replace the rule, or callers get +`403`. During a rolling upgrade, instances of earlier versions still give +admins the totals per user, until the last of them is replaced. + **Provenance for owners only (breaking change, rule removed):** `GET /tasks/{id}/provenance` is now allowed for the owner of the task only: admins get `403 Forbidden`, like everyone else who doesn't own the task, @@ -213,7 +240,8 @@ users](access-control.md#acting-for-users)) now hold that user or clear it on request as described in [Usage records](operations.md#usage-records). Admins can split the totals of `GET /usage` by those users (`group_by=acting_for`) or limit them to one -(`acting_for=`, see [Usage](api.md#usage)); the default response is +(`acting_for=`, see [Usage](api.md#usage); no longer since the +[unreleased changes](#unreleased-changes)); the default response is unchanged, and execution reports still hold no personal data. Records written by earlier versions (also by Celery workers not yet updated during a rolling update) have no `acting_for` and count as run for no one. To @@ -444,7 +472,8 @@ instance, with its owner, and admins get the totals per user at `GET /usage` you set it (see [Accounting of resource usage](configuration.md#accounting-of-resource-usage)). Tasks that finished before are not recorded. The endpoint needs the new rule `admins-get-usage` -of the base config: overlays whose policies are a list (which replaces all +(renamed later, see [Unreleased changes](#unreleased-changes)) of the base +config: overlays whose policies are a list (which replaces all rules) must add it, or admins get `403`. proTES creates the collection `usage` with two indexes (`finished_at`; `user_id`, `finished_at`) on its first start, also while accounting is off; the records are kept until you diff --git a/pro_tes/accounting/__init__.py b/pro_tes/accounting/__init__.py index 9393c996..86c03d4f 100644 --- a/pro_tes/accounting/__init__.py +++ b/pro_tes/accounting/__init__.py @@ -3,8 +3,10 @@ Deployments may record, for each task that finished at its TES instance, which resources it used: how long it ran (wall-clock time, from the logs of its TES instance), and the resources it requested (`resources` of the task: -CPU cores, RAM, disk), multiplied by that time. Admins get the totals per -user via the API (`GET /usage`). Off by default (cf. `custom.accounting`). +CPU cores, RAM, disk), multiplied by that time. Each caller gets the totals +of their own tasks via the API (`GET /usage`), and admins anonymous totals +over all tasks, withheld below a minimum number of tasks. Off by default +(cf. `custom.accounting`). TES instances don't report the resources that tasks consumed, so the records hold allocations, as requested, not measurements; the time is that of the @@ -13,8 +15,8 @@ Each record holds the owner of the task (`user_id`, the subject identifier that the task document holds already), the user that a service client ran -the task for (`acting_for`, likewise; admins may get the totals per such -user), the task identifier, the TES instance, its final state, the times +the task for (`acting_for`, likewise; that user gets the totals of such +tasks), the task identifier, the TES instance, its final state, the times and the numbers; nothing else of the task. Records are kept apart from the tasks, so that the retention of finished tasks (:py:mod:`pro_tes.retention`) doesn't remove them; operators delete them (see `docs/operations.md`). @@ -32,22 +34,29 @@ The module is self-contained: the Celery worker calls :py:func:`record_usage` once a task finished at its TES instance, before its final state is stored, and the controllers of `GET /usage` and `GET -/usage/reports` call :py:func:`usage_totals` and -:py:func:`execution_reports`. It uses no other part of proTES than the -fields of stored tasks (`user_id`, `acting_for`, `task.id`, `task.resources`, -`task.executors[].image`, `task.tags`). +/usage/reports` call :py:func:`own_usage_totals`, +:py:func:`aggregate_totals` and :py:func:`execution_reports`. It uses no +other part of proTES than the fields of stored tasks (`user_id`, +`acting_for`, `task.id`, `task.resources`, `task.executors[].image`, +`task.tags`). """ from pro_tes.accounting.config import Accounting, ExecutionReports from pro_tes.accounting.record import record_usage, usage_record -from pro_tes.accounting.report import usage_totals +from pro_tes.accounting.report import ( + aggregate_totals, + own_usage_totals, + usage_totals, +) from pro_tes.accounting.reports import TooManyRecords, execution_reports __all__ = [ "Accounting", "ExecutionReports", "TooManyRecords", + "aggregate_totals", "execution_reports", + "own_usage_totals", "record_usage", "usage_record", "usage_totals", diff --git a/pro_tes/accounting/config.py b/pro_tes/accounting/config.py index 924cacd2..2934b35b 100644 --- a/pro_tes/accounting/config.py +++ b/pro_tes/accounting/config.py @@ -262,13 +262,19 @@ class Accounting(BaseModel): served either way. reports: What the execution reports of the records name (cf. :py:mod:`pro_tes.accounting.reports`). + min_aggregate_tasks: The minimum number of tasks of the anonymous + totals that admins get (`GET /usage`); totals over fewer tasks + are withheld, so that they don't tell what single users did. Attributes: enabled: Whether the resources of finished tasks are recorded. reports: What the execution reports of the records name. + min_aggregate_tasks: The minimum number of tasks of anonymous + totals (at least 1). """ model_config = ConfigDict(extra="forbid") enabled: bool = False reports: ExecutionReports = ExecutionReports() + min_aggregate_tasks: int = Field(default=5, ge=1) diff --git a/pro_tes/accounting/report.py b/pro_tes/accounting/report.py index e5cdeceb..d01c508f 100644 --- a/pro_tes/accounting/report.py +++ b/pro_tes/accounting/report.py @@ -1,4 +1,4 @@ -"""Totals of the resources that tasks used, per user.""" +"""Totals of the resources that tasks used: per user, or anonymous.""" from datetime import datetime import math @@ -116,3 +116,107 @@ def usage_totals( # sums of finite records may still overflow report.append({**key, **{k: _cap(v) for k, v in total.items()}}) return report + + +def own_usage_totals( + usage: Collection[dict[str, Any]], + owner: str, + since: datetime | None = None, + until: datetime | None = None, + group_by: str = "user_id", + owned: bool = True, + acted_for: bool = True, +) -> list[dict[str, Any]]: + """Get the totals of the resources that the tasks of a caller used. + + The tasks that the caller owns, and the tasks that service clients ran + for the caller (`acting_for`), which the clients own; no totals of + anyone else. + + Args: + usage: Database collection of the records (cf. + :py:func:`pro_tes.accounting.record_usage`). + owner: The caller, as owners are stored (`user_id`, cf. + :py:func:`pro_tes.ga4gh.tes.ownership.get_owner`); users that + service clients ran tasks for are stored in the same form. + since: Only tasks that finished at or after this time. + until: Only tasks that finished before this time. + group_by: Totals of the caller's own tasks in one row (`user_id`, + the default), or per user that the caller, as a service client, + ran them for (`acting_for`). + owned: Whether to include the totals of the caller's own tasks. + acted_for: Whether to include the totals of the tasks that service + clients ran for the caller. + + Returns: + The totals of the caller's own tasks (cf. :py:func:`usage_totals`), + then those of the tasks that service clients ran for the caller, + per service client (`user_id`) and with `acting_for`, in the order + of the clients. + + Raises: + ValueError: `group_by` is no grouping of :py:data:`GROUPINGS`. + """ + totals: list[dict[str, Any]] = [] + if owned: + totals += usage_totals( + usage, user_id=owner, since=since, until=until, group_by=group_by + ) + if acted_for: + totals += [ + total + for total in usage_totals( + usage, + since=since, + until=until, + acting_for=owner, + group_by="acting_for", + ) + # counted with the caller's own tasks already + if total["user_id"] != owner + ] + return totals + + +def aggregate_totals( + usage: Collection[dict[str, Any]], + min_tasks: int, + since: datetime | None = None, + until: datetime | None = None, +) -> dict[str, Any]: + """Get anonymous totals of the resources that all tasks used. + + Totals over few tasks can tell what single users did (e.g., in a narrow + time range with one user's tasks), so they are withheld below a minimum + number of tasks. + + Args: + usage: Database collection of the records (cf. + :py:func:`pro_tes.accounting.record_usage`). + min_tasks: The minimum number of tasks of totals that are given + (cf. `custom.accounting.min_aggregate_tasks`). + since: Only tasks that finished at or after this time. + until: Only tasks that finished before this time. + + Returns: + Whether the totals are withheld (`withheld`), as they cover fewer + tasks than `min_tasks`; if not, the number of tasks (`tasks`), of + those whose run time is unknown (`untimed_tasks`), and the sums of + their run times (`wall_seconds`) and resource-seconds, as in + :py:func:`usage_totals`, without user identifiers. + """ + group: dict[str, Any] = { + "_id": None, + "tasks": {"$sum": 1}, + "untimed_tasks": {"$sum": {"$cond": ["$timed", 0, 1]}}, + } + for field in SUMMED: + group[field] = {"$sum": f"${field}"} + totals = list( + usage.aggregate([{"$match": finished_range(since, until)}, {"$group": group}]) + ) + if not totals or totals[0]["tasks"] < min_tasks: + return {"withheld": True} + total = totals[0] + total.pop("_id") + return {"withheld": False, **{k: _cap(v) for k, v in total.items()}} diff --git a/pro_tes/api/additions.openapi.yaml b/pro_tes/api/additions.openapi.yaml index 4b104003..79471c73 100644 --- a/pro_tes/api/additions.openapi.yaml +++ b/pro_tes/api/additions.openapi.yaml @@ -93,33 +93,39 @@ paths: - TaskService summary: GetUsage description: |- - proTES extension: get the resources that tasks used, per user, as - recorded when they finished at their TES instances (if + proTES extension: get the resources that tasks used, as recorded + when they finished at their TES instances (if `custom.accounting.enabled`): the number of tasks, their run times, - and the resources they requested times their run times. For admins. + and the resources they requested times their run times. Every caller + gets the totals of their own tasks and of the tasks that service + clients ran for them; admins also get anonymous totals over all + tasks (`aggregate`). Nobody gets the totals of anyone else. operationId: GetUsage parameters: - name: user_id in: query required: false - description: Only the tasks of this user (their owner, `user_id`). + description: >- + Only the caller's own tasks (`user_id`), not those that service + clients ran for the caller; must name the caller. schema: type: string - name: acting_for in: query required: false description: >- - Only the tasks that service clients ran for this user (named when - they created the tasks, in the form of owners; `acting_for`), not - those that the user owns. + Only the tasks that service clients ran for the caller (named + when they created the tasks, in the form of owners; `acting_for`), + not those that the caller owns; must name the caller. schema: type: string - name: group_by in: query required: false description: >- - Totals per owner of the tasks (`user_id`, the default), or per owner - and the user that a service client ran the tasks for (`acting_for`). + Totals of the caller's own tasks in one row (`user_id`, the + default), or per user that the caller, a service client, ran them + for (`acting_for`). schema: type: string enum: @@ -144,7 +150,7 @@ paths: type: string responses: 200: - description: The totals per user. + description: The caller's totals, and anonymous totals for admins. content: application/json: schema: @@ -158,7 +164,9 @@ paths: schema: $ref: '#/components/schemas/ProblemDetails' 403: - description: The caller is not an admin. + description: >- + `user_id` or `acting_for` names someone else than the caller + (also for admins). content: application/json: schema: @@ -224,7 +232,8 @@ components: schemas: UsageReport: description: >- - The resources that tasks used, per user (proTES extension). + The resources that the caller's tasks used, and, for admins, all + tasks (proTES extension). type: object required: - recording @@ -238,9 +247,46 @@ components: way. users: type: array - description: Totals per user, in the order of their identifiers. + description: >- + The caller's totals: of the tasks the caller owns, then, per + service client, of the tasks that it ran for the caller (with + `acting_for`). items: $ref: '#/components/schemas/UserUsage' + aggregate: + $ref: '#/components/schemas/AggregateUsage' + AggregateUsage: + description: >- + For admins only: anonymous totals over all tasks that finished in + the time range, without user identifiers; withheld if they cover + fewer tasks than `custom.accounting.min_aggregate_tasks`. + type: object + required: + - withheld + properties: + withheld: + type: boolean + description: >- + Whether the totals are withheld, as they cover too few tasks; + the other fields are then left out. + tasks: + type: integer + description: Number of tasks. + untimed_tasks: + type: integer + description: Number of the tasks whose run time is unknown. + wall_seconds: + type: number + description: Run time of the tasks, in seconds. + cpu_core_seconds: + type: number + description: Requested CPU cores times run time. + ram_gb_seconds: + type: number + description: Requested RAM (GB) times run time. + disk_gb_seconds: + type: number + description: Requested disk (GB) times run time. UserUsage: description: >- The resources that the tasks of a user used: allocations (the diff --git a/pro_tes/config.yaml b/pro_tes/config.yaml index 52ce736b..ac7450e0 100644 --- a/pro_tes/config.yaml +++ b/pro_tes/config.yaml @@ -63,8 +63,8 @@ security: # authenticated caller may list their own; the user creating a task becomes # its owner, and only owners may read and cancel a task and get its # provenance, also after losing the role `user`. Admins (the role `admin`) - # may only read the usage per user and the execution reports, not the - # tasks of others nor their provenance. Roles are given to groups of the + # may only read anonymous usage totals and the execution reports, not the + # tasks of others nor their provenance, nor the usage of single users. Roles are given to groups of the # identity provider (values of the claim `claim_groups`) by # `group_mapping`, e.g.: # claim_groups: groups @@ -99,8 +99,10 @@ security: owners-get-cancel-tasks: [p, owner, "/ga4gh/tes/v1/tasks/:id", (GET)|(HEAD)|(POST)] # the provenance of a task, for its owner only (not for admins either) owners-get-provenance: [p, owner, "/ga4gh/tes/v1/tasks/:id/provenance", (GET)|(HEAD)] - # the resources that tasks used, per user (`custom.accounting`) - admins-get-usage: [p, admin, /ga4gh/tes/v1/usage, (GET)|(HEAD)] + # the resources that tasks used (`custom.accounting`): every + # authenticated caller gets the totals of their own tasks, admins also + # anonymous totals over all tasks (checked by the controller) + authenticated-get-usage: [p, "*", /ga4gh/tes/v1/usage, (GET)|(HEAD)] # the same records as execution reports, without user identifiers admins-get-usage-reports: [p, admin, /ga4gh/tes/v1/usage/reports, (GET)|(HEAD)] # what users may choose per task (FOCA's plugin listing) @@ -439,12 +441,16 @@ custom: # Accounting of the resources that tasks used, per user, off by default: # the Celery workers record the run time of each task that finished at its # TES instance and the resources it requested, with its owner (`user_id`); - # admins get the totals per user at `GET /usage` (see `docs/configuration.md`) - # and the records as execution reports at `GET /usage/reports`, which name + # each caller gets the totals of their own tasks at `GET /usage`, admins + # also anonymous totals (see `docs/configuration.md`), and admins get the + # records as execution reports at `GET /usage/reports`, which name # the providers and locations of `reports` (see `docs/configuration.md`, # Execution reports) accounting: enabled: false + # admins get anonymous totals at `GET /usage` only over at least this + # many tasks (at least 1); fewer are withheld + min_aggregate_tasks: 5 reports: max_records: 10000 infra: [] diff --git a/pro_tes/exceptions.py b/pro_tes/exceptions.py index 0cfa4e37..a831193f 100644 --- a/pro_tes/exceptions.py +++ b/pro_tes/exceptions.py @@ -170,6 +170,14 @@ class InvalidUsageTime(BadRequest): """ +class UsageOfOthers(Forbidden): + """Raised when a request for the usage of tasks names someone else. + + Cf. the query parameters `user_id` and `acting_for` of `GET /usage`: + every caller gets only the totals of their own tasks, admins too. + """ + + class TooManyUsageRecords(BadRequest): """Raised when a request for execution reports covers too many tasks. @@ -247,6 +255,14 @@ class TaskNotCancelable(Conflict): "detail": "`since` or `until` is no valid time (RFC 3339).", "status": 400, }, + UsageOfOthers: { + "title": "Forbidden", + "detail": ( + "The usage of the tasks of others can't be requested; `user_id`" + " and `acting_for` may only name the caller." + ), + "status": 403, + }, TooManyUsageRecords: { "title": "Bad request", "detail": ( diff --git a/pro_tes/ga4gh/tes/server.py b/pro_tes/ga4gh/tes/server.py index e284f4b0..c983000b 100644 --- a/pro_tes/ga4gh/tes/server.py +++ b/pro_tes/ga4gh/tes/server.py @@ -15,11 +15,19 @@ problem, request_id, ) +from foca.security.access_control import get_current_roles +from foca.security.access_control.constants import ADMIN_ROLE from foca.utils.logging import log_traffic -from pro_tes.accounting import TooManyRecords, execution_reports, usage_totals +from pro_tes.accounting import ( + TooManyRecords, + aggregate_totals, + execution_reports, + own_usage_totals, +) from pro_tes.config_models import CustomConfig -from pro_tes.exceptions import InvalidUsageTime, TooManyUsageRecords +from pro_tes.exceptions import InvalidUsageTime, TooManyUsageRecords, UsageOfOthers +from pro_tes.ga4gh.tes.ownership import get_owner from pro_tes.ga4gh.tes.task_runs import TaskRuns from pro_tes.utils.db import TASK_DB, USAGE_COLLECTION @@ -126,35 +134,58 @@ def GetTaskProvenance(id: str, *args: Any, **kwargs: Any) -> dict[str, Any]: # GET /usage @log_traffic def GetUsage(*args: Any, **kwargs: Any) -> dict[str, Any]: - """Get the resources that tasks used, per user (proTES extension). + """Get the resources that tasks used (proTES extension). - For admins only (enforced by the policies). + For every authenticated caller (enforced by the policies): the totals of + the caller's own tasks and of the tasks that service clients ran for the + caller; for admins, also anonymous totals over all tasks. Nobody gets + the totals of anyone else. Args: *args: Variable length argument list. - **kwargs: Arbitrary keyword arguments: the user (`user_id`), the - user that service clients ran the tasks for (`acting_for`) and - the time range (`since`, `until`) of the tasks, if any, and the - grouping of the totals (`group_by`, checked against the API - spec). + **kwargs: Arbitrary keyword arguments: the caller as owner of the + tasks (`user_id`) or as the user that service clients ran them + for (`acting_for`), and the time range (`since`, `until`) of the + tasks, if any, and the grouping of the totals (`group_by`, + checked against the API spec). Returns: Whether resources are recorded (`recording`, cf. - `custom.accounting.enabled`), and the totals per user (`users`, cf. - :py:func:`pro_tes.accounting.usage_totals`). + `custom.accounting.enabled`), the caller's totals (`users`, cf. + :py:func:`pro_tes.accounting.own_usage_totals`), and, for admins, + the anonymous totals (`aggregate`, cf. + :py:func:`pro_tes.accounting.aggregate_totals`). + + Raises: + pro_tes.exceptions.UsageOfOthers: `user_id` or `acting_for` names + someone else than the caller. """ - totals = usage_totals( - get_collection(TASK_DB, USAGE_COLLECTION), - user_id=kwargs.get("user_id"), - since=_parse_time(kwargs.get("since"), "since"), - until=_parse_time(kwargs.get("until"), "until"), - acting_for=kwargs.get("acting_for"), - group_by=kwargs.get("group_by", "user_id"), - ) - return { - "recording": get_custom_config(CustomConfig).accounting.enabled, - "users": totals, + owner = get_owner() + user_id = kwargs.get("user_id") + acting_for = kwargs.get("acting_for") + if any(name not in (None, owner) for name in (user_id, acting_for)): + raise UsageOfOthers + since = _parse_time(kwargs.get("since"), "since") + until = _parse_time(kwargs.get("until"), "until") + usage = get_collection(TASK_DB, USAGE_COLLECTION) + accounting = get_custom_config(CustomConfig).accounting + report: dict[str, Any] = { + "recording": accounting.enabled, + "users": own_usage_totals( + usage, + owner=owner, + since=since, + until=until, + group_by=kwargs.get("group_by", "user_id"), + owned=acting_for is None, + acted_for=user_id is None, + ), } + if ADMIN_ROLE in get_current_roles(): + report["aggregate"] = aggregate_totals( + usage, accounting.min_aggregate_tasks, since=since, until=until + ) + return report # GET /usage/reports diff --git a/pro_tes/security.py b/pro_tes/security.py index b6aa44b9..de9226ab 100644 --- a/pro_tes/security.py +++ b/pro_tes/security.py @@ -52,6 +52,7 @@ def check_task_ownership() -> None: RENAMED_RULES: dict[str, tuple[str, ...]] = { "users-create-list-tasks": ("users-create-tasks", "authenticated-list-tasks"), + "admins-get-usage": ("authenticated-get-usage",), } diff --git a/tests/accounting/test_usage_endpoint.py b/tests/accounting/test_usage_endpoint.py index b88cc077..d3f9fc95 100644 --- a/tests/accounting/test_usage_endpoint.py +++ b/tests/accounting/test_usage_endpoint.py @@ -1,4 +1,9 @@ -"""Tests of serving the resources that tasks used, per user (`GET /usage`).""" +"""Tests of serving the resources that tasks used (`GET /usage`). + +Every caller gets the totals of their own tasks and of the tasks that +service clients ran for them; admins get, besides, anonymous totals over all +tasks, withheld below a minimum number of tasks (#569). +""" from datetime import UTC, datetime, timedelta from pathlib import Path @@ -7,6 +12,7 @@ from connexion import FlaskApp from flask.testing import FlaskClient from foca import get_custom_config +from pydantic import ValidationError from pymongo import MongoClient import pytest import tes @@ -14,6 +20,7 @@ from pro_tes.accounting import Accounting, usage_record from pro_tes.accounting.report import GROUPINGS +from pro_tes.app import init_app from pro_tes.config_models import CustomConfig from tests.conftest import ( ADMIN, @@ -23,127 +30,306 @@ OUTSIDER, USER, make_headers, + reset_gateway, + set_overlays, + subject, +) +from tests.ga4gh.tes.test_service_clients import ( + CLIENT_OWNER, + client_headers, + service_overlay, + use_overlay, ) PATH = "/ga4gh/tes/v1/usage" -SPEC = Path(__file__).parents[2] / "pro_tes" / "api" / "additions.openapi.yaml" +ROOT = Path(__file__).parents[2] +SPEC = ROOT / "pro_tes" / "api" / "additions.openapi.yaml" START = datetime(2026, 11, 1, tzinfo=UTC) +# Totals of one task of `record()` (1 CPU core, for an hour) +ONE_TASK = { + "tasks": 1, + "untimed_tasks": 0, + "wall_seconds": 3600.0, + "cpu_core_seconds": 3600.0, + "ram_gb_seconds": 0.0, + "disk_gb_seconds": 0.0, +} + + +def record( + mongo_client: MongoClient[dict[str, Any]], + task_id: str, + user_id: str, + day: int = 0, + acting_for: str | None = None, +) -> None: + """Store the usage record of a task that ran for an hour with 1 CPU core. + + Args: + mongo_client: The MongoDB client. + task_id: Identifier of the task. + user_id: Owner of the task, as stored. + day: Days after `START` that the task started. + acting_for: The user that a service client ran the task for, if any. + """ + start = START + timedelta(days=day) + document: dict[str, Any] = { + "user_id": user_id, + "task": {"id": task_id, "resources": {"cpu_cores": 1}}, + } + if acting_for is not None: + document["acting_for"] = acting_for + mongo_client[DB]["usage"].insert_one( + usage_record( + document=document, + logs=[tes.TaskLog(start_time=start, end_time=start + timedelta(hours=1))], + backend="https://tes.example.org", + state="COMPLETE", + now=start + timedelta(hours=2), + ) + ) @pytest.fixture def records(mongo_client: MongoClient[dict[str, Any]]) -> None: - """Records of a task of `USER` and one of `ADMIN_USER`, a day apart.""" - for day, (task_id, user_id) in enumerate((("T1", USER), ("T2", ADMIN_USER))): - start = START + timedelta(days=day) - document = { - "user_id": user_id, - "task": {"id": task_id, "resources": {"cpu_cores": 2}}, - } - mongo_client[DB]["usage"].insert_one( - usage_record( - document=document, - logs=[ - tes.TaskLog(start_time=start, end_time=start + timedelta(hours=1)) - ], - backend="https://tes.example.org", - state="COMPLETE", - now=start + timedelta(hours=2), - ) + """Records of a task of `USER` and one of `ADMIN_USER`, a day apart. + + And one of a task that the service client `engine` ran for `OTHER_USER`, + on the first day. + """ + record(mongo_client, "T1", subject(USER)) + record(mongo_client, "T2", subject(ADMIN_USER), day=1) + record(mongo_client, "T3", "client:engine", acting_for=subject(OTHER_USER)) + + +def set_minimum(app: FlaskApp, minimum: int) -> None: + """Set the minimum number of tasks of anonymous totals. + + Args: + app: The app. + minimum: The minimum (`custom.accounting.min_aggregate_tasks`). + """ + with app.app.app_context(): + get_custom_config(CustomConfig).accounting = Accounting( + min_aggregate_tasks=minimum ) -@pytest.mark.parametrize("user", [ADMIN, ADMIN_USER]) -def test_get_usage(client: FlaskClient, records: None, user: str) -> None: - """Admins get the totals per user; by default, nothing is recorded.""" - response = client.get(PATH, headers=make_headers(user)) +def test_get_own_usage(client: FlaskClient, records: None) -> None: + """Users get the totals of their own tasks only, without anonymous totals. + + By default, nothing is recorded. + """ + response = client.get(PATH) assert response.status_code == 200 - report = response.get_json() - assert report["recording"] is False - assert [total["user_id"] for total in report["users"]] == [USER, ADMIN_USER] - assert report["users"][0] == { - "user_id": USER, - "tasks": 1, - "untimed_tasks": 0, - "wall_seconds": 3600.0, - "cpu_core_seconds": 7200.0, - "ram_gb_seconds": 0.0, - "disk_gb_seconds": 0.0, + assert response.get_json() == { + "recording": False, + "users": [{"user_id": subject(USER), **ONE_TASK}], } -def test_get_usage_filtered(client: FlaskClient, records: None) -> None: - """Admins may filter by user and time range. +def test_get_usage_acting_for(client: FlaskClient, records: None) -> None: + """Users get the totals of the tasks service clients ran for them. - UTC without time zone; `t` and `z` may be lowercase, as in RFC 3339. + As a row of their own, per service client, with `acting_for`. """ - headers = make_headers(ADMIN) - response = client.get(PATH, query_string={"user_id": USER}, headers=headers) - assert [total["user_id"] for total in response.get_json()["users"]] == [USER] + response = client.get(PATH, headers=make_headers(OTHER_USER)) + assert response.status_code == 200 + assert response.get_json()["users"] == [ + {"user_id": "client:engine", "acting_for": subject(OTHER_USER), **ONE_TASK} + ] + + +def test_get_usage_owned_and_acting_for( + client: FlaskClient, records: None, mongo_client: MongoClient[dict[str, Any]] +) -> None: + """Totals of own tasks come first, then those run for the user.""" + record(mongo_client, "T4", subject(OTHER_USER)) + users = client.get(PATH, headers=make_headers(OTHER_USER)).get_json()["users"] + assert users == [ + {"user_id": subject(OTHER_USER), **ONE_TASK}, + {"user_id": "client:engine", "acting_for": subject(OTHER_USER), **ONE_TASK}, + ] response = client.get( PATH, - query_string={"since": "2026-11-02t00:00:00", "until": "2026-11-03T00:00:00z"}, - headers=headers, + query_string={"group_by": "acting_for"}, + headers=make_headers(OTHER_USER), ) - assert response.status_code == 200 - assert [total["user_id"] for total in response.get_json()["users"]] == [ADMIN_USER] + assert response.get_json()["users"][0] == { + "user_id": subject(OTHER_USER), + "acting_for": None, + **ONE_TASK, + } -@pytest.fixture -def client_record(mongo_client: MongoClient[dict[str, Any]], records: None) -> None: - """The records above, and one of a task a client ran for `OTHER_USER`.""" - document = { - "user_id": "client:engine", - "acting_for": OTHER_USER, - "task": {"id": "T3", "resources": {"cpu_cores": 1}}, - } - mongo_client[DB]["usage"].insert_one( - usage_record( - document=document, - logs=[tes.TaskLog(start_time=START, end_time=START + timedelta(hours=3))], - backend="https://tes.example.org", - state="COMPLETE", - now=START + timedelta(hours=4), - ) - ) +@pytest.mark.parametrize("user", [OUTSIDER, ADMIN]) +def test_get_usage_no_own_tasks(client: FlaskClient, records: None, user: str) -> None: + """Callers without tasks, also without a role, get no rows.""" + response = client.get(PATH, headers=make_headers(user)) + assert response.status_code == 200 + assert response.get_json()["users"] == [] + +def test_get_own_usage_filtered(client: FlaskClient, records: None) -> None: + """Users may name themselves in the filters, and limit the time range. -def test_get_usage_per_acting_for(client: FlaskClient, client_record: None) -> None: - """Admins may split the totals by the users that clients ran tasks for.""" - headers = make_headers(ADMIN) + UTC without time zone; `t` and `z` may be lowercase, as in RFC 3339. + `user_id` limits the totals to own tasks, `acting_for` to the tasks run + for the user; both together match no task. + """ + me = subject(OTHER_USER) + headers = make_headers(OTHER_USER) + response = client.get(PATH, query_string={"user_id": me}, headers=headers) + assert response.get_json()["users"] == [] + response = client.get(PATH, query_string={"acting_for": me}, headers=headers) + assert [row["user_id"] for row in response.get_json()["users"]] == ["client:engine"] + response = client.get( + PATH, query_string={"user_id": me, "acting_for": me}, headers=headers + ) + assert response.get_json()["users"] == [] response = client.get( - PATH, query_string={"group_by": "acting_for"}, headers=headers + PATH, + query_string={"since": "2026-11-02t00:00:00", "until": "2026-11-03T00:00:00z"}, + headers=make_headers(ADMIN_USER), ) assert response.status_code == 200 - users = response.get_json()["users"] - assert [(total["user_id"], total["acting_for"]) for total in users] == [ - (USER, None), - (ADMIN_USER, None), - ("client:engine", OTHER_USER), + assert [row["user_id"] for row in response.get_json()["users"]] == [ + subject(ADMIN_USER) ] - assert users[2]["wall_seconds"] == 3 * 3600.0 + response = client.get( + PATH, query_string={"since": "2026-11-02T00:00:00Z"}, headers=headers + ) + assert response.get_json()["users"] == [] + + +@pytest.mark.parametrize("user", [USER, ADMIN, ADMIN_USER]) +@pytest.mark.parametrize("name", ["user_id", "acting_for"]) +def test_get_usage_of_others_forbidden( + client: FlaskClient, records: None, user: str, name: str +) -> None: + """Nobody may name others in the filters (`403`), admins neither.""" + for other in (subject(OTHER_USER), "client:engine", OTHER_USER): + response = client.get( + PATH, query_string={name: other}, headers=make_headers(user) + ) + assert response.status_code == 403 + + +@pytest.mark.parametrize("user", [ADMIN, ADMIN_USER]) +def test_get_usage_aggregate( + app: FlaskApp, client: FlaskClient, records: None, user: str +) -> None: + """Admins get anonymous totals over all tasks, besides their own totals.""" + set_minimum(app, 3) + report = client.get(PATH, headers=make_headers(user)).get_json() + assert report["aggregate"] == { + "withheld": False, + "tasks": 3, + "untimed_tasks": 0, + "wall_seconds": 3 * 3600.0, + "cpu_core_seconds": 3 * 3600.0, + "ram_gb_seconds": 0.0, + "disk_gb_seconds": 0.0, + } + own = [row["user_id"] for row in report["users"]] + assert own == ([subject(ADMIN_USER)] if user == ADMIN_USER else []) -def test_get_usage_of_client_per_acting_for( - client: FlaskClient, client_record: None +def test_get_usage_aggregate_time_range( + app: FlaskApp, client: FlaskClient, records: None ) -> None: - """The totals of one client may be split by the users it ran tasks for.""" + """The anonymous totals are limited by `since` and `until`.""" + set_minimum(app, 1) response = client.get( PATH, - query_string={"user_id": "client:engine", "group_by": "acting_for"}, + query_string={"since": "2026-11-02T00:00:00Z"}, headers=make_headers(ADMIN), ) + assert response.get_json()["aggregate"]["tasks"] == 1 + + +def test_get_usage_aggregate_withheld_default( + client: FlaskClient, records: None +) -> None: + """Totals over fewer tasks than the minimum (5 by default) are withheld.""" + report = client.get(PATH, headers=make_headers(ADMIN)).get_json() + assert report["aggregate"] == {"withheld": True} + + +@pytest.mark.parametrize(("minimum", "withheld"), [(3, False), (4, True)]) +def test_get_usage_aggregate_withheld_configured( + app: FlaskApp, client: FlaskClient, records: None, minimum: int, withheld: bool +) -> None: + """The minimum is configurable (`min_aggregate_tasks`).""" + set_minimum(app, minimum) + aggregate = client.get(PATH, headers=make_headers(ADMIN)).get_json()["aggregate"] + assert aggregate["withheld"] is withheld + assert ("tasks" in aggregate) is not withheld + + +def test_get_usage_aggregate_empty(app: FlaskApp, client: FlaskClient) -> None: + """Without records, the anonymous totals are withheld, also at minimum 1.""" + set_minimum(app, 1) + report = client.get(PATH, headers=make_headers(ADMIN)).get_json() + assert report["aggregate"] == {"withheld": True} + + +@pytest.mark.parametrize("minimum", [0, -1]) +def test_minimum_at_least_one(minimum: int) -> None: + """The minimum number of tasks of anonymous totals is at least 1.""" + with pytest.raises(ValidationError): + Accounting(min_aggregate_tasks=minimum) + + +def test_minimum_default() -> None: + """The minimum is 5 by default, also in the base config.""" + assert Accounting().min_aggregate_tasks == 5 + config = yaml.safe_load((ROOT / "pro_tes" / "config.yaml").read_text()) + assert config["custom"]["accounting"]["min_aggregate_tasks"] == 5 + + +def test_get_usage_service_client( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + app_env: None, + mongo_client: MongoClient[dict[str, Any]], +) -> None: + """Service clients get their own totals, split by named users on request.""" + use_overlay(monkeypatch, tmp_path, service_overlay()) + reset_gateway() + client = init_app().app.test_client() + record(mongo_client, "T1", CLIENT_OWNER, acting_for=subject(USER)) + record(mongo_client, "T2", CLIENT_OWNER, acting_for=subject(OTHER_USER)) + record(mongo_client, "T3", subject(USER)) + response = client.get(PATH, headers=client_headers()) assert response.status_code == 200 - users = response.get_json()["users"] - assert [(total["user_id"], total["acting_for"]) for total in users] == [ - ("client:engine", OTHER_USER) + (row,) = response.get_json()["users"] + assert (row["user_id"], row["tasks"], row["wall_seconds"]) == ( + CLIENT_OWNER, + 2, + 7200.0, + ) + response = client.get( + PATH, query_string={"group_by": "acting_for"}, headers=client_headers() + ) + rows = response.get_json()["users"] + assert [(row["user_id"], row["acting_for"]) for row in rows] == [ + (CLIENT_OWNER, subject(USER)), + (CLIENT_OWNER, subject(OTHER_USER)), ] + response = client.get( + PATH, query_string={"user_id": CLIENT_OWNER}, headers=client_headers() + ) + assert response.get_json()["users"][0]["tasks"] == 2 + response = client.get( + PATH, query_string={"acting_for": subject(USER)}, headers=client_headers() + ) + assert response.status_code == 403 def test_get_usage_group_by_invalid(client: FlaskClient) -> None: """Other groupings get `400`.""" - response = client.get( - PATH, query_string={"group_by": "state"}, headers=make_headers(ADMIN) - ) + response = client.get(PATH, query_string={"group_by": "state"}) assert response.status_code == 400 @@ -158,30 +344,11 @@ def test_get_usage_groupings_in_spec() -> None: assert parameter["schema"]["enum"] == list(GROUPINGS) -def test_get_usage_of_acting_for(client: FlaskClient, client_record: None) -> None: - """Admins may limit the totals to the tasks run for one user.""" - response = client.get( - PATH, query_string={"acting_for": OTHER_USER}, headers=make_headers(ADMIN) - ) - assert response.status_code == 200 - assert response.get_json()["users"] == [ - { - "user_id": "client:engine", - "tasks": 1, - "untimed_tasks": 0, - "wall_seconds": 3 * 3600.0, - "cpu_core_seconds": 3 * 3600.0, - "ram_gb_seconds": 0.0, - "disk_gb_seconds": 0.0, - } - ] - - def test_get_usage_recording(app: FlaskApp, client: FlaskClient) -> None: """The report tells whether usage is recorded.""" with app.app.app_context(): get_custom_config(CustomConfig).accounting = Accounting(enabled=True) - response = client.get(PATH, headers=make_headers(ADMIN)) + response = client.get(PATH) assert response.get_json() == {"recording": True, "users": []} @@ -213,17 +380,44 @@ def test_get_usage_invalid_time(client: FlaskClient, name: str, value: str) -> N ) -@pytest.mark.parametrize("user", [USER, OUTSIDER]) -def test_get_usage_forbidden(client: FlaskClient, records: None, user: str) -> None: - """Users who are not admins get `403`.""" - assert client.get(PATH, headers=make_headers(user)).status_code == 403 - - def test_get_usage_anonymous(anonymous_client: FlaskClient) -> None: """Requests without access token get `401`.""" assert anonymous_client.get(PATH).status_code == 401 +@pytest.mark.parametrize("user", [USER, OUTSIDER]) +def test_get_usage_reports_forbidden(client: FlaskClient, user: str) -> None: + """Execution reports stay for admins only.""" + response = client.get(f"{PATH}/reports", headers=make_headers(user)) + assert response.status_code == 403 + + +@pytest.mark.parametrize("rule", [["p", "admin", PATH, "(GET)|(HEAD)"], None]) +def test_old_usage_rule_refused( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + app_env: None, + rule: list[str] | None, +) -> None: + """Overlays that name the former rule `admins-get-usage` stop the start. + + A rule under the old name is refused (it was renamed to + `authenticated-get-usage`); removing it (`null`) is refused by FOCA, as + the rule is no longer in the base config. + """ + overlay = tmp_path / "policies.yaml" + overlay.write_text( + yaml.safe_dump( + {"security": {"access_control": {"policies": {"admins-get-usage": rule}}}} + ), + encoding="utf-8", + ) + set_overlays(monkeypatch, overlay) + reset_gateway() + with pytest.raises((RuntimeError, ValueError), match="admins-get-usage"): + init_app() + + def test_usage_indexes( app: FlaskApp, mongo_client: MongoClient[dict[str, Any]] ) -> None: diff --git a/tests/ga4gh/tes/test_service_clients.py b/tests/ga4gh/tes/test_service_clients.py index 93fb9268..e70b33af 100644 --- a/tests/ga4gh/tes/test_service_clients.py +++ b/tests/ga4gh/tes/test_service_clients.py @@ -421,13 +421,7 @@ def test_user_named_as_client( assert response.status_code == 403 -@pytest.mark.parametrize( - "method, path", - [ - ("GET", f"{BASE_PATH}/usage"), - ("GET", f"{BASE_PATH}/usage/reports"), - ], -) +@pytest.mark.parametrize("method, path", [("GET", f"{BASE_PATH}/usage/reports")]) def test_nothing_beyond(service_client: FlaskClient, method: str, path: str) -> None: """Service clients have no admin rights (`403`).""" response = service_client.open(path, method=method, headers=client_headers()) From 07dae3ca523c0cfeb2a226762da824fc54fb4871 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sun, 6 Dec 2026 00:27:09 +0100 Subject: [PATCH 6/9] refactor: share usage sums and test them directly Review fixes for #569: `own_usage_totals` and `aggregate_totals` share the accumulators of `usage_totals` and get unit tests; the flags are named `include_owned` and `include_acted_for`. The docs no longer claim more than the minimum gives: it counts tasks, not users, and doesn't stop differencing. `user_id` takes the stored (namespaced) form. More endpoint tests (HEAD, grouping of aggregates, error detail, the error of each overlay of the old rule); comments re-wrapped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- docs/api.md | 15 ++- docs/configuration.md | 4 +- pro_tes/accounting/report.py | 52 +++++---- pro_tes/api/additions.openapi.yaml | 6 +- pro_tes/config.yaml | 8 +- pro_tes/ga4gh/tes/server.py | 6 +- tests/accounting/test_report.py | 138 +++++++++++++++++++++++- tests/accounting/test_usage_endpoint.py | 43 ++++++-- 8 files changed, 226 insertions(+), 46 deletions(-) diff --git a/docs/api.md b/docs/api.md index e461d5c6..cf9b375c 100644 --- a/docs/api.md +++ b/docs/api.md @@ -241,7 +241,9 @@ named users), in the order of the named users: The query parameters limit the totals: - `user_id`: only the caller's own tasks, without those that service clients - ran for the caller; it must name the caller; + ran for the caller; it must name the caller, in the form of `user_id` in + the response (by default namespaced by issuer, `|`, see + [Task owners](operations.md#task-owners)); - `acting_for`: only the tasks that service clients ran for the caller; it must name the caller (both together match no tasks); - `since` and `until`: the tasks that finished at or after `since` and @@ -259,8 +261,8 @@ that finished in the time range (`since`, `until`), without user identifiers. Totals over fewer tasks than `custom.accounting.min_aggregate_tasks` (default `5`, see [Accounting of resource usage](configuration.md#accounting-of-resource-usage)) are -withheld, so that a narrow time range doesn't tell what single users did: -`aggregate` then holds only `"withheld": true`. +withheld, so that a narrow time range with few tasks doesn't tell what +single users did: `aggregate` then holds only `"withheld": true`. ```json { @@ -272,8 +274,11 @@ withheld, so that a narrow time range doesn't tell what single users did: } ``` -Repeated requests over overlapping time ranges can still be compared -(differencing): the minimum makes that harder, but doesn't rule it out. +The minimum is no privacy guarantee: it counts tasks, not users (one +user's five tasks in a time range are given), and an admin can compare the +totals of overlapping time ranges (differencing), e.g., two ranges that +differ by one second, to get the totals of the tasks that finished in +between. Every authenticated caller may get it (rule `authenticated-get-usage`); requests without a valid access token get `401 Unauthorized` (see [Access diff --git a/docs/configuration.md b/docs/configuration.md index 8543f83e..664727bd 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -880,7 +880,9 @@ the recording; stored records are still served. Admins get the totals over all tasks only if they cover at least `min_aggregate_tasks` tasks (default `5`; at least `1`); totals over fewer tasks, e.g., of a narrow time range with one user's tasks, are withheld, -so that they don't tell what single users did: +so that they don't tell what single users did. The minimum counts tasks, +not users, and doesn't stop admins from comparing overlapping time ranges +(see [Usage](api.md#usage)): ```yaml custom: diff --git a/pro_tes/accounting/report.py b/pro_tes/accounting/report.py index d01c508f..004573ee 100644 --- a/pro_tes/accounting/report.py +++ b/pro_tes/accounting/report.py @@ -9,7 +9,7 @@ from pro_tes.accounting.record import RESOURCES -# Fields of the records that are summed up per user +# Fields of the records that are summed up in totals SUMMED = ("wall_seconds", *RESOURCES.values()) # Groupings of the totals (`group_by` of :py:func:`usage_totals`), by the @@ -36,6 +36,23 @@ def _cap(value: Any) -> Any: return value +def _sums() -> dict[str, Any]: + """Get the accumulators of totals, for a `$group` stage. + + Returns: + The number of tasks (`tasks`), of those whose run time is unknown + (`untimed_tasks`), and the sums of the fields of + :py:data:`SUMMED`. + """ + sums: dict[str, Any] = { + "tasks": {"$sum": 1}, + "untimed_tasks": {"$sum": {"$cond": ["$timed", 0, 1]}}, + } + for field in SUMMED: + sums[field] = {"$sum": f"${field}"} + return sums + + def finished_range( since: datetime | None = None, until: datetime | None = None ) -> dict[str, Any]: @@ -65,7 +82,7 @@ def usage_totals( acting_for: str | None = None, group_by: str = "user_id", ) -> list[dict[str, Any]]: - """Get the totals of the resources that tasks used, per user. + """Get the totals of the resources that tasks used, per owner. Args: usage: Database collection of the records (cf. @@ -103,11 +120,8 @@ def usage_totals( # missing fields (e.g., `acting_for` of records of earlier versions) # count as `None`, rather than as groups of their own "_id": {field: {"$ifNull": [f"${field}", None]} for field in fields}, - "tasks": {"$sum": 1}, - "untimed_tasks": {"$sum": {"$cond": ["$timed", 0, 1]}}, + **_sums(), } - for field in SUMMED: - group[field] = {"$sum": f"${field}"} sort = {f"_id.{field}": 1 for field in fields} totals = usage.aggregate([{"$match": match}, {"$group": group}, {"$sort": sort}]) report = [] @@ -124,8 +138,8 @@ def own_usage_totals( since: datetime | None = None, until: datetime | None = None, group_by: str = "user_id", - owned: bool = True, - acted_for: bool = True, + include_owned: bool = True, + include_acted_for: bool = True, ) -> list[dict[str, Any]]: """Get the totals of the resources that the tasks of a caller used. @@ -144,9 +158,10 @@ def own_usage_totals( group_by: Totals of the caller's own tasks in one row (`user_id`, the default), or per user that the caller, as a service client, ran them for (`acting_for`). - owned: Whether to include the totals of the caller's own tasks. - acted_for: Whether to include the totals of the tasks that service - clients ran for the caller. + include_owned: Whether to include the totals of the caller's own + tasks. + include_acted_for: Whether to include the totals of the tasks that + service clients ran for the caller. Returns: The totals of the caller's own tasks (cf. :py:func:`usage_totals`), @@ -158,11 +173,11 @@ def own_usage_totals( ValueError: `group_by` is no grouping of :py:data:`GROUPINGS`. """ totals: list[dict[str, Any]] = [] - if owned: + if include_owned: totals += usage_totals( usage, user_id=owner, since=since, until=until, group_by=group_by ) - if acted_for: + if include_acted_for: totals += [ total for total in usage_totals( @@ -188,7 +203,8 @@ def aggregate_totals( Totals over few tasks can tell what single users did (e.g., in a narrow time range with one user's tasks), so they are withheld below a minimum - number of tasks. + number of tasks. The minimum counts tasks, not users, and doesn't + prevent comparing the totals of overlapping time ranges (differencing). Args: usage: Database collection of the records (cf. @@ -205,13 +221,7 @@ def aggregate_totals( their run times (`wall_seconds`) and resource-seconds, as in :py:func:`usage_totals`, without user identifiers. """ - group: dict[str, Any] = { - "_id": None, - "tasks": {"$sum": 1}, - "untimed_tasks": {"$sum": {"$cond": ["$timed", 0, 1]}}, - } - for field in SUMMED: - group[field] = {"$sum": f"${field}"} + group: dict[str, Any] = {"_id": None, **_sums()} totals = list( usage.aggregate([{"$match": finished_range(since, until)}, {"$group": group}]) ) diff --git a/pro_tes/api/additions.openapi.yaml b/pro_tes/api/additions.openapi.yaml index 79471c73..00d50f11 100644 --- a/pro_tes/api/additions.openapi.yaml +++ b/pro_tes/api/additions.openapi.yaml @@ -107,7 +107,8 @@ paths: required: false description: >- Only the caller's own tasks (`user_id`), not those that service - clients ran for the caller; must name the caller. + clients ran for the caller; must name the caller, in the form of + `user_id` in the response (by default `|`). schema: type: string - name: acting_for @@ -259,7 +260,8 @@ components: description: >- For admins only: anonymous totals over all tasks that finished in the time range, without user identifiers; withheld if they cover - fewer tasks than `custom.accounting.min_aggregate_tasks`. + fewer tasks than `custom.accounting.min_aggregate_tasks` (which + counts tasks, not users). type: object required: - withheld diff --git a/pro_tes/config.yaml b/pro_tes/config.yaml index ac7450e0..e926e04a 100644 --- a/pro_tes/config.yaml +++ b/pro_tes/config.yaml @@ -64,9 +64,9 @@ security: # its owner, and only owners may read and cancel a task and get its # provenance, also after losing the role `user`. Admins (the role `admin`) # may only read anonymous usage totals and the execution reports, not the - # tasks of others nor their provenance, nor the usage of single users. Roles are given to groups of the - # identity provider (values of the claim `claim_groups`) by - # `group_mapping`, e.g.: + # tasks of others nor their provenance, nor the usage of single users. + # Roles are given to groups of the identity provider (values of the claim + # `claim_groups`) by `group_mapping`, e.g.: # claim_groups: groups # group_mapping: # compute-users: user @@ -438,7 +438,7 @@ custom: finished_days: null interval: 3600 batch_size: 500 - # Accounting of the resources that tasks used, per user, off by default: + # Accounting of the resources that tasks used, off by default: # the Celery workers record the run time of each task that finished at its # TES instance and the resources it requested, with its owner (`user_id`); # each caller gets the totals of their own tasks at `GET /usage`, admins diff --git a/pro_tes/ga4gh/tes/server.py b/pro_tes/ga4gh/tes/server.py index c983000b..221db4fb 100644 --- a/pro_tes/ga4gh/tes/server.py +++ b/pro_tes/ga4gh/tes/server.py @@ -177,8 +177,10 @@ def GetUsage(*args: Any, **kwargs: Any) -> dict[str, Any]: since=since, until=until, group_by=kwargs.get("group_by", "user_id"), - owned=acting_for is None, - acted_for=user_id is None, + # `user_id` selects the caller's own tasks only, `acting_for` + # those that service clients ran for the caller only + include_owned=acting_for is None, + include_acted_for=user_id is None, ), } if ADMIN_ROLE in get_current_roles(): diff --git a/tests/accounting/test_report.py b/tests/accounting/test_report.py index 9b132f4e..35406534 100644 --- a/tests/accounting/test_report.py +++ b/tests/accounting/test_report.py @@ -1,4 +1,4 @@ -"""Tests of the totals of the resources that tasks used, per user.""" +"""Tests of the totals of the resources that tasks used: own, or anonymous.""" from datetime import UTC, datetime, timedelta import sys @@ -9,7 +9,12 @@ import pytest import tes -from pro_tes.accounting import usage_record, usage_totals +from pro_tes.accounting import ( + aggregate_totals, + own_usage_totals, + usage_record, + usage_totals, +) from pro_tes.accounting.report import SUMMED from tests.conftest import DB @@ -206,3 +211,132 @@ def test_totals_grouped_by_unknown(usage: Collection[dict[str, Any]]) -> None: """Other groupings are errors.""" with pytest.raises(ValueError, match="group_by"): usage_totals(usage, group_by="state") + + +def test_own_totals(client_usage: Collection[dict[str, Any]]) -> None: + """Own tasks first, then per service client those it ran for the owner.""" + totals = own_usage_totals(client_usage, owner="alice") + assert [(total["user_id"], total.get("acting_for")) for total in totals] == [ + ("alice", None), + ("client:engine", "alice"), + ] + assert totals[0]["tasks"] == 3 + assert totals[1]["tasks"] == 2 + + +@pytest.mark.parametrize( + ("include_owned", "include_acted_for", "expected"), + [ + (True, True, ["alice", "client:engine"]), + (True, False, ["alice"]), + (False, True, ["client:engine"]), + (False, False, []), + ], +) +def test_own_totals_parts( + client_usage: Collection[dict[str, Any]], + include_owned: bool, + include_acted_for: bool, + expected: list[str], +) -> None: + """The caller's own tasks and those run for the caller can be left out.""" + totals = own_usage_totals( + client_usage, + owner="alice", + include_owned=include_owned, + include_acted_for=include_acted_for, + ) + assert [total["user_id"] for total in totals] == expected + + +def test_own_totals_of_client(client_usage: Collection[dict[str, Any]]) -> None: + """Service clients get their own totals, also per named user. + + Tasks of other service clients for the same users are not included. + """ + add(client_usage, "D1", "client:other", 1, acting_for="alice") + (total,) = own_usage_totals(client_usage, owner="client:engine") + assert (total["user_id"], total["tasks"]) == ("client:engine", 4) + totals = own_usage_totals( + client_usage, owner="client:engine", group_by="acting_for" + ) + assert [(total["user_id"], total["acting_for"]) for total in totals] == [ + ("client:engine", None), + ("client:engine", "alice"), + ("client:engine", "carol"), + ] + + +def test_own_totals_not_counted_twice(usage: Collection[dict[str, Any]]) -> None: + """Tasks that an owner ran for itself count once, with its own tasks.""" + add(usage, "S1", "client:engine", 1, acting_for="client:engine") + totals = own_usage_totals(usage, owner="client:engine") + assert [(total["user_id"], total["tasks"]) for total in totals] == [ + ("client:engine", 1) + ] + + +def test_own_totals_grouped_by_unknown(usage: Collection[dict[str, Any]]) -> None: + """Unknown groupings are errors.""" + with pytest.raises(ValueError, match="group_by"): + own_usage_totals(usage, owner="alice", group_by="state") + + +def test_own_totals_none(usage: Collection[dict[str, Any]]) -> None: + """Callers without records get no totals.""" + assert own_usage_totals(usage, owner="dave") == [] + + +@pytest.mark.parametrize(("minimum", "withheld"), [(5, False), (6, True)]) +def test_aggregate_totals( + usage: Collection[dict[str, Any]], minimum: int, withheld: bool +) -> None: + """Totals over all tasks are given from the minimum number of tasks on.""" + aggregate = aggregate_totals(usage, min_tasks=minimum) + if withheld: + assert aggregate == {"withheld": True} + else: + assert aggregate == { + "withheld": False, + "tasks": 5, + "untimed_tasks": 1, + "wall_seconds": 4.5 * 3600.0, + "cpu_core_seconds": 4.5 * 3600.0, + "ram_gb_seconds": 9 * 3600.0, + "disk_gb_seconds": 13.5 * 3600.0, + } + + +def test_aggregate_totals_time_range(usage: Collection[dict[str, Any]]) -> None: + """Only tasks that finished in the time range count.""" + aggregate = aggregate_totals(usage, min_tasks=1, since=START + timedelta(days=5)) + assert aggregate["tasks"] == 2 + + +def test_aggregate_totals_empty(mongo_client: MongoClient[dict[str, Any]]) -> None: + """Without records, the totals are withheld.""" + assert aggregate_totals(mongo_client[DB]["usage"], min_tasks=1) == { + "withheld": True + } + + +@pytest.mark.parametrize("field", SUMMED) +def test_aggregate_totals_overflow( + mongo_client: MongoClient[dict[str, Any]], field: str +) -> None: + """Sums too large for a float are the largest float.""" + usage = mongo_client[DB]["usage"] + for task in ("TASK01", "TASK02"): + record = dict.fromkeys(SUMMED, 1.0) + record[field] = 1e308 + usage.insert_one( + { + "_id": task, + "user_id": "carol", + "timed": True, + "finished_at": datetime(2026, 11, 13, tzinfo=UTC), + **record, + } + ) + aggregate = aggregate_totals(usage, min_tasks=1) + assert aggregate[field] == sys.float_info.max diff --git a/tests/accounting/test_usage_endpoint.py b/tests/accounting/test_usage_endpoint.py index d3f9fc95..17833820 100644 --- a/tests/accounting/test_usage_endpoint.py +++ b/tests/accounting/test_usage_endpoint.py @@ -204,15 +204,35 @@ def test_get_own_usage_filtered(client: FlaskClient, records: None) -> None: @pytest.mark.parametrize("user", [USER, ADMIN, ADMIN_USER]) @pytest.mark.parametrize("name", ["user_id", "acting_for"]) +@pytest.mark.parametrize("other", [subject(OTHER_USER), "client:engine", OTHER_USER]) def test_get_usage_of_others_forbidden( - client: FlaskClient, records: None, user: str, name: str + client: FlaskClient, records: None, user: str, name: str, other: str ) -> None: """Nobody may name others in the filters (`403`), admins neither.""" - for other in (subject(OTHER_USER), "client:engine", OTHER_USER): - response = client.get( - PATH, query_string={name: other}, headers=make_headers(user) - ) - assert response.status_code == 403 + response = client.get(PATH, query_string={name: other}, headers=make_headers(user)) + assert response.status_code == 403 + assert response.get_json()["detail"].startswith( + "The usage of the tasks of others can't be requested" + ) + + +def test_head_usage(client: FlaskClient, records: None) -> None: + """Callers may send `HEAD` requests for their usage.""" + assert client.head(PATH).status_code == 200 + + +def test_get_usage_aggregate_ignores_grouping( + app: FlaskApp, client: FlaskClient, records: None +) -> None: + """The anonymous totals are the same with any grouping.""" + set_minimum(app, 1) + headers = make_headers(ADMIN) + aggregates = [ + client.get(PATH, query_string=query, headers=headers).get_json()["aggregate"] + for query in ({}, {"group_by": "acting_for"}) + ] + assert aggregates[0] == aggregates[1] + assert aggregates[0]["tasks"] == 3 @pytest.mark.parametrize("user", [ADMIN, ADMIN_USER]) @@ -392,16 +412,21 @@ def test_get_usage_reports_forbidden(client: FlaskClient, user: str) -> None: assert response.status_code == 403 -@pytest.mark.parametrize("rule", [["p", "admin", PATH, "(GET)|(HEAD)"], None]) +@pytest.mark.parametrize( + ("rule", "error"), + [(["p", "admin", PATH, "(GET)|(HEAD)"], RuntimeError), (None, ValueError)], + ids=["rule", "null"], +) def test_old_usage_rule_refused( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, app_env: None, rule: list[str] | None, + error: type[Exception], ) -> None: """Overlays that name the former rule `admins-get-usage` stop the start. - A rule under the old name is refused (it was renamed to + A rule under the old name is refused by proTES (it was renamed to `authenticated-get-usage`); removing it (`null`) is refused by FOCA, as the rule is no longer in the base config. """ @@ -414,7 +439,7 @@ def test_old_usage_rule_refused( ) set_overlays(monkeypatch, overlay) reset_gateway() - with pytest.raises((RuntimeError, ValueError), match="admins-get-usage"): + with pytest.raises(error, match="admins-get-usage"): init_app() From 5986c2e81daba472b36c46bac2662ff0df61b244 Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sun, 6 Dec 2026 00:40:56 +0100 Subject: [PATCH 7/9] docs: drop "per user" and warn about minimum 1 Second-round review fixes for #569: module and OpenAPI comments no longer say "per user"; the docs say that `min_aggregate_tasks: 1` gives single-task totals; the include flags test checks `acting_for`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- docs/configuration.md | 4 +++- pro_tes/accounting/__init__.py | 2 +- pro_tes/accounting/report.py | 2 +- pro_tes/api/additions.openapi.yaml | 2 +- tests/accounting/test_report.py | 12 +++++++----- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 664727bd..42a80f07 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -882,7 +882,9 @@ Admins get the totals over all tasks only if they cover at least tasks, e.g., of a narrow time range with one user's tasks, are withheld, so that they don't tell what single users did. The minimum counts tasks, not users, and doesn't stop admins from comparing overlapping time ranges -(see [Usage](api.md#usage)): +(see [Usage](api.md#usage)). A minimum of 1 withholds nothing but empty +totals, so admins can read the totals of single tasks in narrow time +ranges: ```yaml custom: diff --git a/pro_tes/accounting/__init__.py b/pro_tes/accounting/__init__.py index 86c03d4f..323187e0 100644 --- a/pro_tes/accounting/__init__.py +++ b/pro_tes/accounting/__init__.py @@ -1,4 +1,4 @@ -"""Accounting of the resources that tasks used, per user (opt-in). +"""Accounting of the resources that tasks used (opt-in). Deployments may record, for each task that finished at its TES instance, which resources it used: how long it ran (wall-clock time, from the logs of diff --git a/pro_tes/accounting/report.py b/pro_tes/accounting/report.py index 004573ee..d098757a 100644 --- a/pro_tes/accounting/report.py +++ b/pro_tes/accounting/report.py @@ -1,4 +1,4 @@ -"""Totals of the resources that tasks used: per user, or anonymous.""" +"""Totals of the resources that tasks used: per owner, or anonymous.""" from datetime import datetime import math diff --git a/pro_tes/api/additions.openapi.yaml b/pro_tes/api/additions.openapi.yaml index 00d50f11..b6b04760 100644 --- a/pro_tes/api/additions.openapi.yaml +++ b/pro_tes/api/additions.openapi.yaml @@ -85,7 +85,7 @@ paths: application/json: schema: $ref: '#/components/schemas/ProblemDetails' - # proTES extension: the resources that tasks used, per user (see + # proTES extension: the resources that tasks used (see # docs/api.md) /usage: get: diff --git a/tests/accounting/test_report.py b/tests/accounting/test_report.py index 35406534..620022f2 100644 --- a/tests/accounting/test_report.py +++ b/tests/accounting/test_report.py @@ -227,9 +227,9 @@ def test_own_totals(client_usage: Collection[dict[str, Any]]) -> None: @pytest.mark.parametrize( ("include_owned", "include_acted_for", "expected"), [ - (True, True, ["alice", "client:engine"]), - (True, False, ["alice"]), - (False, True, ["client:engine"]), + (True, True, [("alice", None), ("client:engine", "alice")]), + (True, False, [("alice", None)]), + (False, True, [("client:engine", "alice")]), (False, False, []), ], ) @@ -237,7 +237,7 @@ def test_own_totals_parts( client_usage: Collection[dict[str, Any]], include_owned: bool, include_acted_for: bool, - expected: list[str], + expected: list[tuple[str, str | None]], ) -> None: """The caller's own tasks and those run for the caller can be left out.""" totals = own_usage_totals( @@ -246,7 +246,9 @@ def test_own_totals_parts( include_owned=include_owned, include_acted_for=include_acted_for, ) - assert [total["user_id"] for total in totals] == expected + assert [(total["user_id"], total.get("acting_for")) for total in totals] == ( + expected + ) def test_own_totals_of_client(client_usage: Collection[dict[str, Any]]) -> None: From 177d0e0b7ac243e5cffb5b66ce1a8c6b257e807e Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sun, 6 Dec 2026 00:47:53 +0100 Subject: [PATCH 8/9] docs: name the renamed usage rule in 0.8.0 notes The 0.8.0 upgrade section now says that `admins-get-usage` is named `authenticated-get-usage` since the unreleased changes, and that the old name stops the start (contract review of #569). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- docs/upgrading.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/upgrading.md b/docs/upgrading.md index c589696b..df91c876 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -472,9 +472,10 @@ instance, with its owner, and admins get the totals per user at `GET /usage` you set it (see [Accounting of resource usage](configuration.md#accounting-of-resource-usage)). Tasks that finished before are not recorded. The endpoint needs the new rule `admins-get-usage` -(renamed later, see [Unreleased changes](#unreleased-changes)) of the base -config: overlays whose policies are a list (which replaces all -rules) must add it, or admins get `403`. proTES creates the collection +of the base config: overlays whose policies are a list (which replaces all +rules) must add it, or admins get `403`. Since the [unreleased +changes](#unreleased-changes), the rule is named `authenticated-get-usage` +instead, and overlays that still name `admins-get-usage` stop the start. proTES creates the collection `usage` with two indexes (`finished_at`; `user_id`, `finished_at`) on its first start, also while accounting is off; the records are kept until you delete them (see [Usage records](operations.md#usage-records)). From 48fd6b282b4011ba330cfc9af92c89e7c8aa4b6c Mon Sep 17 00:00:00 2001 From: Alex Kanitz Date: Sun, 6 Dec 2026 01:22:46 +0100 Subject: [PATCH 9/9] fix: check usage grouping before any totals Sourcery review of #571: `own_usage_totals` refuses unknown groupings also when it leaves out the caller's own tasks; the spec says where `acting_for` appears; the tests of withheld totals and of service clients' own rows check whole values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011FSoqPsbB5s4NvhhYYcDJk --- pro_tes/accounting/report.py | 2 ++ pro_tes/api/additions.openapi.yaml | 8 +++++--- tests/accounting/test_report.py | 2 ++ tests/accounting/test_usage_endpoint.py | 10 +++++++--- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/pro_tes/accounting/report.py b/pro_tes/accounting/report.py index d098757a..2d00fe6c 100644 --- a/pro_tes/accounting/report.py +++ b/pro_tes/accounting/report.py @@ -172,6 +172,8 @@ def own_usage_totals( Raises: ValueError: `group_by` is no grouping of :py:data:`GROUPINGS`. """ + if group_by not in GROUPINGS: + raise ValueError(f"Unknown `group_by`: {group_by!r}") totals: list[dict[str, Any]] = [] if include_owned: totals += usage_totals( diff --git a/pro_tes/api/additions.openapi.yaml b/pro_tes/api/additions.openapi.yaml index b6b04760..e152cedb 100644 --- a/pro_tes/api/additions.openapi.yaml +++ b/pro_tes/api/additions.openapi.yaml @@ -313,9 +313,11 @@ components: type: string nullable: true description: >- - With `group_by=acting_for` only: the user that the service client - owning the tasks ran them for; null for tasks run for no one - (e.g., created by users, or by service clients for themselves). + The user that the service client owning the tasks ran them for: + on the rows of the tasks that service clients ran for the caller, + and with `group_by=acting_for` on the caller's own rows; null for + tasks run for no one (e.g., created by users, or by service + clients for themselves). tasks: type: integer description: Number of tasks. diff --git a/tests/accounting/test_report.py b/tests/accounting/test_report.py index 620022f2..4916dd37 100644 --- a/tests/accounting/test_report.py +++ b/tests/accounting/test_report.py @@ -282,6 +282,8 @@ def test_own_totals_grouped_by_unknown(usage: Collection[dict[str, Any]]) -> Non """Unknown groupings are errors.""" with pytest.raises(ValueError, match="group_by"): own_usage_totals(usage, owner="alice", group_by="state") + with pytest.raises(ValueError, match="group_by"): + own_usage_totals(usage, owner="alice", group_by="state", include_owned=False) def test_own_totals_none(usage: Collection[dict[str, Any]]) -> None: diff --git a/tests/accounting/test_usage_endpoint.py b/tests/accounting/test_usage_endpoint.py index 17833820..1f54d934 100644 --- a/tests/accounting/test_usage_endpoint.py +++ b/tests/accounting/test_usage_endpoint.py @@ -283,8 +283,11 @@ def test_get_usage_aggregate_withheld_configured( """The minimum is configurable (`min_aggregate_tasks`).""" set_minimum(app, minimum) aggregate = client.get(PATH, headers=make_headers(ADMIN)).get_json()["aggregate"] - assert aggregate["withheld"] is withheld - assert ("tasks" in aggregate) is not withheld + if withheld: + assert aggregate == {"withheld": True} + else: + assert aggregate["withheld"] is False + assert aggregate["tasks"] == 3 def test_get_usage_aggregate_empty(app: FlaskApp, client: FlaskClient) -> None: @@ -340,7 +343,8 @@ def test_get_usage_service_client( response = client.get( PATH, query_string={"user_id": CLIENT_OWNER}, headers=client_headers() ) - assert response.get_json()["users"][0]["tasks"] == 2 + (row,) = response.get_json()["users"] + assert (row["user_id"], row["tasks"]) == (CLIENT_OWNER, 2) response = client.get( PATH, query_string={"acting_for": subject(USER)}, headers=client_headers() )