Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,12 @@ csharp_style_namespace_declarations = file_scoped:warning
# Switch expression
dotnet_diagnostic.CS8509.severity = error # missing switch case for named enum value
dotnet_diagnostic.CS8524.severity = none # missing switch case for unnamed enum value

# CA2253: Named placeholders should nto be numeric values
dotnet_diagnostic.CA2253.severity = suggestion

# CA2254: Template should be a static expression
dotnet_diagnostic.CA2254.severity = warning

# CA1727: Use PascalCase for named placeholders
dotnet_diagnostic.CA1727.severity = suggestion
2 changes: 1 addition & 1 deletion bitwarden_license/src/Sso/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,6 @@ public void Configure(
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());

// Log startup
logger.LogInformation(Constants.BypassFiltersEventId, globalSettings.ProjectName + " started.");
logger.LogInformation(Constants.BypassFiltersEventId, "{Project} started.", globalSettings.ProjectName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ public async Task PatchGroup_InvalidOperation_Success(SutProvider<PatchGroupComm
await sutProvider.GetDependency<IGroupService>().DidNotReceiveWithAnyArgs().DeleteUserAsync(default, default);

// Assert: logging
sutProvider.GetDependency<ILogger<PatchGroupCommand>>().ReceivedWithAnyArgs().LogWarning(default);
sutProvider.GetDependency<ILogger<PatchGroupCommand>>().ReceivedWithAnyArgs().LogWarning("");
}

[Theory]
Expand Down
4 changes: 2 additions & 2 deletions src/Admin/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public async Task<IActionResult> GetLatestVersion(ProjectType project, Cancellat
}
catch (HttpRequestException e)
{
_logger.LogError(e, $"Error encountered while sending GET request to {requestUri}");
_logger.LogError(e, "Error encountered while sending GET request to {RequestUri}", requestUri);
return new JsonResult("Unable to fetch latest version") { StatusCode = StatusCodes.Status500InternalServerError };
}

Expand All @@ -83,7 +83,7 @@ public async Task<IActionResult> GetInstalledWebVersion(CancellationToken cancel
}
catch (HttpRequestException e)
{
_logger.LogError(e, $"Error encountered while sending GET request to {requestUri}");
_logger.LogError(e, "Error encountered while sending GET request to {RequestUri}", requestUri);
return new JsonResult("Unable to fetch installed version") { StatusCode = StatusCodes.Status500InternalServerError };
}

Expand Down
2 changes: 1 addition & 1 deletion src/Admin/Jobs/AliveJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protected async override Task ExecuteJobAsync(IJobExecutionContext context)
{
_logger.LogInformation(Constants.BypassFiltersEventId, "Execute job task: Keep alive");
var response = await _httpClient.GetAsync(_globalSettings.BaseServiceUri.Admin);
_logger.LogInformation(Constants.BypassFiltersEventId, "Finished job task: Keep alive, " +
_logger.LogInformation(Constants.BypassFiltersEventId, "Finished job task: Keep alive, {StatusCode}",
response.StatusCode);
}
}
2 changes: 1 addition & 1 deletion src/Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,6 @@ public void Configure(
}

// Log startup
logger.LogInformation(Constants.BypassFiltersEventId, globalSettings.ProjectName + " started.");
logger.LogInformation(Constants.BypassFiltersEventId, "{Project} started.", globalSettings.ProjectName);
}
}
2 changes: 1 addition & 1 deletion src/Api/Tools/Controllers/SendsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public async Task<ObjectResult> AzureValidateFile()
}
catch (Exception e)
{
_logger.LogError(e, $"Uncaught exception occurred while handling event grid event: {JsonSerializer.Serialize(eventGridEvent)}");
_logger.LogError(e, "Uncaught exception occurred while handling event grid event: {Event}", JsonSerializer.Serialize(eventGridEvent));
return;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Utilities/ExceptionHandlerFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public override void OnException(ExceptionContext context)
else
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ExceptionHandlerFilterAttribute>>();
logger.LogError(0, exception, exception.Message);
logger.LogError(0, exception, "Unhandled exception");
errorMessage = "An unhandled server error has occurred.";
context.HttpContext.Response.StatusCode = 500;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Vault/Controllers/CiphersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1573,7 +1573,7 @@ public async Task<ObjectResult> AzureValidateFile()
}
catch (Exception e)
{
_logger.LogError(e, $"Uncaught exception occurred while handling event grid event: {JsonSerializer.Serialize(eventGridEvent)}");
_logger.LogError(e, "Uncaught exception occurred while handling event grid event: {Event}", JsonSerializer.Serialize(eventGridEvent));
return;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public async Task UpdateAsync(Guid organizationId, IEnumerable<OrganizationAuthR
AuthRequestExpiresAfter = _globalSettings.PasswordlessAuth.AdminRequestExpiration
}
);
processor.Process((Exception e) => _logger.LogError(e.Message));
processor.Process((Exception e) => _logger.LogError("Error processing organization auth request: {Message}", e.Message));
await processor.Save((IEnumerable<OrganizationAdminAuthRequest> authRequests) => _authRequestRepository.UpdateManyAsync(authRequests));
await processor.SendPushNotifications((ar) => _pushNotificationService.PushAuthRequestResponseAsync(ar));
await processor.SendApprovalEmailsForProcessedRequests(SendApprovalEmail);
Expand All @@ -114,7 +114,7 @@ async Task SendApprovalEmail<T>(T authRequest, string identifier) where T : Auth
// This should be impossible
if (user == null)
{
_logger.LogError($"User {authRequest.UserId} not found. Trusted device admin approval email not sent.");
_logger.LogError("User {UserId} not found. Trusted device admin approval email not sent.", authRequest.UserId);
return;
}

