(refactor): codebase review, small syntax fixes

This commit is contained in:
Maksym Sadovnychyy 2023-08-01 12:31:24 +02:00
parent 23fa0d9826
commit 767b4f2fc6
29 changed files with 1368 additions and 1410 deletions

View File

@ -8,7 +8,9 @@
</PropertyGroup>
<ItemGroup>
<Folder Include="Abstractions\" />
<Compile Remove="Abstractions\**" />
<EmbeddedResource Remove="Abstractions\**" />
<None Remove="Abstractions\**" />
</ItemGroup>
</Project>

View File

@ -1,8 +1,8 @@
using System.Text.Json.Serialization;
using System.Text.Json;
namespace MaksIT.Core.Extensions {
public static class ObjectExtensions {
namespace MaksIT.Core.Extensions;
public static class ObjectExtensions {
/// <summary>
///
@ -33,5 +33,4 @@ namespace MaksIT.Core.Extensions {
return JsonSerializer.Serialize(obj, options);
}
}
}

View File

@ -6,8 +6,8 @@ using System.Text.Json.Serialization;
using System.Text.Json;
using System.Threading.Tasks;
namespace MaksIT.Core.Extensions {
public static class StringExtensions {
namespace MaksIT.Core.Extensions;
public static class StringExtensions {
/// <summary>
/// Converts JSON string to object
/// </summary>
@ -36,5 +36,4 @@ namespace MaksIT.Core.Extensions {
? JsonSerializer.Deserialize<T>(s, options)
: default;
}
}
}

View File

@ -1,7 +1,7 @@
using System.Runtime.InteropServices;
namespace MaksIT.Core {
public static class OperatingSystem {
namespace MaksIT.Core;
public static class OperatingSystem {
public static bool IsWindows() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
@ -10,5 +10,4 @@ namespace MaksIT.Core {
public static bool IsLinux() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
}
}

View File

@ -2,8 +2,8 @@
using System.Text.Json.Serialization;
namespace MaksIT.LetsEncrypt.Entities.Jws {
public class Jwk {
namespace MaksIT.LetsEncrypt.Entities.Jws;
public class Jwk {
/// <summary>
/// "kty" (Key Type) Parameter
/// <para>
@ -101,5 +101,4 @@ namespace MaksIT.LetsEncrypt.Entities.Jws {
/// </summary>
[JsonPropertyName("alg")]
public string? Algorithm { get; set; }
}
}

View File

@ -1,20 +1,20 @@
using System;
using System.Text.Json.Serialization;
namespace MaksIT.LetsEncrypt.Entities.Jws
{
namespace MaksIT.LetsEncrypt.Entities.Jws;
public class JwsMessage {
public class JwsMessage {
public string? Protected { get; set; }
public string? Payload { get; set; }
public string? Signature { get; set; }
}
}
public class JwsHeader {
public class JwsHeader {
[JsonPropertyName("alg")]
public string? Algorithm { get; set; }
@ -33,8 +33,4 @@ namespace MaksIT.LetsEncrypt.Entities.Jws
[JsonPropertyName("Host")]
public string? Host { get; set; }
}
}

View File

@ -1,7 +1,7 @@
using System;
namespace MaksIT.LetsEncrypt.Entities {
public class AuthorizationChallenge {
namespace MaksIT.LetsEncrypt.Entities;
public class AuthorizationChallenge {
public Uri? Url { get; set; }
public string? Type { get; set; }
@ -9,5 +9,4 @@ namespace MaksIT.LetsEncrypt.Entities {
public string? Status { get; set; }
public string? Token { get; set; }
}
}

View File

@ -1,11 +1,8 @@
using System.Security.Cryptography;
namespace MaksIT.LetsEncrypt.Entities
{
public class CachedCertificateResult
{
namespace MaksIT.LetsEncrypt.Entities;
public class CachedCertificateResult {
public RSACryptoServiceProvider? PrivateKey { get; set; }
public string? Certificate { get; set; }
}
}

View File

@ -1,18 +1,62 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Text;
using MaksIT.LetsEncrypt.Entities.Jws;
namespace MaksIT.LetsEncrypt.Entities {
public class CertificateCache {
namespace MaksIT.LetsEncrypt.Entities;
public class CertificateCache {
public string? Cert { get; set; }
public byte[]? Private { get; set; }
}
}
public class RegistrationCache {
public class RegistrationCache {
public Dictionary<string, CertificateCache>? CachedCerts { get; set; }
public byte[]? AccountKey { get; set; }
public string? Id { get; set; }
public Jwk? Key { get; set; }
public Uri? Location { get; set; }
/// <summary>
///
/// </summary>
/// <param name="subject"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool TryGetCachedCertificate(string subject, out CachedCertificateResult? value) {
value = null;
if (CachedCerts == null)
return false;
if (!CachedCerts.TryGetValue(subject, out var cache)) {
return false;
}
var cert = new X509Certificate2(Encoding.ASCII.GetBytes(cache.Cert));
// if it is about to expire, we need to refresh
if ((cert.NotAfter - DateTime.UtcNow).TotalDays < 30)
return false;
var rsa = new RSACryptoServiceProvider(4096);
rsa.ImportCspBlob(cache.Private);
value = new CachedCertificateResult {
Certificate = cache.Cert,
PrivateKey = rsa
};
return true;
}
/// <summary>
///
/// </summary>
/// <param name="hostsToRemove"></param>
public void ResetCachedCertificate(IEnumerable<string> hostsToRemove) {
if (CachedCerts != null)
foreach (var host in hostsToRemove)
CachedCerts.Remove(host);
}
}

View File

@ -1,8 +1,6 @@
using System;
using System.Net.Http;
namespace MaksIT.LetsEncrypt.Exceptions {
public class LetsEncrytException : Exception {

namespace MaksIT.LetsEncrypt.Exceptions;
public class LetsEncrytException : Exception {
public LetsEncrytException(Problem problem, HttpResponseMessage response)
: base($"{problem.Type}: {problem.Detail}") {
Problem = problem;
@ -12,14 +10,14 @@ namespace MaksIT.LetsEncrypt.Exceptions {
public Problem Problem { get; }
public HttpResponseMessage Response { get; }
}
}
public class Problem {
public class Problem {
public string Type { get; set; }
public string Detail { get; set; }
public string RawJson { get; set; }
}
}

View File

@ -2,11 +2,10 @@
using MaksIT.LetsEncrypt.Services;
namespace MaksIT.LetsEncrypt.Extensions {
public static class ServiceCollectionExtensions {
namespace MaksIT.LetsEncrypt.Extensions;
public static class ServiceCollectionExtensions {
public static void RegisterLetsEncrypt(this IServiceCollection services) {
services.AddHttpClient<ILetsEncryptService, LetsEncryptService>();
}
}
}

View File

@ -1,5 +1,4 @@
namespace MaksIT.LetsEncrypt.Models.Interfaces {
public interface IHasLocation {
namespace MaksIT.LetsEncrypt.Models.Interfaces;
public interface IHasLocation {
Uri? Location { get; set; }
}
}

View File

@ -1,7 +1,5 @@
namespace MaksIT.LetsEncrypt.Models.Requests
{
public class FinalizeRequest
{
namespace MaksIT.LetsEncrypt.Models.Requests;
public class FinalizeRequest {
public string? Csr { get; set; }
}
}

View File

@ -5,9 +5,9 @@ using MaksIT.LetsEncrypt.Models.Interfaces;
* https://tools.ietf.org/html/draft-ietf-acme-acme-18#section-7.3
*/
namespace MaksIT.LetsEncrypt.Models.Responses
{
public class Account : IHasLocation {
namespace MaksIT.LetsEncrypt.Models.Responses;
public class Account : IHasLocation {
public bool TermsOfServiceAgreed { get; set; }
@ -34,5 +34,4 @@ namespace MaksIT.LetsEncrypt.Models.Responses
public Uri? Orders { get; set; }
public Uri? Location { get; set; }
}
}

View File

@ -1,11 +1,9 @@
using System;
namespace MaksIT.LetsEncrypt.Models.Responses
{
public class AcmeDirectory
{
public Uri NewNonce { get; set; }
namespace MaksIT.LetsEncrypt.Models.Responses;
public class AcmeDirectory {
public Uri NewNonce { get; set; }
public Uri NewAccount { get; set; }
@ -20,10 +18,8 @@ namespace MaksIT.LetsEncrypt.Models.Responses
public Uri KeyChange { get; set; }
public AcmeDirectoryMeta Meta { get; set; }
}
public class AcmeDirectoryMeta
{
public string TermsOfService { get; set; }
}
}
public class AcmeDirectoryMeta {
public string TermsOfService { get; set; }
}

View File

@ -1,8 +1,9 @@

using MaksIT.LetsEncrypt.Entities;
namespace MaksIT.LetsEncrypt.Models.Responses {
public class AuthorizationChallengeResponse {
namespace MaksIT.LetsEncrypt.Models.Responses;
public class AuthorizationChallengeResponse {
public OrderIdentifier? Identifier { get; set; }
public string? Status { get; set; }
@ -12,9 +13,8 @@ namespace MaksIT.LetsEncrypt.Models.Responses {
public bool Wildcard { get; set; }
public AuthorizationChallenge[]? Challenges { get; set; }
}
public class AuthorizeChallenge {
public string? KeyAuthorization { get; set; }
}
}
public class AuthorizeChallenge {
public string? KeyAuthorization { get; set; }
}

View File

@ -1,16 +1,16 @@
using MaksIT.LetsEncrypt.Exceptions;
using MaksIT.LetsEncrypt.Models.Interfaces;
namespace MaksIT.LetsEncrypt.Models.Responses {
namespace MaksIT.LetsEncrypt.Models.Responses;
public class OrderIdentifier {
public class OrderIdentifier {
public string? Type { get; set; }
public string? Value { get; set; }
}
}
public class Order : IHasLocation {
public class Order : IHasLocation {
public Uri? Location { get; set; }
public string? Status { get; set; }
@ -30,5 +30,4 @@ namespace MaksIT.LetsEncrypt.Models.Responses {
public Uri? Finalize { get; set; }
public Uri? Certificate { get; set; }
}
}

View File

@ -11,8 +11,9 @@ using MaksIT.LetsEncrypt.Entities.Jws;
using MaksIT.Core.Extensions;
namespace MaksIT.LetsEncrypt.Services {
public interface IJwsService {
namespace MaksIT.LetsEncrypt.Services;
public interface IJwsService {
void SetKeyId(string location);
JwsMessage Encode(JwsHeader protectedHeader);
@ -25,10 +26,10 @@ namespace MaksIT.LetsEncrypt.Services {
string Base64UrlEncoded(string s);
string Base64UrlEncoded(byte[] arg);
}
}
public class JwsService : IJwsService {
public class JwsService : IJwsService {
public Jwk _jwk;
private RSA _rsa;
@ -108,5 +109,4 @@ namespace MaksIT.LetsEncrypt.Services {
}
}

View File

@ -18,12 +18,10 @@ using MaksIT.LetsEncrypt.Models.Responses;
using MaksIT.LetsEncrypt.Models.Interfaces;
using MaksIT.LetsEncrypt.Models.Requests;
using MaksIT.LetsEncrypt.Entities.Jws;
using System.Xml;
using System.Diagnostics;
namespace MaksIT.LetsEncrypt.Services {
namespace MaksIT.LetsEncrypt.Services;
public interface ILetsEncryptService {
public interface ILetsEncryptService {
Task ConfigureClient(string url);
@ -38,12 +36,12 @@ namespace MaksIT.LetsEncrypt.Services {
Task<(X509Certificate2 Cert, RSA PrivateKey)> GetCertificate(string subject);
RegistrationCache? GetRegistrationCache();
}
}
public class LetsEncryptService : ILetsEncryptService {
public class LetsEncryptService : ILetsEncryptService {
//private static readonly JsonSerializerSettings jsonSettings = new JsonSerializerSettings {
// NullValueHandling = NullValueHandling.Ignore,
@ -473,5 +471,4 @@ namespace MaksIT.LetsEncrypt.Services {
var result = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, _directory.NewNonce));
return result.Headers.GetValues("Replay-Nonce").First();
}
}
}

View File

@ -1,7 +1,3 @@
using System.Text;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@ -10,18 +6,17 @@ using MaksIT.Core.Extensions;
using MaksIT.LetsEncrypt.Services;
using MaksIT.LetsEncrypt.Entities;
using MaksIT.LetsEncryptConsole.Services;
using SSHProvider;
using Mono.Unix.Native;
using Serilog.Core;
namespace MaksIT.LetsEncryptConsole {
using MaksIT.SSHProvider;
public interface IApp {
namespace MaksIT.LetsEncryptConsole;
public interface IApp {
Task Run(string[] args);
}
}
public class App : IApp {
public class App : IApp {
private readonly string _appPath = AppDomain.CurrentDomain.BaseDirectory;
@ -107,7 +102,7 @@ namespace MaksIT.LetsEncryptConsole {
// if valid check if cert and key exists otherwise recreate
// else continue with new certificate request
var certRes = new CachedCertificateResult();
if (TryGetCachedCertificate(registrationCache, site.Name, out certRes)) {
if (registrationCache.TryGetCachedCertificate(site.Name, out certRes)) {
string cert = Path.Combine(sslPath, $"{site.Name}.crt");
//if(!File.Exists(cert))
File.WriteAllText(cert, certRes.Certificate);
@ -156,10 +151,6 @@ namespace MaksIT.LetsEncryptConsole {
}
}
break;
}
@ -182,9 +173,10 @@ namespace MaksIT.LetsEncryptConsole {
await Task.Delay(1000);
// Download new certificate
#region Download new certificate
_logger.LogInformation("4. Download certificate...");
var (cert, key) = await _letsEncryptService.GetCertificate(site.Name);
#endregion
#region Persist cache
registrationCache = _letsEncryptService.GetRegistrationCache();
@ -194,7 +186,7 @@ namespace MaksIT.LetsEncryptConsole {
#region Save cert and key to filesystem
certRes = new CachedCertificateResult();
if (TryGetCachedCertificate(registrationCache, site.Name, out certRes)) {
if (registrationCache.TryGetCachedCertificate(site.Name, out certRes)) {
File.WriteAllText(Path.Combine(sslPath, site.Name + ".crt"), certRes.Certificate);
@ -252,50 +244,9 @@ namespace MaksIT.LetsEncryptConsole {
}
}
/// <summary>
///
/// </summary>
/// <param name="subject"></param>
/// <param name="value"></param>
/// <returns></returns>
private bool TryGetCachedCertificate(RegistrationCache? registrationCache, string subject, out CachedCertificateResult? value) {
value = null;
if (registrationCache?.CachedCerts == null)
return false;
if (!registrationCache.CachedCerts.TryGetValue(subject, out var cache)) {
return false;
}
var cert = new X509Certificate2(Encoding.ASCII.GetBytes(cache.Cert));
// if it is about to expire, we need to refresh
if ((cert.NotAfter - DateTime.UtcNow).TotalDays < 30)
return false;
var rsa = new RSACryptoServiceProvider(4096);
rsa.ImportCspBlob(cache.Private);
value = new CachedCertificateResult {
Certificate = cache.Cert,
PrivateKey = rsa
};
return true;
}
/// <summary>
///
/// </summary>
/// <param name="hostsToRemove"></param>
public RegistrationCache? ResetCachedCertificate(RegistrationCache? registrationCache, IEnumerable<string> hostsToRemove) {
if (registrationCache?.CachedCerts != null)
foreach (var host in hostsToRemove)
registrationCache.CachedCerts.Remove(host);
return registrationCache;
}
private void UploadFiles(
ILogger logger,
SSHClientSettings sshSettings,
@ -319,5 +270,4 @@ namespace MaksIT.LetsEncryptConsole {
sshService.RunSudoCommand(sshSettings.Password, $"chown {owner} {workDir} -R");
sshService.RunSudoCommand(sshSettings.Password, $"chmod {changeMode} {workDir} -R");
}
}
}

View File

@ -1,30 +1,30 @@
using System.Runtime.InteropServices;
namespace MaksIT.LetsEncryptConsole {
public class Configuration {
namespace MaksIT.LetsEncryptConsole;
public class Configuration {
public LetsEncryptEnvironment[]? Environments { get; set; }
public Customer[]? Customers { get; set; }
}
}
public class OsWindows {
public class OsWindows {
public string? Path { get; set; }
}
}
public class OsLinux {
public class OsLinux {
public string? Path { get; set; }
public string? Owner { get; set; }
public string? ChangeMode { get; set; }
}
}
public class OsDependant {
public class OsDependant {
public OsWindows? Windows { get; set; }
public OsLinux? Linux { get; set; }
}
}
public class SSHClientSettings {
public class SSHClientSettings {
public bool Active { get; set; }
public string? Host { get; set; }
@ -34,7 +34,7 @@ namespace MaksIT.LetsEncryptConsole {
public string? Username { get; set; }
public string? Password { get; set; }
}
}
@ -69,4 +69,3 @@ namespace MaksIT.LetsEncryptConsole {
public string[]? Hosts { get; set; }
public string? Challenge { get; set; }
}
}

View File

@ -6,8 +6,9 @@ using Serilog;
using MaksIT.LetsEncryptConsole.Services;
using MaksIT.LetsEncrypt.Extensions;
namespace MaksIT.LetsEncryptConsole {
class Program {
namespace MaksIT.LetsEncryptConsole;
class Program {
private static readonly IConfiguration _configuration = InitConfig();
static void Main(string[] args) {
@ -66,5 +67,5 @@ namespace MaksIT.LetsEncryptConsole {
return configuration.Build();
}
}
}

View File

@ -1,13 +1,13 @@
using System.Security.Cryptography;
namespace MaksIT.LetsEncryptConsole.Services {
namespace MaksIT.LetsEncryptConsole.Services;
public interface IKeyService {
public interface IKeyService {
void ExportPublicKey(RSACryptoServiceProvider csp, TextWriter outputStream);
void ExportPrivateKey(RSACryptoServiceProvider csp, TextWriter outputStream);
}
}
public class KeyService : IKeyService {
public class KeyService : IKeyService {
/// <summary>
/// Export a certificate to a PEM format string
/// </summary>
@ -147,5 +147,4 @@ namespace MaksIT.LetsEncryptConsole.Services {
}
}
}
}
}

View File

@ -1,12 +1,12 @@
using System.Diagnostics;
namespace MaksIT.LetsEncryptConsole.Services {
namespace MaksIT.LetsEncryptConsole.Services;
public interface ITerminalService {
public interface ITerminalService {
void Exec(string cmd);
}
}
public class TerminalService : ITerminalService {
public class TerminalService : ITerminalService {
public void Exec(string cmd) {
var escapedArgs = cmd.Replace("\"", "\\\"");
@ -25,6 +25,4 @@ namespace MaksIT.LetsEncryptConsole.Services {
pc.Start();
pc.WaitForExit();
}
}
}

View File

@ -1,10 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MaksIT.SSHProvider;
namespace SSHProvider {
public class Configuration {
}
public class Configuration {
}

View File

@ -5,7 +5,7 @@ using Renci.SshNet;
using Renci.SshNet.Common;
using System.Text.RegularExpressions;
namespace SSHProvider {
namespace MaksIT.SSHProvider {
public interface ISSHService : IDisposable {
IDomainResult Upload(string workingdirectory, string fileName, byte[] bytes);
@ -77,8 +77,8 @@ namespace SSHProvider {
_logger.LogInformation($"Listing directory:");
foreach (var fi in listDirectory) {
_logger.LogInformation($" - " + fi.Name);
foreach (var file in listDirectory) {
_logger.LogInformation($" - " + file.Name);
}
return IDomainResult.Success();

View File

@ -7,9 +7,9 @@ using Xunit;
//using PecMgr.VaultProvider;
//using PecMgr.Core.Abstractions;
namespace MaksIT.Tests.SSHProviderTests.Abstractions {
//[TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)]
public abstract class ConfigurationBase {
namespace MaksIT.Tests.SSHProviderTests.Abstractions;
//[TestCaseOrderer(PriorityOrderer.Name, PriorityOrderer.Assembly)]
public abstract class ConfigurationBase {
protected IConfiguration Configuration;
@ -59,5 +59,4 @@ namespace MaksIT.Tests.SSHProviderTests.Abstractions {
return configurationBuilder.Build();
}
}
}

View File

@ -4,10 +4,10 @@ using Serilog;
using Microsoft.Extensions.Configuration;
using SSHProvider;
using MaksIT.SSHProvider;
namespace MaksIT.Tests.SSHProviderTests.Abstractions {
public abstract class ServicesBase : ConfigurationBase {
namespace MaksIT.Tests.SSHProviderTests.Abstractions;
public abstract class ServicesBase : ConfigurationBase {
public ServicesBase() : base() { }
@ -26,5 +26,4 @@ namespace MaksIT.Tests.SSHProviderTests.Abstractions {
#endregion
}
}
}

View File

@ -3,12 +3,12 @@ using System.Security.Cryptography;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SSHProvider;
using MaksIT.SSHProvider;
using MaksIT.Tests.SSHProviderTests.Abstractions;
namespace SSHSerivceTests {
public class UnitTest1 : ServicesBase {
namespace MaksIT.SSHSerivceTests;
public class UnitTest1 : ServicesBase {
public readonly string _appPath = AppDomain.CurrentDomain.BaseDirectory;
@ -54,5 +54,4 @@ namespace SSHSerivceTests {
}
}
}
}
}