mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9079de1c0 | ||
|
|
99633b185d | ||
|
|
e6ee703849 | ||
|
|
3be832a12b |
No files matched your search
@@ -1083,14 +1083,13 @@ func (e *PolicyEngine) EvaluateStringCondition(block map[string]interface{}, eva
|
||||
for _, contextValue := range contextStrings {
|
||||
contextValueMatchedSet := false
|
||||
for _, expected := range expectedStrings {
|
||||
expandedExpected := expandPolicyVariables(expected, evalCtx)
|
||||
if useWildcard {
|
||||
if wildcard.MatchesWildcard(expandedExpected, contextValue) {
|
||||
if awsIAMResourceMatch(expected, contextValue, evalCtx) {
|
||||
contextValueMatchedSet = true
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if expandedExpected == contextValue {
|
||||
if expandPolicyVariables(expected, evalCtx) == contextValue {
|
||||
contextValueMatchedSet = true
|
||||
break
|
||||
}
|
||||
@@ -1124,14 +1123,13 @@ func (e *PolicyEngine) EvaluateStringCondition(block map[string]interface{}, eva
|
||||
for _, contextValue := range contextStrings {
|
||||
contextValueMatchedSet := false
|
||||
for _, expected := range expectedStrings {
|
||||
expandedExpected := expandPolicyVariables(expected, evalCtx)
|
||||
if useWildcard {
|
||||
if wildcard.MatchesWildcard(expandedExpected, contextValue) {
|
||||
if awsIAMResourceMatch(expected, contextValue, evalCtx) {
|
||||
contextValueMatchedSet = true
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if expandedExpected == contextValue {
|
||||
if expandPolicyVariables(expected, evalCtx) == contextValue {
|
||||
contextValueMatchedSet = true
|
||||
break
|
||||
}
|
||||
@@ -1232,38 +1230,15 @@ func validateStatementWithType(statement *Statement, policyType string) error {
|
||||
|
||||
// awsIAMMatch performs AWS IAM-compliant pattern matching with case-insensitivity and policy variable support
|
||||
func awsIAMMatch(pattern, value string, evalCtx *EvaluationContext) bool {
|
||||
// Step 1: Substitute policy variables (e.g., ${aws:username}, ${saml:username})
|
||||
expandedPattern := expandPolicyVariables(pattern, evalCtx)
|
||||
|
||||
// Step 2: Handle special patterns
|
||||
if expandedPattern == "*" {
|
||||
return true // Universal wildcard
|
||||
}
|
||||
|
||||
// Step 3: Case-insensitive exact match
|
||||
if strings.EqualFold(expandedPattern, value) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Step 4: Handle AWS-style wildcards (case-insensitive)
|
||||
if strings.Contains(expandedPattern, "*") || strings.Contains(expandedPattern, "?") {
|
||||
return wildcard.MatchesWildcard(strings.ToLower(expandedPattern), strings.ToLower(value))
|
||||
}
|
||||
|
||||
return false
|
||||
expand := func(v string) string { return expandPolicyVariables(v, evalCtx) }
|
||||
return wildcard.MatchesExpandedWildcard(pattern, policyVariablePattern, expand, value, true)
|
||||
}
|
||||
|
||||
// awsIAMResourceMatch matches resource ARNs case-sensitively: object keys and
|
||||
// identity names that differ only in case name different resources.
|
||||
func awsIAMResourceMatch(pattern, value string, evalCtx *EvaluationContext) bool {
|
||||
expandedPattern := expandPolicyVariables(pattern, evalCtx)
|
||||
if expandedPattern == "*" || expandedPattern == value {
|
||||
return true
|
||||
}
|
||||
if strings.Contains(expandedPattern, "*") || strings.Contains(expandedPattern, "?") {
|
||||
return wildcard.MatchesWildcard(expandedPattern, value)
|
||||
}
|
||||
return false
|
||||
expand := func(v string) string { return expandPolicyVariables(v, evalCtx) }
|
||||
return wildcard.MatchesExpandedWildcard(pattern, policyVariablePattern, expand, value, false)
|
||||
}
|
||||
|
||||
// expandPolicyVariables substitutes AWS policy variables in the pattern
|
||||
@@ -1390,13 +1365,12 @@ func (e *PolicyEngine) evaluateStringConditionIgnoreCase(block map[string]interf
|
||||
// Check against all expected values
|
||||
switch v := expectedValues.(type) {
|
||||
case string:
|
||||
expandedPattern := expandPolicyVariables(v, evalCtx)
|
||||
if useWildcard {
|
||||
if wildcard.MatchesWildcard(strings.ToLower(expandedPattern), strings.ToLower(ctxStr)) {
|
||||
if awsIAMMatch(v, ctxStr, evalCtx) {
|
||||
itemMatchedSet = true
|
||||
}
|
||||
} else {
|
||||
if strings.EqualFold(expandedPattern, ctxStr) {
|
||||
if strings.EqualFold(expandPolicyVariables(v, evalCtx), ctxStr) {
|
||||
itemMatchedSet = true
|
||||
}
|
||||
}
|
||||
@@ -1412,14 +1386,13 @@ func (e *PolicyEngine) evaluateStringConditionIgnoreCase(block map[string]interf
|
||||
}
|
||||
}
|
||||
for _, valStr := range slice {
|
||||
expandedPattern := expandPolicyVariables(valStr, evalCtx)
|
||||
if useWildcard {
|
||||
if wildcard.MatchesWildcard(strings.ToLower(expandedPattern), strings.ToLower(ctxStr)) {
|
||||
if awsIAMMatch(valStr, ctxStr, evalCtx) {
|
||||
itemMatchedSet = true
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if strings.EqualFold(expandedPattern, ctxStr) {
|
||||
if strings.EqualFold(expandPolicyVariables(valStr, evalCtx), ctxStr) {
|
||||
itemMatchedSet = true
|
||||
break
|
||||
}
|
||||
@@ -1452,13 +1425,12 @@ func (e *PolicyEngine) evaluateStringConditionIgnoreCase(block map[string]interf
|
||||
// Handle different value types
|
||||
switch v := expectedValues.(type) {
|
||||
case string:
|
||||
expandedPattern := expandPolicyVariables(v, evalCtx)
|
||||
if useWildcard {
|
||||
if wildcard.MatchesWildcard(strings.ToLower(expandedPattern), strings.ToLower(ctxStr)) {
|
||||
if awsIAMMatch(v, ctxStr, evalCtx) {
|
||||
itemMatchedSet = true
|
||||
}
|
||||
} else {
|
||||
if strings.EqualFold(expandedPattern, ctxStr) {
|
||||
if strings.EqualFold(expandPolicyVariables(v, evalCtx), ctxStr) {
|
||||
itemMatchedSet = true
|
||||
}
|
||||
}
|
||||
@@ -1474,14 +1446,13 @@ func (e *PolicyEngine) evaluateStringConditionIgnoreCase(block map[string]interf
|
||||
}
|
||||
}
|
||||
for _, valStr := range slice {
|
||||
expandedPattern := expandPolicyVariables(valStr, evalCtx)
|
||||
if useWildcard {
|
||||
if wildcard.MatchesWildcard(strings.ToLower(expandedPattern), strings.ToLower(ctxStr)) {
|
||||
if awsIAMMatch(valStr, ctxStr, evalCtx) {
|
||||
itemMatchedSet = true
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if strings.EqualFold(expandedPattern, ctxStr) {
|
||||
if strings.EqualFold(expandPolicyVariables(valStr, evalCtx), ctxStr) {
|
||||
itemMatchedSet = true
|
||||
break
|
||||
}
|
||||
|
||||
@@ -188,3 +188,71 @@ func TestActionResourceConsistencyWithStringConditions(t *testing.T) {
|
||||
assert.Equal(t, "Allow", string(result.MatchingStatements[0].Effect),
|
||||
"Matching statement should have Allow effect")
|
||||
}
|
||||
|
||||
func TestPolicyVariableValuesAreNotWildcards(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
require.NoError(t, engine.Initialize(&PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"}))
|
||||
require.NoError(t, engine.AddPolicy("", "home-policy", &PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []Statement{
|
||||
{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"arn:aws:s3:::home/${jwt:email}/*"},
|
||||
},
|
||||
{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:ListBucket"},
|
||||
Resource: []string{"arn:aws:s3:::home"},
|
||||
Condition: map[string]map[string]interface{}{
|
||||
"StringLike": {"s3:prefix": []string{"${jwt:email}/*"}},
|
||||
},
|
||||
},
|
||||
{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:PutObject"},
|
||||
Resource: []string{"arn:aws:s3:::home/*"},
|
||||
Condition: map[string]map[string]interface{}{
|
||||
"StringLikeIgnoreCase": {"s3:prefix": "${jwt:email}/*"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
object := "arn:aws:s3:::home/alice@corp.com/secret.txt"
|
||||
tests := []struct {
|
||||
name string
|
||||
email string
|
||||
action string
|
||||
resource string
|
||||
prefix string
|
||||
want Effect
|
||||
}{
|
||||
{"owner get", "alice@corp.com", "s3:GetObject", object, "", EffectAllow},
|
||||
{"other user get", "bob@corp.com", "s3:GetObject", object, "", EffectDeny},
|
||||
{"star email get", "*@corp.com", "s3:GetObject", object, "", EffectDeny},
|
||||
{"bare star get", "*", "s3:GetObject", object, "", EffectDeny},
|
||||
{"question mark get", "?lice@corp.com", "s3:GetObject", object, "", EffectDeny},
|
||||
{"literal star owner get", "*@corp.com", "s3:GetObject", "arn:aws:s3:::home/*@corp.com/x", "", EffectAllow},
|
||||
{"owner list", "alice@corp.com", "s3:ListBucket", "arn:aws:s3:::home", "alice@corp.com/", EffectAllow},
|
||||
{"star list", "*", "s3:ListBucket", "arn:aws:s3:::home", "alice@corp.com/", EffectDeny},
|
||||
{"owner put ignore case", "Alice@corp.com", "s3:PutObject", object, "alice@corp.com/", EffectAllow},
|
||||
{"star put ignore case", "*", "s3:PutObject", object, "alice@corp.com/", EffectDeny},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
requestContext := map[string]interface{}{"jwt:email": tt.email}
|
||||
if tt.prefix != "" {
|
||||
requestContext["s3:prefix"] = tt.prefix
|
||||
}
|
||||
result, err := engine.Evaluate(context.Background(), "", &EvaluationContext{
|
||||
Principal: "user",
|
||||
Action: tt.action,
|
||||
Resource: tt.resource,
|
||||
RequestContext: requestContext,
|
||||
}, []string{"home-policy"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tt.want, result.Effect)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -51,13 +51,34 @@ func (e *StringNotEqualsEvaluator) Evaluate(conditionValue interface{}, contextV
|
||||
type StringLikeEvaluator struct{}
|
||||
|
||||
func (e *StringLikeEvaluator) Evaluate(conditionValue interface{}, contextValues []string) bool {
|
||||
patterns := normalizeToStringSlice(conditionValue)
|
||||
for _, pattern := range patterns {
|
||||
for _, contextValue := range contextValues {
|
||||
if wildcard.MatchesWildcard(pattern, contextValue) {
|
||||
for _, contextValue := range contextValues {
|
||||
if matchesLikePattern(conditionValue, contextValue) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// likePatterns holds *Like condition values with their policy variables still
|
||||
// unexpanded, so the expanded text is matched literally.
|
||||
type likePatterns struct {
|
||||
patterns []string
|
||||
expand func(string) string
|
||||
}
|
||||
|
||||
func matchesLikePattern(conditionValue interface{}, contextValue string) bool {
|
||||
if lp, ok := conditionValue.(likePatterns); ok {
|
||||
for _, pattern := range lp.patterns {
|
||||
if wildcard.MatchesExpandedWildcard(pattern, PolicyVariableRegex, lp.expand, contextValue, false) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, pattern := range normalizeToStringSlice(conditionValue) {
|
||||
if wildcard.MatchesWildcard(pattern, contextValue) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -66,12 +87,9 @@ func (e *StringLikeEvaluator) Evaluate(conditionValue interface{}, contextValues
|
||||
type StringNotLikeEvaluator struct{}
|
||||
|
||||
func (e *StringNotLikeEvaluator) Evaluate(conditionValue interface{}, contextValues []string) bool {
|
||||
patterns := normalizeToStringSlice(conditionValue)
|
||||
for _, pattern := range patterns {
|
||||
for _, contextValue := range contextValues {
|
||||
if wildcard.MatchesWildcard(pattern, contextValue) {
|
||||
return false
|
||||
}
|
||||
for _, contextValue := range contextValues {
|
||||
if matchesLikePattern(conditionValue, contextValue) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
@@ -499,12 +517,9 @@ func (e *ArnEqualsEvaluator) Evaluate(conditionValue interface{}, contextValues
|
||||
type ArnLikeEvaluator struct{}
|
||||
|
||||
func (e *ArnLikeEvaluator) Evaluate(conditionValue interface{}, contextValues []string) bool {
|
||||
patterns := normalizeToStringSlice(conditionValue)
|
||||
for _, pattern := range patterns {
|
||||
for _, contextValue := range contextValues {
|
||||
if wildcard.MatchesWildcard(pattern, contextValue) {
|
||||
return true
|
||||
}
|
||||
for _, contextValue := range contextValues {
|
||||
if matchesLikePattern(conditionValue, contextValue) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
@@ -702,12 +717,20 @@ func evaluateConditions(conditions PolicyConditions, contextValues map[string][]
|
||||
|
||||
// Substitute variables in expected values
|
||||
expectedValues := value.Strings()
|
||||
substitutedValues := make([]string, len(expectedValues))
|
||||
for i, v := range expectedValues {
|
||||
substitutedValues[i] = SubstituteVariables(v, contextValues, claims)
|
||||
var conditionValue interface{}
|
||||
if strings.HasSuffix(operator, "Like") {
|
||||
conditionValue = likePatterns{patterns: expectedValues, expand: func(v string) string {
|
||||
return SubstituteVariables(v, contextValues, claims)
|
||||
}}
|
||||
} else {
|
||||
substitutedValues := make([]string, len(expectedValues))
|
||||
for i, v := range expectedValues {
|
||||
substitutedValues[i] = SubstituteVariables(v, contextValues, claims)
|
||||
}
|
||||
conditionValue = substitutedValues
|
||||
}
|
||||
|
||||
if !conditionEvaluator.Evaluate(substitutedValues, contextVals) {
|
||||
if !conditionEvaluator.Evaluate(conditionValue, contextVals) {
|
||||
return false // If any condition fails, the whole condition block fails
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
|
||||
)
|
||||
|
||||
// PolicyEvaluationResult represents the result of policy evaluation
|
||||
@@ -181,9 +182,9 @@ func (engine *PolicyEngine) evaluateCompiledPolicy(policy *CompiledPolicy, args
|
||||
|
||||
// matchesDynamicPatterns checks if a value matches any of the dynamic patterns after variable substitution
|
||||
func (engine *PolicyEngine) matchesDynamicPatterns(patterns []string, value string, args *PolicyEvaluationArgs) bool {
|
||||
expand := func(v string) string { return SubstituteVariables(v, args.Conditions, args.Claims) }
|
||||
for _, pattern := range patterns {
|
||||
substituted := SubstituteVariables(pattern, args.Conditions, args.Claims)
|
||||
if FastMatchesWildcard(substituted, value) {
|
||||
if wildcard.MatchesExpandedWildcard(pattern, PolicyVariableRegex, expand, value, false) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,3 +150,79 @@ func TestEvaluatePolicyForRequestVariables(t *testing.T) {
|
||||
t.Errorf("Expected Indeterminate when resource doesn't match variable, got %v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyVariableValuesAreNotWildcards(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
policyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:GetObject",
|
||||
"Resource": "arn:aws:s3:::home/${jwt:email}/*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": "arn:aws:iam::123456789012:user/${jwt:preferred_username}"},
|
||||
"Action": "s3:PutObject",
|
||||
"Resource": "arn:aws:s3:::home/*"
|
||||
}
|
||||
]
|
||||
}`
|
||||
if err := engine.SetBucketPolicy("home", policyJSON); err != nil {
|
||||
t.Fatalf("Failed to set bucket policy: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
action string
|
||||
key string
|
||||
principal string
|
||||
claims map[string]interface{}
|
||||
want PolicyEvaluationResult
|
||||
}{
|
||||
{"owner", "s3:GetObject", "alice@corp.com/secret.txt", "*", map[string]interface{}{"email": "alice@corp.com"}, PolicyResultAllow},
|
||||
{"other user", "s3:GetObject", "alice@corp.com/secret.txt", "*", map[string]interface{}{"email": "bob@corp.com"}, PolicyResultIndeterminate},
|
||||
{"star email", "s3:GetObject", "alice@corp.com/secret.txt", "*", map[string]interface{}{"email": "*@corp.com"}, PolicyResultIndeterminate},
|
||||
{"bare star email", "s3:GetObject", "alice@corp.com/secret.txt", "*", map[string]interface{}{"email": "*"}, PolicyResultIndeterminate},
|
||||
{"question mark email", "s3:GetObject", "alice@corp.com/secret.txt", "*", map[string]interface{}{"email": "?lice@corp.com"}, PolicyResultIndeterminate},
|
||||
{"literal star owner", "s3:GetObject", "*@corp.com/own.txt", "*", map[string]interface{}{"email": "*@corp.com"}, PolicyResultAllow},
|
||||
{"principal owner", "s3:PutObject", "x", "arn:aws:iam::123456789012:user/alice", map[string]interface{}{"preferred_username": "alice"}, PolicyResultAllow},
|
||||
{"principal star", "s3:PutObject", "x", "arn:aws:iam::123456789012:user/alice", map[string]interface{}{"preferred_username": "*"}, PolicyResultIndeterminate},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := engine.EvaluatePolicy("home", &PolicyEvaluationArgs{
|
||||
Action: tt.action,
|
||||
Resource: "arn:aws:s3:::home/" + tt.key,
|
||||
Principal: tt.principal,
|
||||
Claims: tt.claims,
|
||||
})
|
||||
if got != tt.want {
|
||||
t.Errorf("got %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLikeConditionVariableValuesAreNotWildcards(t *testing.T) {
|
||||
prefix := map[string][]string{"s3:prefix": {"alice@corp.com/"}}
|
||||
for _, operator := range []string{"StringLike", "ForAnyValue:StringLike", "StringNotLike"} {
|
||||
conditions := PolicyConditions{operator: {"s3:prefix": NewStringOrStringSlice("${jwt:email}/*")}}
|
||||
for _, email := range []string{"alice@corp.com", "bob@corp.com", "*@corp.com", "*", "?lice@corp.com"} {
|
||||
want := email == "alice@corp.com"
|
||||
if operator == "StringNotLike" {
|
||||
want = !want
|
||||
}
|
||||
if got := EvaluateConditions(conditions, prefix, nil, map[string]interface{}{"email": email}); got != want {
|
||||
t.Errorf("%s email=%q: got %v, want %v", operator, email, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
arnLike := PolicyConditions{"ArnLike": {"aws:SourceArn": NewStringOrStringSlice("arn:aws:iam::123456789012:user/${jwt:sub}")}}
|
||||
source := map[string][]string{"aws:SourceArn": {"arn:aws:iam::123456789012:user/alice"}}
|
||||
if EvaluateConditions(arnLike, source, nil, map[string]interface{}{"sub": "*"}) {
|
||||
t.Errorf("ArnLike matched another user's ARN through a wildcard sub")
|
||||
}
|
||||
}
|
||||
@@ -761,9 +761,9 @@ func (cs *CompiledStatement) matchesPrincipalSet(args *PolicyEvaluationArgs, mat
|
||||
return true
|
||||
}
|
||||
}
|
||||
expand := func(v string) string { return SubstituteVariables(v, args.Conditions, args.Claims) }
|
||||
for _, pattern := range dynamic {
|
||||
substituted := SubstituteVariables(pattern, args.Conditions, args.Claims)
|
||||
if FastMatchesWildcard(substituted, args.Principal) {
|
||||
if wildcard.MatchesExpandedWildcard(pattern, PolicyVariableRegex, expand, args.Principal, false) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,12 +117,47 @@ func (m *WildcardMatcher) Match(str string) bool {
|
||||
if m.useRegex {
|
||||
return m.regex.MatchString(str)
|
||||
}
|
||||
return matchWildcardString(m.pattern, str)
|
||||
return matchWildcardString(m.pattern, nil, str)
|
||||
}
|
||||
|
||||
// MatchesWildcard provides a simple function interface for wildcard matching.
|
||||
func MatchesWildcard(pattern, str string) bool {
|
||||
return matchWildcardString(pattern, str)
|
||||
return matchWildcardString(pattern, nil, str)
|
||||
}
|
||||
|
||||
// MatchesExpandedWildcard matches str against pattern after replacing each
|
||||
// match of vars with expand(match). The replacement text is matched literally,
|
||||
// so only '*' and '?' written in pattern itself act as wildcards.
|
||||
func MatchesExpandedWildcard(pattern string, vars *regexp.Regexp, expand func(string) string, str string, ignoreCase bool) bool {
|
||||
if ignoreCase {
|
||||
str = strings.ToLower(str)
|
||||
}
|
||||
locs := vars.FindAllStringIndex(pattern, -1)
|
||||
if len(locs) == 0 {
|
||||
if ignoreCase {
|
||||
pattern = strings.ToLower(pattern)
|
||||
}
|
||||
return matchWildcardString(pattern, nil, str)
|
||||
}
|
||||
var expanded strings.Builder
|
||||
var literal []bool
|
||||
add := func(s string, isLiteral bool) {
|
||||
if ignoreCase {
|
||||
s = strings.ToLower(s)
|
||||
}
|
||||
expanded.WriteString(s)
|
||||
for range len(s) {
|
||||
literal = append(literal, isLiteral)
|
||||
}
|
||||
}
|
||||
prev := 0
|
||||
for _, loc := range locs {
|
||||
add(pattern[prev:loc[0]], false)
|
||||
add(expand(pattern[loc[0]:loc[1]]), true)
|
||||
prev = loc[1]
|
||||
}
|
||||
add(pattern[prev:], false)
|
||||
return matchWildcardString(expanded.String(), literal, str)
|
||||
}
|
||||
|
||||
// FastMatchesWildcard uses a cached WildcardMatcher for repeated pattern matching.
|
||||
@@ -140,8 +175,12 @@ func CompileWildcardPattern(pattern string) (*regexp.Regexp, error) {
|
||||
return compileWildcardPattern(pattern)
|
||||
}
|
||||
|
||||
func matchWildcardString(pattern, str string) bool {
|
||||
if pattern == "*" {
|
||||
func isWildcardAt(pattern string, literal []bool, i int, c byte) bool {
|
||||
return pattern[i] == c && (literal == nil || !literal[i])
|
||||
}
|
||||
|
||||
func matchWildcardString(pattern string, literal []bool, str string) bool {
|
||||
if len(pattern) == 1 && isWildcardAt(pattern, literal, 0, '*') {
|
||||
return true
|
||||
}
|
||||
if pattern == str {
|
||||
@@ -157,11 +196,11 @@ func matchWildcardString(pattern, str string) bool {
|
||||
switch {
|
||||
// '*' must be checked before literal equality so a '*' in the target
|
||||
// cannot consume the pattern wildcard without a backtrack point
|
||||
case patternIndex < len(pattern) && pattern[patternIndex] == '*':
|
||||
case patternIndex < len(pattern) && isWildcardAt(pattern, literal, patternIndex, '*'):
|
||||
lastStarIndex = patternIndex
|
||||
lastStarMatchIndex = targetIndex
|
||||
patternIndex++
|
||||
case patternIndex < len(pattern) && (pattern[patternIndex] == '?' || pattern[patternIndex] == str[targetIndex]):
|
||||
case patternIndex < len(pattern) && (isWildcardAt(pattern, literal, patternIndex, '?') || pattern[patternIndex] == str[targetIndex]):
|
||||
targetIndex++
|
||||
patternIndex++
|
||||
case lastStarIndex != -1:
|
||||
@@ -173,7 +212,7 @@ func matchWildcardString(pattern, str string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
for patternIndex < len(pattern) && pattern[patternIndex] == '*' {
|
||||
for patternIndex < len(pattern) && isWildcardAt(pattern, literal, patternIndex, '*') {
|
||||
patternIndex++
|
||||
}
|
||||
return patternIndex == len(pattern)
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package wildcard
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMatchesWildcard(t *testing.T) {
|
||||
tests := []struct {
|
||||
@@ -215,3 +218,38 @@ func BenchmarkFastMatchesWildcard(b *testing.B) {
|
||||
FastMatchesWildcard("s3:Get*", "s3:GetObject")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesExpandedWildcard(t *testing.T) {
|
||||
vars := regexp.MustCompile(`\$\{([^}]+)\}`)
|
||||
values := map[string]string{"${user}": "", "${star}": "*", "${q}": "?lice", "${mixed}": "Al*"}
|
||||
expand := func(v string) string {
|
||||
if s, ok := values[v]; ok {
|
||||
return s
|
||||
}
|
||||
return v
|
||||
}
|
||||
tests := []struct {
|
||||
pattern string
|
||||
str string
|
||||
ignoreCase bool
|
||||
want bool
|
||||
}{
|
||||
{"home/${star}/*", "home/alice/secret", false, false},
|
||||
{"home/${star}/*", "home/*/own", false, true},
|
||||
{"${star}", "anything", false, false},
|
||||
{"${star}", "*", false, true},
|
||||
{"home/${q}/*", "home/alice/x", false, false},
|
||||
{"home/${q}/*", "home/?lice/x", false, true},
|
||||
{"home/${user}*", "home/anyone", false, true},
|
||||
{"home/${unset}/*", "home/${unset}/x", false, true},
|
||||
{"home/${unset}/*", "home/alice/x", false, false},
|
||||
{"Home/${mixed}/?", "home/al*/x", true, true},
|
||||
{"Home/${mixed}/?", "home/alice/x", true, false},
|
||||
{"plain*", "plain-text", false, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := MatchesExpandedWildcard(tt.pattern, vars, expand, tt.str, tt.ignoreCase); got != tt.want {
|
||||
t.Errorf("MatchesExpandedWildcard(%q, %q, ignoreCase=%v) = %v, want %v", tt.pattern, tt.str, tt.ignoreCase, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user