Skip to content

Commit 97314f5

Browse files
Cleanup and refactoring
1 parent 1f7dbab commit 97314f5

File tree

16 files changed

+93
-239
lines changed

16 files changed

+93
-239
lines changed

src/Certify.Core/Management/Challenges/ChallengeResponseService.cs

Lines changed: 0 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -315,17 +315,6 @@ public async Task<PendingAuthorization> PrepareAutomatedChallengeResponse(ILog l
315315
}
316316
}
317317

318-
if (requiredChallenge.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_SNI)
319-
{
320-
// perform tls-sni-01 challenge response
321-
var check = PrepareChallengeResponse_TlsSni01(log, iisManager, pendingAuth.Identifier, managedCertificate, pendingAuth);
322-
if (requestConfig.PerformTlsSniBindingConfigChecks)
323-
{
324-
// set config check OK if all checks return true
325-
pendingAuth.AttemptedChallenge.ConfigCheckedOK = check();
326-
}
327-
}
328-
329318
if (requiredChallenge.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_DNS)
330319
{
331320
// perform dns-01 challenge response
@@ -341,15 +330,6 @@ public async Task<PendingAuthorization> PrepareAutomatedChallengeResponse(ILog l
341330
if (requiredChallenge.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_TKAUTH)
342331
{
343332
pendingAuth.AttemptedChallenge.ConfigCheckedOK = true;
344-
// perform tkauth-01 challenge response
345-
//var check = await PerformChallengeResponse_Dns01(log, domain, managedCertificate, pendingAuth, isTestMode: false, credentialsManager);
346-
/*
347-
pendingAuth.AttemptedChallenge.IsFailure = !check.Result.IsSuccess;
348-
pendingAuth.AttemptedChallenge.ChallengeResultMsg = check.Result.Message;
349-
pendingAuth.AttemptedChallenge.IsAwaitingUser = check.IsAwaitingUser;
350-
pendingAuth.AttemptedChallenge.PropagationSeconds = check.PropagationSeconds;
351-
pendingAuth.IsFailure = !check.Result.IsSuccess;
352-
pendingAuth.AuthorizationError = pendingAuth.IsFailure ? check.Result.Message : "";*/
353333
}
354334
}
355335
}
@@ -555,70 +535,6 @@ private async Task<ActionResult> PerformChallengeResponse_Http01(ILog log, ITarg
555535
}
556536
}
557537

558-
private Func<bool> PrepareChallengeResponse_TlsSni01(ILog log, ITargetWebServer iisManager, CertIdentifierItem domain, ManagedCertificate managedCertificate, PendingAuthorization pendingAuth)
559-
{
560-
var requestConfig = managedCertificate.RequestConfig;
561-
562-
var tlsSniChallenge = pendingAuth.Challenges.FirstOrDefault(c => c.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_SNI);
563-
564-
if (tlsSniChallenge == null)
565-
{
566-
log.Warning($"No tls-sni-01 challenge to complete for {managedCertificate.Name}. Request cannot continue.");
567-
return () => false;
568-
}
569-
570-
var sha256 = System.Security.Cryptography.SHA256.Create();
571-
572-
var z = new byte[tlsSniChallenge.HashIterationCount][];
573-
574-
// compute n sha256 hashes, where n=challengedata.iterationcount
575-
z[0] = sha256.ComputeHash(Encoding.UTF8.GetBytes(tlsSniChallenge.Value));
576-
577-
for (var i = 1; i < z.Length; i++)
578-
{
579-
z[i] = sha256.ComputeHash(z[i - 1]);
580-
}
581-
582-
// generate certs and install iis bindings
583-
var cleanupQueue = new List<Func<Task>>();
584-
585-
var checkQueue = new List<Func<bool>>();
586-
587-
foreach (var hex in z.Select(b =>
588-
BitConverter.ToString(b).Replace("-", "").ToLower()))
589-
{
590-
var sni = $"{hex.Substring(0, 32)}.{hex.Substring(32)}.acme.invalid";
591-
592-
log.Information($"Preparing binding at: https://{domain}, sni: {sni}");
593-
594-
var x509 = CertificateManager.GenerateSelfSignedCertificate(sni);
595-
596-
CertificateManager.StoreCertificate(x509);
597-
598-
var certStoreName = CertificateManager.GetMachineStore().Name;
599-
600-
// iisManager.InstallCertificateforBinding(certStoreName, x509.GetCertHash(),
601-
// managedCertificate.ServerSiteId, sni);
602-
603-
// add check to the queue
604-
checkQueue.Add(() => _netUtil.CheckSNI(domain.Value, sni).Result);
605-
606-
// add cleanup actions to queue
607-
cleanupQueue.Add(() => iisManager.RemoveHttpsBinding(managedCertificate.ServerSiteId, sni));
608-
609-
cleanupQueue.Add(() => Task.Run(() => CertificateManager.RemoveCertificate(x509)));
610-
}
611-
612-
// configure cleanup to execute the cleanup queue
613-
pendingAuth.Cleanup = async () =>
614-
{
615-
cleanupQueue.ForEach(a => a());
616-
};
617-
618-
// perform our own config checks
619-
return () => checkQueue.All(check => check());
620-
}
621-
622538
private DnsChallengeHelper _dnsHelper = null;
623539

