-
Notifications
You must be signed in to change notification settings - Fork 30
Add stats feature to secret-manager #4970
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
166 changes: 166 additions & 0 deletions
166
src/SecretManager/Microsoft.DncEng.SecretManager/Commands/StatsCommand.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| using ConsoleTables; | ||
| using Microsoft.DncEng.CommandLineLib; | ||
| using Microsoft.DncEng.SecretManager.StorageTypes; | ||
| using Microsoft.VisualStudio.Services.Common; | ||
| using Mono.Options; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Command = Microsoft.DncEng.CommandLineLib.Command; | ||
|
|
||
| #nullable enable | ||
|
|
||
| namespace Microsoft.DncEng.SecretManager.Commands; | ||
|
|
||
| [Command("stats", Description = "Emit statistics about supplied manifests")] | ||
| internal class StatsCommand : Command | ||
| { | ||
| // Configuration info | ||
| // This list should be updated to include any SecretType<T> that might throw HumanInterventionRequiredException. | ||
| private readonly List<string> _humanRequiredTypes = | ||
| [ | ||
| "ad-application", | ||
| "domain-account", | ||
| "github-access-token", | ||
| "github-app-secret", | ||
| "github-account", | ||
| "github-oauth-secret", | ||
| "sql-connection-string", | ||
| "text" | ||
| ]; | ||
|
|
||
| // Provided by CLI flags | ||
| private bool _includeExpiration = false; | ||
| private readonly List<string> _manifestFiles = []; | ||
| private readonly List<string> _manifestDirectories = []; | ||
|
|
||
garath marked this conversation as resolved.
Show resolved
Hide resolved
garath marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Provided by DI | ||
| private readonly StorageLocationTypeRegistry _storageLocationTypeRegistry; | ||
| private readonly IConsole _console; | ||
|
|
||
| public StatsCommand(StorageLocationTypeRegistry storageLocationTypeRegistry, IConsole console) | ||
| { | ||
| _storageLocationTypeRegistry = storageLocationTypeRegistry; | ||
| _console = console; | ||
| } | ||
|
|
||
| public override OptionSet GetOptions() | ||
| { | ||
| return base.GetOptions().AddRange(new OptionSet() | ||
| { | ||
| {"m|manifest-file=", "The secret manifest file", f => _manifestFiles.Add(f)}, | ||
| {"p|manifest-path=", "A directory containing one or more manifests", f => _manifestDirectories.Add(f)}, | ||
| {"x|include-expiration", "If set, also determine expiration date of matching secrets", _ => _includeExpiration = true } | ||
| }); | ||
| } | ||
|
|
||
| public override bool AreRequiredOptionsSet() | ||
| { | ||
| return (_manifestFiles.Count + _manifestDirectories.Count) > 0; | ||
| } | ||
|
|
||
| public override async Task RunAsync(CancellationToken cancellationToken) | ||
| { | ||
| IEnumerable<string> missingManifestFiles = _manifestFiles | ||
| .Where(f => !File.Exists(f)); | ||
|
|
||
| if (missingManifestFiles.Any()) | ||
| { | ||
| throw new FailWithExitCodeException(86, $"The following manifest files were not found: {Environment.NewLine} {string.Join(Environment.NewLine, missingManifestFiles)}"); | ||
| } | ||
|
|
||
| IEnumerable<string> missingOrEmptyManifestPaths = _manifestDirectories | ||
| .Where(d => !Directory.EnumerateFiles(d, "*.yaml", SearchOption.TopDirectoryOnly).Any()); | ||
|
|
||
| if (missingOrEmptyManifestPaths.Any()) | ||
| { | ||
| throw new FailWithExitCodeException(86, $"The following manifest directories were not found or contained no manifests: {Environment.NewLine} {string.Join(Environment.NewLine, missingOrEmptyManifestPaths)}"); | ||
| } | ||
|
|
||
| _manifestFiles.AddRange( | ||
| _manifestDirectories | ||
| .SelectMany(d => Directory.EnumerateFiles(d, "*.yaml", SearchOption.TopDirectoryOnly)) | ||
| ); | ||
|
|
||
| int totalEntriesCount = 0; | ||
| List<HumanRequiredSecretsWithExpiryRow> rows = []; | ||
| foreach (string manifestFile in _manifestFiles) | ||
| { | ||
| SecretManifest manifest = SecretManifest.Read(manifestFile); | ||
|
|
||
| totalEntriesCount += manifest.Secrets.Count; | ||
|
|
||
| Dictionary<string, SecretManifest.Secret> humanRequiredSecrets = manifest.Secrets | ||
| .Where(secret => _humanRequiredTypes.Contains(secret.Value.Type)) | ||
| .ToDictionary(x => x.Key, x => x.Value); | ||
|
|
||
| if (humanRequiredSecrets.Count == 0) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (!_includeExpiration) | ||
| { | ||
| rows.AddRange(humanRequiredSecrets.Select(secret => new HumanRequiredSecretsWithExpiryRow(manifestFile, secret.Key, secret.Value.Type, null))); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| _console.WriteLine($"Gathering expiration for {humanRequiredSecrets.Count} secrets in {manifestFile}"); | ||
|
|
||
| using StorageLocationType.Bound storage = _storageLocationTypeRegistry | ||
| .Get(manifest.StorageLocation.Type).BindParameters(manifest.StorageLocation.Parameters); | ||
|
|
||
| Dictionary<string, SecretProperties> existingSecrets = (await storage.ListSecretsAsync()).ToDictionary(p => p.Name); | ||
|
|
||
| foreach (KeyValuePair<string, SecretManifest.Secret> secret in humanRequiredSecrets) | ||
| { | ||
| bool secretFoundInVault = existingSecrets.TryGetValue(secret.Key, out SecretProperties? existingSecretProperties); | ||
|
|
||
| if (!secretFoundInVault || existingSecretProperties is null) | ||
| { | ||
| rows.Add(new HumanRequiredSecretsWithExpiryRow(manifestFile, secret.Key, secret.Value.Type, "Not found in vault")); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| bool secretHasExpirationTag = existingSecretProperties.Tags.TryGetValue(AzureKeyVault.NextRotationOnTag, out string? nextRotationOnValue); | ||
|
|
||
| if (!secretHasExpirationTag || nextRotationOnValue is null) | ||
| { | ||
| rows.Add(new HumanRequiredSecretsWithExpiryRow(manifestFile, secret.Key, secret.Value.Type, "No expiration tag")); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| rows.Add(new HumanRequiredSecretsWithExpiryRow(manifestFile, secret.Key, secret.Value.Type, nextRotationOnValue)); | ||
| } | ||
| } | ||
|
|
||
| if (!rows.Any()) | ||
| { | ||
| Console.WriteLine("No human required secrets found"); | ||
| } | ||
|
|
||
| if (_includeExpiration) | ||
| { | ||
| ConsoleTable.From(rows) | ||
| .Write(Format.Minimal); | ||
| } | ||
| else | ||
| { | ||
| ConsoleTable.From(rows.Select(r => new { r.Manifest, r.Name, r.Type })) | ||
| .Write(Format.Minimal); | ||
| } | ||
|
|
||
| _console.WriteLine(string.Empty); | ||
| _console.WriteLine($"Total entries across all included manifests: {totalEntriesCount}"); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| private record HumanRequiredSecretsWithExpiryRow(string Manifest, string Name, string Type, string? Expiration); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.