From 7735f363f098a898029f0a725efdd89247fd5feb Mon Sep 17 00:00:00 2001 From: Timo Behrendt Date: Wed, 20 May 2026 20:27:59 +0200 Subject: [PATCH] feat: allow proxy provider to reference an outpost to be added to --- README.md | 2 + artifacts/examples/proxyProvider.yaml | 1 + pkg/apis/proxyprovider/v1alpha1/types.go | 1 + pkg/controllers/proxyprovider/controller.go | 59 ++++++ .../proxyprovider/controller_test.go | 168 +++++++++++++++++- .../v1alpha1/proxyproviderspec.go | 9 + pkg/generated/openapi/zz_generated.openapi.go | 13 +- 7 files changed, 245 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 82e5680..5172db3 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ spec: slug: application-example # The ID of the provider, which can be retrieved from e.g. the ProxyPRovider via "kubectl get pp proxy-provider-example -o jsonpath='{.status.pk}'" provider: 105 + # The ID of the outpost, which at current point in time, can only be retrieved from Authentik directly. This value can also not be updated. + outpost: e004ffe7-4af6-4ac1-9e9d-522354799e1f ``` ### PolicyBinding diff --git a/artifacts/examples/proxyProvider.yaml b/artifacts/examples/proxyProvider.yaml index 5de4a22..ad8053b 100644 --- a/artifacts/examples/proxyProvider.yaml +++ b/artifacts/examples/proxyProvider.yaml @@ -9,3 +9,4 @@ spec: authorization_flow: 16896c6d-b326-42d1-8d3f-93f32921962e invalidation_flow: 7acac1ef-19e3-4a6f-8d8d-14ca7031d184 external_host: https://example.t00n.de + outpost: e004ffe7-4af6-4ac1-9e9d-522354799e1f diff --git a/pkg/apis/proxyprovider/v1alpha1/types.go b/pkg/apis/proxyprovider/v1alpha1/types.go index f328cd4..9ccbea8 100644 --- a/pkg/apis/proxyprovider/v1alpha1/types.go +++ b/pkg/apis/proxyprovider/v1alpha1/types.go @@ -37,6 +37,7 @@ type ProxyProviderSpec struct { AuthorizationFlow string `json:"authorization_flow"` InvalidationFlow string `json:"invalidation_flow"` ExternalHost string `json:"external_host"` + Outpost string `json:"outpost"` } type ProxyProviderStatus struct { diff --git a/pkg/controllers/proxyprovider/controller.go b/pkg/controllers/proxyprovider/controller.go index f814fab..62fc597 100644 --- a/pkg/controllers/proxyprovider/controller.go +++ b/pkg/controllers/proxyprovider/controller.go @@ -166,6 +166,12 @@ func (c *ProxyProviderController) reconcileDelete(ctx context.Context, pp *v1alp return fmt.Errorf("error parsing PK: %v", err) } + err = c.reconcileOutpost(ctx, pp.Spec.Outpost, int32(pk), ReconcileOutpostModeRemove) + if err != nil { + return fmt.Errorf("error when calling `reconcileOutpost`: %w", err) + } + + // Delete ProxyProvider r, err := c.authentik.ProvidersApi.ProvidersProxyDestroy(ctx, int32(pk)).Execute() if err != nil { // This handles an edge-case, where when the ProxyProvider on Authentik has already been deleted, but the finalizer is still present. We just remove the finalizer and return. @@ -225,6 +231,11 @@ func (c *ProxyProviderController) reconcileCreate(ctx context.Context, pp *v1alp return fmt.Errorf("error when calling `ProvidersAPI.ProvidersProxyCreate`: %w with response %v", err, r) } + err = c.reconcileOutpost(ctx, pp.Spec.Outpost, resp.Pk, ReconcileOutpostModeAdd) + if err != nil { + return fmt.Errorf("error when calling `reconcileOutpost`: %w", err) + } + pp.Status.PK = strconv.Itoa(int(resp.Pk)) return c.updateProxyProviderStatus(ctx, pp) } @@ -244,3 +255,51 @@ func (c *ProxyProviderController) updateProxyProvider(ctx context.Context, pp *v } return nil } + +type ReconcileOutpostMode string + +const ( + ReconcileOutpostModeAdd ReconcileOutpostMode = "add" + ReconcileOutpostModeRemove ReconcileOutpostMode = "remove" +) + +func (c *ProxyProviderController) reconcileOutpost(ctx context.Context, outpostId string, providerPk int32, mode ReconcileOutpostMode) error { + logger := klog.LoggerWithValues(klog.FromContext(ctx), "outpostId", outpostId, "providerPk", providerPk, "mode", mode) + + outpost, r, err := c.authentik.OutpostsApi.OutpostsInstancesRetrieve(ctx, outpostId).Execute() + if err != nil { + return fmt.Errorf("error when calling `OutpostsAPI.OutpostsInstancesRetrieve`: %w with response %v", err, r) + } + updated := false + + switch mode { + case ReconcileOutpostModeAdd: + if !slices.Contains(outpost.Providers, providerPk) { + outpost.Providers = append(outpost.Providers, providerPk) + updated = true + } else { + logger.V(4).Info("Provider already in outpost") + } + case ReconcileOutpostModeRemove: + if slices.Contains(outpost.Providers, providerPk) { + outpost.Providers = slices.Delete(outpost.Providers, slices.Index(outpost.Providers, providerPk), 1) + updated = true + } + default: + return fmt.Errorf("invalid mode: %s", mode) + } + + if !updated { + return nil + } + + outpostPartialUpdateRequest := &authentikapi.PatchedOutpostRequest{ + Providers: outpost.Providers, + } + _, r, err = c.authentik.OutpostsApi.OutpostsInstancesPartialUpdate(ctx, outpostId).PatchedOutpostRequest(*outpostPartialUpdateRequest).Execute() + if err != nil { + return fmt.Errorf("error when calling `OutpostsAPI.OutpostsInstancesPartialUpdate`: %w with response %v", err, r) + } + + return nil +} diff --git a/pkg/controllers/proxyprovider/controller_test.go b/pkg/controllers/proxyprovider/controller_test.go index 0c37f47..ae88f9d 100644 --- a/pkg/controllers/proxyprovider/controller_test.go +++ b/pkg/controllers/proxyprovider/controller_test.go @@ -21,13 +21,30 @@ import ( "k8s.io/client-go/tools/cache" ) +const testOutpostID = "550e8400-e29b-41d4-a716-446655440000" + func TestController_syncHandler_create(t *testing.T) { const wantPK = 42 + var outpostPartialUpdateCalled bool server := newAuthentikTestServer(t, authentikTestHandlers{ proxyCreate: func(w http.ResponseWriter, _ *http.Request) { writeJSON(t, w, http.StatusCreated, map[string]any{"pk": wantPK}) }, + outpostRetrieve: outpostRetrieveHandler(t, nil), + outpostPartialUpdate: func(w http.ResponseWriter, r *http.Request) { + outpostPartialUpdateCalled = true + var body struct { + Providers []int32 `json:"providers"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("decode outpost patch body: %v", err) + } + if !slices.Contains(body.Providers, wantPK) { + t.Fatalf("patched providers = %v, want to contain %d", body.Providers, wantPK) + } + writeJSON(t, w, http.StatusOK, map[string]any{"pk": testOutpostID, "providers": body.Providers}) + }, }) t.Cleanup(server.Close) @@ -38,6 +55,41 @@ func TestController_syncHandler_create(t *testing.T) { if err != nil { t.Fatalf("syncHandler() error = %v", err) } + if !outpostPartialUpdateCalled { + t.Fatal("expected Authentik outpost partial update call") + } + + got := getProxyProvider(t, ctrl, "default", "test-pp") + if got.Status.PK != "42" { + t.Fatalf("status.pk = %q, want 42", got.Status.PK) + } +} + +func TestController_syncHandler_create_providerAlreadyInOutpost(t *testing.T) { + const wantPK = 42 + + var outpostPartialUpdateCalled bool + server := newAuthentikTestServer(t, authentikTestHandlers{ + proxyCreate: func(w http.ResponseWriter, _ *http.Request) { + writeJSON(t, w, http.StatusCreated, map[string]any{"pk": wantPK}) + }, + outpostRetrieve: outpostRetrieveHandler(t, []int32{wantPK}), + outpostPartialUpdate: func(w http.ResponseWriter, _ *http.Request) { + outpostPartialUpdateCalled = true + }, + }) + t.Cleanup(server.Close) + + ctrl, ctx, cancel := newTestController(t, testProxyProvider(), server.URL) + t.Cleanup(cancel) + + err := ctrl.syncHandler(ctx, cache.ObjectName{Namespace: "default", Name: "test-pp"}) + if err != nil { + t.Fatalf("syncHandler() error = %v", err) + } + if outpostPartialUpdateCalled { + t.Fatal("did not expect Authentik outpost partial update when provider is already present") + } got := getProxyProvider(t, ctrl, "default", "test-pp") if got.Status.PK != "42" { @@ -122,14 +174,29 @@ func TestController_syncHandler_update_providerNotFound(t *testing.T) { } func TestController_syncHandler_delete(t *testing.T) { + const wantPK int32 = 42 now := metav1.Now() pp := testProxyProvider() pp.Status.PK = "42" pp.DeletionTimestamp = &now pp.Finalizers = []string{DeleteAuthentikProxyProviderFinalizer} - var destroyCalled bool + var outpostPartialUpdateCalled, destroyCalled bool server := newAuthentikTestServer(t, authentikTestHandlers{ + outpostRetrieve: outpostRetrieveHandler(t, []int32{wantPK}), + outpostPartialUpdate: func(w http.ResponseWriter, r *http.Request) { + outpostPartialUpdateCalled = true + var body struct { + Providers []int32 `json:"providers"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("decode outpost patch body: %v", err) + } + if slices.Contains(body.Providers, wantPK) { + t.Fatalf("patched providers = %v, want provider %d removed", body.Providers, wantPK) + } + writeJSON(t, w, http.StatusOK, map[string]any{"pk": testOutpostID, "providers": body.Providers}) + }, proxyDestroy: func(w http.ResponseWriter, r *http.Request) { destroyCalled = true if r.Method != http.MethodDelete { @@ -147,6 +214,49 @@ func TestController_syncHandler_delete(t *testing.T) { if err != nil { t.Fatalf("syncHandler() error = %v", err) } + if !outpostPartialUpdateCalled { + t.Fatal("expected Authentik outpost partial update call") + } + if !destroyCalled { + t.Fatal("expected Authentik destroy call") + } + + got := getProxyProvider(t, ctrl, pp.Namespace, pp.Name) + if slices.Contains(got.Finalizers, DeleteAuthentikProxyProviderFinalizer) { + t.Fatalf("finalizers = %v, want finalizer removed", got.Finalizers) + } +} + +func TestController_syncHandler_delete_providerNotInOutpost(t *testing.T) { + now := metav1.Now() + pp := testProxyProvider() + pp.Status.PK = "42" + pp.DeletionTimestamp = &now + pp.Finalizers = []string{DeleteAuthentikProxyProviderFinalizer} + + var outpostPartialUpdateCalled, destroyCalled bool + server := newAuthentikTestServer(t, authentikTestHandlers{ + outpostRetrieve: outpostRetrieveHandler(t, nil), + outpostPartialUpdate: func(w http.ResponseWriter, _ *http.Request) { + outpostPartialUpdateCalled = true + }, + proxyDestroy: func(w http.ResponseWriter, _ *http.Request) { + destroyCalled = true + w.WriteHeader(http.StatusNoContent) + }, + }) + t.Cleanup(server.Close) + + ctrl, ctx, cancel := newTestController(t, pp, server.URL) + t.Cleanup(cancel) + + err := ctrl.syncHandler(ctx, cache.ObjectName{Namespace: pp.Namespace, Name: pp.Name}) + if err != nil { + t.Fatalf("syncHandler() error = %v", err) + } + if outpostPartialUpdateCalled { + t.Fatal("did not expect Authentik outpost partial update when provider is not in outpost") + } if !destroyCalled { t.Fatal("expected Authentik destroy call") } @@ -158,6 +268,7 @@ func TestController_syncHandler_delete(t *testing.T) { } func TestController_syncHandler_delete_providerAlreadyGone(t *testing.T) { + const wantPK int32 = 42 now := metav1.Now() pp := testProxyProvider() pp.Status.PK = "42" @@ -165,6 +276,16 @@ func TestController_syncHandler_delete_providerAlreadyGone(t *testing.T) { pp.Finalizers = []string{DeleteAuthentikProxyProviderFinalizer} server := newAuthentikTestServer(t, authentikTestHandlers{ + outpostRetrieve: outpostRetrieveHandler(t, []int32{wantPK}), + outpostPartialUpdate: func(w http.ResponseWriter, r *http.Request) { + var body struct { + Providers []int32 `json:"providers"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("decode outpost patch body: %v", err) + } + writeJSON(t, w, http.StatusOK, map[string]any{"pk": testOutpostID, "providers": body.Providers}) + }, proxyDestroy: func(w http.ResponseWriter, _ *http.Request) { http.NotFound(w, nil) }, @@ -235,6 +356,7 @@ func testProxyProvider() *v1alpha1.ProxyProvider { AuthorizationFlow: "flow-auth", InvalidationFlow: "flow-invalidate", ExternalHost: "https://app.example.com", + Outpost: testOutpostID, }, } } @@ -291,10 +413,22 @@ func newAuthentikAPIClientForTest(t *testing.T, serverURL string) *authentikapi. } type authentikTestHandlers struct { - proxyCreate http.HandlerFunc - proxyDestroy http.HandlerFunc - proxyPartialUpdate http.HandlerFunc - allRetrieve http.HandlerFunc + proxyCreate http.HandlerFunc + proxyDestroy http.HandlerFunc + proxyPartialUpdate http.HandlerFunc + allRetrieve http.HandlerFunc + outpostRetrieve http.HandlerFunc + outpostPartialUpdate http.HandlerFunc +} + +func outpostRetrieveHandler(t *testing.T, providers []int32) http.HandlerFunc { + t.Helper() + return func(w http.ResponseWriter, _ *http.Request) { + writeJSON(t, w, http.StatusOK, map[string]any{ + "pk": testOutpostID, + "providers": providers, + }) + } } func newAuthentikTestServer(t *testing.T, handlers authentikTestHandlers) *httptest.Server { @@ -341,6 +475,30 @@ func newAuthentikTestServer(t *testing.T, handlers authentikTestHandlers) *httpt } http.NotFound(w, r) + case strings.HasPrefix(path, "/api/v3/outposts/instances/") && strings.HasSuffix(path, "/"): + idPath := strings.TrimPrefix(path, "/api/v3/outposts/instances/") + idPath = strings.TrimSuffix(idPath, "/") + if idPath == "" || strings.Contains(idPath, "/") { + http.NotFound(w, r) + return + } + switch r.Method { + case http.MethodGet: + if handlers.outpostRetrieve != nil { + handlers.outpostRetrieve(w, r) + return + } + http.NotFound(w, r) + case http.MethodPatch: + if handlers.outpostPartialUpdate != nil { + handlers.outpostPartialUpdate(w, r) + return + } + http.NotFound(w, r) + default: + http.Error(w, "unexpected method on outpost instance", http.StatusMethodNotAllowed) + } + default: http.NotFound(w, r) } diff --git a/pkg/generated/applyconfiguration/proxyprovider/v1alpha1/proxyproviderspec.go b/pkg/generated/applyconfiguration/proxyprovider/v1alpha1/proxyproviderspec.go index c3f060b..9c67f64 100644 --- a/pkg/generated/applyconfiguration/proxyprovider/v1alpha1/proxyproviderspec.go +++ b/pkg/generated/applyconfiguration/proxyprovider/v1alpha1/proxyproviderspec.go @@ -25,6 +25,7 @@ type ProxyProviderSpecApplyConfiguration struct { AuthorizationFlow *string `json:"authorization_flow,omitempty"` InvalidationFlow *string `json:"invalidation_flow,omitempty"` ExternalHost *string `json:"external_host,omitempty"` + Outpost *string `json:"outpost,omitempty"` } // ProxyProviderSpecApplyConfiguration constructs a declarative configuration of the ProxyProviderSpec type for use with @@ -64,3 +65,11 @@ func (b *ProxyProviderSpecApplyConfiguration) WithExternalHost(value string) *Pr b.ExternalHost = &value return b } + +// WithOutpost sets the Outpost field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Outpost field is set to the value of the last call. +func (b *ProxyProviderSpecApplyConfiguration) WithOutpost(value string) *ProxyProviderSpecApplyConfiguration { + b.Outpost = &value + return b +} diff --git a/pkg/generated/openapi/zz_generated.openapi.go b/pkg/generated/openapi/zz_generated.openapi.go index 17097fe..0418349 100644 --- a/pkg/generated/openapi/zz_generated.openapi.go +++ b/pkg/generated/openapi/zz_generated.openapi.go @@ -536,8 +536,15 @@ func schema_pkg_apis_proxyprovider_v1alpha1_ProxyProviderSpec(ref common.Referen Format: "", }, }, + "outpost": { + SchemaProps: spec.SchemaProps{ + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, }, - Required: []string{"name", "authorization_flow", "invalidation_flow", "external_host"}, + Required: []string{"name", "authorization_flow", "invalidation_flow", "external_host", "outpost"}, }, }, } @@ -3056,7 +3063,7 @@ func schema_k8sio_apimachinery_pkg_runtime_RawExtension(ref common.ReferenceCall return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ - Description: "RawExtension is used to hold extensions in external versions.\n\nTo use this, make a field which has RawExtension as its type in your external, versioned struct, and Object in your internal struct. You also need to register your various plugin types.\n\n// Internal package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\"\"`\n\t\tMyPlugin runtime.Object `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// External package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\"\"`\n\t\tMyPlugin runtime.RawExtension `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// On the wire, the JSON will look something like this:\n\n\t{\n\t\t\"kind\":\"MyAPIObject\",\n\t\t\"apiVersion\":\"v1\",\n\t\t\"myPlugin\": {\n\t\t\t\"kind\":\"PluginA\",\n\t\t\t\"aOption\":\"foo\",\n\t\t},\n\t}\n\nSo what happens? Decode first uses json or yaml to unmarshal the serialized data into your external MyAPIObject. That causes the raw JSON to be stored, but not unpacked. The next step is to copy (using pkg/conversion) into the internal struct. The runtime package's DefaultScheme has conversion functions installed which will unpack the JSON stored in RawExtension, turning it into the correct object type, and storing it in the Object. (TODO: In the case where the object is of an unknown type, a runtime.Unknown object will be created and stored.)", + Description: "RawExtension is used to hold extensions in external versions.\n\nTo use this, make a field which has RawExtension as its type in your external, versioned struct, and Object in your internal struct. You also need to register your various plugin types.\n\n// Internal package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\",inline\"`\n\t\tMyPlugin runtime.Object `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// External package:\n\n\ttype MyAPIObject struct {\n\t\truntime.TypeMeta `json:\",inline\"`\n\t\tMyPlugin runtime.RawExtension `json:\"myPlugin\"`\n\t}\n\n\ttype PluginA struct {\n\t\tAOption string `json:\"aOption\"`\n\t}\n\n// On the wire, the JSON will look something like this:\n\n\t{\n\t\t\"kind\":\"MyAPIObject\",\n\t\t\"apiVersion\":\"v1\",\n\t\t\"myPlugin\": {\n\t\t\t\"kind\":\"PluginA\",\n\t\t\t\"aOption\":\"foo\",\n\t\t},\n\t}\n\nSo what happens? Decode first uses json or yaml to unmarshal the serialized data into your external MyAPIObject. That causes the raw JSON to be stored, but not unpacked. The next step is to copy (using pkg/conversion) into the internal struct. The runtime package's DefaultScheme has conversion functions installed which will unpack the JSON stored in RawExtension, turning it into the correct object type, and storing it in the Object. (TODO: In the case where the object is of an unknown type, a runtime.Unknown object will be created and stored.)", Type: []string{"object"}, }, }, @@ -3067,7 +3074,7 @@ func schema_k8sio_apimachinery_pkg_runtime_TypeMeta(ref common.ReferenceCallback return common.OpenAPIDefinition{ Schema: spec.Schema{ SchemaProps: spec.SchemaProps{ - Description: "TypeMeta is shared by all top level objects. The proper way to use it is to inline it in your type, like this:\n\n\ttype MyAwesomeAPIObject struct {\n\t runtime.TypeMeta `json:\"\"`\n\t ... // other fields\n\t}\n\nfunc (obj *MyAwesomeAPIObject) SetGroupVersionKind(gvk *metav1.GroupVersionKind) { metav1.UpdateTypeMeta(obj,gvk) }; GroupVersionKind() *GroupVersionKind\n\nTypeMeta is provided here for convenience. You may use it directly from this package or define your own with the same fields.", + Description: "TypeMeta is shared by all top level objects. The proper way to use it is to inline it in your type, like this:\n\n\ttype MyAwesomeAPIObject struct {\n\t runtime.TypeMeta `json:\",inline\"`\n\t ... // other fields\n\t}\n\nfunc (obj *MyAwesomeAPIObject) SetGroupVersionKind(gvk *metav1.GroupVersionKind) { metav1.UpdateTypeMeta(obj,gvk) }; GroupVersionKind() *GroupVersionKind\n\nTypeMeta is provided here for convenience. You may use it directly from this package or define your own with the same fields.", Type: []string{"object"}, Properties: map[string]spec.Schema{ "apiVersion": {