---
policy: /ce/ca/google/kms/kms-key-rotation
logic: /ce/ca/google/kms/kms-key-rotation/prod.logic.yaml
executionTime: 2025-04-24T23:47:05.238195443Z
rows:
  - id: aC541
    match: true
    status:
      expected: UNDETERMINED
      actual: UNDETERMINED
    conditionIndex:
      expected: 101
      actual: 101
    conditionText:
      expected: CA10__nextRotationTime__c.isEmpty()
      actual: CA10__nextRotationTime__c.isEmpty()
    runtimeError: {}
  - id: aC542
    match: true
    status:
      expected: COMPLIANT
      actual: COMPLIANT
    conditionIndex:
      expected: 199
      actual: 199
    conditionText:
      expected: extract('CA10__nextRotationTime__c').withinNextDays(90) && extract('rotationDuration')
        <= 'P90D'
      actual: extract('CA10__nextRotationTime__c').withinNextDays(90) && extract('rotationDuration')
        <= 'P90D'
    runtimeError: {}
  - id: aC543
    match: true
    status:
      expected: INCOMPLIANT
      actual: INCOMPLIANT
    conditionIndex:
      expected: 200
      actual: 200
    conditionText:
      expected: otherwise
      actual: otherwise
    runtimeError: {}
  - id: aC544
    match: true
    status:
      expected: INCOMPLIANT
      actual: INCOMPLIANT
    conditionIndex:
      expected: 200
      actual: 200
    conditionText:
      expected: otherwise
      actual: otherwise
    runtimeError: {}
