All files / src check.ts

100% Statements 270/270
76.92% Branches 20/26
100% Functions 4/4
100% Lines 270/270

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 2721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 19x 19x 17x 19x 2x 2x 26x 7x 7x 7x 7x 7x 7x 7x 7x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 26x 23x 23x 44x 44x 21x 44x 23x 23x 23x 23x 26x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 9x 9x 9x 9x 9x 7x 7x 7x 7x 1x 7x 7x 7x 7x 7x 1x    
import * as path from 'path';
import {
  PolicyViolationBeta1,
  PolicyViolatingResourceBeta1,
} from 'aws-cdk-lib';
 
/**
 * Messages for a given rule
 */
interface RuleMessages {
  /**
   * A custom message that can be returned by a rule.
   * This would be a message that is defined within a
   * rule by the rule author and is usually user friendly,
   * but arbitrarily formatted.
   *
   * @default - undefined (no custom message)
   */
  readonly custom_message?: string;
 
  /**
   * A guard generated message. This will always
   * be available, but is generally not a user friendly
   * message
   */
  readonly error_message: string;
}
 
/**
 * This is how far the check was able to traverse to.
 */
interface Traversed {
  /**
   * The JSON path that the rule was able to traverse
   * to. For example, `/Resources/MyCustomResource`
   */
  readonly path: string;
 
  /**
   * The value at the traversed to path
   */
  readonly value: any;
}
 
/**
 * The result of running cfn-guard after we parse
 * the results into a well defined schema
 */
export interface GuardResult {
  /**
   * TODO: figure out what this is
   * it's always an empty string
   */
  readonly name?: string;
 
  /**
   * The overall status of the rule, pass or fail
   */
  readonly status: 'PASS' | 'FAIL';
 
  /**
   * A list of rule results for rules that are not compliant
   *
   * @default - will be empty if there are no non-compliant rules
   */
  readonly not_compliant?: NonCompliantRule[];
 
  /**
   * A list of rules that were run, but were not applicable to the
   * template. For example, if the template did not contain any SNS Topics
   * then any rules that applied to SNS topics would appear in this list
   *
   * @default - will be empty if all rules were applicable
   */
  readonly not_applicable?: string[];
 
  /**
   * A list of rules that were applicable to the template and
   * passed validation.
   *
   * @default - will be empty if no rules are compliant
   */
  readonly compliant?: string[];
 
}
 
interface NonCompliantRule {
  /**
   * The name of the Guard rule
   */
  readonly name: string;
 
  /**
   * TODO: this is always empty, how do rules populate this?
   *
   * @default - no rule messages
   */
  readonly messages?: RuleMessages;
 
  /**
   * List of checks that were run as part of the rule
   * and their associated result
   */
  readonly checks: NonCompliantRuleCheck[];
}
 
interface NonCompliantRuleCheck {
  /**
   * Whether or not this is a check that was able
   * to resolve all properties
   */
  readonly resolved: boolean;
 
  /**
   * Information on the properties that failed the check
   * This can be slightly different depending on  whether the
   * check was resolved or not.
   */
  readonly traversed: {
    /**
     * When the check is resolved this has information
     * on the _expected_ value of the property that was checked.
     *
     * When the check is unresolved this has information on
     * The last property it was able to resolve.
     */
    to: Traversed;
 
    /**
     * When the check is unresolved this will be undefined.
     *
     * When the check is resolved this will contain information
     * on the _actual_ value of the property that was checked.
     */
    from?: Traversed;
  };
 
  /**
   * Messages for a given rule
   */
  readonly messages?: RuleMessages;
}
 
type violationResourceMap = {
  resource: Map<string, Pick<PolicyViolatingResourceBeta1, 'locations'>>;
  violation: Pick<PolicyViolationBeta1, 'description' | 'fix'>;
};
 
