Repository navigation
feat(auth): support service tokens - #371
Conversation
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]>
Reviewer's GuideThis 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 validationsequenceDiagram
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
Sequence diagram for service client acting on behalf of a usersequenceDiagram
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
Flow diagram for service token access controlflowchart 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]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
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_idclaim, elseazp) and its subject (claim_identity) is the client's configuredsubject(default: the client ID). Detection is configurable rather than relying onsub == client_idalone, 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.userinfo_claimsnorvalidate_userinfo).token_info["service_client"]holds the client ID (Nonefor other tokens).client:<client ID>plus the role from the newaccess_control.client_mapping(keys must be service clients). Group claims apply as for users. The permissions API visibility filter uses the same subjects.subject_type="client". Roles starting withclient:cannot be granted, andsubject_prefixmust not overlap withclient:.get_current_client()andget_on_behalf_of_user(user=None): service clients withon_behalf_of: truemay name the user they act for, either insecurity.auth.on_behalf_of_headeror in a value the app passes (e.g., a request field). Other callers naming a user get403, and empty or blank names get400.security.auth.clientsis restricted, service clients must be among the accepted clients (validated on startup)._verify_clientnow sharesget_token_client()with service client detection.How it was verified
ruff format --check,ruff check foca tests: cleanmypy foca tests(strict): no issuespytest(Python 3.13): 1325 passed without MongoDB-backed tests after the Sourcery fixes (1354 passed with MongoDB before them; CI runs all); coverage offoca/security/*andfoca/models/config.pyis 100%pytest(Python 3.11, with MongoDB): 1353 passed, 1 skippedmkdocs build --strict: cleanReview fixes (local reviewers, round 1)
is_permitted(). Before, a service token without the access controlclaim_identity(e.g.,email) got a401.get_on_behalf_of_user()now rejects non-string values and values with surrounding whitespace with400.on_behalf_of_headerset while no service client hason_behalf_of.subject_type="client"; added tests for the self-service visibility filter and the no-request-context case.Review fixes (Sourcery)
client_mappingandgroup_mappingthat start withsubject_prefix,group:orclient:are rejected on startup.group_mappinghad the same gap, so it is covered too, and the migration guide mentions it.userinfo_claimscannot containclient_idorazp, so the client is always identified from the verified token.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
g2rules that grantclient:roles should be migrated. FOCA keeps its existing behaviour for subject-like roles, a startup warning plus revocation viaremove_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 optionalissuerfield toServiceClientConfigwould 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 howclients, subjects and group claim values are handled today. Maintainer decision wanted: addservice_clients[].issuerin 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'stoken_infowould 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:
Bug Fixes:
Enhancements:
Documentation:
Tests: