mirror of
https://github.com/fluxcd/flagger.git
synced 2026-02-14 18:10:00 +00:00
Add support for CORS policy to Gateway API
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
This commit is contained in:
@@ -6,13 +6,16 @@ This guide shows you how to use [Gateway API](https://gateway-api.sigs.k8s.io/)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Flagger requires a Kubernetes cluster **v1.19** or newer and any mesh/ingress that implements the `v1beta1` or the `v1` version of Gateway API.
|
||||
Flagger requires a Kubernetes cluster **v1.29** or newer and any mesh/ingress that
|
||||
implements the `v1` version of Gateway API.
|
||||
|
||||
We'll be using Istio for the sake of this tutorial, but you can use any other implementation.
|
||||
|
||||
Install the Gateway API CRDs
|
||||
|
||||
```bash
|
||||
kubectl apply -k "github.com/kubernetes-sigs/gateway-api/config/crd?ref=v1.0.0"
|
||||
# Suggestion: Change v1.4.0 in to the latest Gateway API version
|
||||
kubectl apply --server-side -k "github.com/kubernetes-sigs/gateway-api/config/crd?ref=v1.4.0"
|
||||
```
|
||||
|
||||
Install Istio:
|
||||
@@ -20,8 +23,8 @@ Install Istio:
|
||||
```bash
|
||||
istioctl install --set profile=minimal -y
|
||||
|
||||
# Suggestion: Please change release-1.20 in below command, to your real istio version.
|
||||
kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.20/samples/addons/prometheus.yaml
|
||||
# Suggestion: Change release-1.27 in to the latest Istio version
|
||||
kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.27/samples/addons/prometheus.yaml
|
||||
```
|
||||
|
||||
Install Flagger in the `flagger-system` namespace:
|
||||
@@ -37,9 +40,6 @@ helm upgrade -i flagger flagger/flagger \
|
||||
--set metricsServer=http://prometheus.istio-system:9090
|
||||
```
|
||||
|
||||
> Note: The above installation sets the mesh provider to be `gatewayapi:v1`. If your Gateway API implementation uses the `v1beta1` CRDs, then
|
||||
set the `--meshProvider` value to `gatewayapi:v1beta1`.
|
||||
|
||||
Create a namespace for the `Gateway`:
|
||||
|
||||
```bash
|
||||
@@ -49,7 +49,7 @@ kubectl create ns istio-ingress
|
||||
Create a `Gateway` that configures load balancing, traffic ACL, etc:
|
||||
|
||||
```yaml
|
||||
apiVersion: gateway.networking.k8s.io/v1beta1
|
||||
apiVersion: gateway.networking.k8s.io/v1
|
||||
kind: Gateway
|
||||
metadata:
|
||||
name: gateway
|
||||
@@ -68,7 +68,9 @@ spec:
|
||||
|
||||
## Bootstrap
|
||||
|
||||
Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler \(HPA\), then creates a series of objects \(Kubernetes deployments, ClusterIP services, HTTPRoutes for the Gateway\). These objects expose the application inside the mesh and drive the canary analysis and promotion.
|
||||
Flagger takes a Kubernetes deployment and optionally a horizontal pod autoscaler \(HPA\),
|
||||
then creates a series of objects \(Kubernetes deployments, ClusterIP services, HTTPRoutes for the Gateway\).
|
||||
These objects expose the application inside the mesh and drive the canary analysis and promotion.
|
||||
|
||||
Create a test namespace:
|
||||
|
||||
@@ -88,7 +90,9 @@ Deploy the load testing service to generate traffic during the canary analysis:
|
||||
kubectl apply -k https://github.com/fluxcd/flagger//kustomize/tester?ref=main
|
||||
```
|
||||
|
||||
Create metric templates targeting the Prometheus server in the `flagger-system` namespace. The PromQL queries below are meant for `Envoy`, but you can [change it to your ingress/mesh provider](https://docs.flagger.app/faq#metrics) accordingly.
|
||||
Create metric templates targeting the Prometheus server in the `flagger-system` namespace.
|
||||
The PromQL queries below are meant for `Envoy`,
|
||||
but you can [change it to your ingress/mesh provider](https://docs.flagger.app/faq#metrics) accordingly.
|
||||
|
||||
```yaml
|
||||
apiVersion: flagger.app/v1beta1
|
||||
@@ -237,7 +241,8 @@ Save the above resource as podinfo-canary.yaml and then apply it:
|
||||
kubectl apply -f ./podinfo-canary.yaml
|
||||
```
|
||||
|
||||
When the canary analysis starts, Flagger will call the pre-rollout webhooks before routing traffic to the canary. The canary analysis will run for five minutes while validating the HTTP metrics and rollout hooks every minute.
|
||||
When the canary analysis starts, Flagger will call the pre-rollout webhooks before routing traffic to the canary.
|
||||
The canary analysis will run for five minutes while validating the HTTP metrics and rollout hooks every minute.
|
||||
|
||||
After a couple of seconds Flagger will create the canary objects:
|
||||
|
||||
@@ -266,19 +271,22 @@ export ADDRESS="$(kubectl -n istio-ingress get svc/gateway-istio -ojson \
|
||||
echo $ADDRESS
|
||||
```
|
||||
|
||||
Configure your DNS server with a CNAME record \(AWS\) or A record \(GKE/AKS/DOKS\) and point a domain e.g. `www.example.com` to the LB address.
|
||||
Configure your DNS server with a CNAME record \(AWS\) or A record \(GKE/AKS/DOKS\) and
|
||||
point a domain e.g. `www.example.com` to the LB address.
|
||||
|
||||
Now you can access the podinfo UI using your domain address.
|
||||
|
||||
Note that you should be using HTTPS when exposing production workloads on internet. You can obtain free TLS certs from Let's Encrypt, read this
|
||||
Note that you should be using HTTPS when exposing production workloads on internet.
|
||||
You can obtain free TLS certs from Let's Encrypt, read this
|
||||
[guide](https://github.com/stefanprodan/istio-gke) on how to configure cert-manager to secure Istio with TLS certificates.
|
||||
|
||||
If you're using a local cluster via kind/k3s you can port forward the Envoy LoadBalancer service:
|
||||
|
||||
```bash
|
||||
kubectl port-forward -n istio-ingress svc/gateway-istio 8080:80
|
||||
```
|
||||
|
||||
Now you can access podinfo via `curl -H "Host: www.example.com" localhost:8080`
|
||||
Now you can access podinfo via `curl -H "Host: www.example.com" localhost:8080`.
|
||||
|
||||
## Automated canary promotion
|
||||
|
||||
@@ -319,7 +327,8 @@ Events:
|
||||
Normal Synced 5s flagger Promotion completed! Scaling down podinfo.test
|
||||
```
|
||||
|
||||
**Note** that if you apply new changes to the deployment during the canary analysis, Flagger will restart the analysis.
|
||||
**Note** that if you apply new changes to the deployment during the canary analysis,
|
||||
Flagger will restart the analysis.
|
||||
|
||||
A canary deployment is triggered by changes in any of the following objects:
|
||||
|
||||
@@ -327,7 +336,8 @@ A canary deployment is triggered by changes in any of the following objects:
|
||||
* ConfigMaps mounted as volumes or mapped to environment variables
|
||||
* Secrets mounted as volumes or mapped to environment variables
|
||||
|
||||
You can monitor how Flagger progressively changes the weights of the HTTPRoute object that is attahed to the Gateway with:
|
||||
You can monitor how Flagger progressively changes the weights of
|
||||
the HTTPRoute object that is attached to the Gateway with:
|
||||
|
||||
```bash
|
||||
watch kubectl get httproute -n test podinfo -o=jsonpath='{.spec.rules}'
|
||||
@@ -339,9 +349,9 @@ You can monitor all canaries with:
|
||||
watch kubectl get canaries --all-namespaces
|
||||
|
||||
NAMESPACE NAME STATUS WEIGHT LASTTRANSITIONTIME
|
||||
test podinfo Progressing 15 2022-01-16T14:05:07Z
|
||||
prod frontend Succeeded 0 2022-01-15T16:15:07Z
|
||||
prod backend Failed 0 2022-01-14T17:05:07Z
|
||||
test podinfo Progressing 15 2025-10-16T14:05:07Z
|
||||
prod frontend Succeeded 0 2025-10-15T16:15:07Z
|
||||
prod backend Failed 0 2025-10-14T17:05:07Z
|
||||
```
|
||||
|
||||
## Automated rollback
|
||||
@@ -373,7 +383,8 @@ Generate latency:
|
||||
watch curl http://podinfo-canary:9898/delay/1
|
||||
```
|
||||
|
||||
When the number of failed checks reaches the canary analysis threshold, the traffic is routed back to the primary, the canary is scaled to zero and the rollout is marked as failed.
|
||||
When the number of failed checks reaches the canary analysis threshold,
|
||||
the traffic is routed back to the primary, the canary is scaled to zero and the rollout is marked as failed.
|
||||
|
||||
```text
|
||||
kubectl -n test describe canary/podinfo
|
||||
@@ -398,13 +409,142 @@ Events:
|
||||
Warning Synced 1m flagger Canary failed! Scaling down podinfo.test
|
||||
```
|
||||
|
||||
## A/B Testing
|
||||
|
||||
Besides weighted routing, Flagger can be configured to route traffic to the canary based on HTTP match conditions.
|
||||
In an A/B testing scenario, you'll be using HTTP headers and cookies to target a certain segment of your users.
|
||||
|
||||

|
||||
|
||||
Create a canary custom resource \(replace "www.example.com" with your own domain\):
|
||||
|
||||
```yaml
|
||||
apiVersion: flagger.app/v1beta1
|
||||
kind: Canary
|
||||
metadata:
|
||||
name: podinfo
|
||||
namespace: test
|
||||
spec:
|
||||
# deployment reference
|
||||
targetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: podinfo
|
||||
# the maximum time in seconds for the canary deployment
|
||||
# to make progress before it is rollback (default 600s)
|
||||
progressDeadlineSeconds: 60
|
||||
# HPA reference (optional)
|
||||
autoscalerRef:
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
name: podinfo
|
||||
service:
|
||||
# service port number
|
||||
port: 9898
|
||||
# container port number or name (optional)
|
||||
targetPort: 9898
|
||||
# Gateway API HTTPRoute host names
|
||||
hosts:
|
||||
- www.example.com
|
||||
# Reference to the Gateway that the generated HTTPRoute would attach to.
|
||||
gatewayRefs:
|
||||
- name: gateway
|
||||
namespace: istio-ingress
|
||||
analysis:
|
||||
# schedule interval (default 60s)
|
||||
interval: 1m
|
||||
# total number of iterations
|
||||
iterations: 10
|
||||
# max number of failed iterations before rollback
|
||||
threshold: 2
|
||||
# canary match condition
|
||||
match:
|
||||
- headers:
|
||||
user-agent:
|
||||
regex: ".*Firefox.*"
|
||||
- headers:
|
||||
cookie:
|
||||
regex: "^(.*?;)?(type=insider)(;.*)?$"
|
||||
metrics:
|
||||
- name: error-rate
|
||||
# max error rate (5xx responses)
|
||||
# percentage (0-100)
|
||||
templateRef:
|
||||
name: error-rate
|
||||
namespace: flagger-system
|
||||
thresholdRange:
|
||||
max: 1
|
||||
interval: 1m
|
||||
- name: latency
|
||||
templateRef:
|
||||
name: latency
|
||||
namespace: flagger-system
|
||||
# seconds
|
||||
thresholdRange:
|
||||
max: 0.5
|
||||
interval: 30s
|
||||
# testing (optional)
|
||||
webhooks:
|
||||
- name: load-test
|
||||
url: http://flagger-loadtester.test/
|
||||
timeout: 5s
|
||||
metadata:
|
||||
cmd: "hey -z 2m -q 10 -c 2 -host www.example.com -H 'Cookie: type=insider' http://gateway-istio.istio-ingress/"
|
||||
```
|
||||
|
||||
The above configuration will run an analysis for ten minutes targeting those users that
|
||||
have an insider cookie or are using Firefox as a browser.
|
||||
|
||||
Save the above resource as podinfo-ab-canary.yaml and then apply it:
|
||||
|
||||
```bash
|
||||
kubectl apply -f ./podinfo-ab-canary.yaml
|
||||
```
|
||||
|
||||
Trigger a canary deployment by updating the container image:
|
||||
|
||||
```bash
|
||||
kubectl -n test set image deployment/podinfo \
|
||||
podinfod=stefanprodan/podinfo:6.0.3
|
||||
```
|
||||
|
||||
Flagger detects that the deployment revision changed and starts a new rollout:
|
||||
|
||||
```text
|
||||
kubectl -n test describe canary/podinfo
|
||||
|
||||
Status:
|
||||
Failed Checks: 0
|
||||
Phase: Succeeded
|
||||
Events:
|
||||
Type Reason Age From Message
|
||||
---- ------ ---- ---- -------
|
||||
Normal Synced 3m flagger New revision detected podinfo.test
|
||||
Normal Synced 3m flagger Scaling up podinfo.test
|
||||
Warning Synced 3m flagger Waiting for podinfo.test rollout to finish: 0 of 1 updated replicas are available
|
||||
Normal Synced 3m flagger Advance podinfo.test canary iteration 1/10
|
||||
Normal Synced 3m flagger Advance podinfo.test canary iteration 2/10
|
||||
Normal Synced 3m flagger Advance podinfo.test canary iteration 3/10
|
||||
Normal Synced 2m flagger Advance podinfo.test canary iteration 4/10
|
||||
Normal Synced 2m flagger Advance podinfo.test canary iteration 5/10
|
||||
Normal Synced 1m flagger Advance podinfo.test canary iteration 6/10
|
||||
Normal Synced 1m flagger Advance podinfo.test canary iteration 7/10
|
||||
Normal Synced 55s flagger Advance podinfo.test canary iteration 8/10
|
||||
Normal Synced 45s flagger Advance podinfo.test canary iteration 9/10
|
||||
Normal Synced 35s flagger Advance podinfo.test canary iteration 10/10
|
||||
Normal Synced 25s flagger Copying podinfo.test template spec to podinfo-primary.test
|
||||
Warning Synced 15s flagger Waiting for podinfo-primary.test rollout to finish: 1 of 2 updated replicas are available
|
||||
Normal Synced 5s flagger Promotion completed! Scaling down podinfo.test
|
||||
```
|
||||
|
||||
## Session Affinity
|
||||
|
||||
While Flagger can perform weighted routing and A/B testing individually, with Gateway API it can combine the two leading to a Canary
|
||||
release with session affinity.
|
||||
While Flagger can perform weighted routing and A/B testing individually,
|
||||
with Gateway API it can combine the two leading to a Canary release with session affinity.
|
||||
For more information you can read the [deployment strategies docs](../usage/deployment-strategies.md#canary-release-with-session-affinity).
|
||||
|
||||
> **Note:** The implementation must have support for the [`ResponseHeaderModifier`](https://github.com/kubernetes-sigs/gateway-api/blob/3d22aa5a08413222cb79e6b2e245870360434614/apis/v1beta1/httproute_types.go#L651) API.
|
||||
> **Note:** Session Affinity requires a Gateway API implementation that supports
|
||||
> the [`ResponseHeaderModifier`](https://gateway-api.sigs.k8s.io/guides/http-header-modifier/) API.
|
||||
|
||||
Create a canary custom resource \(replace www.example.com with your own domain\):
|
||||
|
||||
@@ -478,13 +618,6 @@ spec:
|
||||
interval: 30s
|
||||
# testing (optional)
|
||||
webhooks:
|
||||
- name: smoke-test
|
||||
type: pre-rollout
|
||||
url: http://flagger-loadtester.test/
|
||||
timeout: 15s
|
||||
metadata:
|
||||
type: bash
|
||||
cmd: "curl -sd 'anon' http://podinfo-canary.test:9898/token | grep token"
|
||||
- name: load-test
|
||||
url: http://flagger-loadtester.test/
|
||||
timeout: 5s
|
||||
@@ -512,145 +645,14 @@ configured by Flagger in the HTTPRoute object.
|
||||
To configure stickiness for the Primary deployment to ensure fair weighted traffic routing, please
|
||||
checkout the [deployment strategies docs](../usage/deployment-strategies.md#canary-release-with-session-affinity).
|
||||
|
||||
# A/B Testing
|
||||
|
||||
Besides weighted routing, Flagger can be configured to route traffic to the canary based on HTTP match conditions. In an A/B testing scenario, you'll be using HTTP headers or cookies to target a certain segment of your users. This is particularly useful for frontend applications that require session affinity.
|
||||
|
||||

|
||||
|
||||
Create a canary custom resource \(replace "www.example.com" with your own domain\):
|
||||
|
||||
```yaml
|
||||
apiVersion: flagger.app/v1beta1
|
||||
kind: Canary
|
||||
metadata:
|
||||
name: podinfo
|
||||
namespace: test
|
||||
spec:
|
||||
# deployment reference
|
||||
targetRef:
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
name: podinfo
|
||||
# the maximum time in seconds for the canary deployment
|
||||
# to make progress before it is rollback (default 600s)
|
||||
progressDeadlineSeconds: 60
|
||||
# HPA reference (optional)
|
||||
autoscalerRef:
|
||||
apiVersion: autoscaling/v2
|
||||
kind: HorizontalPodAutoscaler
|
||||
name: podinfo
|
||||
service:
|
||||
# service port number
|
||||
port: 9898
|
||||
# container port number or name (optional)
|
||||
targetPort: 9898
|
||||
# Gateway API HTTPRoute host names
|
||||
hosts:
|
||||
- www.example.com
|
||||
# Reference to the Gateway that the generated HTTPRoute would attach to.
|
||||
gatewayRefs:
|
||||
- name: gateway
|
||||
namespace: istio-ingress
|
||||
analysis:
|
||||
# schedule interval (default 60s)
|
||||
interval: 1m
|
||||
# max number of failed metric checks before rollback
|
||||
threshold: 5
|
||||
# max traffic percentage routed to canary
|
||||
# percentage (0-100)
|
||||
maxWeight: 50
|
||||
# canary increment step
|
||||
# percentage (0-100)
|
||||
stepWeight: 10
|
||||
metrics:
|
||||
- name: error-rate
|
||||
# max error rate (5xx responses)
|
||||
# percentage (0-100)
|
||||
templateRef:
|
||||
name: error-rate
|
||||
namespace: flagger-system
|
||||
thresholdRange:
|
||||
max: 1
|
||||
interval: 1m
|
||||
- name: latency
|
||||
templateRef:
|
||||
name: latency
|
||||
namespace: flagger-system
|
||||
# seconds
|
||||
thresholdRange:
|
||||
max: 0.5
|
||||
interval: 30s
|
||||
# testing (optional)
|
||||
webhooks:
|
||||
- name: smoke-test
|
||||
type: pre-rollout
|
||||
url: http://flagger-loadtester.test/
|
||||
timeout: 15s
|
||||
metadata:
|
||||
type: bash
|
||||
cmd: "curl -sd 'anon' http://podinfo-canary.test:9898/token | grep token"
|
||||
- name: load-test
|
||||
url: http://flagger-loadtester.test/
|
||||
timeout: 5s
|
||||
metadata:
|
||||
cmd: "hey -z 2m -q 10 -c 2 -host www.example.com -H 'X-Canary: insider' http://gateway-istio.istio-ingress/"
|
||||
```
|
||||
|
||||
The above configuration will run an analysis for ten minutes targeting those users that have an insider cookie.
|
||||
|
||||
Save the above resource as podinfo-ab-canary.yaml and then apply it:
|
||||
|
||||
```bash
|
||||
kubectl apply -f ./podinfo-ab-canary.yaml
|
||||
```
|
||||
|
||||
Trigger a canary deployment by updating the container image:
|
||||
|
||||
```bash
|
||||
kubectl -n test set image deployment/podinfo \
|
||||
podinfod=stefanprodan/podinfo:6.0.3
|
||||
```
|
||||
|
||||
Flagger detects that the deployment revision changed and starts a new rollout:
|
||||
|
||||
```text
|
||||
kubectl -n test describe canary/podinfo
|
||||
|
||||
Status:
|
||||
Failed Checks: 0
|
||||
Phase: Succeeded
|
||||
Events:
|
||||
Type Reason Age From Message
|
||||
---- ------ ---- ---- -------
|
||||
Normal Synced 3m flagger New revision detected podinfo.test
|
||||
Normal Synced 3m flagger Scaling up podinfo.test
|
||||
Warning Synced 3m flagger Waiting for podinfo.test rollout to finish: 0 of 1 updated replicas are available
|
||||
Normal Synced 3m flagger Advance podinfo.test canary iteration 1/10
|
||||
Normal Synced 3m flagger Advance podinfo.test canary iteration 2/10
|
||||
Normal Synced 3m flagger Advance podinfo.test canary iteration 3/10
|
||||
Normal Synced 2m flagger Advance podinfo.test canary iteration 4/10
|
||||
Normal Synced 2m flagger Advance podinfo.test canary iteration 5/10
|
||||
Normal Synced 1m flagger Advance podinfo.test canary iteration 6/10
|
||||
Normal Synced 1m flagger Advance podinfo.test canary iteration 7/10
|
||||
Normal Synced 55s flagger Advance podinfo.test canary iteration 8/10
|
||||
Normal Synced 45s flagger Advance podinfo.test canary iteration 9/10
|
||||
Normal Synced 35s flagger Advance podinfo.test canary iteration 10/10
|
||||
Normal Synced 25s flagger Copying podinfo.test template spec to podinfo-primary.test
|
||||
Warning Synced 15s flagger Waiting for podinfo-primary.test rollout to finish: 1 of 2 updated replicas are available
|
||||
Normal Synced 5s flagger Promotion completed! Scaling down podinfo.test
|
||||
```
|
||||
|
||||
## Traffic mirroring
|
||||
|
||||

|
||||
|
||||
For applications that perform read operations, Flagger can be configured to do B/G tests with traffic mirroring.
|
||||
Gateway API traffic mirroring will copy each incoming request, sending one request to the primary and one to the canary service.
|
||||
The response from the primary is sent back to the user and the response from the canary is discarded.
|
||||
Metrics are collected on both requests so that the deployment will only proceed if the canary metrics are within the threshold values.
|
||||
|
||||
Note that mirroring should be used for requests that are **idempotent** or capable of being processed twice \(once by the primary and once by the canary\).
|
||||
> **Note:** Traffic mirroring requires a Gateway API implementation that supports
|
||||
> the [`RequestMirror`](https://gateway-api.sigs.k8s.io/guides/http-request-mirroring/) filter.
|
||||
|
||||
You can enable mirroring by replacing `stepWeight` with `iterations` and by setting `analysis.mirror` to `true`:
|
||||
|
||||
@@ -705,26 +707,49 @@ spec:
|
||||
cmd: "hey -z 2m -q 10 -c 2 -host www.example.com http://gateway-istio.istio-ingress/"
|
||||
```
|
||||
|
||||
With the above configuration, Flagger will run a canary release with the following steps:
|
||||
Gateway API traffic mirroring will copy each incoming request, sending one request to the primary and one to the canary service.
|
||||
The response from the primary is sent back to the user and the response from the canary is discarded.
|
||||
|
||||
* detect new revision \(deployment spec, secrets or configmaps changes\)
|
||||
* scale from zero the canary deployment
|
||||
* wait for the HPA to set the canary minimum replicas
|
||||
* check canary pods health
|
||||
* run the acceptance tests
|
||||
* abort the canary release if tests fail
|
||||
* start the load tests
|
||||
* mirror 100% of the traffic from primary to canary
|
||||
* check request success rate and request duration every minute
|
||||
* abort the canary release if the metrics check failure threshold is reached
|
||||
* stop traffic mirroring after the number of iterations is reached
|
||||
* route live traffic to the canary pods
|
||||
* promote the canary \(update the primary secrets, configmaps and deployment spec\)
|
||||
* wait for the primary deployment rollout to finish
|
||||
* wait for the HPA to set the primary minimum replicas
|
||||
* check primary pods health
|
||||
* switch live traffic back to primary
|
||||
* scale to zero the canary
|
||||
* send notification with the canary analysis result
|
||||
Metrics are collected on both requests so that the deployment will only proceed if the canary metrics are within the threshold values.
|
||||
|
||||
The above procedures can be extended with [custom metrics](../usage/metrics.md) checks, [webhooks](../usage/webhooks.md), [manual promotion](../usage/webhooks.md#manual-gating) approval and [Slack or MS Teams](../usage/alerting.md) notifications.
|
||||
|
||||
## CORS Support
|
||||
|
||||
The cross-origin resource sharing policy can be configured the `spec.service.corsPolicy` field of the Canary.
|
||||
|
||||
> **Note:** Cross-origin resource sharing requires a Gateway API implementation that supports
|
||||
> the [`CORS`](https://gateway-api.sigs.k8s.io/geps/gep-1767/) filter.
|
||||
|
||||
Example configuration:
|
||||
|
||||
```yaml
|
||||
apiVersion: flagger.app/v1beta1
|
||||
kind: Canary
|
||||
metadata:
|
||||
name: podinfo
|
||||
namespace: test
|
||||
spec:
|
||||
service:
|
||||
corsPolicy:
|
||||
allowOrigin:
|
||||
- https://foo.example
|
||||
- http://foo.example
|
||||
allowMethods:
|
||||
- GET
|
||||
- PUT
|
||||
- POST
|
||||
- DELETE
|
||||
- PATCH
|
||||
- OPTIONS
|
||||
allowCredentials: true
|
||||
allowHeaders:
|
||||
- Keep-Alive
|
||||
- User-Agent
|
||||
- X-Requested-With
|
||||
- If-Modified-Since
|
||||
- Cache-Control
|
||||
- Content-Type
|
||||
- Authorization
|
||||
maxAge: 24h
|
||||
```
|
||||
|
||||
@@ -839,6 +839,14 @@ func (gwr *GatewayAPIRouter) makeFilters(canary *flaggerv1.Canary) []v1.HTTPRout
|
||||
filters = append(filters, mirrorFilter)
|
||||
}
|
||||
|
||||
if canary.Spec.Service.CorsPolicy != nil {
|
||||
corsFilter := v1.HTTPRouteFilter{
|
||||
Type: v1.HTTPRouteFilterCORS,
|
||||
CORS: gwr.toV1CORSFilter(canary.Spec.Service.CorsPolicy),
|
||||
}
|
||||
filters = append(filters, corsFilter)
|
||||
}
|
||||
|
||||
return filters
|
||||
}
|
||||
|
||||
@@ -854,6 +862,62 @@ func toV1RequestMirrorFilter(requestMirror v1beta1.HTTPRequestMirrorFilter) *v1.
|
||||
}
|
||||
}
|
||||
|
||||
func (gwr *GatewayAPIRouter) toV1CORSFilter(corsPolicy *istiov1beta1.CorsPolicy) *v1.HTTPCORSFilter {
|
||||
cors := &v1.HTTPCORSFilter{}
|
||||
|
||||
// Note: CorsPolicy.AllowOrigins (StringMatch patterns) is not mapped because
|
||||
// Gateway API HTTPCORSFilter.AllowOrigins only supports simple origin strings,
|
||||
if len(corsPolicy.AllowOrigins) > 0 {
|
||||
gwr.logger.Errorf("'corsPolicy.allowOrigins' is not supported by Gateway API, use 'corsPolicy.allowOrigin' instead")
|
||||
}
|
||||
|
||||
// Map AllowOrigin to AllowOrigins
|
||||
// not pattern matching like Istio's StringMatch type.
|
||||
if len(corsPolicy.AllowOrigin) > 0 {
|
||||
for _, origin := range corsPolicy.AllowOrigin {
|
||||
cors.AllowOrigins = append(cors.AllowOrigins, v1.CORSOrigin(origin))
|
||||
}
|
||||
}
|
||||
|
||||
// Map AllowMethods
|
||||
if len(corsPolicy.AllowMethods) > 0 {
|
||||
for _, method := range corsPolicy.AllowMethods {
|
||||
cors.AllowMethods = append(cors.AllowMethods, v1.HTTPMethodWithWildcard(method))
|
||||
}
|
||||
}
|
||||
|
||||
// Map AllowHeaders
|
||||
if len(corsPolicy.AllowHeaders) > 0 {
|
||||
for _, header := range corsPolicy.AllowHeaders {
|
||||
cors.AllowHeaders = append(cors.AllowHeaders, v1.HTTPHeaderName(header))
|
||||
}
|
||||
}
|
||||
|
||||
// Map ExposeHeaders
|
||||
if len(corsPolicy.ExposeHeaders) > 0 {
|
||||
for _, header := range corsPolicy.ExposeHeaders {
|
||||
cors.ExposeHeaders = append(cors.ExposeHeaders, v1.HTTPHeaderName(header))
|
||||
}
|
||||
}
|
||||
|
||||
// Map AllowCredentials
|
||||
if corsPolicy.AllowCredentials {
|
||||
allow := true
|
||||
cors.AllowCredentials = &allow
|
||||
}
|
||||
|
||||
// Map MaxAge - convert duration string to seconds
|
||||
if corsPolicy.MaxAge != "" {
|
||||
// Parse duration string (e.g., "1d", "24h", "5s")
|
||||
duration, err := time.ParseDuration(corsPolicy.MaxAge)
|
||||
if err == nil {
|
||||
cors.MaxAge = int32(duration.Seconds())
|
||||
}
|
||||
}
|
||||
|
||||
return cors
|
||||
}
|
||||
|
||||
func toV1ParentRefs(gatewayRefs []v1beta1.ParentReference) []v1.ParentReference {
|
||||
parentRefs := make([]v1.ParentReference, 0)
|
||||
for i := 0; i < len(gatewayRefs); i++ {
|
||||
|
||||
@@ -23,14 +23,16 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1"
|
||||
v1 "github.com/fluxcd/flagger/pkg/apis/gatewayapi/v1"
|
||||
istiov1beta1 "github.com/fluxcd/flagger/pkg/apis/istio/v1beta1"
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
|
||||
flaggerv1 "github.com/fluxcd/flagger/pkg/apis/flagger/v1beta1"
|
||||
v1 "github.com/fluxcd/flagger/pkg/apis/gatewayapi/v1"
|
||||
istiov1alpha1 "github.com/fluxcd/flagger/pkg/apis/istio/common/v1alpha1"
|
||||
istiov1beta1 "github.com/fluxcd/flagger/pkg/apis/istio/v1beta1"
|
||||
)
|
||||
|
||||
func TestGatewayAPIRouter_Reconcile(t *testing.T) {
|
||||
@@ -538,3 +540,66 @@ func TestGatewayAPIRouter_makeFilters(t *testing.T) {
|
||||
assert.Equal(t, "", filtersDiff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayAPIRouter_makeFilters_CORS(t *testing.T) {
|
||||
canary := newTestGatewayAPICanary()
|
||||
mocks := newFixture(canary)
|
||||
|
||||
// Configure CORS policy
|
||||
canary.Spec.Service.CorsPolicy = &istiov1beta1.CorsPolicy{
|
||||
AllowOrigins: []*istiov1alpha1.StringMatch{{Regex: ".*example.com"}}, // ignored
|
||||
AllowOrigin: []string{"https://example.com", "https://app.example.com"},
|
||||
AllowMethods: []string{"GET", "POST", "PUT"},
|
||||
AllowHeaders: []string{"Content-Type", "Authorization"},
|
||||
ExposeHeaders: []string{"X-Custom-Header"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: "24h",
|
||||
}
|
||||
|
||||
router := &GatewayAPIRouter{
|
||||
gatewayAPIClient: mocks.meshClient,
|
||||
kubeClient: mocks.kubeClient,
|
||||
logger: mocks.logger,
|
||||
}
|
||||
|
||||
filters := router.makeFilters(canary)
|
||||
|
||||
// Find the CORS filter
|
||||
var corsFilter *v1.HTTPRouteFilter
|
||||
for i := range filters {
|
||||
if filters[i].Type == v1.HTTPRouteFilterCORS {
|
||||
corsFilter = &filters[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
require.NotNil(t, corsFilter, "CORS filter should be present")
|
||||
require.NotNil(t, corsFilter.CORS, "CORS configuration should not be nil")
|
||||
|
||||
// Assert AllowOrigins
|
||||
assert.Len(t, corsFilter.CORS.AllowOrigins, 2)
|
||||
assert.Equal(t, v1.CORSOrigin("https://example.com"), corsFilter.CORS.AllowOrigins[0])
|
||||
assert.Equal(t, v1.CORSOrigin("https://app.example.com"), corsFilter.CORS.AllowOrigins[1])
|
||||
|
||||
// Assert AllowMethods
|
||||
assert.Len(t, corsFilter.CORS.AllowMethods, 3)
|
||||
assert.Equal(t, v1.HTTPMethodWithWildcard("GET"), corsFilter.CORS.AllowMethods[0])
|
||||
assert.Equal(t, v1.HTTPMethodWithWildcard("POST"), corsFilter.CORS.AllowMethods[1])
|
||||
assert.Equal(t, v1.HTTPMethodWithWildcard("PUT"), corsFilter.CORS.AllowMethods[2])
|
||||
|
||||
// Assert AllowHeaders
|
||||
assert.Len(t, corsFilter.CORS.AllowHeaders, 2)
|
||||
assert.Equal(t, v1.HTTPHeaderName("Content-Type"), corsFilter.CORS.AllowHeaders[0])
|
||||
assert.Equal(t, v1.HTTPHeaderName("Authorization"), corsFilter.CORS.AllowHeaders[1])
|
||||
|
||||
// Assert ExposeHeaders
|
||||
assert.Len(t, corsFilter.CORS.ExposeHeaders, 1)
|
||||
assert.Equal(t, v1.HTTPHeaderName("X-Custom-Header"), corsFilter.CORS.ExposeHeaders[0])
|
||||
|
||||
// Assert AllowCredentials
|
||||
require.NotNil(t, corsFilter.CORS.AllowCredentials)
|
||||
assert.True(t, *corsFilter.CORS.AllowCredentials)
|
||||
|
||||
// Assert MaxAge (24h = 86400 seconds)
|
||||
assert.Equal(t, int32(86400), corsFilter.CORS.MaxAge)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user