/// <summary> /// /search/ and /characters/{character_id}/search/ /// </summary> /// <param name="search">The string to search on</param> /// <param name="categories">Type of entities to search for</param> /// <param name="isStrict">Whether the search should be a strict match</param> /// <param name="language">Language to use in the response</param> /// <returns></returns> public async Task <EsiResponse <SearchResults> > Query(SearchType type, string search, SearchCategory categories, bool isStrict = false, string language = "en-us") { var categoryList = categories.ToEsiValue(); var endpoint = "/search/"; Dictionary <string, string> replacements = null; RequestSecurity security = RequestSecurity.Public; if (type == SearchType.Character) { security = RequestSecurity.Authenticated; replacements = new Dictionary <string, string>() { { "character_id", character_id.ToString() } }; endpoint = "/characters/{character_id}/search/"; } var response = await Execute <SearchResults>(_client, _config, security, RequestMethod.Get, endpoint, replacements, parameters : new string[] { $"search={search}", $"categories={categoryList}", $"strict={isStrict}", $"language={language}" }, token : _data?.Token); return(response); }
public TestPathSetting(string path, PathMatchType matchType, bool ignoreCase, RequestSecurity security) { Path = path; MatchType = matchType; IgnoreCase = ignoreCase; Security = security; }
public TestPathSetting(string path, PathMatchType matchType, bool ignoreCase, RequestSecurity security) { Path = path; MatchType = matchType; IgnoreCase = ignoreCase; Security = security; }
public void EvaluateReturnsIgnoreAppropriatelyWhenRequestIsAjax() { // Arrange. var mockRequest = new Mock <HttpRequestBase>(); mockRequest.SetupGet(req => req.RawUrl).Returns("/getdata/"); var requestEvaluator = new RequestEvaluator(); // Act. RequestSecurity resultForNonAjaxRequest = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); var queryString = new NameValueCollection { { RequestEvaluator.XRequestedWithHeaderKey, RequestEvaluator.AjaxRequestHeaderValue } }; mockRequest.Setup(req => req.QueryString).Returns(queryString); RequestSecurity resultForAjaxRequest = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); _fixture.Settings.IgnoreAjaxRequests = false; RequestSecurity resultForAjaxRequestWithIgnoreOff = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); // Assert. Assert.NotEqual(RequestSecurity.Ignore, resultForNonAjaxRequest); Assert.Equal(RequestSecurity.Ignore, resultForAjaxRequest); Assert.NotEqual(RequestSecurity.Ignore, resultForAjaxRequestWithIgnoreOff); }
/// <summary> /// Processes a request. /// </summary> /// <param name="context">The context in which the request to process is running.</param> /// <param name="evaluatorCallback">A callback to a custom request evaluator.</param> public void Process(HttpContextBase context, RequestEvaluatorCallback evaluatorCallback) { Logger.Log("Begin request processing."); RequestSecurity expectedSecurity = EvaluateRequestViaCallbackOrEvaluator(context, evaluatorCallback); if (expectedSecurity == RequestSecurity.Ignore) { // No redirect is needed for a result of Ignore. EnrichResponse(context, _settings); Logger.Log("Expected security is Ignore; done.", Logger.LogLevel.Info); return; } string targetUrl = DetermineTargetUrl(context, expectedSecurity); if (string.IsNullOrEmpty(targetUrl)) { // No redirect is needed for a null/empty target URL. EnrichResponse(context, _settings); Logger.Log("No target URI determined; done.", Logger.LogLevel.Info); return; } Redirect(context, targetUrl); }
public void EvaluateReturnsIgnoreAppropriatelyWhenRequestPathIndicatesImage() { // Arrange. var pathsToTest = new[] { "/non-typical-image.psd", "/Media/Document.pdf", "/Images/SomeService/", "/Images/SomeService/?someKey=someValue", "/images/img-handler.ashx", "/images/img-handler.ashx?some-key=some-value", "/Manage/Images/indicator-alert.bmp", "/info/signs/sign1.gif", "/faavicon.ico", "/Media/logo.jpg", "/Media/other-logo.jpeg", "/SomeImage.png", "/drawings/machine.design.svg", "/Info/some-image.tiff", "/Info/another-image.tif", "/OtherResource.axd/resourceImage.webp", "/OddBall.xbm", "/Manage/Images/indicator-alert.bmp?someKey=someValue", "/info/signs/sign1.gif#hash", "/faavicon.ico?flag", "/Media/logo.jpg?some-key=some-value&other-key=other-value", "/Media/other-logo.jpeg?someKey=someValue#here", "/SomeImage.png?someKey=someValue&otherKey=otherValue#here-nor-there", "/drawings/machine.design.svg#hash.sub", "/Info/some-image.tiff?some.key=some.value", "/Info/another-image.tif?some.key=some.value#hash.sub", "/OtherResource.axd/resourceImage.webp?", "/OddBall.xbm?#" }; var results = new RequestSecurity[pathsToTest.Length]; var mockRequest = new Mock <HttpRequestBase>(); var requestEvaluator = new RequestEvaluator(); // Act. for (int index = 0; index < pathsToTest.Length; index++) { string path = pathsToTest[index]; mockRequest.SetupGet(req => req.RawUrl).Returns(path); results[index] = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); } // Assert. for (int i = 0; i < 2; i++) { Assert.NotEqual(RequestSecurity.Ignore, results[i]); } for (int i = 2; i < results.Length; i++) { Assert.Equal(RequestSecurity.Ignore, results[i]); } }
/// <summary> /// Determines a target URL (if any) for this request, based on the expected security. /// </summary> /// <param name="context"></param> /// <param name="expectedSecurity"></param> /// <returns></returns> private string DetermineTargetUrl(HttpContextBase context, RequestSecurity expectedSecurity) { // Ensure the request matches the expected security. Logger.Log("Determining the URI for the expected security.", Logger.LogLevel.Info); ISecurityEvaluator securityEvaluator = SecurityEvaluatorFactory.Instance.Create(context, _settings); ISecurityEnforcer securityEnforcer = SecurityEnforcerFactory.Instance.Create(context, securityEvaluator); string targetUrl = securityEnforcer.GetUriForMatchedSecurityRequest(context.Request, context.Response, expectedSecurity, _settings); return targetUrl; }
/// <summary> /// Determines a target URL (if any) for this request, based on the expected security. /// </summary> /// <param name="context"></param> /// <param name="expectedSecurity"></param> /// <returns></returns> private string DetermineTargetUrl(HttpContextBase context, RequestSecurity expectedSecurity) { // Ensure the request matches the expected security. Logger.Log("Determining the URI for the expected security.", Logger.LogLevel.Info); ISecurityEvaluator securityEvaluator = SecurityEvaluatorFactory.Instance.Create(context, _settings); ISecurityEnforcer securityEnforcer = SecurityEnforcerFactory.Instance.Create(context, securityEvaluator); string targetUrl = securityEnforcer.GetUriForMatchedSecurityRequest(context.Request, context.Response, expectedSecurity, _settings); return(targetUrl); }
public void EvaluateReturnsInsecureWhenNoSettingsPathsMatchRequestPath() { // Arrange. var mockRequest = new Mock <HttpRequestBase>(); mockRequest.SetupGet(req => req.RawUrl).Returns("/Info/AboutUs.aspx"); var requestEvaluator = new RequestEvaluator(); // Act. RequestSecurity security = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); // Assert. Assert.Equal(RequestSecurity.Insecure, security); }
public void EvaluateReturnsIgnoreAppropriatelyWhenRequestPathIndicatesStyleSheet() { // Arrange. var pathsToTest = new[] { "/non-typical-image.psd", "/Media/Document.pdf", "/Styles/SomeService/", "/StyleSheets/SomeService/?someKey=someValue", "/styles/img-handler.ashx", "/stylesheets/img-handler.ashx?some-key=some-value", "/normalize.css", "/Media/Styles/Site.css", "/normalize.css?someKey=someValue", "/Media/Styles/Site.css#hash", "/normalize.css?flag", "/Media/Styles/Site.css?some-key=some-value&other-key=other-value", "/normalize.css?someKey=someValue#here", "/Media/Styles/Site.css?someKey=someValue&otherKey=otherValue#here-nor-there", "/normalize.alternative.css#hash.sub", "/Media/Styles/Site.css?some.key=some.value", "/normalize.css?some.key=some.value#hash.sub", "/Media/Styles/Site.css/resourceImage.webp?", "/normalize.css?#" }; var results = new RequestSecurity[pathsToTest.Length]; var mockRequest = new Mock <HttpRequestBase>(); var requestEvaluator = new RequestEvaluator(); // Act. for (int index = 0; index < pathsToTest.Length; index++) { string path = pathsToTest[index]; mockRequest.SetupGet(req => req.RawUrl).Returns(path); results[index] = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); } // Assert. for (int i = 0; i < 2; i++) { Assert.NotEqual(RequestSecurity.Ignore, results[i]); } for (int i = 2; i < results.Length; i++) { Assert.Equal(RequestSecurity.Ignore, results[i]); } }
public void EvaluateReturnsSecureWhenASecureSettingsPathMatchesRequestPath() { // Arrange. var mockRequest = new Mock <HttpRequestBase>(); mockRequest.SetupGet(req => req.RawUrl).Returns("/login/"); var requestEvaluator = new RequestEvaluator(); // Act. RequestSecurity security = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); // Assert. Assert.Equal(RequestSecurity.Secure, security); }
public void EvaluateReturnsIgnoreWhenModeIsOff() { // Arrange. var mockRequest = new Mock <HttpRequestBase>(); var settings = new Settings { Mode = Mode.Off }; var requestEvaluator = new RequestEvaluator(); // Act. RequestSecurity security = requestEvaluator.Evaluate(mockRequest.Object, settings); // Assert. Assert.Equal(RequestSecurity.Ignore, security); }
public void EvaluateReturnsIgnoreWhenModeIsLocalOnlyAndRequestIsRemote() { // Arrange. var mockRequest = new Mock <HttpRequestBase>(); mockRequest.SetupGet(req => req.IsLocal).Returns(false); var settings = new Settings { Mode = Mode.LocalOnly }; var requestEvaluator = new RequestEvaluator(); // Act. RequestSecurity security = requestEvaluator.Evaluate(mockRequest.Object, settings); // Assert. Assert.Equal(RequestSecurity.Ignore, security); }
/// <summary> /// Gets any URI for the specified request that ensures it is being accessed by the proper protocol, if a match is found in the settings. /// </summary> /// <param name="request">The request to ensure proper access for.</param> /// <param name="response">The response to use if a redirection or other output is necessary.</param> /// <param name="security">The security setting to match.</param> /// <param name="settings">The settings used for any redirection.</param> /// <returns>A URL that ensures the requested resources matches the specified security; or null if the current request already does.</returns> public string GetUriForMatchedSecurityRequest(HttpRequestBase request, HttpResponseBase response, RequestSecurity security, Settings settings) { string targetUrl = null; // Evaluate the request's security. Logger.Log("Determining if the connection is secure."); bool isSecureConnection = _securityEvaluator.IsSecureConnection(request, settings); if (security == RequestSecurity.Secure && !isSecureConnection || security == RequestSecurity.Insecure && isSecureConnection) { Logger.Log("Calculating the target URI to switch to."); // Determine the target protocol and get any base target URL from the settings. string targetProtocolScheme; string baseTargetUrl; if (security == RequestSecurity.Secure) { targetProtocolScheme = Uri.UriSchemeHttps; baseTargetUrl = settings.BaseSecureUri; } else { targetProtocolScheme = Uri.UriSchemeHttp; baseTargetUrl = settings.BaseInsecureUri; } if (string.IsNullOrEmpty(baseTargetUrl)) { // If there is no base target URI, just switch the protocol scheme of the current request's URI. // * Account for cookie-less sessions by applying the application modifier. targetUrl = targetProtocolScheme + Uri.SchemeDelimiter + request.Url.Authority + response.ApplyAppPathModifier(request.RawUrl); } else { // Build the appropriate URI based on the specified target URL. var uri = new StringBuilder(baseTargetUrl); // - Use the full request path, but remove any sub-application path. uri.Append(request.RawUrl); if (request.ApplicationPath.Length > 1) { uri.Remove(baseTargetUrl.Length, request.ApplicationPath.Length); } // Normalize the URI. uri.Replace("//", "/", baseTargetUrl.Length - 1, uri.Length - baseTargetUrl.Length); targetUrl = uri.ToString(); } } return targetUrl; }
public void EvaluateReturnsIgnoreAppropriatelyWhenRequestIsSystemHandler() { // Arrange. var pathsToTest = new[] { "/", "/Default.aspx", "/Info/AboutUs.aspx", "/info/aboutus/", "/Manage/DownloadThatFile.axd", "/Info/WebResource.axd?i=C3E19B2A-15F0-4174-A245-20F08C1DF4B8", "/OtherResource.axd/additional/info", "/trace.axd#details" }; var results = new RequestSecurity[pathsToTest.Length]; var mockRequest = new Mock <HttpRequestBase>(); var requestEvaluator = new RequestEvaluator(); // Act. for (int index = 0; index < pathsToTest.Length; index++) { string path = pathsToTest[index]; mockRequest.SetupGet(req => req.RawUrl).Returns(path); results[index] = requestEvaluator.Evaluate(mockRequest.Object, _fixture.Settings); } // Assert. for (int i = 0; i < 4; i++) { Assert.NotEqual(RequestSecurity.Ignore, results[i]); } for (int i = 4; i < results.Length; i++) { Assert.Equal(RequestSecurity.Ignore, results[i]); } }
public static async Task <EsiResponse <T> > Execute <T>(HttpClient client, EsiConfig config, RequestSecurity security, RequestMethod method, string endpoint, Dictionary <string, string> replacements = null, string[] parameters = null, object body = null, string token = null) { client.DefaultRequestHeaders.Clear(); var path = $"{method.ToString()}|{endpoint}"; var version = EndpointVersion[path]; if (replacements != null) { foreach (var property in replacements) { endpoint = endpoint.Replace($"{{{property.Key}}}", property.Value); } } var url = $"{config.EsiUrl}{version}{endpoint}?datasource={config.DataSource.ToEsiValue()}"; //Attach token to request header if this endpoint requires an authorized character if (security == RequestSecurity.Authenticated) { if (token == null) { throw new ArgumentException("The request endpoint requires SSO authentication and a Token has not been provided."); } client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } if (ETag != null) { client.DefaultRequestHeaders.Add("If-None-Match", $"\"{ETag}\""); ETag = null; } //Attach query string parameters if (parameters != null) { url += $"&{string.Join("&", parameters)}"; } //Serialize post body data HttpContent postBody = null; if (body != null) { postBody = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"); } //Get response from client based on request type //This is also where body variables will be created and attached as necessary HttpResponseMessage response = null; switch (method) { case RequestMethod.Delete: response = await client.DeleteAsync(url).ConfigureAwait(false); break; case RequestMethod.Get: response = await client.GetAsync(url).ConfigureAwait(false); break; case RequestMethod.Post: response = await client.PostAsync(url, postBody).ConfigureAwait(false); break; case RequestMethod.Put: response = await client.PutAsync(url, postBody).ConfigureAwait(false); break; } //Output final object var obj = new EsiResponse <T>(response, path, version); return(obj); }
/// <summary> /// Gets any URI for the specified request that ensures it is being accessed by the proper protocol, if a match is found in the settings. /// </summary> /// <param name="request">The request to ensure proper access for.</param> /// <param name="response">The response to use if a redirection or other output is necessary.</param> /// <param name="security">The security setting to match.</param> /// <param name="settings">The settings used for any redirection.</param> /// <returns>A URL that ensures the requested resources matches the specified security; or null if the current request already does.</returns> public string GetUriForMatchedSecurityRequest(HttpRequestBase request, HttpResponseBase response, RequestSecurity security, Settings settings) { string targetUrl = null; // Evaluate the request's security. Logger.Log("Determining if the connection is secure."); bool isSecureConnection = _securityEvaluator.IsSecureConnection(request, settings); if (security == RequestSecurity.Secure && !isSecureConnection || security == RequestSecurity.Insecure && isSecureConnection) { Logger.Log("Calculating the target URI to switch to."); // Determine the target protocol and get any base target URL from the settings. string targetProtocolScheme; string baseTargetUrl; if (security == RequestSecurity.Secure) { targetProtocolScheme = Uri.UriSchemeHttps; baseTargetUrl = settings.BaseSecureUri; } else { targetProtocolScheme = Uri.UriSchemeHttp; baseTargetUrl = settings.BaseInsecureUri; } if (string.IsNullOrEmpty(baseTargetUrl)) { // If there is no base target URI, just switch the protocol scheme of the current request's URI. // * Account for cookie-less sessions by applying the application modifier. targetUrl = targetProtocolScheme + Uri.SchemeDelimiter + request.Url.Authority + response.ApplyAppPathModifier(request.RawUrl); } else { // Build the appropriate URI based on the specified target URL. var uri = new StringBuilder(baseTargetUrl); // - Use the full request path, but remove any sub-application path. uri.Append(request.RawUrl); if (request.ApplicationPath.Length > 1) { uri.Remove(baseTargetUrl.Length, request.ApplicationPath.Length); } // Normalize the URI. uri.Replace("//", "/", baseTargetUrl.Length - 1, uri.Length - baseTargetUrl.Length); targetUrl = uri.ToString(); } } return(targetUrl); }