Skip to content

CodeQL 4: fix: dispose disposables on exception paths#192

Open
rlorenzo wants to merge 2 commits into
mainfrom
codeql/4-dispose
Open

CodeQL 4: fix: dispose disposables on exception paths#192
rlorenzo wants to merge 2 commits into
mainfrom
codeql/4-dispose

Conversation

@rlorenzo
Copy link
Copy Markdown
Contributor

@rlorenzo rlorenzo commented May 13, 2026

Summary

Closes ~16 CodeQL alerts in two related rule families: cs/dispose-not-called-on-throw (10) and cs/local-not-disposed (6). All same fix shape - wrap IDisposable locals with using.

Effort Excel-generation services (10 alerts)

Seven files have the pattern var wb = new XLWorkbook(); ...; wb.Dispose(); where the explicit Dispose at the bottom is bypassed if SaveAs or any of the intermediate ExcelHelper/ExcelAccessibilityHelper calls throw. Converted to using var wb = new XLWorkbook(); and removed the now-redundant Dispose:

  • web/Areas/Effort/Services/TeachingActivityService.cs (2 sites)
  • web/Areas/Effort/Services/SchoolSummaryService.cs (1 site)
  • web/Areas/Effort/Services/MeritSummaryService.cs (1 site)
  • web/Areas/Effort/Services/MeritMultiYearService.cs (1 site)
  • web/Areas/Effort/Services/MeritReportService.cs (2 sites)
  • web/Areas/Effort/Services/DeptSummaryService.cs (1 site)
  • web/Areas/Effort/Services/EvaluationReportService.cs (2 sites)

Other leaked disposables (6 alerts)

  • web/Areas/CMS/Data/CMS.cs::DecryptFile - Aes local was never disposed.
  • web/Areas/CMS/Data/CMS.cs::DecryptAES - MemoryStream mmsStream, StreamWriter srwTemp, MemoryStream outstream all leaked.
  • web/Areas/Computing/Services/BiorenderStudentLookup.cs::GetBiorenderStudentInfo - SemaphoreSlim throttler leaked.
  • web/Classes/Utilities/F5HttpRequest.cs::HandleConnectionFail - probe HttpRequestMessage newRequest leaked.

CMS.cs touch is outside the range PR #184 modifies (#184 covers lines 469-516 in DownloadZip; these edits are lines 631+).

Context

