Skip to content

Commit

Permalink
Add ability to override HTTP request version; update UA string
Browse files Browse the repository at this point in the history
  • Loading branch information
arktronic-sep committed Nov 8, 2023
1 parent 7ab616a commit 9a03198
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 13 deletions.
3 changes: 2 additions & 1 deletion sama/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:8081",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"ASPNETCORE_ENVIRONMENT": "Development",
"DefaultHttpVersion": "10_OrHigher"
}
}
}
Expand Down
32 changes: 29 additions & 3 deletions sama/Services/HttpCheckService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using sama.Extensions;
using sama.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;

namespace sama.Services
Expand All @@ -12,13 +14,22 @@ public class HttpCheckService : ICheckService
{
private readonly SettingsService _settingsService;
private readonly CertificateValidationService _certService;
private readonly IConfiguration _configuration;
private readonly IServiceProvider _serviceProvider;

public HttpCheckService(SettingsService settingsService, CertificateValidationService certService, IServiceProvider serviceProvider)
private readonly string _appVersion;

private Version? _defaultRequestVersion;
private HttpVersionPolicy? _defaultVersionPolicy;

public HttpCheckService(SettingsService settingsService, CertificateValidationService certService, IConfiguration configuration, IServiceProvider serviceProvider)
{
_settingsService = settingsService;
_certService = certService;
_configuration = configuration;
_serviceProvider = serviceProvider;

_appVersion = typeof(Startup).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
}

public bool CanHandle(Endpoint endpoint)
Expand All @@ -40,11 +51,14 @@ public EndpointCheckResult Check(Endpoint endpoint)
return true;
};

message.Version = GetDefaultRequestVersion();
message.VersionPolicy = GetDefaultVersionPolicy();

var statusCodes = endpoint.GetHttpStatusCodes() ?? new List<int>();
if (statusCodes.Count > 0)
httpHandler.AllowAutoRedirect = false;

message.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
message.Headers.Add("User-Agent", $"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 SAMA/{_appVersion}");
message.Headers.Add("Accept", "text/html, application/xhtml+xml, */*");
client.Timeout = ClientTimeout;

Expand Down Expand Up @@ -105,6 +119,18 @@ public EndpointCheckResult Check(Endpoint endpoint)
}
}

private Version GetDefaultRequestVersion()
{
_defaultRequestVersion ??= Utility.GetConfiguredHttpRequestVersion(_configuration["DefaultHttpVersion"]);
return _defaultRequestVersion;
}

private HttpVersionPolicy GetDefaultVersionPolicy()
{
_defaultVersionPolicy ??= Utility.GetConfiguredHttpVersionPolicy(_configuration["DefaultHttpVersion"]);
return _defaultVersionPolicy.Value;
}

private TimeSpan ClientTimeout
{
get
Expand Down
10 changes: 8 additions & 2 deletions sama/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public Startup(IWebHostEnvironment env)
{
builder.AddJsonFile("/opt/sama-docker/appsettings.json", optional: true);
}
builder.AddEnvironmentVariables();
builder.AddEnvironmentVariables("SAMA_");
Configuration = builder.Build();
}

Expand Down Expand Up @@ -87,8 +87,10 @@ public void ConfigureServices(IServiceCollection services)
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger, IConfiguration configuration)
{
logger.LogInformation("SAMA is being configured...");

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand All @@ -112,6 +114,10 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
endpoints.MapControllerRoute("default", "{controller=Endpoints}/{action=IndexRedirect}/{id?}");
});

var httpRequestVersion = Utility.GetConfiguredHttpRequestVersion(configuration["DefaultHttpVersion"]);
var httpRequestPolicy = Utility.GetConfiguredHttpVersionPolicy(configuration["DefaultHttpVersion"]);
logger.LogInformation($"SAMA configuration is complete. HTTP requests are set to use version {httpRequestVersion} with policy {httpRequestPolicy}.");
}
}
}
45 changes: 44 additions & 1 deletion sama/Utility.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
namespace sama
using System;
using System.Net;
using System.Net.Http;

namespace sama
{
public class Utility
{
Expand All @@ -11,5 +15,44 @@ public static string KindString(Models.Endpoint.EndpointKind kind)
else
return "Unknown";
}

public static Version GetConfiguredHttpRequestVersion(string? configString)
{
var fallback = HttpVersion.Version11;

if (!string.IsNullOrWhiteSpace(configString) && configString.Contains('_'))
{
var versionPart = configString.Split('_')[0];
return versionPart switch
{
"10" => HttpVersion.Version10,
"11" => HttpVersion.Version11,
"20" => HttpVersion.Version20,
"30" => HttpVersion.Version30,
_ => fallback,
};
}

return fallback;
}

public static HttpVersionPolicy GetConfiguredHttpVersionPolicy(string? configString)
{
var fallback = HttpVersionPolicy.RequestVersionOrLower;

if (!string.IsNullOrWhiteSpace(configString) && configString.Contains('_'))
{
var policyPart = configString.Split('_')[1];
return policyPart switch
{
"OrLower" => HttpVersionPolicy.RequestVersionOrLower,
"Exact" => HttpVersionPolicy.RequestVersionExact,
"OrHigher" => HttpVersionPolicy.RequestVersionOrHigher,
_ => fallback,
};
}

return fallback;
}
}
}
6 changes: 4 additions & 2 deletions sama/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
"LogLevel": {
"Default": "Warning",
"Microsoft.AspNetCore.DataProtection": "Error",
"Microsoft.Hosting.Lifetime": "Information"
"Microsoft.Hosting.Lifetime": "Information",
"sama.Startup": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "Data Source=sama.db"
}
},
"DefaultHttpVersion": "11_OrLower"
}
4 changes: 2 additions & 2 deletions sama/sama.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
<MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
<UserSecretsId>aspnet-WebApplication1-1C1369D5-B3C7-4414-ADD2-629BA88766C5</UserSecretsId>
<AssemblyVersion>1.2.3</AssemblyVersion>
<VersionPrefix>1.2.3</VersionPrefix>
<AssemblyVersion>1.3.0</AssemblyVersion>
<VersionPrefix>1.3.0</VersionPrefix>
<VersionSuffix>$([System.DateTime]::UtcNow.ToString(`yyyyMMdd-HHmm`))</VersionSuffix>
</PropertyGroup>

Expand Down
7 changes: 5 additions & 2 deletions unit-tests/Services/HttpCheckServiceTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using sama.Models;
Expand All @@ -16,6 +17,7 @@ namespace TestSama.Services
public class HttpCheckServiceTests
{
private SettingsService _settingsService;
private IConfiguration _configuration;
private CertificateValidationService _certService;
private IServiceProvider _serviceProvider;
private TestHttpHandler _httpHandler;
Expand All @@ -25,11 +27,12 @@ public class HttpCheckServiceTests
public void Setup()
{
_settingsService = Substitute.For<SettingsService>((IServiceProvider)null);
_configuration = Substitute.For<IConfiguration>();
_certService = Substitute.For<CertificateValidationService>(_settingsService);
_serviceProvider = TestUtility.InitDI();
_httpHandler = (TestHttpHandler)_serviceProvider.GetRequiredService<HttpClientHandler>();

_service = new HttpCheckService(_settingsService, _certService, _serviceProvider);
_service = new HttpCheckService(_settingsService, _certService, _configuration, _serviceProvider);

_settingsService.Monitor_RequestTimeoutSeconds.Returns(1);
}
Expand Down

0 comments on commit 9a03198

Please sign in to comment.