Skip to content
Merged
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
22 changes: 13 additions & 9 deletions policy/condition/stringfunc.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,19 @@ import (
"github.com/minio/pkg/v3/wildcard"
)

// substitute expands policy variables in a condition value that is compared as
// text.
func substitute(values map[string][]string) func(string) string {
return func(v string) string {
for _, key := range CommonKeys {
// Empty values are not supported for policy variables.
if rvalues, ok := values[key.Name()]; ok && rvalues[0] != "" {
v = strings.ReplaceAll(v, key.VarName(), rvalues[0])
}
}
return v
return Substitute(v, values, false)
Comment thread
klauspost marked this conversation as resolved.
}
}

// substitutePattern expands policy variables in a condition value that is
// wildcard matched. The result is a pattern for wildcard.MatchEscaped.
func substitutePattern(values map[string][]string) func(string) string {
return func(v string) string {
return Substitute(v, values, true)
}
}

Expand Down Expand Up @@ -131,9 +135,9 @@ type stringLikeFunc struct {

func (f stringLikeFunc) eval(values map[string][]string) bool {
rvalues := getValuesByKey(values, f.k)
fvalues := f.values.ApplyFunc(substitute(values))
fvalues := f.values.ApplyFunc(substitutePattern(values))
for _, v := range rvalues {
matched := !fvalues.FuncMatch(wildcard.Match, v).IsEmpty()
matched := !fvalues.FuncMatch(wildcard.MatchEscaped, v).IsEmpty()
if f.n.qualifier == forAllValues {
if !matched {
return false
Expand Down
71 changes: 71 additions & 0 deletions policy/condition/stringfunc_bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright (c) 2015-2026 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package condition

import "testing"

func BenchmarkStringLikeFuncEvaluate(b *testing.B) {
benchCases := []struct {
name string
prefix string
patterns []string
}{
{"NoVariable", "home/alice/docs/", []string{"home/*", "public/*", "shared/*"}},
{"Variable", "home/alice/docs/", []string{"home/${aws:username}/*", "public/*", "shared/*"}},
{"Escape", "home/alice/*/docs/", []string{"home/${aws:username}/${*}/*", "public/*", "shared/*"}},
}
for _, bc := range benchCases {
function, err := NewStringLikeFunc("", S3Prefix.ToKey(), bc.patterns...)
if err != nil {
b.Fatal(err)
}
values := map[string][]string{
"prefix": {bc.prefix},
"username": {"alice"},
}
if !function.evaluate(values) {
b.Fatalf("%s: want a match", bc.name)
}
b.Run(bc.name, func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
function.evaluate(values)
}
})
}
}

func BenchmarkSubstitute(b *testing.B) {
values := map[string][]string{"username": {"alice"}}
benchCases := []struct {
name, pattern string
}{
{"NoVariable", "test-bucket/home/alice/*"},
{"Variable", "test-bucket/home/${aws:username}/*"},
{"UnknownVariable", "test-bucket/home/${aws:nosuchkey}/*"},
{"Escape", `test-bucket/home/${aws:username}/${*}\file`},
}
for _, bc := range benchCases {
b.Run(bc.name, func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
Substitute(bc.pattern, values, true)
}
})
}
}
42 changes: 42 additions & 0 deletions policy/condition/stringfunc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -817,3 +817,45 @@ func TestNewStringFuncError(t *testing.T) {
t.Errorf("error expected")
}
}

