Skip to content

Commit

Permalink
fakestorage: add name validation on bucket creation
Browse files Browse the repository at this point in the history
  • Loading branch information
fsouza committed Sep 12, 2020
1 parent 32043a0 commit d8107a8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
16 changes: 16 additions & 0 deletions fakestorage/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ package fakestorage

import (
"encoding/json"
"errors"
"net/http"
"regexp"

"github.com/gorilla/mux"
)

var bucketRegexp = regexp.MustCompile(`^[a-zA-Z0-9-][a-zA-Z0-9.-]*[a-zA-Z0-9-]$`)

// CreateBucket creates a bucket inside the server, so any API calls that
// require the bucket name will recognize this bucket.
//
Expand Down Expand Up @@ -62,6 +66,11 @@ func (s *Server) createBucketByPost(w http.ResponseWriter, r *http.Request) {
if data.Versioning != nil {
versioning = data.Versioning.Enabled
}
if err := validateBucketName(name); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

// Create the named bucket
if err := s.backend.CreateBucket(name, versioning); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Expand Down Expand Up @@ -102,3 +111,10 @@ func (s *Server) getBucket(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
encoder.Encode(resp)
}

func validateBucketName(bucketName string) error {
if !bucketRegexp.MatchString(bucketName) {
return errors.New("invalid bucket name")
}
return nil
}
23 changes: 23 additions & 0 deletions fakestorage/bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func TestServerClientBucketAttrsAfterCreateBucket(t *testing.T) {
}

func TestServerClientBucketAttrsAfterCreateBucketByPost(t *testing.T) {
t.Parallel()
for _, versioningEnabled := range []bool{true, false} {
versioningEnabled := versioningEnabled
runServersTest(t, nil, func(t *testing.T, server *Server) {
Expand Down Expand Up @@ -92,6 +93,28 @@ func TestServerClientBucketAttrsAfterCreateBucketByPost(t *testing.T) {
}
}

func TestServerClientBucketCreateValidation(t *testing.T) {
bucketNames := []string{
"..what-is-this",
".host.name.cant.start.with.dot",
"no_underlines_either",
"or spaces",
"don't even try",
"no/slashes/either",
}

for _, bucketName := range bucketNames {
bucketName := bucketName
runServersTest(t, nil, func(t *testing.T, server *Server) {
client := server.Client()
err := client.Bucket(bucketName).Create(context.Background(), "whatever", nil)
if err == nil {
t.Error("unexpected <nil> error")
}
})
}
}

func TestServerClientBucketAttrsNotFound(t *testing.T) {
runServersTest(t, nil, func(t *testing.T, server *Server) {
client := server.Client()
Expand Down

0 comments on commit d8107a8

Please sign in to comment.