Skip to content

Commit

Permalink
API: per instance deployment task edit/execute, refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
webprofusion-chrisc committed Nov 8, 2024
1 parent 9460e10 commit 0c32cf9
Show file tree
Hide file tree
Showing 9 changed files with 302 additions and 101 deletions.
6 changes: 6 additions & 0 deletions src/Certify.Client/CertifyApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,12 @@ public async Task<List<CertificateAuthority>> GetCertificateAuthorities(AuthCont
return JsonConvert.DeserializeObject<List<CertificateAuthority>>(result);
}

public async Task<ActionResult> UpdateCertificateAuthority(CertificateAuthority ca, AuthContext authContext = null)
{
var result = await PostAsync("accounts/authorities", ca, authContext);
return JsonConvert.DeserializeObject<ActionResult>(await result.Content.ReadAsStringAsync());
}

public async Task<ActionResult> DeleteCertificateAuthority(string id, AuthContext authContext = null)
{
var result = await DeleteAsync("accounts/authorities/" + id, authContext);
Expand Down
2 changes: 2 additions & 0 deletions src/Certify.Client/ICertifyClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ public partial interface ICertifyInternalApiClient

#region Accounts
Task<List<CertificateAuthority>> GetCertificateAuthorities(AuthContext authContext = null);

Task<ActionResult> UpdateCertificateAuthority(CertificateAuthority ca, AuthContext authContext = null);
Task<ActionResult> DeleteCertificateAuthority(string id, AuthContext authContext = null);
Task<List<AccountDetails>> GetAccounts(AuthContext authContext = null);
Task<ActionResult> AddAccount(ContactRegistration contact, AuthContext authContext = null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ private async Task<InstanceCommandResult> _managementServerClient_OnGetCommandRe

val = await UpdateCertificateAuthority(item);
}
else if (arg.CommandType == ManagementHubCommands.RemoveCertificateAuthority)
{
var args = JsonSerializer.Deserialize<KeyValuePair<string, string>[]>(arg.Value);
var itemArg = args.FirstOrDefault(a => a.Key == "id");
val = await RemoveCertificateAuthority(itemArg.Value);
}
else if (arg.CommandType == ManagementHubCommands.GetAcmeAccounts)
{
val = await GetAccountRegistrations();
Expand All @@ -187,6 +193,13 @@ private async Task<InstanceCommandResult> _managementServerClient_OnGetCommandRe

val = await AddAccount(registration);
}
else if (arg.CommandType == ManagementHubCommands.RemoveAcmeAccount)
{
var args = JsonSerializer.Deserialize<KeyValuePair<string, string>[]>(arg.Value);
var itemArg = args.FirstOrDefault(a => a.Key == "storageKey");
var deactivateArg = args.FirstOrDefault(a => a.Key == "deactivate");
val = await RemoveAccount(itemArg.Value, bool.Parse(deactivateArg.Value));
}
else if (arg.CommandType == ManagementHubCommands.GetStoredCredentials)
{
val = await _credentialsManager.GetCredentials();
Expand All @@ -209,6 +222,7 @@ private async Task<InstanceCommandResult> _managementServerClient_OnGetCommandRe
{
val = await Core.Management.Challenges.ChallengeProviders.GetChallengeAPIProviders();
}

else if (arg.CommandType == ManagementHubCommands.GetDnsZones)
{
var args = JsonSerializer.Deserialize<KeyValuePair<string, string>[]>(arg.Value);
Expand All @@ -217,6 +231,19 @@ private async Task<InstanceCommandResult> _managementServerClient_OnGetCommandRe

val = await GetDnsProviderZones(providerTypeArg.Value, credentialIdArg.Value);
}
else if (arg.CommandType == ManagementHubCommands.GetDeploymentProviders)
{
val = await GetDeploymentProviders();
}
else if (arg.CommandType == ManagementHubCommands.ExecuteDeploymentTask)
{
var args = JsonSerializer.Deserialize<KeyValuePair<string, string>[]>(arg.Value);

var managedCertificateIdArg = args.FirstOrDefault(a => a.Key == "managedCertificateId");
var taskIdArg = args.FirstOrDefault(a => a.Key == "taskId");

val = await PerformDeploymentTask(null, managedCertificateIdArg.Value, taskIdArg.Value, isPreviewOnly: false, skipDeferredTasks: false, forceTaskExecution: false);
}
else if (arg.CommandType == ManagementHubCommands.Reconnect)
{
await _managementServerClient.Disconnect();
Expand Down
4 changes: 4 additions & 0 deletions src/Certify.Models/API/Management/ManagementHubMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class ManagementHubCommands

public const string GetAcmeAccounts = "GetAcmeAccounts";
public const string AddAcmeAccount = "AddAcmeAccount";
public const string RemoveAcmeAccount = "RemoveAcmeAccount";

public const string GetStoredCredentials = "GetStoredCredentials";
public const string UpdateStoredCredential = "UpdateStoredCredential";
Expand All @@ -38,6 +39,9 @@ public class ManagementHubCommands
public const string GetChallengeProviders = "GetChallengeProviders";
public const string GetDnsZones = "GetDnsZones";

public const string GetDeploymentProviders = "GetDeploymentProviders";
public const string ExecuteDeploymentTask = "ExecuteDeploymentTask";

public const string Reconnect = "Reconnect";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2895,23 +2895,26 @@ public virtual async System.Threading.Tasks.Task<ActionResult> RemoveAcmeAccount
}

/// <summary>
/// Get List of supported deployment tasks
/// Get Deployment Task Providers [Generated by Certify.SourceGenerators]
/// </summary>
/// <returns>OK</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual System.Threading.Tasks.Task<System.Collections.Generic.ICollection<DeploymentProviderDefinition>> GetDeploymentProvidersAsync()
public virtual System.Threading.Tasks.Task<System.Collections.Generic.ICollection<DeploymentProviderDefinition>> GetDeploymentProvidersAsync(string instanceId)
{
return GetDeploymentProvidersAsync(System.Threading.CancellationToken.None);
return GetDeploymentProvidersAsync(instanceId, System.Threading.CancellationToken.None);
}

/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <summary>
/// Get List of supported deployment tasks
/// Get Deployment Task Providers [Generated by Certify.SourceGenerators]
/// </summary>
/// <returns>OK</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual async System.Threading.Tasks.Task<System.Collections.Generic.ICollection<DeploymentProviderDefinition>> GetDeploymentProvidersAsync(System.Threading.CancellationToken cancellationToken)
public virtual async System.Threading.Tasks.Task<System.Collections.Generic.ICollection<DeploymentProviderDefinition>> GetDeploymentProvidersAsync(string instanceId, System.Threading.CancellationToken cancellationToken)
{
if (instanceId == null)
throw new System.ArgumentNullException("instanceId");

var client_ = _httpClient;
var disposeClient_ = false;
try
Expand All @@ -2923,8 +2926,9 @@ public virtual async System.Threading.Tasks.Task<ActionResult> RemoveAcmeAccount

var urlBuilder_ = new System.Text.StringBuilder();
if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl);
// Operation Path: "internal/v1/deploymenttask/providers"
urlBuilder_.Append("internal/v1/deploymenttask/providers");
// Operation Path: "internal/v1/deploymenttask/{instanceId}"
urlBuilder_.Append("internal/v1/deploymenttask/");
urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(instanceId, System.Globalization.CultureInfo.InvariantCulture)));

