-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathProgram.cs
307 lines (248 loc) · 12.2 KB
/
Program.cs
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#region (c) 2024 Joseph Shook. All rights reserved.
// /*
// Authors:
// Joseph Shook [email protected]
//
// See LICENSE in the project root for license information.
// */
#endregion
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json.Serialization;
using Google.Apis.Auth.OAuth2;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using IdentityModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Serilog;
using Udap.CdsHooks.Model;
using Udap.Common;
using Udap.Proxy.Server;
using Udap.Smart.Model;
using Udap.Util.Extensions;
using Yarp.ReverseProxy.Transforms;
using ZiggyCreatures.Caching.Fusion;
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.CreateLogger();
builder.Host.UseSerilog();
// Mount Cloud Secrets
builder.Configuration.AddJsonFile("/secret/udapproxyserverappsettings", true, false);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.Configure<JsonOptions>(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.Converters.Add(new FhirResourceConverter());
});
builder.Services.Configure<CdsServices>(builder.Configuration.GetRequiredSection("CdsServices"));
builder.Services.Configure<SmartMetadata>(builder.Configuration.GetRequiredSection("SmartMetadata"));
builder.Services.Configure<UdapFileCertStoreManifest>(builder.Configuration.GetSection(Constants.UDAP_FILE_STORE_MANIFEST));
builder.Services.AddCdsServices();
builder.Services.AddSmartMetadata();
builder.Services.AddUdapMetadataServer(builder.Configuration);
builder.Services.AddFusionCache()
.WithDefaultEntryOptions(new FusionCacheEntryOptions
{
Duration = TimeSpan.FromMinutes(10),
FactorySoftTimeout = TimeSpan.FromMilliseconds(100),
AllowTimedOutFactoryBackgroundCompletion = true,
FailSafeMaxDuration = TimeSpan.FromHours(12)
});
builder.Services.AddAuthentication(OidcConstants.AuthenticationSchemes.AuthorizationHeaderBearer)
.AddJwtBearer(OidcConstants.AuthenticationSchemes.AuthorizationHeaderBearer, options =>
{
options.Authority = builder.Configuration["Jwt:Authority"];
options.RequireHttpsMetadata = bool.Parse(builder.Configuration["Jwt:RequireHttpsMetadata"] ?? "true");
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
builder.Services.AddCors(options =>
{
options.AddPolicy("DefaultPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("udapPolicy", policy =>
policy.RequireAuthenticatedUser());
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.ConfigureHttpClient((_, handler) =>
{
// this is required to decompress automatically. ******* troubleshooting only *******
handler.AutomaticDecompression = System.Net.DecompressionMethods.All;
})
.AddTransforms(builderContext =>
{
// Conditionally add a transform for routes that require auth.
if (builderContext.Route.Metadata != null &&
(builderContext.Route.Metadata.ContainsKey("GCPKeyResolve") || builderContext.Route.Metadata.ContainsKey("AccessToken")))
{
builderContext.AddRequestTransform(async context =>
{
var resolveAccessToken = await ResolveAccessToken(builderContext.Route.Metadata);
context.ProxyRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", resolveAccessToken);
SetProxyHeaders(context);
});
}
// Use the default credentials. Primary usage: running in Cloud Run under a specific service account
if (builderContext.Route.Metadata != null && (builderContext.Route.Metadata.TryGetValue("ADC", out string? adc)))
{
if (adc.Equals("True", StringComparison.OrdinalIgnoreCase))
{
builderContext.AddRequestTransform(async context =>
{
var googleCredentials = GoogleCredential.GetApplicationDefault();
string accessToken = await googleCredentials.UnderlyingCredential.GetAccessTokenForRequestAsync();
context.ProxyRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
SetProxyHeaders(context);
});
}
}
builderContext.AddResponseTransform(async responseContext =>
{
if (responseContext.HttpContext.Request.Path == "/fhir/r4/metadata")
{
responseContext.SuppressResponseBody = true;
var cache = responseContext.HttpContext.RequestServices.GetRequiredService<IFusionCache>();
var bytes = await cache.GetOrSetAsync("metadata", _ => GetFhirMetadata(responseContext, builder));
// Change Content-Length to match the modified body, or remove it.
responseContext.HttpContext.Response.ContentLength = bytes?.Length;
// Response headers are copied before transforms are invoked, update any needed headers on the HttpContext.Response.
await responseContext.HttpContext.Response.Body.WriteAsync(bytes);
}
//
// Rewrite resource URLs
//
else if (responseContext.HttpContext.Request.Path.HasValue &&
responseContext.HttpContext.Request.Path.Value.StartsWith("/fhir/r4/", StringComparison.OrdinalIgnoreCase))
{
responseContext.SuppressResponseBody = true;
var stream = await responseContext.ProxyResponse!.Content.ReadAsStreamAsync();
Console.WriteLine($"RESPONSE CODE: {responseContext.ProxyResponse.StatusCode}");
using var reader = new StreamReader(stream);
// TODO: size limits, timeouts
var body = await reader.ReadToEndAsync();
var finalBytes = Encoding.UTF8.GetBytes(body.Replace($"\"url\": \"{builder.Configuration["FhirUrlProxy:Back"]}",
$"\"url\": \"{builder.Configuration["FhirUrlProxy:Front"]}"));
responseContext.HttpContext.Response.ContentLength = finalBytes.Length;
await responseContext.HttpContext.Response.Body.WriteAsync(finalBytes);
}
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseCors("DefaultPolicy");
app.UseDefaultFiles();
app.UseStaticFiles();
// Write streamlined request completion events, instead of the more verbose ones from the framework.
// To use the default framework request logging instead, remove this line and set the "Microsoft"
// level in appsettings.json to "Information".
app.UseSerilogRequestLogging();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<RouteLoggingMiddleware>();
app.MapReverseProxy();
app.UseCdsServices("fhir/r4");
app.UseSmartMetadata("fhir/r4");
app.UseUdapMetadataServer("fhir/r4"); // Ensure metadata can only be called from this base URL.
app.Run();
async Task<string?> ResolveAccessToken(IReadOnlyDictionary<string, string> metadata)
{
try
{
if (metadata.ContainsKey("AccessToken"))
{
// You could pass AccessToken as an environment variable
return builder.Configuration.GetValue<string>(metadata["AccessToken"]);
}
var routeAuthorizationPolicy = metadata["GCPKeyResolve"];
var path = builder.Configuration.GetValue<string>(routeAuthorizationPolicy);
if (string.IsNullOrWhiteSpace(path))
{
throw new InvalidOperationException(
$"The route metadata '{routeAuthorizationPolicy}' must be set to a valid path.");
}
var credentials = new ServiceAccountCredentialCache();
return await credentials.GetAccessTokenAsync(path, "https://www.googleapis.com/auth/cloud-healthcare");
}
catch (Exception ex)
{
Console.WriteLine(ex); //todo: Logger
return string.Empty;
}
}
async Task<byte[]?> GetFhirMetadata(ResponseTransformContext responseTransformContext,
WebApplicationBuilder webApplicationBuilder)
{
var stream = responseTransformContext.ProxyResponse?.Content != null
? await responseTransformContext.ProxyResponse.Content.ReadAsStreamAsync()
: Stream.Null;
using var reader = new StreamReader(stream);
var body = await reader.ReadToEndAsync();
if (!string.IsNullOrEmpty(body))
{
var capStatement = await new FhirJsonParser().ParseAsync<CapabilityStatement>(body);
var securityComponent = new CapabilityStatement.SecurityComponent();
securityComponent.Service.Add(
new CodeableConcept("http://fhir.udap.org/CodeSystem/capability-rest-security-service",
"UDAP",
"OAuth2 using UDAP profile (see http://www.udap.org)"));
//
// https://build.fhir.org/ig/HL7/fhir-extensions/StructureDefinition-oauth-uris.html
//
var oauthUrlExtensions = new Extension();
var securityExtension = new Extension("http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris", oauthUrlExtensions);
securityExtension.Extension.Add(new Extension() { Url = "token", Value = new FhirUri(webApplicationBuilder.Configuration["Jwt:Token"]) });
securityExtension.Extension.Add(new Extension() { Url = "authorize", Value = new FhirUri(webApplicationBuilder.Configuration["Jwt:Authorize"]) });
securityExtension.Extension.Add(new Extension() { Url = "register", Value = new FhirUri(webApplicationBuilder.Configuration["Jwt:Register"]) });
securityExtension.Extension.Add(new Extension() { Url = "manage", Value = new FhirUri(webApplicationBuilder.Configuration["Jwt:Manage"]) });
securityComponent.Extension.Add(securityExtension);
capStatement.Rest.First().Security = securityComponent;
body = new FhirJsonSerializer().SerializeToString(capStatement);
var bytes = Encoding.UTF8.GetBytes(body);
return bytes;
}
return null;
}
void SetProxyHeaders(RequestTransformContext requestTransformContext)
{
if (requestTransformContext.HttpContext.Request.Headers.Authorization.Count == 0)
{
return;
}
var bearerToken = requestTransformContext.HttpContext.Request.Headers.Authorization.First();
if (bearerToken == null)
{
return;
}
foreach (var requestHeader in requestTransformContext.HttpContext.Request.Headers)
{
Console.WriteLine(requestHeader.Value);
}
var tokenHandler = new JwtSecurityTokenHandler();
var jsonToken = tokenHandler.ReadJwtToken(requestTransformContext.HttpContext.Request.Headers.Authorization.First()?.Replace("Bearer", "").Trim());
var scopes = jsonToken.Claims.Where(c => c.Type == "scope");
var iss = jsonToken.Claims.Where(c => c.Type == "iss");
// var sub = jsonToken.Claims.Where(c => c.Type == "sub"); // figure out what subject should be for GCP
// Never let the requester set this header.
requestTransformContext.ProxyRequest.Headers.Remove("X-Authorization-Scope");
requestTransformContext.ProxyRequest.Headers.Remove("X-Authorization-Issuer");
// Google Cloud way of passing scopes to the Fhir Server
var spaceSeparatedString = scopes.Select(s => s.Value)
.Where(s => s != "udap") //gcp doesn't know udap Need better filter to block unknown scopes
.ToSpaceSeparatedString();
requestTransformContext.ProxyRequest.Headers.Add("X-Authorization-Scope", spaceSeparatedString);
requestTransformContext.ProxyRequest.Headers.Add("X-Authorization-Issuer", iss.SingleOrDefault()?.Value);
// context.ProxyRequest.Headers.Add("X-Authorization-Subject", sub.SingleOrDefault().Value);
}