Skip to content

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

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

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

Conversation

@rlorenzo

@rlorenzo rlorenzo commented May 13, 2026

Copy link
Copy Markdown
Contributor

Summary

Final slice of the CodeQL style sweep. Most alerts originally scoped here have since landed on main through other PRs in the series; this PR carries the remaining fixes plus a CAS log-injection hardening that surfaced while touching the same line.

Closes

cs/useless-tostring-call (2):

  • TermCodeService.cs:39 - drop redundant year.ToString() inside string.Format
  • HomeController.cs:315 - redundant doc.ToString() in string concat; the log line now routes through LogSanitizer (see below)

cs/missed-ternary-operator (1):

  • VerificationService.cs:773 - dueDate if/else assignment collapsed to a ternary

cs/loss-of-precision (3):

  • test/ClinicalScheduler/EmailNotificationTest.cs:122-123 and TestDataBuilder.cs:179 - -7 * (...)-7.0 * (...) so the week-offset arithmetic flowing into DateTime.AddDays(double) is computed in double

Also in this PR

  • fix(security): HomeController CAS auth-failure log now sanitizes the raw CAS XML via LogSanitizer.SanitizeString() before logging
  • Comment accuracy (Copilot review feedback):
    • HttpHelper.Configure doc summary no longer calls the static configuration method a "constructor" (also fixes the "memeory" typo)
    • HomeController stale "uncomment this line" comment replaced with one describing the now-active, sanitized diagnostic log
    • VerificationService due-date comment now references the configurable VerificationReplyDays instead of hard-coding "7 days"

Not addressed

cs/complex-condition and similar subjective-rewrite alerts remain open; converting them would hurt readability. Other items from the original sweep scope (multi-statement ternary candidates, complex-block, the test-file implicit conversions) were picked up by later PRs in the series and are no longer part of this branch.

Context

Twelfth in the CodeQL N: cleanup series.

Test plan

  • Pre-commit lint + backend tests + build verification all passed
  • Playwright smoke test (SMOKETEST-EFFORT-Verification): verification email due-date verified end-to-end for both branches of the refactored ternary - ExpectedCloseDate set (close - 7 days) and fallback (today + 7 days); login path, instructor list, and My Effort page load clean
  • CodeQL workflow on this PR shows the listed style alerts closed

@coderabbitai

coderabbitai Bot commented May 13, 2026

Copy link
Copy Markdown
Contributor

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.
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.
Description check ✅ Passed The description comprehensively details the CodeQL style sweep changes across multiple files, clearly mapping alerts to their fixes with specifics (file paths, line numbers, change types).

✏️ 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

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

codecov-commenter commented May 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 43.20%. Comparing base (185f8b2) to head (92f13f0).

Files with missing lines Patch % Lines
web/Controllers/HomeController.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #198      +/-   ##
==========================================
- Coverage   43.21%   43.20%   -0.01%     
==========================================
  Files         894      894              
  Lines       51851    51847       -4     
  Branches     4844     4843       -1     
==========================================
- Hits        22406    22402       -4     
  Misses      28899    28899              
  Partials      546      546              
Flag Coverage Δ
backend 43.30% <80.00%> (-0.01%) ⬇️
frontend 41.32% <ø> (ø)

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.

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

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor
✅ 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.

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

Copilot AI 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.

Pull request overview

This PR continues the CodeQL cleanup series by addressing remaining straightforward C# style alerts (e.g., unnecessary ToString() usage, missed ternaries/null-coalescing, and loss-of-precision warnings) across web and test projects.

Changes:

  • Sanitizes a CAS XML response before logging, reducing log-injection risk when troubleshooting missing usernames.
  • Simplifies conditional assignments/formatting (e.g., ternary for due-date selection, removing redundant ToString() in string.Format).
  • Adjusts ClinicalScheduler test date math to use double arithmetic for DateTime.AddDays(double).

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
web/Controllers/HomeController.cs Sanitizes CAS response string before logging when username is missing.
web/Classes/HttpHelper.cs Fixes a documentation typo in the Configure XML doc comment.
web/Areas/Effort/Services/VerificationService.cs Converts due-date selection to a ternary assignment.
web/Areas/Curriculum/Services/TermCodeService.cs Removes redundant ToString() in string.Format call.
test/ClinicalScheduler/TestDataBuilder.cs Uses double math for AddDays offset calculation.
test/ClinicalScheduler/EmailNotificationTest.cs Uses double math for AddDays offset calculation in test seed data.

Comment thread web/Controllers/HomeController.cs Outdated
Comment thread web/Classes/HttpHelper.cs
@rlorenzo rlorenzo force-pushed the codeql/12-style-sweep branch 2 times, most recently from 0cbb8ac to 6cf8c1d Compare June 12, 2026 23:19
@rlorenzo

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

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.

Copilot AI 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.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Comment thread web/Controllers/HomeController.cs Outdated
Comment thread web/Areas/Effort/Services/VerificationService.cs Outdated
rlorenzo added 3 commits June 12, 2026 16:50
- 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
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.

Copilot AI 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.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

@rlorenzo rlorenzo requested a review from bsedwards June 13, 2026 01:50
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.

4 participants