Skip to content

Policy Troubleshooter & Debugging Violations

Tại sao debugging quan trọng

VPC SC và Org Policies đều trả về HTTP 403 khi deny request. Lỗi 403 từ VPC SC trông giống IAM 403, và 403 từ Org Policy trông giống IAM 403. Nếu không có công cụ và kỹ năng debugging đúng, team có thể mất hàng giờ đi tìm "IAM permission thiếu" trong khi thực ra là VPC SC hay Org Policy đang block.

Mặt khác, khi VPC SC hoặc Org Policy đang ở dry-run mode, violations phải được đọc từ audit logs — application không thấy gì bất thường nhưng security team cần liên tục monitor để đảm bảo mọi legitimate access đã được authorize.

Chương này cung cấp systematic debugging methodology cho cả hai loại policy.

Phân biệt 403 từ VPC SC, Org Policy, và IAM

Bước đầu tiên trong debugging là xác định đúng nguyên nhân của 403:

bash
# Step 1: Xem raw error message
# IAM 403:
{
  "error": {
    "code": 403,
    "message": "bigquery.tables.getData denied on...",
    "status": "PERMISSION_DENIED"
  }
}

# VPC SC 403:
{
  "error": {
    "code": 403,
    "message": "Request is prohibited by organization's policy. [...]",
    "status": "PERMISSION_DENIED",
    "details": [{
      "@type": "type.googleapis.com/google.rpc.ErrorInfo",
      "reason": "SECURITY_POLICY_VIOLATED",
      "domain": "accesscontextmanager.googleapis.com"
    }]
  }
}

# Org Policy 403:
{
  "error": {
    "code": 403,
    "message": "Operation denied by organization policy: custom.requireCloudSqlDeletionProtection",
    "status": "PERMISSION_DENIED"
  }
}

Dấu hiệu nhận biết:

  • VPC SC: Message chứa "prohibited by organization's policy" với SECURITY_POLICY_VIOLATED reason và domain accesscontextmanager.googleapis.com
  • Org Policy: Message chứa tên constraint, ví dụ "compute.vmExternalIpAccess" hay "custom.myConstraint"
  • IAM: Message chứa permission name cụ thể (e.g., "bigquery.tables.getData denied")

Debugging VPC SC Violations

Công cụ chính: Violation Analyzer

VPC SC cung cấp Violation Analyzer để decode violations. Mỗi VPC SC violation được gán một unique ID — đây là key để trace violation trong các tools.

Bước 1: Tìm violation ID trong audit logs

bash
# Query Cloud Audit Logs tìm VPC SC violations gần đây
gcloud logging read \
  'protoPayload.metadata."@type"="type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata"' \
  --project=PROJECT_ID \
  --freshness=1h \
  --format=json | jq '.[].protoPayload.metadata.vpcServiceControlsUniqueId'

Hoặc trong Logs Explorer với filter:

protoPayload.metadata."@type"="type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata"

Bước 2: Sử dụng Violation Analyzer với unique ID

Trong Google Cloud Console → Security → VPC Service Controls → Violation Analyzer, paste unique ID để xem full analysis. Hoặc dùng gcloud:

bash
# Decode violation bằng unique ID
gcloud access-context-manager violations analyze \
  --organization=ORGANIZATION_ID \
  --violation-id=VIOLATION_ID

Analyzer sẽ cho biết:

  • Request đến từ đâu (identity, network, IP)
  • Resource đang được access
  • Tại sao bị block (violation reason)
  • Perimeter nào được invoke
  • Access levels hoặc ingress rules nào đã được evaluate

Audit Log Structure cho VPC SC

