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

[PM-336] Nullable Platform & Unowned Services #5646

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟnamespace Bit.Core.Platform.Installations;
๏ปฟ#nullable enable

namespace Bit.Core.Platform.Installations;

/// <summary>
/// Command interface responsible for updating data on an `Installation`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟnamespace Bit.Core.Platform.Installations;
๏ปฟ#nullable enable

namespace Bit.Core.Platform.Installations;

/// <summary>
/// Commands responsible for updating an installation from
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟnamespace Bit.Core.Platform.Installations;
๏ปฟ#nullable enable

namespace Bit.Core.Platform.Installations;

/// <summary>
/// Queries responsible for fetching an installation from
Expand All @@ -19,7 +21,7 @@ public GetInstallationQuery(IInstallationRepository installationRepository)
}

/// <inheritdoc cref="IGetInstallationQuery.GetByIdAsync"/>
public async Task<Installation> GetByIdAsync(Guid installationId)
public async Task<Installation?> GetByIdAsync(Guid installationId)
{
if (installationId == default(Guid))
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟnamespace Bit.Core.Platform.Installations;
๏ปฟ#nullable enable

namespace Bit.Core.Platform.Installations;

/// <summary>
/// Query interface responsible for fetching an installation from
Expand All @@ -16,5 +18,5 @@ public interface IGetInstallationQuery
/// <param name="installationId">The GUID id of the installation.</param>
/// <returns>A task containing an `Installation`.</returns>
/// <seealso cref="T:Bit.Core.Platform.Installations.Repositories.IInstallationRepository"/>
Task<Installation> GetByIdAsync(Guid installationId);
Task<Installation?> GetByIdAsync(Guid installationId);
}
4 changes: 3 additions & 1 deletion src/Core/Platform/PlatformServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing Bit.Core.Platform.Installations;
๏ปฟ#nullable enable

using Bit.Core.Platform.Installations;
using Microsoft.Extensions.DependencyInjection;

namespace Bit.Core.Platform;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing Bit.Core.Enums;
#nullable enable

using Bit.Core.Enums;
using Bit.Core.NotificationHub;

namespace Bit.Core.Platform.Push;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing Bit.Core.Enums;
#nullable enable

using Bit.Core.Enums;
using Bit.Core.NotificationHub;

namespace Bit.Core.Platform.Push.Internal;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing Bit.Core.Enums;
๏ปฟ#nullable enable

using Bit.Core.Enums;
using Bit.Core.IdentityServer;
using Bit.Core.Models.Api;
using Bit.Core.NotificationHub;
Expand Down
2 changes: 1 addition & 1 deletion src/Core/Repositories/ICollectionRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public interface ICollectionRepository : IRepository<Collection, Guid>
Task<CollectionAdminDetails?> GetByIdWithPermissionsAsync(Guid collectionId, Guid? userId, bool includeAccessRelationships);

Task CreateAsync(Collection obj, IEnumerable<CollectionAccessSelection>? groups, IEnumerable<CollectionAccessSelection>? users);
Task ReplaceAsync(Collection obj, IEnumerable<CollectionAccessSelection> groups, IEnumerable<CollectionAccessSelection> users);
Task ReplaceAsync(Collection obj, IEnumerable<CollectionAccessSelection>? groups, IEnumerable<CollectionAccessSelection>? users);
Task DeleteUserAsync(Guid collectionId, Guid organizationUserId);
Task UpdateUsersAsync(Guid id, IEnumerable<CollectionAccessSelection> users);
Task<ICollection<CollectionAccessSelection>> GetManyUsersByIdAsync(Guid id);
Expand Down
14 changes: 8 additions & 6 deletions src/Core/Services/ILicensingService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing System.Security.Claims;
๏ปฟ#nullable enable

using System.Security.Claims;
using Bit.Core.AdminConsole.Entities;
using Bit.Core.Entities;
using Bit.Core.Models.Business;
Expand All @@ -12,14 +14,14 @@ public interface ILicensingService
Task<bool> ValidateUserPremiumAsync(User user);
bool VerifyLicense(ILicense license);
byte[] SignLicense(ILicense license);
Task<OrganizationLicense> ReadOrganizationLicenseAsync(Organization organization);
Task<OrganizationLicense> ReadOrganizationLicenseAsync(Guid organizationId);
ClaimsPrincipal GetClaimsPrincipalFromLicense(ILicense license);
Task<OrganizationLicense?> ReadOrganizationLicenseAsync(Organization organization);
Task<OrganizationLicense?> ReadOrganizationLicenseAsync(Guid organizationId);
ClaimsPrincipal? GetClaimsPrincipalFromLicense(ILicense license);

