Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LNK-3039: Security Fixes (Dev) #531

Merged
merged 9 commits into from
Nov 1, 2024
Merged

Conversation

MontaltoNick
Copy link
Contributor

@MontaltoNick MontaltoNick commented Oct 31, 2024

🛠 Description of Changes

https://lantana.atlassian.net/browse/LNK-3031
https://lantana.atlassian.net/browse/LNK-3039
https://lantana.atlassian.net/browse/LNK-3040
https://lantana.atlassian.net/browse/LNK-3032

🧪 Testing Performed

Please describe the testing that was performed on the changes included in this PR.

Summary by CodeRabbit

  • Bug Fixes

    • Simplified error handling in user creation to improve response clarity when an email conflict occurs.
    • Streamlined error handling across multiple controllers, ensuring exceptions are logged and returned as user-friendly problem responses without rethrowing.
  • New Features

    • Enhanced structured logging for improved clarity in error reporting across various controller methods.
    • Improved security by sanitizing logged facility IDs in the RemoveFacility method.
  • Documentation

    • Updated internal documentation to reflect changes in error handling and logging practices.

@MontaltoNick MontaltoNick changed the title LNK-3039: Security Fixes LNK-3039: Security Fixes (Dev) Oct 31, 2024
Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

This pull request introduces modifications across several controller classes in the .NET application, primarily focused on enhancing error handling and logging practices. Changes include the removal of specific logging statements in favor of simpler, structured logging approaches that capture exceptions more effectively. Additionally, the response mechanisms for errors have been standardized to return a Problem result with relevant details instead of rethrowing exceptions. The CreateNewUser class has also been simplified by eliminating URI construction for existing users during email conflicts.

Changes

File Path Change Summary
DotNet/Account/Presentation/Endpoints/User/Handlers/CreateNewUser.cs Removed URI construction for existing users in conflict handling.
DotNet/Census/Controllers/CensusConfigController.cs Simplified error logging and responses in Create, Get, Put, and Delete methods.
DotNet/Census/Controllers/CensusController.cs Updated error handling in GetCensusHistory, GetAdmittedPatients, GetCurrentCensus, and GetAllPatientsForFacility methods to use simplified logging and return Problem results.
DotNet/Normalization/Controllers/NormalizationController.cs Enhanced structured logging and error responses in StoreTenant, GetConfig, UpdateTenantNormalization, and DeleteTenantNormalization methods.
DotNet/Tenant/Controllers/FacilityController.cs Improved structured logging in StoreFacility, UpdateFacility, and DeleteFacility; simplified null checks in LookupFacilityById.
DotNet/Census/Domain/Managers/CensusConfigManager.cs Simplified error logging in AddOrUpdateCensusConfig method.
DotNet/Normalization/Application/Managers/NormalizationConfigManager.cs Modified error logging in SaveConfigEntity method to remove facility ID from logs.
DotNet/Tenant/Services/FacilityConfigurationService.cs Sanitized facilityId in logging within RemoveFacility method.

Possibly related PRs

  • LNK-3033: Census Mass Assignment #505: The changes in the CensusConfigModel class, which involve adding [DataContract] and [DataMember] attributes, relate to the main PR's focus on modifying the CreateNewUser class's handling of user creation and conflict resolution, as both involve adjustments to data handling and serialization practices.
  • LNK-3044: Log Forging Query Dispatch #526: The sanitization of identifiers in the PatientDispatchManager class enhances security in logging, similar to the main PR's change in handling user conflict responses, indicating a broader focus on improving data handling and response mechanisms across the application.

Suggested reviewers

  • amphillipsLGC
  • dvargaslantana

🐰 In the code, we hop and play,
With logging clear, we pave the way.
Errors caught, no more to chase,
Simplified paths in our coding space.
For users new, we pave the lane,
In this rabbit hole, we’ll code again! 🐇


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 68c60df and db1295f.

📒 Files selected for processing (1)
  • DotNet/Census/Domain/Managers/CensusConfigManager.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • DotNet/Census/Domain/Managers/CensusConfigManager.cs

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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: 16