json
{
  "protoPayload": {
    "serviceName": "storage.googleapis.com",
    "methodName": "google.storage.v1.Storage.GetObject",
    "resourceName": "projects/_/buckets/protected-bucket/objects/file.txt",
    "authenticationInfo": {
      "principalEmail": "sa@project.iam.gserviceaccount.com"
    },
    "requestMetadata": {
      "callerIp": "203.0.113.50",
      "callerNetwork": "//compute.googleapis.com/projects/source-project/global/networks/default"
    },
    "metadata": {
      "@type": "type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata",
      "vpcServiceControlsUniqueId": "ABCDEF123456",
      "resourceNames": ["projects/protected-project"],
      "dryRun": false,    // true = dry-run mode
      // Violation details:
      "ingressViolations": [{
        "servicePerimeter": "accessPolicies/123/servicePerimeters/prod",
        "targetResource": "projects/protected-project",
        "accessLevel": "",
        "ingressViolation": {
          "ingressSource": {
            "callerNetwork": "//compute.googleapis.com/projects/source-project/global/networks/default"
          }
        }
      }],
      "violationReason": "NO_MATCHING_ACCESS_LEVEL"
    }
  }
}

Violation Reasons và cách xử lý

violationReasonNguyên nhânCách fix
NO_MATCHING_ACCESS_LEVELRequest không match access level nàoThêm IP/device vào access level, hoặc thêm ingress rule
NETWORK_NOT_IN_SAME_SERVICE_PERIMETERClient network và target project không trong cùng perimeterAdd host project vào perimeter, hoặc add VPC network
RESOURCES_NOT_IN_SAME_SERVICE_PERIMETERRequest access resources ở cả hai phía perimeterThêm ingress/egress rule, hoặc add project vào perimeter
SERVICE_NOT_ALLOWED_FROM_VPCService không được include trong perimeter cho VPC accessAdd service vào perimeter's restricted services
NO_MATCHING_INGRESS_SOURCEKhông có ingress rule nào match nguồnThêm ingress rule với đúng identity và source
NO_MATCHING_EGRESS_TARGETKhông có egress rule nào match đíchThêm egress rule với đúng identity và destination

VPC SC Violation Dashboard

Console → Security → VPC Service Controls → Violations cung cấp aggregated view tất cả violations trong organization, group theo:

  • Service perimeter
  • Service bị ảnh hưởng
  • Violation type
  • Time series

Dashboard này đặc biệt hữu ích trong giai đoạn dry-run để nhanh chóng thấy pattern violations trước khi enforce.

IAM Role cần cho troubleshooting

bash
# Role cần thiết để sử dụng violation analyzer
roles/accesscontextmanager.vpcScTroubleshooterViewer

# Grant role tại organization level
gcloud organizations add-iam-policy-binding ORGANIZATION_ID \
  --member=user:security-admin@company.com \
  --role=roles/accesscontextmanager.vpcScTroubleshooterViewer

Debugging Org Policy Violations

Org Policy violation trong audit logs

Org Policy violations xuất hiện trong audit logs với log name cloudaudit.googleapis.com/policy:

json
{
  "logName": "projects/my-project/logs/cloudaudit.googleapis.com%2Fpolicy",
  "protoPayload": {
    "@type": "type.googleapis.com/google.cloud.audit.AuditLog",
    "methodName": "v1.compute.instances.insert",
    "resourceName": "projects/my-project/zones/us-central1-a/instances/my-vm",
    "status": {
      "code": 7,
      "message": "PERMISSION_DENIED"
    },
    "metadata": {
      "@type": "type.googleapis.com/google.cloud.audit.OrgPolicyAuditMetadata",
      "policyViolationInfo": {
        "orgPolicyViolationInfo": {
          "violationInfo": [{
            "constraint": "constraints/compute.vmExternalIpAccess",
            "errorMessage": "Constraint constraints/compute.vmExternalIpAccess violated for...",
            "policyType": "MANAGED_POLICY"
          }]
        }
      }
    }
  }
}

Policy Troubleshooter cho Org Policy

Policy Troubleshooter (Console → IAM & Admin → Policy Troubleshooter) có thể analyze cả IAM policies Org Policy violations trong một tool:

bash
# CLI version
gcloud policy-troubleshoot org-policy \
  CONSTRAINT \
  --resource=RESOURCE_NAME \
  --identity=IDENTITY \
  --project=PROJECT_ID

