1
0
mirror of https://github.com/bitwarden/server synced 2025-12-06 00:03:34 +00:00

[PM-22739] Add ClaimsPrincipal Extension

feat: add ClaimsPrincipal Extension
test: add tests
This commit is contained in:
Ike
2025-08-15 10:06:40 -04:00
committed by GitHub
parent 41f82bb357
commit 8a36d96e56
2 changed files with 76 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
using System.Security.Claims;
using Bit.Core.Identity;
namespace Bit.Core.Auth.UserFeatures.SendAccess;
public static class SendAccessClaimsPrincipalExtensions
{
public static Guid GetSendId(this ClaimsPrincipal user)
{
ArgumentNullException.ThrowIfNull(user);
var sendIdClaim = user.FindFirst(Claims.SendId)
?? throw new InvalidOperationException("Send ID claim not found.");
if (!Guid.TryParse(sendIdClaim.Value, out var sendGuid))
{
throw new InvalidOperationException("Invalid Send ID claim value.");
}
return sendGuid;
}
}

View File

@@ -0,0 +1,54 @@
using System.Security.Claims;
using Bit.Core.Auth.UserFeatures.SendAccess;
using Bit.Core.Identity;
using Xunit;
namespace Bit.Core.Test.Auth.UserFeatures.SendAccess;
public class SendAccessClaimsPrincipalExtensionsTests
{
[Fact]
public void GetSendId_ReturnsGuid_WhenClaimIsPresentAndValid()
{
// Arrange
var guid = Guid.NewGuid();
var claims = new[] { new Claim(Claims.SendId, guid.ToString()) };
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));
// Act
var result = principal.GetSendId();
// Assert
Assert.Equal(guid, result);
}
[Fact]
public void GetSendId_ThrowsInvalidOperationException_WhenClaimIsMissing()
{
// Arrange
var principal = new ClaimsPrincipal(new ClaimsIdentity());
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => principal.GetSendId());
Assert.Equal("Send ID claim not found.", ex.Message);
}
[Fact]
public void GetSendId_ThrowsInvalidOperationException_WhenClaimValueIsInvalid()
{
// Arrange
var claims = new[] { new Claim(Claims.SendId, "not-a-guid") };
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => principal.GetSendId());
Assert.Equal("Invalid Send ID claim value.", ex.Message);
}
[Fact]
public void GetSendId_ThrowsArgumentNullException_WhenPrincipalIsNull()
{
// Act & Assert
Assert.Throws<ArgumentNullException>(() => SendAccessClaimsPrincipalExtensions.GetSendId(null));
}
}