Config/Annotations: Add relative-redirects. (#12161)

This commit is contained in:
chriss-de 2024-11-13 22:02:48 +01:00 committed by GitHub
parent 0207d1878a
commit 698960e9b7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 182 additions and 0 deletions

View file

@ -38,6 +38,7 @@ type Config struct {
URL string `json:"url"`
Code int `json:"code"`
FromToWWW bool `json:"fromToWWW"`
Relative bool `json:"relative"`
}
const (
@ -46,6 +47,7 @@ const (
temporalRedirectAnnotationCode = "temporal-redirect-code"
permanentRedirectAnnotation = "permanent-redirect"
permanentRedirectAnnotationCode = "permanent-redirect-code"
relativeRedirectsAnnotation = "relative-redirects"
)
var redirectAnnotations = parser.Annotation{
@ -83,6 +85,12 @@ var redirectAnnotations = parser.Annotation{
Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options
Documentation: `This annotation allows you to modify the status code used for permanent redirects.`,
},
relativeRedirectsAnnotation: {
Validator: parser.ValidateBool,
Scope: parser.AnnotationScopeLocation,
Risk: parser.AnnotationRiskLow,
Documentation: `If enabled, redirects issued by nginx will be relative. See https://nginx.org/en/docs/http/ngx_http_core_module.html#absolute_redirect`,
},
},
}
@ -109,6 +117,11 @@ func (r redirect) Parse(ing *networking.Ingress) (interface{}, error) {
return nil, err
}
rr, err := parser.GetBoolAnnotation(relativeRedirectsAnnotation, ing, r.annotationConfig.Annotations)
if err != nil && !errors.IsMissingAnnotations(err) {
return nil, err
}
tr, err := parser.GetStringAnnotation(temporalRedirectAnnotation, ing, r.annotationConfig.Annotations)
if err != nil && !errors.IsMissingAnnotations(err) {
return nil, err
@ -132,6 +145,7 @@ func (r redirect) Parse(ing *networking.Ingress) (interface{}, error) {
URL: tr,
Code: trc,
FromToWWW: r3w,
Relative: rr,
}, nil
}
@ -154,6 +168,13 @@ func (r redirect) Parse(ing *networking.Ingress) (interface{}, error) {
URL: pr,
Code: prc,
FromToWWW: r3w,
Relative: rr,
}, nil
}
if rr {
return &Config{
Relative: rr,
}, nil
}
@ -177,6 +198,9 @@ func (r1 *Config) Equal(r2 *Config) bool {
if r1.FromToWWW != r2.FromToWWW {
return false
}
if r1.Relative != r2.Relative {
return false
}
return true
}

View file

@ -193,3 +193,22 @@ func TestIsValidURL(t *testing.T) {
t.Errorf("expected nil but got %v", err)
}
}
func TestParseAnnotations(t *testing.T) {
ing := new(networking.Ingress)
data := map[string]string{}
data[parser.GetAnnotationWithPrefix(relativeRedirectsAnnotation)] = "true"
ing.SetAnnotations(data)
_, err := NewParser(&resolver.Mock{}).Parse(ing)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
// test ingress using the annotation without a TLS section
_, err = NewParser(&resolver.Mock{}).Parse(ing)
if err != nil {
t.Errorf("unexpected error parsing ingress with relative-redirects")
}
}