Skip to content

feat(jans-fido2): retry MDS TOC download at startup when the blob is …#14483

Open
imran-ishaq wants to merge 3 commits into
mainfrom
jans-fido2-mds-toc-startup-retry
Open

feat(jans-fido2): retry MDS TOC download at startup when the blob is …#14483
imran-ishaq wants to merge 3 commits into
mainfrom
jans-fido2-mds-toc-startup-retry

Conversation

@imran-ishaq

@imran-ishaq imran-ishaq commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Description

At startup, the FIDO2 server (jans-fido2) fetches the FIDO Alliance MDS TOC blob (toc.jwt) exactly once via TocService.init() → fetchMetadata(). There is no retry loop. If that single download fails — e.g. a transient network glitch or a temporary outage of https://mds.fidoalliance.org/ — the server comes up with a missing/empty TOC in the DB and cannot validate authenticator attestations. The only subsequent attempt is the 24-hour MDS3UpdateTimer, so the server can remain without metadata for up to a day.

Additionally, the download runs synchronously on the ApplicationInitialized observer thread, so a slow/hanging MDS endpoint blocks application initialization.

A missing TOC specifically breaks the FIDO2 server (attestation validation), whereas a merely stale-but-present TOC still works — so the two cases should be treated differently.

Target issue

When the TOC blob is missing at startup, the server should retry the download a few times (configurable) before giving up, to ride out transient MDS outages.
Retries should apply only to the missing-TOC case, not to a stale-but-present TOC (which keeps the single-attempt behavior, matching the daily timer).
The startup download/retry should not block application initialization — it should run in the background.

closes #14482

Implementation Details


Test and Document the changes

  • Static code analysis has been run locally and issues have been fixed
  • Relevant unit and integration tests have been added/updated
  • Relevant documentation has been updated if any (i.e. user guides, installation and configuration guides, technical design docs etc)

Please check the below before submitting your PR. The PR will not be merged if there are no commits that start with docs: to indicate documentation changes or if the below checklist is not selected.

  • I confirm that there is no impact on the docs due to the code changes in this PR.

Summary by CodeRabbit

  • New Features
    • Added new FIDO2 settings for MDS TOC download startup retries and retry interval.
    • TOC metadata fetching now runs asynchronously at startup and can retry when TOC data is missing.
  • Bug Fixes
    • Automatically applies default retry configuration values when they aren’t set.
  • Documentation
    • Updated configuration guides, example JSON outputs, and Swagger schema to include the new settings.
  • Tests
    • Added coverage for TOC download/retry and “missing TOC” detection scenarios.

…missing

Signed-off-by: imran <imranishaq7071@gmail.com>
@imran-ishaq
imran-ishaq marked this pull request as ready for review July 2, 2026 14:09
@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds two new FIDO2 configuration properties, updates defaults and documentation, and reworks TocService to fetch MDS TOC metadata asynchronously at startup with retry behavior when the TOC blob is missing.

Changes

MDS TOC Startup Retry

Layer / File(s) Summary
Fido2Configuration retry fields and accessors
jans-fido2/model/src/main/java/io/jans/fido2/model/conf/Fido2Configuration.java
Adds new fields, getters/setters, constructor removal, and toString() output for mdsDownloadStartupRetries and mdsDownloadStartupRetryInterval.
TocService async retry logic
jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java
Runs startup loading asynchronously, adds missing-TOC retry handling, and updates TOC parsing, persistence, lookup, and logging paths.
Defaults, schema, and documentation
docker-jans-fido2/scripts/upgrade.py, jans-linux-setup/jans_setup/templates/jans-fido2/dynamic-conf.json, jans-config-api/plugins/docs/fido2-plugin-swagger.yaml, docs/janssen-server/config-guide/fido2-config/janssen-fido2-configuration.md, docs/janssen-server/fido/config.md
Sets default values, extends the OpenAPI schema, and updates configuration docs and sample JSON output for the new fields.
TocService behavior tests
jans-fido2/server/src/test/java/io/jans/fido2/service/mds/TocServiceTest.java
Adds coverage for startup retry flow and TOC-missing detection outcomes.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Related issues: #14482 — MDS TOC not downloaded on startup when blob is missing (single attempt, no retry, blocks initialization).