Fourth in the CodeQL N: cleanup series (after #189, #190, #191).

Test plan

  • npm run test:backend - 1946 tests passing
  • npm run verify:build - clean (0 errors)
  • Pre-commit lint+test+verify all passed
  • CodeQL workflow on this PR shows the 16 listed alerts closed

Closes CodeQL cs/dispose-not-called-on-throw (10) and
cs/local-not-disposed (6).

Effort Excel-generation services (7 files, 10 XLWorkbook sites):
convert `var wb = new XLWorkbook(); ...; wb.Dispose();` to
`using var wb = new XLWorkbook();` so the workbook is released even if
SaveAs or any of the intermediate ExcelHelper calls throw.

Other disposables that were leaked entirely:
- CMS.cs DecryptFile/DecryptAES: add `using` to Aes, MemoryStream, and
  StreamWriter locals.
- BiorenderStudentLookup: add `using` to the SemaphoreSlim throttler.
- F5HttpRequest.HandleConnectionFail: add `using` to the probe
  HttpRequestMessage.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR converts manual resource disposal to C# using declarations across cryptographic operations, Excel report generation, and utility services. All changes preserve existing behavior while ensuring deterministic cleanup of Aes, XLWorkbook, SemaphoreSlim, and HttpRequestMessage resources.

Changes

Resource Lifecycle Management

Layer / File(s) Summary
Cryptography and Stream Resource Cleanup
web/Areas/CMS/Data/CMS.cs
DecryptFile and DecryptAES now use using declarations for Aes cipher, MemoryStream, and StreamWriter to ensure disposal without changing decryption logic.
Excel Workbook Lifecycle in Report Services
web/Areas/Effort/Services/DeptSummaryService.cs, EvaluationReportService.cs, MeritMultiYearService.cs, MeritReportService.cs, MeritSummaryService.cs, SchoolSummaryService.cs, TeachingActivityService.cs
All report generators replace var wb = new XLWorkbook() + explicit wb.Dispose() with using var wb = new XLWorkbook(). Stream position resets and return behavior remain unchanged.
Other Resource Patterns
web/Areas/Computing/Services/BiorenderStudentLookup.cs, web/Classes/Utilities/F5HttpRequest.cs
SemaphoreSlim throttling in GetBiorenderStudentInfo and HttpRequestMessage construction in HandleConnectionFail adopt using declarations for proper cleanup.

🎯 2 (Simple) | ⏱️ ~8 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% 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 The title clearly describes the main change: fixing disposal of IDisposable objects on exception paths by wrapping them with using declarations.
Description check ✅ Passed The description is directly related to the changeset, detailing which CodeQL alerts are fixed, which files are modified, and the pattern of changes applied throughout.
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/4-dispose

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 16.66667% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 42.96%. Comparing base (38de1ad) to head (1839715).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
web/Areas/CMS/Data/CMS.cs 0.00% 4 Missing ⚠️
web/Classes/Utilities/F5HttpRequest.cs 0.00% 3 Missing ⚠️
...b/Areas/Effort/Services/EvaluationReportService.cs 0.00% 2 Missing ⚠️
web/Areas/Effort/Services/MeritReportService.cs 0.00% 2 Missing ⚠️
...Areas/Computing/Services/BiorenderStudentLookup.cs 0.00% 1 Missing ⚠️
web/Areas/Effort/Services/DeptSummaryService.cs 0.00% 1 Missing ⚠️
web/Areas/Effort/Services/MeritSummaryService.cs 0.00% 1 Missing ⚠️
web/Areas/Effort/Services/SchoolSummaryService.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main     #192   +/-   ##
=======================================
  Coverage   42.96%   42.96%           
=======================================
  Files         877      877           
  Lines       51468    51456   -12     
  Branches     4802     4802           
=======================================
- Hits        22113    22110    -3     
+ Misses      28831    28822    -9     
  Partials      524      524           
Flag Coverage Δ
backend 43.04% <16.66%> (+<0.01%) ⬆️
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.

ReSharper UsingStatementResourceInitialization: object initializer
inside 'using' means an exception during property assignment would
skip Dispose. Split into 'using var x = new()' + per-property assign.
@rlorenzo
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 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.

Caution

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

⚠️ Outside diff range comments (2)
web/Classes/Utilities/F5HttpRequest.cs (1)

49-50: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Dispose the warm-up response returned by Send(newRequest).

The response from the session-establishing GET is ignored and never disposed. Wrap it in using before issuing the retried request.

Proposed fix
-//don't care about the response
-await Send(newRequest);
+// don't care about payload, but dispose response resources
+using var warmupResponse = await Send(newRequest);
 return await Send(await CopyHttpRequest(request), 1);
🤖 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 `@web/Classes/Utilities/F5HttpRequest.cs` around lines 49 - 50, The call to
Send(newRequest) performs a warm-up GET whose HttpResponseMessage is never
disposed; change the logic in the method that calls Send(newRequest) so that the
result is awaited into a variable and wrapped in a using (or disposed) before
proceeding to call Send(await CopyHttpRequest(request), 1) — i.e., obtain the
response from Send(newRequest), dispose it (using a using block or calling
Dispose()), then execute the retried request built by CopyHttpRequest(request).
web/Areas/Computing/Services/BiorenderStudentLookup.cs (1)

23-47: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Semaphore permit leak can deadlock the loop on invalid emails.

WaitAsync happens before validation, but Release only happens in the task path. Invalid emails consume permits permanently and can block at Line 25 after 20 invalid entries.

Proposed fix
 foreach (var email in emails)
 {
-    await throttler.WaitAsync();
-
     var emailTrimmed = email.Trim();
     if (!emailTrimmed.Contains('@'))
     {
         emailTrimmed += "@ucdavis.edu";
     }
-    if (IsValidEmail(emailTrimmed))
-    {
-        resultList.Add(
-            Task.Run(async () =>
-            {
-                try
-                {
-                    return await GetSingleStudent(emailTrimmed);
-                }
-                finally
-                {
-                    throttler.Release();
-                }
-            })
-        );
-    }
+    if (!IsValidEmail(emailTrimmed))
+        continue;
+
+    await throttler.WaitAsync();
+    resultList.Add(
+        Task.Run(async () =>
+        {
+            try
+            {
+                return await GetSingleStudent(emailTrimmed);
+            }
+            finally
+            {
+                throttler.Release();
+            }
+        })
+    );
 }
🤖 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 `@web/Areas/Computing/Services/BiorenderStudentLookup.cs` around lines 23 - 47,
The loop calls throttler.WaitAsync() before validating emails, causing permits
to be consumed for invalid addresses and never released; move the
throttler.WaitAsync call so it's only awaited when you actually schedule a task
(i.e., perform emailTrimmed = email.Trim(); normalize domain; if
(IsValidEmail(emailTrimmed)) { await throttler.WaitAsync();
resultList.Add(Task.Run(async () => { try { return await
GetSingleStudent(emailTrimmed); } finally { throttler.Release(); } })); } ), or
alternatively ensure you call throttler.Release() on the invalid path
immediately after WaitAsync; update the code around the foreach, IsValidEmail,
throttler.WaitAsync, GetSingleStudent and throttler.Release usage accordingly.
🤖 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 `@web/Areas/Computing/Services/BiorenderStudentLookup.cs`:
- Around line 23-47: The loop calls throttler.WaitAsync() before validating
emails, causing permits to be consumed for invalid addresses and never released;
move the throttler.WaitAsync call so it's only awaited when you actually
schedule a task (i.e., perform emailTrimmed = email.Trim(); normalize domain; if
(IsValidEmail(emailTrimmed)) { await throttler.WaitAsync();
resultList.Add(Task.Run(async () => { try { return await
GetSingleStudent(emailTrimmed); } finally { throttler.Release(); } })); } ), or
alternatively ensure you call throttler.Release() on the invalid path
immediately after WaitAsync; update the code around the foreach, IsValidEmail,
throttler.WaitAsync, GetSingleStudent and throttler.Release usage accordingly.

In `@web/Classes/Utilities/F5HttpRequest.cs`:
- Around line 49-50: The call to Send(newRequest) performs a warm-up GET whose
HttpResponseMessage is never disposed; change the logic in the method that calls
Send(newRequest) so that the result is awaited into a variable and wrapped in a
using (or disposed) before proceeding to call Send(await
CopyHttpRequest(request), 1) — i.e., obtain the response from Send(newRequest),
dispose it (using a using block or calling Dispose()), then execute the retried
request built by CopyHttpRequest(request).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0b073be6-48c3-4aab-a5c2-0425ba3acebf

📥 Commits

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

📒 Files selected for processing (10)
  • web/Areas/CMS/Data/CMS.cs
  • web/Areas/Computing/Services/BiorenderStudentLookup.cs
  • web/Areas/Effort/Services/DeptSummaryService.cs
  • web/Areas/Effort/Services/EvaluationReportService.cs
  • web/Areas/Effort/Services/MeritMultiYearService.cs
  • web/Areas/Effort/Services/MeritReportService.cs
  • web/Areas/Effort/Services/MeritSummaryService.cs
  • web/Areas/Effort/Services/SchoolSummaryService.cs
  • web/Areas/Effort/Services/TeachingActivityService.cs
  • web/Classes/Utilities/F5HttpRequest.cs

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