Expand Down
6 changes: 3 additions & 3 deletions src/Core/Jobs/BaseJobsHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@
throw new Exception("Job failed to start after 10 retries.");
}

_logger.LogWarning($"Exception while trying to schedule job: {job.FullName}, {e}");
_logger.LogWarning(e, "Exception while trying to schedule job: {JobName}", job.FullName);
var random = new Random();

Check warning on line 111 in src/Core/Jobs/BaseJobsHostedService.cs

View workflow job for this annotation

GitHub Actions / Sonar / Quality scan

Make sure that using this pseudorandom number generator is safe here. (https://rules.sonarsource.com/csharp/RSPEC-2245)
await Task.Delay(random.Next(50, 250));
}
}
Expand All @@ -125,7 +125,7 @@
continue;
}

_logger.LogInformation($"Deleting old job with key {key}");
_logger.LogInformation("Deleting old job with key {Key}", key);
await _scheduler.DeleteJob(key);
}

Expand All @@ -138,7 +138,7 @@
continue;
}

_logger.LogInformation($"Unscheduling old trigger with key {key}");
_logger.LogInformation("Unscheduling old trigger with key {Key}", key);
await _scheduler.UnscheduleJob(key);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task SyncOrganization(Guid organizationId, Guid cloudOrganizationId
.ToDictionary(i => i.SponsoringOrganizationUserId);
if (!organizationSponsorshipsDict.Any())
{
_logger.LogInformation($"No existing sponsorships to sync for organization {organizationId}");
_logger.LogInformation("No existing sponsorships to sync for organization {organizationId}", organizationId);
return;
}
var syncedSponsorships = new List<OrganizationSponsorshipData>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ public override void OnException(ExceptionContext context)

var logger = context.HttpContext.RequestServices
.GetRequiredService<ILogger<LoggingExceptionHandlerFilterAttribute>>();
logger.LogError(0, exception, exception.Message);
logger.LogError(0, exception, "Unhandled exception");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,7 @@ await _eventService.LogUserEventAsync(user.Id,
if (_globalSettings.SelfHosted)
{
_logger.LogWarning(Constants.BypassFiltersEventId,
string.Format("Failed login attempt{0}{1}", twoFactorRequest ? ", 2FA invalid." : ".",
$" {CurrentContext.IpAddress}"));
"Failed login attempt. Is2FARequest: {Is2FARequest} IpAddress: {IpAddress}", twoFactorRequest, CurrentContext.IpAddress);
}

await Task.Delay(2000); // Delay for brute force.
Expand Down Expand Up @@ -294,7 +293,7 @@ protected async Task LogFailedLoginEvent(User user, EventType eventType)
formattedMessage = "Failed login attempt.";
break;
}
_logger.LogWarning(Constants.BypassFiltersEventId, formattedMessage);
_logger.LogWarning(Constants.BypassFiltersEventId, "{FailedLoginMessage}", formattedMessage);
}
await Task.Delay(2000); // Delay for brute force.
}
Expand Down
2 changes: 1 addition & 1 deletion src/Identity/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,6 @@ public void Configure(
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());

