-
Notifications
You must be signed in to change notification settings - Fork 7
DE-135 - Doppler security #12
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
7 commits
Select commit
Hold shift + click to select a range
52272ef
chore: add public and private key files for development environment
andresmoschini 1a61e6e
chore(deps): add dependency on Microsoft.AspNetCore.Authentication.Jw…
andresmoschini c341615
feat: add a new test endpoint for anonymous connections
andresmoschini 6ffde0e
feat: add a new test endpoint for connections with valid token signature
andresmoschini 8db618a
feat: add a new test endpoint for connections with a super user's token
andresmoschini fbc09fe
feat: add a new test endpoint for connections related to an account id
andresmoschini 78e27fd
feat: add a new test endpoint for connections related to an accountname
andresmoschini 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 |
|---|---|---|
|
|
@@ -26,3 +26,4 @@ yarn.lock | |
| package-lock.json | ||
| [eE]ncrypted.[sS]ecret.* | ||
| *.csproj.user | ||
| *.key | ||
Large diffs are not rendered by default.
Oops, something went wrong.
16 changes: 16 additions & 0 deletions
16
Doppler.HelloMicroservice.Test/HttpResponseMessageExtensions.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,16 @@ | ||
| using System; | ||
| using System.Linq; | ||
| using System.Net.Http; | ||
|
|
||
| namespace Doppler.HelloMicroservice | ||
| { | ||
| public static class HttpResponseMessageExtensions | ||
| { | ||
| public static string GetHeadersAsString(this HttpResponseMessage response) | ||
| { | ||
| var keysAndValues = response.Headers.SelectMany(x => x.Value.Select(y => new { x.Key, Value = y })); | ||
| var headerLines = keysAndValues.Select(x => $"{x.Key}: {x.Value}"); | ||
| return string.Join("\n", headerLines); | ||
| } | ||
| } | ||
| } |
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,50 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
| using Doppler.HelloMicroservice.DopplerSecurity; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.AspNetCore.Mvc; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Doppler.HelloMicroservice.Controllers | ||
| { | ||
| [Authorize] | ||
| [ApiController] | ||
| public class HelloController | ||
| { | ||
| [AllowAnonymous] | ||
| [HttpGet("/hello/anonymous")] | ||
| public string GetForAnonymous() | ||
| { | ||
| return "Hello anonymous!"; | ||
| } | ||
|
|
||
| [HttpGet("/hello/valid-token")] | ||
| public string GetForValidToken() | ||
| { | ||
| return "Hello! you have a valid token!"; | ||
| } | ||
|
|
||
| [Authorize(Policies.ONLY_SUPERUSER)] | ||
| [HttpGet("/hello/superuser")] | ||
| public string GetForSuperUserToken() | ||
| { | ||
| return "Hello! you have a valid SuperUser token!"; | ||
| } | ||
|
|
||
| [Authorize(Policies.OWN_RESOURCE_OR_SUPERUSER)] | ||
| [HttpGet("/accounts/{accountId:int:min(0)}/hello")] | ||
| public string GetForAccountById(int accountId) | ||
| { | ||
| return $"Hello! \"you\" that have access to the account with ID '{accountId}'"; | ||
| } | ||
|
|
||
| [Authorize(Policies.OWN_RESOURCE_OR_SUPERUSER)] | ||
| [HttpGet("/accounts/{accountname}/hello")] | ||
| public string GetForAccountByName(string accountname) | ||
| { | ||
| return $"Hello! \"you\" that have access to the account with accountname '{accountname}'"; | ||
| } | ||
| } | ||
| } |
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
61 changes: 61 additions & 0 deletions
61
Doppler.HelloMicroservice/DopplerSecurity/ConfigureDopplerSecurityOptions.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,61 @@ | ||
| using Microsoft.AspNetCore.Hosting; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.Extensions.FileProviders; | ||
| using Microsoft.Extensions.Options; | ||
| using Microsoft.IdentityModel.Tokens; | ||
| using System; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Text.RegularExpressions; | ||
| using System.Security.Cryptography; | ||
|
|
||
| namespace Doppler.HelloMicroservice.DopplerSecurity | ||
| { | ||
| public class ConfigureDopplerSecurityOptions : IConfigureOptions<DopplerSecurityOptions> | ||
| { | ||
| private readonly IConfiguration _configuration; | ||
| private readonly IFileProvider _fileProvider; | ||
|
|
||
| public ConfigureDopplerSecurityOptions(IConfiguration configuration, IWebHostEnvironment webHostEnvironment) | ||
| { | ||
| _configuration = configuration; | ||
| _fileProvider = webHostEnvironment.ContentRootFileProvider; | ||
| } | ||
|
|
||
| private static string ReadToEnd(IFileInfo fileInfo) | ||
| { | ||
| using var stream = fileInfo.CreateReadStream(); | ||
| using var reader = new StreamReader(stream); | ||
| return reader.ReadToEnd(); | ||
| } | ||
|
|
||
| private static RsaSecurityKey ParseXmlString(string xmlString) | ||
| { | ||
| using var rsaProvider = new RSACryptoServiceProvider(); | ||
| rsaProvider.FromXmlString(xmlString); | ||
| var rsaParameters = rsaProvider.ExportParameters(false); | ||
| return new RsaSecurityKey(RSA.Create(rsaParameters)); | ||
| } | ||
|
|
||
| public void Configure(DopplerSecurityOptions options) | ||
| { | ||
| var path = _configuration.GetValue( | ||
| DopplerSecurityDefaults.PUBLIC_KEYS_FOLDER_CONFIG_KEY, | ||
| DopplerSecurityDefaults.PUBLIC_KEYS_FOLDER_DEFAULT_CONFIG_VALUE); | ||
|
|
||
| var filenameRegex = new Regex(_configuration.GetValue( | ||
| DopplerSecurityDefaults.PUBLIC_KEYS_FILENAME_CONFIG_KEY, | ||
| DopplerSecurityDefaults.PUBLIC_KEYS_FILENAME_REGEX_DEFAULT_CONFIG_VALUE)); | ||
|
|
||
| var files = _fileProvider.GetDirectoryContents(path) | ||
| .Where(x => !x.IsDirectory && filenameRegex.IsMatch(x.Name)); | ||
|
|
||
| var publicKeys = files | ||
| .Select(ReadToEnd) | ||
| .Select(ParseXmlString) | ||
| .ToArray(); | ||
|
|
||
| options.SigningKeys = publicKeys; | ||
| } | ||
| } | ||
| } |
10 changes: 10 additions & 0 deletions
10
Doppler.HelloMicroservice/DopplerSecurity/DopplerAuthorizationRequirement.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,10 @@ | ||
| using Microsoft.AspNetCore.Authorization; | ||
|
|
||
| namespace Doppler.HelloMicroservice.DopplerSecurity | ||
| { | ||
| public class DopplerAuthorizationRequirement : IAuthorizationRequirement | ||
| { | ||
| public bool AllowSuperUser { get; init; } | ||
| public bool AllowOwnResource { get; init; } | ||
| } | ||
| } |
11 changes: 11 additions & 0 deletions
11
Doppler.HelloMicroservice/DopplerSecurity/DopplerSecurityDefaults.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,11 @@ | ||
| namespace Doppler.HelloMicroservice.DopplerSecurity | ||
| { | ||
| public static class DopplerSecurityDefaults | ||
| { | ||
| public const string PUBLIC_KEYS_FOLDER_CONFIG_KEY = "DopplerSecurity:PublicKeysFolder"; | ||
| public const string PUBLIC_KEYS_FOLDER_DEFAULT_CONFIG_VALUE = "public-keys"; | ||
| public const string PUBLIC_KEYS_FILENAME_CONFIG_KEY = @"DopplerSecurity:PublicKeysFilenameRegex"; | ||
| public const string PUBLIC_KEYS_FILENAME_REGEX_DEFAULT_CONFIG_VALUE = "\\.xml$"; | ||
| public const string SUPERUSER_JWT_KEY = "isSU"; | ||
| } | ||
| } |
10 changes: 10 additions & 0 deletions
10
Doppler.HelloMicroservice/DopplerSecurity/DopplerSecurityOptions.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,10 @@ | ||
| using Microsoft.IdentityModel.Tokens; | ||
| using System.Collections.Generic; | ||
|
|
||
| namespace Doppler.HelloMicroservice.DopplerSecurity | ||
| { | ||
| public class DopplerSecurityOptions | ||
| { | ||
| public IEnumerable<SecurityKey> SigningKeys { get; set; } = new SecurityKey[0]; | ||
| } | ||
| } |
75 changes: 75 additions & 0 deletions
75
Doppler.HelloMicroservice/DopplerSecurity/DopplerSecurityServiceCollectionExtensions.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,75 @@ | ||
| using Doppler.HelloMicroservice.DopplerSecurity; | ||
| using Microsoft.AspNetCore.Authentication.JwtBearer; | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.Extensions.Options; | ||
| using Microsoft.IdentityModel.Tokens; | ||
|
|
||
| namespace Microsoft.Extensions.DependencyInjection | ||
| { | ||
| public static class DopplerSecurityServiceCollectionExtensions | ||
| { | ||
| public static IServiceCollection AddDopplerSecurity(this IServiceCollection services) | ||
| { | ||
| services.AddSingleton<IAuthorizationHandler, IsSuperUserAuthorizationHandler>(); | ||
| services.AddSingleton<IAuthorizationHandler, IsOwnResourceAuthorizationHandler>(); | ||
|
|
||
| services.ConfigureOptions<ConfigureDopplerSecurityOptions>(); | ||
|
|
||
| services.AddOptions<AuthorizationOptions>() | ||
| .Configure(o => | ||
| { | ||
| var simpleAuthenticationPolicy = new AuthorizationPolicyBuilder() | ||
| .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) | ||
| .RequireAuthenticatedUser() | ||
| .Build(); | ||
|
|
||
| var onlySuperUserPolicy = new AuthorizationPolicyBuilder() | ||
| .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) | ||
| .AddRequirements(new DopplerAuthorizationRequirement() | ||
| { | ||
| AllowSuperUser = true | ||
| }) | ||
| .RequireAuthenticatedUser() | ||
| .Build(); | ||
|
|
||
| var ownResourceOrSuperUserPolicy = new AuthorizationPolicyBuilder() | ||
| .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) | ||
| .AddRequirements(new DopplerAuthorizationRequirement() | ||
| { | ||
| AllowSuperUser = true, | ||
| AllowOwnResource = true | ||
| }) | ||
| .RequireAuthenticatedUser() | ||
| .Build(); | ||
|
|
||
| // TODO: I would like to use ownResourceOrSuperUserPolicy as the default policy, but I | ||
| // cannot override a more restrictive policy with a less restrictive one. So, | ||
| // for the moment, we have to be carefull and chooses the right one for each | ||
| // controller. | ||
| o.DefaultPolicy = simpleAuthenticationPolicy; | ||
|
|
||
| o.AddPolicy(Policies.ONLY_SUPERUSER, onlySuperUserPolicy); | ||
| o.AddPolicy(Policies.OWN_RESOURCE_OR_SUPERUSER, ownResourceOrSuperUserPolicy); | ||
| }); | ||
|
|
||
| services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme) | ||
| .Configure<IOptions<DopplerSecurityOptions>>((o, securityOptions) => | ||
| { | ||
| o.SaveToken = true; | ||
| o.TokenValidationParameters = new TokenValidationParameters() | ||
| { | ||
| IssuerSigningKeys = securityOptions.Value.SigningKeys, | ||
| ValidateIssuer = false, | ||
| ValidateAudience = false, | ||
| }; | ||
| }); | ||
|
|
||
| services.AddAuthentication() | ||
| .AddJwtBearer(); | ||
|
|
||
| services.AddAuthorization(); | ||
|
|
||
| return services; | ||
| } | ||
| } | ||
| } | ||
82 changes: 82 additions & 0 deletions
82
Doppler.HelloMicroservice/DopplerSecurity/IsOwnResourceAuthorizationHandler.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,82 @@ | ||
|
|
||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.Extensions.Logging; | ||
| using System.Security.Claims; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.AspNetCore.Mvc.Filters; | ||
| using Microsoft.AspNetCore.Routing; | ||
| using Microsoft.AspNetCore.Http; | ||
|
|
||
| namespace Doppler.HelloMicroservice.DopplerSecurity | ||
| { | ||
| public class IsOwnResourceAuthorizationHandler : AuthorizationHandler<DopplerAuthorizationRequirement> | ||
| { | ||
| private readonly ILogger<IsOwnResourceAuthorizationHandler> _logger; | ||
|
|
||
| public IsOwnResourceAuthorizationHandler(ILogger<IsOwnResourceAuthorizationHandler> logger) | ||
| { | ||
| _logger = logger; | ||
| } | ||
|
|
||
| protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DopplerAuthorizationRequirement requirement) | ||
| { | ||
| if (requirement.AllowOwnResource && IsOwnResource(context)) | ||
| { | ||
| context.Succeed(requirement); | ||
| } | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private bool IsOwnResource(AuthorizationHandlerContext context) | ||
| { | ||
| if (!TryGetRouteData(context, out var routeData)) | ||
| { | ||
| _logger.LogError("Is not possible access to Resource information. Type of context.Resource: {ResourceType}", context.Resource?.GetType().Name ?? "null"); | ||
| return false; | ||
| } | ||
|
|
||
| if (routeData.Values.TryGetValue("accountId", out var accountId) && accountId?.ToString() == GetTokenNameIdentifier(context.User)) | ||
| { | ||
| // TODO: In case of using different public keys, for example Doppler and Relay, | ||
| // it is necessary to check token Issuer information, to validate right origin. | ||
| return true; | ||
| } | ||
|
|
||
| if (routeData.Values.TryGetValue("accountname", out var accountname) && accountname?.ToString() == GetTokenUniqueName(context.User)) | ||
| { | ||
| // TODO: In case of using different public keys, for example Doppler and Relay, | ||
| // it is necessary to check token Issuer information, to validate right origin. | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static string GetTokenUniqueName(ClaimsPrincipal user) => | ||
| user.FindFirst(c => c.Type == ClaimTypes.Name)?.Value; | ||
|
|
||
| private static string GetTokenNameIdentifier(ClaimsPrincipal user) => | ||
| user.FindFirst(c => c.Type == ClaimTypes.NameIdentifier)?.Value; | ||
|
|
||
| private static bool TryGetRouteData(AuthorizationHandlerContext context, out RouteData routeData) | ||
| { | ||
| // In my local environment with .NET 5 | ||
| if (context.Resource is HttpContext httpContext) | ||
| { | ||
| routeData = httpContext.GetRouteData(); | ||
| return true; | ||
| } | ||
|
|
||
| // ASP.NET Core 2? | ||
| if (context.Resource is AuthorizationFilterContext authorizationFilterContext) | ||
| { | ||
| routeData = authorizationFilterContext.RouteData; | ||
| return true; | ||
| } | ||
|
|
||
| routeData = null; | ||
| return false; | ||
| } | ||
| } | ||
| } |
48 changes: 48 additions & 0 deletions
48
Doppler.HelloMicroservice/DopplerSecurity/IsSuperUserAuthorizationHandler.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,48 @@ | ||
| using Microsoft.AspNetCore.Authorization; | ||
| using Microsoft.Extensions.Logging; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using System.Security.Claims; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Doppler.HelloMicroservice.DopplerSecurity | ||
| { | ||
| public class IsSuperUserAuthorizationHandler : AuthorizationHandler<DopplerAuthorizationRequirement> | ||
| { | ||
| private readonly ILogger<IsSuperUserAuthorizationHandler> _logger; | ||
|
|
||
| public IsSuperUserAuthorizationHandler(ILogger<IsSuperUserAuthorizationHandler> logger) | ||
| { | ||
| _logger = logger; | ||
| } | ||
|
|
||
| protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DopplerAuthorizationRequirement requirement) | ||
| { | ||
| if (requirement.AllowSuperUser && IsSuperUser(context)) | ||
| { | ||
| context.Succeed(requirement); | ||
| } | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private bool IsSuperUser(AuthorizationHandlerContext context) | ||
| { | ||
| if (!context.User.HasClaim(c => c.Type.Equals(DopplerSecurityDefaults.SUPERUSER_JWT_KEY))) | ||
| { | ||
| _logger.LogDebug("The token hasn't super user permissions."); | ||
| return false; | ||
| } | ||
|
|
||
| var isSuperUser = bool.Parse(context.User.FindFirst(c => c.Type.Equals(DopplerSecurityDefaults.SUPERUSER_JWT_KEY)).Value); | ||
| if (isSuperUser) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| _logger.LogDebug("The token super user permissions is false."); | ||
| return false; | ||
| } | ||
| } | ||
| } |
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 @@ | ||
| namespace Doppler.HelloMicroservice.DopplerSecurity | ||
| { | ||
| public static class Policies | ||
| { | ||
| public const string ONLY_SUPERUSER = nameof(ONLY_SUPERUSER); | ||
| public const string OWN_RESOURCE_OR_SUPERUSER = nameof(OWN_RESOURCE_OR_SUPERUSER); | ||
| } | ||
| } |
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.
@ms-darianbenito this what we were talking about today.