Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions 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);
_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
}
6 changes: 6 additions & 0 deletions Casbin/Enforcer.Internal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ private bool InternalEnforce<TRequest, TPolicy>(in EnforceContext context, in TR
{
EnforceSession session = new EnforceSession();
IExpressionHandler expressionHandler = Model.ExpressionHandler;
#if !NET452
if (expressionHandler is ExpressionHandler exprHandler)
Comment thread
sagilio marked this conversation as resolved.
Outdated
{
exprHandler.Logger = Logger;
}
#endif
PolicyScanner<TRequest> scanner = context.View.PolicyAssertion.Scan(in requestValues);

EffectChain effectChain = new();
Expand Down
13 changes: 12 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 @@ -65,6 +72,7 @@
where TRequest : IRequestValues
where TPolicy : IPolicyValues
{
expressionString = expressionString.Replace('\'', '"');
if (context.View.SupportGeneric is false)
{
if (_cachePool.TryGetFunc(expressionString,
Expand Down Expand Up @@ -117,9 +125,12 @@
{
func = CompileExpression<TRequest, TPolicy>(in context, expressionString);
}
catch (Exception)
catch (Exception e)

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

View workflow job for this annotation

GitHub Actions / InferSharp

The variable 'e' is declared but never used

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

View workflow job for this annotation

GitHub Actions / build

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