624540
internal async Task<DnsChallengeHelperResult> PerformChallengeResponse_Dns01(ILog log, CertIdentifierItem domain, ManagedCertificate managedCertificate, PendingAuthorization pendingAuth, bool isTestMode, bool isCleanupOnly, ICredentialsManager credentialsManager)

src/Certify.Models/Certify.Models.csproj

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,24 @@
1616
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
1717
<PlatformTarget>AnyCPU</PlatformTarget>
1818
</PropertyGroup>
19+
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard2.0|AnyCPU'">
20+
<NoWarn>1701;1702;CA1864</NoWarn>
21+
</PropertyGroup>
22+
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net462|AnyCPU'">
23+
<NoWarn>1701;1702;CA1864</NoWarn>
24+
</PropertyGroup>
25+
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net9.0|AnyCPU'">
26+
<NoWarn>1701;1702;CA1864</NoWarn>
27+
</PropertyGroup>
28+
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|netstandard2.0|AnyCPU'">
29+
<NoWarn>1701;1702;CA1864</NoWarn>
30+
</PropertyGroup>
31+
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net462|AnyCPU'">
32+
<NoWarn>1701;1702;CA1864</NoWarn>
33+
</PropertyGroup>
34+
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net9.0|AnyCPU'">
35+
<NoWarn>1701;1702;CA1864</NoWarn>
36+
</PropertyGroup>
1937
<ItemGroup>
2038
<PackageReference Include="Fody" Version="6.9.1">
2139
<PrivateAssets>all</PrivateAssets>

src/Certify.Models/Config/CertRequestConfig.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,12 +109,12 @@ public CertRequestConfig()
109109
/// <summary>
110110
/// Optional subject alternative names for our SSL Cert request
111111
/// </summary>
112-
public string[]? SubjectAlternativeNames { get; set; } = Array.Empty<string>();
112+
public string[]? SubjectAlternativeNames { get; set; } = [];
113113

114114
/// <summary>
115115
/// Optional list of IP addresses to include in cert request, primary first
116116
/// </summary>
117-
public string[]? SubjectIPAddresses { get; set; } = Array.Empty<string>();
117+
public string[]? SubjectIPAddresses { get; set; } = [];
118118

119119
/// <summary>
120120
/// Root path for our website content, used when responding to file based challenges

src/Certify.Models/Config/ManagedCertificate.cs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,6 @@ public Lifetime(DateTimeOffset dateStart, DateTimeOffset dateEnd)
7777

