Skip to content

feat: limit services per user - #286

Merged
uniqueg merged 6 commits into
devfrom
feat/services-limit
Oct 29, 2026
Merged

uniqueg merged 6 commits into
devfrom
feat/services-limit

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Users other than admins may only have registered a limited number of the
registered services: custom.access_control.max_services_per_user, default
50, null = no limit, 0 = admins only. Further POST /services get 409
with code services-limit. Config only (Helm: via config), like
max_unused_service_types.

  • What counts: the service stores who registered it in the hidden field
    _createdBy (not served; kept on updates and renames; null for services
    that admins register in admin mode). A service keeps counting for its
    creator whatever its roles later, so handing it to a group doesn't free a
    place. Updates, renames, role grants and accepted invitations never fail
    on the limit.
  • Concurrency: a counter per user (service_counts) is reserved with an
    atomic conditional $inc before the service is stored. It is released on
    failed registrations and on deletes (find_one_and_delete returns the
    creator), so concurrent registrations can't exceed the limit. A
    concurrent first reservation that loses the counter insert retries without
    upsert.
  • Startup: services stored before get the user who is their only
    owner (no or several user owners: they count for nobody). The counters
    are then reconciled with the stored services (compare-and-set, so
    concurrent requests aren't overwritten).
  • Migration of subjects (namespace_subjects): also namespaces
    _createdBy, and moves the counters of bare users.
  • Published in the service info (registration_rules.max_services_per_user).
    Documented in the API spec, docs/configuration.md "Services per user",
    access control, API, docs/upgrading.md "From 0.6.0", and the chart
    README's rate-limit section.
  • Writes per time window stay out of the app, as decided (ingress rate
    limits, already documented); the issue's Helm-values step is dropped for
    consistency with the type limit.

Closes #124

Release notes (for v1.0.0rc1, under Features)

Verification

  • coverage run -m pytest (mongomock): 1509 passed, 262 skipped, coverage
    100%.
  • Full suite against an own MongoDB 7.0.34 (port 27124, removed afterwards):
    1515 passed, 255 skipped (before the last review fixes; their tests,
    tests/test_service_limits.py, test_namespace_subjects.py and
    test_issuers.py, passed against it afterwards). This covers concurrent registrations (30
    parallel POSTs, limit 5: exactly 5 pass), concurrent reservations, and
    concurrent first reservations of fresh users (no spurious refusals).
  • pre-commit run --all-files (ruff, mypy, semgrep, ast-grep, gitleaks,
    actionlint): passed.
  • mkdocs build --strict: passed.
  • Reviews: adversarial and quality reviewers, 2 rounds.
  • CI: all checks passed (CI passed; Test (mongomock), Test (MongoDB 7.0), Lint,
    Docs, Chart, Smoke test, Scan image, Release readiness, CodeQL, Read the Docs).

Declined review findings

  • Backfill makes one role lookup per service without _createdBy
    (N+1 on the first start): it's a one-off. Later starts query the new
    index and find none.

  • Production projection of the delete includes id (a mongomock quirk
    returns no document for projections without fields). It's harmless and
    commented.

  • Release guard catches Exception, not BaseException: a worker abort
    (e.g., a Gunicorn timeout) can leave one reservation. It's corrected
    when the worker restarts, because create_app() reconciles in every
    worker.

  • Sourcery: drift after writes whose acknowledgement is lost, drift from
    reservations in flight during startup reconciliation, and a delete during
    the subject migration. Each is bounded (one per affected request),
    reconciled when any worker starts, and documented; avoiding them would
    need transactions (replica sets) or a distributed lock.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 5 commits October 28, 2026 22:13
Users other than admins may only have registered
`custom.access_control.max_services_per_user` of the registered
services (default 50, `null` for no limit, `0` for admins only);
further `POST /services` get `409` with code `services-limit`.

Services count for the user who registered them, stored in the hidden
field `_createdBy` (kept on updates and renames, not served; `null` for
services registered by admins in admin mode). A counter per user
(collection `service_counts`) is reserved with an atomic conditional
`$inc` before the service is stored, released on failed registrations
and on deletes, so concurrent registrations can't exceed the limit. On
startup, the app adds the user to services stored before (the only
user owner, if any) and reconciles the counters.

The limit is published in the registration rules of the service info,
and documented in the configuration, access control, API and upgrade
docs.

Closes #124

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	cloud_registry/config.yaml
#	cloud_registry/service_models/custom_config.py
#	docs/configuration.md
#	docs/upgrading.md
- Concurrent first registrations of a user no longer get a spurious
  `services-limit`: a counter inserted by a concurrent request is
  incremented by a retry without upsert (MongoDB doesn't retry upserts
  whose filter isn't the key alone).
- The subject migration (`namespace_subjects`) namespaces `_createdBy`
  of services and moves the counters of bare users.
- Deletes use `find_one_and_delete`: the tests that hook into deletes of
  services follow it (they failed on real MongoDB only).
- The limit's detail no longer claims a count the user may not have
  (e.g., with a limit of `0`); `reserve_service()` returns nothing; the
  release on failed registrations catches `Exception`.
- Docs: drift bound of the counters, the key in the chart README, the
  upgrade query with the deployment's limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Failed registrations release the reservation only if the service
  wasn't stored (e.g., a read after the insert failed).
- The subject migration deletes a bare counter before it adds its value
  to the namespaced one, so concurrent changes aren't lost; it uses one
  helper for namespaced subjects, and its docstring names `services`.
- The log of refused registrations names the limit, not a count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v1.0.0-rc1 milestone Oct 29, 2026
@uniqueg uniqueg added priority: medium Medium priority type: feature New feature or request type: security Related to security labels Oct 29, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces a default limit of 50 registered services per non-admin user, enforced with atomic per-user MongoDB counters and hidden creator metadata, including cleanup, startup reconciliation, subject migration, API publication, documentation, and comprehensive concurrency and lifecycle coverage.

Sequence diagram for atomic service registration limits

sequenceDiagram
    actor User
    participant API as POST /services
    participant Counters as service_counts
    participant Services as services

    User->>API: postService()
    API->>Counters: reserve_service(user)
    alt reservation below configured limit
        Counters-->>API: atomic increment succeeds
        API->>Services: register_metadata()
        alt service storage fails
            API->>Counters: release_service(user)
        end
        API-->>User: 201 Created
    else limit reached
        Counters-->>API: reservation rejected
        API-->>User: 409 services-limit
    end
Loading

Sequence diagram for service deletion and counter release

sequenceDiagram
    actor User
    participant API as DELETE /services/{serviceId}
    participant Services as services
    participant Counters as service_counts

    User->>API: deleteService(serviceId)
    API->>Services: find_one_and_delete(serviceId)
    Services-->>API: deleted service with _createdBy
    API->>Counters: release_service(_createdBy)
    API-->>User: deletion succeeds
Loading

Entity relationship diagram for service registration counters

erDiagram
    SERVICES {
        string id PK
        string _createdBy
    }
    SERVICE_COUNTS {
        string _id PK
        int count
    }
    SERVICE_COUNTS ||--o{ SERVICES : counts
Loading

File-Level Changes

Change Details Files
Add configurable per-user service registration limits with atomic reservation and release accounting.
  • Add max_services_per_user configuration with defaults for unlimited and admins-only modes.
  • Reserve counters atomically before POST registration and release them on failed registration or deletion.
  • Return the services-limit conflict code and expose the effective limit through service metadata.
cloud_registry/ga4gh/registry/service_limits.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/service_models/custom_config.py
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/service_info.py
cloud_registry/api/additions.openapi.yaml
Persist service creators and maintain accounting across lifecycle operations and application restarts.
  • Store the hidden _createdBy field for non-admin registrations while preserving it across updates and renames.
  • Add startup backfill from sole user owners and compare-and-set counter reconciliation.
  • Use atomic deletion to retrieve the creator and release its counter.
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/app.py
cloud_registry/config.yaml
Extend subject namespacing and migration support for service ownership accounting.
  • Namespace _createdBy values for bare users.
  • Merge and move bare-user service counters into namespaced identities.
  • Include the migration in dry-run results and documentation.
cloud_registry/namespace_subjects.py
docs/upgrading.md
Document the new behavior and validate configuration, API exposure, concurrency, migration, and lifecycle edge cases.
  • Document configuration, access-control semantics, rate-limit boundaries, upgrade guidance, and API conflict metadata.
  • Add unit and MongoDB-backed concurrency tests for reservations, first inserts, cleanup, startup reconciliation, and creator backfill.
docs/configuration.md
docs/access-control.md
docs/api.md
deployment/README.md
tests/test_service_limits.py
tests/test_namespace_subjects.py
tests/test_service_info.py
tests/test_app.py
tests/ga4gh/registry/test_service.py
tests/test_access_control.py
tests/test_rename.py
tests/mock_data.py

Assessment against linked issues

Issue Objective Addressed Explanation
#124 Limit the number of services each user can register with a configurable limit, define admin/group counting behavior, and prevent concurrent creates from exceeding the limit while allowing updates. ✅
#124 Enforce the limit on service creation and return the issue-requested 429 or 403 response with a clear problem detail. ❌ The PR enforces the limit and provides a clear problem detail, but returns 409 Conflict (services-limit) rather than either 429 or 403 specified by the issue.
#124 Make the limit configurable and document its behavior, configuration, and how to disable it in the relevant user and deployment documentation. ✅

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 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (614195c) to head (c4f1bf7).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #286    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           21        22     +1     
  Lines         2195      2321   +126     
==========================================
+ Hits          2195      2321   +126     

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

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

@uniqueg
uniqueg marked this pull request as ready for review October 29, 2026 00:34

@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 7 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="304-308" />
<code_context>
+            store_pending_type(service.data.get("type"))
+            service.pending = is_pending(type_document(service.data.get("type")))
+            service.register_metadata()
+        except Exception:
+            # unless the service was stored (e.g., a read after the insert
+            # failed)
+            if not service.was_created:
+                release_service(service.created_by)
+            raise
+    except (InvalidService, UnusedTypesLimit, ServicesLimit) as exc:
</code_context>
<issue_to_address>
**Ambiguous writes corrupt service counts**

When mongoDB commits a service insert or delete but the client receives an error before the write result or corresponding counter update is confirmed, `RegisterService.register_metadata()` leaves `was_created` false until `insert_one()` returns, so `_register_service()` releases a reservation for a service that is already stored; when `find_one_and_delete()` commits but reports an error, deletion cleanup skips the decrement. Counts drift, allowing registrations beyond the limit or blocking valid registrations until startup reconciliation.

Determine whether each service write committed after an ambiguous error, then safely apply or reconcile its corresponding counter change before returning.

Also at `cloud_registry/ga4gh/registry/server.py:184`.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/service_limits.py" line_range="96" />
<code_context>
+    limit = get_custom_config(CustomConfig).access_control.max_services_per_user
+    counts = get_collection(SERVICE_COUNTS)
+    if limit is None:
+        counts.update_one({"_id": user}, {"$inc": {COUNT: 1}}, upsert=True)
+        return
+    if limit > 0 and _increment_below(user, limit):
</code_context>
<issue_to_address>
**Concurrent reservations corrupt counts**

When the limit is `null` and concurrent registrations make the first reservations for the same user, `counts.update_one(..., upsert=True)` can raise `DuplicateKeyError` when the same user makes concurrent first reservations. Unlike `_increment_below()`, this path does not retry; `_register_service()` then releases a reservation this request never acquired, so the caller gets a 500 and the other request’s count is decremented.

Handle `DuplicateKeyError` in the unbounded branch by retrying the increment without upsert, without releasing a count unless this request incremented it.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/service_limits.py" line_range="96" />
<code_context>
+    limit = get_custom_config(CustomConfig).access_control.max_services_per_user
+    counts = get_collection(SERVICE_COUNTS)
+    if limit is None:
+        counts.update_one({"_id": user}, {"$inc": {COUNT: 1}}, upsert=True)
+        return
+    if limit > 0 and _increment_below(user, limit):
</code_context>
<issue_to_address>
**Ambiguous reservations block users**

When mongoDB applies the increment but the client receives an error before the operation is acknowledged, `update_one` can commit the counter increment and then raise when its acknowledgment times out. `reserve_service` propagates that exception, and `_register_service` has not yet entered the cleanup `try`, so the reservation remains and later registrations can be refused until startup reconciliation.

Handle ambiguous reservation failures by reconciling the affected user’s counter against stored services before returning the error, without blindly decrementing a reservation that may not have been applied.

Also at `cloud_registry/ga4gh/registry/server.py:298`.
</issue_to_address>

### Comment 4
<location path="cloud_registry/ga4gh/registry/service_limits.py" line_range="242" />
<code_context>
+        query: dict[str, Any] = {"_id": user}
+        query[COUNT] = before if before is not None else {"$exists": False}
+        try:
+            result = counts.update_one(query, {"$set": {COUNT: after}}, upsert=True)
+        except DuplicateKeyError:
+            # changed or added concurrently
</code_context>
<issue_to_address>
**Startup erases an active reservation**

When a POST reserves a place before the startup counter snapshot, but stores its service only after the startup aggregate is read and the counter is reset, `reconcile_service_counts()` can set the counter to the number of stored services even though it includes a reservation for a service not stored yet. That reservation is lost when the service is inserted, so a subsequent registration can pass the limit and leave the user over it.

Prevent startup reconciliation from overwriting in-flight reservations, for example by quiescing registrations while reconciling or tracking reservations separately from stored-service counts.
</issue_to_address>

### Comment 5
<location path="cloud_registry/namespace_subjects.py" line_range="223-224" />
<code_context>
+        count += 1
+        if not dry_run:
+            services.update_one(
+                {"_id": service["_id"]},
+                {"$set": {SERVICE_CREATOR: _namespaced(namespace, subject)}},
+            )
+    counters = get_collection(SERVICE_COUNTS)
</code_context>
<issue_to_address>
**Migration restores a deleted service count**

When A service is deleted after its creator is namespaced but before its bare counter is transferred, and the namespaced counter is absent or zero, `_namespace_services()` rewrites the creator before the bare counter moves, so the delete does not reduce that stale bare count; the migration then transfers it to the namespaced user. The user is overcounted and registrations are refused until startup reconciliation.

Coordinate creator rewriting and counter transfer with deletions so a deleted service's count cannot be transferred.

Also at `cloud_registry/namespace_subjects.py:233-239`.
</issue_to_address>

### Comment 6
<location path="tests/test_service_limits.py" line_range="646-647" />
<code_context>
+        Returns:
+            The only user owner.
+        """
+        mongo_client[DB]["services"].update_many(
+            {CREATED_BY: {"$exists": False}}, {"$set": {CREATED_BY: "other"}}
+        )
+        return owner(path)
</code_context>
<issue_to_address>
**Backfill test masks no-op**

When the startup backfill iterates a service but does not perform its guarded update after calling `_single_user_owner`, `test_creators_added_concurrently` passes even if `add_service_creators()` never applies its own update: the patched `set_first` writes `other` to every missing service before the final assertion, so the test doesn't verify that the backfill preserves a concurrent value.

Make the simulated concurrent update occur independently of the helper call, then assert that the backfill leaves that inserted value intact.
</issue_to_address>

### Comment 7
<location path="tests/test_service_limits.py" line_range="738" />
<code_context>
+            DuplicateKeyError: For counters.
+        """
+        if self.name == SERVICE_COUNTS:
+            raise DuplicateKeyError("duplicate")
+        return update_one(self, *args, **kwargs)
+
</code_context>
<issue_to_address>
**Duplicate-key test masks no-op**

When the reconciliation update encounters the simulated `DuplicateKeyError`, `test_counters_inserted_meanwhile` passes if `reconcile_service_counts()` does nothing: the patched `update_one` raises without inserting a counter, and the test expects the collection to remain empty. It therefore doesn't verify that a counter inserted concurrently survives reconciliation.

Insert the counter in the patched method before raising `DuplicateKeyError`, and assert that reconciliation leaves that counter unchanged.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 7 findings to address first, and a mistaken creator attribution can persist on a service and skew which user’s quota is consumed; startup reconciliation repairs counters, but it does not correct an attribution that was already written. Reverting removes the registration limit, though any incorrect attribution data may need manual repair.

Blocking findings: cloud_registry/ga4gh/registry/server.py:308, cloud_registry/ga4gh/registry/service_limits.py:96, cloud_registry/ga4gh/registry/service_limits.py:96, cloud_registry/ga4gh/registry/service_limits.py:242, cloud_registry/namespace_subjects.py:224, and 2 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/namespace_subjects.py Resolved
Comment thread tests/test_service_limits.py Resolved
Comment thread tests/test_service_limits.py Resolved
Without a limit, a first reservation that loses a concurrent counter
insert increments the inserted counter instead of failing. The tests of
the concurrent backfill and of counters inserted during reconciliation
now fail if the code under test does nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: medium Medium priority type: feature New feature or request type: security Related to security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: limit services and writes per user

1 participant