func validateNodeServerCert()

in cmd/gcp-controller-manager/node_csr_approver.go [350:409]


func validateNodeServerCert(ctx *controllerContext, csr *capi.CertificateSigningRequest, x509cr *x509.CertificateRequest) (bool, error) {
	switch {
	case len(x509cr.IPAddresses) == 0:
		klog.Infof("deny CSR %q: no SAN IPs", csr.Name)
		return false, nil
	case len(x509cr.EmailAddresses) > 0 || len(x509cr.URIs) > 0:
		klog.Infof("deny CSR %q: only DNS and IP SANs allowed", csr.Name)
		return false, nil
	}

	srv := compute.NewInstancesService(ctx.gcpCfg.Compute)
	instanceName := strings.TrimPrefix(csr.Spec.Username, "system:node:")
	for _, z := range ctx.gcpCfg.Zones {
		inst, err := srv.Get(ctx.gcpCfg.ProjectID, z, instanceName).Do()
		if err != nil {
			if isNotFound(err) {
				continue
			}
			return false, err
		}

		// Format the Domain-scoped projectID before validating the DNS name, e.g. example.com:my-project-123456789012
		projectID := ctx.gcpCfg.ProjectID
		if strings.Contains(projectID, ":") {
			parts := strings.Split(projectID, ":")
			if len(parts) != 2 {
				klog.Infof("expected the Domain-scoped project to contain only one colon, got: %s", projectID)
				return false, err
			}
			projectID = fmt.Sprintf("%s.%s", parts[1], parts[0])
		}

		for _, dns := range x509cr.DNSNames {
			// Linux DNSName should be as the format of [INSTANCE_NAME].c.[PROJECT_ID].internal when using the global DNS, and [INSTANCE_NAME].[ZONE].c.[PROJECT_ID].internal when using zonal DNS.
			// Windows DNSName should be INSTANCE_NAME
			if dns != instanceName && dns != fmt.Sprintf("%s.c.%s.internal", instanceName, projectID) && dns != fmt.Sprintf("%s.%s.c.%s.internal", instanceName, z, projectID) {
				klog.Infof("deny CSR %q: DNSName in CSR (%q) doesn't match default DNS format on instance %q", csr.Name, dns, instanceName)
				return false, nil
			}
		}
	scanIPs:
		for _, ip := range x509cr.IPAddresses {
			for _, iface := range inst.NetworkInterfaces {
				if ip.String() == iface.NetworkIP {
					continue scanIPs
				}
				for _, ac := range iface.AccessConfigs {
					if ip.String() == ac.NatIP {
						continue scanIPs
					}
				}
			}
			klog.Infof("deny CSR %q: IP addresses in CSR (%q) don't match NetworkInterfaces on instance %q (%+v)", csr.Name, x509cr.IPAddresses, instanceName, inst.NetworkInterfaces)
			return false, nil
		}
		return true, nil
	}
	klog.Infof("deny CSR %q: instance name %q doesn't match any VM in cluster project/zone", csr.Name, instanceName)
	return false, nil
}