package compute

// ATTENTION!
// This rule was autogenerated!
// Before making changes, consider updating the generator.

import (
	"github.com/aquasecurity/tfsec/internal/app/tfsec/block"
	"github.com/aquasecurity/tfsec/internal/app/tfsec/hclcontext"
	"github.com/aquasecurity/tfsec/internal/app/tfsec/scanner"
	"github.com/aquasecurity/tfsec/pkg/provider"
	"github.com/aquasecurity/tfsec/pkg/result"
	"github.com/aquasecurity/tfsec/pkg/rule"
	"github.com/aquasecurity/tfsec/pkg/severity"
	"github.com/zclconf/go-cty/cty"
)

func init() {
	scanner.RegisterCheckRule(rule.Rule{
		Provider:  provider.GoogleProvider,
		Service:   "compute",
		ShortCode: "no-oslogin-override",
		Documentation: rule.RuleDocumentation{
			Summary:     "Instances should not override the project setting for OS Login",
			Explanation: `OS Login automatically revokes the relevant SSH keys when an IAM user has their access revoked.`,
			Impact:      "Access via SSH key cannot be revoked automatically when an IAM user is removed.",
			Resolution:  "Enable OS Login at project level and remove instance-level overrides",
			BadExample: []string{`
resource "google_compute_instance" "default" {
  name         = "test"
  machine_type = "e2-medium"
  zone         = "us-central1-a"

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }

  // Local SSD disk
  scratch_disk {
    interface = "SCSI"
  }

  metadata = {
    enable-oslogin = false
  }
}
`},
			GoodExample: []string{`
resource "google_compute_instance" "default" {
  name         = "test"
  machine_type = "e2-medium"
  zone         = "us-central1-a"

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }

  // Local SSD disk
  scratch_disk {
    interface = "SCSI"
  }

  metadata = {
  }
}
`},
			Links: []string{
				"https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance#",
			},
		},
		RequiredTypes: []string{
			"resource",
		},
		RequiredLabels: []string{
			"google_compute_instance",
		},
		DefaultSeverity: severity.Medium,
		CheckFunc: func(set result.Set, resourceBlock block.Block, _ *hclcontext.Context) {
			metadataAttr := resourceBlock.GetAttribute("metadata")
			val := metadataAttr.MapValue("enable-oslogin")
			if val.Type() == cty.Bool && val.False() {
				set.AddResult().
					WithDescription("Resource'%s' has OS Login disabled at instance-level", resourceBlock).
					WithAttribute(metadataAttr)
				return
			}
		},
	})
}
