Skip to content

feat(auth): support service tokens - #371

Merged
uniqueg merged 7 commits into
devfrom
feat/service-tokens
Oct 22, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/service-tokens

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #340.

Services in ELIXIR On-Cloud call each other with OAuth 2.0 client-credentials tokens (e.g., a workflow engine calling a task service). These tokens represent the client, not a user, and have no user info. This PR adds support for them:

  • security.auth.service_clients (client_id, subject, on_behalf_of). A token is a service token if it was issued to a service client (client_id claim, else azp) and its subject (claim_identity) is the client's configured subject (default: the client ID). Detection is configurable rather than relying on sub == client_id alone, because what LS Login puts into its client-credentials tokens has not been verified. The docs say so and ask deployers to check a token per client.
  • No user info is requested for service tokens (neither userinfo_claims nor validate_userinfo). token_info["service_client"] holds the client ID (None for other tokens).
  • Access control enforces service tokens as client:<client ID> plus the role from the new access_control.client_mapping (keys must be service clients). Group claims apply as for users. The permissions API visibility filter uses the same subjects.
  • Resource role helpers accept subject_type="client". Roles starting with client: cannot be granted, and subject_prefix must not overlap with client:.
  • get_current_client() and get_on_behalf_of_user(user=None): service clients with on_behalf_of: true may name the user they act for, either in security.auth.on_behalf_of_header or in a value the app passes (e.g., a request field). Other callers naming a user get 403, and empty or blank names get 400.
  • If security.auth.clients is restricted, service clients must be among the accepted clients (validated on startup).
  • _verify_client now shares get_token_client() with service client detection.
  • Docs: a "Service tokens" section in Authentication, a "Service clients" section in Access control, the configuration pages, the reference, the template config and the 0.16 migration guide.

