Skip to content

Commit

Permalink
fix: Fail if configuration has no policies
Browse files Browse the repository at this point in the history
  • Loading branch information
me-viper committed Sep 26, 2023
1 parent c8eee1a commit 948464c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/OpaDotNet.Extensions.AspNetCore/ConfigurationPolicySource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public ConfigurationPolicySource(
/// <inheritdoc />
protected override async Task<Stream?> CompileBundleFromSource(bool recompiling, CancellationToken cancellationToken = default)
{
var hasSources = false;
using var ms = new MemoryStream();
var bundleWriter = new BundleWriter(ms);

Expand All @@ -48,16 +49,22 @@ public ConfigurationPolicySource(
foreach (var (name, policy) in _policy.CurrentValue)
{
if (!string.IsNullOrWhiteSpace(policy.DataJson))
bundleWriter.WriteEntry(policy.DataJson, $"{policy.Package}/data.json");
bundleWriter.WriteEntry(policy.DataJson, $"/{policy.Package}/data.json");

if (!string.IsNullOrWhiteSpace(policy.DataYaml))
bundleWriter.WriteEntry(policy.DataYaml, $"{policy.Package}/data.yaml");
bundleWriter.WriteEntry(policy.DataYaml, $"/{policy.Package}/data.yaml");

if (!string.IsNullOrWhiteSpace(policy.Source))
{
hasSources = true;
bundleWriter.WriteEntry(policy.Source, $"/{policy.Package}/{name}.rego");
}
}
}

if (!hasSources)
throw new RegoCompilationException("Configuration has no policies defined");

ms.Seek(0, SeekOrigin.Begin);

var result = await Compiler.CompileStream(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,25 @@ public ConfigurationPolicySourceTests(ITestOutputHelper output)

private record UserPolicyInput([UsedImplicitly] string User);

[Fact]
public async Task NoPolicies()
{
var policyOptions = new OpaPolicyOptions();
var optionsMonitor = new PolicyOptionsMonitor(policyOptions);

using var compiler = new ConfigurationPolicySource(
new RegoInteropCompiler(
null,
_loggerFactory.CreateLogger<RegoInteropCompiler>()
),
new OptionsWrapper<OpaAuthorizationOptions>(new()),
optionsMonitor,
_loggerFactory
);

await Assert.ThrowsAsync<RegoCompilationException>(() => compiler.StartAsync(CancellationToken.None));
}

[Theory]
[InlineData(2, "p1/t1/allow")]
[InlineData(3, "p2/allow")]
Expand Down

0 comments on commit 948464c

Please sign in to comment.