Skip to content

Backend cleanup: audit, Program.cs split, fix BondEntry AddLabel no-op#515

Merged
avresial merged 2 commits into
developfrom
claude/backend-cleanup-audit-3kuc2u
Jul 1, 2026
Merged

Backend cleanup: audit, Program.cs split, fix BondEntry AddLabel no-op#515
avresial merged 2 commits into
developfrom
claude/backend-cleanup-audit-3kuc2u

Conversation

@avresial

@avresial avresial commented Jul 1, 2026

Copy link
Copy Markdown
Owner

Summary

Backend cleanup pass. Audited the four backend layers (Api, Application, Domain, Infrastructure) and recorded the findings in a new Cleanup.md, then executed the safe, high-value items.

The audit found the backend generally healthy: clean-architecture boundaries are respected (Domain has no EF/ASP.NET refs; the AppDbContext/EF mentions in Application are only in comments), controllers stay thin, and naming conventions are consistent. Findings were mostly about size/complexity plus one latent bug.

Changes

  • Cleanup.md — full audit with a task list (done items + recommended follow-ups).
  • Program.cs split — extracted the inline DI wiring into cohesive extension methods in ApiConfigurationExtensions.cs: AddApiOptions, AddApiSecurity, AddApiBackgroundServices. Pure move, no behaviour change; Program.cs shrinks ~200 lines and reads as a high-level outline. Logging filters stay on builder.Logging where they belong.
  • Fix BondEntryRepository.AddLabel no-op — it fetched the entry and label but never attached the label before SaveChangesAsync (returned true doing nothing). Now attaches the label and is idempotent, matching CurrencyEntryRepository. Latent — no production call sites yet, so no user-visible change / no changelog entry.
  • Tests — added BondEntryRepositoryLabelTests (attach, idempotency, missing-label).

Follow-ups documented (not in this PR)

  • Extract a ResolvedInstrumentPersister from InstrumentResolver (persistence/mapping vs. resolution).
  • Collapse the N+1 explicit-interface neighbour-lookups in BondEntryRepository onto the existing set-based queries.

Validation

  • dotnet build ./code/FinanceManager.slnx — clean (0 warnings).
  • dotnet format --verify-no-changes — clean.
  • Unit tests: 497 passed, 0 failed.

No UI changes.

https://claude.ai/code/session_012EXPZbnNNfCTpZc9xJfmP9


Generated by Claude Code

Summary by CodeRabbit

  • New Features

    • Centralized API startup configuration for a more consistent app setup.
    • Added safer handling for authentication, CORS, proxy forwarding, and background processing.
  • Bug Fixes

    • Prevents duplicate labels from being added to the same bond entry.
    • Improves validation for required security and service settings, helping the app fail fast with clearer setup issues.
  • Tests

    • Added coverage for attaching labels, duplicate-label behavior, and missing-label handling.

…no-op

- Add Cleanup.md audit of the backend layers
- Extract Program.cs DI wiring into AddApiOptions/AddApiSecurity/
  AddApiBackgroundServices extension methods (pure move, no behaviour change)
- Fix BondEntryRepository.AddLabel which fetched the entry/label but never
  attached the label; make it idempotent to match CurrencyEntryRepository
- Add unit tests covering BondEntryRepository.AddLabel

Claude-Session: https://claude.ai/code/session_012EXPZbnNNfCTpZc9xJfmP9
@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@avresial, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 47 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4a850758-e9cb-47cf-956e-1d2bb5c89be4

📥 Commits

Reviewing files that changed from the base of the PR and between 58e549e and 1f49a04.

📒 Files selected for processing (3)
  • code/Directory.Packages.props
  • code/FinanceManager.Api/ApiConfigurationExtensions.cs
  • code/FinanceManager.Api/FinanceManager.Api.csproj

Walkthrough

This PR extracts API dependency-injection wiring (options binding, JWT/CORS/forwarded-header security, and background services) from Program.cs into a new ApiConfigurationExtensions class, and makes BondEntryRepository.AddLabel idempotent, adding corresponding unit tests.

Changes

API startup configuration extraction

Layer / File(s) Summary
Options binding and validation
code/FinanceManager.Api/ApiConfigurationExtensions.cs
Adds AddApiOptions binding JWT, lockout, stock, and various provider options, configures antiforgery, and validates startup values.
Security wiring (JWT, CORS, forwarded headers)
code/FinanceManager.Api/ApiConfigurationExtensions.cs
Adds AddApiSecurity handling JWT signing key resolution/validation, CORS allowlist policy, JWT bearer events for SignalR/guest sessions, and reverse-proxy trust configuration.
Background services wiring
code/FinanceManager.Api/ApiConfigurationExtensions.cs
Adds AddApiBackgroundServices registering hosted services, channels, stores, and database logging components.
Program.cs refactor
code/FinanceManager.Api/Program.cs
Removes inlined JWT/CORS/background configuration, updates imports, and delegates to the new extension methods.