Troubleshooter sẽ:

  1. Xác định constraint đang vi phạm
  2. Trace inheritance path (organization → folder → project) để xem policy nào đang effective
  3. Giải thích tại sao request bị block
  4. Gợi ý cách fix

Effective Policy — Xem policy thực sự đang được enforce

Để biết policy nào đang effective tại một resource cụ thể (sau khi tính inheritance):

bash
# Xem effective org policy cho một resource
gcloud resource-manager org-policies describe \
  CONSTRAINT_NAME \
  --effective \
  --project=PROJECT_ID

# Hoặc cho folder/organization
gcloud resource-manager org-policies describe \
  compute.vmExternalIpAccess \
  --effective \
  --folder=FOLDER_ID

# Liệt kê tất cả org policies đang áp dụng
gcloud resource-manager org-policies list \
  --project=PROJECT_ID \
  --show-unset  # Bao gồm cả constraints chưa được set (inherit từ parent)

Debugging Custom Constraints

Custom constraints có thêm một điểm failure — runtime CEL errors. Khi custom constraint fail runtime (thay vì return false), GCP log một error khác:

json
{
  "protoPayload": {
    "metadata": {
      "policyViolationInfo": {
        "orgPolicyViolationInfo": {
          "violationInfo": [{
            "constraint": "constraints/custom.myConstraint",
            "errorMessage": "BAD_CONDITION: Custom constraint evaluation error...",
            "policyType": "CUSTOM_POLICY"
          }]
        }
      }
    }
  }
}

Để debug custom constraint CEL:

bash
# Test CEL expression bằng cách describe constraint
gcloud org-policies get-custom-constraint \
  custom.myConstraint \
  --organization=ORGANIZATION_ID

# Simulate constraint evaluation bằng Policy Simulator (nếu available)
gcloud policy-intelligence simulate orgpolicy \
  --organization=ORGANIZATION_ID \
  --resource=//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/test \
  --import-file=simulated-resource.json

Systematic Debugging Workflow

Khi gặp unexpected 403, follow workflow sau:

1. Xác định loại 403
   ├── Message chứa "prohibited by organization's policy" và SECURITY_POLICY_VIOLATED
   │   → Đây là VPC SC violation → Go to step 2a
   ├── Message chứa constraint name (compute.*, custom.*)
   │   → Đây là Org Policy violation → Go to step 2b
   └── Message chứa permission name (bigquery.tables.getData denied)
       → Đây là IAM violation → Debug IAM

2a. VPC SC Debugging:
   ├── Tìm vpcServiceControlsUniqueId trong audit logs
   ├── Dùng Violation Analyzer với unique ID
   ├── Xác định violationReason
   ├── Xác định: Cần add ingress rule, egress rule, hay access level?
   └── Apply fix → Test lại

2b. Org Policy Debugging:
   ├── Xác định constraint name từ error message
   ├── Chạy `gcloud resource-manager org-policies describe CONSTRAINT --effective --project=PROJECT_ID`
   ├── Trace inheritance: tại level nào policy được set?
   ├── Quyết định: Cần thêm exception hay thay đổi policy?
   └── Apply fix → Test lại

Monitoring Liên Tục

Thiết lập alerting để phát hiện violations kịp thời:

bash
# Tạo log-based metric cho VPC SC violations
gcloud logging metrics create vpc_sc_violations \
  --description="Count of VPC SC violations" \
  --log-filter='protoPayload.metadata."@type"="type.googleapis.com/google.cloud.audit.VpcServiceControlAuditMetadata" AND protoPayload.metadata.dryRun=false'

# Tạo alerting policy cho metric trên
# (Dùng Cloud Monitoring Console để tạo alerting policy từ metric này)

Phân biệt alerting cho:

  • Dry-run violations: Cần review nhưng không urgent — có thể daily digest
  • Enforced violations (dryRun=false): Có thể là security incident — cần immediate alert
  • Org Policy violations: Review weekly để phát hiện drift và potential misuse

References