All files / Scripts/rules/engine HeaderValidationRules.ts

97.91% Statements 94/96
89.06% Branches 57/64
95.83% Functions 23/24
98.9% Lines 90/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 2886x 6x 6x   6x           62x   43x     62x           62x         62x   60x         62x 26x   26x 2x     60x             6x 32x           1503x   1503x 1303x 1184x   1183x 51x         1502x               212x   1492x     1491x   42x                     58x   51x   11x   8x   5x 10x   9x       9x         3x                     53x               28x   28x 27x 29x   29x 26x             3x 2x                   28x 27x 2x   2x   2x 2x 4x   4x 4x                   2x                       1303x       51x       8x                     54x   58x 9x 9x       49x   49x             3x 3x 3x   3x   3x   3x     3x         46x 46x             54x 54x   51x   51x 4x     4x     4x 4x               6x         6x 105x   105x 268x 1427x 152x         105x  
import { OtherRow } from "../../row/OtherRow";
import { AndValidationRule } from "../types/AndValidationRule";
import { HeaderSectionMissingRule } from "../types/HeaderSectionMissingRule";
import { HeaderSection, IAndRuleData, IComplexValidationRule, IRuleData, ISimpleValidationRule, IValidationRule } from "../types/interfaces";
import { SimpleValidationRule } from "../types/SimpleValidationRule";
 
// Add the rule to the rulesFlagged component of the toObject.  This is used
// to flag sub-sections within a tab with a rule that they have violated.
function addRuleFlagged( toObject: HeaderSection, rule: IValidationRule | IValidationRule[] ): void
{
    if ( !toObject.rulesFlagged )
    {
        toObject.rulesFlagged = [];
    }
 
    Iif ( Array.isArray( rule ) )
    {
        rule.forEach( function ( oneRule ) { addRuleFlagged( toObject, oneRule ); } );
    }
    else
    {
        pushUniqueRule( toObject.rulesFlagged, rule );
    }
 
    function pushUniqueRule(ruleArray: IValidationRule[], rule: IValidationRule): void {
 
        if (!arrayContains(ruleArray, rule))
        {
            ruleArray.push(rule);
        }
 
        function arrayContains(array: IValidationRule[], value: IValidationRule): boolean
        {
            for (let index = 0; index < array.length; index++) {
                const entry = array[index];
 
                if (entry === value) {
                    return true;
                };
            };
            return false;
        };
    }
}
 
type ValidationRule = ISimpleValidationRule | IComplexValidationRule;
 
export class HeaderValidationRulesEngine {
    private validationRuleSet: ValidationRule[] = [];
    /**
     * Find all the Violations that exist in the section. This only tests for violations of simple rules
     * (rules that implement 'violatesRule') as complex rules apply across multiple sections.
     */
    public findViolations(section: HeaderSection): ISimpleValidationRule[] {
        const rulesViolated: ISimpleValidationRule[] = [];
 
        this.validationRuleSet.forEach((rule) => {
            if (this.isSimpleRule(rule)) {
                const flaggedText = rule.violatesRule(section);
 
                if (flaggedText) {
                    rulesViolated.push(rule);
                }
            }
        });
 
        return rulesViolated;
    }
 
    /**
     * Flag all rows within the tab (set of sections to display) that violate a rule
     */
    public flagAllRowsWithViolations(tabData: HeaderSection[], setOfSections: HeaderSection[][]): void {
        // for each section in the set of data displayed on one tab
        tabData.forEach((tabDataSection) => {
            // Find any violations of rules for that section
            const newItemsFlagged = this.findViolations(tabDataSection);
 
            // For each rule that was violated
            newItemsFlagged.forEach((ruleFlagged) => {
                // Flag the section that the rule that was violated says to mark with an error message
                this.flagRuleInSections(ruleFlagged, setOfSections);
            });
        });
    }
 
    /**
     * Find and flag all the complex rules that are violated. Label the sections that the violated rule
     * says to mark the error on.
     */
    public findComplexViolations(setOfSections: HeaderSection[][]): void {
        // for each of the rules that have been defined
        this.validationRuleSet.forEach((rule) => {
            // IF it is a complex rule
            if (this.isComplexRule(rule)) {
                // Check Complex rule
                if (rule.violatesComplexRule(setOfSections)) {
                    // IF it's an AND rule with subrules, only flag the child rules with parent context
                    if (this.isAndRule(rule)) {
                        // Show sub-rules with message and parent context
                        rule.rulesToAndArray.forEach((reportRule) => {
                            if (reportRule && reportRule.errorMessage !== "") {
                                // Attach parent AND rule information to child rule
                                reportRule.parentAndRule = {
                                    message: rule.errorMessage,
                                    severity: rule.severity || "error"
                                };
                                this.flagRuleInSections(reportRule, setOfSections);
                            }
                        });
                    } else {
                        // For non-AND rules, flag the rule itself
                        this.flagRuleInSections(rule, setOfSections);
                    }
                }
            }
        });
    }
 
    /**
     * Add Rule to the set of rules to check the header for
     */
    public addRule(newRule: ValidationRule): void {
        this.validationRuleSet.push(newRule);
    }
 
