diff --git a/changelog.d/4694-error-email-throttling.added.md b/changelog.d/4694-error-email-throttling.added.md new file mode 100644 index 0000000000..0cff0c54e1 --- /dev/null +++ b/changelog.d/4694-error-email-throttling.added.md @@ -0,0 +1 @@ +- Error emails can be throttled per error fingerprint and globally with `errorEmailRateLimit`, `errorEmailRateWindowMinutes`, and `errorEmailGlobalRateLimit`; all defaults remain unlimited (#4694) diff --git a/cli/lucli/templates/app/.ai/views.md b/cli/lucli/templates/app/.ai/views.md index 900b337ed2..6c9b02c39c 100644 --- a/cli/lucli/templates/app/.ai/views.md +++ b/cli/lucli/templates/app/.ai/views.md @@ -52,3 +52,21 @@ In the `development` environment, an error response asked for as `Accept: application/json` (or `?format=json`) is that same payload as JSON, and `Accept: text/markdown` (or `?format=md`) gets it as Markdown, with the error page's status code. Testing and production responses are unchanged. + +### Error-email throttling + +Production turns `sendEmailOnError` on; configure `errorEmailAddress` (or `errorEmailToAddress`) or no email is sent. To keep a bot scan or a repeating error +from flooding the inbox, set: + +- `errorEmailRateLimit` — most emails for one error fingerprint per window + (default `0`, unlimited); +- `errorEmailGlobalRateLimit` — most error emails across all fingerprints per + window (default `0`, unlimited); +- `errorEmailRateWindowMinutes` — the fixed window in minutes (default `15`). + +A fingerprint is the root cause type + message + first application stack frame. +When a window expires, the next allowed email includes a short count of the +occurrences suppressed since the last one. These counters live in the +application scope per server; on a multi-server deployment the caps are per +node, not global across the fleet. + diff --git a/cli/lucli/templates/app/config/production/settings.cfm b/cli/lucli/templates/app/config/production/settings.cfm index de41808e32..2b561651a4 100644 --- a/cli/lucli/templates/app/config/production/settings.cfm +++ b/cli/lucli/templates/app/config/production/settings.cfm @@ -6,4 +6,8 @@ // Error emails (sendEmailOnError is on in production) go only to an address // you configure; with none set, no error email is sent. Example: // set(errorEmailAddress = "ops@example.com"); +// Optional error-email throttling (caps default to 0 = unlimited): +// set(errorEmailRateLimit = 3); // per error fingerprint, per window +// set(errorEmailGlobalRateLimit = 30); // all error emails, per window +// set(errorEmailRateWindowMinutes = 15); // fixed window, 1..1440 diff --git a/cli/lucli/templates/app/config/settings.cfm b/cli/lucli/templates/app/config/settings.cfm index fee3b880a5..d1ae95dcef 100644 --- a/cli/lucli/templates/app/config/settings.cfm +++ b/cli/lucli/templates/app/config/settings.cfm @@ -29,6 +29,10 @@ // Error emails: production turns sendEmailOnError on, but they go only to // an address you configure. With none set, no error email is sent. // set(errorEmailAddress=env("WHEELS_ERROR_EMAIL", "")); + // Optional error-email throttling (both caps default to 0 = unlimited): + // set(errorEmailRateLimit=3); // per error fingerprint, per window + // set(errorEmailGlobalRateLimit=30); // all error emails, per window + // set(errorEmailRateWindowMinutes=15); // fixed window, 1..1440 /* Canonical base URL for absolute links, redirects and emails. When set, its diff --git a/cli/src/commands/wheels/get/settings.cfc b/cli/src/commands/wheels/get/settings.cfc index 817aacd99f..c25cf3b286 100644 --- a/cli/src/commands/wheels/get/settings.cfc +++ b/cli/src/commands/wheels/get/settings.cfc @@ -188,6 +188,9 @@ component extends="../base" { "errorEmailAddress": "", "errorEmailServer": "", "errorEmailSubject": "Error", + "errorEmailRateLimit": 0, + "errorEmailRateWindowMinutes": 15, + "errorEmailGlobalRateLimit": 0, "excludeFromErrorEmail": "", "includeErrorInEmailSubject": true, "overwritePlugins": true, diff --git a/docs/consumer-ai/.ai/views.md b/docs/consumer-ai/.ai/views.md index 900b337ed2..6c9b02c39c 100644 --- a/docs/consumer-ai/.ai/views.md +++ b/docs/consumer-ai/.ai/views.md @@ -52,3 +52,21 @@ In the `development` environment, an error response asked for as `Accept: application/json` (or `?format=json`) is that same payload as JSON, and `Accept: text/markdown` (or `?format=md`) gets it as Markdown, with the error page's status code. Testing and production responses are unchanged. + +### Error-email throttling + +Production turns `sendEmailOnError` on; configure `errorEmailAddress` (or `errorEmailToAddress`) or no email is sent. To keep a bot scan or a repeating error +from flooding the inbox, set: + +- `errorEmailRateLimit` — most emails for one error fingerprint per window + (default `0`, unlimited); +- `errorEmailGlobalRateLimit` — most error emails across all fingerprints per + window (default `0`, unlimited); +- `errorEmailRateWindowMinutes` — the fixed window in minutes (default `15`). + +A fingerprint is the root cause type + message + first application stack frame. +When a window expires, the next allowed email includes a short count of the +occurrences suppressed since the last one. These counters live in the +application scope per server; on a multi-server deployment the caps are per +node, not global across the fleet. + diff --git a/vendor/wheels/events/EventMethods.cfc b/vendor/wheels/events/EventMethods.cfc index d7f68809e6..97582317fb 100644 --- a/vendor/wheels/events/EventMethods.cfc +++ b/vendor/wheels/events/EventMethods.cfc @@ -51,6 +51,13 @@ component extends="wheels.Global" implements="wheels.interfaces.events.EventHand $warnNoErrorEmailRecipient(); return; } + // Throttle after the recipient check (no state for an unconfigured app) + // and before building/sending. With both caps 0 this returns + // allowed=true without reading or creating any state. + local.throttle = $errorEmailThrottleReserve(arguments.exception); + if (!local.throttle.allowed) { + return; + } if (Len(local.args.from) && Len(local.args.to)) { if (StructKeyExists(application.wheels, "errorEmailServer") && Len(application.wheels.errorEmailServer)) { local.args.server = application.wheels.errorEmailServer; @@ -70,6 +77,9 @@ component extends="wheels.Global" implements="wheels.interfaces.events.EventHand $template = "/wheels/events/onerror/cfmlerror.cfm", exception = arguments.exception ); + if (Len(local.throttle.summary)) { + local.args.tagContent = local.throttle.summary & local.args.tagContent; + } StructDelete(local.args, "layouts", false); StructDelete(local.args, "detectMultiPart", false); try { @@ -79,6 +89,361 @@ component extends="wheels.Global" implements="wheels.interfaces.events.EventHand } } + /** + * Internal: one error-email throttle setting as a whole number from 0 to + * `maximum`, written as plain digits (an engine double may carry a ".0" tail). + * Anything else — missing, fractional, signed, exponent notation, an array or + * struct, or out of range — is the fallback; 0 is a valid value (unlimited). + * Mirrors JobTickEndpoint.$wholeSetting(), but lives here because onError must + * never throw: the one warning is best-effort and the fallback is always used. + */ + public numeric function $errorEmailWholeSettingAllowZero( + required string name, + required numeric fallback, + required numeric maximum + ) { + return $errorEmailWholeSetting( + name = arguments.name, + fallback = arguments.fallback, + maximum = arguments.maximum, + minimum = 0 + ); + } + + /** + * Internal: one error-email throttle setting as a whole number from `minimum` + * to `maximum`, written as plain digits. A ".0" tail is accepted because the + * JobTickEndpoint.$wholeSetting() precedent accepts it for engine doubles + * (that allowance is documented there and deliberately mirrored here). + * Anything else — missing, fractional, signed, exponent notation, an array or + * struct, or out of range — is the fallback, with one warning per setting. + * Never throws: this runs inside onError. + */ + public numeric function $errorEmailWholeSetting( + required string name, + required numeric fallback, + required numeric maximum, + numeric minimum = 0 + ) { + local.value = ""; + try { + if (StructKeyExists(application, "wheels") && StructKeyExists(application.wheels, arguments.name)) { + local.value = application.wheels[arguments.name]; + } + } catch (any e) { + } + local.valid = false; + if (IsSimpleValue(local.value)) { + local.text = Trim(ToString(local.value)); + if (ReFind("^[0-9]+(\.0+)?$", local.text)) { + local.number = Val(ListFirst(local.text, ".")); + if (local.number >= arguments.minimum && local.number <= arguments.maximum) { + local.valid = true; + } + } + } + if (local.valid) { + return local.number; + } + // Best-effort single warning per setting per application; never throw. + try { + if (!StructKeyExists(application.wheels, "$errorEmailThrottleSettingsWarned")) { + application.wheels["$errorEmailThrottleSettingsWarned"] = {}; + } + if (!StructKeyExists(application.wheels.$errorEmailThrottleSettingsWarned, arguments.name)) { + application.wheels.$errorEmailThrottleSettingsWarned[arguments.name] = true; + WriteLog( + file = "wheels", + type = "warning", + text = "Wheels: #arguments.name# must be a whole number from #arguments.minimum# to #arguments.maximum#; using the default #arguments.fallback# for error-email throttling." + ); + } + } catch (any e) { + } + return arguments.fallback; + } + + /** + * Internal: the defensive part of fingerprinting — root-cause type/message and + * the tagContext frames, from either the root cause or the outer exception. + * Every field is optional on some engine; this must never throw. + */ + public struct function $errorEmailRootDetails(required any exception) { + local.details = {type = "Application", message = "", frames = []}; + try { + local.root = {}; + if (StructKeyExists(arguments.exception, "rootCause") && IsStruct(arguments.exception.rootCause)) { + local.root = arguments.exception.rootCause; + } + if (StructKeyExists(local.root, "type") && IsSimpleValue(local.root.type) && Len(Trim(ToString(local.root.type)))) { + local.details.type = ToString(local.root.type); + } else if (StructKeyExists(arguments.exception, "type") && IsSimpleValue(arguments.exception.type) && Len(Trim(ToString(arguments.exception.type)))) { + local.details.type = ToString(arguments.exception.type); + } + if (StructKeyExists(local.root, "message") && IsSimpleValue(local.root.message)) { + local.details.message = ToString(local.root.message); + } else if (StructKeyExists(arguments.exception, "message") && IsSimpleValue(arguments.exception.message)) { + local.details.message = ToString(arguments.exception.message); + } + if (StructKeyExists(local.root, "tagContext") && IsArray(local.root.tagContext)) { + local.details.frames = local.root.tagContext; + } else if (StructKeyExists(arguments.exception, "tagContext") && IsArray(arguments.exception.tagContext)) { + local.details.frames = arguments.exception.tagContext; + } else if (StructKeyExists(local.root, "tagContext") && IsStruct(local.root.tagContext)) { + local.details.frames = [local.root.tagContext]; + } else if (StructKeyExists(arguments.exception, "tagContext") && IsStruct(arguments.exception.tagContext)) { + local.details.frames = [arguments.exception.tagContext]; + } + } catch (any e) { + } + return local.details; + } + + /** + * Internal: first application frame as {file, line}. Framework frames under + * vendor/wheels are skipped; with no app frame the first frame is used, and + * with no frames at all the file is "no-frame". Defensive on every shape. + */ + public struct function $errorEmailApplicationFrame(required array frames) { + local.first = {}; + local.firstApplication = {}; + try { + for (local.frame in arguments.frames) { + if (!IsStruct(local.frame)) { + continue; + } + local.path = ""; + if (StructKeyExists(local.frame, "template") && IsSimpleValue(local.frame.template) && Len(Trim(ToString(local.frame.template)))) { + local.path = ToString(local.frame.template); + } else if (StructKeyExists(local.frame, "file") && IsSimpleValue(local.frame.file)) { + local.path = ToString(local.frame.file); + } + local.line = 0; + if (StructKeyExists(local.frame, "line") && IsNumeric(local.frame.line)) { + local.line = Int(Val(local.frame.line)); + } + local.candidate = {path = local.path, line = local.line}; + if (StructIsEmpty(local.first)) { + local.first = local.candidate; + } + local.normalized = Replace(local.path, "\", "/", "all"); + if (!FindNoCase("/vendor/wheels/", "/" & local.normalized & "/")) { + local.firstApplication = local.candidate; + break; + } + } + } catch (any e) { + } + local.use = StructIsEmpty(local.firstApplication) ? local.first : local.firstApplication; + local.file = "no-frame"; + local.line = 0; + if (!StructIsEmpty(local.use)) { + local.normalized = Replace(local.use.path, "\", "/", "all"); + if (Len(local.normalized)) { + local.file = GetFileFromPath(local.normalized); + if (!Len(local.file)) { + local.file = local.normalized; + } + } + local.line = local.use.line; + } + return {file = local.file, line = local.line}; + } + + /** + * Internal: SHA-256 fingerprint of an exception's root cause — type, message + * (first 1000 chars) and the first application stack frame's file basename and + * line. Only the hash is stored in application state. + */ + public string function $errorEmailFingerprint(required any exception) { + local.details = $errorEmailRootDetails(arguments.exception); + local.frame = $errorEmailApplicationFrame(local.details.frames); + local.canonical = LCase(Trim(local.details.type)) & "|" & LCase(Trim(Left(local.details.message, 1000))) & "|" & LCase(Trim(local.frame.file)) & ":" & local.frame.line; + return Hash(local.canonical, "SHA-256", "utf-8"); + } + + /** + * Internal: warn once per application that the throttle lock was unavailable. + * Fail-open is deliberate, but a missing lock on every error must not write a + * log line per error — that is the flood this feature exists to prevent, + * moved into the log. Mirrors $legacyDebugIpBlockWarned (settings.cfm). + * Best-effort: never throws. + */ + public void function $warnErrorEmailThrottleLockFailure() { + try { + if (StructKeyExists(application.wheels, "$errorEmailThrottleLockWarned")) { + return; + } + application.wheels["$errorEmailThrottleLockWarned"] = true; + WriteLog( + file = "wheels", + type = "warning", + text = "Wheels: the error-email throttle lock was not available; sending error emails unthrottled (fail-open). This warning is logged once per application start." + ); + } catch (any e) { + } + } + + /** + * Internal: decides whether this error email may be sent and, when one is + * allowed after suppressions, returns the numbers-only summary paragraph. + * Fails open: with both caps 0 it never touches state, and a lock failure is + * logged and treated as allowed (a throttling failure must not lose an error). + */ + public struct function $errorEmailThrottleReserve(required any exception) { + local.perCap = $errorEmailWholeSettingAllowZero(name = "errorEmailRateLimit", fallback = 0, maximum = 1000); + local.globalCap = $errorEmailWholeSettingAllowZero(name = "errorEmailGlobalRateLimit", fallback = 0, maximum = 10000); + // Approved range is 1..1440: 0 is out of range and falls back with one + // warning (the helper logs it), never a silent clamp. + local.window = $errorEmailWholeSetting( + name = "errorEmailRateWindowMinutes", + fallback = 15, + maximum = 1440, + minimum = 1 + ); + if (local.perCap == 0 && local.globalCap == 0) { + return {allowed = true, summary = ""}; + } + local.hash = $errorEmailFingerprint(arguments.exception); + local.result = {allowed = true, summary = ""}; + try { + lock name="wheels.errorEmailThrottle.#application.applicationName#" type="exclusive" timeout="5" { + local.result = $errorEmailThrottleUnderLock( + hash = local.hash, + perCap = local.perCap, + globalCap = local.globalCap, + window = local.window + ); + } + } catch (any e) { + $warnErrorEmailThrottleLockFailure(); + return {allowed = true, summary = ""}; + } + return local.result; + } + + /** + * Internal: the locked half of $errorEmailThrottleReserve. Fixed window; a + * rolled window keeps `suppressed` until an allowed email reports it, so the + * next send still summarises everything suppressed since the previous one. + * State is capped at 512 fingerprints (expired, unsuppressed entries pruned + * first, then the oldest windowStart evicted). + */ + public struct function $errorEmailThrottleUnderLock( + required string hash, + required numeric perCap, + required numeric globalCap, + required numeric window + ) { + if (!StructKeyExists(application.wheels, "errorEmailThrottle") || !IsStruct(application.wheels.errorEmailThrottle)) { + application.wheels["errorEmailThrottle"] = { + global = {windowStart = Now(), count = 0, suppressed = 0}, + fingerprints = {} + }; + } + local.state = application.wheels.errorEmailThrottle; + local.now = Now(); + if (DateDiff("n", local.state.global.windowStart, local.now) >= arguments.window) { + local.state.global.windowStart = local.now; + local.state.global.count = 0; + } + if (!StructKeyExists(local.state.fingerprints, arguments.hash)) { + local.state.fingerprints[arguments.hash] = {windowStart = local.now, count = 0, suppressed = 0}; + } + local.fingerprint = local.state.fingerprints[arguments.hash]; + if (DateDiff("n", local.fingerprint.windowStart, local.now) >= arguments.window) { + local.fingerprint.windowStart = local.now; + local.fingerprint.count = 0; + } + + local.allowed = true; + if (arguments.perCap > 0 && local.fingerprint.count >= arguments.perCap) { + local.allowed = false; + } + if (arguments.globalCap > 0 && local.state.global.count >= arguments.globalCap) { + local.allowed = false; + } + + if (!local.allowed) { + local.fingerprint.suppressed = local.fingerprint.suppressed + 1; + local.state.global.suppressed = local.state.global.suppressed + 1; + $errorEmailThrottlePrune(state = local.state, window = arguments.window, now = local.now); + return {allowed = false, summary = ""}; + } + + local.fingerprintSuppressed = local.fingerprint.suppressed; + local.globalSuppressed = local.state.global.suppressed; + local.fingerprint.count = local.fingerprint.count + 1; + local.state.global.count = local.state.global.count + 1; + local.fingerprint.suppressed = 0; + local.state.global.suppressed = 0; + $errorEmailThrottlePrune(state = local.state, window = arguments.window, now = local.now); + return { + allowed = true, + summary = $errorEmailThrottleSummary( + fingerprintSuppressed = local.fingerprintSuppressed, + globalSuppressed = local.globalSuppressed, + window = arguments.window + ) + }; + } + + /** + * Internal: the numbers-only summary paragraph; no exception text. Empty when + * nothing was suppressed since the previous allowed email. + */ + public string function $errorEmailThrottleSummary( + required numeric fingerprintSuppressed, + required numeric globalSuppressed, + required numeric window + ) { + local.minutes = arguments.window; + if (arguments.fingerprintSuppressed > 0 && arguments.globalSuppressed > 0) { + return "
Wheels: #arguments.fingerprintSuppressed# occurrence(s) of this error and #arguments.globalSuppressed# error email(s) were suppressed in the last #local.minutes# minute(s).
"; + } + if (arguments.fingerprintSuppressed > 0) { + return "Wheels: #arguments.fingerprintSuppressed# occurrence(s) of this error were suppressed in the last #local.minutes# minute(s).
"; + } + if (arguments.globalSuppressed > 0) { + return "Wheels: #arguments.globalSuppressed# error email(s) were suppressed in the last #local.minutes# minute(s).
"; + } + return ""; + } + + /** + * Internal: bound the throttle state to 512 fingerprints. Expired entries with + * nothing suppressed are dropped first; if that is not enough, the oldest + * windowStart goes. Hashes are 64 characters and values are small, so the cap + * keeps a bot hitting unique paths from growing state without limit. + */ + public void function $errorEmailThrottlePrune(required struct state, required numeric window, required any now) { + local.max = 512; + if (StructCount(arguments.state.fingerprints) <= local.max) { + return; + } + for (local.key in StructKeyArray(arguments.state.fingerprints)) { + local.entry = arguments.state.fingerprints[local.key]; + if (local.entry.suppressed == 0 && DateDiff("n", local.entry.windowStart, arguments.now) >= arguments.window) { + StructDelete(arguments.state.fingerprints, local.key); + } + } + while (StructCount(arguments.state.fingerprints) > local.max) { + local.oldestKey = ""; + local.oldest = ""; + for (local.key in StructKeyArray(arguments.state.fingerprints)) { + local.entry = arguments.state.fingerprints[local.key]; + if (!Len(local.oldestKey) || DateCompare(local.entry.windowStart, local.oldest) < 0) { + local.oldestKey = local.key; + local.oldest = local.entry.windowStart; + } + } + if (!Len(local.oldestKey)) { + break; + } + StructDelete(arguments.state.fingerprints, local.oldestKey); + } + } + /** * sendEmailOnError is on but no recipient is configured: say so once per * application start in wheels.log instead of sending anything. diff --git a/vendor/wheels/events/init/debugging.cfm b/vendor/wheels/events/init/debugging.cfm index 7083c8d020..d6d2e73ace 100644 --- a/vendor/wheels/events/init/debugging.cfm +++ b/vendor/wheels/events/init/debugging.cfm @@ -14,6 +14,11 @@ application.$wheels.errorEmailToAddress = ""; application.$wheels.errorEmailFromAddress = ""; application.$wheels.includeErrorInEmailSubject = true; + // Error-email throttling. 0 = unlimited/current behaviour; with both caps + // 0 the throttle is bypassed entirely. Opt in via the caps, not a switch. + application.$wheels.errorEmailRateLimit = 0; + application.$wheels.errorEmailRateWindowMinutes = 15; + application.$wheels.errorEmailGlobalRateLimit = 0; // No default recipient. Error emails carry request and session data, so // the address must come from configuration, never from the request. application.$wheels.errorEmailAddress = ""; diff --git a/vendor/wheels/public/views/info.cfm b/vendor/wheels/public/views/info.cfm index d62e4bdb89..bc5edfcb7e 100644 --- a/vendor/wheels/public/views/info.cfm +++ b/vendor/wheels/public/views/info.cfm @@ -62,6 +62,9 @@ settings = [ // 'errorEmailServer' // Check this 'errorEmailAddress', 'errorEmailSubject', + 'errorEmailRateLimit', + 'errorEmailRateWindowMinutes', + 'errorEmailGlobalRateLimit', 'excludeFromErrorEmail', 'sendEmailOnError', 'showErrorInformation' diff --git a/vendor/wheels/tests/specs/events/ErrorEmailThrottleSpec.cfc b/vendor/wheels/tests/specs/events/ErrorEmailThrottleSpec.cfc new file mode 100644 index 0000000000..3ebfc21f64 --- /dev/null +++ b/vendor/wheels/tests/specs/events/ErrorEmailThrottleSpec.cfc @@ -0,0 +1,303 @@ +/** + * Error-email throttling (#4694 Part 1). The approved defaults are unlimited: + * with both caps 0 the send path must behave exactly as it did before this + * feature existed (no state, every configured email sent). The rest of the + * suite drives the OnErrorEventDouble's recording $mail() — no SMTP. + */ +component extends="wheels.WheelsTest" { + + function run() { + + describe("error email throttling (##4694)", () => { + + beforeEach(() => { + variables.saved = {}; + for (var key in [ + "sendEmailOnError", + "errorEmailAddress", + "errorEmailToAddress", + "errorEmailFromAddress", + "errorEmailRateLimit", + "errorEmailRateWindowMinutes", + "errorEmailGlobalRateLimit", + "showErrorInformation" + ]) { + variables.saved[key] = StructKeyExists(application.wheels, key) ? application.wheels[key] : ""; + } + StructDelete(application.wheels, "errorEmailThrottle"); + StructDelete(application.wheels, "$errorEmailThrottleSettingsWarned"); + StructDelete(application.wheels, "$errorEmailThrottleLockWarned"); + application.wheels.sendEmailOnError = true; + application.wheels.errorEmailAddress = "ops@example.com"; + application.wheels.errorEmailToAddress = ""; + application.wheels.errorEmailFromAddress = ""; + application.wheels.errorEmailRateLimit = 0; + application.wheels.errorEmailRateWindowMinutes = 15; + application.wheels.errorEmailGlobalRateLimit = 0; + }); + + afterEach(() => { + for (var key in variables.saved) { + application.wheels[key] = variables.saved[key]; + } + StructDelete(application.wheels, "errorEmailThrottle"); + StructDelete(application.wheels, "$errorEmailThrottleSettingsWarned"); + StructDelete(application.wheels, "$errorEmailThrottleLockWarned"); + }); + + it("sends every configured email and creates no state when both caps are 0", () => { + var em = mailer(); + for (var i = 1; i <= 5; i++) { + em.$runOnErrorSendEmail(sampleException()); + } + expect(em.mailCalls).toBe(5); + expect(StructKeyExists(application.wheels, "errorEmailThrottle")).toBeFalse( + "the default must not create throttle state" + ); + }); + + it("caps one fingerprint and still lets a different fingerprint through", () => { + application.wheels.errorEmailRateLimit = 2; + var em = mailer(); + for (var i = 1; i <= 4; i++) { + em.$runOnErrorSendEmail(sampleException()); + } + expect(em.mailCalls).toBe(2); + em.$runOnErrorSendEmail(sampleException(message = "a different failure")); + expect(em.mailCalls).toBe(3, "a different fingerprint must not be suppressed by this one"); + }); + + it("caps globally across distinct fingerprints", () => { + application.wheels.errorEmailGlobalRateLimit = 2; + var em = mailer(); + em.$runOnErrorSendEmail(sampleException(message = "first")); + em.$runOnErrorSendEmail(sampleException(message = "second")); + em.$runOnErrorSendEmail(sampleException(message = "third")); + expect(em.mailCalls).toBe(2); + expireWindows(); + em.$runOnErrorSendEmail(sampleException(message = "fourth")); + expect(em.mailCalls).toBe(3, "the next window must allow an email"); + expect(em.mailArgs[3].tagContent).toInclude("error email(s) were suppressed"); + }); + + it("resets the count when the window rolls and summarises the suppressions", () => { + application.wheels.errorEmailRateLimit = 1; + var em = mailer(); + em.$runOnErrorSendEmail(sampleException()); + em.$runOnErrorSendEmail(sampleException()); + em.$runOnErrorSendEmail(sampleException()); + expect(em.mailCalls).toBe(1); + expect(em.mailArgs[1].tagContent).notToInclude("were suppressed"); + expireWindows(); + em.$runOnErrorSendEmail(sampleException()); + expect(em.mailCalls).toBe(2); + expect(em.mailArgs[2].tagContent).toInclude("2 occurrence(s) of this error"); + expect(em.mailArgs[2].tagContent).toInclude("15 minute(s)"); + var state = application.wheels.errorEmailThrottle; + expect(state.global.suppressed).toBe(0, "the summary resets the suppressed counts"); + }); + + it("summarises the global count when only the global cap fired", () => { + application.wheels.errorEmailGlobalRateLimit = 1; + var em = mailer(); + em.$runOnErrorSendEmail(sampleException(message = "one")); + em.$runOnErrorSendEmail(sampleException(message = "two")); + expect(em.mailCalls).toBe(1); + expireWindows(); + em.$runOnErrorSendEmail(sampleException(message = "three")); + expect(em.mailCalls).toBe(2); + expect(em.mailArgs[2].tagContent).toInclude("1 error email(s) were suppressed"); + }); + + it("keeps fingerprints isolated by root cause and application frame, with defensive tagContext handling", () => { + var g = mailer(); + var a = g.$errorEmailFingerprint(sampleException()); + var b = g.$errorEmailFingerprint(sampleException(message = "different message")); + expect(a).notToBe(b); + + var sameMessageOtherFrame = sampleException(template = "/app/controllers/Other.cfc", line = 12); + expect(g.$errorEmailFingerprint(sampleException())).notToBe(g.$errorEmailFingerprint(sameMessageOtherFrame)); + + var noContext = sampleException(); + StructDelete(noContext.rootCause, "tagContext"); + expect(g.$errorEmailFingerprint(noContext)).toBe(g.$errorEmailFingerprint(noContext)); + + var lucreStyle = sampleException(); + lucreStyle.rootCause.tagContext = [{file = "/app/controllers/Posts.cfc", line = 42}]; + var adobeStyle = sampleException(); + adobeStyle.rootCause.tagContext = [{template = "/app/controllers/Posts.cfc", line = 42}]; + expect(g.$errorEmailFingerprint(lucreStyle)).toBe(g.$errorEmailFingerprint(adobeStyle)); + }); + + it("skips framework frames and hashes the first application frame", () => { + var g = mailer(); + var first = sampleException( + tagContext = [ + {template = "/vendor/wheels/events/onerror/cfmlerror.cfm", line = 10}, + {template = "/app/controllers/Posts.cfc", line = 42} + ] + ); + var second = sampleException( + tagContext = [ + {template = "/vendor/wheels/events/onapplicationstart.cfc", line = 1}, + {template = "/app/controllers/Posts.cfc", line = 42} + ] + ); + expect(g.$errorEmailFingerprint(first)).toBe(g.$errorEmailFingerprint(second)); + }); + + it("does not create state, send mail, or warn twice when no recipient is configured", () => { + application.wheels.errorEmailAddress = ""; + application.wheels.errorEmailRateLimit = 2; + var em = mailer(); + em.$runOnErrorSendEmail(sampleException()); + em.$runOnErrorSendEmail(sampleException()); + expect(em.mailCalls).toBe(0); + expect(StructKeyExists(application.wheels, "errorEmailThrottle")).toBeFalse(); + }); + + it("falls back to the defaults for invalid settings instead of throwing", () => { + var g = mailer(); + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailRateLimit = -1; + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailRateLimit = 1.5; + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailRateLimit = "1e3"; + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailRateLimit = [3]; + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailRateLimit = {value = 3}; + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailRateLimit = 1001; + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailRateLimit = 0; + expect(g.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + }); + + it("does not throw out of the send path when mail throws, and keeps the state consistent", () => { + application.wheels.errorEmailRateLimit = 1; + var em = mailer(); + em.mailShouldThrow = true; + em.$runOnErrorSendEmail(sampleException()); + em.$runOnErrorSendEmail(sampleException()); + expect(em.mailCalls).toBe(1); + var state = application.wheels.errorEmailThrottle; + expect(state.global.count).toBe(1, "the failed send still consumes the reservation"); + }); + + it("leaves the rendered error path intact", () => { + application.wheels.showErrorInformation = false; + application.wheels.errorEmailRateLimit = 1; + var em = mailer(); + em.$runOnError(exception = sampleException(), eventName = "onError"); + expect(em.mailCalls).toBe(1); + }); + + it("rejects a 0-minute window with a warning instead of silently clamping it", () => { + var em = mailer(); + // Approved range is 1..1440; 0 is out of range, not "unlimited". + application.wheels.errorEmailRateWindowMinutes = 0; + expect( + em.$errorEmailWholeSetting( + name = "errorEmailRateWindowMinutes", + fallback = 15, + maximum = 1440, + minimum = 1 + ) + ).toBe(15); + expect(StructKeyExists(application.wheels, "$errorEmailThrottleSettingsWarned")).toBeTrue(); + expect( + StructKeyExists(application.wheels.$errorEmailThrottleSettingsWarned, "errorEmailRateWindowMinutes") + ).toBeTrue("the invalid window must warn once"); + + application.wheels.errorEmailRateWindowMinutes = 1; + expect( + em.$errorEmailWholeSetting( + name = "errorEmailRateWindowMinutes", + fallback = 15, + maximum = 1440, + minimum = 1 + ) + ).toBe(1); + application.wheels.errorEmailRateWindowMinutes = 60; + expect( + em.$errorEmailWholeSetting( + name = "errorEmailRateWindowMinutes", + fallback = 15, + maximum = 1440, + minimum = 1 + ) + ).toBe(60); + + // Integration: the reserve path must use the 1..1440 parse, not the + // allow-zero helper followed by a silent clamp. + StructDelete(application.wheels, "$errorEmailThrottleSettingsWarned"); + application.wheels.errorEmailRateWindowMinutes = 0; + application.wheels.errorEmailRateLimit = 1; + em.$errorEmailThrottleReserve(sampleException()); + expect(StructKeyExists(application.wheels, "$errorEmailThrottleSettingsWarned")).toBeTrue( + "the reserve path must warn for a 0-minute window" + ); + expect( + StructKeyExists(application.wheels.$errorEmailThrottleSettingsWarned, "errorEmailRateWindowMinutes") + ).toBeTrue(); + }); + + it("still accepts 0 for the caps (0 = unlimited)", () => { + var em = mailer(); + application.wheels.errorEmailRateLimit = 0; + expect(em.$errorEmailWholeSettingAllowZero("errorEmailRateLimit", 0, 1000)).toBe(0); + application.wheels.errorEmailGlobalRateLimit = 0; + expect(em.$errorEmailWholeSettingAllowZero("errorEmailGlobalRateLimit", 0, 10000)).toBe(0); + }); + + it("warns once, not per failure, when the throttle lock is unavailable", () => { + var em = mailer(); + expect(StructKeyExists(application.wheels, "$errorEmailThrottleLockWarned")).toBeFalse(); + em.$warnErrorEmailThrottleLockFailure(); + expect(StructKeyExists(application.wheels, "$errorEmailThrottleLockWarned")).toBeTrue(); + // The second call must take the early return (one warning total). + em.$warnErrorEmailThrottleLockFailure(); + expect(application.wheels.$errorEmailThrottleLockWarned).toBeTrue(); + }); + + }); + + } + + private any function mailer() { + return new wheels.tests._assets.events.OnErrorEventDouble(); + } + + private struct function sampleException( + string message = "Something went wrong", + string template = "/app/controllers/Posts.cfc", + numeric line = 42, + array tagContext = [] + ) { + var frames = ArrayLen(arguments.tagContext) ? arguments.tagContext : [{template = arguments.template, line = arguments.line}]; + return { + type = "Application", + message = arguments.message, + rootCause = { + type = "Wheels.TestError", + message = arguments.message, + tagContext = frames + }, + tagContext = frames + }; + } + + private void function expireWindows() { + if (!StructKeyExists(application.wheels, "errorEmailThrottle")) { + return; + } + var state = application.wheels.errorEmailThrottle; + state.global.windowStart = DateAdd("n", -30, Now()); + for (var key in state.fingerprints) { + state.fingerprints[key].windowStart = DateAdd("n", -30, Now()); + } + } + +}