Skip to content

Commit

Permalink
fix: warnings [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
brunobritodev committed Apr 17, 2022
1 parent d700e6a commit 7b0c06f
Show file tree
Hide file tree
Showing 10 changed files with 38 additions and 34 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public Task Store(KeyMaterial securityParamteres)



public async Task<KeyMaterial?> GetCurrent()
public async Task<KeyMaterial> GetCurrent()
{
if (!_memoryCache.TryGetValue(JwkContants.CurrentJwkCache, out KeyMaterial keyMaterial))
{
Expand Down Expand Up @@ -123,7 +123,7 @@ private IReadOnlyCollection<KeyMaterial> GetKeys()
// IXmlRepository doesn't allow us to update. So remove from Get to prevent errors
if (key.IsExpired(_options.Value.DaysUntilExpire))
{
Revoke(key);
Revoke(key).Wait();
revokedKeys.Add(key.Id.ToString());
}

Expand Down Expand Up @@ -166,7 +166,7 @@ public Task<ReadOnlyCollection<KeyMaterial>> GetLastKeys(int quantity = 5)
.AsReadOnly());
}

public Task<KeyMaterial>? Get(string keyId)
public Task<KeyMaterial> Get(string keyId)
{
var keys = GetKeys();
return Task.FromResult(keys.FirstOrDefault(f => f.KeyId == keyId));
Expand All @@ -181,7 +181,7 @@ public async Task Clear()
}


public async Task Revoke(KeyMaterial? keyMaterial)
public async Task Revoke(KeyMaterial keyMaterial)
{
if(keyMaterial == null)
return;
Expand Down Expand Up @@ -235,6 +235,7 @@ internal IXmlRepository GetFallbackKeyRepositoryEncryptorPair()
}
else
{
#pragma warning disable CA1416
RegistryKey registryKey = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
registryKey = RegistryXmlRepository.DefaultRegistryKey;
Expand All @@ -249,6 +250,7 @@ internal IXmlRepository GetFallbackKeyRepositoryEncryptorPair()
throw new Exception(
"Is not possible to determine which folder are the protection keys. NetDevPack.Security.JwtSigningCredentials.Store.FileSystem or NetDevPack.Security.JwtSigningCredentials.Store.EntityFrameworkCore");
}
#pragma warning restore CA1416
}
}
return key;
Expand Down
18 changes: 9 additions & 9 deletions src/NetDevPack.Security.Jwt.Core/DefaultStore/InMemoryStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,23 @@ namespace NetDevPack.Security.Jwt.Core.DefaultStore;
internal class InMemoryStore : IJsonWebKeyStore
{

private static List<KeyMaterial> _store = new();
private SemaphoreSlim Slim = new(1);
private static readonly List<KeyMaterial> _store = new();
private readonly SemaphoreSlim _slim = new(1);
public Task Store(KeyMaterial keyMaterial)
{
Slim.Wait();
_slim.Wait();
_store.Add(keyMaterial);
Slim.Release();
_slim.Release();

return Task.CompletedTask;
}

public Task<KeyMaterial?> GetCurrent()
public Task<KeyMaterial> GetCurrent()
{
return Task.FromResult(_store.OrderByDescending(s => s.CreationDate).FirstOrDefault());
}

public async Task Revoke(KeyMaterial? keyMaterial)
public async Task Revoke(KeyMaterial keyMaterial)
{
if(keyMaterial == null)
return;
Expand All @@ -33,10 +33,10 @@ public async Task Revoke(KeyMaterial? keyMaterial)
if (oldOne != null)
{
var index = _store.FindIndex(f => f.Id == keyMaterial.Id);
await Slim.WaitAsync();
await _slim.WaitAsync();
_store.RemoveAt(index);
_store.Insert(index, keyMaterial);
Slim.Release();
_slim.Release();
}
}

Expand All @@ -48,7 +48,7 @@ public Task<ReadOnlyCollection<KeyMaterial>> GetLastKeys(int quantity)
.Take(quantity).ToList().AsReadOnly());
}