🧹 Outside diff range and nitpick comments (11)
DotNet/Account/Presentation/Endpoints/User/Handlers/CreateNewUser.cs (3)

Line range hint 48-54: Security concern: Exception handling exposes internal details

The catch block re-throws exceptions which could expose sensitive implementation details to clients. Consider mapping exceptions to appropriate HTTP responses.

Apply this change:

 catch (Exception ex)
 {
     Activity.Current?.SetStatus(ActivityStatusCode.Error);
     Activity.Current?.RecordException(ex);
     logger.LogUserCreationException(ex.Message);
-    throw;
+    return Results.Problem(
+        statusCode: StatusCodes.Status500InternalServerError,
+        title: "An error occurred while processing your request."
+    );
 }

Line range hint 17-24: Add input validation for email

The handler lacks email format validation before checking for existing users. This could lead to unnecessary database queries or storage of invalid data.

Add validation before the existing user check:

 if (model is null)
 {
     return Results.BadRequest("No user was provided in the request.");
 }
+
+if (string.IsNullOrWhiteSpace(model.Email) || !IsValidEmail(model.Email))
+{
+    return Results.BadRequest("Invalid email format.");
+}

//check if user with the same email exists

Add this helper method:

private static bool IsValidEmail(string email)
{
    try
    {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch
    {
        return false;
    }
}

Rate limiting should be implemented to protect the API endpoint

The codebase lacks rate limiting implementation which could make it vulnerable to abuse. Consider:

  1. Install the Microsoft.AspNetCore.RateLimiting NuGet package
  2. Add rate limiting middleware in Program.cs:
builder.Services.AddRateLimiter(options =>
{
    options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
        RateLimitPartition.GetFixedWindowLimiter(
            partitionKey: context.User.Identity?.Name ?? context.Request.Headers.Host.ToString(),
            factory: partition => new FixedWindowRateLimiterOptions
            {
                AutoReplenishment = true,
                PermitLimit = 10,
                Window = TimeSpan.FromSeconds(10)
            }));
});
  1. Apply the middleware:
app.UseRateLimiter();
🔗 Analysis chain

Line range hint 1-54: Consider implementing rate limiting

The endpoint lacks rate limiting which could make it vulnerable to brute force attacks or DoS attempts. Consider adding rate limiting middleware.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if rate limiting is implemented elsewhere
rg -l "RateLimiting" 
rg -l "IpRateLimiting"

Length of output: 43


Script:

#!/bin/bash
# Let's check for rate limiting related configurations and middleware
rg -i "rate.?limit" -A 5

Length of output: 454


Script:

#!/bin/bash
# Check Program.cs, Startup.cs for middleware configuration
fd -e cs "(Program|Startup)" --exec cat {}

Length of output: 173382


Script:

#!/bin/bash
# Check for any NuGet packages related to rate limiting in csproj files
fd -e csproj . --exec cat {}

Length of output: 51177


Script:

#!/bin/bash
# Check for rate limiting middleware/configuration in ASP.NET Core
rg -i "rate.?limit" -A 5 -g "*.cs"

Length of output: 36


Script:

#!/bin/bash
# Check for rate limiting NuGet packages in csproj files
rg -i "rate.?limit" -g "*.csproj"

Length of output: 35


Script:

#!/bin/bash
# Check for rate limiting configuration in appsettings files
rg -i "rate.?limit" -g "appsettings*.json"

Length of output: 44

DotNet/Census/Controllers/CensusConfigController.cs (1)

Line range hint 1-177: Consider additional security measures

While the authorization policy is in place, consider implementing these additional security measures:

  1. Add input validation/sanitization for facilityId parameter
  2. Implement rate limiting for the API endpoints
  3. Add anti-CSRF tokens for state-changing operations (POST, PUT, DELETE)
  4. Consider adding request logging middleware to track API usage patterns

Would you like assistance in implementing any of these security measures?

DotNet/Census/Controllers/CensusController.cs (5)

Line range hint 9-13: Add input validation for facilityId path parameter.