Suggested labels: fido2, enhancement, configuration

Suggested reviewers: yuriyz, mzavgorodniy

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description covers the target issue and expected behavior, but the implementation details section is left blank. Add a brief implementation overview and update the checklist to reflect the added tests and documentation changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: startup MDS TOC download retry behavior in jans-fido2.
Linked Issues check ✅ Passed The code adds startup TOC retry handling, async initialization, config defaults, tests, and docs matching #14482.
Out of Scope Changes check ✅ Passed All changes are scoped to FIDO2 startup retry behavior, configuration, tests, and docs; no unrelated modifications are evident.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jans-fido2-mds-toc-startup-retry

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mo-auto

mo-auto commented Jul 2, 2026

Copy link
Copy Markdown
Member

Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@mo-auto mo-auto added area-documentation Documentation needs to change as part of issue or PR comp-docker-jans-fido2 comp-docs Touching folder /docs comp-jans-config-api Component affected by issue or PR comp-jans-fido2 Component affected by issue or PR comp-jans-linux-setup Component affected by issue or PR kind-feature Issue or PR is a new feature request labels Jul 2, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`:
- Around line 141-228: The new retry/startup flow in TocService is complex and
currently untested, especially the branching in fetchMetadata(boolean
retryWhenTocMissing), the missing-state check in isTocContentMissing(), and the
wait/interrupt behavior in sleepBeforeRetry(). Add focused unit tests for these
methods to cover the stale-vs-missing TOC path, max-attempt bounds, early exit
once the TOC appears, and interrupted sleep handling using the existing
TocService and its collaborators.
- Around line 103-116: The asynchronous `init()` in `TocService` now writes
`tocEntries` from a background thread without any publication guarantee, so
request threads in `getAuthenticatorsMetadata()` may keep seeing stale or null
data. Fix this by making `tocEntries` safely published, such as marking the
field `volatile` or switching it to an `AtomicReference`, and keep the write in
`refreshTOCEntries()` and reads in `getAuthenticatorsMetadata()` using that same
field.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 54d49c2d-b0ec-4a6f-bce3-cd811e5b9fa8

📥 Commits

Reviewing files that changed from the base of the PR and between fe41e0d and bc1580c.

📒 Files selected for processing (7)
  • docker-jans-fido2/scripts/upgrade.py
  • docs/janssen-server/config-guide/fido2-config/janssen-fido2-configuration.md
  • docs/janssen-server/fido/config.md
  • jans-config-api/plugins/docs/fido2-plugin-swagger.yaml
  • jans-fido2/model/src/main/java/io/jans/fido2/model/conf/Fido2Configuration.java
  • jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java
  • jans-linux-setup/jans_setup/templates/jans-fido2/dynamic-conf.json

Signed-off-by: imran <imranishaq7071@gmail.com>
@imran-ishaq
imran-ishaq temporarily deployed to integration-tests July 2, 2026 15:04 — with GitHub Actions Inactive
@imran-ishaq
imran-ishaq temporarily deployed to integration-tests July 2, 2026 15:04 — with GitHub Actions Inactive

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java (3)

120-126: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Publish tocEntries only after it is fully populated.

Line 121 assigns the new map before parseTOCs() completes, so request threads can observe an empty TOC during refresh. Build a local map first, then assign it once.

Suggested fix
 public void refreshTOCEntries() {
-	this.tocEntries = Collections.synchronizedMap(new HashMap<>());
+	Map<String, JsonNode> loadedTocEntries = Collections.synchronizedMap(new HashMap<>());
 	if (appConfiguration.getFido2Configuration().isDisableMetadataService()) {
 		log.debug("SkipDownloadMds is enabled");
 	} else {
-		tocEntries.putAll(parseTOCs());
+		loadedTocEntries.putAll(parseTOCs());
 	}
+	this.tocEntries = loadedTocEntries;
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`
around lines 120 - 126, The refreshTOCEntries() method in TocService publishes
tocEntries too early by assigning a new synchronized map before parseTOCs()
finishes, which can expose an empty TOC to concurrent readers. Build and
populate a local map first (including the parseTOCs() result), then assign it to
the tocEntries field only after it is fully populated, keeping the existing
disableMetadataService branch behavior intact.