public Task<KeyMaterial>? Get(string keyId)
public Task<KeyMaterial> Get(string keyId)
{
return Task.FromResult(_store.FirstOrDefault(w => w.KeyId == keyId));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ namespace NetDevPack.Security.Jwt.Core.Interfaces;
public interface IJsonWebKeyStore
{
Task Store(KeyMaterial keyMaterial);
Task<KeyMaterial?> GetCurrent();
Task Revoke(KeyMaterial? keyMaterial);
Task<KeyMaterial> GetCurrent();
Task Revoke(KeyMaterial keyMaterial);
Task<ReadOnlyCollection<KeyMaterial>> GetLastKeys(int quantity);
Task<KeyMaterial?> Get(string keyId);
Task<KeyMaterial> Get(string keyId);
Task Clear();
}
6 changes: 3 additions & 3 deletions src/NetDevPack.Security.Jwt.Core/Jwa/Algorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ private Algorithm()
public CryptographyType CryptographyType { get; internal set; }
public JwtType JwtType => CryptographyType == CryptographyType.Encryption ? JwtType.Jwe : JwtType.Jws;
public string Alg { get; internal set; }
public string? Curve { get; set; }
public string Curve { get; set; }


public Algorithm WithCurve(string curve)
Expand Down Expand Up @@ -129,14 +129,14 @@ public static Algorithm Create(AlgorithmType algorithmType, JwtType jwtType)
AlgorithmType.RSA => new Algorithm(DigitalSignaturesAlgorithm.RsaSsaPssSha256),
AlgorithmType.ECDsa => new Algorithm(DigitalSignaturesAlgorithm.EcdsaSha256).WithCurve(JsonWebKeyECTypes.P256),
AlgorithmType.HMAC => new Algorithm(DigitalSignaturesAlgorithm.HmacSha256),
_ => throw new InvalidOperationException($"Invalid algorithm for Json Web Signature (JWS): {algorithmType.ToString()}")
_ => throw new InvalidOperationException($"Invalid algorithm for Json Web Signature (JWS): {algorithmType}")
};

return algorithmType switch
{
AlgorithmType.RSA => new Algorithm(EncryptionAlgorithmKey.RsaOAEP).WithContentEncryption(EncryptionAlgorithmContent.Aes128CbcHmacSha256),
AlgorithmType.AES => new Algorithm(EncryptionAlgorithmKey.Aes128KW).WithContentEncryption(EncryptionAlgorithmContent.Aes128CbcHmacSha256),
_ => throw new InvalidOperationException($"Invalid algorithm for Json Web Encryption (JWE): {algorithmType.ToString()}")
_ => throw new InvalidOperationException($"Invalid algorithm for Json Web Encryption (JWE): {algorithmType}")
};
}

Expand Down
2 changes: 1 addition & 1 deletion src/NetDevPack.Security.Jwt.Core/Jwt/JwtService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ private async Task<bool> CheckCompatibility(KeyMaterial currentKey)
return true;
}

private bool NeedsUpdate(KeyMaterial? current)
private bool NeedsUpdate(KeyMaterial current)
{
return current == null || current.IsExpired(_options.Value.DaysUntilExpire);
}
Expand Down
Binary file not shown.
10 changes: 5 additions & 5 deletions src/NetDevPack.Security.Jwt.Store.FileSystem/FileSystemStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public async Task Revoke(KeyMaterial? securityKeyWithPrivate)
foreach (var fileInfo in KeysPath.GetFiles("*.key"))
{
var key = GetKey(fileInfo.FullName);
if (key.Id != securityKeyWithPrivate.Id) continue;
await File.WriteAllTextAsync(fileInfo.FullName, JsonSerializer.Serialize(securityKeyWithPrivate, new JsonSerializerOptions() { IgnoreNullValues = true }));
if (key.Id != securityKeyWithPrivate?.Id) continue;
await File.WriteAllTextAsync(fileInfo.FullName, JsonSerializer.Serialize(securityKeyWithPrivate, new JsonSerializerOptions() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }));
break;
}
ClearCache();
Expand All @@ -88,7 +88,7 @@ private KeyMaterial GetKey(string file)
{
if (!File.Exists(file)) throw new FileNotFoundException("Check configuration - cannot find auth key file: " + file);
var keyParams = JsonSerializer.Deserialize<KeyMaterial>(File.ReadAllText(file));
return keyParams;
return keyParams!;

}

Expand Down Expand Up @@ -117,9 +117,9 @@ public Task<ReadOnlyCollection<KeyMaterial>> GetLastKeys(int quantity = 5)
{
var files = Directory.GetFiles(KeysPath.FullName, $"*{keyId}*.key");
if (files.Any())
return Task.FromResult(GetKey(files.First()));
return Task.FromResult(GetKey(files.First()))!;

return Task.FromResult((KeyMaterial)null);
return Task.FromResult(null as KeyMaterial);
}

