Skip to content

Commit

Permalink
feat: add resource WebsecurityscannerScanRun
Browse files Browse the repository at this point in the history
  • Loading branch information
yuwenma committed Feb 8, 2025
1 parent ad50980 commit 939579e
Show file tree
Hide file tree
Showing 9 changed files with 910 additions and 0 deletions.
16 changes: 16 additions & 0 deletions apis/websecurityscanner/v1alpha1/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright 2025 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.

// +kcc:proto=google.cloud.websecurityscanner.v1beta
package v1alpha1
33 changes: 33 additions & 0 deletions apis/websecurityscanner/v1alpha1/groupversion_info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2025 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.

// +kubebuilder:object:generate=true
// +groupName=websecurityscanner.cnrm.cloud.google.com
package v1alpha1

import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)

var (
// GroupVersion is group version used to register these objects
GroupVersion = schema.GroupVersion{Group: "websecurityscanner.cnrm.cloud.google.com", Version: "v1alpha1"}

// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}

// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
)
118 changes: 118 additions & 0 deletions apis/websecurityscanner/v1alpha1/scanrun_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
// Copyright 2025 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"

"github.com/GoogleCloudPlatform/k8s-config-connector/apis/common"
refsv1beta1 "github.com/GoogleCloudPlatform/k8s-config-connector/apis/refs/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// ScanRunIdentity defines the resource reference to WebsecurityscannerScanRun, which "External" field
// holds the GCP identifier for the KRM object.
type ScanRunIdentity struct {
parent *ScanRunParent
id string
}

func (i *ScanRunIdentity) String() string {
return i.parent.String() + "/scanruns/" + i.id
}

func (i *ScanRunIdentity) ID() string {
return i.id
}

func (i *ScanRunIdentity) Parent() *ScanRunParent {
return i.parent
}

type ScanRunParent struct {
ProjectID string
Location string
}

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


// New builds a ScanRunIdentity from the Config Connector ScanRun object.
func NewScanRunIdentity(ctx context.Context, reader client.Reader, obj *WebsecurityscannerScanRun) (*ScanRunIdentity, error) {

// Get Parent
projectRef, err := refsv1beta1.ResolveProject(ctx, reader, obj.GetNamespace(), obj.Spec.ProjectRef)

Check failure on line 60 in apis/websecurityscanner/v1alpha1/scanrun_identity.go

View workflow job for this annotation

GitHub Actions / lint

obj.Spec.ProjectRef undefined (type WebsecurityscannerScanRunSpec has no field or method ProjectRef)

Check failure on line 60 in apis/websecurityscanner/v1alpha1/scanrun_identity.go

View workflow job for this annotation

GitHub Actions / lint

obj.Spec.ProjectRef undefined (type WebsecurityscannerScanRunSpec has no field or method ProjectRef)
if err != nil {
return nil, err
}
projectID := projectRef.ProjectID
if projectID == "" {
return nil, fmt.Errorf("cannot resolve project")
}
location := obj.Spec.Location

Check failure on line 68 in apis/websecurityscanner/v1alpha1/scanrun_identity.go

View workflow job for this annotation

GitHub Actions / lint

obj.Spec.Location undefined (type WebsecurityscannerScanRunSpec has no field or method Location)

Check failure on line 68 in apis/websecurityscanner/v1alpha1/scanrun_identity.go

View workflow job for this annotation

GitHub Actions / lint

obj.Spec.Location undefined (type WebsecurityscannerScanRunSpec has no field or method Location)

// Get desired ID
resourceID := common.ValueOf(obj.Spec.ResourceID)
if resourceID == "" {
resourceID = obj.GetName()
}
if resourceID == "" {
return nil, fmt.Errorf("cannot resolve resource ID")
}

// Use approved External
externalRef := common.ValueOf(obj.Status.ExternalRef)
if externalRef != "" {
// Validate desired with actual
actualParent, actualResourceID, err := ParseScanRunExternal(externalRef)
if err != nil {
return nil, err
}
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 actualResourceID != resourceID {
return nil, fmt.Errorf("cannot reset `metadata.name` or `spec.resourceID` to %s, since it has already assigned to %s",
resourceID, actualResourceID)
}
}
return &ScanRunIdentity{
parent: &ScanRunParent{
ProjectID: projectID,
Location: location,
},
id: resourceID,
}, nil
}

func ParseScanRunExternal(external string) (parent *ScanRunParent, resourceID string, err error) {
tokens := strings.Split(external, "/")
if len(tokens) != 6 || tokens[0] != "projects" || tokens[2] != "locations" || tokens[4] != "scanruns" {
return nil, "", fmt.Errorf("format of WebsecurityscannerScanRun external=%q was not known (use projects/{{projectID}}/locations/{{location}}/scanruns/{{scanrunID}})", external)
}
parent = &ScanRunParent{
ProjectID: tokens[1],
Location: tokens[3],
}
resourceID = tokens[5]
return parent, resourceID, nil
}
83 changes: 83 additions & 0 deletions apis/websecurityscanner/v1alpha1/scanrun_reference.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright 2025 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"

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

