-
Notifications
You must be signed in to change notification settings - Fork 277
CIMD #303
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
josephdecock
wants to merge
17
commits into
main
Choose a base branch
from
jmdc/cimd
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
CIMD #303
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
8f11ca3
MCP with CIMD Sample
josephdecock c49e0fc
Harden the HttpClient to prevent socket exhaustion
josephdecock 534918c
Cooperative cancellation
josephdecock bd5503d
improve handling of max request size
josephdecock 0336301
Refactor CIMD store into pieces
josephdecock a44743d
Use hybrid cache
josephdecock a88fc2c
Move logging for simplicity
josephdecock ecf5753
Track missed tools
josephdecock 3cbdd09
Introduce CimdRequestContext and CimdDocument
josephdecock 653011f
Move TryParseClientUri
josephdecock 3f6cecd
Comment cleanup
josephdecock 0d55c5c
Better timeouts
josephdecock c66ec07
Document change detection limitation
josephdecock 3b33556
Limit JWKS to 5kb
josephdecock d904142
Clean up readme
josephdecock e33e349
Use decorator to allow for static clients
josephdecock 61c8d64
One more comment
josephdecock File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| keys/ | ||
| *.pem | ||
| *.pfx | ||
| *.p12 | ||
|
|
||
| # Override the repo-root "tools/" ignore rule so that our Tools/ source directory is tracked | ||
| !**/Tools/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "servers": { | ||
| "cimd-demo": { | ||
| "type": "http", | ||
| "url": "https://localhost:7241/" | ||
| } | ||
| } | ||
| } |
16 changes: 16 additions & 0 deletions
16
IdentityServer/v7/CIMD/CIMD.IdentityServer/CIMD.IdentityServer.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Duende.IdentityServer" Version="7.4.6" /> | ||
| <PackageReference Include="Duende.IdentityModel" Version="8.0.0" /> | ||
| <PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.4.0" /> | ||
| <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
59 changes: 59 additions & 0 deletions
59
IdentityServer/v7/CIMD/CIMD.IdentityServer/CimdClientBuilder.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
| using Duende.IdentityModel.Jwk; | ||
| using Duende.IdentityServer; | ||
| using Duende.IdentityServer.Models; | ||
|
|
||
| namespace CIMD.IdentityServer; | ||
|
|
||
| /// <summary> | ||
| /// Creates the IdentityServer Client model from a CIMD document and optional JWKS | ||
| /// </summary> | ||
| public static class CimdClientBuilder | ||
| { | ||
| private static readonly JsonSerializerOptions JwkSerializerOptions = new() | ||
| { | ||
| DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, | ||
| IgnoreReadOnlyFields = true, | ||
| IgnoreReadOnlyProperties = true, | ||
| }; | ||
|
|
||
| public static Client Build( | ||
| string clientId, | ||
| CimdDocument document, | ||
| JsonWebKeySet? keySet) | ||
| { | ||
| var scopes = document.Scope?.Split(' ').ToList() ?? []; | ||
| var allowOfflineAccess = scopes.Contains("offline_access"); | ||
| scopes.Remove("offline_access"); | ||
|
|
||
| var client = new Client | ||
| { | ||
| ClientId = clientId, | ||
| ClientName = document.ClientName, | ||
| LogoUri = document.LogoUri?.ToString(), | ||
| ClientUri = document.ClientUri?.ToString(), | ||
| RedirectUris = document.RedirectUris?.Select(u => u.ToString()).ToList() ?? [], | ||
| PostLogoutRedirectUris = document.PostLogoutRedirectUris?.Select(u => u.ToString()).ToList() ?? [], | ||
| AllowedGrantTypes = document.GrantTypes?.ToList() ?? GrantTypes.Code, | ||
| RequireClientSecret = keySet is not null, | ||
| AllowedScopes = scopes, | ||
| AllowOfflineAccess = allowOfflineAccess | ||
| }; | ||
|
|
||
| if (keySet is not null) | ||
| { | ||
| foreach (var key in keySet.Keys) | ||
| { | ||
| var jwk = JsonSerializer.Serialize(key, JwkSerializerOptions); | ||
| client.ClientSecrets.Add(new Secret | ||
| { | ||
| Type = IdentityServerConstants.SecretTypes.JsonWebKey, | ||
| Value = jwk | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return client; | ||
| } | ||
| } | ||
185 changes: 185 additions & 0 deletions
185
IdentityServer/v7/CIMD/CIMD.IdentityServer/CimdClientStore.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| using Duende.IdentityServer.Models; | ||
| using Duende.IdentityServer.Stores; | ||
| using Microsoft.Extensions.Caching.Hybrid; | ||
|
|
||
| namespace CIMD.IdentityServer; | ||
|
|
||
| /// <summary> | ||
| /// Decorating <see cref="IClientStore"/> that adds CIMD (Client ID Metadata | ||
| /// Document) support. If the client_id is a well-formed CIMD URI (HTTPS with | ||
| /// a path), the document is fetched, validated, and mapped to a | ||
| /// <see cref="Client"/>. Otherwise, the request is delegated to the inner | ||
| /// store, allowing statically configured clients to coexist with CIMD clients. | ||
| /// Uses <see cref="HybridCache"/> for caching with automatic expiration. | ||
| /// </summary> | ||
| /// <typeparam name="T">The inner <see cref="IClientStore"/> implementation to | ||
| /// delegate to for non-CIMD client IDs. Resolved automatically by DI, following | ||
| /// the same generic-constraint stacking pattern used by IdentityServer's own | ||
| /// <c>CachingClientStore<T></c> and <c>ValidatingClientStore<T></c>.</typeparam> | ||
| /// <remarks> | ||
| /// <para><strong>Known limitation — document change detection:</strong> | ||
| /// When a cached CIMD document expires and is re-fetched, this implementation | ||
| /// does not compare the new document to the previously accepted one. If the | ||
| /// document has changed (e.g., new redirect URIs, rotated keys, different | ||
| /// grant types), the new version is accepted without review. A production | ||
| /// implementation should consider persisting previously accepted documents | ||
| /// and comparing on re-fetch so that policy can evaluate whether the changes | ||
| /// are acceptable or represent a potential compromise.</para> | ||
| /// <para>As of this writing, the CIMD draft itself has an open TODO in | ||
| /// section 4.3 (Metadata Caching) regarding stale data considerations.</para> | ||
| /// </remarks> | ||
| public partial class CimdClientStore<T>( | ||
| T innerStore, | ||
| CimdDocumentFetcher fetcher, | ||
| SsrfGuard ssrfGuard, | ||
| ICimdPolicy policy, | ||
| HybridCache cache, | ||
| ILogger<CimdClientStore<T>> logger) : IClientStore | ||
| where T : IClientStore | ||
| { | ||
| private static readonly TimeSpan ResolutionTimeout = TimeSpan.FromSeconds(15); | ||
|
|
||
| public async Task<Client?> FindClientByIdAsync(string clientId) | ||
| { | ||
| // If the client_id isn't a valid CIMD URI, delegate to the inner store | ||
| // (e.g., in-memory clients configured in Config.cs). | ||
| if (!TryParseClientUri(clientId, out _)) | ||
| { | ||
| return await innerStore.FindClientByIdAsync(clientId); | ||
| } | ||
|
|
||
| using var cts = new CancellationTokenSource(ResolutionTimeout); | ||
| try | ||
| { | ||
| return await cache.GetOrCreateAsync( | ||
| $"cimd-client:{clientId}", | ||
| async ct => await ResolveClientAsync(clientId, ct), | ||
| cancellationToken: cts.Token); | ||
| } | ||
| catch (CimdResolutionException) | ||
| { | ||
| // Resolution failed — don't cache the failure | ||
| return null; | ||
| } | ||
| catch (OperationCanceledException) when (cts.IsCancellationRequested) | ||
| { | ||
| Log.ResolutionTimedOut(logger, clientId); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Performs the full CIMD resolution pipeline. Throws | ||
| /// <see cref="CimdResolutionException"/> on any validation failure so that | ||
| /// <see cref="HybridCache"/> does not cache the negative result. | ||
| /// </summary> | ||
| private async Task<Client> ResolveClientAsync(string clientId, CancellationToken ct) | ||
| { | ||
| // TryParseClientUri was already called by FindClientByIdAsync — this | ||
| // is guaranteed to succeed, but we parse again to get the Uri value. | ||
| if (!TryParseClientUri(clientId, out var clientUri)) | ||
| { | ||
| throw new CimdResolutionException(); | ||
| } | ||
|
|
||
| // SSRF protection (CIMD spec section 6.5) | ||
| if (!await ssrfGuard.IsSafeAsync(clientUri, ct)) | ||
| { | ||
| Log.SsrfCheckFailed(logger, clientId); | ||
| throw new CimdResolutionException(); | ||
| } | ||
|
|
||
| // Domain allowlist policy | ||
| var domainResult = await policy.CheckDomainAsync(clientUri, ct); | ||
| if (!domainResult.IsAllowed) | ||
| { | ||
| Log.DomainDeniedByPolicy(logger, clientId, domainResult.Reason); | ||
| throw new CimdResolutionException(); | ||
| } | ||
|
|
||
| // Fetch and deserialize the CIMD document | ||
| var context = await fetcher.FetchAsync(clientUri, ct); | ||
| if (context == null) | ||
| { | ||
| throw new CimdResolutionException(); | ||
| } | ||
|
|
||
| // Validate document contents | ||
| if (!CimdDocumentValidator.ClientIdMatchesDocument(clientId, context.Document)) | ||
| { | ||
| Log.ClientIdMismatch(logger, clientId); | ||
| throw new CimdResolutionException(); | ||
| } | ||
|
|
||
| if (!CimdDocumentValidator.PassesAuthMethodChecks(context.Document, out var authMethodFailureReason)) | ||
| { | ||
| Log.AuthMethodCheckFailed(logger, clientId, authMethodFailureReason); | ||
| throw new CimdResolutionException(); | ||
| } | ||
|
|
||
| // Document-level policy check (has access to response headers via context) | ||
| var documentResult = await policy.ValidateDocumentAsync(context, ct); | ||
| if (!documentResult.IsAllowed) | ||
| { | ||
| Log.DocumentDeniedByPolicy(logger, clientId, documentResult.Reason); | ||
| throw new CimdResolutionException(); | ||
| } | ||
|
|
||
| // Resolve keys and build the IdentityServer client | ||
| var keySet = await fetcher.ResolveJwksAsync(context, ct); | ||
| var client = CimdClientBuilder.Build(clientId, context.Document, keySet); | ||
|
|
||
| Log.RegisteredCimdClient(logger, clientId); | ||
| return client; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Per spec section 3: client URI must be HTTPS, contain a path component, | ||
| /// and MUST NOT contain single/double-dot path segments, a fragment, or | ||
| /// a username or password. | ||
| /// </summary> | ||
| private static bool TryParseClientUri(string clientId, out Uri clientUri) | ||
| { | ||
| if (!Uri.TryCreate(clientId, UriKind.Absolute, out clientUri!) || | ||
| clientUri.Scheme != "https" || | ||
| string.IsNullOrEmpty(clientUri.AbsolutePath.TrimStart('/')) || | ||
| !string.IsNullOrEmpty(clientUri.Fragment) || | ||
| !string.IsNullOrEmpty(clientUri.UserInfo) || | ||
| clientUri.Segments.Any(s => s == "./" || s == "../")) | ||
| { | ||
| clientUri = null!; | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Thrown when CIMD resolution fails, signaling that the result should | ||
| /// not be cached by <see cref="HybridCache"/>. | ||
| /// </summary> | ||
| private sealed class CimdResolutionException : Exception; | ||
|
|
||
| private static partial class Log | ||
| { | ||
| [LoggerMessage(LogLevel.Debug, "Successfully registered CIMD client '{ClientId}'")] | ||
| public static partial void RegisteredCimdClient(ILogger logger, string clientId); | ||
|
|
||
| [LoggerMessage(LogLevel.Error, "CIMD client URI '{ClientId}' resolves to a special-use IP address (RFC 6890); rejecting to prevent SSRF")] | ||
| public static partial void SsrfCheckFailed(ILogger logger, string clientId); | ||
|
|
||
| [LoggerMessage(LogLevel.Error, "CIMD client URI '{ClientId}' was denied by policy: {Reason}")] | ||
| public static partial void DomainDeniedByPolicy(ILogger logger, string clientId, string? reason); | ||
|
|
||
| [LoggerMessage(LogLevel.Error, "CIMD document for '{ClientId}' was denied by policy: {Reason}")] | ||
| public static partial void DocumentDeniedByPolicy(ILogger logger, string clientId, string? reason); | ||
|
|
||
| [LoggerMessage(LogLevel.Error, "CIMD document client_id does not match the request URL '{ClientId}'")] | ||
| public static partial void ClientIdMismatch(ILogger logger, string clientId); | ||
|
|
||
| [LoggerMessage(LogLevel.Error, "CIMD document for '{ClientId}' failed auth method validation: {Reason}")] | ||
| public static partial void AuthMethodCheckFailed(ILogger logger, string clientId, string reason); | ||
|
|
||
| [LoggerMessage(LogLevel.Error, "CIMD resolution for '{ClientId}' timed out")] | ||
| public static partial void ResolutionTimedOut(ILogger logger, string clientId); | ||
| } | ||
| } |
12 changes: 12 additions & 0 deletions
12
IdentityServer/v7/CIMD/CIMD.IdentityServer/CimdDocument.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| using Duende.IdentityModel.Client; | ||
|
|
||
| namespace CIMD.IdentityServer; | ||
|
|
||
| /// <summary> | ||
| /// Represents a Client ID Metadata Document (CIMD). Structurally identical to | ||
| /// <see cref="DynamicClientRegistrationDocument"/> — CIMD reuses the same JSON | ||
| /// schema as RFC 7591 Dynamic Client Registration, but the document is hosted | ||
| /// at a URL that serves as the client_id rather than being submitted to a | ||
| /// registration endpoint. | ||
| /// </summary> | ||
| public class CimdDocument : DynamicClientRegistrationDocument; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see that we're validating the RedirectUris from the document anywhere. Are there rules in the spec which require anything specific about them?