Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
45 changes: 45 additions & 0 deletions internal/adc/translator/annotations/plugins/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package plugins

import (
adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
)

type cors struct{}

// NewCorsHandler creates a handler to convert annotations about
// CORS to APISIX cors plugin.
func NewCorsHandler() PluginAnnotationsHandler {
return &cors{}
}

func (c *cors) PluginName() string {
return "cors"
}

func (c *cors) Handle(e annotations.Extractor) (any, error) {
if !e.GetBoolAnnotation(annotations.AnnotationsEnableCors) {
return nil, nil
}

return &adctypes.CorsConfig{
AllowOrigins: e.GetStringAnnotation(annotations.AnnotationsCorsAllowOrigin),
AllowMethods: e.GetStringAnnotation(annotations.AnnotationsCorsAllowMethods),
AllowHeaders: e.GetStringAnnotation(annotations.AnnotationsCorsAllowHeaders),
}, nil
}
48 changes: 48 additions & 0 deletions internal/adc/translator/annotations/plugins/cors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package plugins

import (
"testing"

"github.com/stretchr/testify/assert"

adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
)

func TestCorsHandler(t *testing.T) {
anno := map[string]string{
annotations.AnnotationsEnableCors: "true",
annotations.AnnotationsCorsAllowHeaders: "abc,def",
annotations.AnnotationsCorsAllowOrigin: "https://a.com",
annotations.AnnotationsCorsAllowMethods: "GET,HEAD",
}
p := NewCorsHandler()
out, err := p.Handle(annotations.NewExtractor(anno))
assert.Nil(t, err, "checking given error")
config := out.(*adctypes.CorsConfig)
assert.Equal(t, "abc,def", config.AllowHeaders)
assert.Equal(t, "https://a.com", config.AllowOrigins)
assert.Equal(t, "GET,HEAD", config.AllowMethods)

assert.Equal(t, "cors", p.PluginName())

anno[annotations.AnnotationsEnableCors] = "false"
out, err = p.Handle(annotations.NewExtractor(anno))
assert.Nil(t, err, "checking given error")
assert.Nil(t, out, "checking given output")
}
66 changes: 66 additions & 0 deletions internal/adc/translator/annotations/plugins/plugins.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package plugins

import (
logf "sigs.k8s.io/controller-runtime/pkg/log"

adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
)

// Handler abstracts the behavior so that the apisix-ingress-controller knows
// how to parse some annotations and convert them to APISIX plugins.
type PluginAnnotationsHandler interface {
// Handle parses the target annotation and converts it to the type-agnostic structure.
// The return value might be nil since some features have an explicit switch, users should
// judge whether Handle is failed by the second error value.
Handle(annotations.Extractor) (any, error)
// PluginName returns a string which indicates the target plugin name in APISIX.
PluginName() string
}

var (
log = logf.Log.WithName("annotations").WithName("plugins").WithName("parser")

handlers = []PluginAnnotationsHandler{
NewRedirectHandler(),
NewCorsHandler(),
}
)

type plugins struct{}

func NewParser() annotations.IngressAnnotationsParser {
return &plugins{}
}

func (p *plugins) Parse(e annotations.Extractor) (any, error) {
plugins := make(adctypes.Plugins)
for _, handler := range handlers {
out, err := handler.Handle(e)
if err != nil {
log.Error(err, "Failed to handle annotation", "handler", handler.PluginName())
continue
}
if out != nil {
plugins[handler.PluginName()] = out
}
}
if len(plugins) > 0 {
return plugins, nil
}
return nil, nil
}
221 changes: 221 additions & 0 deletions internal/adc/translator/annotations_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package translator

import (
"errors"
"testing"

"github.com/stretchr/testify/assert"

adctypes "github.com/apache/apisix-ingress-controller/api/adc"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations"
"github.com/apache/apisix-ingress-controller/internal/adc/translator/annotations/upstream"
)

type mockParser struct {
output any
err error
}

func (m *mockParser) Parse(extractor annotations.Extractor) (any, error) {
return m.output, m.err
}

