Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add path-regex annotation for ingress #4127

Merged
merged 17 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ The table below summarizes the available annotations.
|``nginx.org/proxy-buffer-size`` | ``proxy-buffer-size`` | Sets the value of the [proxy_buffer_size](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size) and [grpc_buffer_size](https://nginx.org/en/docs/http/ngx_http_grpc_module.html#grpc_buffer_size) directives. | Depends on the platform. | |
|``nginx.org/proxy-max-temp-file-size`` | ``proxy-max-temp-file-size`` | Sets the value of the [proxy_max_temp_file_size](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_max_temp_file_size) directive. | ``1024m`` | |
|``nginx.org/server-tokens`` | ``server-tokens`` | Enables or disables the [server_tokens](https://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens) directive. Additionally, with the NGINX Plus, you can specify a custom string value, including the empty string value, which disables the emission of the “Server” field. | ``True`` | |
|``nginx.org/path-regex`` | N/A | Enables regular expression modifiers for [location](https://nginx.org/en/docs/http/ngx_http_core_module.html#location) directive. You can specify one of these values: "case_sensitive", "case_insensitive" or "exact". | | [Path Regex](https://github.com/nginxinc/kubernetes-ingress/tree/examples/ingress-resources/path-regex). |
jjngx marked this conversation as resolved.
Show resolved Hide resolved
{{% /table %}}

### Request URI/Header Manipulation
Expand Down
178 changes: 178 additions & 0 deletions examples/ingress-resources/path-regex/README.md
jjngx marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
# Support for path regular expressions

NGINX and NGINX Plus support regular expression modifiers for [location](https://nginx.org/en/docs/http/ngx_http_core_module.html#location) directive.

The NGINX Ingress Controller provides the following annotations for configuring regular expression support:

* Optional: ```nginx.org/path-regex: "case_sensitive"``` - specifies a preceding regex modifier to be case sensitive (`~*`).
* Optional: ```nginx.org/path-regex: "case_insensitive"``` - specifies a preceding regex modifier to be case sensitive (`~`).
* Optional: ```nginx.org/path-regex: "exact"``` - specifies exact match preceding modifier (`=`).

[NGINX documentation](https://docs.nginx.com/nginx/admin-guide/web-server/web-server/#nginx-location-priority) provides additional information about how NGINX and NGINX Plus resolve location priority. Read [it](https://docs.nginx.com/nginx/admin-guide/web-server/web-server/#nginx-location-priority) before using the ``path-regex`` annotation.

Nginx uses a specific syntax to decide which location block to use to handle a request. Location blocks live within server blocks (or other location blocks) and are used to decide how to process the request URI, for example:

```bash
location optional_modifier location_match {
...
}
```

The ``location_match`` defines what NGINX checks the request URI against. The existence or nonexistence of the modifier in the example affects the way that the Nginx attempts to match the location block. The modifiers you can apply using the ``path-regex`` annotation will cause the associated location block to be interpreted as follows:

* **no modifier** : No modifiers (no annotation applied) - the location is interpreted as a prefix match. This means that the location given will be matched against the beginning of the request URI to determine a match

* **~** : Tilde modifier (annotation value ``case_sensitive``) - the location is interpreted as a case-sensitive regular expression match

* **~***: Tilde and asterisk modifier (annotation value ``case_insensitive``) - the location is interpreted as a case-insensitive regular expression match

* **=** : Equal sign modifier (annotation value ``exact``) - the location is considered a match if the request URI exactly matches the location provided.

## Example 1: Case Sensitive RegEx

In the following example you enable path regex annotation ``nginx.org/path-regex`` and set its value to `case_sensitive`.

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: cafe-ingress
annotations:
nginx.org/path-regex: "case_sensitive"
spec:
tls:
- hosts:
- cafe.example.com
secretName: cafe-secret
rules:
- host: cafe.example.com
http:
paths:
- path: /tea/[A-Z0-9]
backend:
serviceName: tea-svc
servicePort: 80
- path: /coffee/[A-Z0-9]
backend:
serviceName: coffee-svc
servicePort: 80
```

Corresponding NGINX config file snippet:

```bash
...

location ~ "^/tea/[A-Z0-9]" {

set $service "tea-svc";
status_zone "tea-svc";

...

location ~ "^/coffee/[A-Z0-9]" {

set $service "coffee-svc";
status_zone "coffee-svc";

...
```

## Example 2: Case Insensitive RegEx

In the following example you enable path regex annotation ``nginx.org/path-regex`` and set its value to `case_insensitive`.

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: cafe-ingress
annotations:
nginx.org/path-regex: "case_insensitive"
spec:
tls:
- hosts:
- cafe.example.com
secretName: cafe-secret
rules:
- host: cafe.example.com
http:
paths:
- path: /tea/[A-Z0-9]
backend:
serviceName: tea-svc
servicePort: 80
- path: /coffee/[A-Z0-9]
backend:
serviceName: coffee-svc
servicePort: 80
```

Corresponding NGINX config file snippet:

```bash
...

location ~* "^/tea/[A-Z0-9]" {

set $service "tea-svc";
status_zone "tea-svc";

...

location ~* "^/coffee/[A-Z0-9]" {

set $service "coffee-svc";
status_zone "coffee-svc";

...
```

## Example 3: Exact RegEx

In the following example you enable path regex annotation ``nginx.org/path-regex`` and set its value to `exact` match.

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: cafe-ingress
annotations:
nginx.org/path-regex: "exact"
spec:
tls:
- hosts:
- cafe.example.com
secretName: cafe-secret
rules:
- host: cafe.example.com
http:
paths:
- path: /tea/
backend:
serviceName: tea-svc
servicePort: 80
- path: /coffee/
backend:
serviceName: coffee-svc
servicePort: 80
```

Corresponding NGINX config file snippet:

```bash
...

location = "/tea" {

set $service "tea-svc";
status_zone "tea-svc";

...

location = "/coffee" {

set $service "coffee-svc";
status_zone "coffee-svc";
...
```
16 changes: 16 additions & 0 deletions internal/configs/annotations.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const JWTKeyAnnotation = "nginx.com/jwt-key"
// BasicAuthSecretAnnotation is the annotation where the Secret with the HTTP basic user list
const BasicAuthSecretAnnotation = "nginx.org/basic-auth-secret" // #nosec G101

// PathRegexAnnotation is the annotation where the regex location (path) modifier is specified.
const PathRegexAnnotation = "nginx.org/path-regex"

// AppProtectPolicyAnnotation is where the NGINX App Protect policy is specified
const AppProtectPolicyAnnotation = "appprotect.f5.com/app-protect-policy"

Expand Down Expand Up @@ -73,6 +76,12 @@ var minionInheritanceList = map[string]bool{
"nginx.org/fail-timeout": true,
}

var validPathRegex = map[string]bool{
"case_sensitive": true,
"case_insensitive": true,
"exact": true,
}

func parseAnnotations(ingEx *IngressEx, baseCfgParams *ConfigParams, isPlus bool, hasAppProtect bool, hasAppProtectDos bool, enableInternalRoutes bool) ConfigParams {
cfgParams := *baseCfgParams

Expand Down Expand Up @@ -385,6 +394,13 @@ func parseAnnotations(ingEx *IngressEx, baseCfgParams *ConfigParams, isPlus bool
}
}
}

if pathRegex, exists := ingEx.Ingress.Annotations[PathRegexAnnotation]; exists {
_, ok := validPathRegex[pathRegex]
if !ok {
glog.Errorf("Ingress %s/%s: Invalid value nginx.org/path-regex: got %q. Allowed values: 'case_sensitive', 'case_insensitive', 'exact'", ingEx.Ingress.GetNamespace(), ingEx.Ingress.GetName(), pathRegex)
}
}
return cfgParams
}

Expand Down
6 changes: 5 additions & 1 deletion internal/configs/version1/nginx-plus.ingress.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,11 @@ server {
{{end -}}

{{range $location := $server.Locations}}
location {{$location.Path}} {
{{ if index $.Ingress.Annotations "nginx.org/path-regex" }}
location {{ makePathRegex $location.Path $.Ingress.Annotations | printf }} {
{{ else }}
location {{ $location.Path }} {
{{ end }}
set $service "{{$location.ServiceName}}";
status_zone "{{ $location.ServiceName }}";
{{with $location.MinionIngress}}
Expand Down
6 changes: 5 additions & 1 deletion internal/configs/version1/nginx.ingress.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,11 @@ server {
{{- end}}

{{range $location := $server.Locations}}
location {{$location.Path}} {
{{ if index $.Ingress.Annotations "nginx.org/path-regex" }}
location {{ makePathRegex $location.Path $.Ingress.Annotations | printf }} {
{{ else }}
location {{ $location.Path }} {
{{ end }}
set $service "{{$location.ServiceName}}";
{{with $location.MinionIngress}}
# location for minion {{$location.MinionIngress.Namespace}}/{{$location.MinionIngress.Name}}
Expand Down
29 changes: 27 additions & 2 deletions internal/configs/version1/template_helper.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package version1

import (
"fmt"
"strings"
"text/template"
)
Expand All @@ -13,7 +14,31 @@ func trim(s string) string {
return strings.TrimSpace(s)
}

// makePathRegex takes a string representing a location path
// and a map representing Ingress annotations.
// It returns a location path with added regular expression modifier.
// See [Location Directive].
//
// [Location Directive]: https://nginx.org/en/docs/http/ngx_http_core_module.html#location
func makePathRegex(path string, annotations map[string]string) string {
p, ok := annotations["nginx.org/path-regex"]
if !ok {
return path
}
switch p {
case "case_sensitive":
return fmt.Sprintf("~ \"^%s\"", path)
case "case_insensitive":
return fmt.Sprintf("~* \"^%s\"", path)
case "exact":
return fmt.Sprintf("= \"%s\"", path)
default:
return path
}
}

var helperFunctions = template.FuncMap{
"split": split,
"trim": trim,
"split": split,
"trim": trim,
"makePathRegex": makePathRegex,
}
Loading