export class ViolationCheck {
  private readonly violatingResources = new Map<string, violationResourceMap>();
  private readonly violation: { fix?: string; description?: string } = {};
  constructor(
    private readonly ruleCheck: NonCompliantRule,
    private readonly templatePath: string,
    private readonly rulePath: string,
  ) { }
 
  /**
   * A single guard rule can contain multiple "checks" that are run against a resource
   * or against multiple resources. So for example you might get something like:
   * {
   *   name: 's3-public-buckets-prohibited',
   *   messages: {
   *     custom_message: 'Buckets should not be public',
   *   },
   *   checks: [
   *     {
   *       traversed: {
   *         to: {
   *           path: '/Resources/MyCustomL3ConstructBucket8C61BCA7/Properties/PublicAccessBlockConfiguration/BlockPublicPolicy'
   *         }
   *       }
   *     },
   *     {
   *       traversed: {
   *         to: {
   *           path: '/Resources/MyCustomL3ConstructBucket8C61BCA7/Properties/PublicAccessBlockConfiguration/BlockPublicAcls'
   *         }
   *       }
   *     }
   *   ]
   * }
   *
   * We want to display this to the user as a single violation since there is a single
   * custom_message. This method sets up some inheritance and constructs a single violation per
   * resource+message.
   */
  private setViolatingResources(check: NonCompliantRuleCheck): void {
    // pull the description from the custom message or from the error message if available
    this.violation.description = this.violation.description || check.messages?.custom_message || check.messages?.error_message;
    // The fix will only appear in a custom_message because it would be a user
    // generated message
    this.violation.fix = this.violation.fix ?? check.messages?.custom_message ?? 'N/A';
    const location = check.traversed.to.path;
    const resourceName = location.split('/')[2];
    const violatingResource = this.violatingResources.get(this.violation.fix);
    const result = {
      locations: [location],
    };
    if (violatingResource) {
      const resource = violatingResource.resource.get(resourceName);
      if (resource) {
        resource.locations.push(location);
      } else {
        violatingResource.resource.set(resourceName, result);
      }
    } else {
      this.violatingResources.set(this.violation.fix, {
        resource: new Map([[resourceName, result]]),
        violation: {
          description: this.violation.description ?? '',
          fix: this.violation.fix,
        },
      });
    }
  }
 
  /**
   * Process a Guard result check and return a plugin violation
   * We are establishing a bit of a convention with the messages where we expect
   * the custom_message field to contain a string formatted like this
   * (based on the Control Tower rules)
   *
   *     [FIX]: Do something...
   *     [XXX]: description of the rule
   *
   * If it does contain a structure like that then we try and parse out the
   * fix and description fields, otherwise we just take the custom_message as
   * is and use it for both.
   */
  public processCheck(): PolicyViolationBeta1[] {
    this.ruleCheck.checks.forEach(check => {
      if (check.messages?.custom_message) {
        const message = check.messages.custom_message.split('\n').filter(m => m.trim() !== '');
        message.forEach(m => {
          const mes = m.trim();
          if (mes.startsWith('[FIX]')) {
            this.violation.fix = mes;
          } else {
            this.violation.description = mes;
          }
        });
      }
      this.setViolatingResources(check);
    });
    return Array.from(this.violatingResources.values()).map(violation => {
      return {
        description: violation.violation.description,
        fix: violation.violation.fix,
        ruleMetadata: {
          DocumentationUrl: this.generateRuleDocUrl(),
        },
        ruleName: this.ruleCheck.name,
        violatingResources: Array.from(violation.resource.entries()).map(([key, value]) => {
          return {
            locations: value.locations,
            resourceLogicalId: key,
            templatePath: this.templatePath,
          };
        }),
      };
    });
  }
  private generateRuleDocUrl(): string {
    const serviceName = path.basename(path.dirname(this.rulePath));
    const ruleName = path.basename(this.rulePath, '.guard');
    const root = 'https://docs.aws.amazon.com/controltower/latest/userguide';
    return `${root}/${serviceName}-rules.html#${ruleName}-description`;
  }
}