Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(konnect): handle Certificate creation conflicts #763

Merged
merged 2 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions controller/konnect/ops/ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ func Create[
id, err = getKongCredentialAPIKeyForUID(ctx, sdk.GetAPIKeyCredentialsSDK(), ent)
case *configurationv1alpha1.KongCredentialACL:
id, err = getKongCredentialACLForUID(ctx, sdk.GetACLCredentialsSDK(), ent)
case *configurationv1alpha1.KongCertificate:
id, err = getKongCertificateForUID(ctx, sdk.GetCertificatesSDK(), ent)
// ---------------------------------------------------------------------
// TODO: add other Konnect types
default:
Expand Down
44 changes: 37 additions & 7 deletions controller/konnect/ops/ops_kongcertificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package ops
import (
"context"
"errors"
"fmt"

sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
sdkkonnecterrs "github.com/Kong/sdk-konnect-go/models/sdkerrors"
"github.com/samber/lo"

sdkops "github.com/kong/gateway-operator/controller/konnect/ops/sdk"

Expand Down Expand Up @@ -34,12 +36,15 @@ func createCertificate(
// Can't adopt it as it will cause conflicts between the controller
// that created that entity and already manages it, hm
if errWrap := wrapErrIfKonnectOpFailed(err, CreateOp, cert); errWrap != nil {
SetKonnectEntityProgrammedConditionFalse(cert, "FailedToCreate", errWrap.Error())
return errWrap
}

cert.Status.Konnect.SetKonnectID(*resp.Certificate.ID)
SetKonnectEntityProgrammedCondition(cert)
if resp == nil || resp.Certificate == nil || resp.Certificate.ID == nil || *resp.Certificate.ID == "" {
return fmt.Errorf("failed creating %s: %w", cert.GetTypeName(), ErrNilResponse)
}

// At this point, the Certificate has been created successfully.
cert.SetKonnectID(*resp.Certificate.ID)

return nil
}
Expand Down Expand Up @@ -90,12 +95,9 @@ func updateCertificate(
}
}
}
SetKonnectEntityProgrammedConditionFalse(cert, "FailedToUpdate", errWrap.Error())
return errWrap
}

SetKonnectEntityProgrammedCondition(cert)

return nil
}

Expand All @@ -117,9 +119,37 @@ func deleteCertificate(
}

