Skip to content

feat: add startup checks of the config - #466

Merged
uniqueg merged 6 commits into
devfrom
feat/startup-config-checks
Oct 24, 2026
Merged

uniqueg merged 6 commits into
devfrom
feat/startup-config-checks

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Moves the generic startup checks of cloud-registry into FOCA, run by Foca.create_app():

  • Access control (in register_access_control(), only if access control is enabled, before anything is registered or stored):
    • logs (INFO) the groups and service clients mapped to admin;
    • warns if no group (with claim_groups set) or service client (client_mapping) is mapped to admin and no configured g rule (policies) that applies grants it (rules for group: subjects count only if group claim values are used as group subjects), saying that roles granted via stored rules still apply. Service clients count as FOCA treats them as admins (is_admin()); only direct grants are checked;
    • new option security.access_control.require_admin (default false; requires enabled, like the other options): refuses to start (ValueError) instead of warning;
    • warns if group_mapping is set without claim_groups, or without keep_group_subjects, and if claim_groups has surrounding whitespace.
  • Service clients: public foca.security.auth.require_no_service_clients(app=None) (checks the given Flask app, or the current FOCA app; raises RuntimeError if security.auth.service_clients or on_behalf_of_header is set); not run by FOCA.
  • Placeholder service info (in check_service_info(), on the complete service info including runtime fields): warns, naming the fields, if id is in a reserved example domain in reverse DNS notation (example., com.example, net.example, org.example), or the host of organization.url, contactUrl or documentationUrl is one (example.com|net|org, *.example, subdomains; the address domain for mailto:).
  • Docs: startup checks in docs/configuration/access-control.md, placeholders in docs/configuration/service-info.md, require_no_service_clients() in docs/authentication.md and the API reference, a list of startup checks in docs/deployment.md, the option in templates/config.yaml, and the new warnings and option in docs/migration-0.18.md.

Backwards compatible: only new log messages; the only new error is opt-in. Messages name the setting to change and contain no claim values other than configured group names (escaped).

The log fixture (capturing logs after Foca() configures logging) moves from tests/api/test_service_info.py to tests/conftest.py, for the new create_app() tests.

Verification

  • pre-commit run --all-files: passed
  • ruff check, ruff format --check, mypy: passed
  • coverage run -m pytest (with MongoDB 7.0 on port 12345) + coverage report: 2324 passed (after merging dev), 100% coverage
  • mkdocs build --strict: passed
  • Two review rounds (adversarial + quality reviewer subagents); findings fixed except those below. Sourcery's four findings fixed (whitespace claim, explicit app for require_no_service_clients(), empty group_mapping, logging unapplied admin groups).
  • CI on the first push: all checks passed.

Declined review findings

  • The group_mapping-without-keep_group_subjects warning fires for apps that only map roles (low): issue feat: add startup checks of the config #459 asks for exactly this warning; it names the setting and only adds a log line. Lowering it to INFO, or warning only if rules for group: subjects are configured, can follow if it turns out noisy.
  • Reachability of indirect admin grants (low): rules granting admin to a role nobody can get, or to a client: subject that is not a service client, still count. Checking that would need a fixpoint over the g rules and the auth config; documented instead that only direct grants are checked.

Open questions

  • From the issue, kept as decided there: should group_mapping without claim_groups, and a group claim with surrounding whitespace, become errors (as in cloud-registry), e.g., from FOCA 1.0? This PR keeps them warnings.

Follow-up in cloud-registry (separate issue): set security.access_control.require_admin: true, call require_no_service_clients(), and delete check_admin_groups(), check_no_service_clients(), warn_placeholder_service_info(), the placeholder constants and custom.access_control.

Closes #459

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 24, 2026 14:48
Move the generic startup checks of cloud-registry into FOCA:

- With access control enabled, log the groups mapped to the role
  `admin`, and warn if no group or configured rule grants it (roles of
  stored rules still apply); the new option
  `security.access_control.require_admin` (default: false) makes this
  an error. Warn if `group_mapping` is set without `claim_groups` or
  `keep_group_subjects`, and if `claim_groups` has surrounding
  whitespace.
- Add `foca.security.auth.require_no_service_clients()`, for apps
  whose endpoints don't support service clients; FOCA doesn't run it.
- Warn if the service info has values in reserved example domains
  (RFC 2606), as in templates.

