-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathCimdClientStore.cs
More file actions
228 lines (198 loc) · 9.95 KB
/
CimdClientStore.cs
File metadata and controls
228 lines (198 loc) · 9.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Copyright (c) Duende Software. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
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,
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();
}
// 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();
}
// Enforce scope policy: merge defaults and filter disallowed scopes
var removedScopes = EnforceScopePolicy(context.Document, policy);
if (removedScopes.Count > 0)
{
Log.ScopesRemovedByPolicy(logger, clientId, string.Join(", ", removedScopes));
}
// Redirect URI validation (CIMD spec section 6.1)
foreach (var redirectUri in context.Document.RedirectUris)
{
var redirectResult = await policy.ValidateRedirectUriAsync(redirectUri, context, ct);
if (!redirectResult.IsAllowed)
{
Log.RedirectUriDeniedByPolicy(logger, clientId, redirectUri.ToString(), redirectResult.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;
/// <summary>
/// Merges the policy's <see cref="ICimdPolicy.DefaultScopes"/> into the
/// document and removes any scopes not present in the combined set of
/// default + allowed scopes. Scope comparison is case-sensitive per
/// RFC 6749 section 3.3.
/// </summary>
/// <returns>The list of scopes that were removed from the document.</returns>
private static IReadOnlyList<string> EnforceScopePolicy(
CimdDocument document, ICimdPolicy policy)
{
var requested = document.Scope?
.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? [];
// Build the full set of permitted scopes (case-sensitive per RFC 6749 §3.3)
var permitted = new HashSet<string>(
policy.DefaultScopes.Concat(policy.AllowedScopes),
StringComparer.Ordinal);
var removed = requested.Where(s => !permitted.Contains(s)).ToList();
var filtered = requested.Where(s => permitted.Contains(s));
var final = filtered.Union(policy.DefaultScopes, StringComparer.Ordinal);
document.Scope = string.Join(' ', final);
return removed;
}
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}' 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 document for '{ClientId}' has redirect URI '{RedirectUri}' denied by policy: {Reason}")]
public static partial void RedirectUriDeniedByPolicy(ILogger logger, string clientId, string redirectUri, string? reason);
[LoggerMessage(LogLevel.Error, "CIMD resolution for '{ClientId}' timed out")]
public static partial void ResolutionTimedOut(ILogger logger, string clientId);
[LoggerMessage(LogLevel.Information, "CIMD client '{ClientId}' requested scopes not permitted by policy; removed: {RemovedScopes}")]
public static partial void ScopesRemovedByPolicy(ILogger logger, string clientId, string removedScopes);
}
}