PrepareRequest(client_, request_, urlBuilder_);

Expand Down Expand Up @@ -2978,6 +2982,104 @@ public virtual async System.Threading.Tasks.Task<ActionResult> RemoveAcmeAccount
}
}

/// <summary>
/// Execute Deployment Task [Generated by Certify.SourceGenerators]
/// </summary>
/// <returns>OK</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual System.Threading.Tasks.Task<System.Collections.Generic.ICollection<ActionStep>> ExecuteDeploymentTaskAsync(string instanceId, string managedCertificateId, string taskId)
{
return ExecuteDeploymentTaskAsync(instanceId, managedCertificateId, taskId, System.Threading.CancellationToken.None);
}

/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <summary>
/// Execute Deployment Task [Generated by Certify.SourceGenerators]
/// </summary>
/// <returns>OK</returns>
/// <exception cref="ApiException">A server side error occurred.</exception>
public virtual async System.Threading.Tasks.Task<System.Collections.Generic.ICollection<ActionStep>> ExecuteDeploymentTaskAsync(string instanceId, string managedCertificateId, string taskId, System.Threading.CancellationToken cancellationToken)
{
if (instanceId == null)
throw new System.ArgumentNullException("instanceId");

if (managedCertificateId == null)
throw new System.ArgumentNullException("managedCertificateId");

if (taskId == null)
throw new System.ArgumentNullException("taskId");

var client_ = _httpClient;
var disposeClient_ = false;
try
{
using (var request_ = new System.Net.Http.HttpRequestMessage())
{
request_.Method = new System.Net.Http.HttpMethod("GET");
request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain"));

var urlBuilder_ = new System.Text.StringBuilder();
if (!string.IsNullOrEmpty(_baseUrl)) urlBuilder_.Append(_baseUrl);
// Operation Path: "internal/v1/deploymenttask/{instanceId}/execute/{managedCertificateId}/{taskId}"
urlBuilder_.Append("internal/v1/deploymenttask/");
urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(instanceId, System.Globalization.CultureInfo.InvariantCulture)));
urlBuilder_.Append("/execute/");
urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(managedCertificateId, System.Globalization.CultureInfo.InvariantCulture)));
urlBuilder_.Append('/');
urlBuilder_.Append(System.Uri.EscapeDataString(ConvertToString(taskId, System.Globalization.CultureInfo.InvariantCulture)));

PrepareRequest(client_, request_, urlBuilder_);

var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);

PrepareRequest(client_, request_, url_);