Estimated code review effort: 4 (Complex) | ~60 minutes

Bond entry label idempotency

Layer / File(s) Summary
Idempotent AddLabel and tests
code/FinanceManager.Infrastructure/Repositories/Account/Entry/BondEntryRepository.cs, code/FinanceManager.Tests.Unit/Infrastructure/Repositories/BondEntryRepositoryLabelTests.cs
AddLabel now includes Labels navigation and returns early if the label already exists; new tests verify attachment, idempotency, and missing-label behavior.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Program
  participant AddApiSecurity
  participant IGuestSessionStore

  Client->>Program: Request with access_token
  Program->>AddApiSecurity: OnMessageReceived (extract token from query)
  AddApiSecurity->>AddApiSecurity: OnTokenValidated
  AddApiSecurity->>IGuestSessionStore: IsActive(guest claim)
  IGuestSessionStore-->>AddApiSecurity: active/inactive
  AddApiSecurity-->>Program: succeed or fail token
Loading

Possibly related PRs

  • avresial/FinanceManager#371: Both PRs modify ASP.NET startup security wiring in Program.cs, one refactoring JWT/CORS/forwarded-header setup into extensions, the other adjusting environment-aware security header placement.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: backend cleanup, Program.cs extraction, and the BondEntry AddLabel fix.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/backend-cleanup-audit-3kuc2u

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.

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

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 `@code/FinanceManager.Api/ApiConfigurationExtensions.cs`:
- Around line 204-221: Reject malformed reverse-proxy settings during startup:
in ApiConfigurationExtensions.ConfigureForwardedHeaders, the current
IPAddress.TryParse and IPNetwork.TryParse loops silently ignore bad entries, so
change them to validate every value and throw an InvalidOperationException when
any proxy IP or CIDR is invalid. Keep the existing startup guard for missing
configuration, and ensure the failure happens before ForwardedHeadersOptions is
finalized so invalid ReverseProxy:KnownProxies/ReverseProxy:KnownNetworks values
cannot be partially applied.
- Around line 147-156: In ApiConfigurationExtensions, the JWT setup currently
reads issuer and audience directly from configuration without validating them
first. Add an early startup check in the JWT configuration path to ensure both
JwtConfig:Issuer and JwtConfig:Audience are present and non-empty before
building TokenValidationParameters, and then use those validated local values
for ValidIssuer and ValidAudience so authentication fails fast instead of later
on every request. Refer to the JWT auth configuration block and
TokenValidationParameters setup to locate the change.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2abe51c6-b3b8-42f9-a9ce-b3654a8e454d

📥 Commits

Reviewing files that changed from the base of the PR and between 87fcf09 and 58e549e.

⛔ Files ignored due to path filters (1)
  • Cleanup.md is excluded by !**/*.md
📒 Files selected for processing (4)
  • code/FinanceManager.Api/ApiConfigurationExtensions.cs
  • code/FinanceManager.Api/Program.cs
  • code/FinanceManager.Infrastructure/Repositories/Account/Entry/BondEntryRepository.cs
  • code/FinanceManager.Tests.Unit/Infrastructure/Repositories/BondEntryRepositoryLabelTests.cs

Comment thread code/FinanceManager.Api/ApiConfigurationExtensions.cs
Comment thread code/FinanceManager.Api/ApiConfigurationExtensions.cs Outdated
- Pin transitive Microsoft.OpenApi to 2.7.5 (patches GHSA-v5pm-xwqc-g5wc,
  High) via central version + direct reference in the Api project, since
  central transitive pinning is disabled. Clears the security-scan CI job.
- Fail fast at startup when JwtConfig:Issuer/Audience are missing, instead
  of rejecting every token at request time (addresses review feedback).
- Reject malformed ReverseProxy:KnownProxies/KnownNetworks entries at
  startup instead of silently dropping them (addresses review feedback).

Claude-Session: https://claude.ai/code/session_012EXPZbnNNfCTpZc9xJfmP9
@avresial avresial marked this pull request as ready for review July 1, 2026 05:31
@avresial avresial merged commit d981e9d into develop Jul 1, 2026
7 checks passed
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.

2 participants