func TestStringFuncEscapes(t *testing.T) {
testCases := []struct {
condValue string
reqValue string
wantEqual bool
wantLike bool
}{
// ${*} is a literal asterisk to both operators. Only StringLike reads
// an unescaped '*' as a wildcard.
{"prefix${*}", "prefix*", true, true},
{"prefix${*}", "prefixfoo", false, false},
{"prefix*", "prefixfoo", false, true},
{"${?}", "?", true, true},
{"${?}", "a", false, false},
{"${$}{aws:username}", "${aws:username}", true, true},
{"${$}{aws:username}", "david", false, false},
{"${aws:username}", "david", true, true},
}

for _, tc := range testCases {
t.Run(tc.condValue+"|"+tc.reqValue, func(t *testing.T) {
reqValues := map[string][]string{"prefix": {tc.reqValue}, "username": {"david"}}

eqFunc, err := NewStringEqualsFunc("", S3Prefix.ToKey(), tc.condValue)
if err != nil {
t.Fatalf("NewStringEqualsFunc: %v", err)
}
if got := eqFunc.evaluate(reqValues); got != tc.wantEqual {
t.Fatalf("StringEquals(%q).evaluate(%q) = %v, want %v", tc.condValue, tc.reqValue, got, tc.wantEqual)
}

likeFunc, err := newStringLikeFunc(S3Prefix.ToKey(), NewValueSet(NewStringValue(tc.condValue)), "")
if err != nil {
t.Fatalf("newStringLikeFunc: %v", err)
}
if got := likeFunc.evaluate(reqValues); got != tc.wantLike {
t.Fatalf("StringLike(%q).evaluate(%q) = %v, want %v", tc.condValue, tc.reqValue, got, tc.wantLike)
}
})
}
}
111 changes: 111 additions & 0 deletions policy/condition/substitute.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copyright (c) 2015-2025 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package condition

import (
"strings"
)

// Predefined policy variables, each expanding to one literal character. A
// policy uses them where it needs the character itself rather than a wildcard
// or the start of a variable.
const (
// VarAsterisk expands to a literal '*'.
VarAsterisk = "${*}"

// VarQuestion expands to a literal '?'.
VarQuestion = "${?}"

// VarDollar expands to a literal '$'.
VarDollar = "${$}"
)

// Substitute expands the policy variables in pattern using the request's
// condition values. A variable that is unknown or carries no value is left as
// written. An expanded value is never scanned for further variables.
//
// The escapes ${*}, ${?} and ${$} expand to a literal character. Set escape to
// match the result with wildcard.MatchEscaped. Leave it unset to compare the
// result as text.
func Substitute(pattern string, values map[string][]string, escape bool) string {
if strings.IndexByte(pattern, '$') < 0 && (!escape || strings.IndexByte(pattern, '\\') < 0) {
return pattern
}
var buf [128]byte
return string(AppendSubstitute(buf[:0], pattern, values, escape))
}

// AppendSubstitute is Substitute that appends the result to dst, so a caller
// whose result stays local can expand without allocating.
func AppendSubstitute(dst []byte, pattern string, values map[string][]string, escape bool) []byte {
for len(pattern) > 0 {
idx := strings.IndexByte(pattern, '$')
if idx < 0 {
return appendText(dst, pattern, escape)
}
dst = appendText(dst, pattern[:idx], escape)
pattern = pattern[idx:]
if len(pattern) < 3 || pattern[1] != '{' {
dst = append(dst, '$')
pattern = pattern[1:]
continue
}
// No '}' in pattern means none in any suffix of it either. Emit the
// rest and stop, instead of rescanning at every '${'.
keyEnds := strings.IndexByte(pattern, '}')
if keyEnds < 0 {
return appendText(dst, pattern, escape)
}

name := pattern[2:keyEnds]
switch pattern[:keyEnds+1] {
case VarAsterisk, VarQuestion, VarDollar:
if escape {
dst = append(dst, '\\')
}
dst = append(dst, name...)
default:
ckey := KeyName(name)
// Only replace keys we know, and only when they carry a value.
if rvalues, ok := values[ckey.Name()]; CommonKeysMap[ckey] && ok && len(rvalues) > 0 && rvalues[0] != "" {
dst = appendText(dst, rvalues[0], escape)
} else {
dst = appendText(dst, pattern[:keyEnds+1], escape)
}
}
pattern = pattern[keyEnds+1:]
}
return dst
}