usedFiles:
  - path: /ce/ca/google/kms/kms-key-rotation/policy.yaml
    md5Hash: 3B0DBE28DCCE356153E289289202AF97
    content: "---\nnames: \n  full: \"Google KMS Crypto Key is not rotated every 90\
      \ days\"\n  contextual: \"Crypto Key is not rotated every 90 days\"\ndescription:\
      \ \"Google Cloud Key Management Service stores cryptographic keys in a hierarchical\
      \ \\\n structure designed for useful and elegant access control management.\
      \ \\\n The format for the rotation schedule depends on the client library that\
      \ is used. For the \\\n gcloud command-line tool, the next rotation time must\
      \ be in ISO or RFC3339 format, and \\\n the rotation period must be in the form\
      \ INTEGER[UNIT], where units can be one of \\\n seconds (s), minutes (m), hours\
      \ (h) or days (d).\"\ntype: COMPLIANCE_POLICY\ncategories:\n  - \"SECURITY\"\
      \nframeworkMappings:\n  - /frameworks/cis-gcp-v3.0.0/01/10\n  - /frameworks/cloudaware/secret-and-certificate-governance/expiration-management\n\
      similarPolicies:\n  cloudConformity:\n    - url: \"https://www.trendmicro.com/cloudoneconformity-staging/knowledge-base/gcp/CloudKMS/rotate-kms-encryption-keys.html\"\
      \n      name: \"Rotate Google Cloud KMS Keys\"\n "
  - path: /ce/ca/google/kms/kms-key-rotation/prod.logic.yaml
    md5Hash: FDA9B107E5FDA82DA38A41CF89A775A6
    content: |
      ---

      inputType: "CA10__CaGoogleCloudKmsCryptoKey__c"
      testData:
        - file: test-data.json
      importExtracts:
        - file: /types/CA10__CaGoogleCloudKmsCryptoKey__c/object.extracts.yaml
      conditions:
        - status: "COMPLIANT"
          currentStateMessage: "KMS encryption key is rotated within a period of 90 days."
          check:
           AND:
            args:
              - IS_WITHIN_NEXT_DAYS:
                  offsetDays: 90
                  arg:
                    EXTRACT: "CA10__nextRotationTime__c"
              - LESS_THAN_EQUAL:
                  left:
                    EXTRACT: "rotationDuration"
                  right:
                    DURATION: "P90D"
      otherwise:
        status: "INCOMPLIANT"
        currentStateMessage: "KMS encryption key is not rotated within a period of 90 days."
        remediationMessage: "Change KMS encryption key rotation period."
  - path: /ce/ca/google/kms/kms-key-rotation/test-data.json
    md5Hash: 35B353D7F0D4B6EDE9EC7998BA730BA9
    content: |
      [
        {
          "expectedResult": {
            "status": "UNDETERMINED",
            "conditionIndex": "101",
            "conditionText": "CA10__nextRotationTime__c.isEmpty()",
            "runtimeError": null
          },
          "context": { "snapshotTime": "2024-09-19T23:57:56Z" },
          "Id": "aC541",
          "CA10__disappearanceTime__c": null,
          "CA10__nextRotationTime__c": null,
          "CA10__rotationPeriod__c": ""
        },
        {
          "expectedResult": {
            "status": "COMPLIANT",
            "conditionIndex": "199",
            "conditionText": "extract('CA10__nextRotationTime__c').withinNextDays(90) && extract('rotationDuration') <= 'P90D'",
            "runtimeError": null
          },
          "context": { "snapshotTime": "2024-09-19T23:57:56Z" },
          "Id": "aC542",
          "CA10__disappearanceTime__c": null,
          "CA10__nextRotationTime__c": "2024-10-19T23:57:56Z",
          "CA10__rotationPeriod__c": "2592000s"
        },
        {
          "expectedResult": {
            "status": "INCOMPLIANT",
            "conditionIndex": "200",
            "conditionText": "otherwise",
            "runtimeError": null
          },
          "context": { "snapshotTime": "2024-09-19T23:57:56Z" },
          "Id": "aC543",
          "CA10__disappearanceTime__c": null,
          "CA10__nextRotationTime__c": "2022-03-11T04:24:49Z",
          "CA10__rotationPeriod__c": "2592000s"
        },
        {
          "expectedResult": {
            "status": "INCOMPLIANT",
            "conditionIndex": "200",
            "conditionText": "otherwise",
            "runtimeError": null
          },
          "context": { "snapshotTime": "2024-09-19T23:57:56Z" },
          "Id": "aC544",
          "CA10__disappearanceTime__c": null,
          "CA10__nextRotationTime__c": "2024-10-19T23:57:56Z",
          "CA10__rotationPeriod__c": "130600m"
        }
      ]
  - path: /types/CA10__CaGoogleCloudKmsCryptoKey__c/object.extracts.yaml
    md5Hash: FBA6F55EDAD759EA3CCFC1311CEB0AAB
    content: "---\nextracts:\n  - name: \"Name\"\n    value: \n      FIELD:\n    \
      \    path: \"Name\"\n        undeterminedIf:\n          isEmpty: \"Name should\
      \ not be empty\"\n  - name: \"CA10__rotationPeriod__c\"\n    value: \n     \
      \ FIELD:\n        path: \"CA10__rotationPeriod__c\"\n        undeterminedIf:\n\
      \          isEmpty: \"Empty rotation period\"\n  - name: \"rotationDuration\"\
      \n    value:\n      DURATION_FROM:\n        arg:\n          EXTRACT: \"CA10__rotationPeriod__c\"\
      \n        format: GCP\n  - name: \"CA10__nextRotationTime__c\"\n    value: \n\
      \      FIELD:\n        path: \"CA10__nextRotationTime__c\"\n        undeterminedIf:\n\
      \          isEmpty: \"Empty value of next rotation time\"\n\n"
