Skip to content

Commit

Permalink
restoring autokeyconfig alpha resource
Browse files Browse the repository at this point in the history
  • Loading branch information
nb-goog committed Nov 14, 2024
1 parent 23736c6 commit 91791b2
Show file tree
Hide file tree
Showing 5 changed files with 495 additions and 8 deletions.
167 changes: 167 additions & 0 deletions apis/kms/v1alpha1/autokeyconfig_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// 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 v1alpha1

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 = &KMSAutokeyConfigRef{}

// KMSAutokeyConfigRef defines the resource reference to KMSAutokeyConfig, which "External" field
// holds the GCP identifier for the KRM object.
type KMSAutokeyConfigRef struct {
// A reference to an externally managed KMSAutokeyConfig resource.
// Should be in the format "folders/<folderID>/autokeyConfig".
External string `json:"external,omitempty"`

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

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

parent *KMSAutokeyConfigParent
}

// NormalizedExternal provision the "External" value for other resource that depends on KMSAutokeyConfig.
// If the "External" is given in the other resource's spec.KMSAutokeyConfigRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual KMSAutokeyConfig object from the cluster.
func (r *KMSAutokeyConfigRef) 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", KMSAutokeyConfigGVK.Kind)
}
// From given External
if r.External != "" {
if _, err := ParseKMSAutokeyConfigExternal(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(KMSAutokeyConfigGVK)
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", KMSAutokeyConfigGVK, 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 KMSAutokeyConfigRef from the Config Connector KMSAutokeyConfig object.
func NewKMSAutokeyConfigRef(ctx context.Context, reader client.Reader, obj *KMSAutokeyConfig) (*KMSAutokeyConfigRef, error) {
id := &KMSAutokeyConfigRef{}

// Get Parent
folderRef, err := refsv1beta1.ResolveFolder(ctx, reader, obj, obj.Spec.FolderRef)
if err != nil {
return nil, err
}
folderID := folderRef.FolderID
if folderID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
id.parent = &KMSAutokeyConfigParent{FolderID: folderID}

// Use approved External
externalRef := valueOf(obj.Status.ExternalRef)
if externalRef == "" {
id.External = AsKMSAutokeyConfigExternal(id.parent)
return id, nil
}

// Validate desired with actual
actualParent, err := ParseKMSAutokeyConfigExternal(externalRef)
if err != nil {
return nil, err
}
if actualParent.FolderID != folderID {
return nil, fmt.Errorf("spec.folderRef changed, expect %s, got %s", actualParent.FolderID, folderID)
}
id.External = externalRef
id.parent = &KMSAutokeyConfigParent{FolderID: folderID}
return id, nil
}

func (r *KMSAutokeyConfigRef) Parent() (*KMSAutokeyConfigParent, error) {
if r.parent != nil {
return r.parent, nil
}
if r.External != "" {
parent, err := ParseKMSAutokeyConfigExternal(r.External)
if err != nil {
return nil, err
}
return parent, nil
}
return nil, fmt.Errorf("KMSAutokeyConfigRef not initialized from `NewKMSAutokeyConfigRef` or `NormalizedExternal`")
}

type KMSAutokeyConfigParent struct {
FolderID string
}

func (p *KMSAutokeyConfigParent) String() string {
return "folders/" + p.FolderID
}

func AsKMSAutokeyConfigExternal(parent *KMSAutokeyConfigParent) (external string) {
return parent.String() + "/autokeyConfig"
}

func ParseKMSAutokeyConfigExternal(external string) (parent *KMSAutokeyConfigParent, err error) {
external = strings.TrimPrefix(external, "/")
tokens := strings.Split(external, "/")
if len(tokens) != 3 || tokens[0] != "folders" || tokens[2] != "autokeyConfig" {
return nil, fmt.Errorf("format of KMSAutokeyConfig external=%q was not known (use folders/<folderID>/autokeyConfig)", external)
}
parent = &KMSAutokeyConfigParent{
FolderID: tokens[1],
}
return parent, nil
}

func valueOf[T any](t *T) T {
var zeroVal T
if t == nil {
return zeroVal
}
return *t
}
97 changes: 97 additions & 0 deletions apis/kms/v1alpha1/autokeyconfig_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// 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 v1alpha1

import (
"github.com/GoogleCloudPlatform/k8s-config-connector/pkg/apis/k8s/v1alpha1"

refs "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var KMSAutokeyConfigGVK = GroupVersion.WithKind("KMSAutokeyConfig")

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

// KMSAutokeyConfigSpec defines the desired state of KMSAutokeyConfig
// +kcc:proto=google.cloud.kms.v1.AutokeyConfig
type KMSAutokeyConfigSpec struct {

// NOTE: ResourceID field is not required for AutokeyConfig as its ID has the format folders/<folderID>/autokeyConfig i.e., it doesnt have any unique ID of its own and relies on folderID for uniqueness.

// Immutable. The folder that this resource belongs to.
// +required
FolderRef *refs.FolderRef `json:"folderRef"`

// +optional
KeyProjectRef *refs.ProjectRef `json:"keyProject,omitempty"`
}

// KMSAutokeyConfigStatus defines the config connector machine state of KMSAutokeyConfig
type KMSAutokeyConfigStatus 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 KMSAutokeyConfig resource in GCP.
ExternalRef *string `json:"externalRef,omitempty"`

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

// KMSAutokeyConfigSpec defines the desired state of KMSAutokeyConfig
// +kcc:proto=google.cloud.kms.v1.AutokeyConfig
type KMSAutokeyConfigObservedState struct {
// Output only. Current state of this AutokeyConfig.
// +optional
State *string `json:"state,omitempty"`
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:resource:categories=gcp,shortName=gcpkmsautokeyconfig;gcpkmsautokeyconfigs
// +kubebuilder:subresource:status
// +kubebuilder:metadata:labels="cnrm.cloud.google.com/managed-by-kcc=true";"cnrm.cloud.google.com/system=true"
// +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'"

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

Spec KMSAutokeyConfigSpec `json:"spec,omitempty"`
Status KMSAutokeyConfigStatus `json:"status,omitempty"`
}

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

func init() {
SchemeBuilder.Register(&KMSAutokeyConfig{}, &KMSAutokeyConfigList{})
}
8 changes: 0 additions & 8 deletions apis/kms/v1alpha1/keyhandle_reference.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,3 @@ func AsKMSKeyHandleExternal_FromSpec(spec *KMSKeyHandleSpec) (parent *KMSKeyHand
}
return parent, valueOf(spec.ResourceID), nil
}

func valueOf[T any](t *T) T {
var zeroVal T
if t == nil {
return zeroVal
}
return *t
}
27 changes: 27 additions & 0 deletions apis/kms/v1alpha1/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 91791b2

Please sign in to comment.