var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var disposeResponse_ = true;
try
{
var headers_ = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>>();
foreach (var item_ in response_.Headers)
headers_[item_.Key] = item_.Value;
if (response_.Content != null && response_.Content.Headers != null)
{
foreach (var item_ in response_.Content.Headers)
headers_[item_.Key] = item_.Value;
}

ProcessResponse(client_, response_);

var status_ = (int)response_.StatusCode;
if (status_ == 200)
{
var objectResponse_ = await ReadObjectResponseAsync<System.Collections.Generic.ICollection<ActionStep>>(response_, headers_, cancellationToken).ConfigureAwait(false);
if (objectResponse_.Object == null)
{
throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null);
}
return objectResponse_.Object;
}
else
{
var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null);
}
}
finally
{
if (disposeResponse_)
response_.Dispose();
}
}
}
finally
{
if (disposeClient_)
client_.Dispose();
}
}

/// <summary>
/// Get all managed certificates matching criteria
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Certify.Client;
using Certify.Server.Api.Public.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -16,31 +17,18 @@ public partial class DeploymentTaskController : ApiControllerBase
private readonly ILogger<DeploymentTaskController> _logger;

private readonly ICertifyInternalApiClient _client;
private readonly ManagementAPI _mgmtAPI;

/// <summary>
/// Constructor
/// </summary>
/// <param name="logger"></param>
/// <param name="client"></param>
public DeploymentTaskController(ILogger<DeploymentTaskController> logger, ICertifyInternalApiClient client)
public DeploymentTaskController(ILogger<DeploymentTaskController> logger, ICertifyInternalApiClient client, ManagementAPI mgmtAPI)
{
_logger = logger;
_client = client;
}

/// <summary>
/// Get List of supported deployment tasks
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<Models.Config.DeploymentProviderDefinition>))]
[Route("providers")]
public async Task<IActionResult> GetDeploymentProviders()
{
var list = await _client.GetDeploymentProviderList();
return new OkObjectResult(list);
_mgmtAPI = mgmtAPI;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,16 @@ public async Task<StatusSummary> GetManagedCertificateSummary(AuthContext? curre
return await PerformInstanceCommandTaskWithResult<ActionResult?>(instanceId, args, ManagementHubCommands.UpdateCertificateAuthority);
}

public async Task<ActionResult?> RemoveCertificateAuthority(string instanceId, string id, AuthContext? currentAuthContext)
{
var args = new KeyValuePair<string, string>[] {
new("instanceId", instanceId),
new("id", id)
};

return await PerformInstanceCommandTaskWithResult<ActionResult?>(id, args, ManagementHubCommands.RemoveCertificateAuthority);
}

public async Task<ICollection<Models.AccountDetails>?> GetAcmeAccounts(string instanceId, AuthContext? currentAuthContext)
{
var args = new KeyValuePair<string, string>[] {
Expand All @@ -215,14 +225,41 @@ public async Task<StatusSummary> GetManagedCertificateSummary(AuthContext? curre

return await PerformInstanceCommandTaskWithResult<ActionResult?>(instanceId, args, ManagementHubCommands.AddAcmeAccount);
}
public async Task<ActionResult?> RemoveAcmeAccount(string instanceId, string storageKey, bool deactivate, AuthContext? currentAuthContext)
{
var args = new KeyValuePair<string, string>[] {
new("instanceId", instanceId),
new("storageKey", storageKey),
new("deactivate", deactivate.ToString())
};

return await PerformInstanceCommandTaskWithResult<ActionResult?>(instanceId, args, ManagementHubCommands.RemoveAcmeAccount);
}
public async Task<ICollection<ChallengeProviderDefinition>?> GetChallengeProviders(string instanceId, AuthContext? currentAuthContext)
{
var args = new KeyValuePair<string, string>[] {
new("instanceId", instanceId)
};
return await PerformInstanceCommandTaskWithResult<ICollection<ChallengeProviderDefinition>>(instanceId, args, ManagementHubCommands.GetChallengeProviders);
}
public async Task<ICollection<DeploymentProviderDefinition>?> GetDeploymentProviders(string instanceId, AuthContext? currentAuthContext)
{
var args = new KeyValuePair<string, string>[] {
new("instanceId", instanceId)
};
return await PerformInstanceCommandTaskWithResult<ICollection<DeploymentProviderDefinition>>(instanceId, args, ManagementHubCommands.GetDeploymentProviders);
}

public async Task<ICollection<ActionStep>?> ExecuteDeploymentTask(string instanceId, string managedCertificateId, string taskId, AuthContext? currentAuthContext)
{
var args = new KeyValuePair<string, string>[] {
new("instanceId", instanceId),
new("managedCertificateId", managedCertificateId),
new("taskId", taskId)
};

return await PerformInstanceCommandTaskWithResult<ICollection<ActionStep>>(instanceId, args, ManagementHubCommands.ExecuteDeploymentTask);
}

public async Task<ICollection<Models.Providers.DnsZone>?> GetDnsZones(string instanceId, string providerTypeId, string credentialId, AuthContext? currentAuthContext)
{
Expand Down
Loading

0 comments on commit 0c32cf9

Please sign in to comment.