The `log` fixture moves to `tests/conftest.py`, for the tests of
`Foca.create_app()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the checks of access control settings and `require_admin`,
placeholder service info, `require_no_service_clients()`, a list of
startup checks in the deployment guide, the option in the config
template, and the new warnings in the migration notes for 0.18.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Count service clients mapped to `admin` (`client_mapping`), count
groups mapped to it only with a group claim set, and configured rules
for groups only if group claim values are used as group subjects, so
that `require_admin` neither refuses valid nor passes ineffective
configurations. Simplify the placeholder check, test the group check
messages by table and document the changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rules granting `admin` to roles or service clients count whether or
not any request can have them. Also mention `claim_groups` in the
template comment of `require_admin`, and reflow edited paragraphs.

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

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds backward-compatible startup diagnostics for access-control misconfiguration and placeholder service metadata, with opt-in failure when no admin grant exists and a separate API for rejecting service clients; documentation, templates, and comprehensive tests are updated accordingly.

Sequence diagram for FOCA startup checks

sequenceDiagram
    participant App as Application
    participant Foca
    participant AccessControl as register_access_control()
    participant ServiceInfo as check_service_info()
    participant Logger

    App->>Foca: create_app()
    Foca->>AccessControl: register_access_control()
    AccessControl->>AccessControl: _check_group_config()
    AccessControl->>AccessControl: _check_admin_role()
    alt admin grant found
        AccessControl->>Logger: log mapped admins
    else no admin grant
        alt require_admin enabled
            AccessControl-->>Foca: raise ValueError
        else default behavior
            AccessControl->>Logger: log warning
        end
    end
    Foca->>ServiceInfo: check_service_info()
    ServiceInfo->>ServiceInfo: _placeholder_fields()
    alt placeholder fields found
        ServiceInfo->>Logger: log warning with field names
    end
    Foca-->>App: configured application
Loading

Sequence diagram for rejecting unsupported service clients

sequenceDiagram
    participant App as Application
    participant Foca
    participant Auth as require_no_service_clients()

    App->>Foca: create_app()
    Foca-->>App: configured application
    App->>Auth: require_no_service_clients()
    alt service_clients or on_behalf_of_header configured
        Auth-->>App: raise RuntimeError
    else neither configured
        Auth-->>App: return
    end
Loading

Flow diagram for access-control admin startup validation

flowchart TD
    A[Access control enabled] --> B["_check_group_config()"]
    B --> C["_check_admin_role()"]
    C --> D{Admin mapping or applicable policy rule?}
    D -->|Yes| E[Continue startup]
    D -->|No| F{require_admin enabled?}
    F -->|Yes| G[Raise ValueError]
    F -->|No| H[Log warning]
    H --> E
    B --> I[Warn about invalid group settings]
    I --> E
Loading

File-Level Changes

Change Details Files
Add access-control startup diagnostics and optional admin enforcement before registration or persistence.
  • Run group configuration checks only when access control is enabled.
  • Log admin groups and service clients, and inspect direct configured grants to the admin role.
  • Warn on missing admin grants by default or raise when require_admin is enabled.
  • Warn about ineffective group mappings, missing group claims, whitespace, and disabled group subjects.
  • Add and validate the security.access_control.require_admin option.
foca/models/config.py
foca/security/access_control/register_access_control.py
templates/config.yaml
tests/models/test_config.py
tests/security/access_control/test_register_access_control.py
tests/test_foca.py
Add a reusable application-level guard against unsupported service-client authentication.
  • Expose require_no_service_clients() through the authentication API and reference documentation.
  • Raise when service clients or on-behalf-of authentication is configured.
  • Keep the check opt-in rather than running it from FOCA startup.
foca/security/auth.py
docs/authentication.md
docs/reference.md
tests/security/test_auth.py
Detect and report placeholder service information during complete service-info checks.
  • Inspect runtime-computed fields as well as configured service information.
  • Detect reserved example domains in service IDs and URL or mailto hosts.
  • Log a warning naming placeholder fields while allowing startup to continue.
foca/api/service_info.py
docs/configuration/service-info.md
tests/api/test_service_info.py
Document startup behavior and migration implications across configuration and deployment guidance.
  • Document access-control, service-info, and authentication startup checks.
  • Describe warning versus failure behavior and configuration remedies.
  • Update migration notes and templates with the new option and APIs.
docs/access-control.md
docs/configuration/access-control.md
docs/deployment.md
docs/migration-0.18.md
docs/configuration/service-info.md
docs/authentication.md
docs/reference.md
templates/config.yaml
Expand test infrastructure and coverage for startup diagnostics.
  • Move the logging fixture to shared test configuration.
  • Cover access-control checks, admin enforcement ordering, service-client rejection, placeholder detection, and runtime fields.
tests/conftest.py
tests/api/test_service_info.py
tests/security/access_control/test_register_access_control.py
tests/security/test_auth.py
tests/test_foca.py

Assessment against linked issues

Issue Objective Addressed Explanation
#459 Run startup access-control checks when access control is enabled: log admin mappings, warn or optionally refuse startup when no configured admin grant exists, and warn about ineffective group-claim and group-subject settings. ✅
#459 Provide a public require_no_service_clients() check for apps that do not support service clients, without running it automatically from FOCA. ✅
#459 Warn about reserved example-domain placeholders in configured service-info fields, and document the checks, option, and migration behavior in the requested docs and template. ✅

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7802f8e) to head (f89b8a1).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #466   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         3378      3446   +68     
=========================================
+ Hits          3378      3446   +68     
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 24, 2026 13:08

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

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

## Individual Comments

### Comment 1
<location path="foca/security/access_control/register_access_control.py" line_range="245" />
<code_context>
+            `require_admin` is set.
+    """
+    conf = access_control_config
+    has_groups = bool(conf.claim_groups)
+    keeps_group_subjects = has_groups and (
+        conf.group_mapping is None or conf.keep_group_subjects
</code_context>
<issue_to_address>
**Startup accepts missing admin access**

When `claim_groups` has surrounding whitespace, a group maps to `admin`, `require_admin` is true, and no other admin grant applies, `bool(conf.claim_groups)` treats the padded name as configured, so `_check_admin_role` counts the mapping even though tokens using the unpadded claim provide no group admin; startup succeeds without an effective admin grant.

Normalize or reject whitespace-padded `claim_groups` before checking whether group mappings provide an admin grant.
</issue_to_address>

### Comment 2
<location path="foca/security/auth.py" line_range="272" />
<code_context>
+            current app context, if any, otherwise the most recently
+            created one (cf. :py:func:`foca.config.access.get_config`).
+    """
+    auth = get_config().security.auth
+    if auth.service_clients or auth.on_behalf_of_header is not None:
+        raise RuntimeError(
</code_context>
<issue_to_address>
**Startup checks the wrong app**

When multiple FOCA apps have different service-client settings and the helper runs outside the target app's context after another app was created, `require_no_service_clients()` calls `get_config()` without an app argument, so it checks the most recently created app instead of the target app; unsupported settings can pass for one app or spuriously reject another.

Make `require_no_service_clients()` read the configuration belonging to the app whose startup check is running.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/register_access_control.py" line_range="202" />
<code_context>
+            "have no groups: remove the whitespace.",
+            claim_groups,
+        )
+    if conf.group_mapping and not claim_groups:
+        logger.warning(
+            "Groups are mapped to roles "
</code_context>
<issue_to_address>
**Empty mapping hides missing group claim**

When `group_mapping` is `{}`, `claim_groups` is unset, and `keep_group_subjects` is true, `_check_group_config` skips its missing-claim warning for an empty `group_mapping`. With `keep_group_subjects: true`, group subjects then cannot be obtained because no `claim_groups` is configured, so group-based rules silently do not apply.

Check `conf.group_mapping is not None` rather than its truthiness when deciding whether to warn about a missing group claim.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/register_access_control.py" line_range="257" />
<code_context>
+        mapped = sorted(
+            key for key, role in (mapping or {}).items() if role == ADMIN_ROLE
+        )
+        if mapped and applies:
+            found = True
+            logger.info(
</code_context>
<issue_to_address>
**Configured admin groups go unlogged**

When `group_mapping` maps one or more values to `admin` but `claim_groups` is unset, `applies` is false when `claim_groups` is unset, so `_check_admin_role` skips logging group values mapped to `admin`. The startup warning identifies the missing claim setting but omits the configured group names, contrary to the documented promise to log those mappings.

Log configured admin group values regardless of whether the mapping currently applies, and separately indicate whether they are effective.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: foca/security/access_control/register_access_control.py:245, foca/security/auth.py:272, foca/security/access_control/register_access_control.py:202


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

Comment thread foca/security/auth.py Resolved
uniqueg and others added 2 commits October 24, 2026 15:13
- Don't count groups mapped to `admin` if the group claim has
  surrounding whitespace, but log mapped groups that don't apply.
- Warn about a missing group claim also with an empty `group_mapping`.
- `require_no_service_clients()` takes an optional app to check, for
  processes with several FOCA apps.

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

@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.

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit 24934d0 into dev Oct 24, 2026
32 checks passed
@uniqueg
uniqueg deleted the feat/startup-config-checks branch October 24, 2026 13:23
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.

feat: add startup checks of the config

1 participant