storage_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package storage
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "log"
  21. "net"
  22. "net/http"
  23. "net/http/httptest"
  24. "strings"
  25. "testing"
  26. "time"
  27. "golang.org/x/net/context"
  28. "google.golang.org/cloud"
  29. )
  30. func TestSignedURL(t *testing.T) {
  31. expires, _ := time.Parse(time.RFC3339, "2002-10-02T10:00:00-05:00")
  32. url, err := SignedURL("bucket-name", "object-name", &SignedURLOptions{
  33. GoogleAccessID: "xxx@clientid",
  34. PrivateKey: dummyKey("rsa"),
  35. Method: "GET",
  36. MD5: []byte("202cb962ac59075b964b07152d234b70"),
  37. Expires: expires,
  38. ContentType: "application/json",
  39. Headers: []string{"x-header1", "x-header2"},
  40. })
  41. if err != nil {
  42. t.Error(err)
  43. }
  44. want := "https://storage.googleapis.com/bucket-name/object-name?" +
  45. "Expires=1033570800&GoogleAccessId=xxx%40clientid&Signature=" +
  46. "ITqNWQHr7ayIj%2B0Ds5%2FzUT2cWMQQouuFmu6L11Zd3kfNKvm3sjyGIzO" +
  47. "gZsSUoter1SxP7BcrCzgqIZ9fQmgQnuIpqqLL4kcGmTbKsQS6hTknpJM%2F" +
  48. "2lS4NY6UH1VXBgm2Tce28kz8rnmqG6svcGvtWuOgJsETeSIl1R9nAEIDCEq" +
  49. "ZJzoOiru%2BODkHHkpoFjHWAwHugFHX%2B9EX4SxaytiN3oEy48HpYGWV0I" +
  50. "h8NvU1hmeWzcLr41GnTADeCn7Eg%2Fb5H2GCNO70Cz%2Bw2fn%2BofLCUeR" +
  51. "YQd%2FhES8oocv5kpHZkstc8s8uz3aKMsMauzZ9MOmGy%2F6VULBgIVvi6a" +
  52. "AwEBIYOw%3D%3D"
  53. if url != want {
  54. t.Fatalf("Unexpected signed URL; found %v", url)
  55. }
  56. }
  57. func TestSignedURL_PEMPrivateKey(t *testing.T) {
  58. expires, _ := time.Parse(time.RFC3339, "2002-10-02T10:00:00-05:00")
  59. url, err := SignedURL("bucket-name", "object-name", &SignedURLOptions{
  60. GoogleAccessID: "xxx@clientid",
  61. PrivateKey: dummyKey("pem"),
  62. Method: "GET",
  63. MD5: []byte("202cb962ac59075b964b07152d234b70"),
  64. Expires: expires,
  65. ContentType: "application/json",
  66. Headers: []string{"x-header1", "x-header2"},
  67. })
  68. if err != nil {
  69. t.Error(err)
  70. }
  71. want := "https://storage.googleapis.com/bucket-name/object-name?" +
  72. "Expires=1033570800&GoogleAccessId=xxx%40clientid&Signature=" +
  73. "B7XkS4dfmVDoe%2FoDeXZkWlYmg8u2kI0SizTrzL5%2B9RmKnb5j7Kf34DZ" +
  74. "JL8Hcjr1MdPFLNg2QV4lEH86Gqgqt%2Fv3jFOTRl4wlzcRU%2FvV5c5HU8M" +
  75. "qW0FZ0IDbqod2RdsMONLEO6yQWV2HWFrMLKl2yMFlWCJ47et%2BFaHe6v4Z" +
  76. "EBc0%3D"
  77. if url != want {
  78. t.Fatalf("Unexpected signed URL; found %v", url)
  79. }
  80. }
  81. func TestSignedURL_URLUnsafeObjectName(t *testing.T) {
  82. expires, _ := time.Parse(time.RFC3339, "2002-10-02T10:00:00-05:00")
  83. url, err := SignedURL("bucket-name", "object name界", &SignedURLOptions{
  84. GoogleAccessID: "xxx@clientid",
  85. PrivateKey: dummyKey("pem"),
  86. Method: "GET",
  87. MD5: []byte("202cb962ac59075b964b07152d234b70"),
  88. Expires: expires,
  89. ContentType: "application/json",
  90. Headers: []string{"x-header1", "x-header2"},
  91. })
  92. if err != nil {
  93. t.Error(err)
  94. }
  95. want := "https://storage.googleapis.com/bucket-name/object%20nam" +
  96. "e%E7%95%8C?Expires=1033570800&GoogleAccessId=xxx%40clientid" +
  97. "&Signature=bxORkrAm73INEMHktrE7VoUZQzVPvL5NFZ7noAI5zK%2BGSm" +
  98. "%2BWFvsK%2FVnRGtYK9BK89jz%2BX4ZQd87nkMEJw1OsqmGNiepyzB%2B3o" +
  99. "sUYrHyV7UnKs9bkQpBkqPFlfgK1o7oX4NJjA1oKjuHP%2Fj5%2FC15OPa3c" +
  100. "vHV619BEb7vf30nAwQM%3D"
  101. if url != want {
  102. t.Fatalf("Unexpected signed URL; found %v", url)
  103. }
  104. }
  105. func TestSignedURL_MissingOptions(t *testing.T) {
  106. pk := dummyKey("rsa")
  107. var tests = []struct {
  108. opts *SignedURLOptions
  109. errMsg string
  110. }{
  111. {
  112. &SignedURLOptions{},
  113. "missing required credentials",
  114. },
  115. {
  116. &SignedURLOptions{GoogleAccessID: "access_id"},
  117. "missing required credentials",
  118. },
  119. {
  120. &SignedURLOptions{
  121. GoogleAccessID: "access_id",
  122. PrivateKey: pk,
  123. },
  124. "missing required method",
  125. },
  126. {
  127. &SignedURLOptions{
  128. GoogleAccessID: "access_id",
  129. PrivateKey: pk,
  130. Method: "PUT",
  131. },
  132. "missing required expires",
  133. },
  134. }
  135. for _, test := range tests {
  136. _, err := SignedURL("bucket", "name", test.opts)
  137. if !strings.Contains(err.Error(), test.errMsg) {
  138. t.Errorf("expected err: %v, found: %v", test.errMsg, err)
  139. }
  140. }
  141. }
  142. func dummyKey(kind string) []byte {
  143. slurp, err := ioutil.ReadFile(fmt.Sprintf("./testdata/dummy_%s", kind))
  144. if err != nil {
  145. log.Fatal(err)
  146. }
  147. return slurp
  148. }
  149. func TestCopyToMissingFields(t *testing.T) {
  150. var tests = []struct {
  151. srcBucket, srcName, destBucket, destName string
  152. errMsg string
  153. }{
  154. {
  155. "mybucket", "", "mybucket", "destname",
  156. "the source and destination object names must both be non-empty",
  157. },
  158. {
  159. "mybucket", "srcname", "mybucket", "",
  160. "the source and destination object names must both be non-empty",
  161. },
  162. {
  163. "", "srcfile", "mybucket", "destname",
  164. "the source and destination bucket names must both be non-empty",
  165. },
  166. {
  167. "mybucket", "srcfile", "", "destname",
  168. "the source and destination bucket names must both be non-empty",
  169. },
  170. }
  171. ctx := context.Background()
  172. client, err := NewClient(ctx, cloud.WithBaseHTTP(&http.Client{Transport: &fakeTransport{}}))
  173. if err != nil {
  174. panic(err)
  175. }
  176. for i, test := range tests {
  177. src := client.Bucket(test.srcBucket).Object(test.srcName)
  178. dst := client.Bucket(test.destBucket).Object(test.destName)
  179. _, err := src.CopyTo(ctx, dst, nil)
  180. if !strings.Contains(err.Error(), test.errMsg) {
  181. t.Errorf("CopyTo test #%v:\ngot err %q\nwant err %q", i, err, test.errMsg)
  182. }
  183. }
  184. }
  185. func TestObjectNames(t *testing.T) {
  186. // Naming requirements: https://cloud.google.com/storage/docs/bucket-naming
  187. const maxLegalLength = 1024
  188. type testT struct {
  189. name, want string
  190. }
  191. tests := []testT{
  192. // Embedded characters important in URLs.
  193. {"foo % bar", "foo%20%25%20bar"},
  194. {"foo ? bar", "foo%20%3F%20bar"},
  195. {"foo / bar", "foo%20/%20bar"},
  196. {"foo %?/ bar", "foo%20%25%3F/%20bar"},
  197. // Non-Roman scripts
  198. {"타코", "%ED%83%80%EC%BD%94"},
  199. {"世界", "%E4%B8%96%E7%95%8C"},
  200. // Longest legal name
  201. {strings.Repeat("a", maxLegalLength), strings.Repeat("a", maxLegalLength)},
  202. // Line terminators besides CR and LF: https://en.wikipedia.org/wiki/Newline#Unicode
  203. {"foo \u000b bar", "foo%20%0B%20bar"},
  204. {"foo \u000c bar", "foo%20%0C%20bar"},
  205. {"foo \u0085 bar", "foo%20%C2%85%20bar"},
  206. {"foo \u2028 bar", "foo%20%E2%80%A8%20bar"},
  207. {"foo \u2029 bar", "foo%20%E2%80%A9%20bar"},
  208. // Null byte.
  209. {"foo \u0000 bar", "foo%20%00%20bar"},
  210. // Non-control characters that are discouraged, but not forbidden, according to the documentation.
  211. {"foo # bar", "foo%20%23%20bar"},
  212. {"foo []*? bar", "foo%20%5B%5D%2A%3F%20bar"},
  213. // Angstrom symbol singleton and normalized forms: http://unicode.org/reports/tr15/
  214. {"foo \u212b bar", "foo%20%E2%84%AB%20bar"},
  215. {"foo \u0041\u030a bar", "foo%20A%CC%8A%20bar"},
  216. {"foo \u00c5 bar", "foo%20%C3%85%20bar"},
  217. // Hangul separating jamo: http://www.unicode.org/versions/Unicode7.0.0/ch18.pdf (Table 18-10)
  218. {"foo \u3131\u314f bar", "foo%20%E3%84%B1%E3%85%8F%20bar"},
  219. {"foo \u1100\u1161 bar", "foo%20%E1%84%80%E1%85%A1%20bar"},
  220. {"foo \uac00 bar", "foo%20%EA%B0%80%20bar"},
  221. }
  222. // C0 control characters not forbidden by the docs.
  223. var runes []rune
  224. for r := rune(0x01); r <= rune(0x1f); r++ {
  225. if r != '\u000a' && r != '\u000d' {
  226. runes = append(runes, r)
  227. }
  228. }
  229. tests = append(tests, testT{fmt.Sprintf("foo %s bar", string(runes)), "foo%20%01%02%03%04%05%06%07%08%09%0B%0C%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20bar"})
  230. // C1 control characters, plus DEL.
  231. runes = nil
  232. for r := rune(0x7f); r <= rune(0x9f); r++ {
  233. runes = append(runes, r)
  234. }
  235. tests = append(tests, testT{fmt.Sprintf("foo %s bar", string(runes)), "foo%20%7F%C2%80%C2%81%C2%82%C2%83%C2%84%C2%85%C2%86%C2%87%C2%88%C2%89%C2%8A%C2%8B%C2%8C%C2%8D%C2%8E%C2%8F%C2%90%C2%91%C2%92%C2%93%C2%94%C2%95%C2%96%C2%97%C2%98%C2%99%C2%9A%C2%9B%C2%9C%C2%9D%C2%9E%C2%9F%20bar"})
  236. opts := &SignedURLOptions{
  237. GoogleAccessID: "xxx@clientid",
  238. PrivateKey: dummyKey("rsa"),
  239. Method: "GET",
  240. MD5: []byte("202cb962ac59075b964b07152d234b70"),
  241. Expires: time.Date(2002, time.October, 2, 10, 0, 0, 0, time.UTC),
  242. ContentType: "application/json",
  243. Headers: []string{"x-header1", "x-header2"},
  244. }
  245. for _, test := range tests {
  246. g, err := SignedURL("bucket-name", test.name, opts)
  247. if err != nil {
  248. t.Errorf("SignedURL(%q) err=%v, want nil", test.name, err)
  249. }
  250. if w := "/bucket-name/" + test.want; !strings.Contains(g, w) {
  251. t.Errorf("SignedURL(%q)=%q, want substring %q", test.name, g, w)
  252. }
  253. }
  254. }
  255. func TestCondition(t *testing.T) {
  256. gotReq := make(chan *http.Request, 1)
  257. ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  258. io.Copy(ioutil.Discard, r.Body)
  259. gotReq <- r
  260. if r.Method == "POST" {
  261. w.WriteHeader(200)
  262. } else {
  263. w.WriteHeader(500)
  264. }
  265. }))
  266. defer ts.Close()
  267. tlsConf := &tls.Config{InsecureSkipVerify: true}
  268. tr := &http.Transport{
  269. TLSClientConfig: tlsConf,
  270. DialTLS: func(netw, addr string) (net.Conn, error) {
  271. return tls.Dial("tcp", ts.Listener.Addr().String(), tlsConf)
  272. },
  273. }
  274. defer tr.CloseIdleConnections()
  275. hc := &http.Client{Transport: tr}
  276. ctx := context.Background()
  277. c, err := NewClient(ctx, cloud.WithBaseHTTP(hc))
  278. if err != nil {
  279. t.Fatal(err)
  280. }
  281. obj := c.Bucket("buck").Object("obj")
  282. dst := c.Bucket("dstbuck").Object("dst")
  283. tests := []struct {
  284. fn func()
  285. want string
  286. }{
  287. {
  288. func() { obj.WithConditions(Generation(1234)).NewReader(ctx) },
  289. "GET /buck/obj?generation=1234",
  290. },
  291. {
  292. func() { obj.WithConditions(IfGenerationMatch(1234)).NewReader(ctx) },
  293. "GET /buck/obj?ifGenerationMatch=1234",
  294. },
  295. {
  296. func() { obj.WithConditions(IfGenerationNotMatch(1234)).NewReader(ctx) },
  297. "GET /buck/obj?ifGenerationNotMatch=1234",
  298. },
  299. {
  300. func() { obj.WithConditions(IfMetaGenerationMatch(1234)).NewReader(ctx) },
  301. "GET /buck/obj?ifMetagenerationMatch=1234",
  302. },
  303. {
  304. func() { obj.WithConditions(IfMetaGenerationNotMatch(1234)).NewReader(ctx) },
  305. "GET /buck/obj?ifMetagenerationNotMatch=1234",
  306. },
  307. {
  308. func() { obj.WithConditions(IfMetaGenerationNotMatch(1234)).Attrs(ctx) },
  309. "GET https://www.googleapis.com/storage/v1/b/buck/o/obj?alt=json&ifMetagenerationNotMatch=1234&projection=full",
  310. },
  311. {
  312. func() { obj.WithConditions(IfMetaGenerationMatch(1234)).Update(ctx, ObjectAttrs{}) },
  313. "PATCH https://www.googleapis.com/storage/v1/b/buck/o/obj?alt=json&ifMetagenerationMatch=1234&projection=full",
  314. },
  315. {
  316. func() { obj.WithConditions(Generation(1234)).Delete(ctx) },
  317. "DELETE https://www.googleapis.com/storage/v1/b/buck/o/obj?alt=json&generation=1234",
  318. },
  319. {
  320. func() {
  321. w := obj.WithConditions(IfGenerationMatch(1234)).NewWriter(ctx)
  322. w.ContentType = "text/plain"
  323. w.Close()
  324. },
  325. "POST https://www.googleapis.com/upload/storage/v1/b/buck/o?alt=json&ifGenerationMatch=1234&projection=full&uploadType=multipart",
  326. },
  327. {
  328. func() {
  329. obj.WithConditions(IfGenerationMatch(1234)).CopyTo(ctx, dst.WithConditions(IfMetaGenerationMatch(5678)), nil)
  330. },
  331. "POST https://www.googleapis.com/storage/v1/b/buck/o/obj/copyTo/b/dstbuck/o/dst?alt=json&ifMetagenerationMatch=5678&ifSourceGenerationMatch=1234&projection=full",
  332. },
  333. }
  334. for i, tt := range tests {
  335. tt.fn()
  336. select {
  337. case r := <-gotReq:
  338. got := r.Method + " " + r.RequestURI
  339. if got != tt.want {
  340. t.Errorf("%d. RequestURI = %q; want %q", i, got, tt.want)
  341. }
  342. case <-time.After(5 * time.Second):
  343. t.Fatalf("%d. timeout", i)
  344. }
  345. if err != nil {
  346. t.Fatal(err)
  347. }
  348. }
  349. // Test an error, too:
  350. err = obj.WithConditions(Generation(1234)).NewWriter(ctx).Close()
  351. if err == nil || !strings.Contains(err.Error(), "NewWriter: condition Generation not supported") {
  352. t.Errorf("want error about unsupported condition; got %v", err)
  353. }
  354. }