Skip to content

Commit

Permalink
chore: Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
spbsoluble committed Sep 17, 2024
1 parent 4c3b9d4 commit e183886
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 55 deletions.
45 changes: 30 additions & 15 deletions kubernetes-orchestrator-extension/Clients/KubeClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,15 @@ private K8SConfiguration ParseKubeConfig(string kubeconfig, bool skipTLSVerify =
{
_logger.LogTrace("Entered ParseKubeConfig()");
var k8SConfiguration = new K8SConfiguration();

_logger.LogTrace("Checking if kubeconfig is null or empty");
if (string.IsNullOrEmpty(kubeconfig))
{
_logger.LogError("kubeconfig is null or empty");
throw new KubeConfigException("kubeconfig is null or empty, please provide a valid kubeconfig in JSON format. For more information on how to create a kubeconfig file, please visit https://github.com/Keyfactor/k8s-orchestrator/tree/main/scripts/kubernetes#example-service-account-json");
throw new KubeConfigException(
"kubeconfig is null or empty, please provide a valid kubeconfig in JSON format. For more information on how to create a kubeconfig file, please visit https://github.com/Keyfactor/k8s-orchestrator/tree/main/scripts/kubernetes#example-service-account-json");
}

try
{
// test if kubeconfig is base64 encoded
Expand All @@ -119,10 +120,11 @@ private K8SConfiguration ParseKubeConfig(string kubeconfig, bool skipTLSVerify =
if (!kubeconfig.StartsWith("{"))
{
_logger.LogError("kubeconfig is not a JSON object");
throw new KubeConfigException("kubeconfig is not a JSON object, please provide a valid kubeconfig in JSON format. For more information on how to create a kubeconfig file, please visit: https://github.com/Keyfactor/k8s-orchestrator/tree/main/scripts/kubernetes#get_service_account_credssh");
throw new KubeConfigException(
"kubeconfig is not a JSON object, please provide a valid kubeconfig in JSON format. For more information on how to create a kubeconfig file, please visit: https://github.com/Keyfactor/k8s-orchestrator/tree/main/scripts/kubernetes#get_service_account_credssh");
// return k8SConfiguration;
}
}


_logger.LogDebug("Parsing kubeconfig as a dictionary of string, string");

Expand Down Expand Up @@ -152,18 +154,21 @@ private K8SConfiguration ParseKubeConfig(string kubeconfig, bool skipTLSVerify =
_logger.LogTrace("Creating Cluster object for cluster '{Name}'", clusterMetadata["name"]?.ToString());
// get environment variable for skip tls verify and convert to bool
var skipTlsEnvStr = Environment.GetEnvironmentVariable("KEYFACTOR_ORCHESTRATOR_SKIP_TLS_VERIFY");
_logger.LogTrace("KEYFACTOR_ORCHESTRATOR_SKIP_TLS_VERIFY environment variable: {SkipTlsVerify}", skipTlsEnvStr);
if (!string.IsNullOrEmpty(skipTlsEnvStr) && (bool.TryParse(skipTlsEnvStr, out var skipTlsVerifyEnv) || skipTlsEnvStr == "1"))
_logger.LogTrace("KEYFACTOR_ORCHESTRATOR_SKIP_TLS_VERIFY environment variable: {SkipTlsVerify}",
skipTlsEnvStr);
if (!string.IsNullOrEmpty(skipTlsEnvStr) &&
(bool.TryParse(skipTlsEnvStr, out var skipTlsVerifyEnv) || skipTlsEnvStr == "1"))
{
if (skipTlsEnvStr == "1") skipTlsVerifyEnv = true;
_logger.LogDebug("Setting skip-tls-verify to {SkipTlsVerify}", skipTlsVerifyEnv);
if (skipTlsVerifyEnv && !skipTLSVerify)
{
_logger.LogWarning("Skipping TLS verification is enabled in environment variable KEYFACTOR_ORCHESTRATOR_SKIP_TLS_VERIFY this takes the highest precedence and verification will be skipped. To disable this, set the environment variable to 'false' or remove it");
_logger.LogWarning(
"Skipping TLS verification is enabled in environment variable KEYFACTOR_ORCHESTRATOR_SKIP_TLS_VERIFY this takes the highest precedence and verification will be skipped. To disable this, set the environment variable to 'false' or remove it");
skipTLSVerify = true;
}
}

var clusterObj = new Cluster
{
Name = clusterMetadata["name"]?.ToString(),
Expand Down Expand Up @@ -242,7 +247,7 @@ private IKubernetes GetKubeClient(string kubeconfig)
_logger.LogDebug("Calling ParseKubeConfig()");
var k8SConfiguration = ParseKubeConfig(kubeconfig);
_logger.LogDebug("Finished calling ParseKubeConfig()");

// use k8sConfiguration over credentialFileName
KubernetesClientConfiguration config;
if (k8SConfiguration != null) // Config defined in store parameters takes highest precedence
Expand All @@ -260,7 +265,9 @@ private IKubernetes GetKubeClient(string kubeconfig)
config = KubernetesClientConfiguration.BuildDefaultConfig();
}
}
else if (string.IsNullOrEmpty(credentialFileName)) // If no config defined in store parameters, use default config. This should never happen though.
else if
(string.IsNullOrEmpty(
credentialFileName)) // If no config defined in store parameters, use default config. This should never happen though.
{
_logger.LogWarning(
"No config defined in store parameters, using default config. This should never happen!");
Expand Down Expand Up @@ -1802,7 +1809,7 @@ public List<string> DiscoverSecrets(string[] allowedKeys, string secType, string
_logger.LogTrace("Client BaseUrl: {BaseUrl}", Client.BaseUri);
_logger.LogDebug("Calling CoreV1.ListNamespace()");
namespaces = Client.CoreV1.ListNamespace();

_logger.LogDebug("returned from CoreV1.ListNamespace()");
_logger.LogTrace("namespaces.Items.Count: {Count}", namespaces.Items.Count);
_logger.LogTrace("namespaces.Items: {Items}", namespaces.Items.ToString());
Expand All @@ -1818,7 +1825,8 @@ public List<string> DiscoverSecrets(string[] allowedKeys, string secType, string
if (nsLi != "all" && nsLi != nsObj.Metadata.Name)
{
_logger.LogWarning(
"Skipping namespace '{Namespace}' because it does not match the namespace filter", nsObj.Metadata.Name);
"Skipping namespace '{Namespace}' because it does not match the namespace filter",
nsObj.Metadata.Name);
continue;
}

Expand Down Expand Up @@ -2194,7 +2202,7 @@ public CsrObject GenerateCertificateRequest(string name, string[] sans, IPAddres
X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature,
false));
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, false));
new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));
request.CertificateExtensions.Add(sanBuilder.Build());
var csr = request.CreateSigningRequest();
var csrPem = "-----BEGIN CERTIFICATE REQUEST-----\r\n" +
Expand Down Expand Up @@ -2314,4 +2322,11 @@ public V1Secret CreateOrUpdatePkcs12Secret(Pkcs12Secret k8SData, string kubeSecr
// Replace existing secret
return Client.CoreV1.ReplaceNamespacedSecret(s1, kubeSecretName, kubeNamespace);
}

