-
Notifications
You must be signed in to change notification settings - Fork 50
Audit log for authorization decisions #5520
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
ramonsmits
wants to merge
12
commits into
auth
Choose a base branch
from
authorizationauditlog
base: auth
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
Show all changes
12 commits
Select commit
Hold shift + click to select a range
1118c00
✨ Audit log for every authorization decision
ramonsmits 64c5ddc
✨ Configurable required subject claims for the audit log
ramonsmits aa96bf5
Merge remote-tracking branch 'origin/auth' into authorizationauditlog
ramonsmits a40d990
Merge branch 'auth' into authorizationauditlog
ramonsmits 2f5433a
Separate allow/deny log templates, log deny as Warning
ramonsmits 696e544
Add TODO for instance-specific audit categories in AuthorizationAuditLog
ramonsmits f29a318
IDE0055
ramonsmits 1e2d894
Refactor dependencies on settings to inject `OpenIdConnectSettings`
ramonsmits 96a1af1
✨ Route ServiceControl.Audit category to a structured JSON log target
ramonsmits 084fc6a
🐛 Align AuthorizationAuditLog tests with the Allow:/Deny: templates
ramonsmits bcb1082
✨ Emit the authorization audit event as an Elastic Common Schema (ECS…
ramonsmits 1203afd
Remove outdated TODO in `AuthorizationAuditLog` comment regarding ins…
ramonsmits 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
Some comments aren't visible on the classic Files Changed page.
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
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
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,42 +1,90 @@ | ||||||
| #nullable enable | ||||||
| namespace ServiceControl.Hosting.Auth; | ||||||
|
|
||||||
| using System; | ||||||
| using System.Linq; | ||||||
| using System.Security.Claims; | ||||||
| using System.Threading.Tasks; | ||||||
| using Microsoft.AspNetCore.Authorization; | ||||||
| using ServiceControl.Infrastructure; | ||||||
| using ServiceControl.Infrastructure.Auth; | ||||||
|
|
||||||
| /// <summary> | ||||||
| /// Verb-level authorization handler for <see cref="PermissionRequirement"/>. It resolves the user's | ||||||
| /// roles and checks them against the hardcoded <see cref="RolePermissions"/> policy: the user must hold | ||||||
| /// a role (e.g. <c>reader</c> / <c>writer</c>) that grants the requested permission. | ||||||
| /// a role (e.g. <c>reader</c> / <c>writer</c>) that grants the requested permission. Every decision is | ||||||
| /// captured through <see cref="IAuthorizationAuditLog"/> for compliance. | ||||||
| /// <para> | ||||||
| /// Only registered — and only reached — when OIDC is enabled. When it is disabled, | ||||||
| /// <see cref="PermissionPolicyProvider"/> returns an allow-all policy that carries no | ||||||
| /// <see cref="PermissionRequirement"/>, so this handler is not needed. | ||||||
| /// </para> | ||||||
| /// </summary> | ||||||
| public sealed class PermissionVerbHandler : AuthorizationHandler<PermissionRequirement> | ||||||
| public sealed class PermissionVerbHandler( | ||||||
| IAuthorizationAuditLog auditLog, | ||||||
| OpenIdConnectSettings oidcSettings) | ||||||
| : AuthorizationHandler<PermissionRequirement> | ||||||
| { | ||||||
| public PermissionVerbHandler(string rolesClaimName) | ||||||
| { | ||||||
| RoleClaimType = rolesClaimName; | ||||||
| } | ||||||
| // The per-IdP variability of the source claim is absorbed by RolesClaimsTransformation, which | ||||||
| // reads from the path configured in Authentication.RolesClaim and emits canonical "roles" claims. | ||||||
| const string RoleClaimType = "roles"; | ||||||
|
|
||||||
| protected override Task HandleRequirementAsync( | ||||||
| AuthorizationHandlerContext context, | ||||||
| PermissionRequirement requirement) | ||||||
| { | ||||||
| var roles = context.User.FindAll(RoleClaimType).Select(claim => claim.Value); | ||||||
| // Unauthenticated requests have no subject and no roles. The framework will challenge with | ||||||
| // 401 because the policy also includes RequireAuthenticatedUser; skipping here keeps the | ||||||
| // audit log restricted to identified principals. | ||||||
| if (context.User.Identity?.IsAuthenticated != true) | ||||||
| { | ||||||
| return Task.CompletedTask; | ||||||
| } | ||||||
|
|
||||||
| var subjectId = RequireClaim(context.User, oidcSettings.SubjectIdClaim, "Authentication.SubjectIdClaim"); | ||||||
| var subjectName = RequireClaim(context.User, oidcSettings.SubjectNameClaim, "Authentication.SubjectNameClaim"); | ||||||
| var roles = context.User.FindAll(RoleClaimType).Select(claim => claim.Value).ToArray(); | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Rather use the standard |
||||||
| var permission = requirement.Permission; | ||||||
|
|
||||||
| if (RolePermissions.IsGranted(roles, requirement.Permission)) | ||||||
| if (RolePermissions.IsGranted(roles, permission)) | ||||||
| { | ||||||
| auditLog.Decision( | ||||||
| subjectId, | ||||||
| subjectName, | ||||||
| permission, | ||||||
| resource: null, | ||||||
| allowed: true, | ||||||
| reason: roles.Length == 0 | ||||||
| ? $"User holds '{permission}'" | ||||||
| : $"User holds '{permission}' via role(s) [{string.Join(", ", roles)}]"); | ||||||
|
|
||||||
| context.Succeed(requirement); | ||||||
| return Task.CompletedTask; | ||||||
| } | ||||||
|
|
||||||
| // Otherwise leave the requirement unmet → the request is denied (403/401). | ||||||
| auditLog.Decision( | ||||||
| subjectId, | ||||||
| subjectName, | ||||||
| permission, | ||||||
| resource: null, | ||||||
| allowed: false, | ||||||
| reason: roles.Length == 0 | ||||||
| ? $"User has no roles granting '{permission}'" | ||||||
| : $"None of the user's role(s) [{string.Join(", ", roles)}] grants '{permission}'"); | ||||||
|
|
||||||
| // Leave the requirement unmet → the framework forbids (403). | ||||||
| return Task.CompletedTask; | ||||||
| } | ||||||
|
|
||||||
| internal string RoleClaimType = "roles"; | ||||||
| } | ||||||
| static string RequireClaim(ClaimsPrincipal user, string claimType, string settingName) | ||||||
| { | ||||||
| var value = user.FindFirst(claimType)?.Value; | ||||||
| if (string.IsNullOrEmpty(value)) | ||||||
| { | ||||||
| throw new InvalidOperationException( | ||||||
| $"Authenticated principal is missing the required '{claimType}' claim configured by {settingName}. " + | ||||||
| "Configure the identity provider to emit this claim, or point the setting at the claim the IdP actually emits."); | ||||||
| } | ||||||
| return value; | ||||||
| } | ||||||
| } | ||||||
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
98 changes: 98 additions & 0 deletions
98
src/ServiceControl.Infrastructure.Tests/Auth/AuthorizationAuditLogTests.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,98 @@ | ||
| #nullable enable | ||
| namespace ServiceControl.Infrastructure.Tests.Auth; | ||
|
|
||
| using System; | ||
| using System.Text.Json; | ||
| using Microsoft.Extensions.Logging; | ||
| using NUnit.Framework; | ||
| using ServiceControl.Infrastructure.Auth; | ||
|
|
||
| [TestFixture] | ||
| public class AuthorizationAuditLogTests | ||
| { | ||
| [Test] | ||
| public void Decision_allow_emits_one_entry_on_audit_category() | ||
| { | ||
| var provider = new RecordingLoggerProvider(); | ||
| var factory = LoggerFactory.Create(b => b.AddProvider(provider)); | ||
| var auditLog = new AuthorizationAuditLog(factory); | ||
|
|
||
| auditLog.Decision("alice-sub-001", "Alice Smith", "error:messages:retry", "acme.sales", allowed: true, reason: "role:reader matched"); | ||
|
|
||
| var entries = provider.EntriesFor("ServiceControl.Audit"); | ||
| Assert.That(entries, Has.Count.EqualTo(1)); | ||
| var ecs = JsonDocument.Parse(entries[0].Message).RootElement; | ||
| Assert.That(ecs.GetProperty("event").GetProperty("type")[0].GetString(), Is.EqualTo("allowed")); | ||
| Assert.That(ecs.GetProperty("event").GetProperty("outcome").GetString(), Is.EqualTo("success")); | ||
| Assert.That(ecs.GetProperty("user").GetProperty("id").GetString(), Is.EqualTo("alice-sub-001")); | ||
| Assert.That(ecs.GetProperty("user").GetProperty("name").GetString(), Is.EqualTo("Alice Smith")); | ||
| Assert.That(ecs.GetProperty("event").GetProperty("action").GetString(), Is.EqualTo("error:messages:retry")); | ||
| Assert.That(entries[0].Level, Is.EqualTo(LogLevel.Information)); | ||
| } | ||
|
|
||
| [Test] | ||
| public void Decision_deny_emits_one_entry_on_audit_category() | ||
| { | ||
| var provider = new RecordingLoggerProvider(); | ||
| var factory = LoggerFactory.Create(b => b.AddProvider(provider)); | ||
| var auditLog = new AuthorizationAuditLog(factory); | ||
|
|
||
| auditLog.Decision("bob-sub-002", "Bob Jones", "error:messages:retry", null, allowed: false, reason: "no matching role"); | ||
|
|
||
| var entries = provider.EntriesFor("ServiceControl.Audit"); | ||
| Assert.That(entries, Has.Count.EqualTo(1)); | ||
| var ecs = JsonDocument.Parse(entries[0].Message).RootElement; | ||
| Assert.That(ecs.GetProperty("event").GetProperty("type")[0].GetString(), Is.EqualTo("denied")); | ||
| Assert.That(ecs.GetProperty("event").GetProperty("outcome").GetString(), Is.EqualTo("failure")); | ||
| Assert.That(ecs.GetProperty("user").GetProperty("id").GetString(), Is.EqualTo("bob-sub-002")); | ||
| Assert.That(ecs.GetProperty("servicecontrol").GetProperty("resource").ValueKind, Is.EqualTo(JsonValueKind.Null)); | ||
| Assert.That(entries[0].Level, Is.EqualTo(LogLevel.Warning)); | ||
| } | ||
|
|
||
| [Test] | ||
| public void Decision_does_not_appear_on_other_categories() | ||
| { | ||
| var provider = new RecordingLoggerProvider(); | ||
| var factory = LoggerFactory.Create(b => b.AddProvider(provider)); | ||
| var auditLog = new AuthorizationAuditLog(factory); | ||
|
|
||
| auditLog.Decision("carol-sub-003", "Carol White", "error:endpoints:view", null, allowed: true, reason: "role:reader matched"); | ||
|
|
||
| Assert.That(provider.EntriesFor("ServiceControl.SomeOtherCategory"), Is.Empty); | ||
| } | ||
|
|
||
| [Test] | ||
| public void Multiple_decisions_accumulate_in_order() | ||
| { | ||
| var provider = new RecordingLoggerProvider(); | ||
| var factory = LoggerFactory.Create(b => b.AddProvider(provider)); | ||
| var auditLog = new AuthorizationAuditLog(factory); | ||
|
|
||
| auditLog.Decision("alice-sub-001", "alice", "error:messages:view", null, allowed: true, "role matched"); | ||
| auditLog.Decision("alice-sub-001", "alice", "error:messages:retry", "acme.finance", allowed: false, "out of scope"); | ||
|
|
||
| var entries = provider.EntriesFor("ServiceControl.Audit"); | ||
| Assert.That(entries, Has.Count.EqualTo(2)); | ||
| Assert.That(JsonDocument.Parse(entries[0].Message).RootElement.GetProperty("event").GetProperty("type")[0].GetString(), Is.EqualTo("allowed")); | ||
| Assert.That(JsonDocument.Parse(entries[1].Message).RootElement.GetProperty("event").GetProperty("type")[0].GetString(), Is.EqualTo("denied")); | ||
| } | ||
|
|
||
| [TestCase(null, "Alice", "error:messages:retry", "reason")] | ||
| [TestCase("", "Alice", "error:messages:retry", "reason")] | ||
| [TestCase("alice-sub-001", null, "error:messages:retry", "reason")] | ||
| [TestCase("alice-sub-001", "", "error:messages:retry", "reason")] | ||
| [TestCase("alice-sub-001", "Alice", null, "reason")] | ||
| [TestCase("alice-sub-001", "Alice", "", "reason")] | ||
| [TestCase("alice-sub-001", "Alice", "error:messages:retry", null)] | ||
| [TestCase("alice-sub-001", "Alice", "error:messages:retry", "")] | ||
| public void Decision_throws_when_required_argument_is_null_or_empty(string? subjectId, string? subjectName, string? permission, string? reason) | ||
| { | ||
| var provider = new RecordingLoggerProvider(); | ||
| var factory = LoggerFactory.Create(b => b.AddProvider(provider)); | ||
| var auditLog = new AuthorizationAuditLog(factory); | ||
|
|
||
| Assert.That( | ||
| () => auditLog.Decision(subjectId!, subjectName!, permission!, resource: null, allowed: true, reason: reason!), | ||
| Throws.InstanceOf<ArgumentException>()); | ||
| } | ||
| } |
59 changes: 59 additions & 0 deletions
59
src/ServiceControl.Infrastructure.Tests/Auth/RecordingLoggerProvider.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,59 @@ | ||
| #nullable enable | ||
| namespace ServiceControl.Infrastructure.Tests.Auth; | ||
|
|
||
| using System; | ||
| using System.Collections.Concurrent; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| /// <summary> | ||
| /// In-memory <see cref="ILoggerProvider"/> that captures log entries for test assertions. | ||
| /// Thread-safe. Use <see cref="Entries"/> for all captured entries; <see cref="EntriesFor(string)"/> | ||
| /// to filter by category. | ||
| /// </summary> | ||
| sealed class RecordingLoggerProvider : ILoggerProvider | ||
| { | ||
| readonly ConcurrentQueue<LogEntry> entries = new(); | ||
|
|
||
| public IReadOnlyList<LogEntry> Entries => entries.ToArray(); | ||
|
|
||
| public IReadOnlyList<LogEntry> EntriesFor(string category) => | ||
| entries.Where(e => e.Category == category).ToArray(); | ||
|
|
||
| public ILogger CreateLogger(string categoryName) => | ||
| new RecordingLogger(categoryName, entries); | ||
|
|
||
| public void Dispose() { } | ||
| } | ||
|
|
||
| sealed record LogEntry( | ||
| string Category, | ||
| LogLevel Level, | ||
| EventId EventId, | ||
| string Message, | ||
| Exception? Exception); | ||
|
|
||
| sealed class RecordingLogger(string category, ConcurrentQueue<LogEntry> sink) : ILogger | ||
| { | ||
| public IDisposable? BeginScope<TState>(TState state) where TState : notnull => NullScope.Instance; | ||
|
|
||
| public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; | ||
|
|
||
| public void Log<TState>( | ||
| LogLevel logLevel, | ||
| EventId eventId, | ||
| TState state, | ||
| Exception? exception, | ||
| Func<TState, Exception?, string> formatter) | ||
| { | ||
| var message = formatter(state, exception); | ||
| sink.Enqueue(new LogEntry(category, logLevel, eventId, message, exception)); | ||
| } | ||
|
|
||
| sealed class NullScope : IDisposable | ||
| { | ||
| public static readonly NullScope Instance = new(); | ||
| public void Dispose() { } | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Rather use the standard
ClaimTypes.Roleinstead of our own custom string.