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
3 changes: 3 additions & 0 deletions src/cCoder.Security.Data/Models/DTOs/ChangePasswordRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,8 @@ public class ChangePasswordRequest
{
public string OldPassword { get; set; }
public string NewPassword { get; set; }

public string ConfirmPassword { get; set; }

public string Token { get; set; }
}
4 changes: 4 additions & 0 deletions src/cCoder.Security.Data/project.stxjson
Original file line number Diff line number Diff line change
Expand Up @@ -2076,6 +2076,10 @@
"BaseType": null,
"Interfaces": [],
"Properties": [
{
"Name": "ConfirmPassword",
"Type": "System.String"
},
{
"Name": "NewPassword",
"Type": "System.String"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,119 @@ public void MeReturnsCurrentUserWithoutProtectedFields()

ssoUserProcessingServiceMock.Verify(expression: service => service.Me(), times: Times.Once);
}

[Fact]
public async Task UpdateMeChangesOnlyEditableProfileFields()
{
// Given
SSOUser storedUser = new()
{
Id = "existing.user",
DisplayName = "Old name",
Email = "old@example.com",
PhoneNumber = "0123",
PasswordHash = "stored-hash",
AccessFailedCount = 2,
EmailConfirmed = true,
LockoutEnabled = false
};

SSOUser request = new()
{
Id = "attempted.identity.change",
DisplayName = "New name",
Email = "new@example.com",
PhoneNumber = "0456",
PasswordHash = "attempted-password-change",
AccessFailedCount = 99,
LockoutEnabled = true
};

Mock<ISSOUserProcessingService> service = new(MockBehavior.Strict);

service
.Setup(expression: item => item.Me())
.Returns(value: storedUser);

service
.Setup(expression: item => item.UpdateSSOUserAsync(
item: It.IsAny<SSOUser>()))
.Returns(value: new ValueTask<SSOUser>(result: storedUser));

ICurrentUserAggregationService manager =
new CurrentUserAggregationService(
ssoUserProcessingService: service.Object,
authInfo: new SSOAuthInfo
{
SSOUserId = storedUser.Id
});

// When
SSOUser result = await manager.UpdateCurrentSSOUserAsync(
updatedUser: request);

// Then
storedUser.Id
.Should()
.Be(expected: "existing.user");

storedUser.PasswordHash
.Should()
.Be(expected: "stored-hash");

storedUser.AccessFailedCount
.Should()
.Be(expected: 2);

storedUser.LockoutEnabled
.Should()
.BeFalse();

result.DisplayName
.Should()
.Be(expected: "New name");

result.Email
.Should()
.Be(expected: "new@example.com");

result.PhoneNumber
.Should()
.Be(expected: "0456");

result.PasswordHash
.Should()
.BeNull();
}

[Fact]
public async Task UpdateMeRejectsGuestBeforeUserLookup()
{
// Given
Mock<ISSOUserProcessingService> service = new(MockBehavior.Strict);

ICurrentUserAggregationService manager =
new CurrentUserAggregationService(
ssoUserProcessingService: service.Object,
authInfo: new SSOAuthInfo
{
SSOUserId = "Guest"
});

// When
Func<Task> updateCurrentUser = async () =>
await manager.UpdateCurrentSSOUserAsync(
updatedUser: new SSOUser
{
DisplayName = "Guest",
Email = "guest@example.com"
});

// Then
await updateCurrentUser
.Should()
.ThrowAsync<SecurityAggregationAuthenticationException>();

service.VerifyNoOtherCalls();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// ---------------------------------------------------------------
// Copyright (c) Paul.Ward@ccoder.co.uk
// ---------------------------------------------------------------

using cCoder.Security.Exposures;
using cCoder.Security.Exposures.Controllers;
using cCoder.Security.Models.DTOs;
using cCoder.Security.Models.Entities;
using cCoder.Security.Models.Exceptions;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using System.Security;
using System.Security.Claims;
using Xunit;

namespace cCoder.Security.Tests;

public sealed partial class ControllerHttpComplianceTests
{
[Fact]
public async Task PostChangePassword_WhenConfirmationDiffers_ShouldReturnBadRequest()
{
// Given
(AuthenticationController controller, Mock<IAuthenticationManager> manager) =
CreateAuthenticatedPasswordController();

ChangePasswordRequest request = CreatePasswordRequest();
request.ConfirmPassword = "different-password";

// When
IActionResult result = await controller.PostChangePassword(
newChangePasswordRequest: request);

// Then
result
.Should()
.BeOfType<BadRequestObjectResult>();

manager.Verify(
expression: service => service.ChangePasswordAsync(
username: It.IsAny<string>(),
oldPassword: It.IsAny<string>(),
newPassword: It.IsAny<string>()),
times: Times.Never);
}

[Theory]
[InlineData("authentication", StatusCodes.Status401Unauthorized)]
[InlineData("validation", StatusCodes.Status400BadRequest)]
[InlineData("security", StatusCodes.Status401Unauthorized)]
[InlineData("dependency", StatusCodes.Status503ServiceUnavailable)]
[InlineData("unexpected", StatusCodes.Status500InternalServerError)]
public async Task PostChangePassword_WhenServiceFails_ShouldReturnSafeStatus(
string failure,
int expectedStatus)
{
// Given
(AuthenticationController controller, Mock<IAuthenticationManager> manager) =
CreateAuthenticatedPasswordController();

Exception exception = failure switch
{
"authentication" => new SecurityAggregationAuthenticationException(
innerException: new SecurityException()),
"validation" => new SecurityAggregationValidationException(
innerException: new ArgumentException()),
"security" => new SecurityAggregationServiceException(
innerException: new Exception(
message: "wrapped",
innerException: new SecurityException())),
"dependency" => new SecurityAggregationDependencyException(
innerException: new InvalidOperationException()),
_ => new InvalidOperationException()
};

manager
.Setup(expression: service => service.ChangePasswordAsync(
username: "current.user",
oldPassword: "old-password",
newPassword: "new-password"))
.Returns(value: ValueTask.FromException(exception: exception));

// When
IActionResult result = await controller.PostChangePassword(
newChangePasswordRequest: CreatePasswordRequest());

// Then
int actualStatus = result switch
{
ChallengeResult => StatusCodes.Status401Unauthorized,
ObjectResult objectResult => objectResult.StatusCode!.Value,
_ => throw new InvalidOperationException(
message: $"Unexpected result type {result.GetType().Name}.")
};

actualStatus.Should()
.Be(expected: expectedStatus);
}

private static (
AuthenticationController Controller,
Mock<IAuthenticationManager> Manager)
CreateAuthenticatedPasswordController()
{
Mock<IAuthenticationManager> authenticationManager = new();
Mock<ISecurityCurrentUserManager> currentUserManager = new();

currentUserManager
.Setup(expression: manager => manager.GetCurrentUser())
.Returns(value: new SSOUser { Id = "current.user" });

AuthenticationController controller = new(
authenticationAggregationService: authenticationManager.Object,
currentUserManager: currentUserManager.Object);

controller.ControllerContext.HttpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(
identity: new ClaimsIdentity(
claims: [],
authenticationType: "Test"))
};

return (controller, authenticationManager);
}

private static ChangePasswordRequest CreatePasswordRequest() =>
new()
{
ConfirmPassword = "new-password",
NewPassword = "new-password",
OldPassword = "old-password"
};
}
Loading
Loading