Validation Errors - custom log level
Hi,
First of, great work on IS4 really satisfied with the product in general.
This is a feature request for adding the option to set the log level of errors involving validators in IS4.
To be precise, that includes all validator classes within IdentityServer4.Validation namespace.
This could be done a bit broader as well, by setting sections/areas of IS4 like, stores, services etc... and allowing the developers to change the default log levels of various sections. Either through constants or whichever method you consider viable.
I've already tried this by cloning your dev branch and implementing it. Works as intended. However I'd like to discuss this as a permanent feature as it may prove useful.
What's the motivation?
Any input on this?
Hi and sorry for the delay I’m on a trip so no constant internet connection.
Anyways, the motivation for this came from observing our production environment for last few months. More control over the log levels in various places would be more than welcome. For instance, we wish to setup an automated alert system but we dont want certain logs to be considered as errors so they dont alert anyone.
I’m sure that more freedom in this manner will be beneficial since not everyone wants to log things as errors that they dont consider errors in their setups.
OK - I see.
We are planning to re-work the whole logging/auditing system for v3. So I am bit reluctant to make such changes before the grand re-design.
But what would be your proposal on how to implement that?
If you’re reworking logging in general than a minor update for this would suffice I dont have example code on me since Im limited to my phone, but the basic idea could be to create an extension method(s) for logging and make it switch based on some value either from your constant class or from wherever that in my mind feels like least trouble and change for this sort of thing. Then just change all desired elements to use those extension methods. It would stay clean and well theres always an option to just extend this even further with the use of something like serilog for more customization of logged properties etc. but not much point in that if you’re reworking the whole thing. I’d just stick to the simple example of extension method per ‘area’ and change them set defaults within those methods to be safe and set the needed value to default as well to be clearer.
@leastprivilege Have you had time to make any decision regarding this?
I'd use the Microsoft.Extensions.Logging.Abstractions NuGet for the log. One can than filter log events by namespace.
Microsoft's logging interface is very basic, but it is supported by all common logging libraries.
Doh. Yes absolutely.
Will close this as resolved.
@MovGP0 We are using Microsoft.Extensions.Logging.Abstractions however I fail to see how this relates. I don't want to filter them, I want to set the different log level for various errors.
Perhaps I'm missing something here.
You are right - I was too quick closing the issue.
That being said - we don't plan to touch the logging system soon. As I mentioned before, we are planning to re-write it anyways. Then this requirement will be considered.
Check Serilog - it offers a pretty powerful filtering and processing pipeline - maybe you can achieve your goal this way.
@leastprivilege We're already using Serilog for various things, however unfortunately it cannot override this in any way. Guess we'll wait for your upgrade on logging. Then we can review this matter and see if it can be done more naturally.
Serilog is the library I am using in all my projects. However, I am not sure if it's the right tool for libraries on GitHub. A common logging library might be the better choice here. People who use the library in their projects should use Serilog, but not required to do so.
This is of great interest to us as well. Here is some detail from our perspective;
Background
We run pretty aggressive monitoring and alerting on error logs in production - more than N error logs in X min results in a page to on-call.
Currently a lot of internal IdentityServer4 logging emits Error events in situations where IdentityServer is doing exactly the right thing (eg token is invalid, authZ code is invalid, etc) and is technically not itself experiencing errors at all. Sure a client isn't getting the response they want but if that's due to invalid input that's not an error at our end - and isn't something we can do anything about. (Well, we can and do plead with people to stop doing bad things but our Salesforce integration support is just a deadend and I think they'll spam us with invalid input forever.)
My primary concern is that IdentityServer is emitting Error logs in cases which are not errors. The client isn't getting the response they want but IdentityServer is doing exactly what it should. This makes it impossible to isolate actual errors from noise caused by badly behaved clients.
Request
Would you be open to a PR which alters the log levels for client-caused request rejection down to Warn or Info level? This would most likely target all types under the IdentityServer4.Validation namespace. We would be happy to contribute this.
You mention
we are planning to re-write [the logging system] anyways. Then this requirement will be considered.
Is there an issue somewhere where we could contribute requirements/input to this?
Alternatively, when looking at your logging rewrite would you consider providing something like a Dictionary<string,LogLevel> for log level mappings? That would allow us to override the log level for a specific log message, and then the app code could lookup the log level at runtime like so;
private void Log(string message) {
var logLevel = LogLevels[message];
_logger.Log(logLevel, message);
});
There are obviously other considerations but the basic idea is to provide a means to control log levels where that is appropriate (clearly it's not appropriate everywhere).
Thanks. 🙂
Workaround
We also use Serilog and what we've done is to add a LogLevelModifyingSink which alters the level of logs emitted by IdentityServer on the way out - typically to drop Error logs down to Warn or lower. See below for impl details if that's useful. It's just a pretty nasty workaround to have to apply - incurs overhead on the logging output and may hide some legitimate error logs.
Here is our logic (and we're about to add yet more log level overrides);
/// <summary>
/// Runs conditional logic on logs to alter log levels on the fly
/// </summary>
/// <remarks>
/// Useful to control logs from third party libs which output logs with levels that we think are too spammy or not helpful.
/// </remarks>
public class LogLevelModifyingSink : ILogEventSink, IDisposable
{
readonly ILogEventSink _pipeline;
readonly LogLevelModifier _logLevelModifier;
// this is a list of loglevel modifiers
// each modifier has a predicate which takes a logevent and returns whether the log level should be modified,
// and a replacement logeventlevel (used if modifying the log)
static readonly IList<(ShouldModifyLog,LogEventLevel)> LogLevelModifiers = new List<(ShouldModifyLog, LogEventLevel)> {
(IsIdentityServerErrorLogScopeValidatorRequestedScopeNotAllowed,LogEventLevel.Warning),
(IsIdentityServerErrorLogTokenRequestValidator_RequestedScopeNotAllowedOrAuthorisationCodeInvalid,LogEventLevel.Warning),
(IsIdentityServerErrorLogTokenValidatorInvalidReferenceToken,LogEventLevel.Warning)
};
// a list of quick checks to see if we should handle a particular log
static readonly IList<ShouldModifyLog> ShouldHandlePredicates = new List<ShouldModifyLog> {
logEvent => logEvent.SourceContextHasNamespaceStartingWith(IdentityServer4Namespace),
};
static bool IsIdentityServerErrorLogScopeValidatorRequestedScopeNotAllowed(LogEvent logEvent) {
return logEvent.Level.Equals(LogEventLevel.Error)
&& logEvent.SourceContext().Equals($"{IdentityServer4Namespace}.Validation.ScopeValidator")
&& logEvent.MessageTemplate.Text.StartsWith("Requested scope not allowed");
}
static bool IsIdentityServerErrorLogTokenValidatorInvalidReferenceToken(LogEvent logEvent) {
return logEvent.Level.Equals(LogEventLevel.Error)
&& logEvent.SourceContext().Equals($"{IdentityServer4Namespace}.Validation.TokenValidator")
&& logEvent.MessageTemplate.Text.StartsWith("Invalid reference token");
}
static bool IsIdentityServerErrorLogTokenRequestValidator_RequestedScopeNotAllowedOrAuthorisationCodeInvalid(LogEvent logEvent) {
return logEvent.Level.Equals(LogEventLevel.Error)
&& logEvent.SourceContext().Equals($"{IdentityServer4Namespace}.Validation.TokenRequestValidator")
&& (
// requested scope not allowed
logEvent.MessageTemplate.Text.Equals("{details}") || // wut? :confounded:
logEvent.MessageTemplate.Text.StartsWith("Invalid authorization code")
);
}
#endregion
public LogLevelModifyingSink(ILogEventSink pipeline) {
_pipeline = pipeline;
_logLevelModifier = new LogLevelModifier(ShouldHandlePredicates, LogLevelModifiers);
}
public void Dispose() {
(_pipeline as IDisposable)?.Dispose();
}
[DebuggerStepThrough]
public void Emit(LogEvent logEvent) {
// let's assume that all our own logs have correct logging levels and we can just pass-thru
if(logEvent.SourceContextHasNamespaceStartingWith(MyCompanyNamespace)) {
_pipeline.Emit(logEvent);
}
// otherwise it's third party so we'll check...
else if(_logLevelModifier.ShouldHandle(logEvent)) {
var modifiedEvent = _logLevelModifier.Modify(logEvent);
_pipeline.Emit(modifiedEvent);
}
else {
_pipeline.Emit(logEvent);
}
}
}
and the LogLevelModifier impl includes
/// <summary>
/// Runs through the <see cref="_logLevelModifiers"/> and applies the first one that matches.
/// </summary>
/// <param name="logEvent"></param>
/// <returns>A log event with an altered log level</returns>
[DebuggerStepThrough]
public LogEvent Modify(LogEvent logEvent) {
foreach(var (predicate, replacementLogLevel) in _logLevelModifiers) {
var replacementLogEvent = ConditionallyModifyLogLevel(predicate, logEvent, replacementLogLevel, out var wasModified);
if(wasModified) {
return replacementLogEvent;
}
}
// shouldn't get here
return logEvent;
}
static LogEvent ConditionallyModifyLogLevel(ShouldModifyLog predicate, LogEvent logEvent, LogEventLevel replacementLevel, out bool wasModified) {
if(predicate(logEvent)) {
wasModified = true;
return ModifyLog(logEvent, replacementLevel);
}
// shouldn't get here
wasModified = false;
return logEvent;
}
static LogEvent ModifyLog(LogEvent logEvent, LogEventLevel replacementLevel) {
return new LogEvent(
logEvent.Timestamp,
replacementLevel, // only changing this
logEvent.Exception,
logEvent.MessageTemplate,
logEvent.Properties.Select(kvp => new LogEventProperty(kvp.Key, kvp.Value)));
}
I have faced this same problem multiple times. There is no simple answer since incessant hammering of a authn system is a valid error condition. You probably will not like the answer we crafted, which was to write a program that would measure the errors per account and report when they exceeded a threshold. That was done in a SIEM system with the capability to handle little microprograms like that.
It really is not possible for any general system (like idsvr) to know the threshold characteristics of each install. Nor is it likely that they will remain constant over time even at the same site.
I agree with the @MovGP0 comment - use a common format and let the security analysis sort it out. Peace ..tom
There is no simple answer since incessant hammering of a authn system is a valid error condition.
Thanks - that's helpful feedback. And I agree - sort of.
Where I work we've attempted to handle this with rate limiting on requests (that are necessarily unauthenticated), if we can extract identifying information such as clientid from the request. Or we can ip block at our internal WAF if it's bad enough and we can't extract uniquely identifying information.
It really is not possible for any general system (like idsvr) to know the threshold characteristics of each install.
Yes that's true, but I'd argue idsvr is not the right place to identify whether this is an error or not. We can only see if it's truly 'incessant hammering of a authn system' from outside the request; as you say in a system which can measure and respond to aggregated counts of a specific type of log/event.
The problem as I see it is that idsvr is unilaterally deeming that threshold to be 1, where any validation failure is an error, not N validation failures over X time. Idsvr conflates actual errors we can fix with validation errors we can't. I'd much rather idsvr emitted validation errors via an event or non-error log that allows external systems to aggregate and determine if there is in fact an error.
use a common format and let the security analysis sort it out
So I totally agree - use a common format, don't prematurely mark these as errors and let downstream analysis/monitoring sort it out. That's my argument - that it's not an idsvr concern.
You may very well be correct, but the solution is not up to me. I will point out that Windows considers (or did consider) this to be an error.
@leastprivilege, @brockallen Would you be open to a PR which gives idsvr lib consumers the ability to alter the log levels for client-caused request/validation rejection (I would downgrade these to Warn or Info level)? This would most likely target all types under the IdentityServer4.Validation namespace. We would be happy to contribute this.
Also, you mentioned
we are planning to re-write [the logging system] anyways. Then this requirement will be considered.
Is there an issue somewhere where we could contribute requirements/input to this, or even just see what is planned?
Will be tracked here: https://github.com/IdentityServer/IdentityServer4/issues/3518
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.