public struct CsrObject
{
public string Csr;
public string PrivateKey;
public string PublicKey;
}
}
75 changes: 35 additions & 40 deletions kubernetes-orchestrator-extension/Jobs/JobBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -506,33 +506,40 @@ protected string ResolveStorePath(string spath)

break;
case 2 when IsClusterStore(Capability):
Logger.LogWarning("`StorePath`: `{StorePath}` is 2 parts this is not a valid combination for `K8SCluster` and will be ignored", spath);
Logger.LogWarning(
"`StorePath`: `{StorePath}` is 2 parts this is not a valid combination for `K8SCluster` and will be ignored",
spath);
break;
case 2 when IsNamespaceStore(Capability):
var nsPrefix = sPathParts[0];
Logger.LogTrace("nsPrefix: {NsPrefix}", nsPrefix);
var nsName = sPathParts[1];
Logger.LogTrace("nsName: {NsName}", nsName);

Logger.LogInformation(
"`StorePath`: `{StorePath}` is 2 parts and store type is `K8SNS`, assuming that store path pattern is either `<cluster_name>/<namespace_name>` or `namespace/<namespace_name>`", spath);
"`StorePath`: `{StorePath}` is 2 parts and store type is `K8SNS`, assuming that store path pattern is either `<cluster_name>/<namespace_name>` or `namespace/<namespace_name>`",
spath);
if (string.IsNullOrEmpty(KubeNamespace))
{
Logger.LogInformation("`KubeNamespace` is empty, setting `KubeNamespace` to `{Namespace}`", nsName);
KubeNamespace = nsName;
}
else
{
Logger.LogInformation("`KubeNamespace` parameter is not empty, ignoring `StorePath` value `{StorePath}`", spath);
Logger.LogInformation(
"`KubeNamespace` parameter is not empty, ignoring `StorePath` value `{StorePath}`", spath);
}

