id: gcloud-pg-log-statement-flag-not-configured

info:
  name: Log Statement Flag Not Configured Properly for PostgreSQL Database Instances
  author: princechaddha
  severity: medium
  description: |
    Ensure that the "log_statement" database flag configured for your Google Cloud PostgreSQL database instances has the appropriate value (logging level) in accordance with your organization's logging policy. The "log_statement" flag controls which SQL statements are logged, with valid values being: none, ddl, mod, and all.
  impact: |
    An improperly configured "log_statement" flag can result in either excessive logging, which impacts performance, or insufficient logging, which hinders troubleshooting and auditing.
  remediation: |
    Set the "log_statement" flag to the appropriate value (e.g., mod) based on your organization's logging policy to balance performance and logging requirements.
  reference:
    - https://cloud.google.com/sql/docs/postgres/flags
  tags: cloud,devops,gcp,gcloud,google-cloud-sql,postgresql,logging,gcp-cloud-config

flow: |
  code(1)
  for(let projectId of iterate(template.projectIds)){
    set("projectId", projectId)
    code(2)
    for(let sqlInstance of iterate(template.sqlInstances)){
      set("sqlInstance", sqlInstance)
      code(3)
    }
  }

self-contained: true

code:
  - engine:
      - sh
      - bash
    source: |
      gcloud projects list --format="json(projectId)"

    extractors:
      - type: json
        name: projectIds
        internal: true
        json:
          - '.[].projectId'

  - engine:
      - sh
      - bash
    source: |
      gcloud sql instances list --project $projectId --filter=DATABASE_VERSION:POSTGRES* --format="json(name)"

    extractors:
      - type: json
        name: sqlInstances
        internal: true
        json:
          - '.[].name'

  - engine:
      - sh
      - bash
    source: |
      gcloud sql instances describe $sqlInstance --project $projectId --format=json | jq -r '.settings.databaseFlags[]? | select(.name=="log_statement") | .value // "null"'

    matchers:
      - type: word
        words:
          - 'null'

    extractors:
      - type: dsl
        dsl:
          - '"The log_statement flag is not configured or is set to an inappropriate value for PostgreSQL instance " + sqlInstance + " in project " + projectId'
# digest: 4b0a00483046022100c3f4b8b166f8a753a7b337572a22e14613bc854d94456f126d6900eb5c8faaaf022100da9e70bcb45595b51b02e43e7dcdb1559570321389f8820317a46d334a0b7d7a:922c64590222798bb761d5b6d8e72950