Skip to content
This repository has been archived by the owner on Mar 16, 2024. It is now read-only.

Commit

Permalink
Fix edge case in range syntax sugar
Browse files Browse the repository at this point in the history
Handle special case where the range first character in the range is lowercase
and the second is uppercase. This is necessary because uppercase letters come
before lowercase letters in the ASCII table, and lets us support ranges like
`a-Z`.

Signed-off-by: Nick Hale <[email protected]>
  • Loading branch information
njhale committed Oct 17, 2023
1 parent 87ccaa2 commit 23c6764
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
40 changes: 28 additions & 12 deletions pkg/secrets/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/rand"
"math/big"
"sort"
"unicode"

"k8s.io/apimachinery/pkg/util/sets"
)
Expand Down Expand Up @@ -48,26 +49,41 @@ func inflateRanges(characterSet string) string {
)
for i := 0; i < len(runeSet); i++ {
cur := runeSet[i]
if alphanumeric(cur) {
// Alphanumeric character detected
if i+2 < len(runeSet) && runeSet[i+1] == '-' && alphanumeric(runeSet[i+2]) {
// Range detected, convert to full set of characters
start, end := cur, runeSet[i+2]
if start > end {
// Swap start and end if they're out of order
start, end = end, start
// Alphanumeric character detected
if alphanumeric(cur) && (i+2 < len(runeSet) && runeSet[i+1] == '-' && alphanumeric(runeSet[i+2])) {
// Range detected, convert to full set of characters
start, end := cur, runeSet[i+2]
if start > end {
// Swap start and end if they're out of order
start, end = end, start
}

// Handle special case where the range first character in the range is lowercase and the second is uppercase.
// This is necessary because uppercase letters come before lowercase letters in the ASCII table, and lets
// us support ranges like `a-Z`.
if unicode.IsLower(end) && unicode.IsUpper(start) {
for c := start; c <= 'z'; c++ {
if alphanumeric(c) {
inflated.Insert(c)
}
}

for c := 'A'; c <= end; c++ {
if alphanumeric(c) {
inflated.Insert(c)
}
}
} else {
for c := start; c <= end; c++ {
if alphanumeric(c) {
inflated.Insert(c)
}
}

// Skip the next two characters since we've already processed them
i += 2
continue
}

// Skip the next two characters since we've already processed them
i += 2
continue
}

inflated.Insert(cur)
Expand Down
8 changes: 8 additions & 0 deletions pkg/secrets/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ func TestInflateRanges(t *testing.T) {
name: "z-A",
want: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
},
{
name: "a-Z",
want: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
},
{
name: "Z-a",
want: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
},
{
name: "a-z",
want: "abcdefghijklmnopqrstuvwxyz",
Expand Down

0 comments on commit 23c6764

Please sign in to comment.