Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Casbin.UnitTests/Mock/MockLogger.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#if !NET452
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;

Expand All @@ -11,11 +12,14 @@ public class MockLogger<T> : ILogger<T>

public MockLogger(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper;

public List<(LogLevel Level, Exception Exception, string Message)> Logs { get; } = new();

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
{
string outPut = formatter(state, null);
string outPut = formatter(state, exception);
_testOutputHelper.WriteLine(outPut);
Logs.Add((logLevel, exception, outPut));
}

public bool IsEnabled(LogLevel logLevel) => true;
Expand Down
29 changes: 29 additions & 0 deletions Casbin.UnitTests/ModelTests/EnforcerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1290,4 +1290,33 @@ public async Task TestEnforceExWithMatcherAsync()
}

#endregion

#if !NET452
#region ExpressionHandler Tests

[Fact]
public void TestExpressionHandlerSingleQuoteReplacement()
{
Enforcer e = new(TestModelFixture.GetBasicTestModel());
// Single quotes should be replaced with double quotes to handle DynamicExpresso limitations
string matcherWithSingleQuotes = "r.sub == 'alice' && r.obj == p.obj && r.act == p.act";

Assert.True(e.EnforceWithMatcher(matcherWithSingleQuotes, "alice", "data1", "read"));
Assert.False(e.EnforceWithMatcher(matcherWithSingleQuotes, "alice", "data1", "write"));
Assert.False(e.EnforceWithMatcher(matcherWithSingleQuotes, "bob", "data1", "read"));
}

[Fact]
public void TestExpressionHandlerLogsWarningOnInvalidExpression()
{
var logger = new MockLogger<Enforcer>(_testOutputHelper);
Enforcer e = new(TestModelFixture.GetBasicTestModel()) { Logger = logger };

// An invalid expression should return false and log a warning
Assert.False(e.EnforceWithMatcher("this_is_not_valid!!!", "alice", "data1", "read"));
Assert.Contains(logger.Logs, log => log.Level == Microsoft.Extensions.Logging.LogLevel.Warning);
}

#endregion
#endif
}
1 change: 1 addition & 0 deletions Casbin/EnforceView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public static EnforceView CreateWithMatcher(
string policyType = PermConstants.DefaultPolicyType,
string effectType = PermConstants.DefaultPolicyEffectType)
{
matcher = matcher.Replace('\'', '"');
IReadOnlyAssertion requestAssertion = model.Sections.GetRequestAssertion(requestType);
PolicyAssertion policyAssertion = model.Sections.GetPolicyAssertion(policyType);
IReadOnlyAssertion effectAssertion = model.Sections.GetPolicyEffectAssertion(effectType);
Expand Down
33 changes: 31 additions & 2 deletions Casbin/Enforcer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Threading.Tasks;
using Casbin.Caching;
using Casbin.Effect;
using Casbin.Evaluation;
using Casbin.Model;
using Casbin.Persist;
using Casbin.Persist.Adapter.File;
Expand Down Expand Up @@ -84,7 +85,22 @@ public IReadOnlyWatcher Watcher
set => Model.WatcherHolder.Watcher = value;
}

public IModel Model { get; set; }
private IModel _model;

public IModel Model
{
get => _model;
set
{
_model = value;
#if !NET452
if (value?.ExpressionHandler is ExpressionHandler exprHandler)
{
exprHandler.Logger = _logger;
}
#endif
}
}

public IReadOnlyAdapter Adapter
{
Expand All @@ -99,7 +115,20 @@ public IEnforceCache EnforceCache
}

#if !NET452
public ILogger Logger { get; set; }
private ILogger _logger;

public ILogger Logger
{
get => _logger;
set
{
_logger = value;
if (_model?.ExpressionHandler is ExpressionHandler exprHandler)
{
exprHandler.Logger = value;
}
}
}
#endif

#endregion
Expand Down
12 changes: 11 additions & 1 deletion Casbin/Evaluation/ExpressionHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
using Casbin.Functions;
using Casbin.Model;
using DynamicExpresso;
#if !NET452
using Microsoft.Extensions.Logging;
#endif

namespace Casbin.Evaluation;

Expand All @@ -20,6 +23,10 @@

private bool TryCompile { get; set; } = true;

#if !NET452
internal ILogger Logger { get; set; }
#endif

public ExpressionHandler()
{
_interpreter = CreateInterpreter();
Expand Down Expand Up @@ -117,9 +124,12 @@
{
func = CompileExpression<TRequest, TPolicy>(in context, expressionString);
}
catch (Exception)
catch (Exception e)

Check warning on line 127 in Casbin/Evaluation/ExpressionHandler.cs

View workflow job for this annotation

GitHub Actions / build

The variable 'e' is declared but never used

Check warning on line 127 in Casbin/Evaluation/ExpressionHandler.cs

View workflow job for this annotation

GitHub Actions / InferSharp

The variable 'e' is declared but never used
{
func = null;
#if !NET452
Logger?.LogWarning(e, "Failed to compile the expression \"{ExpressionString}\".", expressionString);
#endif
return false;
}
return true;
Expand Down
Loading