Skip to content

Commit

Permalink
Merge pull request GoogleCloudPlatform#3319 from nb-goog/handle_beta
Browse files Browse the repository at this point in the history
Promote KmsKeyhandle from alpha to beta
  • Loading branch information
google-oss-prow[bot] authored Dec 5, 2024
2 parents 57c4001 + 8a81641 commit 6f0f51a
Show file tree
Hide file tree
Showing 20 changed files with 1,207 additions and 33 deletions.
202 changes: 202 additions & 0 deletions apis/kms/v1beta1/keyhandle_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v1beta1

import (
"context"
"fmt"
"strings"

refsv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/k8s"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)

var _ refsv1beta1.ExternalNormalizer = &KMSKeyHandleRef{}

// KMSKeyHandleRef defines the resource reference to KMSKeyHandle, which "External" field
// holds the GCP identifier for the KRM object.
type KMSKeyHandleRef struct {
// A reference to an externally managed KMSKeyHandle resource.
// Should be in the format "projects/<projectID>/locations/<location>/keyHandles/<keyhandleID>".
External string `json:"external,omitempty"`

// The name of a KMSKeyHandle resource.
Name string `json:"name,omitempty"`

// The namespace of a KMSKeyHandle resource.
Namespace string `json:"namespace,omitempty"`

parent *KMSKeyHandleParent
}

// NormalizedExternal provision the "External" value for other resource that depends on KMSKeyHandle.
// If the "External" is given in the other resource's spec.KMSKeyHandleRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual KMSKeyHandle object from the cluster.
func (r *KMSKeyHandleRef) NormalizedExternal(ctx context.Context, reader client.Reader, otherNamespace string) (string, error) {
if r.External != "" && r.Name != "" {
return "", fmt.Errorf("cannot specify both name and external on %s reference", KMSKeyHandleGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := ParseKMSKeyHandleExternal(r.External); err != nil {
return "", err
}
return r.External, nil
}

// From the Config Connector object
if r.Namespace == "" {
r.Namespace = otherNamespace
}
key := types.NamespacedName{Name: r.Name, Namespace: r.Namespace}
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(KMSKeyHandleGVK)
if err := reader.Get(ctx, key, u); err != nil {
if apierrors.IsNotFound(err) {
return "", k8s.NewReferenceNotFoundError(u.GroupVersionKind(), key)
}
return "", fmt.Errorf("reading referenced %s %s: %w", KMSKeyHandleGVK, key, err)
}
// Get external from status.externalRef. This is the most trustworthy place.
actualExternalRef, _, err := unstructured.NestedString(u.Object, "status", "externalRef")
if err != nil {
return "", fmt.Errorf("reading status.externalRef: %w", err)
}
if actualExternalRef == "" {
return "", k8s.NewReferenceNotReadyError(u.GroupVersionKind(), key)
}
r.External = actualExternalRef
return r.External, nil
}

// New builds a KMSKeyHandleRef from the Config Connector KMSKeyHandle object.
func NewKMSKeyHandleRef(ctx context.Context, reader client.Reader, obj *KMSKeyHandle) (*KMSKeyHandleRef, error) {
id := &KMSKeyHandleRef{}

// Get Parent
projectRef, err := refsv1beta1.ResolveProject(ctx, reader, obj.GetNamespace(), obj.Spec.ProjectRef)
if err != nil {
return nil, err
}
projectID := projectRef.ProjectID
if projectID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
location := valueOf(obj.Spec.Location)
id.parent = &KMSKeyHandleParent{ProjectID: projectID, Location: location}

// Get desired ID
desiredHandleID := valueOf(obj.Spec.ResourceID)

// At this point we are expecting desiredHandleID to be either empty or valid uuid
// 1. if desiredHandleID empty:
// id.external will be projects/<pid>/locations/<loc>/keyHandles/. i.e without resourceID.
// A call will be made to find() with invalid externalID which will return false.
// 2. if desiredHandleID is a valid UUID: id.external will be valid.

// Use approved External
externalRef := valueOf(obj.Status.ExternalRef)
if externalRef != "" {
actualParent, actualHandleID, err := ParseKMSKeyHandleExternal(externalRef)
if err != nil {
return nil, err
}
// Validate desired with actual
if actualParent.ProjectID != projectID {
return nil, fmt.Errorf("spec.projectRef changed, expect %s, got %s", actualParent.ProjectID, projectID)
}
if actualParent.Location != location {
return nil, fmt.Errorf("spec.location changed, expect %s, got %s", actualParent.Location, location)
}
if desiredHandleID != "" && (actualHandleID != desiredHandleID) {
return nil, fmt.Errorf("cannot reset `spec.resourceID` to %s, since it has already assigned to %s",
desiredHandleID, actualHandleID)
}
id.External = externalRef
return id, nil
}
id.parent = &KMSKeyHandleParent{ProjectID: projectID, Location: location}
id.External = id.parent.String() + "/keyHandles/" + desiredHandleID
return id, nil
}

func (r *KMSKeyHandleRef) KeyHandleID() (string, bool, error) {
if r.External != "" {
_, id, err := ParseKMSKeyHandleExternal(r.External)
if err != nil {
return "", false, err
}
return id, id != "", nil
}
return "", false, fmt.Errorf("KMSKeyHandleRef not normalized to External form or not created from `New()`")
}

func (r *KMSKeyHandleRef) Parent() (*KMSKeyHandleParent, error) {
if r.parent != nil {
return r.parent, nil
}
if r.External != "" {
parent, _, err := ParseKMSKeyHandleExternal(r.External)
if err != nil {
return nil, err
}
return parent, nil
}
return nil, fmt.Errorf("KMSKeyHandleRef not initialized from `NewKMSKeyHandleRef` or `NormalizedExternal`")
}

type KMSKeyHandleParent struct {
ProjectID string
Location string
}

func (p *KMSKeyHandleParent) String() string {
return "projects/" + p.ProjectID + "/locations/" + p.Location
}

func AsKMSKeyHandleExternal(parent *KMSKeyHandleParent, resourceID string) (external string) {
return parent.String() + "/keyHandles/" + resourceID
}

func ParseKMSKeyHandleExternal(external string) (parent *KMSKeyHandleParent, resourceID string, err error) {
external = strings.TrimPrefix(external, "/")
tokens := strings.Split(external, "/")
if len(tokens) != 6 || tokens[0] != "projects" || tokens[2] != "locations" || tokens[4] != "keyHandles" {
return nil, "", fmt.Errorf("format of KMSKeyHandle external=%q was not known (use projects/<projectId>/locations/<location>/keyHandles/<keyhandleID>)", external)
}
parent = &KMSKeyHandleParent{
ProjectID: tokens[1],
Location: tokens[3],
}
resourceID = tokens[5]
return parent, resourceID, nil
}

func AsKMSKeyHandleExternal_FromSpec(spec *KMSKeyHandleSpec) (parent *KMSKeyHandleParent, resourceID string, err error) {
external := strings.TrimPrefix(spec.ProjectRef.External, "/")
tokens := strings.Split(external, "/")
if len(tokens) != 2 || tokens[0] != "projects" {
return nil, "", fmt.Errorf("invalid projectRef found in KMSKeyHandle=%q was not known (use projects/<projectId>)", external)
}
parent = &KMSKeyHandleParent{
ProjectID: tokens[1],
Location: valueOf(spec.Location),
}
return parent, valueOf(spec.ResourceID), nil
}
102 changes: 102 additions & 0 deletions apis/kms/v1beta1/keyhandle_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package v1beta1

import (
refs "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var KMSKeyHandleGVK = SchemeGroupVersion.WithKind("KMSKeyHandle")

// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.

// KMSKeyHandleSpec defines the desired state of KMSKeyHandle
// +kcc:proto=google.cloud.kms.v1.KeyHandle
type KMSKeyHandleSpec struct {
// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="ResourceID field is immutable"
// Immutable.
// The KMS Key Handle ID used for resource creation or acquisition.
// For creation: If specified, this value is used as the key handle ID. If not provided, a UUID will be generated and assigned as the key handle ID.
// For acquisition: This field must be provided to identify the key handle resource to acquire.
ResourceID *string `json:"resourceID,omitempty"`

// Project hosting KMSKeyHandle
ProjectRef *refs.ProjectRef `json:"projectRef,omitempty"`

// Location name to create KeyHandle
Location *string `json:"location,omitempty"`

// Indicates the resource type that the resulting [CryptoKey][] is meant to
// protect, e.g. `{SERVICE}.googleapis.com/{TYPE}`. See documentation for
// supported resource types https://cloud.google.com/kms/docs/autokey-overview#compatible-services.
ResourceTypeSelector *string `json:"resourceTypeSelector,omitempty"`
}

// KMSKeyHandleStatus defines the config connector machine state of KMSKeyHandle
type KMSKeyHandleStatus struct {
/* Conditions represent the latest available observations of the
object's current state. */
Conditions []v1alpha1.Condition `json:"conditions,omitempty"`

// ObservedGeneration is the generation of the resource that was most recently observed by the Config Connector controller. If this is equal to metadata.generation, then that means that the current reported status reflects the most recent desired state of the resource.
ObservedGeneration *int64 `json:"observedGeneration,omitempty"`

// A unique specifier for the KMSKeyHandle resource in GCP.
ExternalRef *string `json:"externalRef,omitempty"`

// ObservedState is the state of the resource as most recently observed in GCP.
ObservedState *KMSKeyHandleObservedState `json:"observedState,omitempty"`
}

// KMSKeyHandleObservedState is the state of the KMSKeyHandle resource as most recently observed in GCP.
type KMSKeyHandleObservedState struct {
KMSKey *string `json:"kmsKey,omitempty"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:resource:categories=gcp,shortName=gcpkmskeyhandle;gcpkmskeyhandles
// +kubebuilder:subresource:status
// +kubebuilder:metadata:labels="cnrm.cloud.google.com/managed-by-kcc=true";"cnrm.cloud.google.com/system=true";"cnrm.cloud.google.com/stability-level=beta"
// +kubebuilder:printcolumn:name="Age",JSONPath=".metadata.creationTimestamp",type="date"
// +kubebuilder:printcolumn:name="Ready",JSONPath=".status.conditions[?(@.type=='Ready')].status",type="string",description="When 'True', the most recent reconcile of the resource succeeded"
// +kubebuilder:printcolumn:name="Status",JSONPath=".status.conditions[?(@.type=='Ready')].reason",type="string",description="The reason for the value in 'Ready'"
// +kubebuilder:printcolumn:name="Status Age",JSONPath=".status.conditions[?(@.type=='Ready')].lastTransitionTime",type="date",description="The last transition time for the value in 'Status'"

// KMSKeyHandle is the Schema for the KMSKeyHandle API
// +k8s:openapi-gen=true
// +kubebuilder:storageversion
type KMSKeyHandle struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

// +required
Spec KMSKeyHandleSpec `json:"spec,omitempty"`
Status KMSKeyHandleStatus `json:"status,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// KMSKeyHandleList contains a list of KMSKeyHandle
type KMSKeyHandleList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []KMSKeyHandle `json:"items"`
}

func init() {
SchemeBuilder.Register(&KMSKeyHandle{}, &KMSKeyHandleList{})
}
54 changes: 27 additions & 27 deletions apis/kms/v1beta1/types.generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 6f0f51a

Please sign in to comment.