break;
case 2:
Logger.LogInformation("`StorePath`: `{StorePath}` is 2 parts, assuming that store path pattern is the `<cluster>/<secret_name>` ", spath);
Logger.LogInformation(
"`StorePath`: `{StorePath}` is 2 parts, assuming that store path pattern is the `<cluster>/<secret_name>` ",
spath);
var kNs = sPathParts[0];
Logger.LogTrace("kNs: {KubeNamespace}", kNs);
var kSn = sPathParts[1];
Logger.LogTrace("kSn: {KubeSecretName}", kSn);

if (string.IsNullOrEmpty(KubeNamespace))
{
Logger.LogInformation("`KubeNamespace` is not set, setting `KubeNamespace` to `{Namespace}`", kNs);
Expand All @@ -555,10 +562,14 @@ protected string ResolveStorePath(string spath)

break;
case 3 when IsClusterStore(Capability):
Logger.LogError("`StorePath`: `{StorePath}` is 3 parts and store type is `K8SCluster`, this is not a valid combination and `StorePath` will be ignored", spath);
Logger.LogError(
"`StorePath`: `{StorePath}` is 3 parts and store type is `K8SCluster`, this is not a valid combination and `StorePath` will be ignored",
spath);
break;
case 3 when IsNamespaceStore(Capability):
Logger.LogInformation("`StorePath`: `{StorePath}` is 3 parts and store type is `K8SNS`, assuming that store path pattern is `<cluster>/namespace/<namespace_name>`", spath);
Logger.LogInformation(
"`StorePath`: `{StorePath}` is 3 parts and store type is `K8SNS`, assuming that store path pattern is `<cluster>/namespace/<namespace_name>`",
spath);
var nsCluster = sPathParts[0];
Logger.LogTrace("nsCluster: {NsCluster}", nsCluster);
var nsClarifier = sPathParts[1];
Expand All @@ -568,33 +579,37 @@ protected string ResolveStorePath(string spath)

if (string.IsNullOrEmpty(KubeNamespace))
{
Logger.LogInformation("`KubeNamespace` is not set, setting `KubeNamespace` to `{Namespace}`", nsName3);
Logger.LogInformation("`KubeNamespace` is not set, setting `KubeNamespace` to `{Namespace}`",
nsName3);
KubeNamespace = nsName3;
}
else
{
Logger.LogInformation("`KubeNamespace` is set, ignoring `StorePath` value `{StorePath}`", spath);
Logger.LogInformation("`KubeNamespace` is set, ignoring `StorePath` value `{StorePath}`", spath);
}

if (!string.IsNullOrEmpty(KubeSecretName))
{
Logger.LogWarning("`KubeSecretName` parameter is not empty, but is not supported for `K8SNS` store type and will be ignored");
Logger.LogWarning(
"`KubeSecretName` parameter is not empty, but is not supported for `K8SNS` store type and will be ignored");
KubeSecretName = "";
}

break;
case 3:
Logger.LogInformation("Store path is 3 parts assuming that it is the '<cluster_name>/<namespace_name>/<secret_name>`");
Logger.LogInformation(
"Store path is 3 parts assuming that it is the '<cluster_name>/<namespace_name>/<secret_name>`");
var kH = sPathParts[0];
Logger.LogTrace("kH: {KubeHost}", kH);
var kN = sPathParts[1];
Logger.LogTrace("kN: {KubeNamespace}", kN);
var kS = sPathParts[2];
Logger.LogTrace("kS: {KubeSecretName}", kS);

if (kN is "secret" or "tls" or "certificate" or "namespace")
{
Logger.LogInformation("Store path is 3 parts and the second part is a reserved keyword, assuming that it is the '<cluster_name>/<namespace_name>/<secret_name>'");
Logger.LogInformation(
"Store path is 3 parts and the second part is a reserved keyword, assuming that it is the '<cluster_name>/<namespace_name>/<secret_name>'");
kN = sPathParts[0];
kS = sPathParts[1];
}
Expand Down Expand Up @@ -887,11 +902,11 @@ private void InitializeProperties(dynamic storeProperties)

Logger.LogTrace("Creating new KubeCertificateManagerClient object");
KubeClient = new KubeCertificateManagerClient(KubeSvcCreds);

Logger.LogTrace("Getting KubeHost and KubeCluster from KubeClient");
KubeHost = KubeClient.GetHost();
Logger.LogTrace("KubeHost: {KubeHost}", KubeHost);

Logger.LogTrace("Getting cluster name from KubeClient");
KubeCluster = KubeClient.GetClusterName();
Logger.LogTrace("KubeCluster: {KubeCluster}", KubeCluster);
Expand Down Expand Up @@ -940,17 +955,11 @@ public string GetStorePath()


if (Capability.Contains("K8SNS"))
{
secretType = "namespace";
}
else if (Capability.Contains("K8SCluster"))
{
secretType = "cluster";
}
else
{
secretType = KubeSecretType.ToLower();
}

Logger.LogTrace("secretType: {SecretType}", secretType);
Logger.LogTrace("Entered switch statement based on secretType");
Expand Down Expand Up @@ -1000,15 +1009,14 @@ public string GetStorePath()
Logger.LogError("Unknown error constructing canonical store path {Error}", e.Message);
return StorePath;
}

}

