diff --git a/deployment-configuration/helm/templates/ingress.yaml b/deployment-configuration/helm/templates/ingress.yaml index 143bdeb2..029261e0 100644 --- a/deployment-configuration/helm/templates/ingress.yaml +++ b/deployment-configuration/helm/templates/ingress.yaml @@ -92,10 +92,32 @@ port: number: {{- if (and $app.harness.secured $secured_gatekeepers) }} 8080 {{- else }} {{ $app.harness.service.port | default 80 }}{{- end }} {{- end }} +{{- define "deploy_utils.ingress.cors.nginx" }} +{{- $scheme := ternary "https" "http" (not (not .Values.tls)) }} +{{- $cors := .Values.ingress.cors }} +{{- $origins := list (printf "%s://*.%s" $scheme .Values.domain) (printf "%s://%s" $scheme .Values.domain) }} +{{- /* The nginx wildcard matches a single label: list the nested hosts (e.g. instance.app.) one by one. */}} +{{- range $app := .Values.apps }} + {{- range $subdomain := prepend ($app.harness.aliases | default list) ($app.harness.subdomain | default "") }} + {{- if contains "." $subdomain }} + {{- $origins = append $origins (printf "%s://%s.%s" $scheme $subdomain $.Values.domain) }} + {{- end }} + {{- end }} +{{- end }} +nginx.ingress.kubernetes.io/enable-cors: "true" +nginx.ingress.kubernetes.io/cors-allow-origin: {{ $origins | uniq | join "," | quote }} +nginx.ingress.kubernetes.io/cors-allow-credentials: "true" +nginx.ingress.kubernetes.io/cors-allow-methods: {{ join "," $cors.allowMethods | quote }} +nginx.ingress.kubernetes.io/cors-allow-headers: {{ join "," $cors.allowHeaders | quote }} +{{- with $cors.exposeHeaders }} +nginx.ingress.kubernetes.io/cors-expose-headers: {{ join "," . | quote }} +{{- end }} +{{- end }} {{- if .Values.ingress.enabled }} {{- $domain := .Values.domain }} {{- $tls := not (not .Values.tls) }} {{- $mainapp := .Values.mainapp }} + {{- $cors := (.Values.ingress.cors | default dict).enabled }} {{- range $app := .Values.apps }} {{- if or $app.harness.subdomain $app.harness.domain $app.harness.aliases (and $mainapp (and $app.harness.name (eq $app.harness.name $mainapp))) }} {{- $appIngressName := default $app.harness.service.name $app.harness.name }} @@ -122,8 +144,11 @@ metadata: nginx.ingress.kubernetes.io/proxy-read-timeout: {{ $app.harness.proxy.timeout.read | default $.Values.proxy.timeout.read | default 180 | quote }} nginx.ingress.kubernetes.io/proxy-send-timeout: {{ $app.harness.proxy.timeout.send | default $.Values.proxy.timeout.send | default 180 | quote }} nginx.ingress.kubernetes.io/use-forwarded-headers: {{ $.Values.proxy.forwardedHeaders | quote }} + {{- if $cors }} + {{- include "deploy_utils.ingress.cors.nginx" $ | nindent 4 }} + {{- end }} {{- else if eq $.Values.ingress.ingressClass "traefik" }} - traefik.ingress.kubernetes.io/router.middlewares: {{ printf "%s-ch-body-size@kubernetescrd" $.Values.namespace }}{{ if and $tls $.Values.ingress.ssl_redirect }},{{ printf "%s-ch-ssl-redirect@kubernetescrd" $.Values.namespace }}{{ end }} + traefik.ingress.kubernetes.io/router.middlewares: {{ printf "%s-ch-body-size@kubernetescrd" $.Values.namespace }}{{ if and $tls $.Values.ingress.ssl_redirect }},{{ printf "%s-ch-ssl-redirect@kubernetescrd" $.Values.namespace }}{{ end }}{{ if $cors }},{{ printf "%s-ch-cors@kubernetescrd" $.Values.namespace }}{{ end }} {{- end }} {{- with $.Values.ingress.annotations }} {{- toYaml . | nindent 4 }} @@ -198,9 +223,12 @@ metadata: nginx.ingress.kubernetes.io/proxy-read-timeout: {{ $app.harness.proxy.timeout.read | default $.Values.proxy.timeout.read | default 180 | quote }} nginx.ingress.kubernetes.io/proxy-send-timeout: {{ $app.harness.proxy.timeout.send | default $.Values.proxy.timeout.send | default 180 | quote }} nginx.ingress.kubernetes.io/use-forwarded-headers: {{ $.Values.proxy.forwardedHeaders | quote }} + {{- if $cors }} + {{- include "deploy_utils.ingress.cors.nginx" $ | nindent 4 }} + {{- end }} {{- else if eq $.Values.ingress.ingressClass "traefik" }} traefik.ingress.kubernetes.io/router.pathmatcher: "PathRegexp" - traefik.ingress.kubernetes.io/router.middlewares: {{ printf "%s-ch-proxy-rewrite@kubernetescrd,%s-ch-body-size@kubernetescrd" $.Values.namespace $.Values.namespace }}{{ if and $tls $.Values.ingress.ssl_redirect }},{{ printf "%s-ch-ssl-redirect@kubernetescrd" $.Values.namespace }}{{ end }} + traefik.ingress.kubernetes.io/router.middlewares: {{ printf "%s-ch-proxy-rewrite@kubernetescrd,%s-ch-body-size@kubernetescrd" $.Values.namespace $.Values.namespace }}{{ if and $tls $.Values.ingress.ssl_redirect }},{{ printf "%s-ch-ssl-redirect@kubernetescrd" $.Values.namespace }}{{ end }}{{ if $cors }},{{ printf "%s-ch-cors@kubernetescrd" $.Values.namespace }}{{ end }} {{- end }} {{- with $.Values.ingress.annotations }} {{- toYaml . | nindent 4 }} diff --git a/deployment-configuration/helm/templates/traefik-middlewares.yaml b/deployment-configuration/helm/templates/traefik-middlewares.yaml index b3349384..393e7759 100644 --- a/deployment-configuration/helm/templates/traefik-middlewares.yaml +++ b/deployment-configuration/helm/templates/traefik-middlewares.yaml @@ -42,4 +42,25 @@ spec: scheme: https permanent: true {{- end }} +{{- $cors := .Values.ingress.cors | default dict }} +{{- if $cors.enabled }} +--- +# CORS: equivalent of nginx.ingress.kubernetes.io/enable-cors allowing and *. +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: ch-cors +spec: + headers: + accessControlAllowOriginListRegex: + - {{ printf "^%s://([A-Za-z0-9-]+\\.)*%s$" (ternary "https" "http" $tls) (regexQuoteMeta .Values.domain) | quote }} + accessControlAllowCredentials: true + accessControlAllowMethods: {{ toJson $cors.allowMethods }} + accessControlAllowHeaders: {{ toJson $cors.allowHeaders }} + {{- with $cors.exposeHeaders }} + accessControlExposeHeaders: {{ toJson . }} + {{- end }} + accessControlMaxAge: 1728000 + addVaryHeader: true +{{- end }} {{- end }} diff --git a/deployment-configuration/helm/values.yaml b/deployment-configuration/helm/values.yaml index 5966c02e..b79e36cf 100644 --- a/deployment-configuration/helm/values.yaml +++ b/deployment-configuration/helm/values.yaml @@ -39,6 +39,19 @@ ingress: ingressClass: nginx # -- Additional custom annotations to add to the Ingress resource. annotations: {} + cors: + # -- Allow credentialed cross-origin requests to every application from the + # deployment's own hosts (`` and `*.`). With nginx the wildcard is one + # level deep, and the applications' nested hosts are listed one by one. + # The ingress answers the preflights and its CORS headers replace the ones set by + # gatekeepers or applications for those origins. + enabled: false + # -- Methods allowed in cross-origin requests. + allowMethods: [GET, PUT, POST, DELETE, PATCH, OPTIONS] + # -- Request headers allowed in cross-origin requests. + allowHeaders: [DNT, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range, Authorization, X-CSRFToken] + # -- Response headers exposed to cross-origin callers. + exposeHeaders: [] # -- Enables/disables SSL redirect. ssl_redirect: true letsencrypt: diff --git a/docs/ingress-domains-proxies.md b/docs/ingress-domains-proxies.md index 98780737..51f04f4c 100644 --- a/docs/ingress-domains-proxies.md +++ b/docs/ingress-domains-proxies.md @@ -70,6 +70,35 @@ Note that in the case that gatekeepers are enabled, the same configurations are to the gatekeepers, unless the application override them on `harness.proxy.*`. See also the [gatekeepers documentation](./accounts.md#secure-and-endpoint-with-the-gatekeeper). +## Cross-origin requests between applications (CORS) + +Applications are served on different subdomains, so a page of one application calling the +API of another is a cross-origin request. To let the browser send such requests with +credentials (cookies, `Authorization`) to every application, enable CORS at the ingress in +your `deployment-configuration/values-template.yaml`: + +```yaml +ingress: + cors: + enabled: true + # Optional, defaults shown in deployment-configuration/helm/values.yaml + # allowMethods: [GET, PUT, POST, DELETE, PATCH, OPTIONS] + # allowHeaders: [..., Content-Type, Range, Authorization, X-CSRFToken] + # exposeHeaders: [] +``` + +The allowed origins are `` and `*.`, over https when TLS is enabled. +With nginx the wildcard matches a single subdomain level, so nested application hosts +(e.g. `instance.app.`) are added explicitly; with traefik the `ch-cors` middleware +accepts any depth. Origins outside the domain get no CORS headers from the ingress. + +The ingress answers the preflight (`OPTIONS`) requests itself and, for allowed origins, +its CORS headers replace the ones set by gatekeepers or applications. + +Every host of the domain becomes trusted by every application: a script running on any +`*.` page can read authenticated responses of all of them. Do not enable it when +a subdomain serves untrusted content. + ## Route pattern configuration Cloud Harness allows customizing which request paths are routed to an application diff --git a/tools/deployment-cli-tools/tests/test_helm.py b/tools/deployment-cli-tools/tests/test_helm.py index 68dc8c2b..69932396 100644 --- a/tools/deployment-cli-tools/tests/test_helm.py +++ b/tools/deployment-cli-tools/tests/test_helm.py @@ -1,6 +1,7 @@ import json import logging import os +import re import shutil import subprocess from pathlib import Path @@ -1324,6 +1325,94 @@ def render_gatekeeper(): assert inherited_checksum != tls_checksum +def test_ingress_cors_allows_deployment_subdomains(tmp_path): + out_folder = tmp_path / "test_ingress_cors" + create_helm_chart( + [CLOUDHARNESS_ROOT, RESOURCES], + output_path=out_folder, + domain="my.local", + namespace="test", + local=False, + tls=True, + include=["myapp", "accounts"], + exclude=["legacy"], + ) + + helm_path = out_folder / HELM_CHART_PATH + shutil.rmtree(helm_path / "charts") + values_path = helm_path / "values.yaml" + with open(values_path, "r") as values_file: + values = yaml.load(values_file) + values["apps"]["myapp"]["harness"]["use_services"] = [{"name": "accounts"}] + values["apps"]["myapp"]["harness"]["aliases"] = ["other", "instance.mysubdomain"] + + def render(): + with open(values_path, "w") as values_file: + yaml.dump(values, values_file) + return render_helm_chart(helm_path) + + def myapp_ingresses(manifests): + """The application ingress and its use_services proxy ingress.""" + ingresses = [ + m + for m in manifests + if m["kind"] == "Ingress" and + any(rule["host"] == "mysubdomain.my.local" for rule in m["spec"]["rules"]) + ] + assert len(ingresses) == 2 + return ingresses + + def cors_annotations(ingress): + return {k: v for k, v in ingress["metadata"]["annotations"].items() if "cors" in k} + + # Off by default + manifests = render() + for ingress in myapp_ingresses(manifests): + assert cors_annotations(ingress) == {} + + values["ingress"]["cors"]["enabled"] = True + values["ingress"]["cors"]["exposeHeaders"] = ["Content-Range"] + for ingress in myapp_ingresses(render()): + assert cors_annotations(ingress) == { + "nginx.ingress.kubernetes.io/enable-cors": "true", + # The single-label wildcard does not cover the nested alias, so it is listed + "nginx.ingress.kubernetes.io/cors-allow-origin": + "https://*.my.local,https://my.local,https://instance.mysubdomain.my.local", + "nginx.ingress.kubernetes.io/cors-allow-credentials": "true", + "nginx.ingress.kubernetes.io/cors-allow-methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS", + "nginx.ingress.kubernetes.io/cors-allow-headers": ",".join(values["ingress"]["cors"]["allowHeaders"]), + "nginx.ingress.kubernetes.io/cors-expose-headers": "Content-Range", + } + + values["tls"] = False + for ingress in myapp_ingresses(render()): + assert cors_annotations(ingress)["nginx.ingress.kubernetes.io/cors-allow-origin"] == ( + "http://*.my.local,http://my.local,http://instance.mysubdomain.my.local" + ) + + values["tls"] = True + values["ingress"]["ingressClass"] = "traefik" + manifests = render() + for ingress in myapp_ingresses(manifests): + middlewares = ingress["metadata"]["annotations"]["traefik.ingress.kubernetes.io/router.middlewares"].split(",") + assert "test-ch-cors@kubernetescrd" in middlewares + headers = find_manifest(manifests, "Middleware", "ch-cors")["spec"]["headers"] + assert headers["accessControlAllowCredentials"] is True + assert headers["accessControlExposeHeaders"] == ["Content-Range"] + [origin_regex] = headers["accessControlAllowOriginListRegex"] + assert origin_regex == r"^https://([A-Za-z0-9-]+\.)*my\.local$" + for allowed in ("https://my.local", "https://www.my.local", "https://instance.mysubdomain.my.local"): + assert re.match(origin_regex, allowed) + for refused in ("http://www.my.local", "https://evil.com", "https://evilmy.local", "https://my.local.evil.com"): + assert not re.match(origin_regex, refused) + + values["ingress"]["cors"]["enabled"] = False + manifests = render() + assert not [m for m in manifests if m["kind"] == "Middleware" and m["metadata"]["name"] == "ch-cors"] + for ingress in myapp_ingresses(manifests): + assert "ch-cors" not in ingress["metadata"]["annotations"]["traefik.ingress.kubernetes.io/router.middlewares"] + + def test_clear_all_dbconfig_if_nodb(tmp_path): out_folder = tmp_path / "test_clear_all_dbconfig_if_nodb"