func TestTranslateAnnotations(t *testing.T) {
tests := []struct {
name string
anno map[string]string
parsers map[string]annotations.IngressAnnotationsParser
expected any
expectErr bool
}{
{
name: "successful parsing",
anno: map[string]string{"key1": "value1"},
parsers: map[string]annotations.IngressAnnotationsParser{
"key1": &mockParser{output: "parsedValue1", err: nil},
},
expected: map[string]any{"key1": "parsedValue1"},
expectErr: false,
},
{
name: "parsing with error",
anno: map[string]string{"key1": "value1"},
parsers: map[string]annotations.IngressAnnotationsParser{
"key1": &mockParser{output: nil, err: errors.New("parse error")},
},
expected: map[string]any{},
expectErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
orig := ingressAnnotationParsers
defer func() { ingressAnnotationParsers = orig }()

ingressAnnotationParsers = make(map[string]annotations.IngressAnnotationsParser)
for key, parser := range tt.parsers {
ingressAnnotationParsers[key] = parser
}

dst := make(map[string]any)
err := translateAnnotations(tt.anno, &dst)

if tt.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.expected, dst)
})
}
}

func TestTranslateIngressAnnotations(t *testing.T) {
tests := []struct {
name string
anno map[string]string
expected *IngressConfig
}{
{
name: "no matching annotations",
anno: map[string]string{"upstream": "value1"},
expected: &IngressConfig{},
},
{
name: "invalid scheme",
anno: map[string]string{annotations.AnnotationsUpstreamScheme: "invalid"},
expected: &IngressConfig{},
},
{
name: "http scheme",
anno: map[string]string{annotations.AnnotationsUpstreamScheme: "https"},
expected: &IngressConfig{
Upstream: upstream.Upstream{
Scheme: "https",
},
},
},
{
name: "retries",
anno: map[string]string{annotations.AnnotationsUpstreamRetry: "3"},
expected: &IngressConfig{
Upstream: upstream.Upstream{
Retries: 3,
},
},
},
{
name: "read timeout",
anno: map[string]string{
annotations.AnnotationsUpstreamTimeoutRead: "5s",
},
expected: &IngressConfig{
Upstream: upstream.Upstream{
TimeoutRead: 5,
},
},
},
{
name: "timeouts",
anno: map[string]string{
annotations.AnnotationsUpstreamTimeoutRead: "5s",
annotations.AnnotationsUpstreamTimeoutSend: "6s",
annotations.AnnotationsUpstreamTimeoutConnect: "7s",
},
expected: &IngressConfig{
Upstream: upstream.Upstream{
TimeoutRead: 5,
TimeoutSend: 6,
TimeoutConnect: 7,
},
},
},
{
name: "timeout/scheme/retries",
anno: map[string]string{
annotations.AnnotationsUpstreamTimeoutRead: "5s",
annotations.AnnotationsUpstreamScheme: "http",
annotations.AnnotationsUpstreamRetry: "2",
},
expected: &IngressConfig{
Upstream: upstream.Upstream{
TimeoutRead: 5,
Scheme: "http",
Retries: 2,
},
},
},
{
name: "redirect to https",
anno: map[string]string{
annotations.AnnotationsHttpToHttps: "true",
},
expected: &IngressConfig{
Plugins: adctypes.Plugins{
"redirect": &adctypes.RedirectConfig{
HttpToHttps: true,
},
},
},
},
{
name: "redirect to specific uri",
anno: map[string]string{
annotations.AnnotationsHttpRedirect: "/newpath",
annotations.AnnotationsHttpRedirectCode: "301",
},
expected: &IngressConfig{
Plugins: adctypes.Plugins{
"redirect": &adctypes.RedirectConfig{
URI: "/newpath",
RetCode: 301,
},
},
},
},
{
name: "cors plugin",
anno: map[string]string{
annotations.AnnotationsEnableCors: "true",
annotations.AnnotationsCorsAllowOrigin: "https://example.com",
annotations.AnnotationsCorsAllowHeaders: "header-a,header-b",
annotations.AnnotationsCorsAllowMethods: "GET,POST",
},
expected: &IngressConfig{
Plugins: adctypes.Plugins{
"cors": &adctypes.CorsConfig{
AllowOrigins: "https://example.com",
AllowHeaders: "header-a,header-b",
AllowMethods: "GET,POST",
},
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
translator := &Translator{}
result := translator.TranslateIngressAnnotations(tt.anno)

assert.NotNil(t, result)
assert.Equal(t, tt.expected, result)
})
}
}
Loading