protected string ResolvePamField(string name, string value)
{
try
{
Logger.LogTrace($"Attempting to resolved PAM eligible field {name}");
return Resolver.Resolve(value);
return _resolver.Resolve(value);
}
catch (Exception e)
{
Expand All @@ -1018,7 +1026,6 @@ protected string ResolvePamField(string name, string value)
Logger.LogTrace(e.StackTrace);
return value;
}

}

protected byte[] GetKeyBytes(X509Certificate2 certObj, string certPassword = null)
Expand Down Expand Up @@ -1075,7 +1082,6 @@ protected byte[] GetKeyBytes(X509Certificate2 certObj, string certPassword = nul
try
{
if (certObj.HasPrivateKey)
{
try
{
Logger.LogDebug("Attempting to export private key as PKCS8");
Expand Down Expand Up @@ -1104,7 +1110,6 @@ protected byte[] GetKeyBytes(X509Certificate2 certObj, string certPassword = nul
Logger.LogTrace("ExportEncryptedPkcs8PrivateKey() complete");
return keyBytes;
}
}
}
catch (Exception ie)
{
Expand Down Expand Up @@ -1133,13 +1138,10 @@ protected static JobResult SuccessJob(long jobHistoryId, string jobMessage = nul
var result = new JobResult
{
Result = OrchestratorJobStatusJobResult.Success,
JobHistoryId = jobHistoryId,
JobHistoryId = jobHistoryId
};

if (!string.IsNullOrEmpty(jobMessage))
{
result.FailureMessage = jobMessage;
}
if (!string.IsNullOrEmpty(jobMessage)) result.FailureMessage = jobMessage;

return result;
}
Expand Down Expand Up @@ -1266,15 +1268,11 @@ protected string getK8SStorePassword(V1Secret certData)
Logger.LogDebug("No password found");
var passwdEx = "";
if (!string.IsNullOrEmpty(StorePasswordPath))
{
passwdEx = "Store secret '" + StorePasswordPath + "'did not contain key '" + CertificateDataFieldName +
"' or '" + PasswordFieldName + "'" +
" Please provide a valid store password and try again";
}
else
{
passwdEx = "Invalid store password. Please provide a valid store password and try again";
}

Logger.LogError("{Msg}", passwdEx);
throw new Exception(passwdEx);
Expand Down Expand Up @@ -1306,10 +1304,7 @@ protected Pkcs12Store LoadPkcs12Store(byte[] pkcs12Data, string password)
protected string GetCertificatePem(Pkcs12Store store, string password, string alias = "")
{
Logger.LogDebug("Entered GetCertificatePem()");
if (string.IsNullOrEmpty(alias))
{
alias = store.Aliases.Cast<string>().FirstOrDefault(store.IsKeyEntry);
}
if (string.IsNullOrEmpty(alias)) alias = store.Aliases.Cast<string>().FirstOrDefault(store.IsKeyEntry);

Logger.LogDebug("Attempting to get certificate with alias {Alias}", alias);
var cert = store.GetCertificate(alias).Certificate;
Expand Down

0 comments on commit e183886

Please sign in to comment.