Skip to content

CodeQL 12: chore: style sweep for remaining CodeQL alerts#198

Open
rlorenzo wants to merge 4 commits into
mainfrom
codeql/12-style-sweep
Open

CodeQL 12: chore: style sweep for remaining CodeQL alerts#198
rlorenzo wants to merge 4 commits into
mainfrom
codeql/12-style-sweep

Conversation

@rlorenzo
Copy link
Copy Markdown
Contributor

@rlorenzo rlorenzo commented May 13, 2026

Summary

Sweep PR covering the remaining straightforward CodeQL style alerts that earlier PRs deferred.

Closes

cs/useless-tostring-call (7):

  • HomeController.cs:315 - doc.ToString() in string concat → drop
  • GradYearClassLevel.cs:57,60,69 - .ToString() after int in "V" + ...
  • UinformService.cs:274 - epochTime.ToString() in concat
  • LdapUserContact.cs:39 - v.ToString() in concat
  • TermCodeService.cs:39 - year.ToString() in string.Format

cs/missed-ternary-operator (6 / 17):

  • HttpHelper.cs:51 - HttpContext getter collapsed to expression-bodied ?.HttpContext
  • RAPSController.cs:315,359 - if/else return View(...) → ternary
  • CMSController.cs:28 - if/else return cms.X(...) → ternary
  • VerificationService.cs:773 - dueDate if/else assignment → ternary
  • UserHelper.cs:68,152,280,345 - four if (x != null) return x; else return Y; blocks → x ?? Y (in CodeQL 12 part 1 before this PR was scoped - folded in here)

cs/local-shadows-member (3):

  • HttpHelper.Configure parameters httpContextAccessor, authorizationService, dataProtectionProvider renamed to non-shadowing names (contextAccessor, authzService, dataProtection); the assignments to private static fields no longer need the HttpHelper. qualifier.

cs/loss-of-precision (3):

  • test/ClinicalScheduler/EmailNotificationTest.cs:122-123 and TestDataBuilder.cs:179 - explicit (double) casts around the int arithmetic flowing into DateTime.AddDays(double).

Not addressed

Remaining cs/missed-ternary-operator (11) where the branches contain multi-statement bodies that don't fit ternary cleanly (UinformService.cs:247 deserialize path, EffortAuditService.cs:605 IQueryable build, etc.) - converting them would hurt readability. Same for cs/complex-condition (17) which are subjective rewrites, cs/complex-block (1), cs/nested-if-statements (2). The two js/implicit-operand-conversion alerts in course-import-dialog.test.ts:72,96 are intentional test code simulating non-Error throws.

Context

Twelfth in the CodeQL N: cleanup series.

Test plan

  • npm run test:backend - 1946 tests passing
  • Pre-commit lint+test+verify all passed
  • CodeQL workflow on this PR shows the listed style alerts closed

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

Pull request modernizes code across test data, controllers, and helpers by adopting contemporary C# patterns: DateTime arithmetic precision adjustments, ternary expressions replacing if/else blocks, implicit ToString() calls in string formatting, parameter renames in HttpHelper, and null-coalescing consolidation in UserHelper.

Changes

Code Style Modernization Refactoring

Layer / File(s) Summary
Test Data DateTime Arithmetic Precision
test/ClinicalScheduler/TestDataBuilder.cs, test/ClinicalScheduler/EmailNotificationTest.cs
DateStart and DateEnd calculations in Week test data generation shift from int-based to double-based multiplication (-7.0) for more precise offset computation in AddDays calls.
Control Flow Simplifications
web/Areas/CMS/Controllers/CMSController.cs, web/Areas/Effort/Services/VerificationService.cs, web/Areas/RAPS/Controllers/RAPSController.cs
Four if/else branching patterns compressed into ternary and conditional return expressions: Files endpoint selects between DownloadZip and ProvideFile; dueDate uses conditional expression for expectedCloseDate logic; RoleMembers and RolePermissionsComparison authorization checks return view or 403 response directly.
String Formatting Simplifications
web/Areas/Curriculum/Services/TermCodeService.cs, web/Areas/Directory/Models/LdapUserContact.cs, web/Areas/RAPS/Services/UinformService.cs, web/Areas/Students/Services/GradYearClassLevel.cs, web/Controllers/HomeController.cs
Six locations remove redundant explicit ToString() calls: year formatting in TermCodeService, LDAP attribute concatenation, epoch time signing in UinformService, class-level string building in GradYearClassLevel, and XDocument logging in HomeController.
HttpHelper API Simplification
web/Classes/HttpHelper.cs
Configure() method parameters renamed for brevity (httpContextAccessor→contextAccessor, authorizationService→authzService, dataProtectionProvider→dataProtection); HttpContext property converts from full getter block to expression-bodied syntax using null-conditional operator.
UserHelper Null-Coalescing Consolidation
web/Classes/UserHelper.cs
Four methods unified to use null-coalescing operators: GetRoles and GetAssignedPermissions return empty lists via ?? when cache factory yields null; GetByLoginId captures fallbackUser and returns aaudUser ?? fallbackUser; GetTrueCurrentUser returns trueUser ?? GetCurrentUser().

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 64.71% 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
Title check ✅ Passed Title clearly describes a CodeQL style sweep addressing remaining alerts, directly matching the changeset's refactoring fixes.
Description check ✅ Passed Description details the specific CodeQL alert categories addressed (useless-tostring-call, missed-ternary-operator, local-shadows-member, loss-of-precision), locations, and rationale for deferred items.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 codeql/12-style-sweep

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 and usage tips.

