-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathUtils.cs
1421 lines (1215 loc) · 46.9 KB
/
Utils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Security;
using Dbg = System.Diagnostics.Debug;
namespace Microsoft.PowerShell.SecretManagement
{
#region Utils
internal static class Utils
{
#region Members
private const string NoVaultRegistered = @"
There are currently no extension vaults registered.
At least one vault must be registered before SecretManagement can add or retrieve secrets.
You can download SecretManagement extension vault modules from PowerShellGallery.
https://aka.ms/SecretManagementVaults
";
private const string ImplementingExtension = "Extension";
private const string ConvertJsonToHashtableScript = @"
param (
[string] $json
)
function ConvertToHash
{
param (
[pscustomobject] $object
)
$output = @{}
$object | Get-Member -MemberType NoteProperty | ForEach-Object {
$name = $_.Name
$value = $object.($name)
if ($value -is [object[]])
{
$array = @()
$value | ForEach-Object {
$array += (ConvertToHash $_)
}
$output.($name) = $array
}
elseif ($value -is [pscustomobject])
{
$output.($name) = (ConvertToHash $value)
}
else
{
$output.($name) = $value
}
}
$output
}
$customObject = ConvertFrom-Json -InputObject $json
return ConvertToHash $customObject
";
#endregion
#region Constructor
static Utils()
{
IsWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(
System.Runtime.InteropServices.OSPlatform.Windows);
if (IsWindows)
{
var locationPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
SecretManagementLocalPath = Path.Combine(locationPath, "Microsoft", "PowerShell", "secretmanagement");
}
else
{
var locationPath = Environment.GetEnvironmentVariable("HOME");
SecretManagementLocalPath = Path.Combine(locationPath, ".secretmanagement");
}
}
#endregion
#region Properties
public static string SecretManagementLocalPath { get; }
public static bool IsWindows { get; }
#endregion
#region Methods
public static Hashtable ConvertJsonToHashtable(string json)
{
using (var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace))
{
var results = PowerShellInvoker.InvokeScriptOnPowerShell<Hashtable>(
script: ConvertJsonToHashtableScript,
args: new object[] { json },
psToUse: ps,
error: out ErrorRecord _);
return (results.Count > 0) ? results[0] : null;
}
}
public static Hashtable ConvertDictToHashtable(IDictionary<string, object> dict)
{
var returnHashtable = new Hashtable();
if (dict != null)
{
foreach (var item in dict)
{
returnHashtable.Add(item.Key, item.Value);
}
}
return returnHashtable;
}
public static string ConvertHashtableToJson(Hashtable hashtable)
{
var results = PowerShellInvoker.InvokeScript<string>(
script: @"param ([hashtable] $hashtable) ConvertTo-Json -InputObject $hashtable -Depth 10",
args: new object[] { hashtable },
error: out ErrorRecord _);
return (results.Count > 0) ? results[0] : null;
}
public static SecureString ConvertToSecureString(string secret)
{
var results = PowerShellInvoker.InvokeScript<SecureString>(
script: @"param([string] $value) ConvertTo-SecureString -String $value -AsPlainText -Force",
args: new object[] { secret },
error: out ErrorRecord _);
return (results.Count > 0) ? results[0] : null;
}
public static string GetModuleExtensionName(string moduleName)
{
return string.Format(CultureInfo.InvariantCulture,
@"{0}.{1}", moduleName, ImplementingExtension);
}
public static string TrimQuotes(string name)
{
return name.Trim('\'', '"');
}
public static string QuoteName(string name)
{
bool quotesNeeded = false;
foreach (var c in name)
{
if (Char.IsWhiteSpace(c))
{
quotesNeeded = true;
break;
}
}
if (!quotesNeeded)
{
return name;
}
return "'" + CodeGeneration.EscapeSingleQuotedStringContent(name) + "'";
}
public static void CheckForRegisteredVaults(PSCmdlet cmdlet)
{
if (RegisteredVaultCache.VaultExtensions.Count == 0)
{
cmdlet.WriteWarning(NoVaultRegistered);
}
}
#endregion
}
#endregion
#region Enums
/// <summary>
/// Supported secret types
/// </summary>
public enum SecretType
{
Unknown = 0,
ByteArray,
String,
SecureString,
PSCredential,
Hashtable
};
#endregion
#region Exceptions
public sealed class PasswordRequiredException : InvalidOperationException
{
#region Constructor
public PasswordRequiredException(string msg)
: base(msg)
{
}
#endregion
}
#endregion
#region SecretInformation class
public sealed class SecretInformation
{
#region Properties
/// <summary>
/// Gets the name of the secret.
/// </summary>
public string Name
{
get;
}
/// <summary>
/// Gets the object type of the secret.
/// </summary>
public SecretType Type
{
get;
}
/// <summary>
/// Gets the vault name where the secret resides.
/// </summary>
public string VaultName
{
get;
}
/// <summary>
/// Gets metadata of the secret.
/// </summary>
public ReadOnlyDictionary<string, object> Metadata
{
get;
}
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public SecretInformation(
string name,
SecretType type,
string vaultName)
{
Name = name;
Type = type;
VaultName = vaultName;
}
/// <summary>
/// Constructor
/// </summary>
public SecretInformation(
string name,
SecretType type,
string vaultName,
ReadOnlyDictionary<string, object> metadata) : this(name, type, vaultName)
{
Metadata = metadata;
}
/// <summary>
/// Constructor
/// </summary>
public SecretInformation(
string name,
SecretType type,
string vaultName,
Hashtable metadata) : this(name, type, vaultName)
{
if (metadata == null) { return; }
Dictionary<string, object> metaDictionary = new Dictionary<string, object>(metadata.Count);
foreach (var key in metadata.Keys)
{
metaDictionary.Add((string)key, metadata[key]);
}
Metadata = new ReadOnlyDictionary<string, object>(metaDictionary);
}
private SecretInformation()
{
}
#endregion
}
#endregion
#region Extension vault module class
/// <summary>
/// Class that contains all vault module information and secret manipulation methods.
/// </summary>
internal class ExtensionVaultModule
{
#region Members
#region Script
// Invokes Get-Secret, Set-Secret, Get-SecretInfo, Remove-Secret, Test-SecretVault commands in
// nested module within provided module path.
// Assumes the following directory structure:
// Module directory (parent module)
// Module.psd1
// Module.psm1
// ImplementingModule directory (nested module)
// ImplementingModule.psd1
// ImplementingModule.psm1
private const string RunCommandScript = @"
param (
[string] $ModulePath,
[string] $ImplementingModuleName,
[string] $Command,
[hashtable] $Params
)
$verboseEnabled = $Params.AdditionalParameters.ContainsKey('Verbose') -and ($Params.AdditionalParameters['Verbose'] -eq $true)
$module = Get-Module -Name ([System.IO.Path]::GetFileNameWithoutExtension($ImplementingModuleName)) -ErrorAction Ignore
if ($null -eq $module) {
$module = Import-Module -Name $ModulePath -PassThru
}
if ($null -eq $module) {
return
}
Write-Verbose ""Invoking command $Command on module $ImplementingModuleName"" -Verbose:$verboseEnabled
& $module ""$ImplementingModuleName\$Command"" @Params
";
// Conditionally invokes an optional command if supported by the implementing module.
// Assumes the following directory structure:
// Module directory (parent module)
// Module.psd1
// Module.psm1
// ImplementingModule directory (nested module)
// ImplementingModule.psd1
// ImplementingModule.psm1
private const string RunIfCommandScript = @"
param (
[string] $ModulePath,
[string] $ImplementingModuleName,
[string] $Command,
[hashtable] $Params
)
$verboseEnabled = $Params.AdditionalParameters.ContainsKey('Verbose') -and ($Params.AdditionalParameters['Verbose'] -eq $true)
$module = Get-Module -Name ([System.IO.Path]::GetFileNameWithoutExtension($ImplementingModuleName)) -ErrorAction Ignore
if ($null -eq $module) {
$module = Import-Module -Name $ModulePath -PassThru
}
if ($null -eq $module) {
return
}
try {
Write-Verbose ""Invoking command $Command on module $ImplementingModuleName"" -Verbose:$verboseEnabled
& $module ""$ImplementingModuleName\$Command"" @Params
}
catch [System.Management.Automation.CommandNotFoundException] {
Write-Verbose ""Module $ImplementingModuleName does not support command : $Command"" -Verbose:$verboseEnabled
}
";
// Return values:
// 0 - Command ran (command will emit any error message)
// 1 - Module not found
// 2 - Command not found
private const string RunConditionalCommandScript = @"
param (
[string] $ModulePath,
[string] $ImplementingModuleName,
[string] $Command,
[hashtable] $Params
)
$verboseEnabled = $Params.AdditionalParameters.ContainsKey('Verbose') -and ($Params.AdditionalParameters['Verbose'] -eq $true)
$module = Get-Module -Name ([System.IO.Path]::GetFileNameWithoutExtension($ImplementingModuleName)) -ErrorAction Ignore
if ($null -eq $module) {
$module = Import-Module -Name $ModulePath -PassThru
}
if ($null -eq $module) {
return 1
}
try {
Write-Verbose ""Invoking command $Command on module $ImplementingModuleName"" -Verbose:$verboseEnabled
$null = & $module ""$ImplementingModuleName\$Command"" @Params
return 0
}
catch [System.Management.Automation.CommandNotFoundException] {
return 2
}
";
#endregion
internal const string GetSecretCmd = "Get-Secret";
internal const string GetSecretInfoCmd = "Get-SecretInfo";
internal const string SetSecretCmd = "Set-Secret";
internal const string SetSecretInfoCmd = "Set-SecretInfo";
internal const string RemoveSecretCmd = "Remove-Secret";
internal const string TestVaultCmd = "Test-SecretVault";
internal const string UnregisterSecretVaultCommand = "Unregister-SecretVault";
internal const string ModuleNameStr = "ModuleName";
internal const string ModulePathStr = "ModulePath";
internal const string VaultParametersStr = "VaultParameters";
internal const string DescriptionStr = "Description";
internal const string SetSecretSupportsMetadataStr = "SetSecretSupportsMetadata";
#endregion
#region Properties
/// <summary>
/// Name of extension vault.
/// </summary>
public string VaultName { get; }
/// <summary>
/// Module name to qualify module commands.
/// </summary>
public string ModuleName { get; }
/// <summary>
/// Name of module extension which implements required functions.
/// </summary>
public string ModuleExtensionName { get; }
/// <summary>
/// Module path.
/// </summary>
public string ModulePath { get; }
/// <summary>
/// Additional vault parameters.
/// <summary>
public IReadOnlyDictionary<string, object> VaultParameters { get; }
/// <summary>
/// True when this extension vault is the default vault.
/// </summary>
public bool IsDefault { get; }
/// <summary>
/// Optional description string for vault.
/// </summary>
public string Description { get; }
/// <summary>
/// True when this extension vault Set-Secret function supports the Metadata parameter.
/// </summary>
public bool SetSecretSupportsMetadata { get; }
#endregion
#region Constructor
private ExtensionVaultModule()
{
}
/// <summary>
/// Initializes a new instance of ExtensionVaultModule.
/// </summary>
public ExtensionVaultModule(
string vaultName,
Hashtable vaultInfo,
bool isDefault)
{
// Module information.
IsDefault = isDefault;
VaultName = vaultName;
ModuleName = (string) vaultInfo[ModuleNameStr];
ModuleExtensionName = Utils.GetModuleExtensionName(ModuleName);
ModulePath = (string) vaultInfo[ModulePathStr];
Description = vaultInfo.ContainsKey(DescriptionStr) ? (string) vaultInfo[DescriptionStr] : string.Empty;
SetSecretSupportsMetadata = vaultInfo.ContainsKey(SetSecretSupportsMetadataStr) ?
(bool) vaultInfo[SetSecretSupportsMetadataStr] : false;
// Additional parameters.
var vaultParameters = new Dictionary<string, object>();
if (vaultInfo.ContainsKey(VaultParametersStr))
{
var vaultParamsHashtable = (Hashtable) vaultInfo[VaultParametersStr];
foreach (string key in vaultParamsHashtable.Keys)
{
vaultParameters.Add(
key: key,
value: vaultParamsHashtable[key]);
}
}
VaultParameters = new ReadOnlyDictionary<string, object>(vaultParameters);
}
/// <summary>
/// Initializes a new instance of ExtensionVaultModule from an existing instance.
/// </summary>
public ExtensionVaultModule(
ExtensionVaultModule module)
{
VaultName = module.VaultName;
ModuleName = module.ModuleName;
ModuleExtensionName = module.ModuleExtensionName;
ModulePath = module.ModulePath;
Description = module.Description;
VaultParameters = module.VaultParameters;
IsDefault = module.IsDefault;
SetSecretSupportsMetadata = module.SetSecretSupportsMetadata;
}
#endregion
#region Public methods
/// <summary>
/// Invoke SetSecret method on vault extension.
/// </summary>
/// <param name="name">Name of secret to add.</param>
/// <param name="secret">Secret object to add.</param>
/// <param name="vaultName">Name of registered vault.</param>
/// <param name="metadata">Optional metadata associated with the secret.</param>
/// <param name="cmdlet">Calling cmdlet.</param>
public void InvokeSetSecret(
string name,
object secret,
string vaultName,
Hashtable metadata,
PSCmdlet cmdlet)
{
var additionalParameters = GetAdditionalParams(cmdlet);
var parameters = new Hashtable() {
{ "Name", name },
{ "Secret", secret },
{ "VaultName", vaultName },
{ "AdditionalParameters", additionalParameters }
};
// Include metadata if supported by vault.
if (SetSecretSupportsMetadata)
{
parameters.Add(
key: "Metadata",
value: metadata ?? new Hashtable());
}
InvokeOnCmdlet(
cmdlet: cmdlet,
script: RunCommandScript,
args: new object[] { ModulePath, ModuleExtensionName, SetSecretCmd, parameters },
out Exception terminatingError);
if (terminatingError != null)
{
ThrowPasswordRequiredException(terminatingError);
cmdlet.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: string.Format("Unable to add secret {0} to vault {1}", name, VaultName),
innerException: terminatingError),
"SetSecretInvalidOperation",
ErrorCategory.InvalidOperation,
this));
return;
}
// If metadata is provided but not supported through Set-Secret parameter, then attempt to call
// the separate vault Set-SecretInfo function as an alternative.
if (metadata?.Count > 0 && !SetSecretSupportsMetadata &&
!InvokeSetSecretMetadata(
name: name,
metadata: metadata,
vaultName: vaultName,
cmdlet: cmdlet))
{
// Unable to write metadata, probably because metadata is not supported by the extension vault.
// Remove the secret from the vault, since it did not fully write.
cmdlet.WriteError(
new ErrorRecord(
new PSNotSupportedException(
message: string.Format("Cannot store secret {0}. Vault {1} does not support secret metadata.", name, VaultName)),
"InvokeSetSecretMetadataNotSupported",
ErrorCategory.NotImplemented,
cmdlet));
InvokeRemoveSecret(
name: name,
vaultName: vaultName,
cmdlet: cmdlet);
return;
}
cmdlet.WriteVerbose(
string.Format("Secret {0} was successfully added to vault {1}.", name, VaultName));
}
public bool InvokeSetSecretMetadata(
string name,
Hashtable metadata,
string vaultName,
PSCmdlet cmdlet)
{
var additionalParameters = GetAdditionalParams(cmdlet);
var parameters = new Hashtable() {
{ "Name", name },
{ "Metadata", metadata },
{ "VaultName", vaultName },
{ "AdditionalParameters", additionalParameters }
};
// Result values:
// 0 - Command ran (command will emit any error message)
// 1 - Module not found
// 2 - Command not found
var results = InvokeOnCmdlet<int>(
cmdlet: cmdlet,
script: RunConditionalCommandScript,
args: new object[] { ModulePath, ModuleExtensionName, SetSecretInfoCmd, parameters },
out Exception terminatingError);
if (terminatingError != null)
{
ThrowPasswordRequiredException(terminatingError);
cmdlet.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: string.Format("Unable to add secret metadata {0} to vault {1}", name, VaultName),
innerException: terminatingError),
"SetSecretMetadataInvalidOperation",
ErrorCategory.InvalidOperation,
this));
return false;
}
int result = (results.Count > 0) ? results[0] : 0;
var success = result == 0;
if (success)
{
cmdlet.WriteVerbose(
string.Format("Secret metadata {0} was successfully added to vault {1}.", name, VaultName));
}
return success;
}
/// <summary>
/// Looks up a single secret by name.
/// </summary>
/// <returns>Secret object</returns>
public object InvokeGetSecret(
string name,
string vaultName,
PSCmdlet cmdlet)
{
var additionalParameters = GetAdditionalParams(cmdlet);
var parameters = new Hashtable() {
{ "Name", name },
{ "VaultName", vaultName },
{ "AdditionalParameters", additionalParameters }
};
var results = InvokeOnCmdlet<object>(
cmdlet: cmdlet,
script: RunCommandScript,
args: new object[] { ModulePath, ModuleExtensionName, GetSecretCmd, parameters },
out Exception terminatingError);
if (terminatingError != null)
{
ThrowPasswordRequiredException(terminatingError);
cmdlet.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: string.Format("Unable to get secret {0} from vault {1}", name, VaultName),
innerException: terminatingError),
"GetSecretInvalidOperation",
ErrorCategory.InvalidOperation,
this));
}
else
{
cmdlet.WriteVerbose(
string.Format("Secret {0} was successfully retrieved from vault {1}.", name, VaultName));
}
if (results.Count > 0)
{
if (results[0] is byte)
{
// Re-wrap collection of bytes into a byte array.
byte[] byteArray = new byte[results.Count];
for (int i=0; i<results.Count; i++)
{
byteArray[i] = (byte) results[i];
}
return byteArray;
}
return results[0];
}
return null;
}
/// <summary>
/// Remove a single secret.
/// </summary>
public void InvokeRemoveSecret(
string name,
string vaultName,
PSCmdlet cmdlet)
{
var additionalParameters = GetAdditionalParams(cmdlet);
var parameters = new Hashtable() {
{ "Name", name },
{ "VaultName", vaultName },
{ "AdditionalParameters", additionalParameters }
};
InvokeOnCmdlet(
cmdlet: cmdlet,
script: RunCommandScript,
args: new object[] { ModulePath, ModuleExtensionName, RemoveSecretCmd, parameters },
out Exception terminatingError);
if (terminatingError != null)
{
ThrowPasswordRequiredException(terminatingError);
cmdlet.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: string.Format("Unable to remove secret {0} from vault {1}", name, VaultName),
innerException: terminatingError),
"RemoveSecretInvalidOperation",
ErrorCategory.InvalidOperation,
this));
}
else
{
cmdlet.WriteVerbose(
string.Format("Secret {0} was successfully removed from vault {1}.", name, VaultName));
}
}
/// <summary>
/// Returns secret meta data.
/// </summary>
public SecretInformation[] InvokeGetSecretInfo(
string filter,
string vaultName,
PSCmdlet cmdlet)
{
var additionalParameters = GetAdditionalParams(cmdlet);
var parameters = new Hashtable() {
{ "Filter", filter },
{ "VaultName", vaultName },
{ "AdditionalParameters", additionalParameters }
};
var results = InvokeOnCmdlet<SecretInformation>(
cmdlet: cmdlet,
script: RunCommandScript,
args: new object[] { ModulePath, ModuleExtensionName, GetSecretInfoCmd, parameters },
out Exception terminatingError);
if (terminatingError != null)
{
ThrowPasswordRequiredException(terminatingError);
cmdlet.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: string.Format("Unable to get secret information from vault {0}", VaultName),
innerException: terminatingError),
"GetSecretInfoInvalidOperation",
ErrorCategory.InvalidOperation,
this));
}
else
{
cmdlet.WriteVerbose(
string.Format("Secret information was successfully retrieved from vault {0}.", VaultName));
}
var secretInfo = new SecretInformation[results.Count];
results.CopyTo(secretInfo, 0);
return secretInfo;
}
public bool InvokeTestVault(
string vaultName,
PSCmdlet cmdlet)
{
var additionalParameters = GetAdditionalParams(cmdlet);
var parameters = new Hashtable() {
{ "VaultName", VaultName },
{ "AdditionalParameters", additionalParameters }
};
var results = InvokeOnCmdlet<bool>(
cmdlet: cmdlet,
script: RunCommandScript,
args: new object[] { ModulePath, ModuleExtensionName, TestVaultCmd, parameters },
out Exception terminatingError);
if (terminatingError != null)
{
ThrowPasswordRequiredException(terminatingError);
cmdlet.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: string.Format("Unable to run Test-SecretVault on vault {0}", VaultName),
innerException: terminatingError),
"TestSecretVaultInvalidOperation",
ErrorCategory.InvalidOperation,
this));
}
return (results.Count > 0) ? results[0] : false;
}
/// <Summary>
/// Optional Unregister-Vault extension command. Will invoke if available.
/// </Summary>
public void InvokeUnregisterVault(
PSCmdlet cmdlet)
{
var additionalParameters = GetAdditionalParams(cmdlet);
var parameters = new Hashtable() {
{ "VaultName", VaultName },
{ "AdditionalParameters", additionalParameters }
};
InvokeOnCmdlet(
cmdlet: cmdlet,
script: RunIfCommandScript,
args: new object[] { ModulePath, ModuleExtensionName, UnregisterSecretVaultCommand, parameters },
out Exception terminatingError);
if (terminatingError != null)
{
ThrowPasswordRequiredException(terminatingError);
cmdlet.WriteError(
new ErrorRecord(
new PSInvalidOperationException(
message: string.Format("An error occurred while running Unregister-SecretVault on vault {0}, Error: {1}",
VaultName, terminatingError.Message),
innerException: terminatingError),
"UnregisterSecretVaultInvalidOperation",
ErrorCategory.InvalidOperation,
this));
}
}
/// <summary>
/// Creates copy of this extension module object instance.
/// </summary>
public ExtensionVaultModule Clone()
{
return new ExtensionVaultModule(this);
}
#endregion
#region Private methods
private void ThrowPasswordRequiredException(Exception ex)
{
// Unwrap a PasswordRequiredException inner exception and throw directly.
if (ex.InnerException is PasswordRequiredException passwordRequiredEx)
{
throw passwordRequiredEx;
}
}
private Hashtable GetAdditionalParams(PSCmdlet cmdlet)
{
var additionalParams = new Hashtable();
foreach (var item in VaultParameters)
{
additionalParams.Add(
key: item.Key,
value: item.Value);
}
bool verboseEnabled = cmdlet.MyInvocation.BoundParameters.TryGetValue("Verbose", out dynamic verbose)
? verbose.IsPresent : false;
if (additionalParams.ContainsKey("Verbose"))
{
additionalParams.Remove("Verbose");
}
additionalParams.Add("Verbose", verboseEnabled);
return additionalParams;
}
private static Collection<PSObject> InvokeOnCmdlet(
PSCmdlet cmdlet,
string script,
object[] args,
out Exception terminatingError)
{
try
{
terminatingError = null;
return cmdlet.InvokeCommand.InvokeScript(
script: script,
useNewScope: true,
writeToPipeline: PipelineResultTypes.Error,
input: null,
args: args);
}
catch (Exception ex)
{
terminatingError = ex;
return new Collection<PSObject>();
}
}
private static Collection<T> InvokeOnCmdlet<T>(
PSCmdlet cmdlet,
string script,
object[] args,
out Exception terminatingError)
{
var results = InvokeOnCmdlet(
cmdlet: cmdlet,
script: script,
args: args,
out terminatingError);
var returnCollection = new Collection<T>();
if (terminatingError != null || results.Count == 0)
{
return returnCollection;
}
foreach (var psItem in results)
{
if (psItem != null && psItem.BaseObject is T result)
{
returnCollection.Add(result);
}
}
return returnCollection;
}
#endregion
}
#endregion
#region RegisteredVaultCache