-
Notifications
You must be signed in to change notification settings - Fork 43
Resolve env-dependent storybook.registry via allow-listed interpolation #3486
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
Open
clintandrewhall
wants to merge
2
commits into
main
Choose a base branch
from
storybook-registry-env-interpolation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
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
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
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
94 changes: 94 additions & 0 deletions
94
src/Elastic.Documentation.Configuration/EnvironmentInterpolation.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,94 @@ | ||
| // Licensed to Elasticsearch B.V under one or more agreements. | ||
| // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
| // See the LICENSE file in the project root for more information | ||
|
|
||
| using System.Collections.Frozen; | ||
| using System.Text; | ||
| using System.Text.RegularExpressions; | ||
| using Elastic.Documentation; | ||
|
|
||
| namespace Elastic.Documentation.Configuration; | ||
|
|
||
| /// <summary> | ||
| /// Outcome of interpolating shell-style <c>${VAR}</c> / <c>${VAR:-default}</c> expressions into a config value. | ||
| /// </summary> | ||
| /// <param name="Value">The resolved value, using environment variables where set and defaults otherwise.</param> | ||
| /// <param name="Fallback"> | ||
| /// The environment-independent value (every expression replaced by its committed default). Non-null only when an | ||
| /// allow-listed environment variable actually changed the result, so consumers can degrade to the committed default | ||
| /// if the environment-supplied value turns out to be unusable (e.g. an ephemeral PR registry that 404s). | ||
| /// </param> | ||
| public sealed record InterpolatedValue(string? Value, string? Fallback); | ||
|
|
||
| /// <summary> | ||
| /// Resolves shell-style <c>${VAR}</c> and <c>${VAR:-default}</c> expressions in committed config values. | ||
| /// docs-builder renders untrusted PR branches, so interpolation is restricted to an explicit allow-list — naive access | ||
| /// to the full process environment would let a malicious <c>docset.yml</c> exfiltrate CI secrets (e.g. <c>${AWS_SECRET_ACCESS_KEY}</c>). | ||
| /// </summary> | ||
| public static partial class EnvironmentInterpolation | ||
| { | ||
| /// <summary>Environment variable names that may be interpolated into committed config values.</summary> | ||
| public static readonly FrozenSet<string> AllowedVariables = | ||
| new HashSet<string>(StringComparer.Ordinal) { "KIBANA_STORYBOOK_REGISTRY" }.ToFrozenSet(StringComparer.Ordinal); | ||
|
|
||
| [GeneratedRegex(@"\$\{(?<name>[A-Za-z_][A-Za-z0-9_]*)(?::-(?<default>[^}]*))?\}", RegexOptions.CultureInvariant)] | ||
| private static partial Regex ExpressionRegex(); | ||
|
|
||
| /// <summary> | ||
| /// Interpolates allow-listed environment variables into <paramref name="raw"/>. Non-allow-listed expressions are | ||
| /// left literal (never read from the environment) and reported via <paramref name="onDisallowed"/>. | ||
| /// </summary> | ||
| public static InterpolatedValue Interpolate(string? raw, IEnvironmentVariables environment, Action<string>? onDisallowed = null) | ||
| { | ||
| if (string.IsNullOrEmpty(raw) || !raw.Contains("${", StringComparison.Ordinal)) | ||
| return new InterpolatedValue(raw, null); | ||
|
|
||
| var resolved = new StringBuilder(raw.Length); | ||
| var committed = new StringBuilder(raw.Length); | ||
| var lastIndex = 0; | ||
| var environmentChangedValue = false; | ||
|
|
||
| foreach (Match match in ExpressionRegex().Matches(raw)) | ||
| { | ||
| var literal = raw[lastIndex..match.Index]; | ||
| _ = resolved.Append(literal); | ||
| _ = committed.Append(literal); | ||
| lastIndex = match.Index + match.Length; | ||
|
|
||
| var name = match.Groups["name"].Value; | ||
| var defaultGroup = match.Groups["default"]; | ||
| var defaultValue = defaultGroup.Success ? defaultGroup.Value : string.Empty; | ||
|
|
||
| if (!AllowedVariables.Contains(name)) | ||
| { | ||
| onDisallowed?.Invoke(name); | ||
| _ = resolved.Append(match.Value); | ||
| _ = committed.Append(match.Value); | ||
| continue; | ||
| } | ||
|
|
||
| var environmentValue = environment.GetEnvironmentVariable(name); | ||
| if (!string.IsNullOrEmpty(environmentValue)) | ||
| { | ||
| _ = resolved.Append(environmentValue); | ||
| environmentChangedValue = true; | ||
| } | ||
| else | ||
| _ = resolved.Append(defaultValue); | ||
|
|
||
| _ = committed.Append(defaultValue); | ||
| } | ||
|
|
||
| var tail = raw[lastIndex..]; | ||
| _ = resolved.Append(tail); | ||
| _ = committed.Append(tail); | ||
|
|
||
| var resolvedValue = resolved.ToString(); | ||
| var committedValue = committed.ToString(); | ||
| var fallback = environmentChangedValue && !string.Equals(resolvedValue, committedValue, StringComparison.Ordinal) | ||
| ? committedValue | ||
| : null; | ||
|
|
||
| return new InterpolatedValue(resolvedValue, fallback); | ||
| } | ||
| } |
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
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
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
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
117 changes: 117 additions & 0 deletions
117
tests/Elastic.Documentation.Configuration.Tests/ConfigurationFileStorybookRegistryTests.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,117 @@ | ||
| // Licensed to Elasticsearch B.V under one or more agreements. | ||
| // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
| // See the LICENSE file in the project root for more information | ||
|
|
||
| using System.Collections.Frozen; | ||
| using System.IO.Abstractions; | ||
| using System.IO.Abstractions.TestingHelpers; | ||
| using AwesomeAssertions; | ||
| using Elastic.Documentation.Configuration.Builder; | ||
| using Elastic.Documentation.Configuration.Products; | ||
| using Elastic.Documentation.Configuration.Toc; | ||
| using Elastic.Documentation.Configuration.Versions; | ||
| using Elastic.Documentation.Diagnostics; | ||
| using Nullean.ScopedFileSystem; | ||
|
|
||
| namespace Elastic.Documentation.Configuration.Tests; | ||
|
|
||
| public class ConfigurationFileStorybookRegistryTests | ||
| { | ||
| private const string Default = "https://ci-artifacts.kibana.dev/storybooks/main/storybook-docs/docs_registry.json"; | ||
| private const string Expression = $"${{KIBANA_STORYBOOK_REGISTRY:-{Default}}}"; | ||
|
|
||
| [Fact] | ||
| public void UnsetVariable_ResolvesToCommittedDefault_WithNoFallback() | ||
| { | ||
| var config = CreateConfiguration(Expression, new MockEnvironment()); | ||
|
|
||
| config.StorybookRegistry.Should().Be(Default); | ||
| config.StorybookRegistryFallback.Should().BeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void SetVariable_ResolvesToEnvironmentValue_AndExposesDefaultAsFallback() | ||
| { | ||
| const string prRegistry = "https://ci-artifacts.kibana.dev/storybooks/pr-42/storybook-docs/docs_registry.json"; | ||
| var config = CreateConfiguration(Expression, new MockEnvironment { ["KIBANA_STORYBOOK_REGISTRY"] = prRegistry }); | ||
|
|
||
| config.StorybookRegistry.Should().Be(prRegistry); | ||
| config.StorybookRegistryFallback.Should().Be(Default); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void DisallowedVariable_IsLeftLiteral_AndWarns() | ||
| { | ||
| var collector = new DiagnosticsCollector([]); | ||
| var config = CreateConfiguration("${AWS_SECRET_ACCESS_KEY:-fallback}", new MockEnvironment { ["AWS_SECRET_ACCESS_KEY"] = "super-secret" }, collector); | ||
|
|
||
| config.StorybookRegistry.Should().Be("${AWS_SECRET_ACCESS_KEY:-fallback}"); | ||
| config.StorybookRegistry.Should().NotContain("super-secret"); | ||
| collector.Warnings.Should().Be(1, "a disallowed interpolation variable must emit exactly one warning"); | ||
| } | ||
|
|
||
| private static ConfigurationFile CreateConfiguration(string registry, IEnvironmentVariables environment, DiagnosticsCollector? collector = null) | ||
| { | ||
| collector ??= new DiagnosticsCollector([]); | ||
| var root = Paths.WorkingDirectoryRoot.FullName; | ||
| var configFilePath = Path.Join(root, "docs", "_docset.yml"); | ||
| var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> | ||
| { | ||
| { configFilePath, new MockFileData("") } | ||
| }, root); | ||
|
|
||
| var configPath = fileSystem.FileInfo.New(configFilePath); | ||
| var docsDir = fileSystem.DirectoryInfo.New(Path.Join(root, "docs")); | ||
|
|
||
| var context = new MockDocumentationSetContext(collector, fileSystem, configPath, docsDir, environment); | ||
| var versionsConfig = new VersionsConfiguration { VersioningSystems = new Dictionary<VersioningSystemId, VersioningSystem>() }; | ||
| var productsConfig = new ProductsConfiguration | ||
| { | ||
| Products = new Dictionary<string, Product>().ToFrozenDictionary(), | ||
| PublicReferenceProducts = new Dictionary<string, Product>().ToFrozenDictionary(), | ||
| ProductDisplayNames = new Dictionary<string, string>().ToFrozenDictionary() | ||
| }; | ||
|
|
||
| var docSet = new DocumentationSetFile | ||
| { | ||
| Project = "test", | ||
| TableOfContents = [], | ||
| Storybook = new DocumentationSetStorybook { Registry = registry } | ||
| }; | ||
|
|
||
| return new ConfigurationFile(docSet, context, versionsConfig, productsConfig); | ||
| } | ||
|
|
||
| private sealed class MockEnvironment : IEnvironmentVariables | ||
| { | ||
| private readonly Dictionary<string, string?> _variables = [with(StringComparer.Ordinal)]; | ||
|
|
||
| public string? this[string name] | ||
| { | ||
| set => _variables[name] = value; | ||
| } | ||
|
|
||
| public string? GetEnvironmentVariable(string name) => _variables.GetValueOrDefault(name); | ||
|
|
||
| public bool IsRunningOnCI => false; | ||
| } | ||
|
|
||
| private sealed class MockDocumentationSetContext( | ||
| IDiagnosticsCollector collector, | ||
| IFileSystem fileSystem, | ||
| IFileInfo configurationPath, | ||
| IDirectoryInfo documentationSourceDirectory, | ||
| IEnvironmentVariables environment) | ||
| : IDocumentationSetContext | ||
| { | ||
| public IDiagnosticsCollector Collector => collector; | ||
| public ScopedFileSystem ReadFileSystem => WriteFileSystem; | ||
| public ScopedFileSystem WriteFileSystem { get; } = FileSystemFactory.ScopeCurrentWorkingDirectoryForWrite(fileSystem); | ||
| public IDirectoryInfo OutputDirectory => fileSystem.DirectoryInfo.New(Path.Join(Paths.WorkingDirectoryRoot.FullName, ".artifacts")); | ||
| public IFileInfo ConfigurationPath => configurationPath; | ||
| public BuildType BuildType => BuildType.Isolated; | ||
| public IDirectoryInfo DocumentationSourceDirectory => documentationSourceDirectory; | ||
| public GitCheckoutInformation Git => GitCheckoutInformationFactory.Create(documentationSourceDirectory, fileSystem); | ||
| public IEnvironmentVariables Environment => environment; | ||
| } | ||
| } | ||
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
Oops, something went wrong.
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.