While the controller is properly secured with admin authorization, the facilityId path parameter should be validated to prevent path traversal attacks. Consider adding a route constraint or validation attribute.

Example implementation:

-[Route("api/census/{facilityId}")]
+[Route("api/census/{facilityId:regex(^[a-zA-Z0-9-_]+$)}")]

Line range hint 60-99: Add input validation for date parameters and secure FHIR resource construction.

  1. The date parameters lack validation, which could lead to potential DoS through large date ranges.
  2. The FHIR resource construction should ensure no sensitive patient data is accidentally exposed.

Add date validation:

if (startDate != default && endDate != default && startDate > endDate)
{
    return BadRequest("Start date must be before end date");
}

if (endDate != default && endDate > DateTime.UtcNow)
{
    return BadRequest("End date cannot be in the future");
}

// Optional: Limit date range to prevent DoS
if ((endDate - startDate).TotalDays > 365)
{
    return BadRequest("Date range cannot exceed 365 days");
}

Line range hint 122-130: Strengthen input validation for facilityId.

While the method checks for null/empty, it should also validate the format and length of the facilityId to prevent injection attacks.

-if (string.IsNullOrEmpty(facilityId))
+if (string.IsNullOrEmpty(facilityId) || facilityId.Length > 50 || !Regex.IsMatch(facilityId, "^[a-zA-Z0-9-_]+$"))
 {
-    return BadRequest("FacilityId parameter is null or empty.");
+    return BadRequest("Invalid facility ID format.");
 }

Line range hint 149-156: Add input validation for facilityId.

This method is missing the facilityId validation that exists in GetCurrentCensus. Add consistent validation across all methods.

if (string.IsNullOrEmpty(facilityId) || facilityId.Length > 50 || !Regex.IsMatch(facilityId, "^[a-zA-Z0-9-_]+$"))
{
    return BadRequest("Invalid facility ID format.");
}

Potential security risk: Exception details exposed in API responses

The codebase consistently exposes exception messages in API responses across multiple controllers, which could leak sensitive information about the system's internals to potential attackers. This includes:

  • Direct exposure of exception messages in Problem() responses
  • Raw exception messages in BadRequest() responses
  • Some controllers even expose inner exception details (e.g., ConnectionValidationController)

Key locations that need attention:

  • DotNet/Census/Controllers/CensusController.cs
  • DotNet/DataAcquisition/Controllers/ConnectionValidationController.cs (exposes inner exceptions)
  • DotNet/Tenant/Controllers/FacilityController.cs
  • DotNet/Normalization/Controllers/NormalizationController.cs
  • DotNet/DataAcquisition/Controllers/QueryConfigController.cs

Recommendation: Replace exception messages with user-friendly error messages that don't expose internal details. Only log the full exception details for debugging purposes.

🔗 Analysis chain

Line range hint 1-160: Verify consistent error handling across the codebase.

Let's check if other controllers might be exposing exception details in their error responses.


Let me check the actual implementation of these error responses to better understand the pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Problem() calls that might expose exception messages
rg -l 'Problem.*ex\.Message' 

# Search for other potential exception exposure patterns
rg -l 'new ObjectResult.*ex' 
rg -l 'BadRequest.*ex\.Message'

Length of output: 839


Script:

#!/bin/bash
# Check the actual implementation of Problem() calls
rg -A 2 'Problem.*ex\.Message' 

# Check BadRequest implementations
rg -A 2 'BadRequest.*ex\.Message'

Length of output: 22710

DotNet/Normalization/Controllers/NormalizationController.cs (1)

Line range hint 1-199: Consider implementing centralized error handling

To ensure consistent and secure error handling across all controllers, consider implementing a global error handling middleware or base controller.

This would help:

  1. Standardize error responses
  2. Prevent accidental exposure of sensitive information
  3. Centralize security logging
  4. Implement proper error correlation IDs

Would you like me to provide an example implementation of a secure error handling middleware?

DotNet/Tenant/Controllers/FacilityController.cs (1)

Line range hint 1-285: Security: Consider adding rate limiting and audit logging