public Task Clear()
Expand Down
2 changes: 2 additions & 0 deletions tests/NetDevPack.Security.Jwt.Tests/AspNetGeneralContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ namespace NetDevPack.Security.Jwt.Tests
{
public class AspNetGeneralContext : DbContext, IDataProtectionKeyContext, ISecurityKeyContext
{
#pragma warning disable CS8618
public AspNetGeneralContext(DbContextOptions<AspNetGeneralContext> options)
#pragma warning restore CS8618
: base(options) { }

public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public async Task ShouldNotThrowExceptionWhenGetSignManyTimes()
Issuer = "test.jwt",
Subject = new ClaimsIdentity(),
Expires = DateTime.UtcNow.AddMinutes(3),
SigningCredentials = new SigningCredentials(currentD.GetSecurityKey(), _options.Value.Jws)
SigningCredentials = new SigningCredentials(currentD?.GetSecurityKey(), _options.Value.Jws)
};
}

Expand Down Expand Up @@ -84,7 +84,7 @@ public async Task Should_Remove_Private_Key_And_Update(string algorithm)
await _store.Revoke(keyMaterial);

var current = await _store.Get(keyMaterial.KeyId);
current.GetSecurityKey().HasPrivateKey.Should().BeFalse();
current?.GetSecurityKey().HasPrivateKey.Should().BeFalse();
}


Expand Down Expand Up @@ -156,9 +156,9 @@ public async Task Should_Remove_Private_Key_After_Update_A_Expired_Jwk(string al
await _store.Revoke(keyMaterial);

var keyDb = (await _store.GetLastKeys(5)).FirstOrDefault(w => w.KeyId == keyMaterial.KeyId);
var jsonWebKey = keyDb.GetSecurityKey();
var jsonWebKey = keyDb?.GetSecurityKey();

jsonWebKey.Kty.Should().NotBeNullOrEmpty();
jsonWebKey!.Kty.Should().NotBeNullOrEmpty();
jsonWebKey.HasPrivateKey.Should().BeFalse();
switch (jsonWebKey.Kty)
{
Expand Down Expand Up @@ -255,7 +255,7 @@ public async Task Should_Save_Crypto_And_Recover(string algorithm)
(await _store.GetLastKeys(5)).Count.Should().BePositive();

var currentKey = await _store.GetCurrent();
newKey.KeyId.Should().Be(currentKey.KeyId);
newKey?.KeyId.Should().Be(currentKey?.KeyId);
}


Expand All @@ -278,7 +278,7 @@ public async Task Should_Save_Probabilistic_Jwk_Recover_And_Signing(string algor
// recovered from database
var currentKey = await _store.GetCurrent();

newKey.KeyId.Should().Be(currentKey.KeyId);
newKey.KeyId.Should().Be(currentKey?.KeyId);
var claims = new ClaimsIdentity(GenerateClaim().Generate(5));
var descriptor = new SecurityTokenDescriptor
{
Expand Down Expand Up @@ -331,7 +331,7 @@ public async Task ShouldSaveDeterministicJwkRecoverAndSigning(string algorithm)
// recovered from database
var currentKey = await _store.GetCurrent();

newKey.Key.KeyId.Should().Be(currentKey.KeyId);
newKey.Key.KeyId.Should().Be(currentKey?.KeyId);

var claims = new ClaimsIdentity(GenerateClaim().Generate(5));
var descriptor = new SecurityTokenDescriptor
Expand Down Expand Up @@ -388,7 +388,7 @@ public async Task ShouldSaveJweRecoverAndEncrypt(string algorithm, string encryp
var currentKey = await _store.Get(newKey.KeyId);


newKey.KeyId.Should().Be(currentKey.KeyId);
newKey.KeyId.Should().Be(currentKey?.KeyId);
var claims = new ClaimsIdentity(GenerateClaim().Generate(5));
var descriptor = new SecurityTokenDescriptor
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void DetachAll()
{

var database = Services.GetService<AspNetGeneralContext>();
foreach (var dbEntityEntry in database.ChangeTracker.Entries())
foreach (var dbEntityEntry in database!.ChangeTracker.Entries())
{
if (dbEntityEntry.Entity != null)
{
Expand Down

0 comments on commit 7b0c06f

Please sign in to comment.