// ScanRunRef defines the resource reference to WebsecurityscannerScanRun, which "External" field
// holds the GCP identifier for the KRM object.
type ScanRunRef struct {
// A reference to an externally managed WebsecurityscannerScanRun resource.
// Should be in the format "projects/{{projectID}}/locations/{{location}}/scanruns/{{scanrunID}}".
External string `json:"external,omitempty"`

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

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

// NormalizedExternal provision the "External" value for other resource that depends on WebsecurityscannerScanRun.
// If the "External" is given in the other resource's spec.WebsecurityscannerScanRunRef, the given value will be used.
// Otherwise, the "Name" and "Namespace" will be used to query the actual WebsecurityscannerScanRun object from the cluster.
func (r *ScanRunRef) 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", WebsecurityscannerScanRunGVK.Kind)
}
// From given External
if r.External != "" {
if _, _, err := ParseScanRunExternal(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(WebsecurityscannerScanRunGVK)
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", WebsecurityscannerScanRunGVK, 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
}
84 changes: 84 additions & 0 deletions apis/websecurityscanner/v1alpha1/scanrun_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright 2025 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"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var WebsecurityscannerScanRunGVK = GroupVersion.WithKind("WebsecurityscannerScanRun")

// WebsecurityscannerScanRunSpec defines the desired state of WebsecurityscannerScanRun
// +kcc:proto=google.cloud.websecurityscanner.v1beta.ScanRun
type WebsecurityscannerScanRunSpec struct {
// The WebsecurityscannerScanRun name. If not given, the metadata.name will be used.
ResourceID *string `json:"resourceID,omitempty"`
}

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

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

// WebsecurityscannerScanRunObservedState is the state of the WebsecurityscannerScanRun resource as most recently observed in GCP.
// +kcc:proto=google.cloud.websecurityscanner.v1beta.ScanRun
type WebsecurityscannerScanRunObservedState struct {
}

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// TODO(user): make sure the pluralizaiton below is correct
// +kubebuilder:resource:categories=gcp,shortName=gcpwebsecurityscannerscanrun;gcpwebsecurityscannerscanruns
// +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'"

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

// +required
Spec WebsecurityscannerScanRunSpec `json:"spec,omitempty"`
Status WebsecurityscannerScanRunStatus `json:"status,omitempty"`
}

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

func init() {
SchemeBuilder.Register(&WebsecurityscannerScanRun{}, &WebsecurityscannerScanRunList{})

Check failure on line 83 in apis/websecurityscanner/v1alpha1/scanrun_types.go

View workflow job for this annotation

GitHub Actions / lint

cannot use &WebsecurityscannerScanRun{} (value of type *WebsecurityscannerScanRun) as "k8s.io/apimachinery/pkg/runtime".Object value in argument to SchemeBuilder.Register: *WebsecurityscannerScanRun does not implement "k8s.io/apimachinery/pkg/runtime".Object (missing method DeepCopyObject)

Check failure on line 83 in apis/websecurityscanner/v1alpha1/scanrun_types.go

View workflow job for this annotation

GitHub Actions / lint

cannot use &WebsecurityscannerScanRunList{} (value of type *WebsecurityscannerScanRunList) as "k8s.io/apimachinery/pkg/runtime".Object value in argument to SchemeBuilder.Register: *WebsecurityscannerScanRunList does not implement "k8s.io/apimachinery/pkg/runtime".Object (missing method DeepCopyObject) (typecheck)

Check failure on line 83 in apis/websecurityscanner/v1alpha1/scanrun_types.go

View workflow job for this annotation

GitHub Actions / lint

cannot use &WebsecurityscannerScanRun{} (value of type *WebsecurityscannerScanRun) as "k8s.io/apimachinery/pkg/runtime".Object value in argument to SchemeBuilder.Register: *WebsecurityscannerScanRun does not implement "k8s.io/apimachinery/pkg/runtime".Object (missing method DeepCopyObject)

Check failure on line 83 in apis/websecurityscanner/v1alpha1/scanrun_types.go

View workflow job for this annotation

GitHub Actions / lint

cannot use &WebsecurityscannerScanRunList{} (value of type *WebsecurityscannerScanRunList) as "k8s.io/apimachinery/pkg/runtime".Object value in argument to SchemeBuilder.Register: *WebsecurityscannerScanRunList does not implement "k8s.io/apimachinery/pkg/runtime".Object (missing method DeepCopyObject)) (typecheck)
}
Loading

0 comments on commit 939579e

Please sign in to comment.