149-167: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Treat configured retries as retries, not total attempts.

The PR objective and config name describe mdsDownloadStartupRetries as retries. This loop uses it as total attempts, so the default 3 produces only 2 retries after the first attempt.

Suggested fix
 int maxAttempts = 1;
 if (retryWhenTocMissing && isTocContentMissing()) {
-	maxAttempts = Math.max(1, appConfiguration.getFido2Configuration().getMdsDownloadStartupRetries());
-	log.info("MDS TOC blob is missing at startup, will attempt to download it up to {} time(s)", maxAttempts);
+	int retries = Math.max(0, appConfiguration.getFido2Configuration().getMdsDownloadStartupRetries());
+	maxAttempts = 1 + retries;
+	log.info("MDS TOC blob is missing at startup, will attempt the initial download plus {} retry(ies)", retries);
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`
around lines 149 - 167, The retry loop in TocService is treating
mdsDownloadStartupRetries as total attempts instead of retries, so the first
fetch is consuming one of the configured retries. Update the logic around
fetchMetadataOnce() to always perform the initial attempt, then allow the
configured number of additional retry attempts when isTocContentMissing()
remains true. Keep the existing retry guard and logging, but adjust
maxAttempts/loop bounds so the configured value reflects retries rather than
total attempts.

371-383: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add explicit connect/read timeouts before opening the MDS URL. URL.openStream() can block indefinitely on a slow or unresponsive endpoint, which can stall the retry loop and tie up the async worker.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`
around lines 371 - 383, The downloadMdsFromServer method currently uses
URL.openStream() without any network timeouts, which can block indefinitely.
Update this path in TocService so the metadataUrl connection is opened
explicitly with connect and read timeouts before reading the stream, then keep
the existing IOUtils/base64Service/persistTocDocument flow unchanged. Make the
timeout values configurable or use sensible defaults, and preserve the current
error handling in the catch block.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`:
- Around line 120-126: The refreshTOCEntries() method in TocService publishes
tocEntries too early by assigning a new synchronized map before parseTOCs()
finishes, which can expose an empty TOC to concurrent readers. Build and
populate a local map first (including the parseTOCs() result), then assign it to
the tocEntries field only after it is fully populated, keeping the existing
disableMetadataService branch behavior intact.
- Around line 149-167: The retry loop in TocService is treating
mdsDownloadStartupRetries as total attempts instead of retries, so the first
fetch is consuming one of the configured retries. Update the logic around
fetchMetadataOnce() to always perform the initial attempt, then allow the
configured number of additional retry attempts when isTocContentMissing()
remains true. Keep the existing retry guard and logging, but adjust
maxAttempts/loop bounds so the configured value reflects retries rather than
total attempts.
- Around line 371-383: The downloadMdsFromServer method currently uses
URL.openStream() without any network timeouts, which can block indefinitely.
Update this path in TocService so the metadataUrl connection is opened
explicitly with connect and read timeouts before reading the stream, then keep
the existing IOUtils/base64Service/persistTocDocument flow unchanged. Make the
timeout values configurable or use sensible defaults, and preserve the current
error handling in the catch block.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: d1da8c2e-9e21-4766-8a80-7d418d42e6a3

📥 Commits

Reviewing files that changed from the base of the PR and between bc1580c and df5f889.

📒 Files selected for processing (3)
  • jans-fido2/model/src/main/java/io/jans/fido2/model/conf/Fido2Configuration.java
  • jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java
  • jans-fido2/server/src/test/java/io/jans/fido2/service/mds/TocServiceTest.java

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 2, 2026
Signed-off-by: imran <imranishaq7071@gmail.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java (2)

154-158: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

mdsDownloadStartupRetries is used as total attempts, not retries.

maxAttempts = getMdsDownloadStartupRetries() means a value of 3 yields 3 total downloads (1 initial + 2 retries), yet the property name and @DocProperty in Fido2Configuration describe it as the number of times the download is retried. This off-by-one between the documented semantics and behavior can mislead operators tuning the value. Either treat it as maxAttempts = retries + 1, or align the property description to state it is the total number of attempts.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`
around lines 154 - 158, The TOC startup download limit in TocService is treating
mdsDownloadStartupRetries as total attempts instead of retries, which is
inconsistent with the Fido2Configuration property documentation. Update the
logic in TocService so the loop limit reflects retries plus the initial attempt,
or alternatively change the property’s documented semantics to clearly state it
configures total attempts; keep the behavior and docs aligned around
getMdsDownloadStartupRetries().

229-239: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Interrupt during retry wait doesn't stop the retry loop.

sleepBeforeRetry() correctly restores the interrupt flag, but control returns to the for loop in fetchMetadata(boolean), which continues to the next attempt. On the following iteration Thread.sleep(...) will immediately re-throw InterruptedException, so the remaining attempts run back-to-back with no delay (busy retrying during e.g. shutdown). Consider aborting the loop when interrupted.

🔧 Suggested fix
-			sleepBeforeRetry();
+			sleepBeforeRetry();
+			if (Thread.currentThread().isInterrupted()) {
+				log.warn("MDS TOC download retry loop interrupted, aborting remaining attempts");
+				return;
+			}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`
around lines 229 - 239, The interrupt handling in sleepBeforeRetry is restoring
the flag but still allows fetchMetadata to continue retrying, which causes the
remaining attempts to run immediately. Update the retry flow in fetchMetadata
and/or sleepBeforeRetry so that an InterruptedException causes the retry loop to
abort early, using the existing sleepBeforeRetry and fetchMetadata symbols to
locate the control flow. Keep the interrupt status restored, then return or
break out of the loop instead of proceeding to the next retry.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`:
- Around line 105-106: Restore safe cross-thread publication for the shared
MessageDigest in TocService: the digester field is initialized in
loadGlobalVariables() on the async startup path and read later by getDigester(),
so it needs volatile again or another safe-publication mechanism. Also address
the thread-safety risk of sharing a single MessageDigest instance across request
threads by avoiding a mutable singleton digest state or by creating/using a
per-call instance within getDigester().

---

Outside diff comments:
In `@jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java`:
- Around line 154-158: The TOC startup download limit in TocService is treating
mdsDownloadStartupRetries as total attempts instead of retries, which is
inconsistent with the Fido2Configuration property documentation. Update the
logic in TocService so the loop limit reflects retries plus the initial attempt,
or alternatively change the property’s documented semantics to clearly state it
configures total attempts; keep the behavior and docs aligned around
getMdsDownloadStartupRetries().
- Around line 229-239: The interrupt handling in sleepBeforeRetry is restoring
the flag but still allows fetchMetadata to continue retrying, which causes the
remaining attempts to run immediately. Update the retry flow in fetchMetadata
and/or sleepBeforeRetry so that an InterruptedException causes the retry loop to
abort early, using the existing sleepBeforeRetry and fetchMetadata symbols to
locate the control flow. Keep the interrupt status restored, then return or
break out of the loop instead of proceeding to the next retry.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8bb9f826-5f74-485c-8522-231730eead68

📥 Commits

Reviewing files that changed from the base of the PR and between df5f889 and c42e26a.

📒 Files selected for processing (2)
  • jans-fido2/model/src/main/java/io/jans/fido2/model/conf/Fido2Configuration.java
  • jans-fido2/server/src/main/java/io/jans/fido2/service/mds/TocService.java

@sonarqubecloud

sonarqubecloud Bot commented Jul 3, 2026

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Jul 3, 2026

Copy link
Copy Markdown

@sonarqubecloud

sonarqubecloud Bot commented Jul 3, 2026

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-documentation Documentation needs to change as part of issue or PR comp-docker-jans-fido2 comp-docs Touching folder /docs comp-jans-config-api Component affected by issue or PR comp-jans-fido2 Component affected by issue or PR comp-jans-linux-setup Component affected by issue or PR kind-feature Issue or PR is a new feature request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

jans-fido2: MDS TOC not downloaded on startup when blob is missing — single attempt, no retry, blocks initialization

2 participants