// Log startup
logger.LogInformation(Constants.BypassFiltersEventId, globalSettings.ProjectName + " started.");
logger.LogInformation(Constants.BypassFiltersEventId, "{Project} started.", globalSettings.ProjectName);
}
}
2 changes: 1 addition & 1 deletion src/SharedWeb/Utilities/ExceptionHandlerFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public override void OnException(ExceptionContext context)
else
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ExceptionHandlerFilterAttribute>>();
logger.LogError(0, exception, exception.Message);
logger.LogError(0, exception, "Unhandled exception");
errorMessage = "An unhandled server error has occurred.";
context.HttpContext.Response.StatusCode = 500;
}
Expand Down
3 changes: 1 addition & 2 deletions test/Core.Test/Auth/Services/AuthRequestServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -467,10 +467,9 @@ await sutProvider.GetDependency<IMailService>()
Arg.Any<string>(),
Arg.Any<string>());

var expectedLogMessage = "There are no admin emails to send to.";
sutProvider.GetDependency<ILogger<AuthRequestService>>()
.Received(1)
.LogWarning(expectedLogMessage);
.LogWarning("There are no admin emails to send to.");
}

/// <summary>
Expand Down
1 change: 1 addition & 0 deletions test/Identity.Test/Identity.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Diagnostics.Testing" Version="9.3.0" />
<PackageReference Include="coverlet.collector" Version="$(CoverletCollectorVersion)">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
Expand Down
10 changes: 6 additions & 4 deletions test/Identity.Test/IdentityServer/BaseRequestValidatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using Duende.IdentityServer.Validation;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Options;
using NSubstitute;
using Xunit;
Expand All @@ -40,7 +41,7 @@ public class BaseRequestValidatorTests
private readonly IDeviceValidator _deviceValidator;
private readonly ITwoFactorAuthenticationValidator _twoFactorAuthenticationValidator;
private readonly IOrganizationUserRepository _organizationUserRepository;
private readonly ILogger<BaseRequestValidatorTests> _logger;
private readonly FakeLogger<BaseRequestValidatorTests> _logger;
private readonly ICurrentContext _currentContext;
private readonly GlobalSettings _globalSettings;
private readonly IUserRepository _userRepository;
Expand All @@ -62,7 +63,7 @@ public BaseRequestValidatorTests()
_deviceValidator = Substitute.For<IDeviceValidator>();
_twoFactorAuthenticationValidator = Substitute.For<ITwoFactorAuthenticationValidator>();
_organizationUserRepository = Substitute.For<IOrganizationUserRepository>();
_logger = Substitute.For<ILogger<BaseRequestValidatorTests>>();
_logger = new FakeLogger<BaseRequestValidatorTests>();
_currentContext = Substitute.For<ICurrentContext>();
_globalSettings = Substitute.For<GlobalSettings>();
_userRepository = Substitute.For<IUserRepository>();
Expand Down Expand Up @@ -115,7 +116,8 @@ public async Task ValidateAsync_ContextNotValid_SelfHosted_ShouldBuildErrorResul
await _sut.ValidateAsync(context);

