diff --git a/.github/workflows/ci-actions.yml b/.github/workflows/ci-actions.yml new file mode 100644 index 0000000..6e0b1f5 --- /dev/null +++ b/.github/workflows/ci-actions.yml @@ -0,0 +1,47 @@ +name: Test GitHub Actions + +# yamllint disable-line rule:truthy +on: + push: + branches: + - main + paths: + - .github/workflows/** + pull_request: + branches: + - '**' + paths: + - .github/workflows/** + types: + - opened + - synchronize + - reopened + - ready_for_review + +concurrency: + group: ${{ github.workflow }}@${{ github.event.pull_request.head.label || github.head_ref || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + zizmor: + name: Lint GitHub Actions + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run zizmor + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 + with: + advanced-security: false + inputs: ./.github/ + online-audits: false # https://github.com/zizmorcore/zizmor/issues/1350 + persona: pedantic + + - name: Run actionlint + uses: rhysd/actionlint@914e7df21a07ef503a81201c76d2b11c789d3fca # v1.7.12 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc9995b..3fcabcc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,11 +9,16 @@ on: branches: - main +concurrency: + group: ${{ github.workflow }}@${{ github.event.pull_request.head.label || github.head_ref || github.ref }} + cancel-in-progress: true + permissions: contents: read jobs: lint: + name: Test and Lint App runs-on: ubuntu-latest permissions: contents: read diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f2c2e2b..45db911 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,10 @@ on: required: true default: dev +concurrency: + group: ${{ github.workflow }}@${{ github.event.pull_request.head.label || github.head_ref || github.ref }} + cancel-in-progress: true + permissions: contents: read @@ -21,10 +25,11 @@ env: jobs: build-and-push: + name: Build and Push to Container Registry runs-on: ubuntu-latest permissions: contents: read - packages: write + packages: write # required for publishing artifacts steps: - name: Checkout code @@ -46,11 +51,14 @@ jobs: - name: Compute image tag id: meta + env: + GITHUB_EVENT_NAME: ${{ github.event.name }} + GITHUB_EVENT_INPUTS_TAG: ${{ github.event.inputs.tag }} run: | - if ["${{ github.event.name }}" = "workflow_dispatch"]; then - echo "TAG=${{ github.event.inputs.tag }}" >> $GITHUB_OUTPUT + if [ "${GITHUB_EVENT_NAME}" = "workflow_dispatch" ]; then + echo "TAG=${GITHUB_EVENT_INPUTS_TAG}" >> "$GITHUB_OUTPUT" else - echo "TAG=${GITHUB_REF_NAME}" >> $GITHUB_OUTPUT + echo "TAG=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT" fi - name: Build and push with Bake @@ -61,4 +69,4 @@ jobs: env: REGISTRY: ${{ env.REGISTRY }} IMAGE_NAME: ${{ env.IMAGE_NAME }} - TAG: ${{ steps.meta.outputsk.TAG }} + TAG: ${{ steps.meta.outputs.TAG }} diff --git a/controllers/httproute_controller_test.go b/controllers/httproute_controller_test.go index e61bd2c..4f98fc9 100644 --- a/controllers/httproute_controller_test.go +++ b/controllers/httproute_controller_test.go @@ -12,37 +12,86 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" ) -func TestHTTPRouteWatcher_Lifecycle(t *testing.T) { - ctx := context.Background() +type testEnv struct { + client client.Client + reconciler *HTTPRouteWatcher + mu sync.Mutex + events []WebhookPayload + statusCode int + lastAuthHeader string +} + +func newTestEnv(t *testing.T, objs ...client.Object) *testEnv { + t.Helper() + + env := &testEnv{ + statusCode: http.StatusOK, + } - var mu sync.Mutex - var receivedEvents []WebhookPayload + // mock server + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + env.mu.Lock() + env.lastAuthHeader = r.Header.Get("Authorization") + code := env.statusCode + env.mu.Unlock() + + if code >= 400 { + w.WriteHeader(code) + return + } - // mock HTTP server for webhook calls - mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var payload WebhookPayload if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { t.Errorf("failed to decode webhook payload: %v", err) w.WriteHeader(http.StatusBadRequest) return } - mu.Lock() - receivedEvents = append(receivedEvents, payload) - mu.Unlock() + + env.mu.Lock() + env.events = append(env.events, payload) + env.mu.Unlock() w.WriteHeader(http.StatusOK) })) - defer mockServer.Close() + t.Cleanup(server.Close) // k8s client scheme := runtime.NewScheme() _ = clientgoscheme.AddToScheme(scheme) _ = gatewayv1.Install(scheme) + env.client = fake.NewClientBuilder(). + WithScheme(scheme). + WithObjects(objs...). + Build() + + env.reconciler = &HTTPRouteWatcher{ + Client: env.client, + ExternalAPIURL: server.URL, + } + + return env +} + +func (e *testEnv) recordedEvents() []WebhookPayload { + e.mu.Lock() + defer e.mu.Unlock() + out := make([]WebhookPayload, len(e.events)) + copy(out, e.events) + return out +} + +func TestHTTPRouteWatcher_Lifecycle(t *testing.T) { + ctx := context.Background() + route := &gatewayv1.HTTPRoute{ ObjectMeta: metav1.ObjectMeta{ Name: "my-route", @@ -57,70 +106,290 @@ func TestHTTPRouteWatcher_Lifecycle(t *testing.T) { }, } - fakeClient := fake.NewClientBuilder(). - WithScheme(scheme). - WithObjects(route). - Build() - - reconciler := &HTTPRouteWatcher{ - Client: fakeClient, - ExternalAPIURL: mockServer.URL, - } - + env := newTestEnv(t, route) req := ctrl.Request{ NamespacedName: types.NamespacedName{Name: "my-route", Namespace: "default"}, } // --- TEST: CREATE --- - if _, err := reconciler.Reconcile(ctx, req); err != nil { + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { // first reconcile registers the finalizer t.Fatalf("reconcile 1 failed: %v", err) } - - if _, err := reconciler.Reconcile(ctx, req); err != nil { + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { // second reconcile triggers the CREATED api call t.Fatalf("reconcile 2 failed: %v", err) } - if len(receivedEvents) != 1 || receivedEvents[0].Event != "CREATED" { - t.Fatalf("expected 1 CREATED event, got: %+v", receivedEvents) + events := env.recordedEvents() + if len(events) != 1 || events[0].Event != "CREATED" { + t.Fatalf("expected 1 CREATED event, got: %+v", events) + } + if len(events[0].Hostnames) != 1 || events[0].Hostnames[0] != "app.example.com" { + t.Fatalf("expected hostname app.example.com, got: %+v", events[0].Hostnames) } // --- TEST: SKIP NOOP --- - if _, err := reconciler.Reconcile(ctx, req); err != nil { - // status-only update should not trigger api calls + events = env.recordedEvents() + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { t.Fatalf("status reconcile failed: %v", err) } - if len(receivedEvents) != 1 { - t.Fatalf("expected no duplicate call on same generation, got %d events", len(receivedEvents)) + if len(events) != 1 { + t.Fatalf("expected no duplicate call on same generation, got %d events", len(events)) } // --- TEST: UPDATE --- var updatedRoute gatewayv1.HTTPRoute - _ = fakeClient.Get(ctx, req.NamespacedName, &updatedRoute) + _ = env.client.Get(ctx, req.NamespacedName, &updatedRoute) updatedRoute.Generation = 2 // API server increments generation updatedRoute.Spec.Hostnames = []gatewayv1.Hostname{"www.example.com"} - _ = fakeClient.Update(ctx, &updatedRoute) + _ = env.client.Update(ctx, &updatedRoute) - if _, err := reconciler.Reconcile(ctx, req); err != nil { + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { t.Fatalf("update reconcile failed: %v", err) } - if len(receivedEvents) != 2 || receivedEvents[1].Event != "UPDATED" { - t.Fatalf("expected UPDATED event, got %+v", receivedEvents) + events = env.recordedEvents() + if len(events) != 2 || events[1].Event != "UPDATED" { + t.Fatalf("expected UPDATED event, got: %+v", events) + } + if len(events[1].Hostnames) != 1 || events[1].Hostnames[0] != "www.example.com" { + t.Fatalf("expected updated hostname www.example.com, got: %+v", events[1].Hostnames) } // --- TEST: DELETE --- - _ = fakeClient.Get(ctx, req.NamespacedName, &updatedRoute) - if err := fakeClient.Delete(ctx, &updatedRoute); err != nil { - t.Fatalf("failed to delete route: %v", err) + _ = env.client.Get(ctx, req.NamespacedName, &updatedRoute) + if err := env.client.Delete(ctx, &updatedRoute); err != nil { + t.Fatalf("delete route failed: %v", err) } - if _, err := reconciler.Reconcile(ctx, req); err != nil { + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { t.Fatalf("delete reconcile failed: %v", err) } - if len(receivedEvents) != 3 || receivedEvents[2].Event != "DELETED" { - t.Fatalf("expected DELETED event, got: %+v", receivedEvents) + events = env.recordedEvents() + if len(events) != 3 || events[2].Event != "DELETED" { + t.Fatalf("expected DELETED event, got: %+v", events) + } +} + +func TestHTTPRouteWatcher_AnnotationRemoved_CleansUpFinalizer(t *testing.T) { + ctx := context.Background() + + route := &gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: "untracked-route", + Namespace: "default", + Finalizers: []string{finalizerName}, + Annotations: map[string]string{ + lastSyncedAnnotation: "1", + }, + }, + } + + env := newTestEnv(t, route) + req := ctrl.Request{ + NamespacedName: types.NamespacedName{Name: "untracked-route", Namespace: "default"}, + } + + // --- TEST: Remove finalizer without calling external API --- + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { + t.Fatalf("reconcile failed: %v", err) + } + + var updated gatewayv1.HTTPRoute + if err := env.client.Get(ctx, req.NamespacedName, &updated); err != nil { + t.Fatalf("failed to fetch updated route: %v", err) + } + if controllerutil.ContainsFinalizer(&updated, finalizerName) { + t.Fatalf("expected finalizer %q to be removed, still present: %v", finalizerName, updated.Finalizers) + } + if len(env.recordedEvents()) != 0 { + t.Fatalf("expected 0 API calls when annotation is missing, got: %+v", env.recordedEvents()) + } + + // --- TEST: noop when neither annotation nor finalizer are present --- + if _, err := env.reconciler.Reconcile(ctx, req); err != nil { + t.Fatalf("second reconcile failed: %v", err) + } +} + +func TestHTTPRouteWatcher_ErrorsAndAuth(t *testing.T) { + tests := []struct { + name string + route *gatewayv1.HTTPRoute + deleteBeforeSync bool + apiStatusCode int + apiToken string + overrideURL string + wantErr bool + wantFinalizerKept bool + wantAuthHeader string + }{ + { + name: "not found route cleanly ignores error", + route: nil, + apiStatusCode: http.StatusOK, + wantErr: false, + }, + { + name: "API 500 on create returns error and does not stamp generation", + route: &gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: "fail-create", + Namespace: "default", + Generation: 1, + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, + }, + }, + apiStatusCode: http.StatusInternalServerError, + wantErr: true, + wantFinalizerKept: true, + }, + { + name: "API 500 on delete returns error and keeps finalizer", + route: &gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: "fail-delete", + Namespace: "default", + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, + }, + }, + deleteBeforeSync: true, + apiStatusCode: http.StatusInternalServerError, + wantErr: true, + wantFinalizerKept: true, + }, + { + name: "invalid external URL returns request error", + route: &gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: "bad-url", + Namespace: "default", + Generation: 1, + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, + }, + }, + overrideURL: "://invalid-url", + wantErr: true, + wantFinalizerKept: true, + }, + { + name: "sends Bearer token when APIToken is configured", + route: &gatewayv1.HTTPRoute{ + ObjectMeta: metav1.ObjectMeta{ + Name: "auth-route", + Namespace: "default", + Generation: 1, + Finalizers: []string{finalizerName}, + Annotations: map[string]string{triggerAnnotation: "true"}, + }, + }, + apiStatusCode: http.StatusOK, + apiToken: "super-secret-token", + wantErr: false, + wantFinalizerKept: true, + wantAuthHeader: "Bearer super-secret-token", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + + var env *testEnv + req := ctrl.Request{ + NamespacedName: types.NamespacedName{Name: "missing-route", Namespace: "default"}, + } + + if tc.route != nil { + env = newTestEnv(t, tc.route) + req.Name = tc.route.Name + req.Namespace = tc.route.Namespace + } else { + env = newTestEnv(t) + } + + env.statusCode = tc.apiStatusCode + env.reconciler.APIToken = tc.apiToken + if tc.overrideURL != "" { + env.reconciler.ExternalAPIURL = tc.overrideURL + } + + if tc.deleteBeforeSync && tc.route != nil { + if err := env.client.Delete(ctx, tc.route); err != nil { + t.Fatalf("failed to mark route for deletion: %v", err) + } + } + + _, err := env.reconciler.Reconcile(ctx, req) + if (err != nil) != tc.wantErr { + t.Fatalf("Reconcile() error = %v, wantErr %v", err, tc.wantErr) + } + + if tc.wantAuthHeader != "" && env.lastAuthHeader != tc.wantAuthHeader { + t.Fatalf("Authorization header = %q, want %q", env.lastAuthHeader, tc.wantAuthHeader) + } + + if tc.route != nil { + var current gatewayv1.HTTPRoute + if err := env.client.Get(ctx, req.NamespacedName, ¤t); err != nil { + t.Fatalf("failed to get route after reconcile: %v", err) + } + + hasFinalizer := controllerutil.ContainsFinalizer(¤t, finalizerName) + if hasFinalizer != tc.wantFinalizerKept { + t.Fatalf("finalizer present = %v, want %v", hasFinalizer, tc.wantFinalizerKept) + } + + if tc.wantErr && current.Annotations[lastSyncedAnnotation] != "" { + t.Fatalf("expected lastSyncedAnnotation not to be stamped on failed API call, got %q", current.Annotations[lastSyncedAnnotation]) + } + } + }) + } +} + +func TestHTTPRouteWatcher_SetupWithManager(t *testing.T) { + // mock API server discovery endpoints + apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api": + _, _ = w.Write([]byte(`{"kind":"APIVersions","versions":["v1"]}`)) + case "/apis": + _, _ = w.Write([]byte(`{"kind":"APIGroupList","groups":[]}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(apiServer.Close) + + scheme := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(scheme); err != nil { + t.Fatalf("failed to add client-go scheme: %v", err) + } + if err := gatewayv1.Install(scheme); err != nil { + t.Fatalf("failed to install gatewayv1 scheme: %v", err) + } + + // disable metrics and probes to avoid port conflicts + mgr, err := ctrl.NewManager(&rest.Config{Host: apiServer.URL}, ctrl.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: "0"}, + HealthProbeBindAddress: "0", + }) + if err != nil { + t.Fatalf("failed to create manager: %v", err) + } + + reconciler := &HTTPRouteWatcher{ + Client: mgr.GetClient(), + } + if err := reconciler.SetupWithManager(mgr); err != nil { + t.Fatalf("SetupWithManager() unexpected error = %v", err) } }