aboutsummaryrefslogtreecommitdiffstats
path: root/certServiceK8sExternalProvider/src
diff options
context:
space:
mode:
Diffstat (limited to 'certServiceK8sExternalProvider/src')
-rw-r--r--certServiceK8sExternalProvider/src/api/cerservice_issuer_crd_deepcopy.go162
-rw-r--r--certServiceK8sExternalProvider/src/api/certservice_issuer_crd_schema.go140
-rw-r--r--certServiceK8sExternalProvider/src/api/groupversion_info.go43
-rw-r--r--certServiceK8sExternalProvider/src/certservice-controller/certificaterequest_reconciler.go162
-rw-r--r--certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_reconciler.go125
-rw-r--r--certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_status_reconciler.go115
-rw-r--r--certServiceK8sExternalProvider/src/certservice-provisioner/certservice-provisioner.go165
7 files changed, 908 insertions, 4 deletions
diff --git a/certServiceK8sExternalProvider/src/api/cerservice_issuer_crd_deepcopy.go b/certServiceK8sExternalProvider/src/api/cerservice_issuer_crd_deepcopy.go
new file mode 100644
index 00000000..2b2e455b
--- /dev/null
+++ b/certServiceK8sExternalProvider/src/api/cerservice_issuer_crd_deepcopy.go
@@ -0,0 +1,162 @@
+/*
+ * ============LICENSE_START=======================================================
+ * oom-certservice-k8s-external-provider
+ * ================================================================================
+ * Copyright (c) 2019 Smallstep Labs, Inc.
+ * Modifications copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * This source code was copied from the following git repository:
+ * https://github.com/smallstep/step-issuer
+ * The source code was modified for usage in the ONAP project.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+
+package api
+
+import (
+ runtime "k8s.io/apimachinery/pkg/runtime"
+)
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *SecretKeySelector) DeepCopyInto(out *SecretKeySelector) {
+ *out = *in
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecretKeySelector.
+func (in *SecretKeySelector) DeepCopy() *SecretKeySelector {
+ if in == nil {
+ return nil
+ }
+ out := new(SecretKeySelector)
+ in.DeepCopyInto(out)
+ return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CertServiceIssuer) DeepCopyInto(out *CertServiceIssuer) {
+ *out = *in
+ out.TypeMeta = in.TypeMeta
+ in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
+ in.Spec.DeepCopyInto(&out.Spec)
+ in.Status.DeepCopyInto(&out.Status)
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertServiceIssuer.
+func (in *CertServiceIssuer) DeepCopy() *CertServiceIssuer {
+ if in == nil {
+ return nil
+ }
+ out := new(CertServiceIssuer)
+ in.DeepCopyInto(out)
+ return out
+}
+
+// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
+func (in *CertServiceIssuer) DeepCopyObject() runtime.Object {
+ if c := in.DeepCopy(); c != nil {
+ return c
+ }
+ return nil
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CertServiceIssuerCondition) DeepCopyInto(out *CertServiceIssuerCondition) {
+ *out = *in
+ if in.LastTransitionTime != nil {
+ in, out := &in.LastTransitionTime, &out.LastTransitionTime
+ *out = (*in).DeepCopy()
+ }
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertServiceIssuerCondition.
+func (in *CertServiceIssuerCondition) DeepCopy() *CertServiceIssuerCondition {
+ if in == nil {
+ return nil
+ }
+ out := new(CertServiceIssuerCondition)
+ in.DeepCopyInto(out)
+ return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CertServiceIssuerList) DeepCopyInto(out *CertServiceIssuerList) {
+ *out = *in
+ out.TypeMeta = in.TypeMeta
+ in.ListMeta.DeepCopyInto(&out.ListMeta)
+ if in.Items != nil {
+ in, out := &in.Items, &out.Items
+ *out = make([]CertServiceIssuer, len(*in))
+ for i := range *in {
+ (*in)[i].DeepCopyInto(&(*out)[i])
+ }
+ }
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertServiceIssuerList.
+func (in *CertServiceIssuerList) DeepCopy() *CertServiceIssuerList {
+ if in == nil {
+ return nil
+ }
+ out := new(CertServiceIssuerList)
+ in.DeepCopyInto(out)
+ return out
+}
+
+// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
+func (in *CertServiceIssuerList) DeepCopyObject() runtime.Object {
+ if c := in.DeepCopy(); c != nil {
+ return c
+ }
+ return nil
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CertServiceIssuerSpec) DeepCopyInto(out *CertServiceIssuerSpec) {
+ *out = *in
+ out.KeyRef = in.KeyRef
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertServiceIssuerSpec.
+func (in *CertServiceIssuerSpec) DeepCopy() *CertServiceIssuerSpec {
+ if in == nil {
+ return nil
+ }
+ out := new(CertServiceIssuerSpec)
+ in.DeepCopyInto(out)
+ return out
+}
+
+// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
+func (in *CertServiceIssuerStatus) DeepCopyInto(out *CertServiceIssuerStatus) {
+ *out = *in
+ if in.Conditions != nil {
+ in, out := &in.Conditions, &out.Conditions
+ *out = make([]CertServiceIssuerCondition, len(*in))
+ for i := range *in {
+ (*in)[i].DeepCopyInto(&(*out)[i])
+ }
+ }
+}
+
+// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertServiceIssuerStatus.
+func (in *CertServiceIssuerStatus) DeepCopy() *CertServiceIssuerStatus {
+ if in == nil {
+ return nil
+ }
+ out := new(CertServiceIssuerStatus)
+ in.DeepCopyInto(out)
+ return out
+}
diff --git a/certServiceK8sExternalProvider/src/api/certservice_issuer_crd_schema.go b/certServiceK8sExternalProvider/src/api/certservice_issuer_crd_schema.go
new file mode 100644
index 00000000..f829ae54
--- /dev/null
+++ b/certServiceK8sExternalProvider/src/api/certservice_issuer_crd_schema.go
@@ -0,0 +1,140 @@
+/*
+ * ============LICENSE_START=======================================================
+ * oom-certservice-k8s-external-provider
+ * ================================================================================
+ * Copyright (c) 2019 Smallstep Labs, Inc.
+ * Modifications copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * This source code was copied from the following git repository:
+ * https://github.com/smallstep/step-issuer
+ * The source code was modified for usage in the ONAP project.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+
+
+package api
+
+import (
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+func init() {
+ SchemeBuilder.Register(&CertServiceIssuer{}, &CertServiceIssuerList{})
+}
+
+// CertServiceIssuerSpec defines the desired state of CertServiceIssuer
+type CertServiceIssuerSpec struct {
+ // URL is the base URL for the CertService certificates instance.
+ URL string `json:"url"`
+
+ // KeyRef is a reference to a Secret containing the provisioner
+ // password used to decrypt the provisioner private key.
+ KeyRef SecretKeySelector `json:"keyRef"`
+}
+
+// CertServiceIssuerStatus defines the observed state of CertServiceIssuer
+type CertServiceIssuerStatus struct {
+ // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
+ // Important: Run "make" to regenerate code after modifying this file
+
+ // +optional
+ Conditions []CertServiceIssuerCondition `json:"conditions,omitempty"`
+}
+
+// +kubebuilder:object:root=true
+
+// CertServiceIssuer is the Schema for the certserviceissuers API
+// +kubebuilder:subresource:status
+type CertServiceIssuer struct {
+ metav1.TypeMeta `json:",inline"`
+ metav1.ObjectMeta `json:"metadata,omitempty"`
+
+ Spec CertServiceIssuerSpec `json:"spec,omitempty"`
+ Status CertServiceIssuerStatus `json:"status,omitempty"`
+}
+
+// +kubebuilder:object:root=true
+
+// CertServiceIssuerList contains a list of CertServiceIssuer
+type CertServiceIssuerList struct {
+ metav1.TypeMeta `json:",inline"`
+ metav1.ListMeta `json:"metadata,omitempty"`
+ Items []CertServiceIssuer `json:"items"`
+}
+
+// SecretKeySelector contains the reference to a secret.
+type SecretKeySelector struct {
+ // The name of the secret in the pod's namespace to select from.
+ Name string `json:"name"`
+
+ // The key of the secret to select from. Must be a valid secret key.
+ // +optional
+ Key string `json:"key,omitempty"`
+}
+
+// ConditionType represents a CertServiceIssuer condition type.
+// +kubebuilder:validation:Enum=Ready
+type ConditionType string
+
+const (
+ // ConditionReady indicates that a CertServiceIssuer is ready for use.
+ ConditionReady ConditionType = "Ready"
+)
+
+// ConditionStatus represents a condition's status.
+// +kubebuilder:validation:Enum=True;False;Unknown
+type ConditionStatus string
+
+// These are valid condition statuses. "ConditionTrue" means a resource is in
+// the condition; "ConditionFalse" means a resource is not in the condition;
+// "ConditionUnknown" means kubernetes can't decide if a resource is in the
+// condition or not. In the future, we could add other intermediate
+// conditions, e.g. ConditionDegraded.
+const (
+ // ConditionTrue represents the fact that a given condition is true
+ ConditionTrue ConditionStatus = "True"
+
+ // ConditionFalse represents the fact that a given condition is false
+ ConditionFalse ConditionStatus = "False"
+
+ // ConditionUnknown represents the fact that a given condition is unknown
+ ConditionUnknown ConditionStatus = "Unknown"
+)
+
+// CertServiceIssuerCondition contains condition information for the CertService issuer.
+type CertServiceIssuerCondition struct {
+ // Type of the condition, currently ('Ready').
+ Type ConditionType `json:"type"`
+
+ // Status of the condition, one of ('True', 'False', 'Unknown').
+ // +kubebuilder:validation:Enum=True;False;Unknown
+ Status ConditionStatus `json:"status"`
+
+ // LastTransitionTime is the timestamp corresponding to the last status
+ // change of this condition.
+ // +optional
+ LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"`
+
+ // Reason is a brief machine readable explanation for the condition's last
+ // transition.
+ // +optional
+ Reason string `json:"reason,omitempty"`
+
+ // Message is a human readable description of the details of the last
+ // transition, complementing reason.
+ // +optional
+ Message string `json:"message,omitempty"`
+}
diff --git a/certServiceK8sExternalProvider/src/api/groupversion_info.go b/certServiceK8sExternalProvider/src/api/groupversion_info.go
new file mode 100644
index 00000000..ebb76424
--- /dev/null
+++ b/certServiceK8sExternalProvider/src/api/groupversion_info.go
@@ -0,0 +1,43 @@
+/*
+ * ============LICENSE_START=======================================================
+ * oom-certservice-k8s-external-provider
+ * ================================================================================
+ * Copyright (c) 2019 Smallstep Labs, Inc.
+ * Modifications copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * This source code was copied from the following git repository:
+ * https://github.com/smallstep/step-issuer
+ * The source code was modified for usage in the ONAP project.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+
+package api
+
+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: "certmanager.onap.org", Version: "v1beta1"}
+
+ // 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
+)
diff --git a/certServiceK8sExternalProvider/src/certservice-controller/certificaterequest_reconciler.go b/certServiceK8sExternalProvider/src/certservice-controller/certificaterequest_reconciler.go
new file mode 100644
index 00000000..1a917e1b
--- /dev/null
+++ b/certServiceK8sExternalProvider/src/certservice-controller/certificaterequest_reconciler.go
@@ -0,0 +1,162 @@
+/*
+ * ============LICENSE_START=======================================================
+ * oom-certservice-k8s-external-provider
+ * ================================================================================
+ * Copyright 2019 The cert-manager authors.
+ * Modifications copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * This source code was copied from the following git repository:
+ * https://github.com/smallstep/step-issuer
+ * The source code was modified for usage in the ONAP project.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+package certservice_controller
+
+import (
+ "context"
+ "fmt"
+ "onap.org/oom-certservice/k8s-external-provider/src/api"
+ provisioners "onap.org/oom-certservice/k8s-external-provider/src/certservice-provisioner"
+
+ "github.com/go-logr/logr"
+ apiutil "github.com/jetstack/cert-manager/pkg/api/util"
+ cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha2"
+ cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1"
+ core "k8s.io/api/core/v1"
+ apierrors "k8s.io/apimachinery/pkg/api/errors"
+ "k8s.io/apimachinery/pkg/types"
+ "k8s.io/client-go/tools/record"
+ ctrl "sigs.k8s.io/controller-runtime"
+ "sigs.k8s.io/controller-runtime/pkg/client"
+)
+
+// CertificateRequestReconciler reconciles a CertServiceIssuer object.
+type CertificateRequestReconciler struct {
+ client.Client
+ Log logr.Logger
+ Recorder record.EventRecorder
+}
+
+// Reconcile will read and validate a CertServiceIssuer resource associated to the
+// CertificateRequest resource, and it will sign the CertificateRequest with the
+// provisioner in the CertServiceIssuer.
+func (r *CertificateRequestReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
+ ctx := context.Background()
+ log := r.Log.WithValues("certificaterequest", req.NamespacedName)
+
+ // Fetch the CertificateRequest resource being reconciled.
+ // Just ignore the request if the certificate request has been deleted.
+ cr := new(cmapi.CertificateRequest)
+ if err := r.Client.Get(ctx, req.NamespacedName, cr); err != nil {
+ if apierrors.IsNotFound(err) {
+ return ctrl.Result{}, nil
+ }
+
+ log.Error(err, "failed to retrieve CertificateRequest resource")
+ return ctrl.Result{}, err
+ }
+
+ // Check the CertificateRequest's issuerRef and if it does not match the api
+ // group name, log a message at a debug level and stop processing.
+ if cr.Spec.IssuerRef.Group != "" && cr.Spec.IssuerRef.Group != api.GroupVersion.Group {
+ log.V(4).Info("resource does not specify an issuerRef group name that we are responsible for", "group", cr.Spec.IssuerRef.Group)
+ return ctrl.Result{}, nil
+ }
+
+ // If the certificate data is already set then we skip this request as it
+ // has already been completed in the past.
+ if len(cr.Status.Certificate) > 0 {
+ log.V(4).Info("existing certificate data found in status, skipping already completed CertificateRequest")
+ return ctrl.Result{}, nil
+ }
+
+ // Fetch the CertServiceIssuer resource
+ iss := api.CertServiceIssuer{}
+ issNamespaceName := types.NamespacedName{
+ Namespace: req.Namespace,
+ Name: cr.Spec.IssuerRef.Name,
+ }
+ if err := r.Client.Get(ctx, issNamespaceName, &iss); err != nil {
+ log.Error(err, "failed to retrieve CertServiceIssuer resource", "namespace", req.Namespace, "name", cr.Spec.IssuerRef.Name)
+ _ = r.setStatus(ctx, cr, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to retrieve CertServiceIssuer resource %s: %v", issNamespaceName, err)
+ return ctrl.Result{}, err
+ }
+
+ // Check if the CertServiceIssuer resource has been marked Ready
+ if !certServiceIssuerHasCondition(iss, api.CertServiceIssuerCondition{Type: api.ConditionReady, Status: api.ConditionTrue}) {
+ err := fmt.Errorf("resource %s is not ready", issNamespaceName)
+ log.Error(err, "failed to retrieve CertServiceIssuer resource", "namespace", req.Namespace, "name", cr.Spec.IssuerRef.Name)
+ _ = r.setStatus(ctx, cr, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "CertServiceIssuer resource %s is not Ready", issNamespaceName)
+ return ctrl.Result{}, err
+ }
+
+ // Load the provisioner that will sign the CertificateRequest
+ provisioner, ok := provisioners.Load(issNamespaceName)
+ if !ok {
+ err := fmt.Errorf("provisioner %s not found", issNamespaceName)
+ log.Error(err, "failed to provisioner for CertServiceIssuer resource")
+ _ = r.setStatus(ctx, cr, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonPending, "Failed to load provisioner for CertServiceIssuer resource %s", issNamespaceName)
+ return ctrl.Result{}, err
+ }
+
+ // Sign CertificateRequest
+ signedPEM, trustedCAs, err := provisioner.Sign(ctx, cr)
+ if err != nil {
+ log.Error(err, "failed to sign certificate request")
+ return ctrl.Result{}, r.setStatus(ctx, cr, cmmeta.ConditionFalse, cmapi.CertificateRequestReasonFailed, "Failed to sign certificate request: %v", err)
+ }
+ cr.Status.Certificate = signedPEM
+ cr.Status.CA = trustedCAs
+
+ return ctrl.Result{}, r.setStatus(ctx, cr, cmmeta.ConditionTrue, cmapi.CertificateRequestReasonIssued, "Certificate issued")
+}
+
+// SetupWithManager initializes the CertificateRequest controller into the
+// controller runtime.
+func (r *CertificateRequestReconciler) SetupWithManager(mgr ctrl.Manager) error {
+ return ctrl.NewControllerManagedBy(mgr).
+ For(&cmapi.CertificateRequest{}).
+ Complete(r)
+}
+
+// certServiceIssuerHasCondition will return true if the given CertServiceIssuer resource has
+// a condition matching the provided CertServiceIssuerCondition. Only the Type and
+// Status field will be used in the comparison, meaning that this function will
+// return 'true' even if the Reason, Message and LastTransitionTime fields do
+// not match.
+func certServiceIssuerHasCondition(iss api.CertServiceIssuer, c api.CertServiceIssuerCondition) bool {
+ existingConditions := iss.Status.Conditions
+ for _, cond := range existingConditions {
+ if c.Type == cond.Type && c.Status == cond.Status {
+ return true
+ }
+ }
+ return false
+}
+
+func (r *CertificateRequestReconciler) setStatus(ctx context.Context, cr *cmapi.CertificateRequest, status cmmeta.ConditionStatus, reason, message string, args ...interface{}) error {
+ completeMessage := fmt.Sprintf(message, args...)
+ apiutil.SetCertificateRequestCondition(cr, cmapi.CertificateRequestConditionReady, status, reason, completeMessage)
+
+ // Fire an Event to additionally inform users of the change
+ eventType := core.EventTypeNormal
+ if status == cmmeta.ConditionFalse {
+ eventType = core.EventTypeWarning
+ }
+ r.Recorder.Event(cr, eventType, reason, completeMessage)
+
+ return r.Client.Status().Update(ctx, cr)
+}
diff --git a/certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_reconciler.go b/certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_reconciler.go
new file mode 100644
index 00000000..d5be11e8
--- /dev/null
+++ b/certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_reconciler.go
@@ -0,0 +1,125 @@
+/*
+ * ============LICENSE_START=======================================================
+ * oom-certservice-k8s-external-provider
+ * ================================================================================
+ * Copyright (c) 2019 Smallstep Labs, Inc.
+ * Modifications copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * This source code was copied from the following git repository:
+ * https://github.com/smallstep/step-issuer
+ * The source code was modified for usage in the ONAP project.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+
+package certservice_controller
+
+import (
+ "context"
+ "fmt"
+ "github.com/go-logr/logr"
+ core "k8s.io/api/core/v1"
+ apierrors "k8s.io/apimachinery/pkg/api/errors"
+ "k8s.io/apimachinery/pkg/types"
+ "k8s.io/client-go/tools/record"
+ "k8s.io/utils/clock"
+ "onap.org/oom-certservice/k8s-external-provider/src/api"
+ provisioners "onap.org/oom-certservice/k8s-external-provider/src/certservice-provisioner"
+ ctrl "sigs.k8s.io/controller-runtime"
+ "sigs.k8s.io/controller-runtime/pkg/client"
+)
+
+// CertServiceIssuerReconciler reconciles a CertServiceIssuer object
+type CertServiceIssuerReconciler struct {
+ client.Client
+ Log logr.Logger
+ Clock clock.Clock
+ Recorder record.EventRecorder
+}
+
+// Reconcile will read and validate the CertServiceIssuer resources, it will set the
+// status condition ready to true if everything is right.
+func (r *CertServiceIssuerReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
+ ctx := context.Background()
+ log := r.Log.WithValues("certservice-issuer-controller", req.NamespacedName)
+
+ iss := new(api.CertServiceIssuer)
+ if err := r.Client.Get(ctx, req.NamespacedName, iss); err != nil {
+ log.Error(err, "failed to retrieve CertServiceIssuer resource")
+ return ctrl.Result{}, client.IgnoreNotFound(err)
+ }
+
+ statusReconciler := newStatusReconciler(r, iss, log)
+ if err := validateCertServiceIssuerSpec(iss.Spec); err != nil {
+ log.Error(err, "failed to validate CertServiceIssuer resource")
+ statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Validation", "Failed to validate resource: %v", err)
+ return ctrl.Result{}, err
+ }
+
+ // Fetch the provisioner password
+ var secret core.Secret
+ secretNamespaceName := types.NamespacedName{
+ Namespace: req.Namespace,
+ Name: iss.Spec.KeyRef.Name,
+ }
+ if err := r.Client.Get(ctx, secretNamespaceName, &secret); err != nil {
+ log.Error(err, "failed to retrieve CertServiceIssuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
+ if apierrors.IsNotFound(err) {
+ statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "NotFound", "Failed to retrieve provisioner secret: %v", err)
+ } else {
+ statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Error", "Failed to retrieve provisioner secret: %v", err)
+ }
+ return ctrl.Result{}, err
+ }
+ password, ok := secret.Data[iss.Spec.KeyRef.Key]
+ if !ok {
+ err := fmt.Errorf("secret %s does not contain key %s", secret.Name, iss.Spec.KeyRef.Key)
+ log.Error(err, "failed to retrieve CertServiceIssuer provisioner secret", "namespace", secretNamespaceName.Namespace, "name", secretNamespaceName.Name)
+ statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "NotFound", "Failed to retrieve provisioner secret: %v", err)
+ return ctrl.Result{}, err
+ }
+
+ // Initialize and store the provisioner
+ p, err := provisioners.New(iss, password)
+ if err != nil {
+ log.Error(err, "failed to initialize provisioner")
+ statusReconciler.UpdateNoError(ctx, api.ConditionFalse, "Error", "failed initialize provisioner")
+ return ctrl.Result{}, err
+ }
+ provisioners.Store(req.NamespacedName, p)
+
+ return ctrl.Result{}, statusReconciler.Update(ctx, api.ConditionTrue, "Verified", "CertServiceIssuer verified and ready to sign certificates")
+}
+
+// SetupWithManager initializes the CertServiceIssuer controller into the controller
+// runtime.
+func (r *CertServiceIssuerReconciler) SetupWithManager(mgr ctrl.Manager) error {
+ return ctrl.NewControllerManagedBy(mgr).
+ For(&api.CertServiceIssuer{}).
+ Complete(r)
+}
+
+func validateCertServiceIssuerSpec(s api.CertServiceIssuerSpec) error {
+ switch {
+ case s.URL == "":
+ return fmt.Errorf("spec.url cannot be empty")
+ case s.KeyRef.Name == "":
+ return fmt.Errorf("spec.keyRef.name cannot be empty")
+ case s.KeyRef.Key == "":
+ return fmt.Errorf("spec.keyRef.key cannot be empty")
+ default:
+ return nil
+ }
+}
diff --git a/certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_status_reconciler.go b/certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_status_reconciler.go
new file mode 100644
index 00000000..c01ae85c
--- /dev/null
+++ b/certServiceK8sExternalProvider/src/certservice-controller/certservice_issuer_status_reconciler.go
@@ -0,0 +1,115 @@
+/*
+ * ============LICENSE_START=======================================================
+ * oom-certservice-k8s-external-provider
+ * ================================================================================
+ * Copyright (c) 2019 Smallstep Labs, Inc.
+ * Modifications copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * This source code was copied from the following git repository:
+ * https://github.com/smallstep/step-issuer
+ * The source code was modified for usage in the ONAP project.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
+
+
+package certservice_controller
+
+import (
+ "context"
+ "fmt"
+ "github.com/go-logr/logr"
+ core "k8s.io/api/core/v1"
+ meta "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "onap.org/oom-certservice/k8s-external-provider/src/api"
+)
+
+type certServiceIssuerStatusReconciler struct {
+ *CertServiceIssuerReconciler
+ issuer *api.CertServiceIssuer
+ logger logr.Logger
+}
+
+func newStatusReconciler(r *CertServiceIssuerReconciler, iss *api.CertServiceIssuer, log logr.Logger) *certServiceIssuerStatusReconciler {
+ return &certServiceIssuerStatusReconciler{
+ CertServiceIssuerReconciler: r,
+ issuer: iss,
+ logger: log,
+ }
+}
+
+func (r *certServiceIssuerStatusReconciler) Update(ctx context.Context, status api.ConditionStatus, reason, message string, args ...interface{}) error {
+ completeMessage := fmt.Sprintf(message, args...)
+ r.setCondition(status, reason, completeMessage)
+
+ // Fire an Event to additionally inform users of the change
+ eventType := core.EventTypeNormal
+ if status == api.ConditionFalse {
+ eventType = core.EventTypeWarning
+ }
+ r.Recorder.Event(r.issuer, eventType, reason, completeMessage)
+
+ return r.Client.Status().Update(ctx, r.issuer)
+}
+
+func (r *certServiceIssuerStatusReconciler) UpdateNoError(ctx context.Context, status api.ConditionStatus, reason, message string, args ...interface{}) {
+ if err := r.Update(ctx, status, reason, message, args...); err != nil {
+ r.logger.Error(err, "failed to update", "status", status, "reason", reason)
+ }
+}
+
+// setCondition will set a 'condition' on the given api.CertServiceIssuer resource.
+//
+// - If no condition of the same type already exists, the condition will be
+// inserted with the LastTransitionTime set to the current time.
+// - If a condition of the same type and state already exists, the condition
+// will be updated but the LastTransitionTime will not be modified.
+// - If a condition of the same type and different state already exists, the
+// condition will be updated and the LastTransitionTime set to the current
+// time.
+func (r *certServiceIssuerStatusReconciler) setCondition(status api.ConditionStatus, reason, message string) {
+ now := meta.NewTime(r.Clock.Now())
+ c := api.CertServiceIssuerCondition{
+ Type: api.ConditionReady,
+ Status: status,
+ Reason: reason,
+ Message: message,
+ LastTransitionTime: &now,
+ }
+
+ // Search through existing conditions
+ for idx, cond := range r.issuer.Status.Conditions {
+ // Skip unrelated conditions
+ if cond.Type != api.ConditionReady {
+ continue
+ }
+
+ // If this update doesn't contain a state transition, we don't update
+ // the conditions LastTransitionTime to Now()
+ if cond.Status == status {
+ c.LastTransitionTime = cond.LastTransitionTime
+ } else {
+ r.logger.Info("found status change for CertServiceIssuer condition; setting lastTransitionTime", "condition", cond.Type, "old_status", cond.Status, "new_status", status, "time", now.Time)
+ }
+
+ // Overwrite the existing condition
+ r.issuer.Status.Conditions[idx] = c
+ return
+ }
+
+ // If we've not found an existing condition of this type, we simply insert
+ // the new condition into the slice.
+ r.issuer.Status.Conditions = append(r.issuer.Status.Conditions, c)
+ r.logger.Info("setting lastTransitionTime for CertServiceIssuer condition", "condition", api.ConditionReady, "time", now.Time)
+}
diff --git a/certServiceK8sExternalProvider/src/certservice-provisioner/certservice-provisioner.go b/certServiceK8sExternalProvider/src/certservice-provisioner/certservice-provisioner.go
index 5648082a..627c2d42 100644
--- a/certServiceK8sExternalProvider/src/certservice-provisioner/certservice-provisioner.go
+++ b/certServiceK8sExternalProvider/src/certservice-provisioner/certservice-provisioner.go
@@ -1,7 +1,164 @@
-package certservice_provisioner
+/*
+ * ============LICENSE_START=======================================================
+ * oom-certservice-k8s-external-provider
+ * ================================================================================
+ * Copyright (c) 2019 Smallstep Labs, Inc.
+ * Modifications copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * This source code was copied from the following git repository:
+ * https://github.com/smallstep/step-issuer
+ * The source code was modified for usage in the ONAP project.
+ * ================================================================================
+ * 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.
+ * ============LICENSE_END=========================================================
+ */
-import "fmt"
+package provisioners
-func SignCertificate() {
- fmt.Println("--> This method is currently a stub.")
+import (
+ "bytes"
+ "context"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/pem"
+ "fmt"
+ certmanager "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha2"
+ "k8s.io/apimachinery/pkg/types"
+ "onap.org/oom-certservice/k8s-external-provider/src/api"
+ ctrl "sigs.k8s.io/controller-runtime"
+ "sync"
+)
+
+var collection = new(sync.Map)
+
+type CertServiceCA struct {
+ name string
+ url string
+ key []byte
+}
+
+func New(iss *api.CertServiceIssuer, key []byte) (*CertServiceCA, error) {
+
+ ca := CertServiceCA{}
+ ca.name = iss.Name
+ ca.url = iss.Spec.URL
+ ca.key = key
+
+ log := ctrl.Log.WithName("certservice-provisioner")
+ log.Info("Configuring CA: ", "name", ca.name, "url", ca.url, "key", ca.key)
+
+ return &ca, nil
+}
+
+func Load(namespacedName types.NamespacedName) (*CertServiceCA, bool) {
+ v, ok := collection.Load(namespacedName)
+ if !ok {
+ return nil, ok
+ }
+ p, ok := v.(*CertServiceCA)
+ return p, ok
+}
+
+func Store(namespacedName types.NamespacedName, provisioner *CertServiceCA) {
+ collection.Store(namespacedName, provisioner)
+}
+
+func (ca *CertServiceCA) Sign(ctx context.Context, cr *certmanager.CertificateRequest) ([]byte, []byte, error) {
+ log := ctrl.Log.WithName("certservice-provisioner")
+ log.Info("Signing certificate: ", "cert-name", cr.Name)
+
+ key, _ := base64.RawStdEncoding.DecodeString(string(ca.key))
+ log.Info("CA: ", "name", ca.name, "url", ca.url, "key", key)
+
+ crPEM := cr.Spec.CSRPEM
+ csrBase64 := crPEM
+ log.Info("Csr PEM: ", "bytes", csrBase64)
+
+ csr, err := decodeCSR(crPEM)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ cert := x509.Certificate{}
+ cert.Raw = csr.Raw
+
+ // TODO
+ // write here code which will call CertServiceCA and sign CSR
+ // END
+
+ encodedPEM, err := encodeX509(&cert)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ signedPEM := encodedPEM
+ trustedCA := encodedPEM
+
+ log.Info("Successfully signed: ", "cert-name", cr.Name)
+ log.Info("Signed cert PEM: ", "bytes", signedPEM)
+ log.Info("Trusted CA PEM: ", "bytes", trustedCA)
+
+ return signedPEM, trustedCA, nil
+}
+
+// TODO JM utility methods - will be used in "real" implementation
+
+// decodeCSR decodes a certificate request in PEM format and returns the
+func decodeCSR(data []byte) (*x509.CertificateRequest, error) {
+ block, rest := pem.Decode(data)
+ if block == nil || len(rest) > 0 {
+ return nil, fmt.Errorf("unexpected CSR PEM on sign request")
+ }
+ if block.Type != "CERTIFICATE REQUEST" {
+ return nil, fmt.Errorf("PEM is not a certificate request")
+ }
+ csr, err := x509.ParseCertificateRequest(block.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("error parsing certificate request: %v", err)
+ }
+ if err := csr.CheckSignature(); err != nil {
+ return nil, fmt.Errorf("error checking certificate request signature: %v", err)
+ }
+ return csr, nil
+}
+
+// encodeX509 will encode a *x509.Certificate into PEM format.
+func encodeX509(cert *x509.Certificate) ([]byte, error) {
+ caPem := bytes.NewBuffer([]byte{})
+ err := pem.Encode(caPem, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
+ if err != nil {
+ return nil, err
+ }
+ return caPem.Bytes(), nil
+}
+
+// generateSubject returns the first SAN that is not 127.0.0.1 or localhost. The
+// CSRs generated by the Certificate resource have always those SANs. If no SANs
+// are available `certservice-issuer-certificate` will be used as a subject is always
+// required.
+func generateSubject(sans []string) string {
+ if len(sans) == 0 {
+ return "certservice-issuer-certificate"
+ }
+ for _, s := range sans {
+ if s != "127.0.0.1" && s != "localhost" {
+ return s
+ }
+ }
+ return sans[0]
+}
+
+func decode(cert string) []byte {
+ bytes, _ := base64.RawStdEncoding.DecodeString(cert)
+ return bytes
}