// Assert
_logger.Received(1).LogWarning(Constants.BypassFiltersEventId, "Failed login attempt. ");
var logs = _logger.Collector.GetSnapshot(true);
Assert.Contains(logs, l => l.Level == LogLevel.Warning && l.Message == "Failed login attempt. Is2FARequest: False IpAddress: ");
var errorResponse = (ErrorResponseModel)context.GrantResult.CustomResponse["ErrorModel"];
Assert.Equal("Username or password is incorrect. Try again.", errorResponse.Message);
}
Expand Down Expand Up @@ -337,7 +339,7 @@ public async Task ValidateAsync_TwoFactorRememberTokenExpired_ShouldNotSendFaile
// 1 -> initial validation passes
_sut.isValid = true;

// 2 -> enable the FailedTwoFactorEmail feature flag
// 2 -> enable the FailedTwoFactorEmail feature flag
_featureService.IsEnabled(FeatureFlagKeys.FailedTwoFactorEmail).Returns(true);

// 3 -> set up 2FA as required
Expand Down
4 changes: 2 additions & 2 deletions util/Migrator/DbMigrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public bool MigrateMsSqlDatabaseWithRetries(bool enableLogging = true,
if (ex.Message.Contains("Server is in script upgrade mode."))
{
attempt++;
_logger.LogInformation($"Database is in script upgrade mode, trying again (attempt #{attempt}).");
_logger.LogInformation("Database is in script upgrade mode, trying again (attempt #{Attempt}).", attempt);
Thread.Sleep(20000);
}
else
Expand Down Expand Up @@ -165,7 +165,7 @@ private bool MigrateDatabase(bool enableLogging = true,
{
stringBuilder.AppendLine(script.Name);
}
_logger.LogInformation(Constants.BypassFiltersEventId, stringBuilder.ToString());
_logger.LogInformation(Constants.BypassFiltersEventId, "{Scripts}", stringBuilder.ToString());
return true;
}

Expand Down
12 changes: 6 additions & 6 deletions util/Migrator/DbUpLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,31 @@ public DbUpLogger(ILogger logger)

public void LogTrace(string format, params object[] args)
{
_logger.LogTrace(Constants.BypassFiltersEventId, format, args);
_logger.LogTrace(Constants.BypassFiltersEventId, "{TraceMessage}", string.Format(format, args));
}

public void LogDebug(string format, params object[] args)
{
_logger.LogDebug(Constants.BypassFiltersEventId, format, args);
_logger.LogDebug(Constants.BypassFiltersEventId, "{DebugMessage}", string.Format(format, args));
}

public void LogInformation(string format, params object[] args)
{
_logger.LogInformation(Constants.BypassFiltersEventId, format, args);
_logger.LogInformation(Constants.BypassFiltersEventId, "{InfoMessage}", string.Format(format, args));
}

public void LogWarning(string format, params object[] args)
{
_logger.LogWarning(Constants.BypassFiltersEventId, format, args);
_logger.LogWarning(Constants.BypassFiltersEventId, "{WarningMessage}", string.Format(format, args));
}

public void LogError(string format, params object[] args)
{
_logger.LogError(Constants.BypassFiltersEventId, format, args);
_logger.LogError(Constants.BypassFiltersEventId, "{ErrorMessage}", string.Format(format, args));
}

public void LogError(Exception ex, string format, params object[] args)
{
_logger.LogError(Constants.BypassFiltersEventId, ex, format, args);
_logger.LogError(Constants.BypassFiltersEventId, ex, "{ErrorMessage}", string.Format(format, args));
}
}
Loading