Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
1602116
Keep validation in FluentValidation when model projects enable nullable
Nov 25, 2026
c0ab933
Enable nullable in Grand.SharedKernel, Grand.Mediator and Grand.Mapping
Nov 25, 2026
0e631f5
Enable nullable in Grand.Domain
Nov 25, 2026
7536bf8
Enable nullable in Grand.Data
Nov 25, 2026
cb6f3dd
Enable nullable in Grand.Infrastructure
Nov 25, 2026
02b5e54
Enable nullable in Grand.Business.Core
Nov 25, 2026
cf277e4
Declare the required fields of Grand.Domain as not null
Nov 25, 2026
05e7f4e
Mark the inputs every mediator request needs as required
Nov 25, 2026
b6c431e
Enable nullable reference types in the Business service projects
Nov 25, 2026
6e117ab
Enable nullable reference types in the modules
Nov 25, 2026
4c6d2d9
Enable nullable reference types in Web.Common and Web.Models
Nov 25, 2026
ceb1924
Enable nullable reference types in Web.AdminShared
Nov 26, 2026
363a605
Enable nullable reference types in Web.Admin, Web.Store and Web.Vendor
Nov 26, 2026
20c2e7f
Enable nullable reference types in Grand.Web
Nov 26, 2026
102cb78
Build the nullable projects with nullable warnings as errors
Nov 26, 2026
3bfe630
Describe the nullable conventions in .ai/knowledge/dotnet.md
Nov 26, 2026
9a5d442
Read the work context through the optional probes where a request may…
Nov 26, 2026
996afd2
Give the sample affiliate a name
Nov 26, 2026
f97415e
Let the payment and shipping provider contracts say what plugins return
Nov 26, 2026
12ffdc4
Tidy the customer access checks that only decide access
Nov 26, 2026
f5e95ef
Web API: answer a PUT of a missing record with 404
Nov 26, 2026
1b957ef
EU VAT: give no exemption for a country that no longer exists
Nov 26, 2026
980f5c5
Downloads: an empty download URL does not use up an allowed download
Nov 26, 2026
fc8976e
Checkout: an unreadable shipping option no longer ends in a 500
Nov 26, 2026
6f618ac
Password change: report an unknown e-mail as such
Nov 26, 2026
fb5e4d2
Web API: read a PUT record once, and authorize before checking the key
Nov 26, 2026
2ec62ab
Admin panels: unwrap an access check in one line
Nov 26, 2026
d1acfeb
Write each null-flow condition once
Nov 26, 2026
d4d5f4a
Declare the references every record has as not null
Nov 27, 2026
992f89d
Test that no mapping stores null in a Domain member declared not null
Nov 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
25 changes: 20 additions & 5 deletions .ai/knowledge/dotnet.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,26 @@ switch (cartItem.ShoppingCartTypeId)

## Nullable Reference Types

The project has nullable reference types enabled. Follow these conventions:

- `string` — the property/parameter is never null; calling code must not pass null.
- `string?` — explicitly nullable; caller or callee handles null.
- Do not suppress warnings with `!` unless you are certain the value cannot be null at that point.
Nullable reference types are enabled, with nullable warnings as errors, in every project except the plugins
(`src/Plugins`) and the test projects (`src/Tests`), which come in a later step. Each enabled project sets
`<Nullable>enable</Nullable>` and `<WarningsAsErrors>nullable</WarningsAsErrors>` in its own `.csproj`; there are
no `#nullable` directives. Razor views compile under their project's setting.

- `string` — never null; calling code must not pass null.
- `string?` — may be null; the callee copes with it.
- Domain entity strings are `string?`; a field every validator requires and every creation site sets is
`string X { get; set; } = null!`. Do not use `= string.Empty` (it changes what MongoDB stores) or `required` on
entities (System.Text.Json enforces it).
- Mediator requests: a property every creation site sets is `required`. A handler that can return null declares it
in the request (`IRequest<X?>`); never annotate `IRequestHandler.Handle` itself.
- A lookup by id takes `string?` and returns `T?`. A value-or-error result is read through its value
(`x is { Outcome: Ok, User: { } user }`), not by testing the error.
- Use `[NotNullWhen]`, `[MemberNotNullWhen]` and `[NotNullIfNotNull]` to say what a check or a mapper guarantees.
`[NotNullWhen]` does nothing on `Task<bool>`: write `x == null || !await Check(x)` instead.
- A field a validator requires gets `ArgumentException.ThrowIfNullOrEmpty(model.X)` where it is used, with a comment
naming the validator.
- Do not suppress warnings: no `#pragma`, no `NoWarn`, no `<Nullable>warnings</Nullable>`. A `!` is allowed only
with a comment that names the invariant the compiler cannot see.