    /**
     * Set the rules from JSON data
     */
    public setRules(simpleRuleSet?: IRuleData[], andRuleSet?: IAndRuleData[]): void {
        // Clear existing rules
        this.validationRuleSet = [];
 
        if (simpleRuleSet) {
            for (let ruleIndex = 0; ruleIndex < simpleRuleSet.length; ruleIndex++) {
                const newRule = simpleRuleSet[ruleIndex];
 
                if (newRule && newRule.RuleType === "SimpleRule") {
                    this.addRule(new SimpleValidationRule(
                        newRule.SectionToCheck,
                        newRule.PatternToCheckFor || "",
                        newRule.MessageWhenPatternFails,
                        newRule.SectionsInHeaderToShowError,
                        newRule.Severity
                    ));
                } else if (newRule && newRule.RuleType === "HeaderMissingRule") {
                    this.addRule(new HeaderSectionMissingRule(
                        newRule.SectionToCheck,
                        newRule.MessageWhenPatternFails,
                        newRule.SectionsInHeaderToShowError,
                        newRule.Severity
                    ));
                }
            }
        }
 
        if (andRuleSet) {
            for (let ruleIndex = 0; ruleIndex < andRuleSet.length; ruleIndex++) {
                const newRule = andRuleSet[ruleIndex];
 
                Eif (newRule && newRule.RulesToAnd) {
                    // Create set of rules to and
                    const rulesToAnd: SimpleValidationRule[] = [];
                    for (let ruleToAndIndex = 0; ruleToAndIndex < newRule.RulesToAnd.length; ruleToAndIndex++) {
                        const newAndRule = newRule.RulesToAnd[ruleToAndIndex];
 
                        Eif (newAndRule) {
                            rulesToAnd.push(new SimpleValidationRule(
                                newAndRule.SectionToCheck,
                                newAndRule.PatternToCheckFor || "",
                                newAndRule.MessageWhenPatternFails,
                                newAndRule.SectionsInHeaderToShowError,
                                newAndRule.Severity
                            ));
                        }
                    }
 
                    this.addRule(new AndValidationRule(
                        newRule.Message,
                        newRule.SectionsInHeaderToShowError,
                        newRule.Severity,
                        rulesToAnd
                    ));
                }
            }
        }
    }
 
    private isSimpleRule(rule: ValidationRule): rule is ISimpleValidationRule {
        return "violatesRule" in rule;
    }
 
    private isComplexRule(rule: ValidationRule): rule is IComplexValidationRule {
        return "violatesComplexRule" in rule;
    }
 
    private isAndRule(rule: ValidationRule): rule is AndValidationRule {
        return "rulesToAndArray" in rule;
    }
 
    /**
     * Flag all the sections that the rule says to, as violating the rule
     */
    private flagRuleInSections(rule: IValidationRule, setOfSections: HeaderSection[][]): void {
        // Each rule has a set of sections that are to be flagged if the rule fails, with the
        // error message from the rule.
 
        // For each section the rule says to flag
        rule.errorReportingSection.forEach((sectionRuleSaysToFlag) => {
            // If this rule has a specific matched section (from an AND rule), only flag that section
            if (rule.matchedSection) {
                addRuleFlagged(rule.matchedSection, rule);
                return;
            }
 
            // Find all occurrences of the section the rule says to flag
            const sectionsToFlag = findSectionSubSection(setOfSections, sectionRuleSaysToFlag);
 
            if (sectionsToFlag.length === 0) {
                // If no sections exist to flag, create a placeholder section
                // This allows the violation to appear in the diagnostic report
                // This is essential for HeaderSectionMissingRule (which checks for absent headers)
                // and also handles edge cases like misconfigured rules or typos in section names
 
                // Add the placeholder to the last section array (typically "Other" headers)
                Eif (setOfSections.length > 0) {
                    const lastSectionArray = setOfSections[setOfSections.length - 1];
                    Eif (lastSectionArray) {
                        // Create a proper OtherRow instance with appropriate number
                        const rowNumber = lastSectionArray.length + 1;
                        // Use a non-empty value so the row appears in new UI (which filters out empty values)
                        const placeholderSection = new OtherRow(rowNumber, sectionRuleSaysToFlag, "(missing)");
 
                        lastSectionArray.push(placeholderSection);
 
                        // Flag the placeholder section
                        addRuleFlagged(placeholderSection, rule);
                    }
                }
            } else {
                // For each of the sections that are to be flagged, associate the rule with the section
                sectionsToFlag.forEach((sectionToFlag) => {
                    addRuleFlagged(sectionToFlag, rule);
                });
            }
        });
 
        // If this is a simple rule with a KEY:VALUE pattern, also flag the broken-out KEY row
        // (e.g., X-Forefront-Antispam-Report with pattern "SFV:SPM" also flags the "SFV" row)
        const simpleRule = rule as ISimpleValidationRule;
        if ("violatesRule" in simpleRule) {
            // Check if pattern matches KEY:VALUE format
            const match = simpleRule.errorPattern.match(/^([A-Z]+):(.+)$/);
 
            if (match && match[1]) {
                const breakoutSectionName = match[1];
 
                // Find the broken-out row section (e.g., "SFV", "IPV", "BCL", etc.)
                const breakoutSections = findSectionSubSection(setOfSections, breakoutSectionName);
 
                // Flag the broken-out section with this same rule
                breakoutSections.forEach((breakoutSection) => {
                    addRuleFlagged(breakoutSection, rule);
                });
            }
        }
    }
}
 
// Create the only instance of the rules list
export const headerValidationRules = new HeaderValidationRulesEngine();
 
/**
 * In the set of sections (array of array of sections) find all of them with particular name
 */
export function findSectionSubSection(setOfSections: HeaderSection[][], subSectionLookingFor: string): HeaderSection[] {
    const results: HeaderSection[] = [];
 
    setOfSections.forEach((section) => {
        section.forEach((subSection) => {
            if (subSection.header === subSectionLookingFor || subSection.headerName === subSectionLookingFor) {
                results.push(subSection);
            }
        });
    });
 
    return results;
}