---
policy: /ce/ca/azure/sql-database/disable-database-allows-ingress-from-any-ip-rule
logic: /ce/ca/azure/sql-database/disable-database-allows-ingress-from-any-ip-rule/prod.logic.yaml
executionTime: 2025-04-24T23:45:46.113662248Z
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: INCOMPLIANT
      actual: INCOMPLIANT
    conditionIndex:
      expected: 299
      actual: 299
    conditionText:
      expected: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([?\
        \ properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress ==\
        \ \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') >\
        \ number(0.0)"
      actual: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([?\
        \ properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress ==\
        \ \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') >\
        \ number(0.0)"
    runtimeError: {}
  - id: test3
    match: true
    status:
      expected: INCOMPLIANT
      actual: INCOMPLIANT
    conditionIndex:
      expected: 199
      actual: 199
    conditionText:
      expected: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('[? name\
        \ == \\'AllowAllWindowsAzureIps\\'].name | [0]') == 'AllowAllWindowsAzureIps'"
      actual: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('[? name\
        \ == \\'AllowAllWindowsAzureIps\\'].name | [0]') == 'AllowAllWindowsAzureIps'"
    runtimeError: {}
  - id: test4
    match: true
    status:
      expected: INCOMPLIANT
      actual: INCOMPLIANT
    conditionIndex:
      expected: 299
      actual: 299
    conditionText:
      expected: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([?\
        \ properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress ==\
        \ \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') >\
        \ number(0.0)"
      actual: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([?\
        \ properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress ==\
        \ \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') >\
        \ number(0.0)"
    runtimeError: {}
  - id: test5
    match: true
    status:
      expected: COMPLIANT
      actual: COMPLIANT
    conditionIndex:
      expected: 400
      actual: 400
    conditionText:
      expected: otherwise
      actual: otherwise
    runtimeError: {}
  - id: test6
    match: true
    status:
      expected: COMPLIANT
      actual: COMPLIANT
    conditionIndex:
      expected: 400
      actual: 400
    conditionText:
      expected: otherwise
      actual: otherwise
    runtimeError: {}
  - id: test7
    match: true
    status:
      expected: COMPLIANT
      actual: COMPLIANT
    conditionIndex:
      expected: 400
      actual: 400
    conditionText:
      expected: otherwise
      actual: otherwise
    runtimeError: {}
  - id: test8
    match: true
    status:
      expected: COMPLIANT
      actual: COMPLIANT
    conditionIndex:
      expected: 400
      actual: 400
    conditionText:
      expected: otherwise
      actual: otherwise
    runtimeError: {}
  - id: test9
    match: true
    status:
      expected: UNDETERMINED
      actual: UNDETERMINED
    conditionIndex:
      expected: 101
      actual: 101
    conditionText:
      expected: CA10__firewallRulesJson__c.delegatedTo(CA10__firewallRulesJson__c).isEmpty()
      actual: CA10__firewallRulesJson__c.delegatedTo(CA10__firewallRulesJson__c).isEmpty()
    runtimeError: {}
usedFiles:
  - path: /ce/ca/azure/sql-database/disable-database-allows-ingress-from-any-ip-rule/policy.yaml
    md5Hash: 7A0A9175654937E55C7DF7A50BDCEFA5
    content: |
      ---
      names:
        full: Azure SQL Database allows ingress from 0.0.0.0/0 (ANY IP)
        contextual: Database allows ingress from 0.0.0.0/0 (ANY IP)
      description: Ensure that no SQL Databases allow ingress from 0.0.0.0/0 (ANY IP).
      type: COMPLIANCE_POLICY
      categories:
        - SECURITY
      frameworkMappings:
        - "/frameworks/cis-azure-v2.1.0/04/01/02"
        - "/frameworks/cis-azure-v3.0.0/05/01/02"
        - "/frameworks/cloudaware/resource-security/public-and-anonymous-access"
      similarPolicies:
        internal:
          - dec-x-0289e9c9
        cloudConformity:
          - url: https://www.trendmicro.com/cloudoneconformity/knowledge-base/azure/Sql/unrestricted-sql-database-access.html
            name: Check for Unrestricted SQL Database Access
  - path: /ce/ca/azure/sql-database/disable-database-allows-ingress-from-any-ip-rule/prod.logic.yaml
    md5Hash: EE5252204BD9144C8C4F2C4CCC2C5440
    content: "---\ninputType: \"CA10__CaAzureSqlServer__c\"\ntestData:\n  - file:\
      \ \"test-data.json\"\nimportExtracts:\n  - file: \"/types/CA10__CaAzureSqlServer__c/object.extracts.yaml\"\
      \nconditions:\n  - status: \"INCOMPLIANT\"\n    currentStateMessage: \"SQL Database\
      \ Server Firewall Rules contain AllowAllWindowsAzureIps rule allowing ingress\
      \ from 0.0.0.0/0 (ANY IP).\"\n    remediationMessage: \"Consider removing or\
      \ disabling the overly permissive rule.\"\n    check:\n# searches for the rule\
      \ with the name AllowAllWindowsAzureIps\n      IS_EQUAL:\n        left:\n  \
      \        JSON_QUERY_TEXT:\n              arg: \n                EXTRACT: \"\
      caJsonFrom__firewallRulesJson__c\"\n              expression: \"[? name == 'AllowAllWindowsAzureIps'].name\
      \ | [0]\"\n              undeterminedIf: \n                evaluationError:\
      \ \"The JSON query has failed.\"\n                resultTypeMismatch: \"The\
      \ JSON query did not return text type.\"\n        right:\n          TEXT: \"\
      AllowAllWindowsAzureIps\"\n  - status: \"INCOMPLIANT\"\n    currentStateMessage:\
      \ \"SQL Database Server Firewall Rules contain a rule allowing ingress from\
      \ 0.0.0.0/0 (ANY IP).\"\n    remediationMessage: \"Consider removing or disabling\
      \ the overly permissive rule.\"\n    check:\n# number of rules with start and\
      \ end IPs as 0.0.0.0\n      GREATER_THAN:\n        left:\n          JSON_QUERY_NUMBER:\n\
      \              arg: \n                EXTRACT: \"caJsonFrom__firewallRulesJson__c\"\
      \n              expression: \"length([? properties.startIpAddress == '0.0.0.0'\
      \ && (properties.endIpAddress == '0.0.0.0' || properties.endIpAddress == '255.255.255.255')])\"\
      \n              undeterminedIf: \n                evaluationError: \"The JSON\
      \ query has failed.\"\n                resultTypeMismatch: \"The JSON query\
      \ did not return number type.\"\n        right:\n          NUMBER: 0.0\n  -\
      \ status: \"COMPLIANT\"\n    currentStateMessage: \"SQL Database Server doesn't\
      \ have any Firewall Rules.\"\n    check:\n      IS_EMPTY:\n        arg:\n  \
      \        EXTRACT: \"CA10__firewallRulesJson__c\"\notherwise:\n  status: \"COMPLIANT\"\
      \n  currentStateMessage: \"SQL Database Server Firewall Rules do not have a\
      \ rule allowing ingress from 0.0.0.0/0 (ANY IP).\"\n"
  - path: /types/CA10__CaAzureSqlServer__c/object.extracts.yaml
    md5Hash: E77808BBEDF31D54E009EEA59AC5EF4B
    content: "---\nextracts:\n# Values: Enabled, Disabled. Not Nullable.\n  - name:\
      \ \"CA10__auditing__c\"\n    value: \n      FIELD:\n        path: \"CA10__auditing__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__auditing__c\"\n            currentStateMessage: \"Unable to determine\
      \ Server auditing settings. Possible permission issue with Microsoft.Sql/servers/auditingSettings/read\"\
      \n          isEmpty: \"SQL Server auditing settings are not populated yet\"\n\
      # Number field\n  - name: \"CA10__auditingRetentionDays__c\"\n    value: \n\
      \      FIELD:\n        path: \"CA10__auditingRetentionDays__c\"\n        undeterminedIf:\n\
      \          noAccessDelegate:\n            path: \"CA10__auditingRetentionDays__c\"\
      \n            currentStateMessage: \"Unable to determine Server auditing settings.\
      \ Possible permission issue with Microsoft.Sql/servers/auditingSettings/read\"\
      \n# Values: servicemanaged, azurekeyvault. Not Nullable. \n  - name: \"CA10__encryptionProtectorKind__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__encryptionProtectorKind__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__encryptionProtectorKind__c\"\n            currentStateMessage: \"Unable\
      \ to determine Server Encryption Protectors. Possible permission issue with\
      \ Microsoft.Sql/servers/encryptionProtector/read\"\n          isEmpty: \"SQL\
      \ Server Encryption Protectors are not populated yet\"\n# Values: ServiceManaged,\
      \ AzureKeyVault. Not Nullable. \n  - name: \"CA10__encryptionProtectorServerKeyType__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__encryptionProtectorServerKeyType__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__encryptionProtectorServerKeyType__c\"\n            currentStateMessage:\
      \ \"Unable to determine Server Encryption Protectors. Possible permission issue\
      \ with Microsoft.Sql/servers/encryptionProtector/read\"\n          isEmpty:\
      \ \"SQL Server Encryption Protectors are not populated yet\"\n# Nullable. \n\
      \  - name: \"CA10__encryptionProtectorUri__c\"\n    value: \n      FIELD:\n\
      \        path: \"CA10__encryptionProtectorUri__c\"\n        undeterminedIf:\n\
      \          noAccessDelegate:\n            path: \"CA10__encryptionProtectorUri__c\"\
      \n            currentStateMessage: \"Unable to determine Server Encryption Protectors.\
      \ Possible permission issue with Microsoft.Sql/servers/encryptionProtector/read\"\
      \n# Values: ActiveDirectory, null. Nullable. \n  - name: \"CA10__activeDirectoryAdminType__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__activeDirectoryAdminType__c\"\
      \n        undeterminedIf:\n          noAccessDelegate:\n            path: \"\
      CA10__activeDirectoryAdminType__c\"\n            currentStateMessage: \"Unable\
      \ to determine Server AD Administrator type. Possible permission issue with\
      \ Microsoft.Sql/servers/administrators\"\n  - name: \"CA10__firewallRulesJson__c\"\
      \n    value: \n      FIELD:\n        path: \"CA10__firewallRulesJson__c\"\n\
      \        returnType: BYTES\n        undeterminedIf:\n          noAccessDelegate:\n\
      \            path: \"CA10__firewallRulesJson__c\"\n            currentStateMessage:\
      \ \"Unable to determine Firewall Rules. Possible permission issue with Microsoft.Sql/servers/firewallRules/read\"\
      \n  - name: \"caJsonFrom__firewallRulesJson__c\"\n    value: \n      JSON_FROM:\n\
      \        arg: \n          EXTRACT: \"CA10__firewallRulesJson__c\"\n        undeterminedIf:\n\
      \          isInvalid: \"Firewall Rules JSON is invalid.\"\n# Nullable. Values:\
      \ Enabled, Disabled, Can't have no access, retrieved via Microsoft.Sql/servers\n\
      \  - name: \"CA10__publicNetworkAccess__c\"\n    value: \n      FIELD:\n   \
      \     path: \"CA10__publicNetworkAccess__c\"\n"
  - path: /ce/ca/azure/sql-database/disable-database-allows-ingress-from-any-ip-rule/test-data.json
    md5Hash: 6797079708A7644D13B8854DA81CDA70
    content: |-
      [
          {
              "expectedResult": {
                  "status": "DISAPPEARED",
                  "conditionIndex": "99",
                  "conditionText": "isDisappeared(CA10__disappearanceTime__c)",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test1",
              "CA10__disappearanceTime__c": "2024-06-07T13:58:24Z",
              "CA10__firewallRulesJson__c": "[{\"properties\":{\"startIpAddress\":\"0.0.0.0\",\"endIpAddress\":\"0.0.0.0\"},\"name\":\"AllowAllWindowsAzureIps\"}]"
          },
          {
              "expectedResult": {
                  "status": "INCOMPLIANT",
                  "conditionIndex": "299",
                  "conditionText": "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([? properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress == \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') > number(0.0)",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test2",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": "[{\"properties\":{\"startIpAddress\":\"0.0.0.0\",\"endIpAddress\":\"0.0.0.0\"},\"name\":\"FirewallRuleName\"}]"
          },
          {
              "expectedResult": {
                  "status": "INCOMPLIANT",
                  "conditionIndex": "199",
                  "conditionText": "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('[? name == \\'AllowAllWindowsAzureIps\\'].name | [0]') == 'AllowAllWindowsAzureIps'",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test3",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": "[{\"properties\":{\"startIpAddress\":\"1.1.1.1\",\"endIpAddress\":\"255.255.255.0\"},\"name\":\"AllowAllWindowsAzureIps\"}]"
          },
          {
              "expectedResult": {
                  "status": "INCOMPLIANT",
                  "conditionIndex": "299",
                  "conditionText": "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([? properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress == \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') > number(0.0)",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test4",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": "[{\"properties\":{\"startIpAddress\":\"0.0.0.0\",\"endIpAddress\":\"255.255.255.255\"},\"name\":\"FirewallRuleName\"}]"
          },
          {
              "expectedResult": {
                  "status": "COMPLIANT",
                  "conditionIndex": "400",
                  "conditionText": "otherwise",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test5",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": "[{\"properties\":{\"startIpAddress\":\"1.1.1.1\",\"endIpAddress\":\"1.1.1.1\"},\"name\":\"FirewallRuleName\"}]"
          },
          {
              "expectedResult": {
                  "status": "COMPLIANT",
                  "conditionIndex": "400",
                  "conditionText": "otherwise",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test6",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": "[{\"name\":\"FirewallRuleName\"}]"
          },
          {
              "expectedResult": {
                  "status": "COMPLIANT",
                  "conditionIndex": "400",
                  "conditionText": "otherwise",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test7",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": "[{\"properties\":{\"startIpAddress\":\"1.1.1.1\",\"endIpAddress\":\"1.1.1.1\"}}]"
          },
          {
              "expectedResult": {
                  "status": "COMPLIANT",
                  "conditionIndex": "400",
                  "conditionText": "otherwise",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test8",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": "[]"
          },
          {
              "expectedResult": {
                  "status": "UNDETERMINED",
                  "conditionIndex": "101",
                  "conditionText": "CA10__firewallRulesJson__c.delegatedTo(CA10__firewallRulesJson__c).isEmpty()",
                  "runtimeError": null
              },
              "context": {
                  "snapshotTime": "2024-06-13T04:17:29Z"
              },
              "Id": "test9",
              "CA10__disappearanceTime__c": null,
              "CA10__firewallRulesJson__c": null
          }
      ]
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" : "INCOMPLIANT",
      "conditionIndex" : "299",
      "conditionText" : "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([? properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress == \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') > number(0.0)",
      "runtimeError" : null
    }
  }, {
    "Id" : "test3",
    "expectedResult" : {
      "status" : "INCOMPLIANT",
      "conditionIndex" : "199",
      "conditionText" : "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('[? name == \\'AllowAllWindowsAzureIps\\'].name | [0]') == 'AllowAllWindowsAzureIps'",
      "runtimeError" : null
    }
  }, {
    "Id" : "test4",
    "expectedResult" : {
      "status" : "INCOMPLIANT",
      "conditionIndex" : "299",
      "conditionText" : "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([? properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress == \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') > number(0.0)",
      "runtimeError" : null
    }
  }, {
    "Id" : "test5",
    "expectedResult" : {
      "status" : "COMPLIANT",
      "conditionIndex" : "400",
      "conditionText" : "otherwise",
      "runtimeError" : null
    }
  }, {
    "Id" : "test6",
    "expectedResult" : {
      "status" : "COMPLIANT",
      "conditionIndex" : "400",
      "conditionText" : "otherwise",
      "runtimeError" : null
    }
  }, {
    "Id" : "test7",
    "expectedResult" : {
      "status" : "COMPLIANT",
      "conditionIndex" : "400",
      "conditionText" : "otherwise",
      "runtimeError" : null
    }
  }, {
    "Id" : "test8",
    "expectedResult" : {
      "status" : "COMPLIANT",
      "conditionIndex" : "400",
      "conditionText" : "otherwise",
      "runtimeError" : null
    }
  }, {
    "Id" : "test9",
    "expectedResult" : {
      "status" : "UNDETERMINED",
      "conditionIndex" : "101",
      "conditionText" : "CA10__firewallRulesJson__c.delegatedTo(CA10__firewallRulesJson__c).isEmpty()",
      "runtimeError" : null
    }
  } ];
  """;

  CREATE TEMP FUNCTION mock_CA10__CaAzureSqlServer__c()
  RETURNS ARRAY<STRUCT<
      Id STRING,
      CA10__disappearanceTime__c TIMESTAMP,
      CA10__firewallRulesJson__c STRING,
      context STRUCT<
          snapshotTime TIMESTAMP
      >
  >>
  DETERMINISTIC
  LANGUAGE js
  AS r"""
    return [ {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test1",
    "CA10__disappearanceTime__c" : new Date("2024-06-07T13:58:24Z"),
    "CA10__firewallRulesJson__c" : "[{\"properties\":{\"startIpAddress\":\"0.0.0.0\",\"endIpAddress\":\"0.0.0.0\"},\"name\":\"AllowAllWindowsAzureIps\"}]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test2",
    "CA10__firewallRulesJson__c" : "[{\"properties\":{\"startIpAddress\":\"0.0.0.0\",\"endIpAddress\":\"0.0.0.0\"},\"name\":\"FirewallRuleName\"}]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test3",
    "CA10__firewallRulesJson__c" : "[{\"properties\":{\"startIpAddress\":\"1.1.1.1\",\"endIpAddress\":\"255.255.255.0\"},\"name\":\"AllowAllWindowsAzureIps\"}]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test4",
    "CA10__firewallRulesJson__c" : "[{\"properties\":{\"startIpAddress\":\"0.0.0.0\",\"endIpAddress\":\"255.255.255.255\"},\"name\":\"FirewallRuleName\"}]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test5",
    "CA10__firewallRulesJson__c" : "[{\"properties\":{\"startIpAddress\":\"1.1.1.1\",\"endIpAddress\":\"1.1.1.1\"},\"name\":\"FirewallRuleName\"}]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test6",
    "CA10__firewallRulesJson__c" : "[{\"name\":\"FirewallRuleName\"}]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test7",
    "CA10__firewallRulesJson__c" : "[{\"properties\":{\"startIpAddress\":\"1.1.1.1\",\"endIpAddress\":\"1.1.1.1\"}}]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test8",
    "CA10__firewallRulesJson__c" : "[]"
  }, {
    "context" : {
      "snapshotTime" : new Date("2024-06-13T04:17:29Z")
    },
    "Id" : "test9",
    "CA10__firewallRulesJson__c" : null
  } ];
  """;

  CREATE TEMP FUNCTION process_CA10__CaAzureSqlServer__c(
      obj STRUCT<
          Id STRING,
          CA10__disappearanceTime__c TIMESTAMP,
          CA10__firewallRulesJson__c STRING
      >,
      snapshotTime TIMESTAMP
  )
  RETURNS STRUCT<status STRING, conditionIndex DECIMAL, conditionText STRING, currentStateMessage STRING, currentStateReferences STRING, remediation STRING, runtimeError STRING>
  DETERMINISTIC
  LANGUAGE js
  OPTIONS (library=['gs://compliance-platform-public/jmespath.min.js'])
  AS r"""
      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]
      function jsonQueryChecked2() {
          var input = extract4.call(extract4);
          var out;
          try {
              out = jmespath.search(input, '[? name == \'AllowAllWindowsAzureIps\'].name | [0]');
          if (out != null && typeof out != 'string') {
              throw new Error("UNDETERMINED condition:103", {cause: {status: 'UNDETERMINED', conditionIndex: 103, conditionText: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('[? name == \\'AllowAllWindowsAzureIps\\'].name | [0]').isResultTypeMismatch()", currentStateMessage: "The JSON query did not return text type.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          } catch (e) {
              throw new Error("UNDETERMINED condition:104", {cause: {status: 'UNDETERMINED', conditionIndex: 104, conditionText: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('[? name == \\'AllowAllWindowsAzureIps\\'].name | [0]').isEvaluationFailed()", currentStateMessage: "The JSON query has failed.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: e.message}});
          }
          return out;
      }
      function jsonChecked5() {
          var input = extract7.call(extract7);
          input = TextLib.isEmpty(input) ? null : input;
          var out;
          try {
              out = JSON.parse(input);
          } catch (e) {
              throw new Error("UNDETERMINED condition:102", {cause: {status: 'UNDETERMINED', conditionIndex: 102, conditionText: "extract('CA10__firewallRulesJson__c').asJson().isInvalid()", currentStateMessage: "Firewall Rules JSON is invalid.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: e.message}});
          }
          return out;
      }
      function fieldChecked8() {
          if ((obj.CA10__firewallRulesJson__c == null || obj.CA10__firewallRulesJson__c == '')) {
              throw new Error("UNDETERMINED condition:101", {cause: {status: 'UNDETERMINED', conditionIndex: 101, conditionText: "CA10__firewallRulesJson__c.delegatedTo(CA10__firewallRulesJson__c).isEmpty()", currentStateMessage: "Unable to determine Firewall Rules. Possible permission issue with Microsoft.Sql/servers/firewallRules/read", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return obj.CA10__firewallRulesJson__c;
      }
      function extract7() { if (!this.out) { this.out = fieldChecked8(); } return this.out; };
      function extract4() { if (!this.out) { this.out = jsonChecked5(); } return this.out; };
      references1.push('Firewall Rules JSON [obj.CA10__firewallRulesJson__c]: ' + obj.CA10__firewallRulesJson__c);
      try {
          if (TextLib.equal(jsonQueryChecked2(), 'AllowAllWindowsAzureIps')) {
              return {status: 'INCOMPLIANT', conditionIndex: 199, conditionText: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('[? name == \\'AllowAllWindowsAzureIps\\'].name | [0]') == 'AllowAllWindowsAzureIps'", currentStateMessage: "SQL Database Server Firewall Rules contain AllowAllWindowsAzureIps rule allowing ingress from 0.0.0.0/0 (ANY IP).", currentStateReferences: references1.join('\n'), remediation: "Consider removing or disabling the overly permissive rule.", runtimeError: null};
          }
      } catch (err) {
          if (err.cause && err.cause.status) { return err.cause; } else { throw err; }
      }
      // condition[2], conditionIndex:[200..299]
      function comparison10() {
          var comparisonLeft19 = jsonQueryChecked11();
          return comparisonLeft19 != null && 0.0 != null && comparisonLeft19 > 0.0;
      }
      function jsonQueryChecked11() {
          var input = extract13.call(extract13);
          var out;
          try {
              out = jmespath.search(input, 'length([? properties.startIpAddress == \'0.0.0.0\' && (properties.endIpAddress == \'0.0.0.0\' || properties.endIpAddress == \'255.255.255.255\')])');
          if (out != null && typeof out != 'number') {
              throw new Error("UNDETERMINED condition:203", {cause: {status: 'UNDETERMINED', conditionIndex: 203, conditionText: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([? properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress == \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])').isResultTypeMismatch()", currentStateMessage: "The JSON query did not return number type.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          } catch (e) {
              throw new Error("UNDETERMINED condition:204", {cause: {status: 'UNDETERMINED', conditionIndex: 204, conditionText: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([? properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress == \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])').isEvaluationFailed()", currentStateMessage: "The JSON query has failed.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: e.message}});
          }
          return out;
      }
      function jsonChecked14() {
          var input = extract16.call(extract16);
          input = TextLib.isEmpty(input) ? null : input;
          var out;
          try {
              out = JSON.parse(input);
          } catch (e) {
              throw new Error("UNDETERMINED condition:202", {cause: {status: 'UNDETERMINED', conditionIndex: 202, conditionText: "extract('CA10__firewallRulesJson__c').asJson().isInvalid()", currentStateMessage: "Firewall Rules JSON is invalid.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: e.message}});
          }
          return out;
      }
      function fieldChecked17() {
          if ((obj.CA10__firewallRulesJson__c == null || obj.CA10__firewallRulesJson__c == '')) {
              throw new Error("UNDETERMINED condition:201", {cause: {status: 'UNDETERMINED', conditionIndex: 201, conditionText: "CA10__firewallRulesJson__c.delegatedTo(CA10__firewallRulesJson__c).isEmpty()", currentStateMessage: "Unable to determine Firewall Rules. Possible permission issue with Microsoft.Sql/servers/firewallRules/read", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return obj.CA10__firewallRulesJson__c;
      }
      function extract16() { if (!this.out) { this.out = fieldChecked17(); } return this.out; };
      function extract13() { if (!this.out) { this.out = jsonChecked14(); } return this.out; };
      try {
          if (comparison10()) {
              return {status: 'INCOMPLIANT', conditionIndex: 299, conditionText: "extract('caJsonFrom__firewallRulesJson__c').jsonQueryText('length([? properties.startIpAddress == \\'0.0.0.0\\' && (properties.endIpAddress == \\'0.0.0.0\\' || properties.endIpAddress == \\'255.255.255.255\\')])') > number(0.0)", currentStateMessage: "SQL Database Server Firewall Rules contain a rule allowing ingress from 0.0.0.0/0 (ANY IP).", currentStateReferences: references1.join('\n'), remediation: "Consider removing or disabling the overly permissive rule.", runtimeError: null};
          }
      } catch (err) {
          if (err.cause && err.cause.status) { return err.cause; } else { throw err; }
      }
      // condition[3], conditionIndex:[300..399]
      function fieldChecked22() {
          if ((obj.CA10__firewallRulesJson__c == null || obj.CA10__firewallRulesJson__c == '')) {
              throw new Error("UNDETERMINED condition:301", {cause: {status: 'UNDETERMINED', conditionIndex: 301, conditionText: "CA10__firewallRulesJson__c.delegatedTo(CA10__firewallRulesJson__c).isEmpty()", currentStateMessage: "Unable to determine Firewall Rules. Possible permission issue with Microsoft.Sql/servers/firewallRules/read", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null}});
          }
          return obj.CA10__firewallRulesJson__c;
      }
      function extract21() { if (!this.out) { this.out = fieldChecked22(); } return this.out; };
      try {
          if (extract21.call(extract21) == null || extract21.call(extract21) == '') {
              return {status: 'COMPLIANT', conditionIndex: 399, conditionText: "extract('CA10__firewallRulesJson__c').isEmpty()", currentStateMessage: "SQL Database Server doesn't have any Firewall Rules.", currentStateReferences: references1.join('\n'), remediation: null, runtimeError: null};
          }
      } catch (err) {
          if (err.cause && err.cause.status) { return err.cause; } else { throw err; }
      }
      return {status: 'COMPLIANT', conditionIndex: 400, conditionText: "otherwise", currentStateMessage: "SQL Database Server Firewall Rules do not have a rule allowing ingress from 0.0.0.0/0 (ANY IP).", 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.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
          sObject.CA10__firewallRulesJson__c AS CA10__firewallRulesJson__c,
          process_CA10__CaAzureSqlServer__c(
              STRUCT(
                  sObject.Id AS Id,
                  sObject.CA10__disappearanceTime__c AS CA10__disappearanceTime__c,
                  sObject.CA10__firewallRulesJson__c AS CA10__firewallRulesJson__c
              ),
              sObject.context.snapshotTime
          ) as result
      FROM UNNEST(mock_CA10__CaAzureSqlServer__c()) AS sObject
  ) sObject ON sObject.Id = expectedResult.Id;