// appendText appends s to dst. With escape set, s is written so that it
// matches only itself.
func appendText(dst []byte, s string, escape bool) []byte {
if !escape {
return append(dst, s...)
}
for {
i := strings.IndexByte(s, '\\')
if i < 0 {
return append(dst, s...)
}
dst = append(dst, s[:i]...)
dst = append(dst, '\\', '\\')
s = s[i+1:]
}
}
95 changes: 95 additions & 0 deletions policy/condition/substitute_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright (c) 2015-2025 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package condition

import (
"strings"
"testing"
"time"

"github.com/minio/pkg/v3/wildcard"
)

func TestSubstitute(t *testing.T) {
values := map[string][]string{
"username": {"david"},
"userid": {""},
}

// wantMatch, when set, is a string the escaped pattern must match.
testCases := []struct {
pattern string
wantLiteral string
wantEscaped string
wantMatch string
}{
{"mybucket/foo", "mybucket/foo", "mybucket/foo", ""},
{"mybucket/${aws:username}/*", "mybucket/david/*", "mybucket/david/*", ""},
// A key with no value, or one that is not a known key, stays as written.
{"mybucket/${aws:userid}/*", "mybucket/${aws:userid}/*", "mybucket/${aws:userid}/*", ""},
{"mybucket/${aws:nosuchkey}", "mybucket/${aws:nosuchkey}", "mybucket/${aws:nosuchkey}", ""},
// The predefined escapes.
{"mybucket/${*}", "mybucket/*", `mybucket/\*`, "mybucket/*"},
{"mybucket/${?}", "mybucket/?", `mybucket/\?`, "mybucket/?"},
{"mybucket/${$}", "mybucket/$", `mybucket/\$`, "mybucket/$"},
{"${*}${?}${$}", "*?$", `\*\?\$`, "*?$"},
// An expansion is not rescanned, so ${$} does not build a variable.
{"${$}{aws:username}", "${aws:username}", `\${aws:username}`, "${aws:username}"},
// A backslash the policy wrote stands for itself either way.
{`my\bucket/${*}`, `my\bucket/*`, `my\\bucket/\*`, `my\bucket/*`},
{`my\bucket`, `my\bucket`, `my\\bucket`, `my\bucket`},
// Incomplete variable syntax is emitted as written.
{"mybucket/$", "mybucket/$", "mybucket/$", ""},
{"mybucket/${", "mybucket/${", "mybucket/${", ""},
{"mybucket/${aws:username", "mybucket/${aws:username", "mybucket/${aws:username", ""},
{"mybucket/${}", "mybucket/${}", "mybucket/${}", ""},
{"mybucket/$${aws:username}", "mybucket/$david", "mybucket/$david", ""},
}

for _, tc := range testCases {
t.Run(tc.pattern, func(t *testing.T) {
if got := Substitute(tc.pattern, values, false); got != tc.wantLiteral {
t.Fatalf("Substitute(%q, false) = %q, want %q", tc.pattern, got, tc.wantLiteral)
}
if got := Substitute(tc.pattern, values, true); got != tc.wantEscaped {
t.Fatalf("Substitute(%q, true) = %q, want %q", tc.pattern, got, tc.wantEscaped)
}
if tc.wantMatch != "" && !wildcard.MatchEscaped(tc.wantEscaped, tc.wantMatch) {
t.Fatalf("escaped pattern %q does not match %q", tc.wantEscaped, tc.wantMatch)
}
})
}
}

// An unclosed '${' must not restart the scan for '}' one byte later. Doing so
// is quadratic in the pattern length.
func TestSubstituteUnterminatedVariablesAreLinear(t *testing.T) {
values := map[string][]string{"username": {"david"}}

for _, n := range []int{1 << 10, 1 << 12, 1 << 14, 1 << 16} {
pattern := strings.Repeat("${", n)
start := time.Now()
got := Substitute(pattern, values, true)
if d := time.Since(start); d > 50*time.Millisecond {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
t.Errorf("Substitute over %d bytes took %v, want well under 50ms", len(pattern), d)
}
if got != pattern {
t.Fatalf("Substitute(%d unterminated variables) rewrote the pattern", n)
}
}
}
Loading
Loading