How it was verified

  • ruff format --check, ruff check foca tests: clean
  • mypy foca tests (strict): no issues
  • pytest (Python 3.13): 1325 passed without MongoDB-backed tests after the Sourcery fixes (1354 passed with MongoDB before them; CI runs all); coverage of foca/security/* and foca/models/config.py is 100%
  • pytest (Python 3.11, with MongoDB): 1353 passed, 1 skipped
  • mkdocs build --strict: clean
  • CI: all checks green (unit tests on Python 3.11-3.14 with MongoDB 7.0/8.0 and lowest dependencies, lint/type-check/build, petstore integration, charts, Read the Docs, codecov patch and project)

Review fixes (local reviewers, round 1)

  • Service tokens are now identified by their client in is_permitted(). Before, a service token without the access control claim_identity (e.g., email) got a 401.
  • get_on_behalf_of_user() now rejects non-string values and values with surrounding whitespace with 400.
  • New warnings: service clients combined with several trusted issuers, and on_behalf_of_header set while no service client has on_behalf_of.
  • Updated docstrings for subject_type="client"; added tests for the self-service visibility filter and the no-request-context case.

Review fixes (Sourcery)

  • Roles in client_mapping and group_mapping that start with subject_prefix, group: or client: are rejected on startup. group_mapping had the same gap, so it is covered too, and the migration guide mentions it.
  • userinfo_claims cannot contain client_id or azp, so the client is always identified from the verified token.
  • The docs now say that service client subjects must be values that users cannot have.

Declined review findings

  • Sourcery: user tokens with the same subject are treated as service tokens. This is the agreed design: detection is configurable because LS Login client-credentials tokens are unverified, and the docs cover it.

  • Sourcery: stored client: rules become active. Such rules matched no one before this PR, so configuring the service client is the deliberate act that activates them.

  • Sourcery: stored g2 rules that grant client: roles should be migrated. FOCA keeps its existing behaviour for subject-like roles, a startup warning plus revocation via remove_resource_role(), rather than deleting stored data.

  • Sourcery: return 400 before 403. Checking authorization before validating input is intentional.

  • Scoping service clients by issuer (adversarial, low-medium). Service clients are not tied to an issuer. With several trusted issuers, a client ID registered at a second issuer could act as the service client, including on_behalf_of. Adding an optional issuer field to ServiceClientConfig would be a new config design decision, so this PR does not add one. Instead, FOCA warns when service clients are combined with several issuers, and the docs explain the risk. This matches how clients, subjects and group claim values are handled today. Maintainer decision wanted: add service_clients[].issuer in a follow-up?

  • Computing the service client once per request (quality, low). get_service_client() runs at validation and again in access control. It is a cheap, pure function of the claims and the config, so the two always agree. Threading the result through Connexion's token_info would couple access control to the token-info layout.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Support OAuth 2.0 service tokens as first-class authenticated clients with client-scoped authorization and optional on-behalf-of user handling.

New Features:

  • Add configurable OAuth 2.0 service-token recognition with client metadata and optional user-info bypass.
  • Enforce service-client access through client-scoped subjects, mapped roles, group claims, and permissions visibility.
  • Support identifying users acted for by authorized service clients and assigning resource roles to clients.

Bug Fixes:

  • Prevent user-info claims from overriding token client identity and reject invalid service-client configuration.

Enhancements:

  • Extend resource-role helpers and access-control subject handling to support service clients.
  • Validate service-client acceptance, role-prefix collisions, and potentially unsafe multi-issuer configurations.

Documentation:

  • Document service-token authentication, service-client access control, configuration, reference APIs, templates, and migration requirements.

Tests:

  • Add coverage for service-token detection, access enforcement, client mappings, on-behalf-of handling, resource roles, visibility filtering, and configuration validation.

uniqueg and others added 5 commits October 22, 2026 02:17
Service clients (security.auth.service_clients) call the app with
client-credentials tokens of their own. A token is a service token if
it was issued to a service client (client_id claim, else azp) and its
subject is the client's configured subject (default: its client ID),
so that detection does not rely on sub == client_id alone. No user
info is requested for service tokens, and token_info has the client ID
as service_client.

Access control enforces policies on service tokens with the subject
client:<client ID> and the role from access_control.client_mapping.
Resource role helpers accept subject_type="client". Service clients
with on_behalf_of may name the user they act for (header
auth.on_behalf_of_header or an app-provided value), available via
get_on_behalf_of_user(); other callers naming users get 403.

Service clients must be among the accepted clients if clients are
restricted, and subject_prefix must not overlap with client:.

Refs #340

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document service clients, on-behalf-of users and client subjects in
access control, including that what LS Login puts into
client-credentials tokens is unverified, so that subjects must be
checked per client. List the new options in the configuration pages,
the template config and the 0.16 migration guide.

Refs #340

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Identify service tokens by their client in is_permitted(), so that they
need not have the identity claim of access control. Reject named users
that are not strings or have surrounding whitespace. Warn about service
clients with several trusted issuers, and about an on-behalf-of header
without service clients acting for users. Update docstrings for the
client subject type and test the self-service visibility filter.

Refs #340

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Avoid a semgrep false positive (credential disclosure) on a debug log
that names the client ID only.

Refs #340

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

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds end-to-end OAuth 2.0 client-credentials support: configured service tokens bypass user-info lookup, are represented as isolated client subjects in access control with optional mapped roles, and can safely act on behalf of users through new APIs and validation rules.

Sequence diagram for service token validation

sequenceDiagram
    participant Client as ServiceClient
    participant Auth as AuthValidation
    participant IdP as IdentityProvider
    participant App as Application

    Client->>Auth: validate_token(token)
    Auth->>Auth: get_token_client(claims)
    Auth->>Auth: get_service_client(claims, conf)
    alt Service token
        Auth-->>App: token_info with service_client
        Note over Auth,IdP: User-info lookup is skipped
    else Other token
        Auth->>IdP: userinfo request when configured
        IdP-->>Auth: user claims
        Auth-->>App: token_info with service_client=None
    end
Loading

Sequence diagram for service client acting on behalf of a user

sequenceDiagram
    actor Caller
    participant API as Controller
    participant Authz as AccessControl
    participant Service as ServiceClient

    Caller->>API: Request with user name
    API->>Authz: get_on_behalf_of_user(user)
    Authz->>Service: get_service_client(claims, conf)
    alt Client may act on behalf of users
        Authz-->>API: user identifier
        API->>API: add_resource_role(subject, role, resource)
    else Caller is not authorized
        Authz-->>API: 403 Forbidden
    end
Loading

Flow diagram for service token access control

flowchart LR
    Token[Service token] --> Detect[get_service_client]
    Detect --> ClientSubject[client:client_id]
    Detect --> Mapping{client_mapping entry}
    Mapping -->|mapped| ClientRole[Mapped role]
    Mapping -->|unmapped| Policy[Policy enforcement]
    ClientSubject --> Policy
    ClientRole --> Policy
    Groups[Group claims] --> Policy
    Policy --> Decision[is_permitted]
Loading

File-Level Changes

Change Details Files
Adds configurable service-token detection and skips user-info retrieval for tokens representing registered service clients.
  • Introduces service-client configuration with client ID, expected token subject, and optional on-behalf-of capability.
  • Identifies clients from client_id or azp, exposes the detected client in token info, and shares lookup logic with accepted-client validation.
  • Validates service-client configuration, accepted-client restrictions, duplicate IDs, and relevant startup warnings.
foca/models/config.py
foca/security/auth.py
tests/models/test_config.py
tests/security/test_auth.py
docs/authentication.md
docs/configuration/auth.md
docs/reference.md
templates/config.yaml
Integrates service clients into access-control subject resolution and policy enforcement.
  • Uses client:<client ID> subjects and optional client_mapping roles for service tokens while preserving group claims.
  • Updates permissions visibility filtering and authorization behavior, including tokens without a user identity claim.
  • Prevents client-prefixed roles and overlapping subject prefixes from creating Casbin subject/role collisions.
foca/models/config.py
foca/security/access_control/constants.py
foca/security/access_control/enforcement.py
foca/security/access_control/access_control_server.py
foca/security/access_control/__init__.py
tests/security/access_control/test_service_clients.py
docs/access-control.md
docs/configuration/access-control.md
docs/migration-0.16.md
Adds APIs for service-client identity and controlled user impersonation, plus client-aware resource roles.
  • Adds get_current_client() and get_on_behalf_of_user() with header/request-value support and 400/403 validation rules.
  • Allows resource-role helpers to use subject_type="client" and rejects granting reserved client subjects as roles.
  • Documents service-client ownership, on-behalf-of usage, and migration constraints.
foca/security/access_control/enforcement.py
foca/security/access_control/__init__.py
tests/security/access_control/test_service_clients.py
docs/access-control.md
docs/authentication.md

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (c171298) to head (2a4dad4).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #371    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           25        25            
  Lines         2014      2120   +106     
==========================================
+ Hits          2014      2120   +106     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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 22, 2026 00:38

@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 6 issues

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

## Individual Comments

### Comment 1
<location path="foca/security/access_control/enforcement.py" line_range="233" />
<code_context>
+        subjects = [_prefix_subject(client.client_id, "client")]
+        mapping = _get_access_control_config().client_mapping or {}
+        if client.client_id in mapping:
+            subjects.append(mapping[client.client_id])
+    return list(dict.fromkeys([*subjects, *get_current_groups()]))
+
</code_context>
<issue_to_address>
**Mapped clients inherit other permissions**

When `client_mapping` maps a service client to a value beginning with `client:`, `user:`, or `group:`, `_get_current_policy_subjects()` appends the mapping value as a policy subject, so Casbin resolves policies for the principal named by that prefix. The mapped client then receives that principal’s permissions.

Reject mapping values that begin with a reserved subject prefix, or otherwise ensure mapped roles cannot be interpreted as policy subjects.

Also at `foca/models/config.py:657`, `foca/models/config.py:1240-1245`.
</issue_to_address>

### Comment 2
<location path="foca/security/auth.py" line_range="152" />
<code_context>
         escape_log_value(claims[conf.claim_identity]),
     )

+    service_client = get_service_client(claims=claims, conf=conf)
     return {
         "jwt": token,
</code_context>
<issue_to_address>
**User tokens gain client privileges**

When `client_id` or `azp` is configured in `userinfo_claims`, absent from a verified token, and user info supplies a service client ID while the token subject matches that client's configured subject, `validate_token()` reclassifies the claims after `_validate()` may have added `client_id` or `azp` from user info. Access control then treats the token as that service client, granting its mapped permissions and on-behalf-of authority even though the verified token did not identify that client.

Base service-client classification only on the verified token's original client claims, and ensure access control uses that same classification.
</issue_to_address>

### Comment 3
<location path="foca/security/auth.py" line_range="203" />
<code_context>
+    for client in conf.service_clients:
+        if client.client_id == client_id:
+            subject = client.client_id if client.subject is None else client.subject
+            return client if claims.get(conf.claim_identity) == subject else None
+    return None
+
</code_context>
<issue_to_address>
**User token can be classified as client**

When a service client also obtains user tokens and a user’s identity claim equals that client’s configured service-token subject, `get_service_client()` treats the token as a service token whenever its client claim and identity claim match the configured values. A user token obtained by that same client with the same subject is therefore given the client’s access-control identity, skips user-info requests, and can use client-only permissions instead of the user’s.

Require a reliable token claim that distinguishes client-credentials grants from user grants, or explicitly constrain and validate the configured service subject so it cannot match a user subject.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/enforcement.py" line_range="230" />
<code_context>
+    if client is None:
+        subjects = [_prefix_subject(str(get_current_subject()))]
+    else:
+        subjects = [_prefix_subject(client.client_id, "client")]
+        mapping = _get_access_control_config().client_mapping or {}
+        if client.client_id in mapping:
</code_context>
<issue_to_address>
**Legacy rules grant clients access**

When an existing policy names `client:<ID>` and a service client with that ID is configured, the service token is checked as `client:<client ID>`, so a previously stored policy with that subject now matches directly and grants the client its permissions, even though the rule predates service-client support. The client receives access that was not intended for it.

Document an upgrade audit for existing policies using `client:` subjects before enabling service clients, and require operators to resolve ambiguous rules.
</issue_to_address>

### Comment 5
<location path="foca/security/access_control/enforcement.py" line_range="343-344" />
<code_context>
     if checked:
         return
-    prefixes = (_get_subject_prefix("user"), _get_subject_prefix("group"))
+    prefixes = (_get_subject_prefix("user"), *SUBJECT_TYPE_PREFIXES.values())
     for ptype in _get_resource_role_ptypes(enforcer.get_model()):
         for subject, role, resource in enforcer.get_named_grouping_policy(ptype):
             if role.startswith(prefixes):
</code_context>
<issue_to_address>
**Users inherit client permissions**

When a persisted resource-role rule grants `client:<id>` as a role, or `client_mapping` maps a client to a prefixed subject, casbin treats the `client:` role as the service client subject, so a user granted that role inherits the client’s resource permissions; a client mapping to a prefixed subject likewise grants that subject’s permissions. The legacy-rule check only logs a warning, and mapped roles are not checked.

Reject subject-prefixed values in `client_mapping` and migrate or revoke existing resource-role rows whose roles use reserved subject prefixes.

Also at `foca/security/access_control/enforcement.py:233`.
</issue_to_address>

### Comment 6
<location path="foca/security/access_control/enforcement.py" line_range="192-199" />
<code_context>
+        user = request.headers.get(header)
+        if user is None:
+            return None
+    client = _get_current_service_client()
+    if client is None or not client.on_behalf_of:
+        logger.info(
+            "Request naming user '%s' rejected: not a service client allowed "
+            "to act for users",
+            escape_log_value(user),
+        )
+        raise Forbidden(description="Only allowed service clients may act for users")
+    # Values passed by the app may come from request fields of any type
+    if not isinstance(user, str) or not user.strip():
</code_context>
<issue_to_address>
**Invalid names return forbidden**

When a caller that is not an allowed service client supplies an empty, whitespace-only, or non-string on-behalf-of value, `get_on_behalf_of_user()` checks client authorization before validating the supplied name, so it raises `Forbidden` instead of `BadRequestProblem`. The caller sees 403 instead of the documented 400 response.

Validate the supplied name before checking whether the caller may act for users.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and a misclassified token or incorrect client-role mapping could let a service client act with unintended permissions, and an allowed client can name users through the on-behalf-of helper. Reverting stops the new behavior, but any data exposed or actions already taken cannot be undone.

Blocking findings: foca/security/access_control/enforcement.py:233, foca/security/auth.py:152, foca/security/auth.py:203, foca/security/access_control/enforcement.py:230, foca/security/access_control/enforcement.py:344, and 1 more


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

Comment thread foca/security/auth.py Resolved
Comment thread foca/security/auth.py Resolved
uniqueg and others added 2 commits October 22, 2026 02:47
Roles of group_mapping and client_mapping must not start with a
subject prefix (subject_prefix, group:, client:), as mapped groups or
clients would otherwise get the rights of that subject. Claims
identifying the client (client_id, azp) cannot be added from user
info, so that user info cannot make a token look like a service token
or a token of an accepted client. Document both and the need for
service client subjects that users cannot have.

Refs #340

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 391013f into dev Oct 22, 2026
15 checks passed
@uniqueg
uniqueg deleted the feat/service-tokens branch October 22, 2026 01:14
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.

1 participant