func kongCertificateToCertificateInput(cert *configurationv1alpha1.KongCertificate) sdkkonnectcomp.CertificateInput {
return sdkkonnectcomp.CertificateInput{
input := sdkkonnectcomp.CertificateInput{
Cert: cert.Spec.Cert,
Key: cert.Spec.Key,
Tags: GenerateTagsForObject(cert, cert.Spec.Tags...),
}
if cert.Spec.CertAlt != "" {
input.CertAlt = lo.ToPtr(cert.Spec.CertAlt)
}
if cert.Spec.KeyAlt != "" {
input.KeyAlt = lo.ToPtr(cert.Spec.KeyAlt)
}

return input
}

func getKongCertificateForUID(
ctx context.Context,
sdk sdkops.CertificatesSDK,
cert *configurationv1alpha1.KongCertificate,
) (string, error) {
resp, err := sdk.ListCertificate(ctx, sdkkonnectops.ListCertificateRequest{
ControlPlaneID: cert.GetControlPlaneID(),
Tags: lo.ToPtr(UIDLabelForObject(cert)),
})
if err != nil {
return "", fmt.Errorf("failed to list %s: %w", cert.GetTypeName(), err)
}

if resp == nil || resp.Object == nil {
return "", fmt.Errorf("failed listing %s: %w", cert.GetTypeName(), ErrNilResponse)
}

return getMatchingEntryFromListResponseData(sliceToEntityWithIDSlice(resp.Object.Data), cert)
}
1 change: 1 addition & 0 deletions controller/konnect/ops/sdk/kongcertificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ type CertificatesSDK interface {
CreateCertificate(ctx context.Context, controlPlaneID string, certificate sdkkonnectcomp.CertificateInput, opts ...sdkkonnectops.Option) (*sdkkonnectops.CreateCertificateResponse, error)
UpsertCertificate(ctx context.Context, request sdkkonnectops.UpsertCertificateRequest, opts ...sdkkonnectops.Option) (*sdkkonnectops.UpsertCertificateResponse, error)
DeleteCertificate(ctx context.Context, controlPlaneID string, certificateID string, opts ...sdkkonnectops.Option) (*sdkkonnectops.DeleteCertificateResponse, error)
ListCertificate(ctx context.Context, request sdkkonnectops.ListCertificateRequest, opts ...sdkkonnectops.Option) (*sdkkonnectops.ListCertificateResponse, error)
}

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

82 changes: 80 additions & 2 deletions test/envtest/konnect_entities_kongcertificate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package envtest

import (
"context"
"slices"
"testing"

sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
sdkkonnecterrs "github.com/Kong/sdk-konnect-go/models/sdkerrors"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
Expand Down Expand Up @@ -53,7 +55,9 @@ func TestKongCertificate(t *testing.T) {
t.Log("Setting up SDK expectations on KongCertificate creation")
sdk.CertificatesSDK.EXPECT().CreateCertificate(mock.Anything, cp.GetKonnectStatus().GetKonnectID(),
mock.MatchedBy(func(input sdkkonnectcomp.CertificateInput) bool {
return input.Cert == deploy.TestValidCertPEM && input.Key == deploy.TestValidCertKeyPEM
return input.Cert == deploy.TestValidCertPEM &&
input.Key == deploy.TestValidCertKeyPEM &&
slices.Contains(input.Tags, "tag1")
}),
).Return(&sdkkonnectops.CreateCertificateResponse{
Certificate: &sdkkonnectcomp.Certificate{
Expand All @@ -65,7 +69,12 @@ func TestKongCertificate(t *testing.T) {
w := setupWatch[configurationv1alpha1.KongCertificateList](t, ctx, cl, client.InNamespace(ns.Name))

t.Log("Creating KongCertificate")
createdCert := deploy.KongCertificateAttachedToCP(t, ctx, clientNamespaced, cp)
createdCert := deploy.KongCertificateAttachedToCP(t, ctx, clientNamespaced, cp,
func(obj client.Object) {
cert := obj.(*configurationv1alpha1.KongCertificate)
cert.Spec.Tags = []string{"tag1"}
},
)

t.Log("Waiting for KongCertificate to be programmed")
watchFor(t, ctx, w, watch.Modified, func(c *configurationv1alpha1.KongCertificate) bool {
Expand Down Expand Up @@ -110,4 +119,73 @@ func TestKongCertificate(t *testing.T) {
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.True(c, factory.SDK.CertificatesSDK.AssertExpectations(t))
}, waitTime, tickTime)

t.Run("should handle conflict in creation correctly", func(t *testing.T) {
const (
certID = "id-conflict"
)
t.Log("Setup mock SDK for creating certificate and listing certificates by UID")
cpID := cp.GetKonnectStatus().GetKonnectID()
sdk.CertificatesSDK.EXPECT().
CreateCertificate(mock.Anything, cpID,
mock.MatchedBy(func(input sdkkonnectcomp.CertificateInput) bool {
return input.Cert == deploy.TestValidCertPEM &&
input.Key == deploy.TestValidCertKeyPEM &&
slices.Contains(input.Tags, "xconflictx")
}),
).
Return(nil,
&sdkkonnecterrs.SDKError{
StatusCode: 400,
Body: ErrBodyDataConstraintError,
},
)

sdk.CertificatesSDK.EXPECT().
ListCertificate(
mock.Anything,
mock.MatchedBy(func(req sdkkonnectops.ListCertificateRequest) bool {
return req.ControlPlaneID == cpID
}),
).
Return(
&sdkkonnectops.ListCertificateResponse{
Object: &sdkkonnectops.ListCertificateResponseBody{
Data: []sdkkonnectcomp.Certificate{
{
ID: lo.ToPtr(certID),
},
},
},
}, nil,
)

t.Log("Creating a KongCertificate")
createdCert := deploy.KongCertificateAttachedToCP(t, ctx, clientNamespaced, cp,
func(obj client.Object) {
cert := obj.(*configurationv1alpha1.KongCertificate)
cert.Spec.Tags = []string{"xconflictx"}
},
)

t.Log("Watching for KongCertificates to verify the created KongCertificate gets programmed")
watchFor(t, ctx, w, watch.Modified, func(c *configurationv1alpha1.KongCertificate) bool {
if c.GetName() != createdCert.GetName() {
return false
}
if !slices.Equal(c.Spec.Tags, createdCert.Spec.Tags) {
return false
}

return c.GetKonnectID() == certID && lo.ContainsBy(c.Status.Conditions, func(condition metav1.Condition) bool {
return condition.Type == konnectv1alpha1.KonnectEntityProgrammedConditionType &&
condition.Status == metav1.ConditionTrue
})
}, "KongCertificate should be programmed and have ID in status after handling conflict")

t.Log("Ensuring that the SDK's create and list methods are called")
assert.EventuallyWithT(t, func(c *assert.CollectT) {
assert.True(c, sdk.CertificatesSDK.AssertExpectations(t))
}, waitTime, tickTime)
})
}
15 changes: 1 addition & 14 deletions test/envtest/konnect_entities_kongconsumergroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,20 +156,7 @@ func TestKongConsumerGroup(t *testing.T) {
nil,
&sdkkonnecterrs.SDKError{
StatusCode: 400,
Body: `{
"code": 3,
"message": "data constraint error",
"details": [
{
"@type": "type.googleapis.com/kong.admin.model.v1.ErrorDetail",
"type": "ERROR_TYPE_REFERENCE",
"field": "name",
"messages": [
"name (type: unique) constraint failed"
]
}
]
}`,
Body: ErrBodyDataConstraintError,
},
)

Expand Down
4 changes: 4 additions & 0 deletions test/helpers/deploy/deploy_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,7 @@ func KongCertificateAttachedToCP(
ctx context.Context,
cl client.Client,
cp *konnectv1alpha1.KonnectGatewayControlPlane,
opts ...objOption,
) *configurationv1alpha1.KongCertificate {
t.Helper()

Expand All @@ -535,6 +536,9 @@ func KongCertificateAttachedToCP(
},
},
}
for _, opt := range opts {
opt(cert)
}
require.NoError(t, cl.Create(ctx, cert))
logObjectCreate(t, cert)

Expand Down
Loading