mirror of
https://github.com/alibaba/higress.git
synced 2026-06-26 10:45:25 +08:00
test(wasm-plugins): lift unit-test coverage to ≥90% across 9 plugins (#3879)
Signed-off-by: jingze <daijingze.djz@alibaba-inc.com> Co-authored-by: woody <yaodiwu618@gmail.com>
This commit is contained in:
207
plugins/wasm-go/extensions/ext-auth/config/config_extra_test.go
Normal file
207
plugins/wasm-go/extensions/ext-auth/config/config_extra_test.go
Normal file
@@ -0,0 +1,207 @@
|
||||
// Copyright (c) 2025 Alibaba Group Holding Ltd.
|
||||
//
|
||||
// Licensed 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 config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// === Module A — parseAuthorizationResponseConfig =======================
|
||||
//
|
||||
// parseAuthorizationResponseConfig sits at 17.6% in the baseline because
|
||||
// every existing fixture either omits authorization_response entirely or
|
||||
// tests it implicitly through ParseConfig with only one of the two list
|
||||
// shapes. The tests below drive each branch directly via ParseConfig:
|
||||
// - allowed_upstream_headers list set
|
||||
// - allowed_client_headers list set
|
||||
// - both lists set
|
||||
// - error propagation when one of the lists has a bad regex matcher
|
||||
// (the only failure mode the function can surface)
|
||||
|
||||
func parseFromJSON(t *testing.T, jsonStr string) (ExtAuthConfig, error) {
|
||||
t.Helper()
|
||||
var cfg ExtAuthConfig
|
||||
err := ParseConfig(gjson.Parse(jsonStr), &cfg)
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
func TestParseAuthorizationResponse_AllowedUpstreamHeaders(t *testing.T) {
|
||||
cfg, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "envoy",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"service_port": 8090,
|
||||
"path_prefix": "/auth"
|
||||
},
|
||||
"authorization_response": {
|
||||
"allowed_upstream_headers": [
|
||||
{"exact": "x-user-id"},
|
||||
{"prefix": "x-auth-"}
|
||||
]
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cfg.HttpService.AuthorizationResponse.AllowedUpstreamHeaders)
|
||||
// Sanity-check matcher behavior end-to-end.
|
||||
require.True(t, cfg.HttpService.AuthorizationResponse.AllowedUpstreamHeaders.Match("x-user-id"))
|
||||
require.True(t, cfg.HttpService.AuthorizationResponse.AllowedUpstreamHeaders.Match("x-auth-token"))
|
||||
require.False(t, cfg.HttpService.AuthorizationResponse.AllowedUpstreamHeaders.Match("authorization"))
|
||||
// Client side intentionally untouched.
|
||||
require.Nil(t, cfg.HttpService.AuthorizationResponse.AllowedClientHeaders)
|
||||
}
|
||||
|
||||
func TestParseAuthorizationResponse_AllowedClientHeaders(t *testing.T) {
|
||||
cfg, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "envoy",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"service_port": 8090,
|
||||
"path_prefix": "/auth"
|
||||
},
|
||||
"authorization_response": {
|
||||
"allowed_client_headers": [
|
||||
{"exact": "www-authenticate"}
|
||||
]
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, cfg.HttpService.AuthorizationResponse.AllowedUpstreamHeaders)
|
||||
require.NotNil(t, cfg.HttpService.AuthorizationResponse.AllowedClientHeaders)
|
||||
require.True(t, cfg.HttpService.AuthorizationResponse.AllowedClientHeaders.Match("www-authenticate"))
|
||||
require.False(t, cfg.HttpService.AuthorizationResponse.AllowedClientHeaders.Match("x-user-id"))
|
||||
}
|
||||
|
||||
func TestParseAuthorizationResponse_BothListsSet(t *testing.T) {
|
||||
cfg, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "envoy",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"service_port": 8090,
|
||||
"path_prefix": "/auth"
|
||||
},
|
||||
"authorization_response": {
|
||||
"allowed_upstream_headers": [{"exact": "x-user-id"}],
|
||||
"allowed_client_headers": [{"prefix": "www-"}]
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cfg.HttpService.AuthorizationResponse.AllowedUpstreamHeaders)
|
||||
require.NotNil(t, cfg.HttpService.AuthorizationResponse.AllowedClientHeaders)
|
||||
}
|
||||
|
||||
// Bad regex inside allowed_upstream_headers must propagate the
|
||||
// BuildRepeatedStringMatcherIgnoreCase error and fail ParseConfig — pins
|
||||
// the err path at config.go:239-241.
|
||||
func TestParseAuthorizationResponse_AllowedUpstreamBadRegex(t *testing.T) {
|
||||
_, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "envoy",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"service_port": 8090,
|
||||
"path_prefix": "/auth"
|
||||
},
|
||||
"authorization_response": {
|
||||
"allowed_upstream_headers": [{"regex": "[unbalanced"}]
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
// Same propagation contract for allowed_client_headers — distinct branch
|
||||
// at config.go:248-250.
|
||||
func TestParseAuthorizationResponse_AllowedClientBadRegex(t *testing.T) {
|
||||
_, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "envoy",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"service_port": 8090,
|
||||
"path_prefix": "/auth"
|
||||
},
|
||||
"authorization_response": {
|
||||
"allowed_client_headers": [{"regex": "[unbalanced"}]
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
// === Module B — parseAuthorizationRequestConfig allowed_headers error ===
|
||||
//
|
||||
// Mirrors the response-side bad-regex case for the request side — the
|
||||
// `allowed_headers` failure path at config.go:194-197 is unreached because
|
||||
// every existing fixture supplies well-formed exact/prefix matchers.
|
||||
|
||||
func TestParseAuthorizationRequest_AllowedHeadersBadRegex(t *testing.T) {
|
||||
_, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "envoy",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"service_port": 8090,
|
||||
"path_prefix": "/auth"
|
||||
},
|
||||
"authorization_request": {
|
||||
"allowed_headers": [{"regex": "[unbalanced"}]
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
// === Module C — parseEndpointConfig small edges ========================
|
||||
//
|
||||
// forward_auth without explicit request_method falls back to GET (default
|
||||
// http.MethodGet at config.go:169).
|
||||
func TestParseEndpointConfig_ForwardAuthDefaultsToGET(t *testing.T) {
|
||||
cfg, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "forward_auth",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"service_port": 8090,
|
||||
"path": "/auth"
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "GET", cfg.HttpService.RequestMethod)
|
||||
}
|
||||
|
||||
// service_port omitted defaults to 80 (config.go:144-146).
|
||||
func TestParseEndpointConfig_ServicePortDefaults80(t *testing.T) {
|
||||
cfg, err := parseFromJSON(t, `{
|
||||
"http_service": {
|
||||
"endpoint_mode": "envoy",
|
||||
"endpoint": {
|
||||
"service_name": "ext-auth.example.com",
|
||||
"path_prefix": "/auth"
|
||||
}
|
||||
}
|
||||
}`)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cfg.HttpService.Client)
|
||||
}
|
||||
93
plugins/wasm-go/extensions/ext-auth/expr/expr_extra_test.go
Normal file
93
plugins/wasm-go/extensions/ext-auth/expr/expr_extra_test.go
Normal file
@@ -0,0 +1,93 @@
|
||||
// Copyright (c) 2025 Alibaba Group Holding Ltd.
|
||||
//
|
||||
// Licensed 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 expr
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// === Module A — MatchRulesDefaults ======================================
|
||||
//
|
||||
// MatchRulesDefaults is at 0% in the baseline. It is consumed by
|
||||
// config.ParseConfig as the zero-value MatchRules when the user supplies
|
||||
// no match_list, so a regression here would silently change route-skip
|
||||
// semantics from "whitelist with empty rule list" (block all by default)
|
||||
// to whatever a future zero-value happens to mean.
|
||||
|
||||
func TestMatchRulesDefaults_WhitelistMode(t *testing.T) {
|
||||
d := MatchRulesDefaults()
|
||||
require.Equal(t, ModeWhitelist, d.Mode)
|
||||
}
|
||||
|
||||
func TestMatchRulesDefaults_EmptyButNonNilRuleList(t *testing.T) {
|
||||
d := MatchRulesDefaults()
|
||||
require.NotNil(t, d.RuleList)
|
||||
require.Len(t, d.RuleList, 0)
|
||||
}
|
||||
|
||||
// In whitelist mode with an empty rule list, every (domain, method, path)
|
||||
// triple must be DENIED by the rule check (i.e. the auth server gets to see
|
||||
// the request). The dual contract — blacklist + empty rule list = ALLOW —
|
||||
// is already covered by match_rules_test.go via populated rule sets, but
|
||||
// the empty-list defaults case is an important degenerate edge.
|
||||
func TestMatchRulesDefaults_EmptyWhitelistDenies(t *testing.T) {
|
||||
d := MatchRulesDefaults()
|
||||
require.False(t, d.IsAllowedByMode("example.com", "GET", "/x"))
|
||||
}
|
||||
|
||||
// === Module B — IsAllowedByMode default branch ==========================
|
||||
//
|
||||
// `default: return false` at match_rules.go:51 is unreachable through
|
||||
// MatchRulesDefaults because Mode is whitelist there. A misconfigured /
|
||||
// hand-built MatchRules with an unknown mode must safely fall back to
|
||||
// "not allowed" so the request still goes through the auth server rather
|
||||
// than silently bypassing it.
|
||||
|
||||
func TestIsAllowedByMode_UnknownModeFallsToFalse(t *testing.T) {
|
||||
mr := MatchRules{Mode: "not-a-mode", RuleList: []Rule{}}
|
||||
require.False(t, mr.IsAllowedByMode("example.com", "GET", "/x"))
|
||||
}
|
||||
|
||||
// === Module C — BuildStringMatcher edges ================================
|
||||
//
|
||||
// BuildStringMatcher is at 75%; the unknown-type error branch and the
|
||||
// invalid-regex branch are both unreached. Both must produce errors rather
|
||||
// than nil-matchers so config.parseMatchRules can surface a proper config
|
||||
// validation error.
|
||||
|
||||
func TestBuildStringMatcher_UnknownType(t *testing.T) {
|
||||
m, err := BuildStringMatcher("not-a-pattern", "x", false)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, m)
|
||||
require.Contains(t, err.Error(), "unknown string matcher type")
|
||||
}
|
||||
|
||||
func TestBuildStringMatcher_InvalidRegex(t *testing.T) {
|
||||
// Unbalanced "[" is a regexp.Compile error.
|
||||
m, err := BuildStringMatcher(MatchPatternRegex, "[unbalanced", false)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, m)
|
||||
}
|
||||
|
||||
// IgnoreCase + already-prefixed `(?i)` regex must NOT double-prefix —
|
||||
// pins matcher.go:119-121's idempotency check.
|
||||
func TestBuildStringMatcher_RegexIgnoreCaseAlreadyPrefixed(t *testing.T) {
|
||||
m, err := BuildStringMatcher(MatchPatternRegex, "(?i)foo", true)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, m)
|
||||
require.True(t, m.Match("FOO"))
|
||||
}
|
||||
131
plugins/wasm-go/extensions/ext-auth/util/utils_test.go
Normal file
131
plugins/wasm-go/extensions/ext-auth/util/utils_test.go
Normal file
@@ -0,0 +1,131 @@
|
||||
// Copyright (c) 2025 Alibaba Group Holding Ltd.
|
||||
//
|
||||
// Licensed 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 util's first test file. SendResponse calls into proxywasm and
|
||||
// requires a host emulator, so it is exercised end-to-end through main
|
||||
// package tests; the three deterministic helpers (ReconvertHeaders,
|
||||
// ExtractFromHeader, ContainsString) are unit-tested directly here so that
|
||||
// future refactors to the helpers themselves don't depend on dragging in
|
||||
// the wasm host harness.
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// === Module A — ReconvertHeaders ========================================
|
||||
|
||||
// nil http.Header must produce a non-panicking nil/empty slice; downstream
|
||||
// proxywasm calls accept either.
|
||||
func TestReconvertHeaders_Nil(t *testing.T) {
|
||||
require.Empty(t, ReconvertHeaders(nil))
|
||||
}
|
||||
|
||||
func TestReconvertHeaders_Empty(t *testing.T) {
|
||||
require.Empty(t, ReconvertHeaders(http.Header{}))
|
||||
}
|
||||
|
||||
// Multi-key + multi-value: each (key, value) pair becomes a separate
|
||||
// [2]string entry, and the result is sorted stably by key — required so
|
||||
// proxywasm sees a deterministic order regardless of map iteration.
|
||||
func TestReconvertHeaders_MultiValueSorted(t *testing.T) {
|
||||
h := http.Header{}
|
||||
h.Add("X-A", "1")
|
||||
h.Add("X-A", "2")
|
||||
h.Set("X-B", "b")
|
||||
h.Set("X-C", "c")
|
||||
|
||||
got := ReconvertHeaders(h)
|
||||
// Two values for X-A → two entries; one each for X-B / X-C.
|
||||
require.Len(t, got, 4)
|
||||
// Sorted by key, ascending.
|
||||
require.Equal(t, "X-A", got[0][0])
|
||||
require.Equal(t, "X-A", got[1][0])
|
||||
require.Equal(t, "X-B", got[2][0])
|
||||
require.Equal(t, "X-C", got[3][0])
|
||||
// Values for the same key preserve their insertion order.
|
||||
require.Equal(t, "1", got[0][1])
|
||||
require.Equal(t, "2", got[1][1])
|
||||
require.Equal(t, "b", got[2][1])
|
||||
}
|
||||
|
||||
// === Module B — ExtractFromHeader =======================================
|
||||
|
||||
// Hit on the literal-case key the caller asked for. The lookup compares the
|
||||
// header key to its lower-case form, so callers must pass already-lowercased
|
||||
// keys; `ExtractFromHeader(headers, "x-foo")` matches both "X-Foo" and
|
||||
// "x-foo" but `(headers, "X-Foo")` matches neither.
|
||||
func TestExtractFromHeader_LowercaseKeyHit(t *testing.T) {
|
||||
headers := [][2]string{
|
||||
{"Authorization", "Bearer token"},
|
||||
{"X-Foo", "bar"},
|
||||
}
|
||||
require.Equal(t, "Bearer token", ExtractFromHeader(headers, "authorization"))
|
||||
}
|
||||
|
||||
// Mixed-case stored key still matches because the comparison lowercases the
|
||||
// stored key, not the search key — pins the asymmetry above.
|
||||
func TestExtractFromHeader_StoredMixedCase(t *testing.T) {
|
||||
headers := [][2]string{{"X-Foo", "bar"}}
|
||||
require.Equal(t, "bar", ExtractFromHeader(headers, "x-foo"))
|
||||
}
|
||||
|
||||
// Leading and trailing whitespace in the stored value is trimmed so the
|
||||
// caller doesn't have to defensively re-trim.
|
||||
func TestExtractFromHeader_TrimsWhitespace(t *testing.T) {
|
||||
headers := [][2]string{{"X-Token", " trimmed-value "}}
|
||||
require.Equal(t, "trimmed-value", ExtractFromHeader(headers, "x-token"))
|
||||
}
|
||||
|
||||
// Miss → empty string, not error: callers branch on `value != ""`.
|
||||
func TestExtractFromHeader_Miss(t *testing.T) {
|
||||
headers := [][2]string{{"X-Foo", "bar"}}
|
||||
require.Equal(t, "", ExtractFromHeader(headers, "x-missing"))
|
||||
}
|
||||
|
||||
func TestExtractFromHeader_EmptySlice(t *testing.T) {
|
||||
require.Equal(t, "", ExtractFromHeader(nil, "x-foo"))
|
||||
require.Equal(t, "", ExtractFromHeader([][2]string{}, "x-foo"))
|
||||
}
|
||||
|
||||
// === Module C — ContainsString ==========================================
|
||||
|
||||
// Hit semantics: case-insensitive equality, NOT substring.
|
||||
func TestContainsString_Hit(t *testing.T) {
|
||||
require.True(t, ContainsString([]string{"GET", "POST"}, "POST"))
|
||||
}
|
||||
|
||||
func TestContainsString_HitCaseInsensitive(t *testing.T) {
|
||||
require.True(t, ContainsString([]string{"GET", "POST"}, "post"))
|
||||
require.True(t, ContainsString([]string{"GeT"}, "get"))
|
||||
}
|
||||
|
||||
// "PO" is not a member, only a prefix — must miss. Pins that the helper
|
||||
// is equality-based, not strings.Contains-based, in case of refactor drift.
|
||||
func TestContainsString_PrefixIsNotMember(t *testing.T) {
|
||||
require.False(t, ContainsString([]string{"POST"}, "PO"))
|
||||
}
|
||||
|
||||
func TestContainsString_Miss(t *testing.T) {
|
||||
require.False(t, ContainsString([]string{"GET", "POST"}, "PUT"))
|
||||
}
|
||||
|
||||
func TestContainsString_EmptySlice(t *testing.T) {
|
||||
require.False(t, ContainsString(nil, "x"))
|
||||
require.False(t, ContainsString([]string{}, "x"))
|
||||
}
|
||||
Reference in New Issue
Block a user