@codecov-commenter
Copy link
Copy Markdown

Bundle Report

Bundle size has no change ✅

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented May 13, 2026

Codecov Report

❌ Patch coverage is 25.00000% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 42.98%. Comparing base (5949e52) to head (a0528cd).

Files with missing lines Patch % Lines
web/Areas/RAPS/Controllers/RAPSController.cs 0.00% 6 Missing ⚠️
web/Classes/UserHelper.cs 0.00% 5 Missing ⚠️
web/Areas/CMS/Controllers/CMSController.cs 0.00% 3 Missing ⚠️
web/Areas/Students/Services/GradYearClassLevel.cs 0.00% 3 Missing ⚠️
web/Areas/Directory/Models/LdapUserContact.cs 0.00% 1 Missing ⚠️
web/Areas/RAPS/Services/UinformService.cs 0.00% 1 Missing ⚠️
web/Classes/HttpHelper.cs 75.00% 1 Missing ⚠️
web/Controllers/HomeController.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #198      +/-   ##
==========================================
+ Coverage   42.96%   42.98%   +0.02%     
==========================================
  Files         877      877              
  Lines       51468    51433      -35     
  Branches     4802     4803       +1     
==========================================
- Hits        22113    22109       -4     
+ Misses      28831    28800      -31     
  Partials      524      524              
Flag Coverage Δ
backend 43.06% <25.00%> (+0.02%) ⬆️
frontend 41.34% <ø> (ø)

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Comment thread test/ClinicalScheduler/EmailNotificationTest.cs Fixed
Comment thread test/ClinicalScheduler/EmailNotificationTest.cs Fixed
Comment thread test/ClinicalScheduler/TestDataBuilder.cs Fixed
Comment thread test/ClinicalScheduler/EmailNotificationTest.cs Fixed
Comment thread test/ClinicalScheduler/EmailNotificationTest.cs Fixed
Comment thread test/ClinicalScheduler/TestDataBuilder.cs Fixed
- UserHelper.cs: capture user into 'fallbackUser' local before
  GetOrCreate lambda so ReSharper AccessToModifiedClosure is silenced
- HttpHelper.cs: drop stale '<param name="memoryCache">' XML tag now
  that the other params don't have matching tags (was creating 5
  InvalidXmlDocComment warnings since the rename)
- test/ClinicalScheduler/{EmailNotificationTest,TestDataBuilder}.cs:
  replace '(double)(-7 * x)' with '-7.0 * x' — same intent (force the
  multiplication into double per cs/loss-of-precision) but no
  RedundantCast warning from ReSharper
@rlorenzo
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 15, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

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 `@web/Areas/RAPS/Controllers/RAPSController.cs`:
- Line 315: Add a deny-access helper on RAPSController to centralize logging and
403 rendering: implement a private method (e.g., DenyAccess(string reason) or
DenyAccessResult(string reason)) in RAPSController that logs the reason via the
controller logger, sets Response.StatusCode = 403, and returns View("403") (or
an appropriate IActionResult). Replace duplicated denial code paths in methods
like any access checks inside RAPSController to call this helper instead of
repeating log + status + view logic, keeping the same log message format and
ensuring the helper returns IActionResult to be used with return statements.

In `@web/Controllers/HomeController.cs`:
- Line 315: The code currently logs raw CAS XML via
HttpHelper.Logger.Log(NLog.LogLevel.Warn, "No username. CAS response: " + doc),
which may leak user identifiers; sanitize/redact sensitive fields from the CAS
response before logging by using the LogSanitizer utilities (e.g.,
LogSanitizer.SanitizeString or SanitizeId) on the variable doc or on the
extracted attributes, then pass the sanitized string to HttpHelper.Logger.Log
(keep the "No username. CAS response:" prefix but replace doc with the sanitized
output).
🪄 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: ASSERTIVE

Plan: Pro

Run ID: f890a93f-65d0-470c-876d-651c0bddcba5

📥 Commits

Reviewing files that changed from the base of the PR and between 38de1ad and eea4ff3.

📒 Files selected for processing (12)
  • test/ClinicalScheduler/EmailNotificationTest.cs
  • test/ClinicalScheduler/TestDataBuilder.cs
  • web/Areas/CMS/Controllers/CMSController.cs
  • web/Areas/Curriculum/Services/TermCodeService.cs
  • web/Areas/Directory/Models/LdapUserContact.cs
  • web/Areas/Effort/Services/VerificationService.cs
  • web/Areas/RAPS/Controllers/RAPSController.cs
  • web/Areas/RAPS/Services/UinformService.cs
  • web/Areas/Students/Services/GradYearClassLevel.cs
  • web/Classes/HttpHelper.cs
  • web/Classes/UserHelper.cs
  • web/Controllers/HomeController.cs

Comment thread web/Areas/RAPS/Controllers/RAPSController.cs
Comment thread web/Controllers/HomeController.cs Outdated
rlorenzo added 2 commits May 15, 2026 11:17
The fallback log path for a CAS validation response with no username
embedded the raw XML in the message. CAS responses come from an
external source and can contain user identifiers and claim attributes,
so per CLAUDE.md the value must pass through LogSanitizer before
hitting the log. Wraps the doc.ToString() in LogSanitizer.SanitizeString.
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.

3 participants