script: |-
  CREATE TEMP FUNCTION mock_ExpectedResult()
  RETURNS ARRAY<STRUCT<
          Id STRING,
          expectedResult STRUCT<status STRING, conditionIndex DECIMAL, conditionText STRING, runtimeError STRING>
      >>
  DETERMINISTIC
  LANGUAGE js
  AS r"""
    return [ {
    "Id" : "aC541",
    "expectedResult" : {
      "status" : "UNDETERMINED",
      "conditionIndex" : "101",
      "conditionText" : "CA10__nextRotationTime__c.isEmpty()",
      "runtimeError" : null
    }
  }, {
    "Id" : "aC542",
    "expectedResult" : {
      "status" : "COMPLIANT",
      "conditionIndex" : "199",
      "conditionText" : "extract('CA10__nextRotationTime__c').withinNextDays(90) && extract('rotationDuration') <= 'P90D'",
      "runtimeError" : null
    }
  }, {
    "Id" : "aC543",
    "expectedResult" : {
      "status" : "INCOMPLIANT",
      "conditionIndex" : "200",
      "conditionText" : "otherwise",
      "runtimeError" : null
    }
  }, {
    "Id" : "aC544",
    "expectedResult" : {
      "status" : "INCOMPLIANT",
      "conditionIndex" : "200",
      "conditionText" : "otherwise",
      "runtimeError" : null
    }
  } ];
  """;

  CREATE TEMP FUNCTION mock_CA10__CaGoogleCloudKmsCryptoKey__c()
  RETURNS ARRAY<STRUCT<
      Id STRING,
      CA10__disappearanceTime__c TIMESTAMP,
      CA10__nextRotationTime__c TIMESTAMP,
      CA10__rotationPeriod__c STRING,
      context STRUCT<
          snapshotTime TIMESTAMP
      >
  >>
  DETERMINISTIC
  LANGUAGE js
  AS r"""
    return [ {
    "context" : {
      "snapshotTime" : new Date("2024-09-19T23:57:56Z")
    },
    "Id" : "aC541",
    "CA10__rotationPeriod__c" : ""
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-09-19T23:57:56Z")
    },
    "Id" : "aC542",
    "CA10__nextRotationTime__c" : new Date("2024-10-19T23:57:56Z"),
    "CA10__rotationPeriod__c" : "2592000s"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-09-19T23:57:56Z")
    },
    "Id" : "aC543",
    "CA10__nextRotationTime__c" : new Date("2022-03-11T04:24:49Z"),
    "CA10__rotationPeriod__c" : "2592000s"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-09-19T23:57:56Z")
    },
    "Id" : "aC544",
    "CA10__nextRotationTime__c" : new Date("2024-10-19T23:57:56Z"),
    "CA10__rotationPeriod__c" : "130600m"
  } ];
  """;

  CREATE TEMP FUNCTION process_CA10__CaGoogleCloudKmsCryptoKey__c(
      obj STRUCT<
          Id STRING,
          CA10__disappearanceTime__c TIMESTAMP,
          CA10__nextRotationTime__c TIMESTAMP,
          CA10__rotationPeriod__c STRING
      >,
      snapshotTime TIMESTAMP
  )
  RETURNS STRUCT<status STRING, conditionIndex DECIMAL, conditionText STRING, currentStateMessage STRING, currentStateReferences STRING, remediation STRING, runtimeError STRING>
  DETERMINISTIC
  LANGUAGE js
  AS r"""
      var IsEmptyLib = new function () {
          this.simpleIsEmpty = function(arg) {
              return arg == null;
          };
          this.simpleIsNotEmpty = function(arg) {
              return arg != null;
          };
      }();
      var today = new Date(snapshotTime.toISOString().substr(0,10)+'T00:00:00.000Z').getTime();
      var todayPlus91Day = new Date(snapshotTime.toISOString().substr(0,10)+'T00:00:00.000Z').getTime() + (91 * 86400000);
      var TextLib = new function () {
          this.normalize = function(arg) {
              return arg == null ? '' : arg.replace(/\s+/g, ' ').trim().toLowerCase();
          };
          this.isEmpty = function(arg) {
              return this.normalize(arg) == '';
          };
          this.isNotEmpty = function(arg) {
              return this.normalize(arg) != '';
          };
          this.equal = function(left, right) {
              return this.normalize(left) == this.normalize(right);
          };
          this.notEqual = function(left, right) {
              return this.normalize(left) != this.normalize(right);
          };
          this.startsWith = function(arg, substring) {
              return this.normalize(arg).startsWith(this.normalize(substring));
          };
          this.endsWith = function(arg, substring) {
              return this.normalize(arg).endsWith(this.normalize(substring));
          };
          this.contains = function(arg, substring) {
              return this.normalize(arg).includes(this.normalize(substring));
          };
      }();
      var DurationLib = new function () {
          var googleFormatRegex = /(?<duration>^\d+)(?<unit>[smhd])/;
          var iso8601DurationRegex = /^P(?:(?<years>\d+)Y)?(?:(?<months>\d+)M)?(?:(?<days>\d+)D)?(?:T(?:(?<hours>\d+)H)?(?:(?<minutes>\d+)M)?(?:(?<seconds>\d+(?:\.\d+)?)S)?)?$/;
          this.parseGoogleFormat = function(arg) {
              var parsed = arg.toLowerCase().match(googleFormatRegex);
              if (parsed == null || parsed.groups == null || parsed.groups.duration == null || parsed.groups.unit == null) {
                  throw new Error("Invalid duration value: " + arg + ". Must match: \d+[smhd]");
              } else {
                  var durationValue = parseFloat(parsed.groups.duration);
                  var multiplier;
                  switch (parsed.groups.unit) {
                      case ('s'):
                          multiplier = 1;
                          break;
                      case ('m'):
                          multiplier = 60;
                          break;
                      case ('h'):
                          multiplier = 60*60;
                          break;
                      case ('d'):
                          multiplier = 60*60*24;
                          break;
                  }
                  return durationValue*multiplier;
              }
          };
          this.checkGoogleFormat = function(arg) {
              return arg != null && googleFormatRegex.test(arg);
          };
          this.parseIso8601Format = function(arg) {
              var parsed = arg.match(iso8601DurationRegex);
              if (parsed == null || parsed.groups == null) {
                  throw new Error("Invalid duration value: " + arg + ". Must match ISO 8601 duration format.");
              } else {
                  var out = 0;
                  if (parsed.groups.years) {
                      // simpliest way for normalizing - it's calculate month as 30 days in year and months convertings, otherwise P1Y != P12M
                      out += parseFloat(parsed.groups.years) * 60*60*24*30*12;
                  }
                  if (parsed.groups.months) {
                      out += parseFloat(parsed.groups.months) * 60*60*24*30;
                  }
                  if (parsed.groups.days) {
                      out += parseFloat(parsed.groups.days) * 60*60*24;
                  }
                  if (parsed.groups.hours) {
                      out += parseFloat(parsed.groups.hours) * 60*60;
                  }
                  if (parsed.groups.minutes) {
                      out += parseFloat(parsed.groups.minutes) * 60;
                  }
                  if (parsed.groups.seconds) {
                      out += parseFloat(parsed.groups.seconds);
                  }
                  return out;
              }
          }
          this.checkIso8601Format = function(arg) {
              return arg != null && iso8601DurationRegex.test(arg);
          };
          this.isEmpty = function(arg) {
              return arg == null || arg.trim() == '';
          };
      }();
      var references1 = [];
      // condition[0], conditionIndex:[0..99]
      references1.push('Deleted From Google [CA10__disappearanceTime__c]: ' + obj.CA10__disappearanceTime__c);
      if (obj.CA10__disappearanceTime__c != null) {
          return {status: 'DISAPPEARED', conditionIndex: 99, conditionText: "isDisappeared(CA10__disappearanceTime__c)", currentStateMessage: "Object is deleted in the source", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null};
      }
      // condition[1], conditionIndex:[100..199]
      function fieldChecked4() {
          if (IsEmptyLib.simpleIsEmpty(obj.CA10__nextRotationTime__c)) {
              throw new Error("UNDETERMINED condition:101", {cause: {status: 'UNDETERMINED', conditionIndex: 101, conditionText: "CA10__nextRotationTime__c.isEmpty()", currentStateMessage: "Empty value of next rotation time", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return obj.CA10__nextRotationTime__c;
      }
      function extract3() { if (!this.out) { this.out = fieldChecked4(); } return this.out; };
      function comparison6() {
          var comparisonRight15 = DurationLib.parseIso8601Format('P90D');
          return extract8.call(extract8) != null && comparisonRight15 != null && extract8.call(extract8) <= comparisonRight15;
      }
      function durationChecked9() {
          var durationFrom10 = extract12.call(extract12);
          return DurationLib.parseGoogleFormat(durationFrom10);
      }
      function fieldChecked13() {
          if (TextLib.isEmpty(obj.CA10__rotationPeriod__c)) {
              throw new Error("UNDETERMINED condition:102", {cause: {status: 'UNDETERMINED', conditionIndex: 102, conditionText: "CA10__rotationPeriod__c.isEmpty()", currentStateMessage: "Empty rotation period", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return obj.CA10__rotationPeriod__c;
      }
      function extract12() { if (!this.out) { this.out = fieldChecked13(); } return this.out; };
      function extract8() { if (!this.out) { this.out = durationChecked9(); } return this.out; };
      references1.push('Next Rotation Time [obj.CA10__nextRotationTime__c]: ' + obj.CA10__nextRotationTime__c);
      references1.push('Rotation Period [obj.CA10__rotationPeriod__c]: ' + obj.CA10__rotationPeriod__c);
      try {
          if ((extract3.call(extract3) != null && extract3.call(extract3).getTime() >= today && extract3.call(extract3).getTime() < todayPlus91Day) && comparison6()) {
              return {status: 'COMPLIANT', conditionIndex: 199, conditionText: "extract('CA10__nextRotationTime__c').withinNextDays(90) && extract('rotationDuration') <= 'P90D'", currentStateMessage: "KMS encryption key is rotated within a period of 90 days.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null};
          }
      } catch (err) {
          if (err.cause && err.cause.status) { return err.cause; } else { throw err; }
      }
      return {status: 'INCOMPLIANT', conditionIndex: 200, conditionText: "otherwise", currentStateMessage: "KMS encryption key is not rotated within a period of 90 days.", currentStateReferences: references1.join('\n'), remediation: "Change KMS encryption key rotation period.", runtimeError: null};
  """;


  SELECT
    expectedResult.Id as Id,
    IF (
      IFNULL(expectedResult.expectedResult.status, '') = IFNULL(sObject.result.status, '')
      AND IFNULL(expectedResult.expectedResult.conditionIndex, -1) = IFNULL(sObject.result.conditionIndex, -1)
      AND IFNULL(expectedResult.expectedResult.conditionText, '') = IFNULL(sObject.result.conditionText, '')
      AND IFNULL(expectedResult.expectedResult.runtimeError, '') = IFNULL(sObject.result.runtimeError, ''),
      "MATCH",
      "FAIL"
    ) as match,
    expectedResult.expectedResult.status as expectedStatus, sObject.result.status as actualStatus,
    expectedResult.expectedResult.conditionIndex as expectedConditionIndex, sObject.result.conditionIndex as actualConditionIndex,
    expectedResult.expectedResult.conditionText as expectedConditionText, sObject.result.conditionText as actualConditionText,
    expectedResult.expectedResult.runtimeError as expectedRuntimeError, sObject.result.runtimeError as actualRuntimeError
  FROM UNNEST(mock_ExpectedResult()) expectedResult
  LEFT JOIN (
      SELECT
          sObject.Id AS Id,
          sObject.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
          sObject.CA10__nextRotationTime__c AS CA10__nextRotationTime__c,
          sObject.CA10__rotationPeriod__c AS CA10__rotationPeriod__c,
          process_CA10__CaGoogleCloudKmsCryptoKey__c(
              STRUCT(
                  sObject.Id AS Id,
                  sObject.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
                  sObject.CA10__nextRotationTime__c AS CA10__nextRotationTime__c,
                  sObject.CA10__rotationPeriod__c AS CA10__rotationPeriod__c
              ),
              sObject.context.snapshotTime
          ) as result
      FROM UNNEST(mock_CA10__CaGoogleCloudKmsCryptoKey__c()) AS sObject
  ) sObject ON sObject.Id = expectedResult.Id;
