---
policy: /ce/ca/azure/monitor/diagnostic-logs-export-to-storage-without-cmk
logic: /ce/ca/azure/monitor/diagnostic-logs-export-to-storage-without-cmk/prod.logic.yaml
executionTime: 2025-05-10T12:02:51.832561477Z
rows:
  - id: test1
    match: true
    status:
      expected: DISAPPEARED
      actual: DISAPPEARED
    conditionIndex:
      expected: 99
      actual: 99
    conditionText:
      expected: isDisappeared(CA10__disappearanceTime__c)
      actual: isDisappeared(CA10__disappearanceTime__c)
    runtimeError: {}
  - id: test2
    match: true
    status:
      expected: INAPPLICABLE
      actual: INAPPLICABLE
    conditionIndex:
      expected: 199
      actual: 199
    conditionText:
      expected: "not(['caDiagnosticSettingOnAzureSubscription'].contains(RecordType.DeveloperName))"
      actual: "not(['caDiagnosticSettingOnAzureSubscription'].contains(RecordType.DeveloperName))"
    runtimeError: {}
  - id: test3
    match: true
    status:
      expected: INAPPLICABLE
      actual: INAPPLICABLE
    conditionIndex:
      expected: 299
      actual: 299
    conditionText:
      expected: isEmptyLookup('CA10__storageAccount__r')
      actual: isEmptyLookup('CA10__storageAccount__r')
    runtimeError: {}
  - id: test4
    match: true
    status:
      expected: INCOMPLIANT
      actual: INCOMPLIANT
    conditionIndex:
      expected: 399
      actual: 399
    conditionText:
      expected: extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') !=
        'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isEmpty()
      actual: extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') != 'Microsoft.Keyvault'
        && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isEmpty()
    runtimeError: {}
  - id: test5
    match: true
    status:
      expected: COMPLIANT
      actual: COMPLIANT
    conditionIndex:
      expected: 499
      actual: 499
    conditionText:
      expected: extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') ==
        'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isNotEmpty()
      actual: extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') == 'Microsoft.Keyvault'
        && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isNotEmpty()
    runtimeError: {}
