Skip to content

feat!: add owner-based access control - #106

Merged
uniqueg merged 24 commits into
devfrom
feat/access-control-signed
Oct 20, 2026
Merged

uniqueg merged 24 commits into
devfrom
feat/access-control-signed

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Owner-based access control for the registry (#62), with FOCA 0.14's access control (Casbin). This replaces #66: its commits are re-applied on top of dev, with the original author preserved and signed commits, so that the PR can be merged. The work decided on 2026-10-20 is added on top.

From #66 (re-applied)

  • Public reads: GET on services, a service, service types and service info need no token. The security: [] overrides are in additions.openapi.yaml and merged into the GA4GH operations, so the vendored specifications are unchanged.
  • Owners: any LS Login user can register a service (POST /services) and becomes its owner. Owners can update and delete their services.
  • Managing permissions: GET /services/{serviceId}/permissions, PUT and DELETE /services/{serviceId}/permissions/{userId} (body {"role": "owner" | "maintainer"}) let owners grant and revoke roles by user ID (sub). Granting a role replaces the user's other role on the service.
  • Maintainers can update (PUT), but not delete a service or manage its permissions.
  • Admins can do everything, including POST /service-info (admins only) and registering services with chosen IDs (PUT of a new service). LS Login provides group memberships via user info only (userinfo_claims).
  • Policies are configured in config.yaml (security.access_control.policies), using FOCA's reference model for resource-scoped roles. Roles on a service are revoked when the service is deleted.
  • RegisterService distinguishes newly created services from replaced ones, so a maintainer replacing a service doesn't become its owner.
  • Skipped commit: eef16a7 (integer status code of POST /service-info), because dev already returns a Response with status 201 (fix!: service info id, precedence and headers #96).

Added (decisions of 2026-10-20)

  • Admin groups are set by the deployment, not in the repo default config. Config overlays merge mappings, so deployments couldn't remove a default mapping.
    • On startup, the app logs the groups mapped to admin.
    • It refuses to start without any, unless custom.access_control.require_admin: false is set (it then logs a warning).
    • The Helm chart fails to render without a mapping, with the same opt-out.
    • The docs show the ELIXIR mapping (ECP_CLN:ADMIN, canonical LS Login form only).
  • Audience required: verify_audience: False is removed from the repo default. FOCA refuses to start when issuers are set without audience, so deployments must set their client IDs.
  • Docker Compose mounts config.dev.yaml, a development overlay that accepts any audience and requires no admins.
  • Tests use tests/config_overlay.yaml, which sets an audience and the ELIXIR admin group.
  • GET /me returns {user_id, admin, services: [{service_id, role}]} for the current user. Owners stay out of the public GA4GH responses.
  • Display names: name from LS Login's user info is stored (collection users) when a user registers a service or calls GET /me. It is listed with the roles on a service, which only owners and admins can see.
  • Last owner: removing or downgrading the last owner of a service returns 409 Conflict, for everyone including admins. To get rid of a service, delete it.
  • The permission controllers are adapted to the linters on dev, and dev's app tests to public reads and admin-only writes.

Closes #62. Replaces #66.

Breaking changes

  • Writes need roles: only owners (and maintainers, for updates) can change a service, and only admins can set the service info or create services with chosen IDs. Existing services have no owner, so only admins can change them (see Populate the Cloud Registry: owners register their own deployments, admins remove placeholder entries generic-issues#29; the redeploy starts with an empty database).
  • Deployments must set security.auth.audience and map an admin group to admin in security.access_control.group_mapping, or set custom.access_control.require_admin: false. Otherwise the app refuses to start, and the Helm chart fails to render without the mapping.

Verification

  • pytest (Helm 3.18.6 on PATH): 136 passed, 100% coverage of cloud_registry. New and adapted tests cover:
    • public reads and 401 for writes without a token;
    • owners, maintainers, admins and permission management (from feat!: add owner-based access control #66);
    • GET /me;
    • names: stored per service once the user has used the registry with the role, deleted with it; no blank names;
    • the last owner (409, also for admins), and restoring an owner removed by concurrent changes;
    • the startup check (logs admin groups; fails without them; warns with require_admin: false);
    • the base config alone failing without an audience;
    • the Compose dev overlay;
    • the Helm fail and its opt-out.
  • ruff check, ruff format --check, mypy cloud_registry tests: clean.
  • helm lint --strict, with and without MongoDB auth: passes.
  • gitleaks dir .: no leaks. The pre-push hook (semgrep, ast-grep) passed.
  • Adversarial and quality review, 2 rounds.
    • Fixed:
      • names were visible to any owner who granted a role to someone who had used the registry; they are now scoped per service;
      • a race between owners removing each other could leave a service without owners;
      • the base path was parsed from the request path;
      • the test mocks were duplicated;
      • test gaps;
      • docs.
    • Declined:
      • A delete racing with an update of the same service can re-create it. This is a narrow window, and admins can repair it; the duplicate check (feat: reject duplicate service registrations #102) will touch this code.
      • An admin PUT of a service ID with a comma returns 500. This is admin-only and comes from FOCA's rule validation; IDs will be validated with feat: reject duplicate service registrations #102.
      • Per-function unit tests: the behaviour is covered through the app tests.
      • Rewriting the history: the PR is squash-merged.
  • Sourcery review (8 findings):
    • Fixed:
      • roles left over from a deleted service carried over to a new service with the same ID; registration now clears them;
      • a failure while adding the owner left an ownerless service; registration is rolled back (400 for invalid IDs);
      • a name could stay stored after a revoke raced with a grant; names are deleted on a user's first grant;
      • a failed demotion could keep the old role; other roles are revoked before granting the new one.
    • Declined: concurrent grants to the same user, unbounded permission listings, and delete vs. update races (narrow windows, admins can repair; revisit with feat: reject duplicate service registrations #102); "owners cannot manage permissions" (they can: resource roles cover sub-paths by default).
  • Not verified: a deployment with real LS Login tokens (planned with the redeploy).
  • CI on 0e12452: all checks pass, including the Docker Compose run, the Helm chart checks and Codecov (patch and project). Earlier, 1e60431 missed Codecov's 100% patch target; the last commit covers the remaining branches. The first run failed in the Docker Compose job: access_control/model.conf was missing from the package data (since feat!: add owner-based access control #66). That is now fixed, and a test checks that the files the base config references are packaged.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 20 commits October 20, 2026 08:26
Replace the config Job, which rewrote the image's config with yq and
patched a ConfigMap with namespace admin rights, with a ConfigMap
rendered by Helm. It holds a FOCA config overlay (`FOCA_CONFIG_OVERLAY`)
generated from `host_name` (HTTPS on port 443, as before) and merged
with the new free-form `config` value, which takes precedence. The
Deployment mounts it as a directory and rolls on config changes.

This also fixes the public URL: the Job set `.endpoints.service`
instead of `.custom.endpoints.service`, so `host_name` was never used.

Remove `update-config-map.sh` and its tools from the image, and install
the app non-editably. Document configuration via overlays for Helm and
Docker Compose. CI lints and renders the chart and validates the
rendered overlay against the app's config models.

Closes #67

BREAKING CHANGE: the chart (version 3.0.0) no longer creates the
`app-config` ConfigMap, the config Job, its ServiceAccount and
RoleBinding, and drops the `apiServer` value; config changes made to
`app-config` must be moved to `config` in the values file. The image no
longer contains the app's source in `/app`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test the config overlay rendered by `helm template` with pytest (when
helm is installed, as on GitHub-hosted runners) instead of an inline
script in CI: generated values, precedence of `config`, and recursive
merging of overlays. Require `host_name`, validate the types of
`host_name` and `config` with a values schema, and document that the
chart needs an image with FOCA 0.14 or later, which keys it expects
unchanged, and that `config` must not contain secrets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test the values schema, precedence of later overlays, and that the
Deployment mounts the overlay ConfigMap where `FOCA_CONFIG_OVERLAY`
points; share the config parsing helper. Install all CI requirements in
one step and fail the chart tests if helm is missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pin MongoDB to 7.0 (as in Docker Compose) instead of `mongo:noble`,
which resolves to the latest version, and replace its pod with the
`Recreate` strategy, as the data volume can only be used by one pod.

Add optional MongoDB authentication (`mongodb.auth`): credentials come
from an existing Secret; MongoDB creates the root user and, via the
init script, an app user with access to the app's database only, which
the app connects as (`MONGO_USERNAME`, `MONGO_PASSWORD`). The init
script no longer creates collections and indexes, which FOCA does on
startup.

Add readiness and liveness probes to the app (Swagger UI) and MongoDB
(TCP). Document version upgrades and downgrades, authentication and
probes, and test the rendered manifests.

Closes #68

BREAKING CHANGE: the default MongoDB image changes from `mongo:noble`
(MongoDB 8.x) to `mongo:7.0`; databases written by MongoDB 8.0 must be
downgraded first or keep their version via `mongodb.image` (see the
deployment docs).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`mongo:noble` may resolve to MongoDB 8.2, whose data cannot be read by
7.0 (or 8.0) directly. Document checking the version and the feature
compatibility version before changing the image, downgrading one
version at a time, and pinning the running version before upgrading
from chart version 2. Document privileged commands with authentication
and password changes.

Add a startup probe to MongoDB, so that the liveness probe cannot
interrupt the initialization of an empty data directory (which would
skip creating the users). Render the Secret references with a helper,
add the MongoDB values to the schema, and test probes and init script
mounts in detail; move the Helm test helpers to `tests/helm.py`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
MongoDB Community Edition does not support binary downgrades, and
`mongo:noble` now resolves to MongoDB 9.0. Tell users upgrading from
chart version 2 to pin the running version, document dump and restore
as the way to an older version, and print both the version and the FCV.

Move the probes to their own section and describe all of them, test
that the init script uses the configured database, lint the chart with
authentication enabled, and note the order of Secret variables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	.github/workflows/checks.yaml
#	deployment/README.md
#	deployment/templates/cloud-registry-deploy.yaml
#	deployment/values.schema.json
#	tests/test_config.py
Use FOCA's access control (Casbin) to implement the agreed permission
model:

- Anyone can read services, service types and service info: the read
  operations of the GA4GH specifications are made public via additions
  merged into them, so the vendored specifications stay unchanged.
- Any LS Login user can register a service (POST) and becomes its
  owner. Owners can update and delete their services and grant other
  users the roles owner or maintainer (update only) via new endpoints
  /services/{serviceId}/permissions[/{userId}].
- Members of ECP_CLN:ADMIN are admins and can do everything, including
  setting the service info and registering services with chosen
  identifiers (PUT of a new service). LS Login provides entitlements
  via user info only, so they are added to the token claims via FOCA's
  security.auth.userinfo_claims.

Policies use FOCA's reference model for resource-scoped roles and are
added on startup; roles on services are revoked when they are deleted.

BREAKING CHANGE: non-admins can no longer modify or delete services
they do not own or maintain, set the service info, or register
services via PUT. Existing services have no owner (see #63).

Closes #62

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Use FOCA options proposed for 0.14.0: policy rules are set via
security.access_control.policies instead of being added in code on
startup (elixir-cloud-aai/foca#311), and the permission endpoints are
routed to their own controller module via x-openapi-router-controller
instead of being re-exported from the server module
(elixir-cloud-aai/foca#310).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reads of services and service info are public now, and writes need a
role: the app tests check that reads need no token, that writes do, and
use an admin (via a mocked group membership) for creating services with
chosen identifiers and for registering service info.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With FOCA 0.14, configured policies are managed on startup and cannot
be changed via the permissions API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Use built-in generics, lazy logging arguments and exception chaining in
the permission controllers, as required by the linters on `dev`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The repo default config no longer maps an admin group or accepts tokens
for any audience: both depend on the deployment, and config overlays
can't remove mappings from the base config.

- On startup, the app logs the groups mapped to the role `admin` and
  fails without any, unless `custom.access_control.require_admin` is
  false (then it warns).
- `verify_audience: False` is removed, so deployments must set
  `security.auth.audience` (FOCA refuses to start otherwise).
- Docker Compose mounts a development overlay (`config.dev.yaml`) that
  accepts any audience and requires no admin groups.
- Tests use an overlay with an audience and the ELIXIR admin group.

BREAKING CHANGE: deployments must set `security.auth.audience` and map
an admin group to `admin` in `security.access_control.group_mapping`
(or set `custom.access_control.require_admin: false`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gned

# Conflicts:
#	.github/workflows/checks.yaml
#	deployment/README.md
#	deployment/templates/_helpers.tpl
#	deployment/templates/cloud-registry-deploy.yaml
#	deployment/templates/mongo-deploy.yaml
#	deployment/values.schema.json
#	deployment/values.yaml
#	tests/helm.py
#	tests/test_chart.py
#	tests/test_config.py
Like the app on startup, rendering fails unless `config` maps a group to
the role `admin`, or sets `custom.access_control.require_admin: false`.
The values document the mapping and the required audience; CI values
and chart tests map a test group.

BREAKING CHANGE: `config.security.access_control.group_mapping` must
map a group to `admin` (or `config.custom.access_control.require_admin`
must be false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `GET /me` returns the current user's identifier (to give to owners),
  whether they are an admin, and their roles on services, so that
  clients can show what users may do. Owners are not exposed in the
  public service responses.
- Display names (`name` from LS Login's user info) are stored when a
  user registers a service or calls `GET /me`, and are listed with the
  roles on a service (owners and admins only).
- Removing or downgrading the last owner of a service returns `409
  Conflict`, also for admins: services always have an owner (delete
  the service instead).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the settings each deployment must make (audience, admin
group), the Docker Compose development overlay, `GET /me`, display
names and the last-owner rule; update the Dockerfile's probe comment
now that reads are public.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings:

- Store display names per service, only once a user has used the
  registry with a role on it, and delete them with the role or the
  service; owners could otherwise look up the name of any user who had
  ever used the registry by granting them a role.
- Re-check owners after removing or downgrading one, and restore the
  removed owner if concurrent requests left none (`409`).
- Take the API base path from the matched blueprint instead of parsing
  the request path.
- Reuse the shared identity provider mock and app fixtures in the access
  control tests; test blank names, unknown services and the restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address round-2 review findings: don't restore an owner role if the
service was deleted meanwhile (404), share the owner check in a helper,
document that `GET /me` stores the user's name for their services, and
clarify the test of the owner restore.

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

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Replaces unrestricted registry writes with FOCA/Casbin owner-based access control, adds service-scoped roles and identity-derived metadata, and enforces deployment-specific audience and admin-group configuration across the app, Helm chart, Compose setup, documentation, packaging, and tests.

Sequence diagram for owner-based service registration

sequenceDiagram
    actor User
    participant API as Registry API
    participant Service as RegisterService
    participant DB as Services database
    participant Policy as FOCA access control

    User->>API: POST /services
    Policy->>API: Authorize authenticated user
    API->>Service: register_metadata()
    Service->>DB: Insert new service
    DB-->>Service: Created service ID
    API->>Policy: add_owner(serviceId)
    Policy-->>API: Owner role stored
    API-->>User: Service ID
Loading

Sequence diagram for service permission management

sequenceDiagram
    actor Owner
    participant API as Registry API
    participant Policy as FOCA access control
    participant DB as Policy and user-name storage

    Owner->>API: PUT /services/{serviceId}/permissions/{userId}
    Policy->>API: Authorize owner or admin
    API->>Policy: putServicePermission(serviceId, userId)
    Policy->>DB: Replace user role on service
    DB-->>Policy: Role stored
    Policy-->>API: Permission
    API-->>Owner: 200 Permission
Loading

Sequence diagram for protected service updates and deletion

sequenceDiagram
    actor User
    participant API as Registry API
    participant Policy as FOCA access control
    participant Services as Services database
    participant Roles as Service roles

    User->>API: PUT or DELETE /services/{serviceId}
    Policy->>API: Check resource role
    alt owner or admin
        API->>Services: Update or delete service
        opt service deleted
            API->>Roles: remove_permissions(serviceId)
        end
        API-->>User: Success
    else maintainer on PUT
        API->>Services: Update service
        API-->>User: Success
    else insufficient role
        API-->>User: 403 Forbidden
    end
Loading

Entity relationship diagram for service-scoped permissions

erDiagram
    SERVICE {
        string service_id PK
    }
    POLICY_RULE {
        string subject
        string role
        string resource
    }
    USER_NAME {
        string service_id PK
        string user_id PK
        string name
    }
    SERVICE ||--o{ POLICY_RULE : has_roles
    SERVICE ||--o{ USER_NAME : stores_names_for
Loading

File-Level Changes

Change Details Files
Introduces Casbin/FOCA resource-scoped authorization for public reads, authenticated writes, service ownership, maintainer access, admin access, and permission management.
  • Adds the access-control model, policies, role enforcement, permission endpoints, and current-user endpoint.
  • Assigns owners on service creation, preserves roles on replacement, and removes roles and per-service names on deletion.
  • Prevents removal or downgrading of the last owner, including concurrent-change recovery.
  • Stores identity-provider display names per service and exposes them only through authorized permission listings.
cloud_registry/access_control/model.conf
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/api/additions.openapi.yaml
cloud_registry/exceptions.py
Makes deployment security configuration explicit and validates administrator setup at both application startup and Helm rendering time.
  • Requires token audiences in deployment overlays and removes permissive audience verification from the base configuration.
  • Requires an admin group mapping by default, with an explicit opt-out and corresponding startup warning.
  • Adds development and test overlays for permissive local authentication and deterministic admin/test identity configuration.
  • Documents deployment configuration, roles, endpoints, identity claims, and operational behavior.
cloud_registry/app.py
cloud_registry/service_models/custom_config.py
config.dev.yaml
deployment/README.md
deployment/templates/cloud-registry-configmap.yaml
deployment/values.yaml
deployment/ci/test-values.yaml
README.md
docker-compose.yaml
Updates packaging, API health behavior, and verification coverage for the new security model.
  • Packages the Casbin model with the installed application and probes the unauthenticated Swagger UI for container health checks.
  • Adapts application and server tests to public reads and role-restricted writes.
  • Adds coverage for ownership, permission transitions, admins, display names, last-owner races, configuration validation, Helm failures, overlays, and packaged referenced files.
  • Updates test identity mocks to provide audiences, group memberships, and user-info names.
Dockerfile
pyproject.toml
tests/conftest.py
tests/test_access_control.py
tests/test_app.py
tests/test_config.py
tests/ga4gh/registry/test_server.py
tests/helm.py

Assessment against linked issues

Issue Objective Addressed Explanation
#62 Allow unauthenticated public reads of services, individual services, service types, and service info while keeping write operations authenticated. ✅
#62 Establish service ownership and enforce write authorization: creators become owners; only owners or admins may update or delete existing services; only admins may create services with chosen IDs or post service info. ✅
#62 Identify admins through deployment-configured LS Login entitlement groups, and provide tests and documentation for the permission model. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

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

Customizing Your Experience

Access your dashboard to:

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

Getting Help

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8cbaf25) to head (0e12452).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      elixir-cloud-aai/cloud-registry#106    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files            7         8     +1     
  Lines          224       365   +141     
==========================================
+ Hits           224       365   +141     

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

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

The access control model (`access_control/model.conf`) was missing from
the package data, so the installed app failed on startup (the Docker
Compose job in CI). A test checks that the files the base config
references exist and match the package data patterns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 20, 2026 15:40

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 8 issues

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

## Individual Comments

### Comment 1
<location path="cloud_registry/ga4gh/registry/server.py" line_range="107" />
<code_context>
     res = db_collection_service.delete_one({"id": serviceId})
     if not res.deleted_count:
         raise NotFound
+    remove_permissions(serviceId)
     return serviceId

</code_context>
<issue_to_address>
**Permissions cross into replacement services**

When deletion overlaps permission changes or recreation, cleanup fails, and the service ID is reused, `deleteService` removes permissions by the reusable service path. Stale roles can grant former users access to the replacement, while cleanup for the deleted service can remove the replacement’s new owner role; an owner restoration can also leave a role that attaches to a later service.

Coordinate deletion, permission changes, and recreation so cleanup applies only to the deleted service incarnation and cannot leave or remove roles on a replacement.

Also at `cloud_registry/ga4gh/registry/server.py:169`, `cloud_registry/ga4gh/registry/permissions.py:155`, `cloud_registry/ga4gh/registry/permissions.py:247`, `cloud_registry/ga4gh/registry/permissions.py:275-283`.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="275-281" />
<code_context>
+    if role != "owner":
+        _check_other_owners(resource, userId)
+    try:
+        add_resource_role(subject=userId, role=role, resource=resource)
+    # FOCA rejects values that can't be stored in policy rules (e.g., user
+    # identifiers with commas)
+    except ValueError as exc:
+        logger.info("Invalid permission: %s", exc)
+        raise BadRequest from exc
+    for other_role in ROLES:
+        if other_role != role:
+            remove_resource_role(subject=userId, role=other_role, resource=resource)
</code_context>
<issue_to_address>
**Concurrent grants remove both roles**

When two owners concurrently grant different roles to the same user on the same service, `putServicePermission` adds the requested role and removes other roles in separate operations, so each request can remove the role added by the other; both requests succeed while the user ends up with no role.

Make replacing a user’s service role atomic or serialize concurrent role updates.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/server.py" line_range="167-168" />
<code_context>
     """
     service = RegisterService(data=_get_request_object(), id=service_id)
     service.register_metadata()
+    if service.was_created:
+        add_owner(service.data["id"])
     return service.data["id"]
</code_context>
<issue_to_address>
**New services become ownerless**

When service metadata is persisted but adding the owner role fails, `register_metadata()` has already persisted the service when `add_owner()` fails, including when FOCA rejects the subject. The request errors and leaves a service only an admin can manage; retrying POST creates a different service instead of repairing it.

Make service creation and owner-role insertion atomic, or roll back the service insert if adding the owner fails.

Also at `cloud_registry/ga4gh/registry/server.py:169-170`, `cloud_registry/ga4gh/registry/permissions.py:141-146`.
</issue_to_address>

### Comment 4
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="172" />
<code_context>
+    """
+    if not service_exists(serviceId):
+        raise NotFound
+    roles = list_resource_roles(service_path(serviceId))
+    names = {
+        user["user_id"]: user["name"]
</code_context>
<issue_to_address>
**Permission listings grow without bounds**

When a service accumulates a very large number of granted roles, `getServicePermissions` materializes every role for the service and returns the full list; sufficiently large grants can consume excessive memory and produce responses too large for clients or the app worker to handle.

Add pagination or a bounded result size to permission listings.
</issue_to_address>

### Comment 5
<location path="cloud_registry/ga4gh/registry/server.py" line_range="107" />
<code_context>
     res = db_collection_service.delete_one({"id": serviceId})
     if not res.deleted_count:
         raise NotFound
+    remove_permissions(serviceId)
     return serviceId

</code_context>
<issue_to_address>
**Deleted service reappears**

When an owner or admin updates a service while another request deletes it, `deleteService` can delete the record while a concurrent `PUT` reaches `replace_one(..., upsert=True)` and recreates it; the delete then returns success even though the service exists again. Depending on interleaving with permission cleanup, the recreated service also ends up without an owner.

Coordinate deletion and replacement so a replacement cannot upsert a service that the concurrent delete is removing.

Also at `cloud_registry/ga4gh/registry/service.py:73-78`.
</issue_to_address>

### Comment 6
<location path="cloud_registry/access_control/model.conf" line_range="28" />
<code_context>
+e = some(where (p.eft == allow))
+
+[matchers]
+m = g(r.sub, "admin") || ((p.sub == "*" || g(r.sub, p.sub) || g2(r.sub, p.sub, r.obj)) && keyMatch2(r.obj, p.obj) && regexMatch(r.act, "^(" + p.act + ")$"))
</code_context>
<issue_to_address>
**Owners cannot manage permissions**

When an owner calls any permission endpoint for their service, `g2` compares the request path with the resource path stored for the owner. Permission requests use nested paths such as `/services/<id>/permissions`, but `add_owner` stores `/services/<id>`, so the owner’s resource role does not match and permission requests return 403.

Match nested permission requests against their parent service resource when checking `g2` roles.
</issue_to_address>

### Comment 7
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="350" />
<code_context>
+        service_id = resource.removeprefix(services_path)
+        if resource.startswith(services_path) and "/" not in service_id:
+            services.append({"service_id": service_id, "role": role})
+    remember_current_user([service["service_id"] for service in services])
+    return {
+        "user_id": user_id,
</code_context>
<issue_to_address>
**Revoked users’ names reappear**

When a user's `/me` request overlaps revocation of their service role, `remember_current_user()` can upsert the user’s name after revocation has removed the role and deleted the stored name. A later grant then exposes that stale name before the user has used the registry with the new role.

Coordinate name persistence with role changes so a `/me` request cannot restore a name after revocation.

Also at `cloud_registry/ga4gh/registry/permissions.py:327`.
</issue_to_address>

### Comment 8
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="275-283" />
<code_context>
+    if role != "owner":
+        _check_other_owners(resource, userId)
+    try:
+        add_resource_role(subject=userId, role=role, resource=resource)
+    # FOCA rejects values that can't be stored in policy rules (e.g., user
+    # identifiers with commas)
+    except ValueError as exc:
+        logger.info("Invalid permission: %s", exc)
+        raise BadRequest from exc
+    for other_role in ROLES:
+        if other_role != role:
+            remove_resource_role(subject=userId, role=other_role, resource=resource)
+    if was_owner and role != "owner":
+        try:
</code_context>
<issue_to_address>
**Failed demotion keeps ownership**

When the new role write succeeds but removal of the existing owner role fails, when granting a maintainer role to an existing owner, the new role is added before the owner role is removed; if removal fails, the request errors but the user retains owner permissions. The caller sees a failed demotion while the user's access is unchanged.

Make role replacement atomic or restore the prior role state whenever any step of the replacement fails.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and if the access-control matcher or policies grant broader rights than intended, unauthorized users could modify or delete services; those changes would remain even after reverting this PR. This defines the authorization boundary for every deployment, so a mistaken policy could take effect silently across the board.

Blocking findings: cloud_registry/ga4gh/registry/server.py:107, cloud_registry/ga4gh/registry/permissions.py:281, cloud_registry/ga4gh/registry/server.py:168, cloud_registry/ga4gh/registry/permissions.py:172, cloud_registry/ga4gh/registry/server.py:107, and 3 more


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

Comment thread cloud_registry/ga4gh/registry/server.py Resolved
Comment thread cloud_registry/ga4gh/registry/server.py Resolved
Comment thread cloud_registry/ga4gh/registry/server.py Resolved
uniqueg and others added 3 commits October 20, 2026 17:50
Address Sourcery findings:

- Clear roles left on an identifier before making the creator owner of
  a new service, so roles of a deleted service (e.g., if revoking them
  failed) don't apply to a new one with the same identifier.
- Delete a new service again if its owner can't be stored, so that it
  doesn't stay without an owner; identifiers FOCA can't store in policy
  rules (e.g., with commas) return 400 instead of 500.
- Revoke other roles before granting a role, so that a failure leaves
  the user with fewer rights, not more.
- Delete stored names when granting a user's first role on a service,
  so that a name stored by a request racing with a revocation isn't
  shown with the new role.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings on the previous commit: test that a failed
grant leaves the user with fewer rights and that services are rolled
back when storing their owner fails for other reasons; roll back roles
too; split the rollback by error type; document the ordering and all
errors of `putServicePermission`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test permissions of unknown services, revoking invalid user
identifiers, a concurrent deletion during the owner restore and claims
without a validated token, for full coverage (Codecov).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit a807793 into dev Oct 20, 2026
11 checks passed
@uniqueg
uniqueg deleted the feat/access-control-signed branch October 20, 2026 16:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cloud Registry backend: public read access, service ownership, ECP_CLN:ADMIN admin role

1 participant