Skip to content

Commit

Permalink
feat: Add connection status to registry integration secret (#29)
Browse files Browse the repository at this point in the history
Change-Id: I48fd38f0aa74235bd7266244e577776d7254d07d
  • Loading branch information
zmotso committed Dec 8, 2023
1 parent bf8da1a commit 612d1ea
Show file tree
Hide file tree
Showing 2 changed files with 164 additions and 10 deletions.
67 changes: 58 additions & 9 deletions controllers/integrationsecret/integrationsecret_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ package integrationsecret

import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"

"github.com/go-resty/resty/v2"
Expand Down Expand Up @@ -130,29 +134,37 @@ func (r *ReconcileIntegrationSecret) updateConnectionAnnotation(ctx context.Cont

func checkConnection(ctx context.Context, secret *corev1.Secret) error {
var (
url string
req *resty.Request
path string
req *resty.Request
)

switch secret.GetLabels()[integrationSecretTypeLabel] {
case "sonarqube":
url = "/api/system/ping"
path = "/api/system/ping"
req = newRequestWithAuth(ctx, secret)
case "nexus":
url = "/service/rest/v1/status"
path = "/service/rest/v1/status"
req = newRequestWithAuth(ctx, secret)
case "dependency-track":
url = "/v1/team/self"
path = "/v1/team/self"
req = newRequest(ctx, string(secret.Data["url"])).SetHeader("X-Api-Key", string(secret.Data["token"]))
case "defectdojo":
url = "/api/v2/user_profile"
path = "/api/v2/user_profile"
req = newRequest(ctx, string(secret.Data["url"])).SetHeader("Authorization", "Token "+string(secret.Data["token"]))
case "registry":
// docker registry specification endpoint https://github.com/opencontainers/distribution-spec/blob/v1.0.1/spec.md#endpoints
path = "/v2"

var err error
if req, err = newRegistryRequest(ctx, secret); err != nil {
return err
}
default:
url = "/"
path = "/"
req = newRequest(ctx, string(secret.Data["url"]))
}

resp, err := req.Get(url)
resp, err := req.Get(path)
if err != nil {
return fmt.Errorf("%w", err)
}
Expand All @@ -175,7 +187,44 @@ func newRequestWithAuth(ctx context.Context, secret *corev1.Secret) *resty.Reque
}

func newRequest(ctx context.Context, url string) *resty.Request {
return resty.New().SetHostURL(url).SetTimeout(time.Second * 5).R().SetContext(ctx)
return resty.New().
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
SetHostURL(url).
SetTimeout(time.Second * 5).
R().
SetContext(ctx)
}

type registryAuth struct {
Username string `json:"username"`
Password string `json:"password"`
}

type registryConfig struct {
Auths map[string]registryAuth `json:"auths"`
}

func newRegistryRequest(ctx context.Context, secret *corev1.Secret) (*resty.Request, error) {
rawConf := secret.Data[".dockerconfigjson"]

if len(rawConf) == 0 {
return nil, fmt.Errorf("no .dockerconfigjson key in secret %s", secret.Name)
}

var conf registryConfig
if err := json.Unmarshal(rawConf, &conf); err != nil {
return nil, fmt.Errorf("failed to unmarshal .dockerconfigjson: %w", err)
}

for url, auth := range conf.Auths {
if !strings.HasPrefix(url, "https://") {
url = "https://" + url
}

return newRequest(ctx, url).SetBasicAuth(auth.Username, auth.Password), nil
}

return nil, errors.New("no auths in .dockerconfigjson")
}

func hasIntegrationSecretLabelLabel(object client.Object) bool {
Expand Down
107 changes: 106 additions & 1 deletion controllers/integrationsecret/integrationsecret_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func TestReconcileIntegrationSecret_Reconcile(t *testing.T) {
t.Parallel()

ns := "default"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.String(), "success") {
w.WriteHeader(http.StatusOK)
return
Expand Down Expand Up @@ -178,6 +178,111 @@ func TestReconcileIntegrationSecret_Reconcile(t *testing.T) {
wantErr: require.NoError,
wantConAnnotation: "true",
},
{
name: "success registry",
secretName: "registry",
client: func(t *testing.T) client.Client {
return fake.NewClientBuilder().WithScheme(s).WithObjects(
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: "registry",
Labels: map[string]string{
integrationSecretTypeLabel: "registry",
},
},
Type: corev1.SecretTypeDockerConfigJson,
Data: map[string][]byte{
".dockerconfigjson": []byte(`{"auths":{"` + server.URL + `/success":{"username":"user1", "password":"password1"}}}`),
},
},
).Build()
},
wantRes: reconcile.Result{
RequeueAfter: successConnectionRequeueTime,
},
wantErr: require.NoError,
wantConAnnotation: "true",
},
{
name: "registry without auth",
secretName: "registry",
client: func(t *testing.T) client.Client {
return fake.NewClientBuilder().WithScheme(s).WithObjects(
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: "registry",
Labels: map[string]string{
integrationSecretTypeLabel: "registry",
},
},
Type: corev1.SecretTypeDockerConfigJson,
Data: map[string][]byte{
".dockerconfigjson": []byte("{}"),
},
},
).Build()
},
wantRes: reconcile.Result{
RequeueAfter: failConnectionRequeueTime,
},
wantErr: require.NoError,
wantConAnnotation: "false",
wantConErrAnnotation: "no auths in .dockerconfigjson",
},
{
name: "registry with invalid config",
secretName: "registry",
client: func(t *testing.T) client.Client {
return fake.NewClientBuilder().WithScheme(s).WithObjects(
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: "registry",
Labels: map[string]string{
integrationSecretTypeLabel: "registry",
},
},
Type: corev1.SecretTypeDockerConfigJson,
Data: map[string][]byte{
".dockerconfigjson": []byte("not a json"),
},
},
).Build()
},
wantRes: reconcile.Result{
RequeueAfter: failConnectionRequeueTime,
},
wantErr: require.NoError,
wantConAnnotation: "false",
wantConErrAnnotation: "failed to unmarshal .dockerconfigjson",
},
{
name: "registry without .dockerconfigjson",
secretName: "registry",
client: func(t *testing.T) client.Client {
return fake.NewClientBuilder().WithScheme(s).WithObjects(
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: ns,
Name: "registry",
Labels: map[string]string{
integrationSecretTypeLabel: "registry",
},
},
Type: corev1.SecretTypeDockerConfigJson,
Data: map[string][]byte{},
},
).Build()
},
wantRes: reconcile.Result{
RequeueAfter: failConnectionRequeueTime,
},
wantErr: require.NoError,
wantConAnnotation: "false",
wantConErrAnnotation: "no .dockerconfigjson key in secret",
},
{
name: "not reachable server",
secretName: "integration-secret",
Expand Down

0 comments on commit 612d1ea

Please sign in to comment.