While the controller has basic authorization, consider these additional security measures:

  1. Implement rate limiting to prevent DoS attacks
  2. Add audit logging for sensitive operations (create/update/delete)
  3. Consider implementing request validation using a request validation pipeline

Example implementation using middleware:

public class AuditLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IAuditLogger _auditLogger;

    public async Task InvokeAsync(HttpContext context)
    {
        if (IsSensitiveOperation(context.Request.Method))
        {
            await _auditLogger.LogAsync(new AuditEvent
            {
                User = context.User.Identity.Name,
                Action = context.Request.Method,
                Resource = context.Request.Path,
                Timestamp = DateTime.UtcNow
            });
        }
        await _next(context);
    }
}

// Add rate limiting using AspNetCoreRateLimit
services.Configure<IpRateLimitOptions>(options =>
{
    options.GeneralRules = new List<RateLimitRule>
    {
        new RateLimitRule
        {
            Endpoint = "*",
            Period = "1m",
            Limit = 30
        }
    };
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 722c782 and 80ab430.

📒 Files selected for processing (5)
  • DotNet/Account/Presentation/Endpoints/User/Handlers/CreateNewUser.cs (1 hunks)
  • DotNet/Census/Controllers/CensusConfigController.cs (4 hunks)
  • DotNet/Census/Controllers/CensusController.cs (4 hunks)
  • DotNet/Normalization/Controllers/NormalizationController.cs (4 hunks)
  • DotNet/Tenant/Controllers/FacilityController.cs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
DotNet/Account/Presentation/Endpoints/User/Handlers/CreateNewUser.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Census/Controllers/CensusConfigController.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Census/Controllers/CensusController.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Normalization/Controllers/NormalizationController.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Tenant/Controllers/FacilityController.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

🔇 Additional comments (2)
DotNet/Account/Presentation/Endpoints/User/Handlers/CreateNewUser.cs (1)

Line range hint 33-34: Avoid logging sensitive user information

The LogUserCreated method potentially logs sensitive user identifiers. Consider logging only non-sensitive metadata or masking sensitive parts of the identifiers.

DotNet/Census/Controllers/CensusConfigController.cs (1)

90-91: ⚠️ Potential issue

Apply consistent error message sanitization

Similar to the Create method, avoid exposing internal error details in the response.

Apply the same pattern of using a sanitized error message in the Problem response.

DotNet/Census/Controllers/CensusConfigController.cs Outdated Show resolved Hide resolved
DotNet/Census/Controllers/CensusConfigController.cs Outdated Show resolved Hide resolved
DotNet/Census/Controllers/CensusConfigController.cs Outdated Show resolved Hide resolved
DotNet/Census/Controllers/CensusController.cs Outdated Show resolved Hide resolved
DotNet/Tenant/Controllers/FacilityController.cs Outdated Show resolved Hide resolved
DotNet/Tenant/Controllers/FacilityController.cs Outdated Show resolved Hide resolved
DotNet/Tenant/Controllers/FacilityController.cs Outdated Show resolved Hide resolved
MontaltoNick and others added 3 commits October 31, 2024 13:58
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
MontaltoNick and others added 4 commits October 31, 2024 14:02
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
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: 6

🧹 Outside diff range and nitpick comments (7)
DotNet/Normalization/Application/Managers/NormalizationConfigManager.cs (1)

Based on the search results from all scripts executed, I can now provide a final response:

Consider implementing additional security measures for OperationSequence validation and rate limiting

While the code has good input validation for null checks and facility existence, and audit logging is well implemented through the audit service, there are two security aspects that should be addressed:

  1. Add input validation for OperationSequence contents to prevent injection attacks:

    • Implement a validator class to validate operation sequence structure and content
    • Add sanitization of operation parameters
    • Consider using a schema validation approach
  2. Add rate limiting to prevent DoS attacks:

    • Implement rate limiting middleware
    • Configure per-client request limits
    • Add retry-after headers for rate-limited responses
🔗 Analysis chain

Line range hint 38-116: Consider additional security improvements for SaveConfigEntity method.

While the method has good input validation, consider implementing these security enhancements:

  1. Add validation for OperationSequence contents to prevent injection attacks
  2. Implement rate limiting to prevent DoS attacks
  3. Add audit logging for configuration changes

Let's verify if audit logging exists elsewhere:


Based on the search results, I can see that audit logging is already well implemented in the codebase. Let me search for validation patterns to check for input validation and rate limiting:


Let me check for any validation classes or interfaces that might be used for input validation:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for audit logging patterns in the codebase
echo "Checking for audit logging implementations..."
rg -i "audit.*log|ActivityLog|ILogger.*audit" 

# Search for rate limiting implementations
echo "Checking for rate limiting implementations..."
rg -i "RateLimit|ThrottleAttribute|IpRateLimit"

Length of output: 163560


Script:

#!/bin/bash
# Search for validation patterns in NormalizationConfigManager and related files
echo "Checking for validation patterns..."
rg -i "validate|sanitize|clean" DotNet/Normalization/Application/

# Search for rate limiting middleware or configurations
echo "Checking for rate limiting configurations..."
rg -i "middleware|configure|startup" DotNet/Normalization/ -A 5

Length of output: 5443


Script:

#!/bin/bash
# Search for validation classes and interfaces
echo "Checking for validation implementations..."
rg -i "class.*validator|interface.*validator|ivalidator" DotNet/Normalization/

# Search for operation sequence validation patterns
echo "Checking for operation sequence validation..."
rg -i "operationsequence.*valid|validate.*operation" DotNet/Normalization/

Length of output: 353

DotNet/Census/Domain/Managers/CensusConfigManager.cs (3)

Line range hint 89-95: Remove sensitive information from error messages.

The current error messages include stack traces, inner exceptions, and source information which could expose system internals to attackers if logs are compromised. This is a security vulnerability that needs to be addressed.

Apply this pattern to all similar catch blocks:

 catch (Exception ex)
 {
-    var message =
-        $"Error saving config for facility {existingEntity.FacilityID} {ex.Message}\n{ex.InnerException}\n{ex.Source}\n{ex.StackTrace}";
-    _logger.LogError(message, ex);
+    _logger.LogError(ex, "Failed to save configuration for facility {FacilityId}", existingEntity.FacilityID);
     throw;
 }

Also applies to: 124-130


Line range hint 143-147: Remove unused sensitive message construction.

The TODO comment indicates unused code that constructs a message containing sensitive information. This should be removed to prevent potential security risks if implemented incorrectly in the future.

Apply this change:

 catch (Exception ex)
 {
-    //TODO: Daniel - doesn't do anything with the message
-    var message =
-        $"Error saving config for facility {existingEntity.FacilityID} {ex.Message}\n{ex.InnerException}\n{ex.Source}\n{ex.StackTrace}";
+    _logger.LogError(ex, "Failed to save new configuration for facility {FacilityId}", existingEntity.FacilityID);
     throw;
 }

Line range hint 66-67: Add security controls for configuration changes.

Consider implementing these security improvements:

  1. Validate ScheduledTrigger input to prevent potential injection attacks
  2. Add audit logging for configuration changes to maintain security trail

Example implementation:

// Add input validation
private void ValidateScheduledTrigger(string trigger)
{
    if (string.IsNullOrEmpty(trigger)) throw new ArgumentException("Trigger cannot be empty");
    if (!CronExpression.IsValidExpression(trigger)) 
        throw new ArgumentException("Invalid trigger format");
}

// Add audit logging
private async Task LogAudit(string facilityId, string action, string details)
{
    await _auditLogger.LogAsync(new AuditEvent
    {
        Action = action,
        Resource = "CensusConfig",
        ResourceId = facilityId,
        Details = details
    });
}
DotNet/Census/Controllers/CensusConfigController.cs (2)

Line range hint 83-89: Add audit logging for configuration retrieval

Configuration access should be audited for security monitoring.

Add audit logging:

 try
 {
+    var user = User.Identity?.Name ?? "unknown";
+    _logger.LogInformation(
+        "Configuration retrieval requested for facility {FacilityId} by user {User}",
+        facilityId,
+        user
+    );
     var response = await _censusConfigManager.GetCensusConfigByFacilityId(facilityId);
     if (response == null)
+    {
+        _logger.LogWarning(
+            "No configuration found for facility {FacilityId} requested by user {User}",
+            facilityId,
+            user
+        );
         return NotFound();
+    }

Line range hint 176-179: Add audit logging for delete operation and fix response code

This critical operation needs audit logging, and the response code should match the documentation.

Apply these improvements:

 try
 {
+    var user = User.Identity?.Name ?? "unknown";
+    _logger.LogInformation(
+        "Configuration deletion requested for facility {FacilityId} by user {User}",
+        facilityId,
+        user
+    );
     await _censusConfigManager.DeleteCensusConfigByFacilityId(facilityId);
+    _logger.LogInformation(
+        "Configuration successfully deleted for facility {FacilityId} by user {User}",
+        facilityId,
+        user
+    );
-    return Accepted();
+    return NoContent();
 }
DotNet/Tenant/Services/FacilityConfigurationService.cs (1)

Line range hint 1-486: Consider implementing comprehensive input sanitization

While this PR introduces input sanitization for logging, a more comprehensive security approach is needed:

  1. Consider creating a security middleware or decorator that automatically sanitizes all input parameters
  2. Implement consistent sanitization across all logging, audit events, and error messages
  3. Add security tests to verify protection against log injection attacks

Would you like assistance in designing a more comprehensive security solution that could be applied consistently across the codebase?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 80ab430 and bf99da8.

📒 Files selected for processing (8)
  • DotNet/Account/Presentation/Endpoints/User/Handlers/CreateNewUser.cs (3 hunks)
  • DotNet/Census/Controllers/CensusConfigController.cs (5 hunks)
  • DotNet/Census/Controllers/CensusController.cs (4 hunks)
  • DotNet/Census/Domain/Managers/CensusConfigManager.cs (1 hunks)
  • DotNet/Normalization/Application/Managers/NormalizationConfigManager.cs (1 hunks)
  • DotNet/Normalization/Controllers/NormalizationController.cs (4 hunks)
  • DotNet/Tenant/Controllers/FacilityController.cs (4 hunks)
  • DotNet/Tenant/Services/FacilityConfigurationService.cs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • DotNet/Account/Presentation/Endpoints/User/Handlers/CreateNewUser.cs
  • DotNet/Census/Controllers/CensusController.cs
  • DotNet/Normalization/Controllers/NormalizationController.cs
  • DotNet/Tenant/Controllers/FacilityController.cs
🧰 Additional context used
📓 Path-based instructions (4)
DotNet/Census/Controllers/CensusConfigController.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Census/Domain/Managers/CensusConfigManager.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Normalization/Application/Managers/NormalizationConfigManager.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

DotNet/Tenant/Services/FacilityConfigurationService.cs (1)

Pattern **: PRs that have "TECH-DEBT" in the title should only contain changes related to typos, unused code, linter/IDE suggestions, swagger specification updates, and logging improvements. These TECH-DEBT PRs should not affect core functionality.

🔇 Additional comments (2)
DotNet/Normalization/Application/Managers/NormalizationConfigManager.cs (1)

71-72: LGTM! Good security improvement in error logging.

The change to remove facility ID from error logs is a positive security enhancement that prevents potential exposure of sensitive information in log files.

DotNet/Tenant/Services/FacilityConfigurationService.cs (1)

20-20: LGTM: Security dependency added correctly

The addition of the security services import is appropriate for implementing input sanitization.

Copy link
Contributor

@amphillipsLGC amphillipsLGC left a comment

Choose a reason for hiding this comment

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

Looks good!

@MontaltoNick MontaltoNick merged commit 969f42c into dev Nov 1, 2024
21 checks passed
@MontaltoNick MontaltoNick deleted the nmontalto/LNK-3039_SecurityIssues branch November 1, 2024 20:28
@MontaltoNick MontaltoNick restored the nmontalto/LNK-3039_SecurityIssues branch November 1, 2024 20:28
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