-
Notifications
You must be signed in to change notification settings - Fork 259
Allow access to health endpoint as per defined roles #2632
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
Merged
Merged
Changes from all commits
Commits
Show all changes
66 commits
Select commit
Hold shift + click to select a range
ee1561d
Modify Config Files according to health check endpoint
7a1734d
formatting
49daea3
modify the if condition for comprehensive check
sezal98 95e4777
Initial commit
374ce72
resolving comments
e2b23c4
Merge branch 'dev/sezalchug/healthConfigFiles' of https://github.com/…
ab2258b
formatting
6125132
Merge branch 'dev/sezalchug/healthConfigFiles' into dev/sezalchug/hea…
c7f0823
merging into config changes
9b6de0b
UTs
e95d6ae
nit changes and UTs and default value
e8cd0b5
formatting
74042e1
response file sample
e1d51aa
based on discussions in the meeting
8207dc5
nits
b7e7218
snapshots
521221f
Merge branch 'main' of https://github.com/Azure/data-api-builder into…
b574648
remove value
cb95c11
format
9ae3150
build
b7fbb77
tests
daa4742
nit comments
80ab25c
revert add entity snapshots
c5eb328
module initializer
bc2adb8
update entity tests revert
5fc5cc6
end to end tests
433010d
serialization and deserialization changes
4cb4fb0
nits
2c20d1a
Role changes in Health endpoint
ed07ac0
formatting
92b23f8
test add jsonignore
705c6ac
modify modulerinitializer
8d6e2ed
resolving comments
c025a6d
add test case to check individual value of true/false
29d05f0
remove writing null values
131e1c1
formatting
176958b
changes with respect to roles
30e9763
revert datasource default
6cbeeec
revert snapshots
ca025dc
add space
7630986
revert space
39cbfba
try with encoding
fa03ded
formatting
06094c4
formatting
7b79233
nits
08f746e
Merge branch 'dev/sezalchug/healthCheckExecution' into dev/sezalchug/…
f5a999f
UTs
d56b0c6
formatting
37612c8
edit error message
c08a2ae
resolving comments
8dcce5d
formatting
5716ab3
resolving comnmnets
9a19993
formatting
650b284
error msg
48bf947
Merge branch 'dev/sezalchug/healthCheckExecution' into dev/sezalchug/…
404897d
nit comments
b3bad84
Merge branch 'main' of https://github.com/Azure/data-api-builder into…
21e4bcd
nits
94cccae
capital variable
7bad17f
resolving comments
3cbe2a5
add test case
d3190a2
resolving comments
4844e81
Merge branch 'main' of https://github.com/Azure/data-api-builder into…
d9fe6e8
Merge branch 'main' into dev/sezalchug/rolesHealthCheck
Aniruddh25 558b430
Fixed formatting issues
RubenCerna2079 24ed5bc
Merge branch 'main' into dev/sezalchug/rolesHealthCheck
RubenCerna2079 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
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
140 changes: 140 additions & 0 deletions
140
src/Config/Converters/RuntimeHealthOptionsConvertorFactory.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,140 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
using Azure.DataApiBuilder.Config.ObjectModel; | ||
|
||
namespace Azure.DataApiBuilder.Config.Converters; | ||
|
||
internal class RuntimeHealthOptionsConvertorFactory : JsonConverterFactory | ||
{ | ||
// Determines whether to replace environment variable with its | ||
// value or not while deserializing. | ||
private bool _replaceEnvVar; | ||
|
||
/// <inheritdoc/> | ||
public override bool CanConvert(Type typeToConvert) | ||
{ | ||
return typeToConvert.IsAssignableTo(typeof(RuntimeHealthCheckConfig)); | ||
} | ||
|
||
/// <inheritdoc/> | ||
public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
return new HealthCheckOptionsConverter(_replaceEnvVar); | ||
} | ||
|
||
internal RuntimeHealthOptionsConvertorFactory(bool replaceEnvVar) | ||
{ | ||
_replaceEnvVar = replaceEnvVar; | ||
} | ||
|
||
private class HealthCheckOptionsConverter : JsonConverter<RuntimeHealthCheckConfig> | ||
{ | ||
// Determines whether to replace environment variable with its | ||
// value or not while deserializing. | ||
private bool _replaceEnvVar; | ||
|
||
/// <param name="replaceEnvVar">Whether to replace environment variable with its | ||
/// value or not while deserializing.</param> | ||
internal HealthCheckOptionsConverter(bool replaceEnvVar) | ||
{ | ||
_replaceEnvVar = replaceEnvVar; | ||
} | ||
|
||
/// <summary> | ||
/// Defines how DAB reads the runtime's health options and defines which values are | ||
/// used to instantiate RuntimeHealthCheckConfig. | ||
/// </summary> | ||
/// <exception cref="JsonException">Thrown when improperly formatted health check options are provided.</exception> | ||
public override RuntimeHealthCheckConfig? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
if (reader.TokenType is JsonTokenType.StartObject) | ||
{ | ||
bool? enabled = null; | ||
HashSet<string>? roles = null; | ||
|
||
while (reader.Read()) | ||
{ | ||
if (reader.TokenType is JsonTokenType.EndObject) | ||
{ | ||
return new RuntimeHealthCheckConfig(enabled, roles); | ||
} | ||
|
||
string? property = reader.GetString(); | ||
reader.Read(); | ||
|
||
switch (property) | ||
{ | ||
case "enabled": | ||
if (reader.TokenType is not JsonTokenType.Null) | ||
{ | ||
enabled = reader.GetBoolean(); | ||
} | ||
|
||
break; | ||
case "roles": | ||
if (reader.TokenType is not JsonTokenType.Null) | ||
{ | ||
// Check if the token type is an array | ||
if (reader.TokenType == JsonTokenType.StartArray) | ||
{ | ||
HashSet<string> stringList = new(); | ||
|
||
// Read the array elements one by one | ||
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) | ||
{ | ||
if (reader.TokenType == JsonTokenType.String) | ||
{ | ||
string? currentRole = reader.DeserializeString(_replaceEnvVar); | ||
if (!string.IsNullOrEmpty(currentRole)) | ||
{ | ||
stringList.Add(currentRole); | ||
} | ||
} | ||
} | ||
|
||
// After reading the array, assign it to the string[] variable | ||
roles = stringList; | ||
} | ||
else | ||
{ | ||
// Handle case where the token is not an array (e.g., throw an exception or handle differently) | ||
throw new JsonException("Expected an array of strings, but the token type is not an array."); | ||
} | ||
} | ||
|
||
break; | ||
sezal98 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
default: | ||
throw new JsonException($"Unexpected property {property}"); | ||
} | ||
} | ||
} | ||
|
||
throw new JsonException("Runtime Health Options has a missing }."); | ||
sezal98 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, RuntimeHealthCheckConfig value, JsonSerializerOptions options) | ||
{ | ||
if (value?.UserProvidedEnabled is true) | ||
{ | ||
writer.WriteStartObject(); | ||
writer.WritePropertyName("enabled"); | ||
JsonSerializer.Serialize(writer, value.Enabled, options); | ||
if (value?.Roles is not null) | ||
{ | ||
writer.WritePropertyName("roles"); | ||
JsonSerializer.Serialize(writer, value.Roles, options); | ||
} | ||
|
||
writer.WriteEndObject(); | ||
} | ||
else | ||
{ | ||
writer.WriteNullValue(); | ||
} | ||
} | ||
} | ||
} |
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
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
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
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
139 changes: 139 additions & 0 deletions
139
src/Service.Tests/Configuration/HealthEndpointRolesTests.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,139 @@ | ||
// Copyright (c) Microsoft Corporation. | ||
// Licensed under the MIT License. | ||
|
||
#nullable enable | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Net; | ||
using System.Net.Http; | ||
using System.Threading.Tasks; | ||
using Azure.DataApiBuilder.Config.ObjectModel; | ||
using Azure.DataApiBuilder.Core.Authorization; | ||
using Microsoft.AspNetCore.TestHost; | ||
using Microsoft.VisualStudio.TestTools.UnitTesting; | ||
|
||
namespace Azure.DataApiBuilder.Service.Tests.Configuration | ||
{ | ||
[TestClass] | ||
public class HealthEndpointRolesTests | ||
{ | ||
private const string STARTUP_CONFIG_ROLE = "authenticated"; | ||
|
||
private const string CUSTOM_CONFIG_FILENAME = "custom-config.json"; | ||
|
||
[TestCleanup] | ||
public void CleanupAfterEachTest() | ||
{ | ||
if (File.Exists(CUSTOM_CONFIG_FILENAME)) | ||
{ | ||
File.Delete(CUSTOM_CONFIG_FILENAME); | ||
} | ||
|
||
TestHelper.UnsetAllDABEnvironmentVariables(); | ||
} | ||
|
||
[TestMethod] | ||
[TestCategory(TestCategory.MSSQL)] | ||
[DataRow(null, null, DisplayName = "Validate Health Report when roles is not configured and HostMode is null.")] | ||
[DataRow(null, HostMode.Development, DisplayName = "Validate Health Report when roles is not configured and HostMode is Development.")] | ||
[DataRow(null, HostMode.Production, DisplayName = "Validate Health Report when roles is not configured and HostMode is Production.")] | ||
[DataRow("authenticated", HostMode.Production, DisplayName = "Validate Health Report when roles is configured to 'authenticated' and HostMode is Production.")] | ||
[DataRow("temp-role", HostMode.Production, DisplayName = "Validate Health Report when roles is configured to 'temp-role' which is not in token and HostMode is Production.")] | ||
[DataRow("authenticated", HostMode.Development, DisplayName = "Validate Health Report when roles is configured to 'authenticated' and HostMode is Development.")] | ||
[DataRow("temp-role", HostMode.Development, DisplayName = "Validate Health Report when roles is configured to 'temp-role' which is not in token and HostMode is Development.")] | ||
public async Task ComprehensiveHealthEndpoint_RolesTests(string role, HostMode hostMode) | ||
sezal98 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
// Arrange | ||
// At least one entity is required in the runtime config for the engine to start. | ||
// Even though this entity is not under test, it must be supplied enable successful | ||
// config file creation. | ||
Entity requiredEntity = new( | ||
Health: new(Enabled: true), | ||
Source: new("books", EntitySourceType.Table, null, null), | ||
Rest: new(Enabled: true), | ||
GraphQL: new("book", "books", true), | ||
Permissions: new[] { ConfigurationTests.GetMinimalPermissionConfig(AuthorizationResolver.ROLE_ANONYMOUS) }, | ||
Relationships: null, | ||
Mappings: null); | ||
|
||
Dictionary<string, Entity> entityMap = new() | ||
{ | ||
{ "Book", requiredEntity } | ||
}; | ||
|
||
CreateCustomConfigFile(entityMap, role, hostMode); | ||
|
||
string[] args = new[] | ||
{ | ||
$"--ConfigFileName={CUSTOM_CONFIG_FILENAME}" | ||
}; | ||
|
||
using (TestServer server = new(Program.CreateWebHostBuilder(args))) | ||
using (HttpClient client = server.CreateClient()) | ||
{ | ||
// Sends a GET request to a protected entity which requires a specific role to access. | ||
// Authorization checks | ||
HttpRequestMessage message = new(method: HttpMethod.Get, requestUri: $"/health"); | ||
string swaTokenPayload = AuthTestHelper.CreateStaticWebAppsEasyAuthToken( | ||
addAuthenticated: true, | ||
specificRole: STARTUP_CONFIG_ROLE); | ||
message.Headers.Add(AuthenticationOptions.CLIENT_PRINCIPAL_HEADER, swaTokenPayload); | ||
message.Headers.Add(AuthorizationResolver.CLIENT_ROLE_HEADER, STARTUP_CONFIG_ROLE); | ||
HttpResponseMessage authorizedResponse = await client.SendAsync(message); | ||
|
||
switch (role) | ||
{ | ||
case null: | ||
if (hostMode == HostMode.Development) | ||
{ | ||
Assert.AreEqual(expected: HttpStatusCode.OK, actual: authorizedResponse.StatusCode); | ||
Aniruddh25 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
else | ||
{ | ||
Assert.AreEqual(expected: HttpStatusCode.Forbidden, actual: authorizedResponse.StatusCode); | ||
} | ||
|
||
break; | ||
case "temp-role": | ||
Assert.AreEqual(expected: HttpStatusCode.Forbidden, actual: authorizedResponse.StatusCode); | ||
break; | ||
|
||
default: | ||
sezal98 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
Assert.AreEqual(expected: HttpStatusCode.OK, actual: authorizedResponse.StatusCode); | ||
break; | ||
} | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Helper function to write custom configuration file with minimal REST/GraphQL global settings | ||
/// using the supplied entities. | ||
/// </summary> | ||
/// <param name="entityMap">Collection of entityName -> Entity object.</param> | ||
/// <param name="role">Allowed Roles for comprehensive health endpoint.</param> | ||
private static void CreateCustomConfigFile(Dictionary<string, Entity> entityMap, string? role, HostMode hostMode = HostMode.Production) | ||
sezal98 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
DataSource dataSource = new( | ||
DatabaseType.MSSQL, | ||
ConfigurationTests.GetConnectionStringFromEnvironmentConfig(environment: TestCategory.MSSQL), | ||
Options: null, | ||
Health: new(true)); | ||
HostOptions hostOptions = new(Mode: hostMode, Cors: null, Authentication: new() { Provider = nameof(EasyAuthType.StaticWebApps) }); | ||
|
||
RuntimeConfig runtimeConfig = new( | ||
Schema: string.Empty, | ||
DataSource: dataSource, | ||
Runtime: new( | ||
Health: new(Enabled: true, Roles: role != null ? new HashSet<string> { role } : null), | ||
Rest: new(Enabled: true), | ||
GraphQL: new(Enabled: true), | ||
Host: hostOptions | ||
), | ||
Entities: new(entityMap)); | ||
|
||
File.WriteAllText( | ||
path: CUSTOM_CONFIG_FILENAME, | ||
contents: runtimeConfig.ToJson()); | ||
} | ||
} | ||
} |
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
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.
Uh oh!
There was an error while loading. Please reload this page.