Still working on getting client credential flow complete, most of the request works but still working on generating the JWT.

This commit is contained in:
eelke 2026-03-16 19:15:04 +01:00
parent 1a8c63808a
commit 8782ef39c6
80 changed files with 1331 additions and 414 deletions

View file

@ -1,5 +1,7 @@
using System.Security.Cryptography;
using FluentValidation;
using IdentityShroud.Core.Contracts;
using IdentityShroud.Core.EFCore;
using IdentityShroud.Core.Model;
using Microsoft.EntityFrameworkCore;
@ -8,24 +10,35 @@ namespace IdentityShroud.Core.Services;
public class ClientService(
Db db,
IDataEncryptionService cryptor,
IValidator<ClientCreateRequest> clientCreateValidator,
IClock clock) : IClientService
{
public async Task<Result<Client>> Create(Guid realmId, ClientCreateRequest request, CancellationToken ct = default)
{
clientCreateValidator.ValidateAndThrow(request);
Realm realm = await db.Realms.FirstOrDefaultAsync(e => e.Id == realmId, ct)
?? throw new InvalidOperationException("Require the id of an existing realm");
Client client = new()
{
RealmId = realmId,
ClientId = request.ClientId,
Name = request.Name,
Description = request.Description,
SignatureAlgorithm = request.SignatureAlgorithm,
AllowClientCredentialsFlow = request.AllowClientCredentialsFlow ?? false,
SignatureAlgorithm = request.SignatureAlgorithm is null ? null : new(request.SignatureAlgorithm),
Confidential = request.Confidential,
AllowClientCredentialsFlow = request.AllowClientCredentialsFlow,
CreatedAt = clock.UtcNow(),
};
if (client.AllowClientCredentialsFlow)
if (request.GenerateSecret is true)
{
client.Secrets.Add(CreateSecret());
await db.Entry(realm).Collection(r => r.DataEncryptionKeys)
.Query()
.LoadAsync(ct);
client.Secrets.Add(CreateSecret(realm));
}
await db.AddAsync(client, ct);
@ -50,15 +63,17 @@ public class ClientService(
return await db.Clients.FirstOrDefaultAsync(c => c.Id == id && c.RealmId == realmId, ct);
}
private ClientSecret CreateSecret()
private ClientSecret CreateSecret(Realm realm)
{
Span<byte> secret = stackalloc byte[24];
RandomNumberGenerator.Fill(secret);
var dek = realm.DataEncryptionKeys.Single(k => k.Active);
return new ClientSecret()
{
CreatedAt = clock.UtcNow(),
Secret = cryptor.Encrypt(secret.ToArray()),
Secret = cryptor.Encrypt(dek, secret),
};
}

View file

@ -5,37 +5,23 @@ using IdentityShroud.Core.Security;
namespace IdentityShroud.Core.Services;
public class DataEncryptionService(
IRealmContext realmContext,
IDekEncryptionService dekCryptor) : IDataEncryptionService
{
// Note this array is expected to have one item in it most of the during key rotation it will have two
// until it is ensured the old key can safely be removed. More then two will work but is not really expected.
private IList<RealmDek>? _deks = null;
private IList<RealmDek> GetDeks()
public EncryptedValue Encrypt(RealmDek dek, ReadOnlySpan<byte> plain)
{
if (_deks is null)
_deks = realmContext.GetDeks().Result;
return _deks;
}
private RealmDek GetActiveDek() => GetDeks().Single(d => d.Active);
private RealmDek GetKey(DekId id) => GetDeks().Single(d => d.Id == id);
public byte[] Decrypt(EncryptedValue input)
{
var dek = GetKey(input.DekId);
var key = dekCryptor.Decrypt(dek.KeyData);
return Encryption.Decrypt(input.Value, key);
}
public EncryptedValue Encrypt(ReadOnlySpan<byte> plain)
{
var dek = GetActiveDek();
var key = dekCryptor.Decrypt(dek.KeyData);
byte[] cipher = Encryption.Encrypt(plain, key);
return new (dek.Id, cipher);
}
public byte[] Decrypt(IReadOnlyList<RealmDek> deks, EncryptedValue input)
{
// Note a missing key SHOULD not happen. If it does happen something has seriously gone wrong like
// - Old key removed before migration completed (should not be possible)
// - Wrong keyset because of programming error.
var dek = deks.SingleOrDefault(d => d.Id == input.DekId)
?? throw new InvalidOperationException("Required key not found");
var key = dekCryptor.Decrypt(dek.KeyData);
return Encryption.Decrypt(input.Value, key);
}
}

View file

@ -1,46 +1,16 @@
using IdentityShroud.Core.Contracts;
using IdentityShroud.Core.Messages;
using IdentityShroud.Core.Model;
using IdentityShroud.Core.Security.Keys;
namespace IdentityShroud.Core.Services;
public class KeyService(
IDekEncryptionService cryptor,
IKeyProviderFactory keyProviderFactory,
IClock clock) : IKeyService
IKeyProviderFactory keyProviderFactory) : IKeyService
{
public RealmKey CreateKey(KeyPolicy policy)
public CreateKeyResponse CreateKey(KeyPolicy policy)
{
IKeyProvider provider = keyProviderFactory.CreateProvider(policy.KeyType);
var plainKey = provider.CreateKey(policy);
KeyData plainKey = provider.CreateKey(policy);
return CreateKey(policy.KeyType, plainKey);
return new CreateKeyResponse(policy.KeyType, plainKey);
}
public JsonWebKey? CreateJsonWebKey(RealmKey realmKey)
{
JsonWebKey jwk = new()
{
KeyId = realmKey.Id.ToString(),
KeyType = realmKey.KeyType,
Use = "sig",
};
IKeyProvider provider = keyProviderFactory.CreateProvider(realmKey.KeyType);
provider.SetJwkParameters(
cryptor.Decrypt(realmKey.Key),
jwk);
return jwk;
}
private RealmKey CreateKey(string keyType, byte[] plainKey) =>
new RealmKey()
{
Id = Guid.NewGuid(),
KeyType = keyType,
Key = cryptor.Encrypt(plainKey),
CreatedAt = clock.UtcNow(),
};
}

View file

@ -0,0 +1,30 @@
namespace IdentityShroud.Core.Services.OpenId;
public interface ITokenService
{
Task<Result<TokenResponse>> Handle(
Dictionary<string, string> form,
string? basicAuthUser,
string? basicAuthPassword,
CancellationToken ct = default);
}
public class TokenService : ITokenService
{
public async Task<Result<TokenResponse>> Handle(
Dictionary<string, string> form,
string? basicAuthUser,
string? basicAuthPassword,
CancellationToken ct = default)
{
return new();
}
public async Task<Result<TokenResponse>> ClientCredentialsFlow(
string clientId,
string clientSecret,
CancellationToken ct = default)
{
return new();
}
}

View file

@ -16,11 +16,11 @@ public class RealmContext(
public async Task<IList<RealmDek>> GetDeks(CancellationToken ct = default)
{
Realm realm = GetRealm();
if (realm.Deks.Count == 0)
if (realm.DataEncryptionKeys.Count == 0)
{
await realmService.LoadDeks(realm);
}
return realm.Deks;
return realm.DataEncryptionKeys;
}
}

View file

@ -1,18 +1,21 @@
using IdentityShroud.Core.Contracts;
using IdentityShroud.Core.EFCore;
using IdentityShroud.Core.Helpers;
using IdentityShroud.Core.Messages.Realm;
using IdentityShroud.Core.Model;
using IdentityShroud.Core.Security;
using IdentityShroud.Core.Security.Keys;
using IdentityShroud.Core.Security.Keys.Aes;
using IdentityShroud.Core.Security.Keys.Rsa;
using Microsoft.EntityFrameworkCore;
namespace IdentityShroud.Core.Services;
public record RealmCreateResponse(Guid Id, string Slug, string Name);
public class RealmService(
Db db,
IKeyService keyService) : IRealmService
IKeyService keyService,
IDekEncryptionService dekCryptor,
IClock clock) : IRealmService
{
public async Task<Realm?> FindById(Guid id, CancellationToken ct = default)
{
@ -26,7 +29,7 @@ public class RealmService(
.SingleOrDefaultAsync(r => r.Slug == slug, ct);
}
public async Task<Result<RealmCreateResponse>> Create(RealmCreateRequest request, CancellationToken ct = default)
public async Task<Result<Realm>> Create(RealmCreateRequest request, CancellationToken ct = default)
{
Realm realm = new()
{
@ -35,26 +38,52 @@ public class RealmService(
Name = request.Name,
};
realm.Keys.Add(keyService.CreateKey(GetKeyPolicy(realm)));
realm.TokenSigningKeys.Add(CreateSigningKey(realm));
realm.DataEncryptionKeys.Add(CreateDataEncryptionKey(realm));
db.Add(realm);
await db.SaveChangesAsync(ct);
return new RealmCreateResponse(
realm.Id, realm.Slug, realm.Name);
return realm;
}
private RealmSigningKey CreateSigningKey(Realm realm)
{
var k = keyService.CreateKey(GetSigningKeyPolicy(realm));
return new RealmSigningKey
{
Id = RealmSigningKeyId.NewId(),
KeyType = k.KeyType,
Key = dekCryptor.Encrypt(k.Key.PrivateKey),
PublicKeyParameters = k.Key.PublicKeyParameters,
CreatedAt = clock.UtcNow(),
};
}
private RealmDek CreateDataEncryptionKey(Realm realm)
{
var k = keyService.CreateKey(GetDataKeyPolicy(realm));
return new RealmDek()
{
Id = DekId.NewId(),
Active = true,
Algorithm = k.KeyType,
KeyData = dekCryptor.Encrypt(k.Key.PrivateKey),
};
}
/// <summary>
/// Place holder for getting policies from the realm and falling back to sane defaults when no policies have been set.
/// </summary>
/// <param name="_"></param>
/// <returns></returns>
private KeyPolicy GetKeyPolicy(Realm _) => new RsaKeyPolicy();
private KeyPolicy GetSigningKeyPolicy(Realm _) => new RsaKeyPolicy();
private KeyPolicy GetDataKeyPolicy(Realm _) => new AesKeyPolicy();
public async Task LoadActiveKeys(Realm realm)
{
await db.Entry(realm).Collection(r => r.Keys)
await db.Entry(realm).Collection(r => r.TokenSigningKeys)
.Query()
.Where(k => k.RevokedAt == null)
.LoadAsync();
@ -62,7 +91,7 @@ public class RealmService(
public async Task LoadDeks(Realm realm)
{
await db.Entry(realm).Collection(r => r.Deks)
await db.Entry(realm).Collection(r => r.DataEncryptionKeys)
.Query()
.LoadAsync();
}