diff --git a/admin/internal/handler/zone/handler_test.go b/admin/internal/handler/zone/handler_test.go index eeda8547d..58eb80a5f 100644 --- a/admin/internal/handler/zone/handler_test.go +++ b/admin/internal/handler/zone/handler_test.go @@ -242,6 +242,18 @@ var _ = Describe("Zone Handler", func() { Expect(route.Spec.Hostnames).To(Equal([]string{"test-stargate.de"})) }) + It("keeps the percent-encoding of the managed route upstream path", func() { + zone.Spec.ManagedRoutes = &adminv1.ManagedRoutesConfig{Routes: []adminv1.ManagedRouteConfig{{Name: "proxy", Path: "/proxy", Url: "https://backend.example.com/api/url%20encoded%20path", Type: adminv1.ManagedRouteTypeProxy}}} + handler := newTestHandler() + Expect(handler.CreateOrUpdate(newTestContext(zone), zone)).To(Succeed()) + markSubResourcesReady(zone) + Expect(handler.CreateOrUpdate(newTestContext(zone), zone)).To(Succeed()) + route := &gatewayapi.Route{} + Expect(k8sClient.Get(ctx, client.ObjectKey{Namespace: zone.Status.Namespace, Name: naming.ForGateway(zone, "standard") + "--proxy"}, route)).To(Succeed()) + Expect(route.Spec.Backend.Upstreams).To(HaveLen(1)) + Expect(route.Spec.Backend.Upstreams[0].Path).To(Equal("/api/url%20encoded%20path")) + }) + It("deduplicates managed route paths and hostnames shared by preset URLs", func() { zone.Spec.Presets[0].Urls = []adminv1.UrlConfig{ {Hostname: "irix.example.com", BasePath: "/"}, diff --git a/admin/internal/handler/zone/routes.go b/admin/internal/handler/zone/routes.go index 219b6a294..e15a37ada 100644 --- a/admin/internal/handler/zone/routes.go +++ b/admin/internal/handler/zone/routes.go @@ -6,7 +6,6 @@ package zone import ( "context" - "net/url" "slices" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -135,16 +134,10 @@ func createManagedRoute(ctx context.Context, hc *HandlingContext, routeConfig ad route.Labels[cconfig.DomainLabelKey] = domainName route.Labels[cconfig.OwnerUidLabelKey] = string(hc.Zone.GetUID()) - upstreamUrl, err := url.Parse(routeConfig.Url) + upstream, err := gatewayapi.ParseUpstream(routeConfig.Url) if err != nil { return ctrlerrors.BlockedErrorf("cannot parse upstream url of internal route %s: %s", routeConfig.Url, err) } - upstream := gatewayapi.Upstream{ - Scheme: upstreamUrl.Scheme, - Hostname: upstreamUrl.Hostname(), - Port: gatewayapi.GetPortOrDefaultFromScheme(upstreamUrl), - Path: upstreamUrl.Path, - } hostnames, paths := preset.ResolveHostnamesAndPaths(routeConfig.Path) diff --git a/agentic/internal/handler/util/route.go b/agentic/internal/handler/util/route.go index 93edfb2cf..f5c2deae7 100644 --- a/agentic/internal/handler/util/route.go +++ b/agentic/internal/handler/util/route.go @@ -178,7 +178,7 @@ func CreateAgenticProxyRoute( if err != nil { return nil, errors.Wrap(err, "failed to build upstream URL for proxy route") } - upstream, err := AsUpstream(upstreamUrl, 0) + upstream, err := gatewayapi.ParseUpstream(upstreamUrl) if err != nil { return nil, errors.Wrap(err, "failed to create upstream for proxy route") } @@ -270,29 +270,14 @@ func DeleteRouteIfExists(ctx context.Context, ref *ctypes.ObjectRef) error { return nil } -// AsUpstream converts a raw URL to a gateway Upstream struct. -func AsUpstream(rawUrl string, weight int32) (gatewayapi.Upstream, error) { - u, err := url.Parse(rawUrl) - if err != nil { - return gatewayapi.Upstream{}, errors.Wrapf(err, "failed to parse URL %s", rawUrl) - } - - return gatewayapi.Upstream{ - Scheme: u.Scheme, - Hostname: u.Hostname(), - Port: gatewayapi.GetPortOrDefaultFromScheme(u), - Path: u.Path, - Weight: weight, - }, nil -} - func MapUpstreamsToGateway(upstreams []agenticv1.Upstream) ([]gatewayapi.Upstream, error) { mapped := make([]gatewayapi.Upstream, 0, len(upstreams)) for _, upstream := range upstreams { - gatewayUpstream, err := AsUpstream(upstream.Url, int32(upstream.Weight)) //nolint:gosec // weight is a small positive integer + gatewayUpstream, err := gatewayapi.ParseUpstream(upstream.Url) if err != nil { return nil, errors.Wrapf(err, "failed to map upstream %s", upstream.Url) } + gatewayUpstream.Weight = int32(upstream.Weight) //nolint:gosec // weight is a small positive integer mapped = append(mapped, gatewayUpstream) } return mapped, nil diff --git a/agentic/internal/handler/util/route_test.go b/agentic/internal/handler/util/route_test.go index 9d0f83733..50e8c0d2e 100644 --- a/agentic/internal/handler/util/route_test.go +++ b/agentic/internal/handler/util/route_test.go @@ -46,3 +46,20 @@ var _ = Describe("MapSubscriberSecurityToGateway", func() { Entry("client_secret_post", agenticv1.TokenRequestClientSecretPost, gatewayapi.TokenRequestClientSecretPost), ) }) + +var _ = Describe("MapUpstreamsToGateway", func() { + It("keeps the percent-encoding of the path and the weight", func() { + mapped, err := MapUpstreamsToGateway([]agenticv1.Upstream{ + {Url: "https://provider.example.com/api/url%20encoded%20path", Weight: 40}, + }) + + Expect(err).ToNot(HaveOccurred()) + Expect(mapped).To(Equal([]gatewayapi.Upstream{{ + Scheme: "https", + Hostname: "provider.example.com", + Port: 443, + Path: "/api/url%20encoded%20path", + Weight: 40, + }})) + }) +}) diff --git a/api/internal/controller/remoteapisubscription_controller_test.go b/api/internal/controller/remoteapisubscription_controller_test.go index f6c2ddda5..c202ba387 100644 --- a/api/internal/controller/remoteapisubscription_controller_test.go +++ b/api/internal/controller/remoteapisubscription_controller_test.go @@ -340,7 +340,7 @@ var _ = Describe("RemoteApiSubscription Controller - Consumer Scenario", Ordered ApprovalState: approvalapi.ApprovalStateGranted.String(), Message: "Test-Message", }, - GatewayUrl: "http://ger.gateway.pol:8080/ger", + GatewayUrl: "http://ger.gateway.pol:8080/ger/url%20encoded%20path", } remoteApiSubscription.SetCondition(condition.NewReadyCondition("RemoteApiSubscriptionReady", "Trust me, I am ready")) @@ -359,6 +359,8 @@ var _ = Describe("RemoteApiSubscription Controller - Consumer Scenario", Ordered g.Expect(k8sClient.Get(ctx, remoteApiSubscription.Status.Route.K8s(), route)).To(Succeed()) g.Expect(route.Spec.AdditionalTags).To(Equal([]string{"variant--default"})) g.Expect(route.Spec.Security.RealmName).To(Equal("remoteapisub-test-cons-realm")) + g.Expect(route.Spec.Backend.Upstreams).To(HaveLen(1)) + g.Expect(route.Spec.Backend.Upstreams[0].Path).To(Equal("/ger/url%20encoded%20path")) }, timeout, interval).Should(Succeed()) }) }) diff --git a/api/internal/handler/remoteapisubscription/consumer_scenario.go b/api/internal/handler/remoteapisubscription/consumer_scenario.go index 05b568223..2ac60764d 100644 --- a/api/internal/handler/remoteapisubscription/consumer_scenario.go +++ b/api/internal/handler/remoteapisubscription/consumer_scenario.go @@ -6,7 +6,6 @@ package remoteapisubscription import ( "context" - "net/url" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/meta" @@ -84,13 +83,11 @@ func (h *RemoteApiSubscriptionHandler) handleConsumerScenario(ctx context.Contex config.BuildLabelKey("type"): "real", } - u, parseErr := url.Parse(obj.Status.GatewayUrl) - if parseErr != nil { - return errors.Wrapf(parseErr, "failed to parse gateway url") + upstream, upstreamErr := gatewayapi.ParseUpstream(obj.Status.GatewayUrl) + if upstreamErr != nil { + return errors.Wrapf(upstreamErr, "failed to parse gateway url") } - port := gatewayapi.GetPortOrDefaultFromScheme(u) - hostnames, paths := preset.ResolveHostnamesAndPaths(obj.Spec.ApiBasePath) route.Spec = gatewayapi.RouteSpec{ @@ -99,14 +96,7 @@ func (h *RemoteApiSubscriptionHandler) handleConsumerScenario(ctx context.Contex Type: gatewayapi.RouteTypePrimary, Security: gatewayapi.Security{RealmName: zone.Status.RealmName}, Backend: gatewayapi.Backend{ - Upstreams: []gatewayapi.Upstream{ - { - Scheme: u.Scheme, - Hostname: u.Hostname(), - Port: port, - Path: u.Path, - }, - }, + Upstreams: []gatewayapi.Upstream{upstream}, }, Hostnames: hostnames, Paths: paths, diff --git a/api/internal/handler/util/gateway.go b/api/internal/handler/util/gateway.go deleted file mode 100644 index fcd021c3a..000000000 --- a/api/internal/handler/util/gateway.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2025 Deutsche Telekom IT GmbH -// -// SPDX-License-Identifier: Apache-2.0 - -package util - -import ( - "net/url" - - "github.com/pkg/errors" - - gatewayapi "github.com/telekom/controlplane/gateway/api/v1" -) - -// AsUpstream converts a raw URL to an Upstream struct, extracting the scheme, hostname, port, and path. -func AsUpstream(rawUrl string, weight int32) (ups gatewayapi.Upstream, err error) { - u, err := url.Parse(rawUrl) - if err != nil { - return ups, errors.Wrapf(err, "failed to parse URL %s", rawUrl) - } - - port := gatewayapi.GetPortOrDefaultFromScheme(u) - - return gatewayapi.Upstream{ - Scheme: u.Scheme, - Hostname: u.Hostname(), - Port: port, - Path: u.Path, - Weight: weight, - }, nil -} diff --git a/api/internal/handler/util/route_util.go b/api/internal/handler/util/route_util.go index 53730e2bd..57d47a8fe 100644 --- a/api/internal/handler/util/route_util.go +++ b/api/internal/handler/util/route_util.go @@ -288,7 +288,7 @@ func CreateProxyRoute(ctx context.Context, downstreamZoneRef, upstreamZoneRef ty if joinErr != nil { return errors.Wrap(joinErr, "failed to build upstream URL for proxy route") } - upstream, upstreamErr := AsUpstream(upstreamUrl, 0) + upstream, upstreamErr := gatewayapi.ParseUpstream(upstreamUrl) if upstreamErr != nil { return errors.Wrap(upstreamErr, "failed to create upstream") } @@ -380,10 +380,11 @@ func configureAsFailoverTarget(_ context.Context, proxyRoute *gatewayapi.Route, failoverTargets := make([]gatewayapi.FailoverTarget, 0, len(options.FailoverUpstreams)) for _, rawUpstream := range options.FailoverUpstreams { - failoverUpstream, upstreamErr := AsUpstream(rawUpstream.Url, int32(rawUpstream.Weight)) //nolint:gosec // weight is a small positive integer + failoverUpstream, upstreamErr := gatewayapi.ParseUpstream(rawUpstream.Url) if upstreamErr != nil { return errors.Wrapf(upstreamErr, "failed to create failover upstream %s", rawUpstream.Url) } + failoverUpstream.Weight = int32(rawUpstream.Weight) //nolint:gosec // weight is a small positive integer failoverTargets = append(failoverTargets, gatewayapi.FailoverTarget{Upstream: failoverUpstream}) } @@ -426,7 +427,7 @@ func addFailoverFallback(ctx context.Context, proxyRoute *gatewayapi.Route, opti return errors.Wrapf(err, "failed to build failover URL for zone %s", failoverZone.String()) } - failoverUpstream, err := AsUpstream(failoverUrl, 0) + failoverUpstream, err := gatewayapi.ParseUpstream(failoverUrl) if err != nil { return errors.Wrapf(err, "failed to create failover upstream for zone %s", failoverZone.String()) } @@ -571,10 +572,11 @@ func CreateRealRoute(ctx context.Context, downstreamZoneRef types.ObjectRef, api gatewayUpstreams := make([]gatewayapi.Upstream, 0, len(apiExposure.Spec.Upstreams)) for _, upstream := range apiExposure.Spec.Upstreams { - gatewayUpstream, upstreamErr := AsUpstream(upstream.Url, int32(upstream.Weight)) //nolint:gosec // weight is a small positive integer + gatewayUpstream, upstreamErr := gatewayapi.ParseUpstream(upstream.Url) if upstreamErr != nil { return errors.Wrapf(upstreamErr, "failed to create upstream for URL %s", upstream.Url) } + gatewayUpstream.Weight = int32(upstream.Weight) //nolint:gosec // weight is a small positive integer gatewayUpstreams = append(gatewayUpstreams, gatewayUpstream) } diff --git a/api/internal/handler/util_real_route_test.go b/api/internal/handler/util_real_route_test.go new file mode 100644 index 000000000..8cf623acc --- /dev/null +++ b/api/internal/handler/util_real_route_test.go @@ -0,0 +1,64 @@ +// Copyright 2026 Deutsche Telekom IT GmbH +// +// SPDX-License-Identifier: Apache-2.0 + +package handler + +import ( + "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + k8sclient "sigs.k8s.io/controller-runtime/pkg/client" + + adminapi "github.com/telekom/controlplane/admin/api/v1" + apiapi "github.com/telekom/controlplane/api/api/v1" + "github.com/telekom/controlplane/api/internal/handler/util" + "github.com/telekom/controlplane/common/pkg/client" + "github.com/telekom/controlplane/common/pkg/types" + "github.com/telekom/controlplane/common/pkg/util/contextutil" + gatewayapi "github.com/telekom/controlplane/gateway/api/v1" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("Creation of Real-Routes", Ordered, func() { + var ( + routeCtx context.Context + providerZone *adminapi.Zone + ) + + BeforeAll(func() { + routeCtx = client.WithClient(context.Background(), client.NewJanitorClient(client.NewScopedClient(k8sClient, testEnvironment))) + routeCtx = contextutil.WithEnv(routeCtx, testEnvironment) + + providerZone = CreateZone("encoded-upstream") + }) + + It("should persist the percent-encoded upstream path", func() { + apiExposure := &apiapi.ApiExposure{ + ObjectMeta: metav1.ObjectMeta{ + Name: "encoded-upstream", + Namespace: testEnvironment, + }, + Spec: apiapi.ApiExposureSpec{ + ApiBasePath: "/encoded/upstream/v1", + Upstreams: []apiapi.Upstream{ + {Url: "https://provider.example.com:8443/api/encoded%20url%20path"}, + }, + }, + } + + route, err := util.CreateRealRoute(routeCtx, *types.ObjectRefFromObject(providerZone), apiExposure) + Expect(err).ToNot(HaveOccurred()) + + persistedRoute := &gatewayapi.Route{} + Expect(k8sClient.Get(routeCtx, k8sclient.ObjectKeyFromObject(route), persistedRoute)).To(Succeed()) + Expect(persistedRoute.Spec.Backend.Upstreams).To(Equal([]gatewayapi.Upstream{{ + Scheme: "https", + Hostname: "provider.example.com", + Port: 8443, + Path: "/api/encoded%20url%20path", + }})) + }) +}) diff --git a/docs/docs/architecture/event.mdx b/docs/docs/architecture/event.mdx index 4972d7478..e6e6b9478 100644 --- a/docs/docs/architecture/event.mdx +++ b/docs/docs/architecture/event.mdx @@ -119,7 +119,7 @@ sequenceDiagram Some subscribers prefer to be *called back*: instead of fetching events, they give the platform an address of their own and let each event be pushed there. The callback route makes this happen. The event backend sends every event to the callback route, which reads the subscriber's real address (carried along with the request) and forwards the event to it. -Callback delivery starts in the **backend zone**, where Horizon runs. In this example, Horizon is configured with `https://dataplane1-gateway/horizon-dataplane3/callback/v1?url=U`, where `U` represents the subscriber's URL. The hostname is illustrative; the actual address comes from the gateway preset. **Backend-local callback ingress means that gateway's advertised URL, not loopback or `localhost`.** +Callback delivery starts in the **backend zone**, where Horizon runs. In this example, Horizon is configured with `https://dataplane1-gateway/horizon-dataplane3/callback/v1?url=U`, where `U` represents the subscriber's query-encoded URL. The hostname is illustrative; the actual address comes from the gateway preset. **Backend-local callback ingress means that gateway's advertised URL, not loopback or `localhost`.** ```mermaid sequenceDiagram diff --git a/docs/docs/user-journey/exposing-apis.mdx b/docs/docs/user-journey/exposing-apis.mdx index 4c0a4ccf2..d8268dc3f 100644 --- a/docs/docs/user-journey/exposing-apis.mdx +++ b/docs/docs/user-journey/exposing-apis.mdx @@ -80,7 +80,7 @@ roverctl apply -f rover.yaml | Field | Description | | ----- | ----------- | | `basePath` | The public API path. Must match an existing Api resource and be unique across the platform. This is how consumers will reach your API. | -| `upstream` | The internal URL where your service is running. The gateway proxies incoming requests to this address. | +| `upstream` | The internal URL where your service is running. The gateway proxies incoming requests to this address. Encoded characters in the path, such as `%20`, are forwarded unchanged. | | `approval` | The approval strategy for subscription requests: `auto`, `simple`, or `foureyes`. See [Approvals](./approvals.mdx). | ### What Happens diff --git a/event/internal/controller/callback_lifecycle_test.go b/event/internal/controller/callback_lifecycle_test.go index efade549c..9cb087965 100644 --- a/event/internal/controller/callback_lifecycle_test.go +++ b/event/internal/controller/callback_lifecycle_test.go @@ -493,7 +493,7 @@ var _ = Describe("callback lifecycle with persisted resources", func() { reconcileSub() Eventually(func(g Gomega) { g.Expect(k8sClient.Get(ctx, childKey, child)).To(Succeed()) - g.Expect(child.Spec.Delivery.Callback).To(Equal(backend.Status.ProxyCallbackURLs["subscriber"] + "?url=https://consumer.example.com/events")) + g.Expect(child.Spec.Delivery.Callback).To(Equal(backend.Status.ProxyCallbackURLs["subscriber"] + "?url=https%3A%2F%2Fconsumer.example.com%2Fevents")) }, 5*time.Second, 100*time.Millisecond).Should(Succeed()) oldScalar := proxy.Status.CallbackURL @@ -511,7 +511,7 @@ var _ = Describe("callback lifecycle with persisted resources", func() { Eventually(func() []reconcile.Request { return r.MapEventConfigToEventSubscription(ctx, proxy) }, 5*time.Second, 100*time.Millisecond).Should(ContainElement(reconcile.Request{NamespacedName: client.ObjectKeyFromObject(sub)})) reconcileSub() Expect(k8sClient.Get(ctx, childKey, child)).To(Succeed()) - Expect(child.Spec.Delivery.Callback).To(Equal(backend.Status.ProxyCallbackURLs["subscriber"] + "?url=https://consumer.example.com/events")) + Expect(child.Spec.Delivery.Callback).To(Equal(backend.Status.ProxyCallbackURLs["subscriber"] + "?url=https%3A%2F%2Fconsumer.example.com%2Fevents")) proxy.Spec.Mesh.ZoneNames = []string{"backend"} Expect(k8sClient.Update(ctx, proxy)).To(Succeed()) diff --git a/event/internal/handler/eventsubscription/handler.go b/event/internal/handler/eventsubscription/handler.go index 824a8b672..43c31869a 100644 --- a/event/internal/handler/eventsubscription/handler.go +++ b/event/internal/handler/eventsubscription/handler.go @@ -444,7 +444,14 @@ func updateCallbackURL(ctx context.Context, sub *eventv1.EventSubscription, expo } // Use rawCallbackUrl as new callback URL and add actual callback URL as query parameter so that provider can use it for callbacks. - sub.Spec.Delivery.Callback = rawCallbackUrl + "?" + util.CallbackURLQueryParam + "=" + sub.Spec.Delivery.Callback + gatewayCallbackUrl, err := url.Parse(rawCallbackUrl) + if err != nil { + return ctrlerrors.BlockedErrorf("cannot parse gateway callback URL %q: %s", rawCallbackUrl, err) + } + query := gatewayCallbackUrl.Query() + query.Set(util.CallbackURLQueryParam, sub.Spec.Delivery.Callback) + gatewayCallbackUrl.RawQuery = query.Encode() + sub.Spec.Delivery.Callback = gatewayCallbackUrl.String() logger.V(1).Info("Updated callback URL for proxy scenario", "callback", sub.Spec.Delivery.Callback) return nil diff --git a/event/internal/handler/eventsubscription/handler_test.go b/event/internal/handler/eventsubscription/handler_test.go index 97730b555..71b0daf21 100644 --- a/event/internal/handler/eventsubscription/handler_test.go +++ b/event/internal/handler/eventsubscription/handler_test.go @@ -675,7 +675,9 @@ var _ = Describe("EventSubscriptionHandler", func() { et := makeReadyEventType(testEventType) exposure := makeReadyEventExposure(testEventType) obj.Spec.Zone.Name = "sub-zone" - obj.Spec.Delivery.Callback = "https://my-callback.example.com" + obj.Spec.Delivery.Callback = "https://my-callback.example.com/events?tenant=a&mode=b" + expectedCallback := "https://expo-gateway.example.com/horizon-sub-zone/callback/v1" + + "?url=https%3A%2F%2Fmy-callback.example.com%2Fevents%3Ftenant%3Da%26mode%3Db" expoConfig := makeReadyEventConfig("expo-zone", false, []string{"sub-zone"}) expoConfig.Status.ProxyCallbackURLs["sub-zone"] = "https://expo-gateway.example.com/horizon-sub-zone/callback/v1" @@ -698,8 +700,7 @@ var _ = Describe("EventSubscriptionHandler", func() { CreateOrUpdate(ctx, mock.AnythingOfType("*v1.Subscriber"), mock.Anything). RunAndReturn(func(_ context.Context, child client.Object, mutate controllerutil.MutateFn) (controllerutil.OperationResult, error) { Expect(mutate()).To(Succeed()) - Expect(child.(*pubsubv1.Subscriber).Spec.Delivery.Callback).To(Equal( - "https://expo-gateway.example.com/horizon-sub-zone/callback/v1?url=https://my-callback.example.com")) + Expect(child.(*pubsubv1.Subscriber).Spec.Delivery.Callback).To(Equal(expectedCallback)) return controllerutil.OperationResultCreated, nil }).Once() fakeClient.EXPECT().AllReady().Return(true).Once() @@ -707,10 +708,7 @@ var _ = Describe("EventSubscriptionHandler", func() { err := h.CreateOrUpdate(ctx, obj) Expect(err).ToNot(HaveOccurred()) - - // Verify callback URL was updated - Expect(obj.Spec.Delivery.Callback).To(HavePrefix("https://expo-gateway.example.com/horizon-sub-zone/callback/v1")) - Expect(obj.Spec.Delivery.Callback).To(ContainSubstring("url=https://my-callback.example.com")) + Expect(obj.Spec.Delivery.Callback).To(Equal(expectedCallback)) }) DescribeTable("requires a ready subscriber-zone EventConfig and primary callback route before provisioning", func(state string) { @@ -800,7 +798,7 @@ var _ = Describe("EventSubscriptionHandler", func() { fakeClient.EXPECT().CreateOrUpdate(ctx, mock.AnythingOfType("*v1.Subscriber"), mock.Anything). RunAndReturn(func(_ context.Context, child client.Object, mutate controllerutil.MutateFn) (controllerutil.OperationResult, error) { Expect(mutate()).To(Succeed()) - Expect(child.(*pubsubv1.Subscriber).Spec.Delivery.Callback).To(Equal(expectedURL + "?url=https://my-callback.example.com")) + Expect(child.(*pubsubv1.Subscriber).Spec.Delivery.Callback).To(Equal(expectedURL + "?url=https%3A%2F%2Fmy-callback.example.com")) return controllerutil.OperationResultCreated, nil }).Once() fakeClient.EXPECT().AllReady().Return(true).Once() diff --git a/event/internal/handler/util/callback_route.go b/event/internal/handler/util/callback_route.go index 52b02d7ff..4c68d32a9 100644 --- a/event/internal/handler/util/callback_route.go +++ b/event/internal/handler/util/callback_route.go @@ -19,12 +19,12 @@ import ( // // Subscriber and backend share the same Zone ("foo" --> "consumer"): // 1. Subscriber has deliveryType callback with the callbackUrl "https://my-callback/v1/post" -// 2. Approval is done and pubsub-Subscription is provisioned with the callbackUrl "https://foo-gateway/horizon-foo/callback/v1?url=https://my-callback/v1/post" +// 2. Approval is done and pubsub-Subscription is provisioned with the callbackUrl "https://foo-gateway/horizon-foo/callback/v1?url=https%3A%2F%2Fmy-callback%2Fv1%2Fpost" // 3. Horizon publishes events as eventstore; the foo-gateway forwards them to the callbackUrl with a gateway LMS token. // // Subscriber is on a different zone ("backend" --> "subscriber" --> "consumer"): // 1. Subscriber has deliveryType callback with the callbackUrl "https://my-callback/v1/post" -// 2. Approval is done and pubsub-Subscription is provisioned with the callbackUrl "https://backend-gateway/horizon-subscriber/callback/v1?url=https://my-callback/v1/post" +// 2. Approval is done and pubsub-Subscription is provisioned with the callbackUrl "https://backend-gateway/horizon-subscriber/callback/v1?url=https%3A%2F%2Fmy-callback%2Fv1%2Fpost" // 3. Horizon sends events as eventstore to the backend gateway, which forwards with a gateway LMS token to the subscriber zone's primary Route; that Route forwards to the callbackUrl. // This also applies when exposure and subscriber share a proxy zone: the first hop remains in the physical backend zone. diff --git a/event/internal/handler/util/publish_route.go b/event/internal/handler/util/publish_route.go index 0158ec69b..166d937ab 100644 --- a/event/internal/handler/util/publish_route.go +++ b/event/internal/handler/util/publish_route.go @@ -50,7 +50,7 @@ func CreatePublishRoute( return nil, err } - upstream, err := parseUpstream(eventConfig.Spec.Local.PublishEventUrl) + upstream, err := gatewayv1.ParseUpstream(eventConfig.Spec.Local.PublishEventUrl) if err != nil { return nil, errors.Wrapf(err, "failed to parse publishEventUrl %q", eventConfig.Spec.Local.PublishEventUrl) } diff --git a/event/internal/handler/util/publish_route_test.go b/event/internal/handler/util/publish_route_test.go index fce096813..069cc0c1d 100644 --- a/event/internal/handler/util/publish_route_test.go +++ b/event/internal/handler/util/publish_route_test.go @@ -185,6 +185,23 @@ var _ = Describe("CreatePublishRoute", func() { Expect(route.Spec.Backend.Upstreams[0].Path).To(Equal("/api/publish")) }) + It("should keep the percent-encoding of the upstream path", func() { + zone := makeZone("zone-a", "zone-a-ns") + eventConfig.Spec.Local.PublishEventUrl = "http://publish-service:8080/api/url%20encoded%20path" + + fakeClient.EXPECT(). + CreateOrUpdate(ctx, mock.AnythingOfType("*v1.Route"), mock.Anything). + RunAndReturn(func(_ context.Context, obj client.Object, mutate controllerutil.MutateFn) (controllerutil.OperationResult, error) { + err := mutate() + return controllerutil.OperationResultCreated, err + }) + + route, err := util.CreatePublishRoute(ctx, zone, eventConfig) + Expect(err).ToNot(HaveOccurred()) + Expect(route.Spec.Backend.Upstreams).To(HaveLen(1)) + Expect(route.Spec.Backend.Upstreams[0].Path).To(Equal("/api/url%20encoded%20path")) + }) + It("should return error when CreateOrUpdate fails", func() { zone := makeZone("zone-a", "zone-a-ns") diff --git a/event/internal/handler/util/shared_route.go b/event/internal/handler/util/shared_route.go index 8f396056f..61210d0a4 100644 --- a/event/internal/handler/util/shared_route.go +++ b/event/internal/handler/util/shared_route.go @@ -49,20 +49,6 @@ func DeleteRouteIfExists(ctx context.Context, ref *ctypes.ObjectRef) error { return nil } -// parseUpstream parses a raw URL string into a gateway Upstream. -func parseUpstream(rawUrl string) (gatewayapi.Upstream, error) { - u, err := url.Parse(rawUrl) - if err != nil { - return gatewayapi.Upstream{}, errors.Wrapf(err, "failed to parse URL %s", rawUrl) - } - return gatewayapi.Upstream{ - Scheme: u.Scheme, - Hostname: u.Hostname(), - Port: gatewayapi.GetPortOrDefaultFromScheme(u), - Path: u.Path, - }, nil -} - type Options struct { Owner metav1.Object @@ -198,7 +184,7 @@ func gatewayUpstream(preset *adminv1.Preset, path string) (gatewayapi.Upstream, } full = joined } - return parseUpstream(full) + return gatewayapi.ParseUpstream(full) } func gatewayRef(zone *adminv1.Zone) (*ctypes.ObjectRef, error) { diff --git a/event/internal/handler/util/sse_route.go b/event/internal/handler/util/sse_route.go index 212e79cc6..9948e109d 100644 --- a/event/internal/handler/util/sse_route.go +++ b/event/internal/handler/util/sse_route.go @@ -64,7 +64,7 @@ func CreateSSERoute( return nil, ctrlerrors.BlockedErrorf("EventConfig %q for zone %q has no local backend; SSE primary Route requires a local (non-proxy) zone", eventConfig.Name, zone.Name) } - upstream, err := parseUpstream(eventConfig.Spec.Local.ServerSendEventUrl) + upstream, err := gatewayapi.ParseUpstream(eventConfig.Spec.Local.ServerSendEventUrl) if err != nil { return nil, errors.Wrapf(err, "failed to parse ServerSendEventUrl %q", eventConfig.Spec.Local.ServerSendEventUrl) } diff --git a/event/internal/handler/util/voyager_route.go b/event/internal/handler/util/voyager_route.go index 8e94f3465..1e8c7df08 100644 --- a/event/internal/handler/util/voyager_route.go +++ b/event/internal/handler/util/voyager_route.go @@ -57,7 +57,7 @@ func CreateVoyagerRoute( return nil, err } - upstream, err := parseUpstream(eventConfig.Spec.Local.VoyagerApiUrl) + upstream, err := gatewayapi.ParseUpstream(eventConfig.Spec.Local.VoyagerApiUrl) if err != nil { return nil, errors.Wrapf(err, "failed to parse voyagerApiUrl %q", eventConfig.Spec.Local.VoyagerApiUrl) } diff --git a/file/internal/handler/zoneserviceconfig/handler.go b/file/internal/handler/zoneserviceconfig/handler.go index 7c0f161c3..8b91320a7 100644 --- a/file/internal/handler/zoneserviceconfig/handler.go +++ b/file/internal/handler/zoneserviceconfig/handler.go @@ -337,20 +337,13 @@ func createManagedRoute(ctx context.Context, zone *adminv1.Zone, obj *filev1.Zon return fmt.Errorf("failed to set controller reference for route: %w", locErr) } - upstreamUrl, locErr := url.Parse(routeConfig.Url) + upstream, locErr := gatewayapi.ParseUpstream(routeConfig.Url) if locErr != nil { return ctrlerrors.BlockedErrorf("cannot parse upstream url of internal route %s: %s", routeConfig.Url, locErr) } route.Labels = util.DomainLabel() - upstream := gatewayapi.Upstream{ - Scheme: upstreamUrl.Scheme, - Hostname: upstreamUrl.Hostname(), - Port: gatewayapi.GetPortOrDefaultFromScheme(upstreamUrl), - Path: upstreamUrl.Path, - } - hostnames, paths := preset.ResolveHostnamesAndPaths(routeConfig.Path) route.Spec = gatewayapi.RouteSpec{ diff --git a/file/internal/handler/zoneserviceconfig/handler_test.go b/file/internal/handler/zoneserviceconfig/handler_test.go index f7d287966..c9be1d19d 100644 --- a/file/internal/handler/zoneserviceconfig/handler_test.go +++ b/file/internal/handler/zoneserviceconfig/handler_test.go @@ -604,6 +604,27 @@ var _ = Describe("tokenEndpointFromIssuer", func() { }) }) +var _ = Describe("createManagedRoute", func() { + It("keeps the percent-encoding of the upstream path", func() { + obj := testZoneServiceConfig() + obj.Spec.API.Url = "https://sftp-api.internal/api/url%20encoded%20path" + ctx, mockClient := newTestContext() + + mockClient.EXPECT().Scheme().Return(buildScheme()).Maybe() + mockClient.EXPECT(). + CreateOrUpdate(mock.Anything, mock.AnythingOfType("*v1.Route"), mock.Anything). + RunAndReturn(func(_ context.Context, _ client.Object, mutate controllerutil.MutateFn) (controllerutil.OperationResult, error) { + return controllerutil.OperationResultCreated, mutate() + }).Once() + + route, err := createManagedRoute(ctx, testReadyZone(), obj) + + Expect(err).NotTo(HaveOccurred()) + Expect(route.Spec.Backend.Upstreams).To(HaveLen(1)) + Expect(route.Spec.Backend.Upstreams[0].Path).To(Equal("/api/url%20encoded%20path")) + }) +}) + var _ = Describe("sftpAPIEndpointFromManagedRoute", func() { It("returns an error when the route has no hostnames", func() { route := &gatewayapi.Route{Spec: gatewayapi.RouteSpec{Paths: []string{testAPIPath}}} diff --git a/gateway/Makefile b/gateway/Makefile index ce94284f9..c4cf383fe 100644 --- a/gateway/Makefile +++ b/gateway/Makefile @@ -70,6 +70,7 @@ COVER_PACKAGES = ./internal/controller/...,./internal/features,./internal/featur .PHONY: test test: manifests generate fmt vet envtest ## Run tests. KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" gotestsum --format pkgname --jsonfile gotest.log -- $(TEST_PACKAGES) -ginkgo.junit-report=ginkgo-junit.xml -coverprofile cover.out --coverpkg $(COVER_PACKAGES) -race + $(MAKE) -C api test # Utilize Kind or modify the e2e tests to load the image locally, enabling compatibility with other vendors. .PHONY: test-e2e # Run the e2e tests against a Kind k8s instance that is spun up. diff --git a/gateway/api/Makefile b/gateway/api/Makefile new file mode 100644 index 000000000..0889f0928 --- /dev/null +++ b/gateway/api/Makefile @@ -0,0 +1,20 @@ +# Copyright 2026 Deutsche Telekom IT GmbH +# +# SPDX-License-Identifier: Apache-2.0 + +.PHONY: build fmt vet test tidy + +build: fmt vet + go build ./... + +fmt: + go fmt ./... + +vet: + go vet ./... + +test: fmt vet + gotestsum --format pkgname --jsonfile gotest.log -- ./... -ginkgo.junit-report=ginkgo-junit.xml -race + +tidy: + go mod tidy diff --git a/gateway/api/go.mod b/gateway/api/go.mod index 4f7192422..8b3036bf9 100644 --- a/gateway/api/go.mod +++ b/gateway/api/go.mod @@ -7,6 +7,8 @@ module github.com/telekom/controlplane/gateway/api go 1.26.11 require ( + github.com/onsi/ginkgo/v2 v2.34.0 + github.com/onsi/gomega v1.44.0 github.com/telekom/controlplane/common v0.0.0 k8s.io/apimachinery v0.37.2 sigs.k8s.io/controller-runtime v0.25.2 @@ -15,6 +17,7 @@ require ( replace github.com/telekom/controlplane/common => ../../common require ( + github.com/Masterminds/semver/v3 v3.4.0 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect @@ -36,7 +39,10 @@ require ( github.com/go-openapi/swag/stringutils v0.27.1 // indirect github.com/go-openapi/swag/typeutils v0.27.1 // indirect github.com/go-openapi/swag/yamlutils v0.27.1 // indirect + github.com/go-task/slim-sprig/v3 v3.0.0 // indirect github.com/google/gnostic-models v0.7.0 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 // indirect github.com/google/uuid v1.6.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect @@ -50,12 +56,15 @@ require ( github.com/x448/float16 v0.8.4 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/mod v0.42.0 // indirect golang.org/x/net v0.62.0 // indirect golang.org/x/oauth2 v0.37.0 // indirect + golang.org/x/sync v0.24.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/term v0.47.0 // indirect golang.org/x/text v0.43.0 // indirect golang.org/x/time v0.15.0 // indirect + golang.org/x/tools v0.51.0 // indirect google.golang.org/protobuf v1.36.12 // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect diff --git a/gateway/api/go.sum b/gateway/api/go.sum index 1598a56d6..91407e3c3 100644 --- a/gateway/api/go.sum +++ b/gateway/api/go.sum @@ -14,6 +14,12 @@ github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjT github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= +github.com/gkampitakis/ciinfo v0.3.2/go.mod h1:1NIwaOcFChN4fa/B0hEBdAb6npDlFL8Bwx4dfRLRqAo= +github.com/gkampitakis/go-diff v1.3.2 h1:Qyn0J9XJSDTgnsgHRdz9Zp24RaJeKMUHg2+PDZZdC4M= +github.com/gkampitakis/go-diff v1.3.2/go.mod h1:LLgOrpqleQe26cte8s36HTWcTmMEur6OPYerdAAS9tk= +github.com/gkampitakis/go-snaps v0.5.15 h1:amyJrvM1D33cPHwVrjo9jQxX8g/7E2wYdZ+01KS3zGE= +github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiHo/hGheFGBZ+mc= github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= @@ -54,6 +60,8 @@ github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAg github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw= +github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -63,8 +71,18 @@ github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 h1:EwtI+Al+DeppwYX2oX github.com/google/pprof v0.0.0-20260402051712-545e8a4df936/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= +github.com/joshdk/go-junit v1.0.0/go.mod h1:TiiV0PqkaNfFXjEiyjWM3XXrhVyCa1K4Zfga6W52ung= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo= +github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg= +github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE= +github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -88,6 +106,8 @@ github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk= github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -96,6 +116,14 @@ github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+Q github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= diff --git a/gateway/api/v1/suite_test.go b/gateway/api/v1/suite_test.go new file mode 100644 index 000000000..34304938e --- /dev/null +++ b/gateway/api/v1/suite_test.go @@ -0,0 +1,18 @@ +// Copyright 2026 Deutsche Telekom IT GmbH +// +// SPDX-License-Identifier: Apache-2.0 + +package v1_test + +import ( + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestV1(t *testing.T) { + RegisterFailHandler(Fail) + + RunSpecs(t, "v1 Suite") +} diff --git a/gateway/api/v1/traffic_types.go b/gateway/api/v1/traffic_types.go index a92bff8f4..0042aa556 100644 --- a/gateway/api/v1/traffic_types.go +++ b/gateway/api/v1/traffic_types.go @@ -15,6 +15,7 @@ type Upstream struct { Port int32 `json:"port"` + // Path is the percent-encoded upstream path. The gateway forwards it verbatim. Path string `json:"path"` } diff --git a/gateway/api/v1/util.go b/gateway/api/v1/util.go index 3a51b6a90..e1e1e858e 100644 --- a/gateway/api/v1/util.go +++ b/gateway/api/v1/util.go @@ -5,6 +5,7 @@ package v1 import ( + "fmt" "math" "net/url" "strconv" @@ -34,3 +35,19 @@ func GetPortOrDefaultFromScheme(url *url.URL) int32 { return 80 } } + +// ParseUpstream converts a raw URL into an Upstream. +// The path keeps its percent-encoding because the gateway forwards it verbatim. +// The weight is not set. +func ParseUpstream(rawURL string) (Upstream, error) { + u, err := url.Parse(rawURL) + if err != nil { + return Upstream{}, fmt.Errorf("failed to parse upstream URL %q: %w", rawURL, err) + } + return Upstream{ + Scheme: u.Scheme, + Hostname: u.Hostname(), + Port: GetPortOrDefaultFromScheme(u), + Path: u.EscapedPath(), + }, nil +} diff --git a/gateway/api/v1/util_test.go b/gateway/api/v1/util_test.go new file mode 100644 index 000000000..34bfef678 --- /dev/null +++ b/gateway/api/v1/util_test.go @@ -0,0 +1,58 @@ +// Copyright 2026 Deutsche Telekom IT GmbH +// +// SPDX-License-Identifier: Apache-2.0 + +package v1_test + +import ( + gatewayv1 "github.com/telekom/controlplane/gateway/api/v1" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("ParseUpstream", func() { + It("maps the URL components", func() { + upstream, err := gatewayv1.ParseUpstream("https://provider.example.com:8443/api/v1") + + Expect(err).ToNot(HaveOccurred()) + Expect(upstream).To(Equal(gatewayv1.Upstream{ + Scheme: "https", + Hostname: "provider.example.com", + Port: 8443, + Path: "/api/v1", + })) + }) + + It("uses the default port of the scheme", func() { + upstream, err := gatewayv1.ParseUpstream("http://provider.example.com/api") + + Expect(err).ToNot(HaveOccurred()) + Expect(upstream.Port).To(Equal(int32(80))) + }) + + It("returns an error for an invalid URL", func() { + _, err := gatewayv1.ParseUpstream("http://provider.example.com/%zz") + + Expect(err).To(MatchError(ContainSubstring("failed to parse upstream URL"))) + }) + + DescribeTable("keeps the percent-encoding of the path", + func(rawUrl, expectedPath string) { + upstream, err := gatewayv1.ParseUpstream(rawUrl) + + Expect(err).ToNot(HaveOccurred()) + Expect(upstream.Path).To(Equal(expectedPath)) + }, + Entry("encoded spaces", + "https://provider.example.com/api/url%20encoded%20path", "/api/url%20encoded%20path"), + Entry("encoded slash", + "https://provider.example.com/files/a%2Fb", "/files/a%2Fb"), + Entry("encoded percent sign", + "https://provider.example.com/discounts/100%25", "/discounts/100%25"), + Entry("double-encoded space", + "https://provider.example.com/items/a%2520b", "/items/a%2520b"), + Entry("path without encoding", + "https://provider.example.com/api/v1", "/api/v1"), + ) +}) diff --git a/gateway/config/crd/bases/gateway.cp.ei.telekom.de_routes.yaml b/gateway/config/crd/bases/gateway.cp.ei.telekom.de_routes.yaml index 8b8b526c1..39a2bc523 100644 --- a/gateway/config/crd/bases/gateway.cp.ei.telekom.de_routes.yaml +++ b/gateway/config/crd/bases/gateway.cp.ei.telekom.de_routes.yaml @@ -71,6 +71,8 @@ spec: hostname: type: string path: + description: Path is the percent-encoded upstream path. + The gateway forwards it verbatim. type: string port: format: int32 @@ -583,6 +585,8 @@ spec: hostname: type: string path: + description: Path is the percent-encoded upstream path. + The gateway forwards it verbatim. type: string port: format: int32 diff --git a/gateway/pkg/kong/client/types.go b/gateway/pkg/kong/client/types.go index 42900df7d..000846114 100644 --- a/gateway/pkg/kong/client/types.go +++ b/gateway/pkg/kong/client/types.go @@ -83,7 +83,7 @@ func FromURL(parsedURL *url.URL) (Upstream, error) { Scheme: parsedURL.Scheme, Host: parsedURL.Hostname(), Port: intPort, - Path: parsedURL.Path, + Path: parsedURL.EscapedPath(), }, err } diff --git a/gateway/pkg/kong/client/types_test.go b/gateway/pkg/kong/client/types_test.go new file mode 100644 index 000000000..1967546e4 --- /dev/null +++ b/gateway/pkg/kong/client/types_test.go @@ -0,0 +1,33 @@ +// Copyright 2026 Deutsche Telekom IT GmbH +// +// SPDX-License-Identifier: Apache-2.0 + +package client_test + +import ( + clientpkg "github.com/telekom/controlplane/gateway/pkg/kong/client" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("NewUpstream", func() { + DescribeTable("keeps the percent-encoding of the path", + func(rawUrl, expectedPath string) { + upstream, err := clientpkg.NewUpstream(rawUrl) + + Expect(err).ToNot(HaveOccurred()) + Expect(upstream.GetPath()).To(Equal(expectedPath)) + }, + Entry("encoded spaces", + "https://provider.example.com:443/api/url%20encoded%20path", "/api/url%20encoded%20path"), + Entry("encoded slash", + "https://provider.example.com:443/files/a%2Fb", "/files/a%2Fb"), + Entry("encoded percent sign", + "https://provider.example.com:443/discounts/100%25", "/discounts/100%25"), + Entry("double-encoded space", + "https://provider.example.com:443/items/a%2520b", "/items/a%2520b"), + Entry("path without encoding", + "http://localhost:8080/proxy", "/proxy"), + ) +}) diff --git a/spectre/internal/handler/spectreapplication_handler_test.go b/spectre/internal/handler/spectreapplication_handler_test.go index 99dcf42d6..7679ac57b 100644 --- a/spectre/internal/handler/spectreapplication_handler_test.go +++ b/spectre/internal/handler/spectreapplication_handler_test.go @@ -628,6 +628,43 @@ var _ = Describe("SpectreApplicationHandler", func() { Expect(obj.Status.SseUrl).To(Equal("https://gateway.example.com:443" + testCanonicalSSEPath + "/" + testSubscriptionId)) }) + It("should keep the percent-encoding of the SSE upstream path", func() { + obj := newSpectreApplication("server_sent_event") + app := makeReadyApplication() + zone := makeReadyZone() + ec := makeReadyEventConfig() + ec.Spec.Local.ServerSendEventUrl = "https://horizon-sse.internal:443/api/url%20encoded%20path" + es := makeEventStore() + + mockGetApplication(app) + mockGetZone(zone) + mockListEventConfigs([]eventv1.EventConfig{ec}) + mockGetEventStore(es) + mockCreateOrUpdatePublisher() + mockCreateOrUpdateSubscriber() + + var capturedRoute *gatewayv1.Route + fakeClient.EXPECT(). + CreateOrUpdate(ctx, mock.AnythingOfType("*v1.Route"), mock.Anything). + Run(func(_ context.Context, obj client.Object, mutate controllerutil.MutateFn) { + _ = mutate() + capturedRoute = obj.(*gatewayv1.Route) + }). + Return(controllerutil.OperationResultCreated, nil).Once() + + mockCleanup() + fakeClient.EXPECT().AnyChanged().Return(false).Once() + fakeClient.EXPECT().AllReady().Return(true).Once() + mockExplicitReadinessChecks("server_sent_event") + + err := h.CreateOrUpdate(ctx, obj) + Expect(err).ToNot(HaveOccurred()) + + Expect(capturedRoute).ToNot(BeNil()) + Expect(capturedRoute.Spec.Backend.Upstreams).To(HaveLen(1)) + Expect(capturedRoute.Spec.Backend.Upstreams[0].Path).To(Equal("/api/url%20encoded%20path")) + }) + It("should serve canonical then legacy paths for every preset URL and publish the first visible URL", func() { obj := newSpectreApplication("server_sent_event") app := makeReadyApplication() diff --git a/spectre/internal/handler/spectreapplication_route.go b/spectre/internal/handler/spectreapplication_route.go index c3f2de6f7..5367fbf41 100644 --- a/spectre/internal/handler/spectreapplication_route.go +++ b/spectre/internal/handler/spectreapplication_route.go @@ -158,7 +158,7 @@ func createSpectreSSEPrimaryRoute( return nil, ctrlerrors.BlockedErrorf("EventConfig %q for zone %q has no local backend", eventConfig.Name, zone.Name) } - upstream, err := parseSSEUpstream(eventConfig.Spec.Local.ServerSendEventUrl) + upstream, err := gatewayv1.ParseUpstream(eventConfig.Spec.Local.ServerSendEventUrl) if err != nil { return nil, errors.Wrapf(err, "failed to parse ServerSendEventUrl %q", eventConfig.Spec.Local.ServerSendEventUrl) } @@ -379,7 +379,7 @@ func gatewayUpstream(preset *adminv1.Preset, path string) (gatewayv1.Upstream, e } full = joined } - return parseSSEUpstream(full) + return gatewayv1.ParseUpstream(full) } // makeSpectreSSERouteName returns a deterministic Route name for a Spectre listener's SSE endpoint. @@ -426,17 +426,3 @@ func dedupeOrdered(values []string) []string { } return out } - -// parseSSEUpstream parses a raw URL into a gateway Upstream. -func parseSSEUpstream(rawUrl string) (gatewayv1.Upstream, error) { - u, err := url.Parse(rawUrl) - if err != nil { - return gatewayv1.Upstream{}, errors.Wrapf(err, "failed to parse URL %q", rawUrl) - } - return gatewayv1.Upstream{ - Scheme: u.Scheme, - Hostname: u.Hostname(), - Port: gatewayv1.GetPortOrDefaultFromScheme(u), - Path: u.Path, - }, nil -}