7878
public int? GetPercentageElapsed(DateTimeOffset testDateTime)
7979
{
80-
if (DateStart == null || DateEnd == null)
81-
{
82-
return null;
83-
}
84-
8580
var lifetime = DateEnd - DateStart;
8681

8782
if (lifetime.TotalMinutes <= 0)
@@ -523,7 +518,7 @@ public CertRequestChallengeConfig GetChallengeConfig(CertIdentifierItem identifi
523518
}
524519

525520
// if exact match exists, use that
526-
var identifierKey = identifier?.Value.ToLowerInvariant() ?? "";
521+
var identifierKey = identifier!.Value.ToLowerInvariant();
527522
if (configsPerDomain.TryGetValue(identifierKey, out var value))
528523
{
529524
return value;
@@ -548,7 +543,7 @@ public CertRequestChallengeConfig GetChallengeConfig(CertIdentifierItem identifi
548543

549544
foreach (var configDomain in allMatchingConfigKeys)
550545
{
551-
if (configDomain.EndsWith(identifier?.Value.ToLowerInvariant(), StringComparison.CurrentCultureIgnoreCase))
546+
if (configDomain.EndsWith(identifier!.Value.ToLowerInvariant(), StringComparison.CurrentCultureIgnoreCase))
552547
{
553548
// use longest matching identifier (so subdomain.test.com takes priority
554549
// over test.com, )

src/Certify.Models/Hub/AccessControl.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33

44
namespace Certify.Models.Hub
@@ -100,8 +100,8 @@ public AccessCheck(string? securityPrincipleId, string resourceType, string reso
100100

101101
public class AccessTokenCheck
102102
{
103-
public AccessToken Token { get; set; }
104-
public AccessCheck Check { get; set; }
103+
public AccessToken Token { get; set; } = default!;
104+
public AccessCheck Check { get; set; } = default!;
105105
}
106106

107107
public class AccessTokenTypes

src/Certify.Models/Hub/HubInfo.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@
22
{
33
public class HubInfo
44
{
5-
public string InstanceId { get; set; }
5+
public string InstanceId { get; set; } = default!;
66

7-
public VersionInfo Version { get; set; }
7+
public VersionInfo Version { get; set; } = default!;
88
}
99

1010
public class HubHealth
1111
{
12-
public string Status { get; set; }
13-
public string Detail { get; set; }
14-
public string Version { get; set; }
15-
public bool ServiceAvailable { get; set; }
16-
public object env { get; set; }
12+
public string Status { get; set; } = default!;
13+
public string Detail { get; set; } = default!;
14+
public string Version { get; set; } = default!;
15+
public bool ServiceAvailable { get; set; } = default!;
16+
public object env { get; set; } = default!;
1717
}
1818
}

src/Certify.Models/Plugins/PluginInterfaces.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public interface IDashboardClient
5151
public interface IProviderPlugin<TProviderInterface, TProviderDefinition>
5252
{
5353
List<TProviderDefinition> GetProviders(Type pluginType);
54-
TProviderInterface GetProvider(Type pluginType, string id);
54+
TProviderInterface? GetProvider(Type pluginType, string id);
5555
}
5656

5757
/// <summary>

src/Certify.Models/Plugins/PluginProviderBase.cs

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public PluginProviderBase(IServiceProvider serviceProvider)
2222

2323
private IServiceProvider? _services { get; }
2424

25-
public TProviderInterface GetProvider(Type pluginType, string? id)
25+
public TProviderInterface? GetProvider(Type pluginType, string? id)
2626
{
2727

2828
id = id?.ToLowerInvariant();
@@ -34,27 +34,29 @@ public TProviderInterface GetProvider(Type pluginType, string? id)
3434

3535
foreach (var t in typeList)
3636
{
37-
var def = (TProviderDefinition)t.GetProperty("Definition").GetValue(null);
38-
if (def != null && def is ProviderDefinition)
37+
var defProperty = t.GetProperty("Definition");
38+
if (defProperty != null)
3939
{
40-
if ((def as ProviderDefinition)?.Id?.ToLowerInvariant() == id)
40+
var def = (TProviderDefinition?)defProperty.GetValue(null);
41+
if (def != null && def is ProviderDefinition)
4142
{
42-
if (_services == null)
43+
if ((def as ProviderDefinition)?.Id?.ToLowerInvariant() == id)
4344
{
44-
return (TProviderInterface)Activator.CreateInstance(t);
45-
}
46-
else
47-
{
48-
return (TProviderInterface)ActivatorUtilities.CreateInstance(_services, t);
45+
if (_services == null)
46+
{
47+
return (TProviderInterface?)Activator.CreateInstance(t);
48+
}
49+
else
50+
{
51+
return (TProviderInterface?)ActivatorUtilities.CreateInstance(_services, t);
52+
}
4953
}
5054
}
5155
}
5256
}
5357

5458
// the requested provider id is not present in this provider plugin, could be in another assembly
55-
#pragma warning disable CS8603 // Possible null reference return.
5659
return default;
57-
#pragma warning restore CS8603 // Possible null reference return.
5860
}
5961

6062
public List<TProviderDefinition> GetProviders(Type pluginType)
@@ -70,8 +72,15 @@ public List<TProviderDefinition> GetProviders(Type pluginType)
7072
{
7173
try
7274
{
73-
var def = (TProviderDefinition)t.GetProperty("Definition").GetValue(null);
74-
list.Add(def);
75+
var defProperty = t.GetProperty("Definition");
76+
if (defProperty != null)
77+
{
78+
var def = (TProviderDefinition?)defProperty.GetValue(null);
79+
if (def != null)
80+
{
81+
list.Add(def);
82+
}
83+
}
7584
}
7685
catch (Exception)
7786
{

src/Certify.Models/Shared/ActionLogCollector.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,6 @@ public List<string> GetActionLogSummary()
4444
return output;
4545
}
4646

47-
public ActionLogItem GetLastActionLogItem() => _actionLogs.LastOrDefault();
47+
public ActionLogItem? GetLastActionLogItem() => _actionLogs.LastOrDefault();
4848
}
4949
}

src/Certify.Models/Shared/Validation/CertificateEditorService.cs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -121,9 +121,8 @@ public static void ApplyAutoConfiguration(ManagedCertificate item, SiteInfo? sel
121121
}
122122

123123
// update our list of selected subject ip addresses, if any
124-
if (!config.SubjectIPAddresses.SequenceEqual(item.DomainOptions.Where(i => i.IsSelected && i.Type == CertIdentifierType.Ip).Select(s => s.Domain).ToArray()))
124+
if (config.SubjectIPAddresses?.SequenceEqual(item.DomainOptions.Where(i => i.IsSelected && i.Type == CertIdentifierType.Ip).Select(s => s.Domain).ToArray()) == false)
125125
{
126-
127126
config.SubjectIPAddresses = item.DomainOptions.Where(i => i.IsSelected && i.Type == CertIdentifierType.Ip && i.Domain != null)
128127
.Select(s => s.Domain ?? string.Empty)
129128
.ToArray();
@@ -343,7 +342,7 @@ public static ValidationResult Validate(ManagedCertificate item, SiteInfo? selec
343342
if (
344343
item.DomainOptions?.Any(d => d.IsSelected && d.Domain != null && d.Domain.StartsWith("*.", StringComparison.InvariantCultureIgnoreCase)) == true
345344
&&
346-
!item.RequestConfig.Challenges.Any(c => c.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_DNS)
345+
item.RequestConfig.Challenges?.Any(c => c.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_DNS) == false
347346
)
348347
{
349348
return new ValidationResult(
@@ -395,7 +394,7 @@ public static ValidationResult Validate(ManagedCertificate item, SiteInfo? selec
395394
}
396395

397396
// TLS-SNI-01 (is now not supported)
398-
if (item.RequestConfig.Challenges.Any(c => c.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_SNI))
397+
if (item.RequestConfig.Challenges?.Any(c => c.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_SNI) == true)
399398
{
400399
return new ValidationResult(
401400
false,
@@ -404,7 +403,7 @@ public static ValidationResult Validate(ManagedCertificate item, SiteInfo? selec
404403
);
405404
}
406405

407-
if (item.RequestConfig.Challenges.Any(c => c.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_DNS && string.IsNullOrEmpty(c.ChallengeProvider)))
406+
if (item.RequestConfig.Challenges?.Any(c => c.ChallengeType == SupportedChallengeTypes.CHALLENGE_TYPE_DNS && string.IsNullOrEmpty(c.ChallengeProvider)) == true)
408407
{
409408
return new ValidationResult(
410409
false,
@@ -413,7 +412,7 @@ public static ValidationResult Validate(ManagedCertificate item, SiteInfo? selec
413412
);
414413
}
415414

416-
if (item.RequestConfig.Challenges.Count(c => string.IsNullOrEmpty(c.DomainMatch)) > 1)
415+
if (item.RequestConfig.Challenges?.Count(c => string.IsNullOrEmpty(c.DomainMatch)) > 1)
417416
{
418417
return new ValidationResult(
419418
false,
@@ -455,7 +454,7 @@ public static ValidationResult Validate(ManagedCertificate item, SiteInfo? selec
455454
}
456455

457456
// check certificate will not exceed 100 name limit. TODO: make this dynamic per selected CA
458-
var numSelectedDomains = item.DomainOptions.Count(d => d.IsSelected);
457+
var numSelectedDomains = item.DomainOptions?.Count(d => d.IsSelected) ?? 0;
459458

460459
if (numSelectedDomains > 100)
461460
{

0 commit comments

Comments
 (0)