diff --git a/pkg/s3/.gitignore b/pkg/s3/.gitignore new file mode 100644 index 00000000..d852bed5 --- /dev/null +++ b/pkg/s3/.gitignore @@ -0,0 +1 @@ +rootkey.csv \ No newline at end of file diff --git a/pkg/s3/auth.go b/pkg/s3/auth.go new file mode 100644 index 00000000..d8c45e24 --- /dev/null +++ b/pkg/s3/auth.go @@ -0,0 +1,206 @@ +/* +Copyright 2011 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package s3 + +import ( + "bytes" + "crypto/hmac" + "crypto/sha1" + "encoding/base64" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strings" + "time" +) + +// See http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html + +type Auth struct { + AccessKey string + SecretAccessKey string + + // Hostname is the S3 hostname to use. + // If empty, the standard US region of "s3.amazonaws.com" is + // used. + Hostname string +} + +const standardUSRegionAWS = "s3.amazonaws.com" + +func (a *Auth) hostname() string { + if a.Hostname != "" { + return a.Hostname + } + return standardUSRegionAWS +} + +func (a *Auth) SignRequest(req *http.Request) { + if date := req.Header.Get("Date"); date == "" { + req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat)) + } + hm := hmac.New(sha1.New, []byte(a.SecretAccessKey)) + ss := a.stringToSign(req) + // log.Printf("String to sign: %q (%x)", ss, ss) + io.WriteString(hm, ss) + + authHeader := new(bytes.Buffer) + fmt.Fprintf(authHeader, "AWS %s:", a.AccessKey) + encoder := base64.NewEncoder(base64.StdEncoding, authHeader) + encoder.Write(hm.Sum(nil)) + encoder.Close() + req.Header.Set("Authorization", authHeader.String()) +} + +func firstNonEmptyString(strs ...string) string { + for _, s := range strs { + if s != "" { + return s + } + } + return "" +} + +// From the Amazon docs: +// +// StringToSign = HTTP-Verb + "\n" + +// Content-MD5 + "\n" + +// Content-Type + "\n" + +// Date + "\n" + +// CanonicalizedAmzHeaders + +// CanonicalizedResource; +func (a *Auth) stringToSign(req *http.Request) string { + buf := new(bytes.Buffer) + buf.WriteString(req.Method) + buf.WriteByte('\n') + buf.WriteString(req.Header.Get("Content-MD5")) + buf.WriteByte('\n') + buf.WriteString(req.Header.Get("Content-Type")) + buf.WriteByte('\n') + if req.Header.Get("x-amz-date") == "" { + buf.WriteString(req.Header.Get("Date")) + } + buf.WriteByte('\n') + a.writeCanonicalizedAmzHeaders(buf, req) + a.writeCanonicalizedResource(buf, req) + return buf.String() +} + +func hasPrefixCaseInsensitive(s, pfx string) bool { + if len(pfx) > len(s) { + return false + } + shead := s[:len(pfx)] + if shead == pfx { + return true + } + shead = strings.ToLower(shead) + return shead == pfx || shead == strings.ToLower(pfx) +} + +func (a *Auth) writeCanonicalizedAmzHeaders(buf *bytes.Buffer, req *http.Request) { + amzHeaders := make([]string, 0) + vals := make(map[string][]string) + for k, vv := range req.Header { + if hasPrefixCaseInsensitive(k, "x-amz-") { + lk := strings.ToLower(k) + amzHeaders = append(amzHeaders, lk) + vals[lk] = vv + } + } + sort.Strings(amzHeaders) + for _, k := range amzHeaders { + buf.WriteString(k) + buf.WriteByte(':') + for idx, v := range vals[k] { + if idx > 0 { + buf.WriteByte(',') + } + if strings.Contains(v, "\n") { + // TODO: "Unfold" long headers that + // span multiple lines (as allowed by + // RFC 2616, section 4.2) by replacing + // the folding white-space (including + // new-line) by a single space. + buf.WriteString(v) + } else { + buf.WriteString(v) + } + } + buf.WriteByte('\n') + } +} + +// Must be sorted: +var subResList = []string{"acl", "lifecycle", "location", "logging", "notification", "partNumber", "policy", "requestPayment", "torrent", "uploadId", "uploads", "versionId", "versioning", "versions", "website"} + +// From the Amazon docs: +// +// CanonicalizedResource = [ "/" + Bucket ] + +// + +// [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"]; +func (a *Auth) writeCanonicalizedResource(buf *bytes.Buffer, req *http.Request) { + bucket := a.bucketFromHostname(req) + if bucket != "" { + buf.WriteByte('/') + buf.WriteString(bucket) + } + buf.WriteString(req.URL.Path) + if req.URL.RawQuery != "" { + n := 0 + vals, _ := url.ParseQuery(req.URL.RawQuery) + for _, subres := range subResList { + if vv, ok := vals[subres]; ok && len(vv) > 0 { + n++ + if n == 1 { + buf.WriteByte('?') + } else { + buf.WriteByte('&') + } + buf.WriteString(subres) + if len(vv[0]) > 0 { + buf.WriteByte('=') + buf.WriteString(url.QueryEscape(vv[0])) + } + } + } + } +} + +// hasDotSuffix reports whether s ends with "." + suffix. +func hasDotSuffix(s string, suffix string) bool { + return len(s) >= len(suffix)+1 && strings.HasSuffix(s, suffix) && s[len(s)-len(suffix)-1] == '.' +} + +func (a *Auth) bucketFromHostname(req *http.Request) string { + host := req.Host + if host == "" { + host = req.URL.Host + } + if host == a.hostname() { + return "" + } + if hostSuffix := a.hostname(); hasDotSuffix(host, hostSuffix) { + return host[:len(host)-len(hostSuffix)-1] + } + if lastColon := strings.LastIndex(host, ":"); lastColon != -1 { + return host[:lastColon] + } + return host +} diff --git a/pkg/s3/auth_test.go b/pkg/s3/auth_test.go new file mode 100644 index 00000000..531667d1 --- /dev/null +++ b/pkg/s3/auth_test.go @@ -0,0 +1,139 @@ +/* +Copyright 2011 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package s3 + +import ( + "bufio" + "fmt" + "net/http" + "strings" + "testing" +) + +type reqAndExpected struct { + req, expected string +} + +func req(s string) *http.Request { + req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(s))) + if err != nil { + panic(fmt.Sprintf("bad request in test: %v (error: %v)", req, err)) + } + return req +} + +func TestStringToSign(t *testing.T) { + var a Auth + tests := []reqAndExpected{ + {`GET /photos/puppy.jpg HTTP/1.1 +Host: johnsmith.s3.amazonaws.com +Date: Tue, 27 Mar 2007 19:36:42 +0000 + +`, + "GET\n\n\nTue, 27 Mar 2007 19:36:42 +0000\n/johnsmith/photos/puppy.jpg"}, + {`PUT /photos/puppy.jpg HTTP/1.1 +Content-Type: image/jpeg +Content-Length: 94328 +Host: johnsmith.s3.amazonaws.com +Date: Tue, 27 Mar 2007 21:15:45 +0000 + +`, + "PUT\n\nimage/jpeg\nTue, 27 Mar 2007 21:15:45 +0000\n/johnsmith/photos/puppy.jpg"}, + {`GET /?prefix=photos&max-keys=50&marker=puppy HTTP/1.1 +User-Agent: Mozilla/5.0 +Host: johnsmith.s3.amazonaws.com +Date: Tue, 27 Mar 2007 19:42:41 +0000 + +`, + "GET\n\n\nTue, 27 Mar 2007 19:42:41 +0000\n/johnsmith/"}, + {`DELETE /johnsmith/photos/puppy.jpg HTTP/1.1 +User-Agent: dotnet +Host: s3.amazonaws.com +Date: Tue, 27 Mar 2007 21:20:27 +0000 +x-amz-date: Tue, 27 Mar 2007 21:20:26 +0000 + +`, + "DELETE\n\n\n\nx-amz-date:Tue, 27 Mar 2007 21:20:26 +0000\n/johnsmith/photos/puppy.jpg"}, + {`PUT /db-backup.dat.gz HTTP/1.1 +User-Agent: curl/7.15.5 +Host: static.johnsmith.net:8080 +Date: Tue, 27 Mar 2007 21:06:08 +0000 +x-amz-acl: public-read +content-type: application/x-download +Content-MD5: 4gJE4saaMU4BqNR0kLY+lw== +X-Amz-Meta-ReviewedBy: joe@johnsmith.net +X-Amz-Meta-ReviewedBy: jane@johnsmith.net +X-Amz-Meta-FileChecksum: 0x02661779 +X-Amz-Meta-ChecksumAlgorithm: crc32 +Content-Disposition: attachment; filename=database.dat +Content-Encoding: gzip +Content-Length: 5913339 + +`, + "PUT\n4gJE4saaMU4BqNR0kLY+lw==\napplication/x-download\nTue, 27 Mar 2007 21:06:08 +0000\nx-amz-acl:public-read\nx-amz-meta-checksumalgorithm:crc32\nx-amz-meta-filechecksum:0x02661779\nx-amz-meta-reviewedby:joe@johnsmith.net,jane@johnsmith.net\n/static.johnsmith.net/db-backup.dat.gz"}, + } + for idx, test := range tests { + got := a.stringToSign(req(test.req)) + if got != test.expected { + t.Errorf("test %d: expected %q", idx, test.expected) + t.Errorf("test %d: got %q", idx, got) + } + } +} + +func TestBucketFromHostname(t *testing.T) { + var a Auth + tests := []reqAndExpected{ + {"GET / HTTP/1.0\n\n", ""}, + {"GET / HTTP/1.0\nHost: s3.amazonaws.com\n\n", ""}, + {"GET / HTTP/1.0\nHost: foo.s3.amazonaws.com\n\n", "foo"}, + {"GET / HTTP/1.0\nHost: foo.com:123\n\n", "foo.com"}, + {"GET / HTTP/1.0\nHost: bar.com\n\n", "bar.com"}, + } + for idx, test := range tests { + got := a.bucketFromHostname(req(test.req)) + if got != test.expected { + t.Errorf("test %d: expected %q; got %q", idx, test.expected, got) + } + } +} + +func TestSignRequest(t *testing.T) { + r := req("GET /foo HTTP/1.1\n\n") + auth := &Auth{AccessKey: "key", SecretAccessKey: "secretkey"} + auth.SignRequest(r) + if r.Header.Get("Date") == "" { + t.Error("expected a Date set") + } + r.Header.Set("Date", "Sat, 02 Apr 2011 04:23:52 GMT") + auth.SignRequest(r) + if e, g := r.Header.Get("Authorization"), "AWS key:kHpCR/N7Rw3PwRlDd8+5X40CFVc="; e != g { + t.Errorf("got header %q; expected %q", g, e) + } +} + +func TestHasDotSuffix(t *testing.T) { + if !hasDotSuffix("foo.com", "com") { + t.Fail() + } + if hasDotSuffix("foocom", "com") { + t.Fail() + } + if hasDotSuffix("com", "com") { + t.Fail() + } +} diff --git a/pkg/s3/client.go b/pkg/s3/client.go new file mode 100644 index 00000000..e6a63754 --- /dev/null +++ b/pkg/s3/client.go @@ -0,0 +1,440 @@ +/* +Copyright 2011 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package s3 implements a generic Amazon S3 client, not specific +// to Camlistore. +package s3 + +import ( + "bytes" + "encoding/base64" + "encoding/hex" + "encoding/xml" + "errors" + "fmt" + "hash" + "io" + "io/ioutil" + "log" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" +) + +const maxList = 1000 + +// Client is an Amazon S3 client. +type Client struct { + *Auth + Transport http.RoundTripper // or nil for the default +} + +type Bucket struct { + Name string + CreationDate string // 2006-02-03T16:45:09.000Z +} + +func (c *Client) transport() http.RoundTripper { + if c.Transport != nil { + return c.Transport + } + return http.DefaultTransport +} + +// bucketURL returns the URL prefix of the bucket, with trailing slash +func (c *Client) bucketURL(bucket string) string { + if IsValidBucket(bucket) && !strings.Contains(bucket, ".") { + return fmt.Sprintf("https://%s.%s/", bucket, c.hostname()) + } + return fmt.Sprintf("https://%s/%s/", c.hostname(), bucket) +} + +func (c *Client) keyURL(bucket, key string) string { + return c.bucketURL(bucket) + key +} + +func newReq(url_ string) *http.Request { + req, err := http.NewRequest("GET", url_, nil) + if err != nil { + panic(fmt.Sprintf("s3 client; invalid URL: %v", err)) + } + req.Header.Set("User-Agent", "minio-s3") + return req +} + +func (c *Client) Buckets() ([]*Bucket, error) { + req := newReq("https://" + c.hostname() + "/") + c.Auth.SignRequest(req) + res, err := c.transport().RoundTrip(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("s3: Unexpected status code %d fetching bucket list", res.StatusCode) + } + return parseListAllMyBuckets(res.Body) +} + +func parseListAllMyBuckets(r io.Reader) ([]*Bucket, error) { + type allMyBuckets struct { + Buckets struct { + Bucket []*Bucket + } + } + var res allMyBuckets + if err := xml.NewDecoder(r).Decode(&res); err != nil { + return nil, err + } + return res.Buckets.Bucket, nil +} + +// Returns 0, os.ErrNotExist if not on S3, otherwise reterr is real. +func (c *Client) Stat(key, bucket string) (size int64, reterr error) { + req := newReq(c.keyURL(bucket, key)) + req.Method = "HEAD" + c.Auth.SignRequest(req) + res, err := c.transport().RoundTrip(req) + if err != nil { + return 0, err + } + if res.Body != nil { + defer res.Body.Close() + } + switch res.StatusCode { + case http.StatusNotFound: + return 0, os.ErrNotExist + case http.StatusOK: + return strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64) + } + return 0, fmt.Errorf("s3: Unexpected status code %d statting object %v", res.StatusCode, key) +} + +func (c *Client) PutObject(key, bucket string, md5 hash.Hash, size int64, body io.Reader) error { + req := newReq(c.keyURL(bucket, key)) + req.Method = "PUT" + req.ContentLength = size + if md5 != nil { + b64 := new(bytes.Buffer) + encoder := base64.NewEncoder(base64.StdEncoding, b64) + encoder.Write(md5.Sum(nil)) + encoder.Close() + req.Header.Set("Content-MD5", b64.String()) + } + c.Auth.SignRequest(req) + req.Body = ioutil.NopCloser(body) + + res, err := c.transport().RoundTrip(req) + if res != nil && res.Body != nil { + defer res.Body.Close() + } + + if err != nil { + return err + } + if res.StatusCode != http.StatusOK { + // res.Write(os.Stderr) + return fmt.Errorf("Got response code %d from s3", res.StatusCode) + } + return nil +} + +type Item struct { + Key string + Size int64 +} + +type listBucketResults struct { + Contents []*Item + IsTruncated bool + MaxKeys int + Name string // bucket name + Marker string +} + +// BucketLocation returns the S3 hostname to be used with the given bucket. +func (c *Client) BucketLocation(bucket string) (location string, err error) { + if !strings.HasSuffix(c.hostname(), "amazonaws.com") { + return "", errors.New("BucketLocation not implemented for non-Amazon S3 hostnames") + } + url_ := fmt.Sprintf("https://s3.amazonaws.com/%s/?location", url.QueryEscape(bucket)) + req := newReq(url_) + c.Auth.SignRequest(req) + res, err := c.transport().RoundTrip(req) + if err != nil { + return + } + var xres xmlLocationConstraint + if err := xml.NewDecoder(res.Body).Decode(&xres); err != nil { + return "", err + } + if xres.Location == "" { + return "s3.amazonaws.com", nil + } + return "s3-" + xres.Location + ".amazonaws.com", nil +} + +// ListBucket returns 0 to maxKeys (inclusive) items from the provided +// bucket. Keys before startAt will be skipped. (This is the S3 +// 'marker' value). If the length of the returned items is equal to +// maxKeys, there is no indication whether or not the returned list is +// truncated. +func (c *Client) ListBucket(bucket string, startAt string, maxKeys int) (items []*Item, err error) { + if maxKeys < 0 { + return nil, errors.New("invalid negative maxKeys") + } + marker := startAt + for len(items) < maxKeys { + fetchN := maxKeys - len(items) + if fetchN > maxList { + fetchN = maxList + } + var bres listBucketResults + + url_ := fmt.Sprintf("%s?marker=%s&max-keys=%d", + c.bucketURL(bucket), url.QueryEscape(marker), fetchN) + + // Try the enumerate three times, since Amazon likes to close + // https connections a lot, and Go sucks at dealing with it: + // https://code.google.com/p/go/issues/detail?id=3514 + const maxTries = 5 + for try := 1; try <= maxTries; try++ { + time.Sleep(time.Duration(try-1) * 100 * time.Millisecond) + req := newReq(url_) + c.Auth.SignRequest(req) + res, err := c.transport().RoundTrip(req) + if err != nil { + if try < maxTries { + continue + } + return nil, err + } + if res.StatusCode != http.StatusOK { + if res.StatusCode < 500 { + body, _ := ioutil.ReadAll(io.LimitReader(res.Body, 1<<20)) + aerr := &Error{ + Op: "ListBucket", + Code: res.StatusCode, + Body: body, + Header: res.Header, + } + aerr.parseXML() + res.Body.Close() + return nil, aerr + } + } else { + bres = listBucketResults{} + var logbuf bytes.Buffer + err = xml.NewDecoder(io.TeeReader(res.Body, &logbuf)).Decode(&bres) + if err != nil { + log.Printf("Error parsing s3 XML response: %v for %q", err, logbuf.Bytes()) + } else if bres.MaxKeys != fetchN || bres.Name != bucket || bres.Marker != marker { + err = fmt.Errorf("Unexpected parse from server: %#v from: %s", bres, logbuf.Bytes()) + log.Print(err) + } + } + res.Body.Close() + if err != nil { + if try < maxTries-1 { + continue + } + log.Print(err) + return nil, err + } + break + } + for _, it := range bres.Contents { + if it.Key == marker && it.Key != startAt { + // Skip first dup on pages 2 and higher. + continue + } + if it.Key < startAt { + return nil, fmt.Errorf("Unexpected response from Amazon: item key %q but wanted greater than %q", it.Key, startAt) + } + items = append(items, it) + marker = it.Key + } + if !bres.IsTruncated { + // log.Printf("Not truncated. so breaking. items = %d; len Contents = %d, url = %s", len(items), len(bres.Contents), url_) + break + } + } + return items, nil +} + +func (c *Client) Get(bucket, key string) (body io.ReadCloser, size int64, err error) { + req := newReq(c.keyURL(bucket, key)) + c.Auth.SignRequest(req) + res, err := c.transport().RoundTrip(req) + if err != nil { + return + } + switch res.StatusCode { + case http.StatusOK: + return res.Body, res.ContentLength, nil + case http.StatusNotFound: + res.Body.Close() + return nil, 0, os.ErrNotExist + default: + res.Body.Close() + return nil, 0, fmt.Errorf("Amazon HTTP error on GET: %d", res.StatusCode) + } +} + +// GetPartial fetches part of the s3 key object in bucket. +// If length is negative, the rest of the object is returned. +// The caller must close rc. +func (c *Client) GetPartial(bucket, key string, offset, length int64) (rc io.ReadCloser, err error) { + if offset < 0 { + return nil, errors.New("invalid negative length") + } + + req := newReq(c.keyURL(bucket, key)) + if length >= 0 { + req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) + } else { + req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) + } + c.Auth.SignRequest(req) + + res, err := c.transport().RoundTrip(req) + if err != nil { + return + } + switch res.StatusCode { + case http.StatusOK, http.StatusPartialContent: + return res.Body, nil + case http.StatusNotFound: + res.Body.Close() + return nil, os.ErrNotExist + default: + res.Body.Close() + return nil, fmt.Errorf("Amazon HTTP error on GET: %d", res.StatusCode) + } +} + +func (c *Client) Delete(bucket, key string) error { + req := newReq(c.keyURL(bucket, key)) + req.Method = "DELETE" + c.Auth.SignRequest(req) + res, err := c.transport().RoundTrip(req) + if err != nil { + return err + } + if res != nil && res.Body != nil { + defer res.Body.Close() + } + if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusNoContent || + res.StatusCode == http.StatusOK { + return nil + } + return fmt.Errorf("Amazon HTTP error on DELETE: %d", res.StatusCode) +} + +// IsValid reports whether bucket is a valid bucket name, per Amazon's naming restrictions. +// +// See http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html +func IsValidBucket(bucket string) bool { + l := len(bucket) + if l < 3 || l > 63 { + return false + } + + valid := false + prev := byte('.') + for i := 0; i < len(bucket); i++ { + c := bucket[i] + switch { + default: + return false + case 'a' <= c && c <= 'z': + valid = true + case '0' <= c && c <= '9': + // Is allowed, but bucketname can't be just numbers. + // Therefore, don't set valid to true + case c == '-': + if prev == '.' { + return false + } + case c == '.': + if prev == '.' || prev == '-' { + return false + } + } + prev = c + } + + if prev == '-' || prev == '.' { + return false + } + return valid +} + +// Error is the type returned by some API operations. +// +// TODO: it should be more/all of them. +type Error struct { + Op string + Code int // HTTP status code + Body []byte // response body + Header http.Header // response headers + + // UsedEndpoint and AmazonCode are the XML response's Endpoint and + // Code fields, respectively. + UseEndpoint string // if a temporary redirect (wrong hostname) + AmazonCode string +} + +func (e *Error) Error() string { + if bytes.Contains(e.Body, []byte("")) { + return fmt.Sprintf("s3.%s: status %d: %s", e.Op, e.Code, e.Body) + } + return fmt.Sprintf("s3.%s: status %d", e.Op, e.Code) +} + +func (e *Error) parseXML() { + var xe xmlError + _ = xml.NewDecoder(bytes.NewReader(e.Body)).Decode(&xe) + e.AmazonCode = xe.Code + if xe.Code == "TemporaryRedirect" { + e.UseEndpoint = xe.Endpoint + } + if xe.Code == "SignatureDoesNotMatch" { + want, _ := hex.DecodeString(strings.Replace(xe.StringToSignBytes, " ", "", -1)) + log.Printf("S3 SignatureDoesNotMatch. StringToSign should be %d bytes: %q (%x)", len(want), want, want) + } + +} + +// xmlError is the Error response from Amazon. +type xmlError struct { + XMLName xml.Name `xml:"Error"` + Code string + Message string + RequestId string + Bucket string + Endpoint string + StringToSignBytes string +} + +// xmlLocationConstraint is the LocationConstraint returned from BucketLocation. +type xmlLocationConstraint struct { + XMLName xml.Name `xml:"LocationConstraint"` + Location string `xml:",chardata"` +} diff --git a/pkg/s3/client_test.go b/pkg/s3/client_test.go new file mode 100644 index 00000000..557b9452 --- /dev/null +++ b/pkg/s3/client_test.go @@ -0,0 +1,105 @@ +/* +Copyright 2011 Google Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package s3 + +import ( + "net/http" + "os" + "reflect" + "strings" + "testing" +) + +var tc *Client + +func getTestClient(t *testing.T) bool { + accessKey := os.Getenv("AWS_ACCESS_KEY_ID") + secret := os.Getenv("AWS_ACCESS_KEY_SECRET") + if accessKey == "" || secret == "" { + t.Logf("Skipping test; no AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY_SECRET set in environment") + return false + } + tc = &Client{&Auth{AccessKey: accessKey, SecretAccessKey: secret}, http.DefaultTransport} + return true +} + +func dumpBuckets(t *testing.T, v []*Bucket) { + for i, b := range v { + t.Logf("Bucket #%d: %#v", i, b) + } +} + +func TestBuckets(t *testing.T) { + if !getTestClient(t) { + return + } + buckets, err := tc.Buckets() + if err != nil { + t.Fatal(err) + } + dumpBuckets(t, buckets) +} + +func TestParseBuckets(t *testing.T) { + res := "\nownerIDFieldbobDisplayNamebucketOne2006-06-21T07:04:31.000ZbucketTwo2006-06-21T07:04:32.000Z" + buckets, err := parseListAllMyBuckets(strings.NewReader(res)) + if err != nil { + t.Fatal(err) + } + if g, w := len(buckets), 2; g != w { + t.Errorf("num parsed buckets = %d; want %d", g, w) + } + want := []*Bucket{ + {Name: "bucketOne", CreationDate: "2006-06-21T07:04:31.000Z"}, + {Name: "bucketTwo", CreationDate: "2006-06-21T07:04:32.000Z"}, + } + dump := func(v []*Bucket) { + for i, b := range v { + t.Logf("Bucket #%d: %#v", i, b) + } + } + if !reflect.DeepEqual(buckets, want) { + t.Error("mismatch; GOT:") + dump(buckets) + t.Error("WANT:") + dump(want) + } +} + +func TestValidBucketNames(t *testing.T) { + m := []struct { + in string + want bool + }{ + {"myawsbucket", true}, + {"my.aws.bucket", true}, + {"my-aws-bucket.1", true}, + {"my---bucket.1", true}, + {".myawsbucket", false}, + {"-myawsbucket", false}, + {"myawsbucket.", false}, + {"myawsbucket-", false}, + {"my..awsbucket", false}, + } + + for _, bt := range m { + got := IsValidBucket(bt.in) + if got != bt.want { + t.Errorf("func(%q) = %v; want %v", bt.in, got, bt.want) + } + } +}