├── InvisibleApi ├── Resources │ └── api.png ├── Models │ └── InvisibleApiConfigurations │ │ └── InvisibleApiConfiguration.cs ├── Extensions │ └── InvisibleApiApplicationBuilderExtension.cs ├── License.txt ├── InvisibleApi.csproj └── Middlewares │ └── InvisibleApiMiddleware.cs ├── InvisibleApi.Infrastructure.Build ├── InvisibleApi.Infrastructure.Build.csproj └── Program.cs ├── .github └── workflows │ └── dotnet.yml ├── InvisibleApi.Tests.Unit ├── InvisibleApi.Tests.Unit.csproj └── Middlewares │ └── InvisibleApiMiddlewareTests.cs ├── InvisibleApi.sln ├── .gitattributes ├── readme.md └── .gitignore /InvisibleApi/Resources/api.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hassanhabib/InvisibleApi/HEAD/InvisibleApi/Resources/api.png -------------------------------------------------------------------------------- /InvisibleApi.Infrastructure.Build/InvisibleApi.Infrastructure.Build.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: .Net 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - master 9 | jobs: 10 | build: 11 | runs-on: windows-2019 12 | steps: 13 | - name: Check Out 14 | uses: actions/checkout@v2 15 | - name: Setup .Net 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 6.0.101 19 | include-prerelease: true 20 | - name: Restore 21 | run: dotnet restore 22 | - name: Build 23 | run: dotnet build --no-restore 24 | - name: Test 25 | run: dotnet test --no-build --verbosity normal 26 | -------------------------------------------------------------------------------- /InvisibleApi/Models/InvisibleApiConfigurations/InvisibleApiConfiguration.cs: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------- 2 | // Copyright (c) Hassan Habib All rights reserved. 3 | // Licensed under the MIT License. 4 | // See License.txt in the project root for license information. 5 | // --------------------------------------------------------------- 6 | 7 | namespace InvisibleApi.Models.InvisibleApiConfigurations 8 | { 9 | public class InvisibleApiConfiguration 10 | { 11 | public string HttpVerb { get; set; } 12 | public string Endpoint { get; set; } 13 | public string Header { get; set; } 14 | public string Value { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /InvisibleApi/Extensions/InvisibleApiApplicationBuilderExtension.cs: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------- 2 | // Copyright (c) Hassan Habib All rights reserved. 3 | // Licensed under the MIT License. 4 | // See License.txt in the project root for license information. 5 | // --------------------------------------------------------------- 6 | 7 | using System.Collections.Generic; 8 | using InvisibleApi.Middlewares; 9 | using InvisibleApi.Models.InvisibleApiConfigurations; 10 | using Microsoft.AspNetCore.Builder; 11 | 12 | namespace InvisibleApi.Extensions 13 | { 14 | public static class InvisibleApiApplicationBuilderExtension 15 | { 16 | public static IApplicationBuilder UseInvisibleApis( 17 | this IApplicationBuilder app, 18 | List invisibleApiDetails) => 19 | app.UseMiddleware(invisibleApiDetails); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /InvisibleApi.Tests.Unit/InvisibleApi.Tests.Unit.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /InvisibleApi/License.txt: -------------------------------------------------------------------------------- 1 | InvisibleApi - .NET Standard 2.1 Library 2 | 3 | Copyright (c) 2021 Hassan Habib All rights reserved. 4 | 5 | Material in this repository is made available under the following terms: 6 | 1. Code is licensed under the MIT license, reproduced below. 7 | 2. Documentation is licensed under the Creative Commons Attribution 3.0 United States (Unported) License. 8 | The text of the license can be found here: http://creativecommons.org/licenses/by/3.0/legalcode 9 | 10 | The MIT License (MIT) 11 | 12 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 13 | associated documentation files (the "Software"), to deal in the Software without restriction, 14 | including without limitation the rights to use, copy, modify, merge, publish, distribute, 15 | sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 16 | furnished to do so, subject to the following conditions: 17 | 18 | The above copyright notice and this permission notice shall be included in all copies or substantial 19 | portions of the Software. 20 | 21 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 22 | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES 24 | OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 25 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /InvisibleApi/InvisibleApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 0.0.1 6 | Hassan Habib 7 | Hassan Habib 8 | InvisibleApi is a .NET Standard library developed to add an extra layer of security to protect your existing API endpoints from scanning or discovery, especially if they were developed for internal use only. 9 | License.txt 10 | api.png 11 | Github 12 | InvisibleApi 13 | Initial Release 14 | true 15 | true 16 | https://github.com/hassanhabib/InvisibleApi 17 | https://github.com/hassanhabib/InvisibleApi 18 | Copyright (c) Hassan Habib 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | True 28 | 29 | 30 | 31 | True 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /InvisibleApi/Middlewares/InvisibleApiMiddleware.cs: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------- 2 | // Copyright (c) Hassan Habib All rights reserved. 3 | // Licensed under the MIT License. 4 | // See License.txt in the project root for license information. 5 | // --------------------------------------------------------------- 6 | 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | using InvisibleApi.Models.InvisibleApiConfigurations; 11 | using Microsoft.AspNetCore.Http; 12 | 13 | namespace InvisibleApi.Middlewares 14 | { 15 | public class InvisibleApiMiddleware 16 | { 17 | private readonly RequestDelegate next; 18 | private readonly List invisibleApiConfigurations; 19 | 20 | public InvisibleApiMiddleware( 21 | List invisibleApiConfigurations, 22 | RequestDelegate next) 23 | { 24 | this.invisibleApiConfigurations = invisibleApiConfigurations; 25 | this.next = next; 26 | } 27 | 28 | public async Task InvokeAsync(HttpContext context) 29 | { 30 | if (IsApiConfigurationMatchOrNotConfigured(context.Request) is false) 31 | { 32 | context.Response.StatusCode = StatusCodes.Status404NotFound; 33 | } 34 | else 35 | { 36 | await next(context); 37 | } 38 | } 39 | 40 | private bool IsApiConfigurationMatchOrNotConfigured(HttpRequest request) 41 | { 42 | InvisibleApiConfiguration invisibleEndpointConfiguration = 43 | this.invisibleApiConfigurations.FirstOrDefault(apiDetails => 44 | apiDetails.Endpoint == request.Path 45 | && apiDetails.HttpVerb == request.Method); 46 | 47 | if (invisibleEndpointConfiguration is { Endpoint: string endpoint }) 48 | { 49 | return this.invisibleApiConfigurations.Any(configuration => 50 | configuration.HttpVerb == request.Method 51 | && configuration.Endpoint == endpoint 52 | && request.Headers[configuration.Header] == configuration.Value); 53 | } 54 | 55 | return true; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /InvisibleApi.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31808.319 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InvisibleApi", "InvisibleApi\InvisibleApi.csproj", "{75B02BE9-4EFB-4D7A-B09B-8387995DCDED}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InvisibleApi.Tests.Unit", "InvisibleApi.Tests.Unit\InvisibleApi.Tests.Unit.csproj", "{FDE39D63-E694-4847-81AB-592022EF4A5C}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C74673A8-CEFB-4B33-9C93-0415BCE4A61E}" 11 | ProjectSection(SolutionItems) = preProject 12 | readme.md = readme.md 13 | EndProjectSection 14 | EndProject 15 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InvisibleApi.Infrastructure.Build", "InvisibleApi.Infrastructure.Build\InvisibleApi.Infrastructure.Build.csproj", "{EA561D35-78C9-4BC3-8529-631DDE3A055A}" 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {75B02BE9-4EFB-4D7A-B09B-8387995DCDED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {75B02BE9-4EFB-4D7A-B09B-8387995DCDED}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {75B02BE9-4EFB-4D7A-B09B-8387995DCDED}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {75B02BE9-4EFB-4D7A-B09B-8387995DCDED}.Release|Any CPU.Build.0 = Release|Any CPU 27 | {FDE39D63-E694-4847-81AB-592022EF4A5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {FDE39D63-E694-4847-81AB-592022EF4A5C}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {FDE39D63-E694-4847-81AB-592022EF4A5C}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {FDE39D63-E694-4847-81AB-592022EF4A5C}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {EA561D35-78C9-4BC3-8529-631DDE3A055A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {EA561D35-78C9-4BC3-8529-631DDE3A055A}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {EA561D35-78C9-4BC3-8529-631DDE3A055A}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {EA561D35-78C9-4BC3-8529-631DDE3A055A}.Release|Any CPU.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(SolutionProperties) = preSolution 37 | HideSolutionNode = FALSE 38 | EndGlobalSection 39 | GlobalSection(ExtensibilityGlobals) = postSolution 40 | SolutionGuid = {6F4268ED-2296-46A5-A23C-77ADA68E633E} 41 | EndGlobalSection 42 | EndGlobal 43 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /InvisibleApi.Infrastructure.Build/Program.cs: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------- 2 | // Copyright (c) Hassan Habib All rights reserved. 3 | // Licensed under the MIT License. 4 | // See License.txt in the project root for license information. 5 | // --------------------------------------------------------------- 6 | 7 | using System.Collections.Generic; 8 | using ADotNet.Clients; 9 | using ADotNet.Models.Pipelines.GithubPipelines.DotNets; 10 | using ADotNet.Models.Pipelines.GithubPipelines.DotNets.Tasks; 11 | using ADotNet.Models.Pipelines.GithubPipelines.DotNets.Tasks.SetupDotNetTaskV1s; 12 | 13 | namespace InvisibleApi.Infrastructure.Build 14 | { 15 | internal class Program 16 | { 17 | static void Main(string[] args) 18 | { 19 | var adotNetClient = new ADotNetClient(); 20 | 21 | var githubPipeline = new GithubPipeline 22 | { 23 | Name = ".Net", 24 | 25 | OnEvents = new Events 26 | { 27 | Push = new PushEvent 28 | { 29 | Branches = new string[] { "master" } 30 | }, 31 | PullRequest = new PullRequestEvent 32 | { 33 | Branches = new string[] { "master" } 34 | } 35 | }, 36 | 37 | Jobs = new Jobs 38 | { 39 | Build = new BuildJob 40 | { 41 | RunsOn = BuildMachines.Windows2019, 42 | 43 | Steps = new List 44 | { 45 | new CheckoutTaskV2 46 | { 47 | Name = "Check Out" 48 | }, 49 | 50 | new SetupDotNetTaskV1 51 | { 52 | Name = "Setup .Net", 53 | 54 | TargetDotNetVersion = new TargetDotNetVersion 55 | { 56 | DotNetVersion = "6.0.101", 57 | IncludePrerelease = true 58 | } 59 | }, 60 | 61 | new RestoreTask 62 | { 63 | Name = "Restore" 64 | }, 65 | 66 | new DotNetBuildTask 67 | { 68 | Name = "Build" 69 | }, 70 | 71 | new TestTask 72 | { 73 | Name = "Test" 74 | } 75 | } 76 | } 77 | } 78 | }; 79 | 80 | adotNetClient.SerializeAndWriteToFile(githubPipeline, "../../../../.github/workflows/dotnet.yml"); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /InvisibleApi.Tests.Unit/Middlewares/InvisibleApiMiddlewareTests.cs: -------------------------------------------------------------------------------- 1 | // --------------------------------------------------------------- 2 | // Copyright (c) Hassan Habib All rights reserved. 3 | // Licensed under the MIT License. 4 | // See License.txt in the project root for license information. 5 | // --------------------------------------------------------------- 6 | 7 | using System.Collections.Generic; 8 | using System.Threading.Tasks; 9 | using FluentAssertions; 10 | using InvisibleApi.Middlewares; 11 | using InvisibleApi.Models.InvisibleApiConfigurations; 12 | using Microsoft.AspNetCore.Http; 13 | using Microsoft.Extensions.Primitives; 14 | using Moq; 15 | using Tynamix.ObjectFiller; 16 | using Xunit; 17 | 18 | namespace InvisibleApi.Tests.Unit.Middlewares 19 | { 20 | public class InvisibleApiMiddlewareTests 21 | { 22 | [Fact] 23 | public async Task ShouldHitApiEndpointIfEndpointIsntConfiguredAsInvisible() 24 | { 25 | // given 26 | var mockedDelegate = new Mock(); 27 | var context = new Mock(); 28 | 29 | // when 30 | var invisibleMiddleware = new InvisibleApiMiddleware( 31 | new List(), 32 | mockedDelegate.Object); 33 | 34 | await invisibleMiddleware.InvokeAsync(context.Object); 35 | 36 | // then 37 | mockedDelegate.Verify(requestDelegate => 38 | requestDelegate(context.Object), 39 | Times.Once); 40 | } 41 | 42 | [Fact] 43 | public async Task ShouldHitApiEndpointIfEndpointIsConfiguredProperly() 44 | { 45 | // given 46 | string randomEndpoint = $"/{GetRandomString()}"; 47 | string randomHeaderName = GetRandomString(); 48 | string randomHeaderValue = GetRandomString(); 49 | string randomHttpVerb = GetRandomString(); 50 | var requestDelegateMock = new Mock(); 51 | var contextMock = new Mock(); 52 | var httpRequestMock = new Mock(); 53 | var httpResponseMock = new Mock(); 54 | 55 | httpRequestMock.SetupGet(request => request.Path) 56 | .Returns(randomEndpoint); 57 | 58 | httpRequestMock.SetupGet(request => request.Headers) 59 | .Returns(new HeaderDictionary(new Dictionary 60 | { 61 | { randomHeaderName, randomHeaderValue} 62 | })); 63 | 64 | httpRequestMock.SetupGet(request => request.Method) 65 | .Returns(randomHttpVerb); 66 | 67 | contextMock.SetupGet(context => context.Request) 68 | .Returns(httpRequestMock.Object); 69 | 70 | contextMock.SetupGet(context => context.Response) 71 | .Returns(httpResponseMock.Object); 72 | 73 | // when 74 | var invisibleMiddleware = new InvisibleApiMiddleware( 75 | new List 76 | { 77 | new InvisibleApiConfiguration 78 | { 79 | HttpVerb = randomHttpVerb, 80 | Endpoint = randomEndpoint, 81 | Header = randomHeaderName, 82 | Value = randomHeaderValue 83 | } 84 | }, 85 | requestDelegateMock.Object); 86 | 87 | await invisibleMiddleware.InvokeAsync(contextMock.Object); 88 | 89 | // then 90 | requestDelegateMock.Verify(requestDelegate => 91 | requestDelegate(contextMock.Object), 92 | Times.Once); 93 | } 94 | 95 | [Fact] 96 | public async Task ShouldReturnNotFoundIfHeaderValueDontMatchInvisibleConfiguration() 97 | { 98 | // given 99 | string randomEndpoint = $"/{GetRandomString()}"; 100 | string randomHeaderName = GetRandomString(); 101 | string randomHeaderValue = GetRandomString(); 102 | string randomHttpVerb = GetRandomString(); 103 | var requestDelegateMock = new Mock(); 104 | var contextMock = new Mock(); 105 | var httpRequestMock = new Mock(); 106 | var httpResponseMock = new Mock(); 107 | 108 | httpRequestMock.SetupGet(request => request.Path) 109 | .Returns(randomEndpoint); 110 | 111 | httpRequestMock.SetupGet(request => request.Headers) 112 | .Returns(new HeaderDictionary(new Dictionary 113 | { 114 | { randomHeaderName, randomHeaderValue} 115 | })); 116 | 117 | httpRequestMock.SetupGet(request => request.Method) 118 | .Returns(randomHttpVerb); 119 | 120 | contextMock.SetupGet(context => context.Request) 121 | .Returns(httpRequestMock.Object); 122 | 123 | httpResponseMock.SetupAllProperties(); 124 | 125 | contextMock.SetupGet(context => context.Response) 126 | .Returns(httpResponseMock.Object); 127 | 128 | // when 129 | var invisibleMiddleware = new InvisibleApiMiddleware( 130 | new List 131 | { 132 | new InvisibleApiConfiguration 133 | { 134 | HttpVerb = randomHttpVerb, 135 | Endpoint = randomEndpoint, 136 | Header = GetRandomString(), 137 | Value = GetRandomString() 138 | } 139 | }, 140 | requestDelegateMock.Object); 141 | 142 | await invisibleMiddleware.InvokeAsync(contextMock.Object); 143 | 144 | // the 145 | httpResponseMock.Object.StatusCode.Should() 146 | .Be(StatusCodes.Status404NotFound); 147 | 148 | requestDelegateMock.Verify(requestDelegate => 149 | requestDelegate(contextMock.Object), 150 | Times.Never); 151 | } 152 | 153 | private static string GetRandomString() => 154 | new MnemonicString().GetValue(); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | # InvisibleApi 6 | I designed & developed this library to help add an extra layer of security for private API endpoints that can only be used/visible to internal consumers and testing frameworks. 7 | 8 | ## Introduction 9 | When designing APIs there are so rules that govern APIs control of their own resources. For instance, an API endpoint that posts `Student` model and deletes that model might be allowed to publically expose a `POST` endpoint to register students but it shouldn't allow external consumers to delete records from its storage. 10 | 11 | What that basically means is that if we are running End-to-End testing on a particular API endpoint, we may need to clean up all test data automatically after the test is over. But in order for that to happen engineers either have to give access to the test bits to the database storage or expose public API endpoints to delete a particular resource by its `Id`. 12 | 13 | ![image](https://user-images.githubusercontent.com/1453985/117775766-ad6f8880-b1ef-11eb-8092-b1b09673bd10.png) 14 | 15 | The problem with allowing any resource other than the owning API to access storage is that it puts the entire resource at risk of deadlocks, overwrites and many other issues that occur when two difference clients are writing to the same storage resource. 16 | 17 | Using In-Memory databases unfortunatley doesn't give the guarantee that a running instance in production is in healthy state from an integration standpoint. 18 | 19 | A solution that allows proper way of accessing and deleting resources without having to expose private endpoints that offer non-public capabilities is required to execute a successful end-to-end testing process. 20 | 21 | ## Extra Layer of Security 22 | There are two very common ways hackers today gain access to particular APIs: 23 | 24 | ### Compromised Client 25 | Hackers may compromise an existing client or consumer of your API to intercept communications, steal access token and identify endpoints in your system that can be attacked or compromised to gain access to your internal data. 26 | 27 | Internal testing systems require access to particular endpoints that are not meant for public access - but following a standardized API naming convention may make it easier for a hacker to predict that an api endpoint such as `POST` `/api/students` will have its equivelant of delete operation such as `Delete` `api/students/{studentId}`. 28 | 29 | ### Network Scanning/Discovery 30 | The other capability hackers may use to discover weakpoints in your system is to scan your network for open ports, API endpoints or any other vunlerabilities that may expose an avaialble resource or access gateway to your system. 31 | 32 | The issue with returning a `403 Unauthorized` error is that it simply gives a challenge to hackers to try and breakthrough the protected endpoint. 33 | 34 | But if a particular endpoint that was discovered by scanning the network returned `404 NotFound` its more likely for a hacker or an automated discovery system to move along without having to think twice about attempting to access that endpoint again. 35 | 36 | That is simply because the endpoint without the proper headers will masquerade itself as invisible - returning `404 NotFound` to indicate there's nothing to access at that particular point. 37 | 38 | 39 | ## The Solution 40 | Invisible API allows ASP.NET Core API developers to configure particular endpoints to become invisible unless the request contained very specific header values. 41 | 42 | Here's how it works: 43 | 44 | ## Setting Things Up 45 | Engineering and Development experiences were the top priority in the process of building this library. You will notice at first glance the simplicity of setting things up. Let's get started! 46 | 47 | ### Nuget Package 48 | First of all make sure you navigate and install InvisibleApi from nuget.org or from Visual Studio 49 | 50 | ### Setting Up InvisibleApi Configurations 51 | When I designed this library, I wanted to allow engineers to have all their invisible APIs configurations sitting in one place so its easier to manage, here's you you can do that: 52 | 53 | In your `Startup.cs` file go ahead and add your invisible apis configurations as follows: 54 | 55 | ```csharp 56 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 57 | { 58 | ... 59 | app.UseInvisibleApis(new List 60 | { 61 | new InvisibleApiConfiguration 62 | { 63 | Endpoint = "/api/home", 64 | Header = "Hush", 65 | Value = "I'm a good guy", 66 | HttpVerb = "GET" 67 | } 68 | }); 69 | 70 | ... 71 | } 72 | ``` 73 | 74 | The invisible API configuration will give you the capability to configure multiple API endpoints, with multiple HttpVerbs all in one spot. 75 | 76 | You can also assign multiple headers and header values for the same API endpoint - whichever one is used will unveil your API endpoint. 77 | 78 | 79 | ### Testing 80 | Now, if we hit the `GET api/home` endpoint with no specified Invisible API configurations the outcome would be as follows: 81 | 82 | #### Without Headers (Invisible) 83 | ![image](https://user-images.githubusercontent.com/1453985/117785474-78683380-b1f9-11eb-9cdd-8f8d612a9f38.png) 84 | 85 | #### With Headers (Visible) 86 | ![image](https://user-images.githubusercontent.com/1453985/117785647-a483b480-b1f9-11eb-9e70-7bf3a1411522.png) 87 | 88 | As you can see above, the API endpoint makes itself invisible (404 Not Found) if the header values are not provided, and then it shows itself if the configured header values are provided. 89 | 90 | 91 | ### Notice 92 | It's important to understand that the InvisibleApi mechanism doesn't replace the existing practices of security patterns - it's important to understand that it only adds an additional layer of security on existing API endpoints in case the token was compromised for whatever reason or the endpoint was discoverd through scanning or discovery. 93 | 94 | ## How Does it Work? 95 | If you haven't checked the source code already, InvisibleApi takes advantage of the powerful features of ASP.NET Middleware to intercept any incoming requests before they actually hit your API endpoints and decide whether to allow the request to go through to your resources/endpoints or not. 96 | 97 | ## Final Note 98 | This library is experimental - use at your own risk, but feel free to reach out and ask any questions if you have any, or simply just open an issue on this repo and I will take a look at it as soon as possible. 99 | 100 | You can also email me on the following address: hassanhabib@live.com -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd --------------------------------------------------------------------------------