usedFiles:
  - path: /ce/ca/azure/monitor/diagnostic-logs-export-to-storage-without-cmk/policy.yaml
    md5Hash: 0D4AD0E1D0D32FDC788ED3DCCEE3D3B6
    content: |
      ---
      names:
        full: Azure Diagnostic Setting Logs export to Storage Account not encrypted with
          Customer-managed key
        contextual: Diagnostic Setting Logs export to Storage Account not encrypted with
          Customer-managed key
      description: Storage accounts with the activity log exports can be configured to use
        Customer Managed Keys (CMK).
      type: COMPLIANCE_POLICY
      categories:
        - SECURITY
      frameworkMappings:
        - "/frameworks/cis-azure-v2.1.0/05/01/03"
        - "/frameworks/cis-azure-v3.0.0/06/01/03"
        - "/frameworks/cloudaware/logging-and-monitoring/logging-and-monitoring-configuration"
        - "/frameworks/cloudaware/resource-security/data-encryption"
      similarPolicies:
        internal:
          - dec-x-5c3c2067
  - path: /ce/ca/azure/monitor/diagnostic-logs-export-to-storage-without-cmk/prod.logic.yaml
    md5Hash: D461FCC9CD93E9A89185440B1FE20593
    content: |-
      inputType: "CA10__CaAzureDiagnosticSetting__c"
      recordTypes:
        - "caDiagnosticSettingOnAzureSubscription"
      importExtracts:
        - file: "/types/CA10__CaAzureStorageAccount__c/object.extracts.yaml"
      testData:
        - file: "test-data.json"
      conditions:
        - status: "INAPPLICABLE"
          currentStateMessage: "This Diagnostic Setting logs are not sent to a Storage account."
          check:
            IS_EMPTY_LOOKUP: "CA10__storageAccount__r"
        - status: "INCOMPLIANT"
          currentStateMessage: "This Diagnostic Setting logs are sent to a Storage account not encrypted with a Customer-managed Key."
          remediationMessage: "Consider encrypting the destination Storage account with a Customer-managed encryption Key."
          check:
            AND:
              args:
                - NOT_EQUAL:
                    left:
                      EXTRACT: "CA10__storageAccount__r.CA10__encryptionKeySource__c"
                    right:
                      TEXT: "Microsoft.Keyvault"
                - IS_EMPTY:
                    arg:
                      EXTRACT: "CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c"
        - status: "COMPLIANT"
          currentStateMessage: "This Diagnostic Setting logs are sent to a Storage account encrypted with Customer-managed Key."
          check:
            AND:
              args:
                - IS_EQUAL:
                    left:
                      EXTRACT: "CA10__storageAccount__r.CA10__encryptionKeySource__c"
                    right:
                      TEXT: "Microsoft.Keyvault"
                - NOT_EMPTY:
                    arg:
                      EXTRACT: "CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c"
      otherwise:
        status: "UNDETERMINED"
        currentStateMessage: "Unexpected values in the fields."
  - path: /types/CA10__CaAzureStorageAccount__c/object.extracts.yaml
    md5Hash: 2E0979CA85C35CDB555F32B262F6942F
    content: "---\nextracts:\n# This is a checkbox. Not nullable. Can't have no access,\
      \ retrieved via Microsoft.Storage/storageAccounts\n  - name: \"CA10__secureTransferRequired__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__secureTransferRequired__c\"\
      \n# Values: Enabled, Disabled. Not Nullable. Can't have no access, retrieved\
      \ via Microsoft.Storage/storageAccounts\n  - name: \"CA10__requireInfrastructureEncryptionState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__requireInfrastructureEncryptionState__c\"\
      \n        undeterminedIf:\n          isEmpty: \"Corrupted data. Require Infrastructure\
      \ Encryption setting cannot be empty.\"\n# Values: Enabled, Disabled. Not Nullable.\
      \ Can't have no access, retrieved via Microsoft.Storage/storageAccounts\n  -\
      \ name: \"CA10__publicNetworkAccessState__c\"\n    value: \n      FIELD:\n \
      \       path: \"CA10__publicNetworkAccessState__c\"\n        undeterminedIf:\n\
      \          isEmpty: \"Corrupted data. Public Network Access cannot be empty.\"\
      \n# Values: Allow, Deny. Not nullable. Can't have no access, retrieved via Microsoft.Storage/storageAccounts.\n\
      \  - name: \"CA10__networkAclsDefaultAction__c\"\n    value: \n      FIELD:\n\
      \        path: \"CA10__networkAclsDefaultAction__c\"\n        undeterminedIf:\n\
      \          isEmpty: \"Corrupted data. Default Network Action cannot be empty.\"\
      \n# Values: any combination of Logging|Metrics|AzureServices or None. Not nullable.\
      \ \n# Can't have no access, retrieved via Microsoft.Storage/storageAccounts.\n\
      \  - name: \"CA10__networkAclsBypass__c\"\n    value: \n      FIELD:\n     \
      \   path: \"CA10__networkAclsBypass__c\"\n        undeterminedIf:\n        \
      \  isEmpty: \"Corrupted data. Network Bypass cannot be empty.\"\n# Values TLS1_0,\
      \ TLS1_1, TLS1_2. Not nullable. Can't have no access, retrieved via Microsoft.Storage/storageAccounts.\n\
      \  - name: \"CA10__minimumTlsVersion__c\"\n    value: \n      FIELD:\n     \
      \   path: \"CA10__minimumTlsVersion__c\"\n        undeterminedIf:\n        \
      \  isEmpty: \"Corrupted data. TLS Version cannot be empty.\"\n# Values: Allow,\
      \ Deny, null (Old storage accounts can have null, which means that the account\
      \ can still have replication). \n# Nullable. Can't have no access, retrieved\
      \ via Microsoft.Storage/storageAccounts.\n  - name: \"CA10__crossTenantReplication__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__crossTenantReplication__c\"\
      \n# Values: Allow, Deny. Not nullable. Can't have no access, retrieved via Microsoft.Storage/storageAccounts.\n\
      \  - name: \"CA10__blobPublicAccess__c\"\n    value: \n      FIELD:\n      \
      \  path: \"CA10__blobPublicAccess__c\"\n        undeterminedIf:\n          isEmpty:\
      \ \"Corrupted data. Allow Blob Anonymous Access cannot be empty.\"\n# Values\
      \ Enabled, Disabled. Not Nullable\n  - name: \"CA10__blobLoggingReadState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__blobLoggingReadState__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__blobLoggingReadState__c\"\n            currentStateMessage: \"Unable to\
      \ determine Blob Container Logging Read property. Possible permission issue\
      \ with Microsoft.Storage/storageAccounts/blobServices/containers/read\"\n  \
      \        isEmpty: \"Storage Blob Logging is not populated yet.\"\n# Values Enabled,\
      \ Disabled. Not Nullable\n  - name: \"CA10__blobLoggingWriteState__c\"\n   \
      \ value: \n      FIELD:\n        path: \"CA10__blobLoggingWriteState__c\"\n\
      \        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__blobLoggingWriteState__c\"\n            currentStateMessage: \"Unable\
      \ to determine Blob Container Logging Write property. Possible permission issue\
      \ with Microsoft.Storage/storageAccounts/blobServices/containers/read\"\n  \
      \        isEmpty: \"Storage Blob Logging is not populated yet.\"\n # Values\
      \ Enabled, Disabled. Not Nullable\n  - name: \"CA10__blobLoggingDeleteState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__blobLoggingDeleteState__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__blobLoggingDeleteState__c\"\n            currentStateMessage: \"Unable\
      \ to determine Blob Container Logging Delete property. Possible permission issue\
      \ with Microsoft.Storage/storageAccounts/blobServices/containers/read\"\n  \
      \        isEmpty: \"Storage Blob Logging is not populated yet.\"\n# Values Enabled,\
      \ Disabled. Not Nullable\n  - name: \"CA10__queueLoggingReadState__c\"\n   \
      \ value: \n      FIELD:\n        path: \"CA10__queueLoggingReadState__c\"\n\
      \        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__queueLoggingReadState__c\"\n            currentStateMessage: \"Unable\
      \ to determine Queue Logging Read property. Possible permission issue with Microsoft.Storage/storageAccounts/queueServices/queues/read\"\
      \n          isEmpty: \"Storage Queue Logging is not populated yet.\"\n# Values\
      \ Enabled, Disabled. Not Nullable\n  - name: \"CA10__queueLoggingWriteState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__queueLoggingWriteState__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__queueLoggingWriteState__c\"\n            currentStateMessage: \"Unable\
      \ to determine Queue Logging Write property. Possible permission issue with\
      \ Microsoft.Storage/storageAccounts/queueServices/queues/read\"\n          isEmpty:\
      \ \"Storage Queue Logging is not populated yet.\"\n# Values Enabled, Disabled.\
      \ Not Nullable\n  - name: \"CA10__queueLoggingDeleteState__c\"\n    value: \n\
      \      FIELD:\n        path: \"CA10__queueLoggingDeleteState__c\"\n        undeterminedIf:\n\
      \          noAccessDelegate:\n            path: \"CA10__queueLoggingDeleteState__c\"\
      \n            currentStateMessage: \"Unable to determine Queue Logging Delete\
      \ property. Possible permission issue with Microsoft.Storage/storageAccounts/queueServices/queues/read\"\
      \n          isEmpty: \"Storage Queue Logging is not populated yet.\"\n# Values\
      \ Enabled, Disabled. Not Nullable\n  - name: \"CA10__tableLoggingReadState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__tableLoggingReadState__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__tableLoggingReadState__c\"\n            currentStateMessage: \"Unable\
      \ to determine Table Logging Read property. Possible permission issue with Microsoft.Storage/storageAccounts/tableServices/tables/read\"\
      \n          isEmpty: \"Storage Table Logging is not populated yet.\"\n# Values\
      \ Enabled, Disabled. Not Nullable\n  - name: \"CA10__tableLoggingWriteState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__tableLoggingWriteState__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__tableLoggingWriteState__c\"\n            currentStateMessage: \"Unable\
      \ to determine Table Logging Write property. Possible permission issue with\
      \ Microsoft.Storage/storageAccounts/tableServices/tables/read\"\n          isEmpty:\
      \ \"Storage Table Logging is not populated yet.\"\n# Values Enabled, Disabled.\
      \ Not Nullable\n  - name: \"CA10__tableLoggingDeleteState__c\"\n    value: \n\
      \      FIELD:\n        path: \"CA10__tableLoggingDeleteState__c\"\n        undeterminedIf:\n\
      \          noAccessDelegate:\n            path: \"CA10__tableLoggingDeleteState__c\"\
      \n            currentStateMessage: \"Unable to determine Table Logging Delete\
      \ property. Possible permission issue with Microsoft.Storage/storageAccounts/tableServices/tables/read\"\
      \n          isEmpty: \"Storage Table Logging is not populated yet.\"\n# Values\
      \ Microsoft.Storage, Microsoft.Keyvault. Not Nullable. Can't have no access,\
      \ retrieved via Microsoft.Storage/storageAccounts\n  - name: \"CA10__encryptionKeySource__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__encryptionKeySource__c\"\n\
      \        undeterminedIf:\n          isEmpty: \"Corrupted data. Encryption Key\
      \ Source cannot be empty.\"\n# Nullable. Can't have no access, retrieved via\
      \ Microsoft.Storage/storageAccounts\n  - name: \"CA10__encryptionKeyVaultUri__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__encryptionKeyVaultUri__c\"\
      \n# Nullable. \n  - name: \"CA10__blobRetentionPolicyDays__c\"\n    value: \n\
      \      FIELD:\n        path: \"CA10__blobRetentionPolicyDays__c\"\n# Values:\
      \ Enabled, Disabled. Nullable. \n  - name: \"CA10__blobRetentionPolicyState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__blobRetentionPolicyState__c\"\
      \n# Nullable. \n  - name: \"CA10__containerRetentionPolicyDays__c\"\n    value:\
      \ \n      FIELD:\n        path: \"CA10__containerRetentionPolicyDays__c\"\n\
      # Values: Enabled, Disabled. Nullable. \n  - name: \"CA10__containerRetentionPolicyState__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__containerRetentionPolicyState__c\"\
      \n# Nullable. Text field.\n  - name: \"CA10__skuName__c\"\n    value:\n    \
      \  FIELD:\n        path: \"CA10__skuName__c\"\n"
  - path: /ce/ca/azure/monitor/diagnostic-logs-export-to-storage-without-cmk/test-data.json
    md5Hash: 100915FC016D3402D90705864D051AF6
    content: |-
      [
          {
              "expectedResult": {
                  "status": "DISAPPEARED",
                  "conditionIndex": "99",
                  "conditionText": "isDisappeared(CA10__disappearanceTime__c)",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-11-12T04:22:47Z"
              },
              "Id": "test1",
              "RecordTypeId": "RecordTypeId2",
              "CA10__disappearanceTime__c": "2024-11-12T04:22:47Z",
              "CA10__storageAccount__c": "",
              "CA10__storageAccountId__c": "",
              "RecordType": {
                  "DeveloperName": "caDiagnosticSettingOnAzureResource",
                  "Id": "RecordTypeId2"
              },
              "CA10__storageAccount__r": {
                  "Id": null,
                  "CA10__disappearanceTime__c": null,
                  "CA10__encryptionKeySource__c": null,
                  "CA10__encryptionKeyVaultUri__c": null
              }
          },
          {
              "expectedResult": {
                  "status": "INAPPLICABLE",
                  "conditionIndex": "199",
                  "conditionText": "not(['caDiagnosticSettingOnAzureSubscription'].contains(RecordType.DeveloperName))",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-11-12T04:22:47Z"
              },
              "Id": "test2",
              "RecordTypeId": "RecordTypeId2",
              "CA10__disappearanceTime__c": null,
              "CA10__storageAccount__c": "",
              "CA10__storageAccountId__c": "",
              "RecordType": {
                  "DeveloperName": "caDiagnosticSettingOnAzureResource",
                  "Id": "RecordTypeId2"
              },
              "CA10__storageAccount__r": {
                  "Id": null,
                  "CA10__disappearanceTime__c": null,
                  "CA10__encryptionKeySource__c": null,
                  "CA10__encryptionKeyVaultUri__c": null
              }
          },
          {
              "expectedResult": {
                  "status": "INAPPLICABLE",
                  "conditionIndex": "299",
                  "conditionText": "isEmptyLookup('CA10__storageAccount__r')",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-11-12T04:22:47Z"
              },
              "Id": "test3",
              "RecordTypeId": "RecordTypeId",
              "CA10__disappearanceTime__c": null,
              "CA10__storageAccount__c": "",
              "CA10__storageAccountId__c": "",
              "RecordType": {
                  "DeveloperName": "caDiagnosticSettingOnAzureSubscription",
                  "Id": "RecordTypeId"
              },
              "CA10__storageAccount__r": {
                  "Id": null,
                  "CA10__disappearanceTime__c": null,
                  "CA10__encryptionKeySource__c": null,
                  "CA10__encryptionKeyVaultUri__c": null
              }
          },
          {
              "expectedResult": {
                  "status": "INCOMPLIANT",
                  "conditionIndex": "399",
                  "conditionText": "extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') != 'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isEmpty()",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-11-12T04:22:47Z"
              },
              "Id": "test4",
              "RecordTypeId": "RecordTypeId",
              "CA10__disappearanceTime__c": null,
              "CA10__storageAccount__c": "storageAccount4",
              "CA10__storageAccountId__c": "storageAccountId4",
              "RecordType": {
                  "DeveloperName": "caDiagnosticSettingOnAzureSubscription",
                  "Id": "RecordTypeId"
              },
              "CA10__storageAccount__r": {
                  "Id": "storageAccount4",
                  "CA10__disappearanceTime__c": null,
                  "CA10__encryptionKeySource__c": "Microsoft.Storage",
                  "CA10__encryptionKeyVaultUri__c": ""
              }
          },
          {
              "expectedResult": {
                  "status": "COMPLIANT",
                  "conditionIndex": "499",
                  "conditionText": "extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') == 'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isNotEmpty()",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-11-12T04:22:47Z"
              },
              "Id": "test5",
              "RecordTypeId": "RecordTypeId",
              "CA10__disappearanceTime__c": null,
              "CA10__storageAccount__c": "storageAccount5",
              "CA10__storageAccountId__c": "storageAccountId5",
              "RecordType": {
                  "DeveloperName": "caDiagnosticSettingOnAzureSubscription",
                  "Id": "RecordTypeId"
              },
              "CA10__storageAccount__r": {
                  "Id": "storageAccount5",
                  "CA10__disappearanceTime__c": null,
                  "CA10__encryptionKeySource__c": "Microsoft.Keyvault",
                  "CA10__encryptionKeyVaultUri__c": "https://example.vault.azure.net/"
              }
          }
      ]
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" : "test1",
    "expectedResult" : {
      "status" : "DISAPPEARED",
      "conditionIndex" : "99",
      "conditionText" : "isDisappeared(CA10__disappearanceTime__c)",
      "runtimeError" : null
    }
  }, {
    "Id" : "test2",
    "expectedResult" : {
      "status" : "INAPPLICABLE",
      "conditionIndex" : "199",
      "conditionText" : "not(['caDiagnosticSettingOnAzureSubscription'].contains(RecordType.DeveloperName))",
      "runtimeError" : null
    }
  }, {
    "Id" : "test3",
    "expectedResult" : {
      "status" : "INAPPLICABLE",
      "conditionIndex" : "299",
      "conditionText" : "isEmptyLookup('CA10__storageAccount__r')",
      "runtimeError" : null
    }
  }, {
    "Id" : "test4",
    "expectedResult" : {
      "status" : "INCOMPLIANT",
      "conditionIndex" : "399",
      "conditionText" : "extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') != 'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isEmpty()",
      "runtimeError" : null
    }
  }, {
    "Id" : "test5",
    "expectedResult" : {
      "status" : "COMPLIANT",
      "conditionIndex" : "499",
      "conditionText" : "extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') == 'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isNotEmpty()",
      "runtimeError" : null
    }
  } ];
  """;

  CREATE TEMP FUNCTION mock_CA10__CaAzureDiagnosticSetting__c()
  RETURNS ARRAY<STRUCT<
      Id STRING,
      RecordTypeId STRING,
      CA10__disappearanceTime__c TIMESTAMP,
      CA10__storageAccount__c STRING,
      CA10__storageAccountId__c STRING,
      context STRUCT<
          snapshotTime TIMESTAMP
      >
  >>
  DETERMINISTIC
  LANGUAGE js
  AS r"""
    return [ {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : "test1",
    "RecordTypeId" : "RecordTypeId2",
    "CA10__disappearanceTime__c" : new Date("2024-11-12T04:22:47Z"),
    "CA10__storageAccount__c" : "",
    "CA10__storageAccountId__c" : ""
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : "test2",
    "RecordTypeId" : "RecordTypeId2",
    "CA10__storageAccount__c" : "",
    "CA10__storageAccountId__c" : ""
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : "test3",
    "RecordTypeId" : "RecordTypeId",
    "CA10__storageAccount__c" : "",
    "CA10__storageAccountId__c" : ""
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : "test4",
    "RecordTypeId" : "RecordTypeId",
    "CA10__storageAccount__c" : "storageAccount4",
    "CA10__storageAccountId__c" : "storageAccountId4"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : "test5",
    "RecordTypeId" : "RecordTypeId",
    "CA10__storageAccount__c" : "storageAccount5",
    "CA10__storageAccountId__c" : "storageAccountId5"
  } ];
  """;

  CREATE TEMP FUNCTION mock_RecordType()
  RETURNS ARRAY<STRUCT<
      DeveloperName STRING,
      Id STRING,
      context STRUCT<
          snapshotTime TIMESTAMP
      >
  >>
  DETERMINISTIC
  LANGUAGE js
  AS r"""
    return [ {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "DeveloperName" : "caDiagnosticSettingOnAzureResource",
    "Id" : "RecordTypeId2"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "DeveloperName" : "caDiagnosticSettingOnAzureSubscription",
    "Id" : "RecordTypeId"
  } ];
  """;

  CREATE TEMP FUNCTION mock_CA10__CaAzureStorageAccount__c()
  RETURNS ARRAY<STRUCT<
      Id STRING,
      CA10__disappearanceTime__c TIMESTAMP,
      CA10__encryptionKeySource__c STRING,
      CA10__encryptionKeyVaultUri__c STRING,
      context STRUCT<
          snapshotTime TIMESTAMP
      >
  >>
  DETERMINISTIC
  LANGUAGE js
  AS r"""
    return [ {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : null,
    "CA10__encryptionKeySource__c" : null,
    "CA10__encryptionKeyVaultUri__c" : null
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : "storageAccount4",
    "CA10__encryptionKeySource__c" : "Microsoft.Storage",
    "CA10__encryptionKeyVaultUri__c" : ""
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-11-12T04:22:47Z")
    },
    "Id" : "storageAccount5",
    "CA10__encryptionKeySource__c" : "Microsoft.Keyvault",
    "CA10__encryptionKeyVaultUri__c" : "https://example.vault.azure.net/"
  } ];
  """;

  CREATE TEMP FUNCTION process_CA10__CaAzureDiagnosticSetting__c(
      obj STRUCT<
          Id STRING,
          RecordTypeId STRING,
          CA10__disappearanceTime__c TIMESTAMP,
          CA10__storageAccount__c STRING,
          CA10__storageAccountId__c STRING,
          RecordType STRUCT<
              DeveloperName STRING,
              Id STRING
          >,
          CA10__storageAccount__r STRUCT<
              Id STRING,
              CA10__disappearanceTime__c TIMESTAMP,
              CA10__encryptionKeySource__c STRING,
              CA10__encryptionKeyVaultUri__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 CollectionLib = new function () {
          this.parse = function(arg, separator) {
              let out = new Set();
              if (arg == null) {
                  return out;
              }
              arg.split(separator).forEach(el => {if (TextLib.isNotEmpty(el)) {out.add(TextLib.normalize(el))}});
              return out;
          };
          this.fromArray = function(arr) {
              let out = new Set();
              if (arr == null) {
                  return out;
              }
              arr.forEach(el => {if (TextLib.isNotEmpty(el)) {out.add(TextLib.normalize(el))}});
              return out;
          };
          this.equal = function(left, right) {
              left = left == null ? new Set() : left;
              right = right == null ? new Set() : right;
              return left.size === right.size && new Set([...left, ...right]).size === left.size;
          };
          this.notEqual = function(left, right) {
              left = left == null ? new Set() : left;
              right = right == null ? new Set() : right;
              return left.size !== right.size || new Set([...left, ...right]).size !== left.size;
          };
          this.contains = function(collection, search) {
              if (collection == null || TextLib.isEmpty(search)) {
                  return false;
              }
              return collection.has(TextLib.normalize(search));
          };
          this.size = function(collection) {
              return collection == null ? 0 : collection.size;
          };
      }();
      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 references1 = [];
      // condition[0], conditionIndex:[0..99]
      references1.push('Deleted From Azure [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]
      references1.push('Record Type Name [obj.RecordType.DeveloperName]: ' + obj.RecordType.DeveloperName);
      if (!CollectionLib.contains(CollectionLib.fromArray(['caDiagnosticSettingOnAzureSubscription']), obj.RecordType.DeveloperName)) {
          return {status: 'INAPPLICABLE', conditionIndex: 199, conditionText: "not(['caDiagnosticSettingOnAzureSubscription'].contains(RecordType.DeveloperName))", currentStateMessage: "Object record type is not applicable", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null};
      }
      // condition[2], conditionIndex:[200..299]
      if (TextLib.isEmpty(obj.CA10__storageAccountId__c) || TextLib.isEmpty(obj.CA10__storageAccount__c) || obj.CA10__storageAccount__r.CA10__disappearanceTime__c != null) {
          return {status: 'INAPPLICABLE', conditionIndex: 299, conditionText: "isEmptyLookup('CA10__storageAccount__r')", currentStateMessage: "This Diagnostic Setting logs are not sent to a Storage account.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null};
      }
      // condition[3], conditionIndex:[300..399]
      function extractChecked3() {
          if (TextLib.isEmpty(obj.CA10__storageAccountId__c)) {
              throw new Error("UNDETERMINED condition:301", {cause: {status: 'UNDETERMINED', conditionIndex: 301, conditionText: "extractCheck(obj.CA10__storageAccountId__c)", currentStateMessage: "Related object via CA10__storageAccountId__c has empty ID", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (TextLib.isEmpty(obj.CA10__storageAccount__c)) {
              throw new Error("UNDETERMINED condition:302", {cause: {status: 'UNDETERMINED', conditionIndex: 302, conditionText: "extractCheck(obj.CA10__storageAccount__c)", currentStateMessage: "Related object via CA10__storageAccount__c is not present", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (obj.CA10__storageAccount__r.CA10__disappearanceTime__c != null) {
              throw new Error("UNDETERMINED condition:303", {cause: {status: 'UNDETERMINED', conditionIndex: 303, conditionText: "extractCheck(obj.CA10__storageAccount__r.CA10__disappearanceTime__c)", currentStateMessage: "Related object via CA10__storageAccount__c is present, but deleted in the source", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return extract4.call(extract4);
      }
      function fieldChecked5() {
          if (TextLib.isEmpty(obj.CA10__storageAccount__r.CA10__encryptionKeySource__c)) {
              throw new Error("UNDETERMINED condition:304", {cause: {status: 'UNDETERMINED', conditionIndex: 304, conditionText: "CA10__encryptionKeySource__c.isEmpty()", currentStateMessage: "Corrupted data. Encryption Key Source cannot be empty.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return obj.CA10__storageAccount__r.CA10__encryptionKeySource__c;
      }
      function extract4() { if (!this.out) { this.out = fieldChecked5(); } return this.out; };
      function extractChecked6() {
          if (TextLib.isEmpty(obj.CA10__storageAccountId__c)) {
              throw new Error("UNDETERMINED condition:305", {cause: {status: 'UNDETERMINED', conditionIndex: 305, conditionText: "extractCheck(obj.CA10__storageAccountId__c)", currentStateMessage: "Related object via CA10__storageAccountId__c has empty ID", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (TextLib.isEmpty(obj.CA10__storageAccount__c)) {
              throw new Error("UNDETERMINED condition:306", {cause: {status: 'UNDETERMINED', conditionIndex: 306, conditionText: "extractCheck(obj.CA10__storageAccount__c)", currentStateMessage: "Related object via CA10__storageAccount__c is not present", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (obj.CA10__storageAccount__r.CA10__disappearanceTime__c != null) {
              throw new Error("UNDETERMINED condition:307", {cause: {status: 'UNDETERMINED', conditionIndex: 307, conditionText: "extractCheck(obj.CA10__storageAccount__r.CA10__disappearanceTime__c)", currentStateMessage: "Related object via CA10__storageAccount__c is present, but deleted in the source", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return extract7.call(extract7);
      }
      function extract7() { if (!this.out) { this.out = obj.CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c; } return this.out; };
      references1.push('Encryption Key Source [obj.CA10__storageAccount__r.CA10__encryptionKeySource__c]: ' + obj.CA10__storageAccount__r.CA10__encryptionKeySource__c);
      references1.push('Encryption Key Vault: URI [obj.CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c]: ' + obj.CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c);
      try {
          if (TextLib.notEqual(extractChecked3(), 'Microsoft.Keyvault') && TextLib.isEmpty(extractChecked6())) {
              return {status: 'INCOMPLIANT', conditionIndex: 399, conditionText: "extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') != 'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isEmpty()", currentStateMessage: "This Diagnostic Setting logs are sent to a Storage account not encrypted with a Customer-managed Key.", currentStateReferences: references1.join('\n'), remediation: "Consider encrypting the destination Storage account with a Customer-managed encryption Key.", runtimeError: null};
          }
      } catch (err) {
          if (err.cause && err.cause.status) { return err.cause; } else { throw err; }
      }
      // condition[4], conditionIndex:[400..499]
      function extractChecked9() {
          if (TextLib.isEmpty(obj.CA10__storageAccountId__c)) {
              throw new Error("UNDETERMINED condition:401", {cause: {status: 'UNDETERMINED', conditionIndex: 401, conditionText: "extractCheck(obj.CA10__storageAccountId__c)", currentStateMessage: "Related object via CA10__storageAccountId__c has empty ID", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (TextLib.isEmpty(obj.CA10__storageAccount__c)) {
              throw new Error("UNDETERMINED condition:402", {cause: {status: 'UNDETERMINED', conditionIndex: 402, conditionText: "extractCheck(obj.CA10__storageAccount__c)", currentStateMessage: "Related object via CA10__storageAccount__c is not present", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (obj.CA10__storageAccount__r.CA10__disappearanceTime__c != null) {
              throw new Error("UNDETERMINED condition:403", {cause: {status: 'UNDETERMINED', conditionIndex: 403, conditionText: "extractCheck(obj.CA10__storageAccount__r.CA10__disappearanceTime__c)", currentStateMessage: "Related object via CA10__storageAccount__c is present, but deleted in the source", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return extract10.call(extract10);
      }
      function fieldChecked11() {
          if (TextLib.isEmpty(obj.CA10__storageAccount__r.CA10__encryptionKeySource__c)) {
              throw new Error("UNDETERMINED condition:404", {cause: {status: 'UNDETERMINED', conditionIndex: 404, conditionText: "CA10__encryptionKeySource__c.isEmpty()", currentStateMessage: "Corrupted data. Encryption Key Source cannot be empty.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return obj.CA10__storageAccount__r.CA10__encryptionKeySource__c;
      }
      function extract10() { if (!this.out) { this.out = fieldChecked11(); } return this.out; };
      function extractChecked12() {
          if (TextLib.isEmpty(obj.CA10__storageAccountId__c)) {
              throw new Error("UNDETERMINED condition:405", {cause: {status: 'UNDETERMINED', conditionIndex: 405, conditionText: "extractCheck(obj.CA10__storageAccountId__c)", currentStateMessage: "Related object via CA10__storageAccountId__c has empty ID", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (TextLib.isEmpty(obj.CA10__storageAccount__c)) {
              throw new Error("UNDETERMINED condition:406", {cause: {status: 'UNDETERMINED', conditionIndex: 406, conditionText: "extractCheck(obj.CA10__storageAccount__c)", currentStateMessage: "Related object via CA10__storageAccount__c is not present", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          if (obj.CA10__storageAccount__r.CA10__disappearanceTime__c != null) {
              throw new Error("UNDETERMINED condition:407", {cause: {status: 'UNDETERMINED', conditionIndex: 407, conditionText: "extractCheck(obj.CA10__storageAccount__r.CA10__disappearanceTime__c)", currentStateMessage: "Related object via CA10__storageAccount__c is present, but deleted in the source", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return extract13.call(extract13);
      }
      function extract13() { if (!this.out) { this.out = obj.CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c; } return this.out; };
      try {
          if (TextLib.equal(extractChecked9(), 'Microsoft.Keyvault') && TextLib.isNotEmpty(extractChecked12())) {
              return {status: 'COMPLIANT', conditionIndex: 499, conditionText: "extract('CA10__storageAccount__r.CA10__encryptionKeySource__c') == 'Microsoft.Keyvault' && extract('CA10__storageAccount__r.CA10__encryptionKeyVaultUri__c').isNotEmpty()", currentStateMessage: "This Diagnostic Setting logs are sent to a Storage account encrypted with Customer-managed Key.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null};
          }
      } catch (err) {
          if (err.cause && err.cause.status) { return err.cause; } else { throw err; }
      }
      return {status: 'UNDETERMINED', conditionIndex: 500, conditionText: "otherwise", currentStateMessage: "Unexpected values in the fields.", currentStateReferences: references1.join('\n'), remediation: null, 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.RecordTypeId AS RecordTypeId,
          sObject.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
          sObject.CA10__storageAccount__c AS CA10__storageAccount__c,
          sObject.CA10__storageAccountId__c AS CA10__storageAccountId__c,
          STRUCT (
              `RecordType`.DeveloperName AS DeveloperName,
              `RecordType`.Id AS Id
          ) AS RecordType,
          STRUCT (
              `CA10__storageAccount__r`.Id AS Id,
              `CA10__storageAccount__r`.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
              `CA10__storageAccount__r`.CA10__encryptionKeySource__c AS CA10__encryptionKeySource__c,
              `CA10__storageAccount__r`.CA10__encryptionKeyVaultUri__c AS CA10__encryptionKeyVaultUri__c
          ) AS CA10__storageAccount__r,
          process_CA10__CaAzureDiagnosticSetting__c(
              STRUCT(
                  sObject.Id AS Id,
                  sObject.RecordTypeId AS RecordTypeId,
                  sObject.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
                  sObject.CA10__storageAccount__c AS CA10__storageAccount__c,
                  sObject.CA10__storageAccountId__c AS CA10__storageAccountId__c,
                  STRUCT (
                      `RecordType`.DeveloperName AS DeveloperName,
                      `RecordType`.Id AS Id
                  ) AS RecordType,
                  STRUCT (
                      `CA10__storageAccount__r`.Id AS Id,
                      `CA10__storageAccount__r`.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
                      `CA10__storageAccount__r`.CA10__encryptionKeySource__c AS CA10__encryptionKeySource__c,
                      `CA10__storageAccount__r`.CA10__encryptionKeyVaultUri__c AS CA10__encryptionKeyVaultUri__c
                  ) AS CA10__storageAccount__r
              ),
              sObject.context.snapshotTime
          ) as result
      FROM UNNEST(mock_CA10__CaAzureDiagnosticSetting__c()) AS sObject
      LEFT JOIN UNNEST(mock_RecordType()) AS `RecordType`
          ON sObject.RecordTypeId = `RecordType`.Id
      LEFT JOIN UNNEST(mock_CA10__CaAzureStorageAccount__c()) AS `CA10__storageAccount__r`
          ON sObject.CA10__storageAccount__c = `CA10__storageAccount__r`.Id
  ) sObject ON sObject.Id = expectedResult.Id;