---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@
<ProjectReference Include="..\Grand.Business.Core\Grand.Business.Core.csproj" />
</ItemGroup>

<PropertyGroup>
<Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors>
</PropertyGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public ExternalAuthenticationService(
/// <param name="language">Working language of the request</param>
/// <returns>Result of an authentication</returns>
protected virtual async Task<ExternalAuthResult> AuthenticateExistingUser(Customer associatedUser,
Customer currentLoggedInUser, Customer customer, string storeId, Language language)
Customer? currentLoggedInUser, Customer customer, string storeId, Language language)
{
//log in guest user
if (currentLoggedInUser == null)
Expand All @@ -92,7 +92,7 @@ protected virtual async Task<ExternalAuthResult> AuthenticateExistingUser(Custom
/// <param name="storeId">Store identifier</param>
/// <param name="language">Working language of the request</param>
/// <returns>Result of an authentication</returns>
protected virtual async Task<ExternalAuthResult> AuthenticateNewUser(Customer currentLoggedInUser,
protected virtual async Task<ExternalAuthResult> AuthenticateNewUser(Customer? currentLoggedInUser,
ExternalAuthParam parameters, Customer customer, string storeId, Language language)
{
//associate external account with logged-in user
Expand Down Expand Up @@ -122,8 +122,11 @@ protected virtual async Task<ExternalAuthResult> AuthenticateNewUser(Customer cu
/// Whether another customer has the provider's e-mail as their e-mail or, with usernames enabled, as their
/// username; registration stores the provider's e-mail in both fields
/// </summary>
private async Task<bool> IsEmailOrUsernameTaken(string email, string storeId)
private async Task<bool> IsEmailOrUsernameTaken(string? email, string storeId)
{
//a provider that gives no e-mail takes nothing over; registration then asks for it
if (string.IsNullOrWhiteSpace(email))
return false;
return await _customerService.GetCustomerByEmail(email, storeId) != null ||
(_customerSettings.UsernamesEnabled &&
await _customerService.GetCustomerByUsername(email, storeId) != null);
Expand All @@ -144,9 +147,12 @@ protected virtual async Task<ExternalAuthResult> RegisterNewUser(ExternalAuthPar
_customerSettings.UserRegistrationType is UserRegistrationType.Standard
or UserRegistrationType.EmailValidation;

//Authenticate registers only with the provider's e-mail
var email = parameters.Email ?? throw new ArgumentException("The provider gave no e-mail", nameof(parameters));

//create registration request
var registrationRequest = new RegistrationRequest(customer,
parameters.Email, parameters.Email,
email, email,
CommonHelper.GenerateRandomDigitCode(20),
PasswordFormat.Hashed,
storeId,
Expand Down Expand Up @@ -214,7 +220,7 @@ public virtual IList<IExternalAuthenticationProvider> LoadActiveAuthenticationPr
/// </summary>
/// <param name="systemName">System name</param>
/// <returns>Found external authentication provider</returns>
public virtual IExternalAuthenticationProvider LoadAuthenticationProviderBySystemName(string systemName)
public virtual IExternalAuthenticationProvider? LoadAuthenticationProviderBySystemName(string? systemName)
{
return _externalAuthenticationProviders.FirstOrDefault(x =>
x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));
Expand All @@ -236,7 +242,7 @@ public virtual IList<IExternalAuthenticationProvider> LoadAllAuthenticationProvi
/// <param name="customer">Customer whose groups the provider may be limited to</param>
/// <param name="store">Store the provider may be limited to</param>
/// <returns>True if is available; otherwise false</returns>
public virtual bool AuthenticationProviderIsAvailable(string systemName, Customer customer, Store store)
public virtual bool AuthenticationProviderIsAvailable(string? systemName, Customer customer, Store store)
{
ArgumentNullException.ThrowIfNull(customer);
ArgumentNullException.ThrowIfNull(store);
Expand Down Expand Up @@ -312,13 +318,13 @@ public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam
/// </summary>
/// <param name="parameters">External authentication parameters</param>
/// <returns>Customer</returns>
public virtual async Task<Customer> GetCustomer(ExternalAuthParam parameters)
public virtual async Task<Customer?> GetCustomer(ExternalAuthParam parameters)
{
ArgumentNullException.ThrowIfNull(parameters);

var associationRecord = (from q in _externalAuthenticationRecordRepository.Table
where q.ExternalIdentifier == parameters.Identifier
&& q.ProviderSystemName.ToLowerInvariant() == parameters.ProviderSystemName.ToLowerInvariant()
&& q.ProviderSystemName != null && q.ProviderSystemName.ToLowerInvariant() == parameters.ProviderSystemName.ToLowerInvariant()
select q).FirstOrDefault();

if (associationRecord == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ public class JwtBearerAuthenticationService : IJwtBearerAuthenticationService
private readonly ICustomerService _customerService;
private readonly IUserApiService _userApiService;
private readonly OidcLoginConfig _oidcLoginConfig;
private string _email;
private string? _email;

private string _errorMessage;
private string? _errorMessage;

public JwtBearerAuthenticationService(
ICustomerService customerService, IUserApiService userApiService, OidcLoginConfig oidcLoginConfig)
Expand All @@ -28,7 +28,7 @@ public JwtBearerAuthenticationService(
/// Valid
/// </summary>
/// <param name="principal">Principal of the validated token</param>
public virtual async Task<bool> Valid(ClaimsPrincipal principal)
public virtual async Task<bool> Valid(ClaimsPrincipal? principal)
{
if (principal == null) return await Task.FromResult(false);

Expand Down Expand Up @@ -76,7 +76,7 @@ public virtual async Task<bool> Valid(ClaimsPrincipal principal)
/// Get error message
/// </summary>
/// <returns></returns>
public virtual Task<string> ErrorMessage()
public virtual Task<string?> ErrorMessage()
{
return Task.FromResult(_errorMessage);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class JwtBearerCustomerAuthenticationService : IJwtBearerCustomerAuthenti
private readonly IRefreshTokenService _refreshTokenService;
private readonly IExternalSignInPolicy _externalSignInPolicy;
private readonly OidcLoginConfig _oidcLoginConfig;
private string _errorMessage;
private string? _errorMessage;

public JwtBearerCustomerAuthenticationService(ICustomerService customerService,
IPermissionService permissionService, IGroupService groupService, IRefreshTokenService refreshTokenService,
Expand All @@ -32,14 +32,14 @@ public JwtBearerCustomerAuthenticationService(ICustomerService customerService,
_oidcLoginConfig = oidcLoginConfig;
}

public async Task<bool> Valid(ClaimsPrincipal principal)
public async Task<bool> Valid(ClaimsPrincipal? principal)
{
if (principal == null) return false;
var customerId = principal.Claims.FirstOrDefault(x => x.Type == "CustomerId")?.Value;
var email = principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value;
var passwordToken = principal.Claims.FirstOrDefault(x => x.Type == "Token")?.Value;
var refreshId = principal.Claims.FirstOrDefault(x => x.Type == "RefreshId")?.Value;
Customer customer = null;
Customer? customer = null;
if (!string.IsNullOrEmpty(customerId))
{
//prefer the stable customer id - unambiguous with per-store identity
Expand Down Expand Up @@ -101,7 +101,7 @@ public async Task<bool> Valid(ClaimsPrincipal principal)
}


public Task<string> ErrorMessage()
public Task<string?> ErrorMessage()
{
return Task.FromResult(_errorMessage);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ public virtual async Task<OidcCustomerResult> Resolve(ClaimsPrincipal principal,
//a link made by e-mail proves no more than the e-mail: it stops serving an account that has since
//become one that connects only with its password
if (linkedResult.Succeeded && link.LinkedByEmail && !_loginConfig.ProviderOnly &&
await RequiresPassword(linkedCustomer, storeId))
return AccountConnectionRequired(linkedCustomer, sub);
await RequiresPassword(linkedResult.Customer, storeId))
return AccountConnectionRequired(linkedResult.Customer, sub);
return linkedResult;
}

Expand Down Expand Up @@ -159,8 +159,9 @@ public virtual async Task<OidcLoginResult> ResolveForLogin(string sub, string em
if (link != null)
{
var linked = await _customerService.GetCustomerById(link.CustomerId);
//Check answers Missing for no customer
var reason = await Check(linked, sub, storeId);
if (reason != Unusable.None)
if (linked == null || reason != Unusable.None)
return OidcLoginResult.Refused(ToRefusal(reason));

//a link made by e-mail (by an access token or an earlier sign-in) is held to the rules of a first link;
Expand Down Expand Up @@ -281,9 +282,10 @@ private async Task<OidcCustomerResult> Register(string sub, string email, string
var (outcome, customer, winner) = await CreateLinkedAccount(sub, email, storeId, null);
return outcome switch {
Provisioning.UserNameTaken => OidcCustomerResult.Forbidden("The user name is already taken"),
Provisioning.LinkedToOtherIdentity => LinkedToOtherIdentity(customer, sub),
Provisioning.LinkedToOtherIdentity when customer != null => LinkedToOtherIdentity(customer, sub),
Provisioning.LostRace => await Usable(winner, sub, storeId),
_ => OidcCustomerResult.Success(customer)
Provisioning.Created when customer != null => OidcCustomerResult.Success(customer),
_ => OidcCustomerResult.Forbidden("The customer account could not be created")
};
}

Expand All @@ -300,7 +302,8 @@ private async Task<OidcLoginResult> ProvisionForLogin(string sub, string email,
Provisioning.LinkedToOtherIdentity => OidcLoginResult.Refused(OidcLoginRefusal.LinkedToOtherIdentity),
//another request of the same user created the account first: its link answers now
Provisioning.LostRace => await ResolveForLogin(sub, email, emailVerified, storeId, language),
_ => OidcLoginResult.SignIn(customer)
Provisioning.Created when customer != null => OidcLoginResult.SignIn(customer),
_ => OidcLoginResult.Refused(OidcLoginRefusal.AccountUnusable)
};
}

Expand All @@ -316,8 +319,8 @@ private enum Provisioning
/// Creates an active account with the Registered group for the subject and links it (not by e-mail). The store's
/// e-mail validation / admin approval does not apply: access comes from the provider and from permissions an admin grants
/// </summary>
private async Task<(Provisioning Outcome, Customer Customer, Customer Winner)> CreateLinkedAccount(string sub,
string email, string storeId, Language language)
private async Task<(Provisioning Outcome, Customer? Customer, Customer? Winner)> CreateLinkedAccount(string sub,
string email, string storeId, Language? language)
{
//the e-mail becomes the user name - another account may hold it as its user name without that e-mail
var normalizedEmail = email.ToLowerInvariant();
Expand Down Expand Up @@ -361,7 +364,7 @@ await _customerManagerService.RegisterCustomer(new RegistrationRequest(customer,
/// subject from linking this store's customer; without per-store identity: any link.
/// Subjects are case-sensitive - exact comparison.
/// </summary>
private async Task<ExternalAuthentication> GetLink(string sub, string storeId)
private async Task<ExternalAuthentication?> GetLink(string sub, string storeId)
{
if (!_customerConfig.RegisterCustomersPerStore)
return await _externalAuthenticationRepository.GetOneAsync(x =>
Expand Down Expand Up @@ -414,7 +417,7 @@ private OidcCustomerResult AccountConnectionRequired(Customer customer, string s
/// first: the link of another subject now holding this customer (OtherLink), or the customer the subject's
/// winning link points to (Customer). Rethrows when the insert failed for another reason.
/// </summary>
private async Task<(Customer Customer, ExternalAuthentication OtherLink)> LinkOrGetWinner(Customer customer,
private async Task<(Customer? Customer, ExternalAuthentication? OtherLink)> LinkOrGetWinner(Customer customer,
string sub, string email, string storeId, bool byEmail)
{
var linkId = OidcLinkId(customer.Id);
Expand Down Expand Up @@ -468,7 +471,7 @@ private enum Unusable { None, Missing, Inactive, Unusable, OtherStore }

//the checks every other login path applies: an active, registered, non-system account, and with per-store
//identity one of the request's store (or of no store)
private async Task<Unusable> Check(Customer customer, string sub, string storeId)
private async Task<Unusable> Check(Customer? customer, string sub, string storeId)
{
if (customer == null)
{
Expand Down Expand Up @@ -498,8 +501,10 @@ private async Task<Unusable> Check(Customer customer, string sub, string storeId
return Unusable.None;
}

private async Task<OidcCustomerResult> Usable(Customer customer, string sub, string storeId) =>
private async Task<OidcCustomerResult> Usable(Customer? customer, string sub, string storeId) =>
await Check(customer, sub, storeId) switch {
//Check answers Missing for no customer
_ when customer == null => OidcCustomerResult.Forbidden("The customer account no longer exists"),
Unusable.None => OidcCustomerResult.Success(customer),
Unusable.Missing => OidcCustomerResult.Forbidden("The customer account no longer exists"),
Unusable.Inactive => OidcCustomerResult.Forbidden("The customer account is inactive"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ private IQueryable<ExternalAuthentication> OidcLinks() =>

private Task<bool> HasLinks() => externalAuthenticationRepository.AnyAsync(OidcLinks());

private void LogMismatch(string linkedAuthority)
private void LogMismatch(string? linkedAuthority)
{
var now = DateTime.UtcNow.Ticks;
var last = Interlocked.Read(ref _lastMismatchLogTicks);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public OidcSessionService(
_logger = logger;
}

public virtual async Task<string> Start(Customer customer, string subject, string sid, string refreshToken, string storeId)
public virtual async Task<string?> Start(Customer customer, string subject, string? sid, string? refreshToken, string storeId)
{
ArgumentNullException.ThrowIfNull(customer);
ArgumentException.ThrowIfNullOrEmpty(subject);
Expand Down Expand Up @@ -252,7 +252,7 @@ await _sessionRepository.UpdateOneAsync(x => x.Id == sessionId && x.EndedUtc ==
_logger.LogInformation("OpenID Connect session {SessionId} ended: {Reason}", sessionId, reason);
}

public virtual async Task<IList<OidcSession>> EndBySid(string subject, string sid)
public virtual async Task<IList<OidcSession>> EndBySid(string? subject, string sid)
{
ArgumentException.ThrowIfNullOrEmpty(sid);
var query = _sessionRepository.Table.Where(x => x.Sid == sid && x.EndedUtc == null);
Expand Down Expand Up @@ -314,12 +314,15 @@ private async Task<IList<OidcSession>> EndAll(IList<OidcSession> sessions,
return sessions;
}

private Task<OidcSession> Get(string sessionId) =>
private Task<OidcSession?> Get(string sessionId) =>
_cache.GetAsync(string.Format(CacheKey.OIDC_SESSION_BY_ID_KEY, sessionId),
() => _sessionRepository.GetByIdAsync(sessionId), CacheTimeMinutes);

private string Unprotect(string protectedToken)
private string? Unprotect(string? protectedToken)
{
//a session stored without a refresh token has none to refresh with
if (protectedToken == null)
return null;
try
{
return _protector.Unprotect(protectedToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Grand.Business.Authentication.Services;
/// </summary>
public static class OidcSignInModeCheck
{
public static string Problem(OidcLoginConfig config, OidcResourceServerConfig resourceServer)
public static string? Problem(OidcLoginConfig config, OidcResourceServerConfig resourceServer)
{
if (config is not { ProviderOnly: true })
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class OidcSsoSignInPolicy(
{
private const string UnavailableLogKey = "Grand.OidcSignInMode.Unavailable";

private async Task<IExternalAuthenticationProvider> RequiredProvider(Customer customer)
private async Task<IExternalAuthenticationProvider?> RequiredProvider(Customer customer)
{
if (customer == null || !config.SsoOnly)
return null;
Expand Down Expand Up @@ -66,7 +66,7 @@ public async Task<PasswordSignInDecision> PasswordSignIn(Customer customer, Sign
return new PasswordSignInDecision(false, provider);
}

private IExternalAuthenticationProvider AvailableProvider()
private IExternalAuthenticationProvider? AvailableProvider()
{
if (!config.IsConfigured(resourceServerConfig))
return null;
Expand Down
Loading
Loading