Task<string> CreateOrganizationTokenAsync(
Task<string?> CreateOrganizationTokenAsync(
Organization organization,
Guid installationId,
SubscriptionInfo subscriptionInfo);

Task<string> CreateUserTokenAsync(User user, SubscriptionInfo subscriptionInfo);
Task<string?> CreateUserTokenAsync(User user, SubscriptionInfo subscriptionInfo);
}
10 changes: 7 additions & 3 deletions src/Core/Services/IMailService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing Bit.Core.AdminConsole.Entities;
๏ปฟ#nullable enable

using Bit.Core.AdminConsole.Entities;
using Bit.Core.AdminConsole.Entities.Provider;
using Bit.Core.Auth.Entities;
using Bit.Core.Billing.Enums;
Expand Down Expand Up @@ -55,7 +57,7 @@ Task SendInvoiceUpcoming(
bool mentionInvoices);
Task SendPaymentFailedAsync(string email, decimal amount, bool mentionInvoices);
Task SendAddedCreditAsync(string email, decimal amount);
Task SendLicenseExpiredAsync(IEnumerable<string> emails, string organizationName = null);
Task SendLicenseExpiredAsync(IEnumerable<string> emails, string? organizationName = null);
Task SendNewDeviceLoggedInEmail(string email, string deviceType, DateTime timestamp, string ip);
Task SendRecoverTwoFactorEmail(string email, DateTime timestamp, string ip);
Task SendOrganizationUserRemovedForPolicySingleOrgEmailAsync(string organizationName, string email);
Expand Down Expand Up @@ -96,9 +98,11 @@ Task SendProviderUpdatePaymentMethod(
Task SendInitiateDeletProviderEmailAsync(string email, Provider provider, string token);
Task SendInitiateDeleteOrganzationEmailAsync(string email, Organization organization, string token);
Task SendRequestSMAccessToAdminEmailAsync(IEnumerable<string> adminEmails, string organizationName, string userRequestingAccess, string emailContent);
#nullable disable
Task SendFamiliesForEnterpriseRemoveSponsorshipsEmailAsync(string email, string offerAcceptanceDate, string organizationId,
string organizationName);
#nullable enable
Task SendClaimedDomainUserEmailAsync(ClaimedUserDomainClaimedEmails emailList);
Task SendDeviceApprovalRequestedNotificationEmailAsync(IEnumerable<string> adminEmails, Guid organizationId, string email, string userName);
Task SendDeviceApprovalRequestedNotificationEmailAsync(IEnumerable<string> adminEmails, Guid organizationId, string email, string? userName);
Task SendBulkSecurityTaskNotificationsAsync(Organization org, IEnumerable<UserSecurityTasksCount> securityTaskNotifications, IEnumerable<string> adminOwnerEmails);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing Amazon;
๏ปฟ#nullable enable

using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using Bit.Core.Models.Mail;
Expand All @@ -17,7 +19,7 @@ public class AmazonSesMailDeliveryService : IMailDeliveryService, IDisposable
private readonly IAmazonSimpleEmailService _client;
private readonly string _source;
private readonly string _senderTag;
private readonly string _configSetName;
private readonly string? _configSetName;

public AmazonSesMailDeliveryService(
GlobalSettings globalSettings,
Expand Down
4 changes: 3 additions & 1 deletion src/Core/Services/Implementations/AzureQueueService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing System.Text;
๏ปฟ#nullable enable

using System.Text;
using System.Text.Json;
using Azure.Storage.Queues;
using Bit.Core.Utilities;
Expand Down
8 changes: 5 additions & 3 deletions src/Core/Services/Implementations/CollectionService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
๏ปฟusing Bit.Core.Context;
๏ปฟ#nullable enable

using Bit.Core.Context;
using Bit.Core.Entities;
using Bit.Core.Exceptions;
using Bit.Core.Models.Data;
Expand Down Expand Up @@ -34,8 +36,8 @@ public CollectionService(
_currentContext = currentContext;
}

public async Task SaveAsync(Collection collection, IEnumerable<CollectionAccessSelection> groups = null,
IEnumerable<CollectionAccessSelection> users = null)
public async Task SaveAsync(Collection collection, IEnumerable<CollectionAccessSelection>? groups = null,
IEnumerable<CollectionAccessSelection>? users = null)
{
var org = await _organizationRepository.GetByIdAsync(collection.OrganizationId);
if (org == null)
Expand Down
26 changes: 16 additions & 10 deletions src/Core/Services/Implementations/HandlebarsMailService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
๏ปฟusing System.Net;
๏ปฟ#nullable enable

using System.Diagnostics;
using System.Net;
using System.Reflection;
using System.Text.Json;
using Bit.Core.AdminConsole.Entities;
Expand Down Expand Up @@ -213,6 +216,7 @@ public async Task SendNoMasterPasswordHintEmailAsync(string email)

public async Task SendOrganizationAutoscaledEmailAsync(Organization organization, int initialSeatCount, IEnumerable<string> ownerEmails)
{
Debug.Assert(organization.Seats.HasValue, "Organization is expected to have a non-null value for seats at the time of sending this email");
var message = CreateDefaultMessage($"{organization.DisplayName()} Seat Count Has Increased", ownerEmails);
var model = new OrganizationSeatsAutoscaledViewModel
{
Expand Down Expand Up @@ -286,7 +290,7 @@ MailQueueMessage CreateMessage(string email, object model)

var messageModels = orgInvitesInfo.OrgUserTokenPairs.Select(orgUserTokenPair =>
{

Debug.Assert(orgUserTokenPair.OrgUser.Email is not null);
var orgUserInviteViewModel = OrganizationUserInvitedViewModel.CreateFromInviteInfo(
orgInvitesInfo, orgUserTokenPair.OrgUser, orgUserTokenPair.Token, _globalSettings);
return CreateMessage(orgUserTokenPair.OrgUser.Email, orgUserInviteViewModel);
Expand Down Expand Up @@ -358,7 +362,7 @@ public async Task SendInitiateDeletProviderEmailAsync(string email, Provider pro
WebVaultUrl = _globalSettings.BaseServiceUri.VaultWithHash,
SiteName = _globalSettings.SiteName,
ProviderId = provider.Id,
ProviderName = CoreHelpers.SanitizeForEmail(provider.DisplayName(), false),
ProviderName = CoreHelpers.SanitizeForEmail(provider.DisplayName()!, false),
ProviderNameUrlEncoded = WebUtility.UrlEncode(provider.Name),
ProviderBillingEmail = provider.BillingEmail,
ProviderCreationDate = provider.CreationDate.ToLongDateString(),
Expand Down Expand Up @@ -448,7 +452,7 @@ public async Task SendAddedCreditAsync(string email, decimal amount)
await _mailDeliveryService.SendEmailAsync(message);
}

public async Task SendLicenseExpiredAsync(IEnumerable<string> emails, string organizationName = null)
public async Task SendLicenseExpiredAsync(IEnumerable<string> emails, string? organizationName = null)
{
var message = CreateDefaultMessage("License Expired", emails);
var model = new LicenseExpiredViewModel();
Expand Down Expand Up @@ -598,12 +602,14 @@ private static MailMessage CreateDefaultMessage(string subject, IEnumerable<stri
}

private async Task AddMessageContentAsync<T>(MailMessage message, string templateName, T model)
where T : notnull
{
message.HtmlContent = await RenderAsync($"{templateName}.html", model);
message.TextContent = await RenderAsync($"{templateName}.text", model);
}

private async Task<string> RenderAsync<T>(string templateName, T model)
private async Task<string?> RenderAsync<T>(string templateName, T model)
where T : notnull
{
await RegisterHelpersAndPartialsAsync();
if (!_templateCache.TryGetValue(templateName, out var template))
Expand All @@ -618,15 +624,15 @@ private async Task<string> RenderAsync<T>(string templateName, T model)
return template != null ? template(model) : null;
}

private async Task<string> ReadSourceAsync(string templateName)
private async Task<string?> ReadSourceAsync(string templateName)
{
var assembly = typeof(HandlebarsMailService).GetTypeInfo().Assembly;
var fullTemplateName = $"{Namespace}.{templateName}.hbs";
if (!assembly.GetManifestResourceNames().Any(f => f == fullTemplateName))
{
return null;
}
using (var s = assembly.GetManifestResourceStream(fullTemplateName))
using (var s = assembly.GetManifestResourceStream(fullTemplateName)!)
using (var sr = new StreamReader(s))
{
return await sr.ReadToEndAsync();
Expand Down Expand Up @@ -757,7 +763,7 @@ private async Task RegisterHelpersAndPartialsAsync()
var emailList = new List<string>();
if (parameters[0] is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Array)
{
emailList = jsonElement.EnumerateArray().Select(e => e.GetString()).ToList();
emailList = jsonElement.EnumerateArray().Select(e => e.GetString()!).ToList();
}
else if (parameters[0] is IEnumerable<string> emails)
{
Expand Down Expand Up @@ -1276,7 +1282,7 @@ public async Task SendFamiliesForEnterpriseRemoveSponsorshipsEmailAsync(string e
await _mailDeliveryService.SendEmailAsync(message);
}

public async Task SendDeviceApprovalRequestedNotificationEmailAsync(IEnumerable<string> adminEmails, Guid organizationId, string email, string userName)
public async Task SendDeviceApprovalRequestedNotificationEmailAsync(IEnumerable<string> adminEmails, Guid organizationId, string email, string? userName)
{
var templateName = _globalSettings.SelfHosted ?
"AdminConsole.SelfHostNotifyAdminDeviceApprovalRequested" :
Expand Down Expand Up @@ -1313,7 +1319,7 @@ MailQueueMessage CreateMessage(UserSecurityTasksCount notification)
await EnqueueMailAsync(messageModels.ToList());
}

private static string GetUserIdentifier(string email, string userName)
private static string GetUserIdentifier(string email, string? userName)
{
return string.IsNullOrEmpty(userName) ? email : CoreHelpers.SanitizeForEmail(userName, false);
}
Expand Down
7 changes: 4 additions & 3 deletions src/Core/Services/Implementations/I18nService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
๏ปฟusing System.Reflection;
๏ปฟ#nullable enable

using Bit.Core.Resources;
using Microsoft.Extensions.Localization;

Expand All @@ -10,8 +11,8 @@ public class I18nService : II18nService

public I18nService(IStringLocalizerFactory factory)
{
var assemblyName = new AssemblyName(typeof(SharedResources).GetTypeInfo().Assembly.FullName);
_localizer = factory.Create("SharedResources", assemblyName.Name);
var assemblyName = typeof(SharedResources).Assembly.GetName()!;
_localizer = factory.Create("SharedResources", assemblyName.Name!);
}

public LocalizedString GetLocalizedHtmlString(string key)
Expand Down
9 changes: 5 additions & 4 deletions src/Core/Services/Implementations/I18nViewLocalizer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
๏ปฟusing System.Reflection;
๏ปฟ#nullable enable

using Bit.Core.Resources;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Localization;
Expand All @@ -13,9 +14,9 @@ public class I18nViewLocalizer : IViewLocalizer
public I18nViewLocalizer(IStringLocalizerFactory stringFactory,
IHtmlLocalizerFactory htmlFactory)
{
var assemblyName = new AssemblyName(typeof(SharedResources).GetTypeInfo().Assembly.FullName);
_stringLocalizer = stringFactory.Create("SharedResources", assemblyName.Name);
_htmlLocalizer = htmlFactory.Create("SharedResources", assemblyName.Name);
var assemblyName = typeof(SharedResources).Assembly.GetName()!;
_stringLocalizer = stringFactory.Create("SharedResources", assemblyName.Name!);
_htmlLocalizer = htmlFactory.Create("SharedResources", assemblyName.Name!);
}

public LocalizedHtmlString this[string name] => _htmlLocalizer[name];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
๏ปฟusing System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates;
using Bit.Core.Platform.X509ChainCustomization;
using Bit.Core.Settings;
using Bit.Core.Utilities;
Expand All @@ -22,12 +22,17 @@
ILogger<MailKitSmtpMailDeliveryService> logger,
IOptions<X509ChainOptions> x509ChainOptions)
{
if (globalSettings.Mail?.Smtp?.Host == null)
if (globalSettings.Mail.Smtp?.Host == null)
{
throw new ArgumentNullException(nameof(globalSettings.Mail.Smtp.Host));
}

_replyEmail = CoreHelpers.PunyEncode(globalSettings.Mail?.ReplyToEmail);
if (globalSettings.Mail.ReplyToEmail == null)
{
throw new InvalidOperationException("A GlobalSettings.Mail.ReplyToEmail is required to be set up.");
}

_replyEmail = CoreHelpers.PunyEncode(globalSettings.Mail.ReplyToEmail);

if (_replyEmail.Contains("@"))
{
Expand Down Expand Up @@ -79,7 +84,7 @@
{
if (_globalSettings.Mail.Smtp.TrustServer)
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;

Check warning on line 87 in src/Core/Services/Implementations/MailKitSmtpMailDeliveryService.cs

View workflow job for this annotation

GitHub Actions / Quality scan

Enable server certificate validation on this SSL/TLS connection (https://rules.sonarsource.com/csharp/RSPEC-4830)
}
else if (_x509ChainOptions.TryGetCustomRemoteCertificateValidationCallback(out var callback))
{
Expand Down
Loading
Loading