types/model: export IsValidNamePart (#3788)

This commit is contained in:
Blake Mizerany 2024-04-20 18:26:34 -07:00 committed by GitHub
parent e6f9bfc0e8
commit 56f8aa6912
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 15 additions and 6 deletions

View file

@ -156,7 +156,7 @@ func ParseName(s, fill string) Name {
r = Name{} r = Name{}
return false return false
} }
if kind == PartExtraneous || !isValidPart(kind, part) { if kind == PartExtraneous || !IsValidNamePart(kind, part) {
r = Name{} r = Name{}
return false return false
} }
@ -176,7 +176,7 @@ func parseMask(s string) Name {
// mask part; treat as empty but valid // mask part; treat as empty but valid
return true return true
} }
if !isValidPart(kind, part) { if !IsValidNamePart(kind, part) {
panic(fmt.Errorf("invalid mask part %s: %q", kind, part)) panic(fmt.Errorf("invalid mask part %s: %q", kind, part))
} }
r.parts[kind] = part r.parts[kind] = part
@ -608,7 +608,7 @@ func ParseNameFromFilepath(s, fill string) Name {
var r Name var r Name
for i := range PartBuild + 1 { for i := range PartBuild + 1 {
part, rest, _ := strings.Cut(s, string(filepath.Separator)) part, rest, _ := strings.Cut(s, string(filepath.Separator))
if !isValidPart(i, part) { if !IsValidNamePart(i, part) {
return Name{} return Name{}
} }
r.parts[i] = part r.parts[i] = part
@ -654,9 +654,12 @@ func (r Name) FilepathNoBuild() string {
return filepath.Join(r.parts[:PartBuild]...) return filepath.Join(r.parts[:PartBuild]...)
} }
// isValidPart reports if s contains all valid characters for the given // IsValidNamePart reports if s contains all valid characters for the given
// part kind. // part kind and is under MaxNamePartLen bytes.
func isValidPart(kind PartKind, s string) bool { func IsValidNamePart(kind PartKind, s string) bool {
if len(s) > MaxNamePartLen {
return false
}
if s == "" { if s == "" {
return false return false
} }

View file

@ -105,6 +105,12 @@ var testNames = map[string]fields{
strings.Repeat("a", MaxNamePartLen+1): {}, strings.Repeat("a", MaxNamePartLen+1): {},
} }
func TestIsValidNameLen(t *testing.T) {
if IsValidNamePart(PartNamespace, strings.Repeat("a", MaxNamePartLen+1)) {
t.Errorf("unexpectedly valid long name")
}
}
// TestConsecutiveDots tests that consecutive dots are not allowed in any // TestConsecutiveDots tests that consecutive dots are not allowed in any
// part, to avoid path traversal. There also are some tests in testNames, but // part, to avoid path traversal. There also are some tests in testNames, but
// this test is more exhaustive and exists to emphasize the importance of // this test is more exhaustive and exists to emphasize the importance of