-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathattachment_test.go
2719 lines (2219 loc) · 104 KB
/
attachment_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package rest
import (
"encoding/base64"
"fmt"
"io"
"log"
"mime"
"mime/multipart"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/couchbase/go-blip"
"github.com/couchbase/sync_gateway/base"
"github.com/couchbase/sync_gateway/db"
"github.com/couchbaselabs/rosmar"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
//from api_test.go
// Validate that Etag header value is surrounded with double quotes, see issue #808
func TestDocEtag(t *testing.T) {
base.SetUpTestLogging(t, base.LevelDebug, base.KeyAll)
rt := NewRestTester(t, &RestTesterConfig{GuestEnabled: true})
defer rt.Close()
response := rt.SendRequest("PUT", "/{{.keyspace}}/doc", `{"prop":true}`)
RequireStatus(t, response, 201)
version := DocVersionFromPutResponse(t, response)
// Validate Etag returned on doc creation
assert.Equal(t, strconv.Quote(version.RevID), response.Header().Get("Etag"))
response = rt.SendRequest("GET", "/{{.keyspace}}/doc", "")
RequireStatus(t, response, 200)
// Validate Etag returned when retrieving doc
assert.Equal(t, strconv.Quote(version.RevID), response.Header().Get("Etag"))
// Validate Etag returned when updating doc
response = rt.SendRequest("PUT", "/{{.keyspace}}/doc?rev="+version.RevID, `{"prop":false}`)
version = DocVersionFromPutResponse(t, response)
assert.Equal(t, strconv.Quote(version.RevID), response.Header().Get("Etag"))
// Test Attachments
attachmentBody := "this is the body of attachment"
attachmentContentType := "content/type"
// attach to existing document with correct rev (should succeed), manual request to change etag
resource := fmt.Sprintf("/{{.keyspace}}/%s/%s?rev=%s", "doc", "attach1", version.RevID)
response = rt.SendAdminRequestWithHeaders(http.MethodPut, resource, attachmentBody, attachmentHeaders())
RequireStatus(t, response, http.StatusCreated)
var body db.Body
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
require.True(t, body["ok"].(bool))
afterAttachmentVersion := DocVersionFromPutResponse(rt.TB(), response)
RequireDocVersionNotEqual(t, version, afterAttachmentVersion)
// validate Etag returned from adding an attachment
assert.Equal(t, strconv.Quote(afterAttachmentVersion.RevID), response.Header().Get("Etag"))
// retrieve attachment
response = rt.SendRequest("GET", "/{{.keyspace}}/doc/attach1", "")
RequireStatus(t, response, 200)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.Equal(t, "", response.Header().Get("Content-Disposition"))
assert.Equal(t, attachmentContentType, response.Header().Get("Content-Type"))
// Validate Etag returned from retrieving an attachment
assert.Equal(t, "\"sha1-nq0xWBV2IEkkpY3ng+PEtFnCcVY=\"", response.Header().Get("Etag"))
}
// Add and retrieve an attachment, including a subrange
func TestDocAttachment(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{GuestEnabled: true})
defer rt.Close()
version := rt.PutDoc("doc", `{"prop":true}`)
attachmentBody := "this is the body of attachment"
attachmentContentType := "content/type"
version = rt.storeAttachment("doc", version, "attach1", attachmentBody)
// retrieve attachment
response := rt.SendRequest("GET", "/{{.keyspace}}/doc/attach1", "")
RequireStatus(t, response, 200)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.Equal(t, "bytes", response.Header().Get("Accept-Ranges"))
assert.Equal(t, "", response.Header().Get("Content-Disposition"))
assert.Equal(t, "30", response.Header().Get("Content-Length"))
assert.Equal(t, attachmentContentType, response.Header().Get("Content-Type"))
// retrieve subrange
response = rt.SendRequestWithHeaders("GET", "/{{.keyspace}}/doc/attach1", "", map[string]string{"Range": "bytes=5-6"})
RequireStatus(t, response, 206)
assert.Equal(t, "is", string(response.Body.Bytes()))
assert.Equal(t, "bytes", response.Header().Get("Accept-Ranges"))
assert.Equal(t, "2", response.Header().Get("Content-Length"))
assert.Equal(t, "bytes 5-6/30", response.Header().Get("Content-Range"))
assert.Equal(t, attachmentContentType, response.Header().Get("Content-Type"))
// attempt to delete an attachment that is not on the document
response = rt.SendRequest("DELETE", "/{{.keyspace}}/doc/attach2?rev="+version.RevID, "")
RequireStatus(t, response, 404)
// attempt to delete attachment from non existing doc
response = rt.SendRequest("DELETE", "/{{.keyspace}}/doc1/attach1?rev=1-xzy", "")
RequireStatus(t, response, 404)
// attempt to delete attachment using incorrect revid
response = rt.SendRequest("DELETE", "/{{.keyspace}}/doc/attach1?rev=1-xzy", "")
RequireStatus(t, response, 409)
// delete the attachment calling the delete attachment endpoint
response = rt.SendRequest("DELETE", "/{{.keyspace}}/doc/attach1?rev="+version.RevID, "")
RequireStatus(t, response, 200)
// attempt to access deleted attachment (should return error)
response = rt.SendRequest("GET", "/{{.keyspace}}/doc/attach1", "")
RequireStatus(t, response, 404)
}
func TestDocAttachmentMetaOption(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{GuestEnabled: true})
defer rt.Close()
version := rt.PutDoc("doc", `{"prop":true}`)
attachmentBody := "this is the body of attachment"
attachmentContentType := "content/type"
// Validate attachment response.
assertAttachmentResponse := func(response *TestResponse) {
RequireStatus(t, response, http.StatusOK)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.Equal(t, "bytes", response.Header().Get("Accept-Ranges"))
assert.Empty(t, response.Header().Get("Content-Disposition"))
assert.Equal(t, "30", response.Header().Get("Content-Length"))
assert.Equal(t, attachmentContentType, response.Header().Get("Content-Type"))
}
// Attach to existing document.
_ = rt.storeAttachment("doc", version, "attach1", attachmentBody)
// Retrieve attachment
response := rt.SendRequest(http.MethodGet, "/{{.keyspace}}/doc/attach1", "")
assertAttachmentResponse(response)
// Retrieve attachment meta only by explicitly enabling meta option.
response = rt.SendRequest(http.MethodGet, "/{{.keyspace}}/doc/attach1?meta=true", "")
RequireStatus(t, response, http.StatusOK)
responseBody := make(map[string]interface{})
err := base.JSONUnmarshal(response.Body.Bytes(), &responseBody)
require.NoError(t, err)
contentType, contentTypeOK := responseBody["content_type"].(string)
require.True(t, contentTypeOK)
assert.Equal(t, attachmentContentType, contentType)
digest, digestOK := responseBody["digest"].(string)
require.True(t, digestOK)
assert.Equal(t, "sha1-nq0xWBV2IEkkpY3ng+PEtFnCcVY=", digest)
key, keyOK := responseBody["key"].(string)
require.True(t, keyOK)
assert.Equal(t, "_sync:att2:E51US4IbE+vqFPGw/hhXciLkFcKWbjo1EcQZYFUjIgI=:sha1-nq0xWBV2IEkkpY3ng+PEtFnCcVY=", key)
length, lengthOK := responseBody["length"].(float64)
require.True(t, lengthOK)
assert.Equal(t, float64(30), length)
revpos, revposOK := responseBody["revpos"].(float64)
require.True(t, revposOK)
assert.Equal(t, float64(2), revpos)
ver, versionOK := responseBody["ver"].(float64)
require.True(t, versionOK)
assert.Equal(t, float64(2), ver)
stub, stubOK := responseBody["stub"].(bool)
require.True(t, stubOK)
require.True(t, stub)
// Retrieve attachment by explicitly disabling meta option.
response = rt.SendRequest(http.MethodGet, "/{{.keyspace}}/doc/attach1?meta=false", "")
assertAttachmentResponse(response)
}
// Add an attachment to a document that has been removed from the users channels
func TestDocAttachmentOnRemovedRev(t *testing.T) {
rt := NewRestTester(t, nil)
defer rt.Close()
rt.CreateUser("user1", []string{"foo"})
version := rt.PutDoc("doc", `{"prop":true, "channels":["foo"]}`)
// Put new revision removing document from users channel set
version = rt.UpdateDoc("doc", version, `{"prop":true}`)
attachmentBody := "this is the body of attachment"
attachmentContentType := "content/type"
reqHeaders := map[string]string{
"Content-Type": attachmentContentType,
}
// attach to existing document with correct rev (should fail)
response := rt.SendUserRequestWithHeaders("PUT", "/{{.keyspace}}/doc/attach1?rev="+version.RevID, attachmentBody, reqHeaders, "user1", "letmein")
RequireStatus(t, response, 404)
}
func TestFunkyDocAndAttachmentIDs(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{GuestEnabled: true})
defer rt.Close()
attachmentBody := "this is the body of attachment"
attachmentContentType := "content/type"
// assertResponse asserts that the specified attachment exists in the response body.
assertResponse := func(response *TestResponse, attachmentBody string) {
RequireStatus(t, response, http.StatusOK)
require.Equal(t, attachmentBody, string(response.Body.Bytes()))
require.Empty(t, response.Header().Get("Content-Disposition"))
require.Equal(t, attachmentContentType, response.Header().Get("Content-Type"))
}
testCases := []struct {
name string
docID string
}{
{
name: "simple",
docID: "doc1",
},
{
name: "single embedded '/'",
docID: "AC%2FDC",
},
{
name: "embedded '+'",
docID: "AC%2BDC%2BGC2",
},
}
for _, testCase := range testCases {
rt.Run(testCase.name, func(t *testing.T) {
version := rt.CreateTestDoc(testCase.docID)
// Add attachment with single embedded '/' (%2F HEX)
version = rt.storeAttachment(testCase.docID, version, "attachpath%2Fattachment.txt", attachmentBody)
// Retrieve attachment
response := rt.SendRequest(http.MethodGet, "/{{.keyspace}}/doc1/attachpath%2Fattachment.txt", "")
assertResponse(response, attachmentBody)
// Add attachment with two embedded '/' (%2F HEX)
_ = rt.storeAttachment(testCase.docID, version, "attachpath%2Fattachpath2%2Fattachment.txt", attachmentBody)
// Retrieve attachment
response = rt.SendRequest(http.MethodGet, "/{{.keyspace}}/doc1/attachpath%2Fattachpath2%2Fattachment.txt", "")
assertResponse(response, attachmentBody)
})
}
}
func TestManualAttachment(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{GuestEnabled: true})
defer rt.Close()
doc1Version := rt.CreateTestDoc("doc1")
// attach to existing document without rev (should fail)
attachmentBody := "this is the body of attachment"
attachmentContentType := "content/type"
reqHeaders := map[string]string{
"Content-Type": attachmentContentType,
}
response := rt.SendRequestWithHeaders("PUT", "/{{.keyspace}}/doc1/attach1", attachmentBody, reqHeaders)
RequireStatus(t, response, 409)
// attach to existing document with wrong rev (should fail)
response = rt.SendRequestWithHeaders("PUT", "/{{.keyspace}}/doc1/attach1?rev=1-xyz", attachmentBody, reqHeaders)
RequireStatus(t, response, 409)
// attach to existing document with wrong rev using If-Match header (should fail)
reqHeaders["If-Match"] = `"` + "1-dnf" + `"`
response = rt.SendRequestWithHeaders("PUT", "/{{.keyspace}}/doc1/attach1", attachmentBody, reqHeaders)
RequireStatus(t, response, 409)
delete(reqHeaders, "If-Match")
// attach to existing document with correct rev (should succeed)
afterAttachmentVersion := rt.storeAttachment("doc1", doc1Version, "attach1", attachmentBody)
RequireDocVersionNotEqual(t, doc1Version, afterAttachmentVersion)
// retrieve attachment
response = rt.SendRequest("GET", "/{{.keyspace}}/doc1/attach1", "")
RequireStatus(t, response, 200)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.True(t, response.Header().Get("Content-Disposition") == "")
assert.True(t, response.Header().Get("Content-Type") == attachmentContentType)
// retrieve attachment as admin should have
// Content-disposition: attachment
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1/attach1", "")
RequireStatus(t, response, 200)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.True(t, response.Header().Get("Content-Disposition") == `attachment`)
assert.True(t, response.Header().Get("Content-Type") == attachmentContentType)
// try to overwrite that attachment
attachmentBody = "updated content"
afterUpdateAttachmentVersion := rt.storeAttachment("doc1", afterAttachmentVersion, "attach1", attachmentBody)
RequireDocVersionNotEqual(t, afterAttachmentVersion, afterUpdateAttachmentVersion)
// try to overwrite that attachment again, this time using If-Match header
attachmentBody = "updated content again"
updateAttachmentAgainVersion := rt.storeAttachmentWithIfMatch("doc1", afterUpdateAttachmentVersion, "attach1", attachmentBody)
RequireDocVersionNotEqual(t, afterUpdateAttachmentVersion, updateAttachmentAgainVersion)
// retrieve attachment
response = rt.SendRequest("GET", "/{{.keyspace}}/doc1/attach1", "")
RequireStatus(t, response, 200)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.True(t, response.Header().Get("Content-Type") == attachmentContentType)
// add another attachment to the document
// also no explicit Content-Type header on this one
// should default to application/octet-stream
attachmentBody = "separate content"
afterSecondAttachmentVersion := rt.storeAttachmentWithHeaders("doc1", updateAttachmentAgainVersion, "attach2", attachmentBody, nil)
RequireDocVersionNotEqual(t, afterUpdateAttachmentVersion, afterSecondAttachmentVersion)
// retrieve attachment
response = rt.SendRequest("GET", "/{{.keyspace}}/doc1/attach2", "")
RequireStatus(t, response, 200)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.True(t, response.Header().Get("Content-Type") == "application/octet-stream")
// now check the attachments index on the document
response = rt.SendRequest("GET", "/{{.keyspace}}/doc1", "")
RequireStatus(t, response, 200)
body := db.Body{}
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
bodyAttachments, ok := body["_attachments"].(map[string]interface{})
if !ok {
t.Errorf("Attachments must be map")
} else {
assert.Len(t, bodyAttachments, 2)
}
// make sure original document property has remained
prop, ok := body["prop"]
if !ok || !prop.(bool) {
t.Errorf("property prop is now missing or modified")
}
}
// PUT attachment on non-existent docid should create empty doc
func TestManualAttachmentNewDoc(t *testing.T) {
rt := NewRestTester(t, nil)
defer rt.Close()
// attach to new document using bogus rev (should fail)
attachmentBody := "this is the body of attachment"
attachmentContentType := "text/plain"
reqHeaders := map[string]string{
"Content-Type": attachmentContentType,
}
response := rt.SendAdminRequestWithHeaders("PUT", "/{{.keyspace}}/notexistyet/attach1?rev=1-abc", attachmentBody, reqHeaders)
RequireStatus(t, response, 409)
// attach to new document using bogus rev using If-Match header (should fail)
reqHeaders["If-Match"] = `"1-xyz"`
response = rt.SendAdminRequestWithHeaders("PUT", "/{{.keyspace}}/notexistyet/attach1", attachmentBody, reqHeaders)
RequireStatus(t, response, 409)
delete(reqHeaders, "If-Match")
// attach to new document without any rev (should succeed)
response = rt.SendAdminRequestWithHeaders("PUT", "/{{.keyspace}}/notexistyet/attach1", attachmentBody, reqHeaders)
RequireStatus(t, response, 201)
var body db.Body
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
assert.Equal(t, true, body["ok"])
RequireDocVersionNotNil(t, DocVersionFromPutResponse(t, response))
// retrieve attachment
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/notexistyet/attach1", "")
RequireStatus(t, response, 200)
assert.Equal(t, attachmentBody, string(response.Body.Bytes()))
assert.True(t, response.Header().Get("Content-Type") == attachmentContentType)
// now check the document
body = db.Body{}
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/notexistyet", "")
RequireStatus(t, response, 200)
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
// body should only have 3 top-level entries _id, _rev, _attachments
assert.True(t, len(body) == 3)
}
// Test for regression of issue #447
func TestAttachmentsNoCrossTalk(t *testing.T) {
rt := NewRestTester(t, nil)
defer rt.Close()
doc1Version := rt.CreateTestDoc("doc1")
attachmentBody := "this is the body of attachment"
// attach to existing document with correct rev (should succeed)
afterAttachmentVersion := rt.storeAttachment("doc1", doc1Version, "attach1", attachmentBody)
reqHeaders := map[string]string{
"Accept": "application/json",
}
response := rt.SendAdminRequestWithHeaders("GET", fmt.Sprintf("/{{.keyspace}}/doc1?rev=%s&revs=true&attachments=true&atts_since=[\"%s\"]", afterAttachmentVersion.RevID, doc1Version.RevID), "", reqHeaders)
assert.Equal(t, 200, response.Code)
// validate attachment has data property
body := db.Body{}
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
log.Printf("response body revid1 = %s", body)
attachments := body["_attachments"].(map[string]interface{})
attach1 := attachments["attach1"].(map[string]interface{})
data := attach1["data"]
assert.True(t, data != nil)
response = rt.SendAdminRequestWithHeaders("GET", fmt.Sprintf("/{{.keyspace}}/doc1?rev=%s&revs=true&attachments=true&atts_since=[\"%s\"]", afterAttachmentVersion.RevID, afterAttachmentVersion.RevID), "", reqHeaders)
assert.Equal(t, 200, response.Code)
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
log.Printf("response body revid1 = %s", body)
attachments = body["_attachments"].(map[string]interface{})
attach1 = attachments["attach1"].(map[string]interface{})
data = attach1["data"]
assert.True(t, data == nil)
}
func TestAddingAttachment(t *testing.T) {
rt := NewRestTester(t, nil)
defer rt.Close()
defer func() { rosmar.MaxDocSize = 0 }()
rosmar.MaxDocSize = 20 * 1024 * 1024
testCases := []struct {
name string
docName string
byteSize int
expectedPut int
expectedGet int
}{
{
name: "Regular attachment",
docName: "doc1",
byteSize: 20,
expectedPut: http.StatusCreated,
expectedGet: http.StatusOK,
},
/* FIXME
{
name: "Too large attachment",
docName: "doc2",
byteSize: 22000000,
expectedPut: http.StatusRequestEntityTooLarge,
expectedGet: http.StatusNotFound,
},
*/
}
for _, testCase := range testCases {
rt.Run(testCase.name, func(tt *testing.T) {
version := rt.CreateTestDoc(testCase.docName)
attachmentBody := base64.StdEncoding.EncodeToString(make([]byte, testCase.byteSize))
rt.storeAttachment(testCase.docName, version, "attach1", attachmentBody)
// Get attachment back
response := rt.SendAdminRequestWithHeaders("GET", "/{{.keyspace}}/"+testCase.docName+"/attach1", "", attachmentHeaders())
RequireStatus(tt, response, testCase.expectedGet)
// If able to retrieve document check it is same as original
if response.Code == 200 {
assert.Equal(tt, response.Body.String(), attachmentBody)
}
})
}
}
// Reproduces panic seen in https://github.com/couchbase/sync_gateway/issues/2528
func TestBulkGetBadAttachmentReproIssue2528(t *testing.T) {
if base.TestUseXattrs() {
// Since we now store attachment metadata in sync data,
// this test cannot modify the xattrs to reproduce the panic
t.Skip("This test only works with XATTRS disabled")
}
rt := NewRestTester(t, nil)
defer rt.Close()
const (
doc1ID = "doc"
doc2ID = "doc2"
attachmentName = "attach1"
)
doc1Version := rt.PutDoc(doc1ID, `{"prop":true}`)
doc2Version := rt.PutDoc(doc2ID, `{"prop":true}`)
// attach to existing document with correct rev (should succeed)
attachmentBody := "this is the body of attachment"
_ = rt.storeAttachment(doc1ID, doc1Version, attachmentName, attachmentBody)
// Get the couchbase doc
couchbaseDoc := db.Body{}
_, err := rt.GetSingleDataStore().Get(doc1ID, &couchbaseDoc)
assert.NoError(t, err, "Error getting couchbaseDoc")
// Doc at this point
/*
{
"_attachments": {
"attach1": {
"content_type": "content/type",
"digest": "sha1-nq0xWBV2IEkkpY3ng+PEtFnCcVY=",
"length": 30,
"revpos": 2,
"stub": true
}
},
"prop": true
}
*/
// Modify the doc directly in the bucket to delete the digest field
s, ok := couchbaseDoc[base.SyncPropertyName].(map[string]interface{})
require.True(t, ok)
couchbaseDoc["_attachments"], ok = s["attachments"].(map[string]interface{})
require.True(t, ok)
attachments, ok := couchbaseDoc["_attachments"].(map[string]interface{})
require.True(t, ok)
attach1, ok := attachments[attachmentName].(map[string]interface{})
require.True(t, ok)
delete(attach1, "digest")
delete(attach1, "content_type")
delete(attach1, "length")
attachments[attachmentName] = attach1
log.Printf("couchbase doc after: %+v", couchbaseDoc)
// Doc at this point
/*
{
"_attachments": {
"attach1": {
"revpos": 2,
"stub": true
}
},
"prop": true
}
*/
// Put the doc back into couchbase
err = rt.GetSingleDataStore().Set(doc1ID, 0, nil, couchbaseDoc)
assert.NoError(t, err, "Error putting couchbaseDoc")
// Flush rev cache so that the _bulk_get request is forced to go back to the bucket to load the doc
// rather than loading it from the (stale) rev cache. The rev cache will be stale since the test
// short-circuits Sync Gateway and directly updates the bucket.
// Reset at the end of the test, to avoid bleed into other tests
rt.GetDatabase().FlushRevisionCacheForTest()
// Get latest rev id
version, _ := rt.GetDoc(doc1ID)
// Do a bulk_get to get the doc -- this was causing a panic prior to the fix for #2528
bulkGetDocs := fmt.Sprintf(`{"docs": [{"id": "%v", "rev": "%v"}, {"id": "%v", "rev": "%v"}]}`, doc1ID, version.RevID, doc2ID, doc2Version.RevID)
bulkGetResponse := rt.SendAdminRequest("POST", "/{{.keyspace}}/_bulk_get?revs=true&attachments=true&revs_limit=2", bulkGetDocs)
if bulkGetResponse.Code != 200 {
panic(fmt.Sprintf("Got unexpected response: %v", bulkGetResponse))
}
bulkGetResponse.DumpBody()
// Parse multipart/mixed docs and create reader
contentType, attrs, _ := mime.ParseMediaType(bulkGetResponse.Header().Get("Content-Type"))
log.Printf("content-type: %v. attrs: %v", contentType, attrs)
assert.Equal(t, "multipart/mixed", contentType)
reader := multipart.NewReader(bulkGetResponse.Body, attrs["boundary"])
// Make sure we see both docs
sawDoc1 := false
sawDoc2 := false
// Iterate over multipart parts and make assertions on each part
// Should get the following docs in their own parts:
/*
{
"error":"500",
"id":"doc",
"reason":"Internal error: Unable to load attachment for doc: doc with name: attach1 and revpos: 2 due to missing digest field",
"rev":"2-d501cf345b2e906547fe27dbbedf825b",
"status":500
}
and:
{
"_id":"doc2",
"_rev":"1-45ca73d819d5b1c9b8eea95290e79004",
"_revisions":{
"ids":[
"45ca73d819d5b1c9b8eea95290e79004"
],
"start":1
},
"prop":true
}
*/
for {
// Get the next part. Break out of the loop if we hit EOF
part, err := reader.NextPart()
if err != nil {
if err == io.EOF {
break
}
}
partBytes, err := io.ReadAll(part)
assert.NoError(t, err, "Unexpected error")
log.Printf("multipart part: %+v", string(partBytes))
partJson := map[string]interface{}{}
err = base.JSONUnmarshal(partBytes, &partJson)
assert.NoError(t, err, "Unexpected error")
// Assert expectations for the doc with attachment errors
rawId, ok := partJson["id"]
if ok {
// expect an error
_, hasErr := partJson["error"]
assert.True(t, hasErr, "Expected error field for this doc")
assert.Equal(t, rawId, doc1ID)
sawDoc1 = true
}
// Assert expectations for the doc with no attachment errors
rawId, ok = partJson[db.BodyId]
if ok {
_, hasErr := partJson["error"]
assert.True(t, !hasErr, "Did not expect error field for this doc")
assert.Equal(t, rawId, doc2ID)
sawDoc2 = true
}
}
assert.True(t, sawDoc2, "Did not see doc 2")
assert.True(t, sawDoc1, "Did not see doc 1")
}
func TestConflictWithInvalidAttachment(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{PersistentConfig: true})
defer rt.Close()
dbConfig := rt.NewDbConfig()
dbConfig.AllowConflicts = base.Ptr(true)
RequireStatus(t, rt.CreateDatabase("db", dbConfig), http.StatusCreated)
// Create Doc
version := rt.CreateTestDoc("doc1")
// Setup Attachment
attachmentContentType := "content/type"
reqHeaders := map[string]string{
"Content-Type": attachmentContentType,
}
// Set attachment
attachmentBody := "aGVsbG8gd29ybGQ=" // hello.txt
response := rt.SendAdminRequestWithHeaders("PUT", "/{{.keyspace}}/doc1/attach1?rev="+version.RevID, attachmentBody, reqHeaders)
RequireStatus(t, response, http.StatusCreated)
docrevId2 := DocVersionFromPutResponse(t, response).RevID
// Update Doc
rev3Input := `{"_attachments":{"attach1":{"content-type": "content/type", "digest":"sha1-b7fDq/pHG8Nf5F3fe0K2nu0xcw0=", "length": 16, "revpos": 2, "stub": true}}, "_id": "doc1", "_rev": "` + docrevId2 + `", "prop":true}`
response = rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1", rev3Input)
RequireStatus(t, response, http.StatusCreated)
docrevId3 := DocVersionFromPutResponse(t, response).RevID
// Get Existing Doc & Update rev
rev4Input := `{"_attachments":{"attach1":{"content-type": "content/type", "digest":"sha1-b7fDq/pHG8Nf5F3fe0K2nu0xcw0=", "length": 16, "revpos": 2, "stub": true}}, "_id": "doc1", "_rev": "` + docrevId3 + `", "prop":true}`
response = rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1", rev4Input)
RequireStatus(t, response, http.StatusCreated)
// Get Existing Doc to Modify
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1?revs=true", "")
RequireStatus(t, response, http.StatusOK)
body := db.Body{}
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
// Modify Doc
parentRevList := [3]string{"foo3", "foo2", version.RevIDDigest()}
body["_rev"] = "3-foo3"
body["rev"] = "3-foo3"
body["_revisions"].(map[string]interface{})["ids"] = parentRevList
body["_revisions"].(map[string]interface{})["start"] = 3
delete(body["_attachments"].(map[string]interface{})["attach1"].(map[string]interface{}), "digest")
// Prepare changed doc
temp, err := base.JSONMarshal(body)
assert.NoError(t, err)
newBody := string(temp)
// Send changed / conflict doc
response = rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1?new_edits=false", newBody)
RequireStatus(t, response, http.StatusBadRequest)
}
// Create doc with attachment at rev 1 using pre-2.5 metadata (outside of _sync)
// Create rev 2 with stub using att revpos 1 and make sure we fetch the attachment correctly
// Reproduces CBG-616
func TestAttachmentRevposPre25Metadata(t *testing.T) {
if base.TestUseXattrs() {
t.Skip("Skipping with xattrs due to use of AddRaw _sync data")
}
rt := NewRestTester(t, nil)
defer rt.Close()
ok, err := rt.GetSingleDataStore().Add("doc1", 0, []byte(`{"_attachments":{"hello.txt":{"digest":"sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=","length":11,"revpos":1,"stub":true}},"_sync":{"rev":"1-6e5a9ed9e2e8637d495ac5dd2fa90479","sequence":2,"recent_sequences":[2],"history":{"revs":["1-6e5a9ed9e2e8637d495ac5dd2fa90479"],"parents":[-1],"channels":[null]},"cas":"","time_saved":"2019-12-06T20:02:25.523013Z"},"test":true}`))
require.NoError(t, err)
require.True(t, ok)
response := rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1?rev=1-6e5a9ed9e2e8637d495ac5dd2fa90479", `{"test":false,"_attachments":{"hello.txt":{"stub":true,"revpos":1}}}`)
RequireStatus(t, response, 201)
var putResp struct {
OK bool `json:"ok"`
Rev string `json:"rev"`
}
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &putResp))
require.True(t, putResp.OK)
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1", "")
RequireStatus(t, response, 200)
var body struct {
Test bool `json:"test"`
Attachments db.AttachmentMap `json:"_attachments"`
}
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
assert.False(t, body.Test)
att, ok := body.Attachments["hello.txt"]
require.True(t, ok)
assert.Equal(t, 1, att.Revpos)
assert.True(t, att.Stub)
assert.Equal(t, "sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=", att.Digest)
}
func TestConflictingBranchAttachments(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{PersistentConfig: true})
defer rt.Close()
dbConfig := rt.NewDbConfig()
dbConfig.AllowConflicts = base.Ptr(true)
RequireStatus(t, rt.CreateDatabase("db", dbConfig), http.StatusCreated)
// Create a document
version := rt.CreateTestDoc("doc1")
// //Create diverging tree
reqBodyRev2 := `{"_rev": "2-two", "_revisions": {"ids": ["two", "` + version.RevIDDigest() + `"], "start": 2}}`
response := rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1?new_edits=false", reqBodyRev2)
RequireStatus(t, response, http.StatusCreated)
docVersion2 := DocVersionFromPutResponse(t, response)
reqBodyRev2a := `{"_rev": "2-two", "_revisions": {"ids": ["twoa", "` + version.RevIDDigest() + `"], "start": 2}}`
response = rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1?new_edits=false", reqBodyRev2a)
RequireStatus(t, response, http.StatusCreated)
docVersion2a := DocVersionFromPutResponse(t, response)
assert.Equal(t, "2-twoa", docVersion2a.RevID)
// Put attachment on doc1 rev 2
rev3Attachment := `aGVsbG8gd29ybGQ=` // hello.txt
docVersion3 := rt.storeAttachment("doc1", docVersion2, "attach1", rev3Attachment)
// Put attachment on doc1 conflicting rev 2a
rev3aAttachment := `Z29vZGJ5ZSBjcnVlbCB3b3JsZA==` // bye.txt
docVersion3a := rt.storeAttachment("doc1", docVersion2a, "attach1a", rev3aAttachment)
// Perform small update on doc3
rev4Body := `{"_id": "doc1", "_attachments": {"attach1": {"content_type": "content/type", "digest": "sha1-b7fDq/pHG8Nf5F3fe0K2nu0xcw0=", "length": 16, "revpos": 3, "stub":true}}}`
docVersion4 := rt.UpdateDoc("doc1", docVersion3, rev4Body)
// Perform small update on doc3a
rev4aBody := `{"_id": "doc1", "_attachments": {"attach1a": {"content_type": "content/type", "digest": "sha1-rdfKyt3ssqPHnWBUxl/xauXXcUs=", "length": 28, "revpos": 3, "stub": true}}}`
docVersion4a := rt.UpdateDoc("doc1", docVersion3a, rev4aBody)
// Ensure the two attachments are different
response1 := rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1?atts_since=[\""+version.RevID+"\"]&rev="+docVersion4.RevID, "")
response2 := rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1?rev="+docVersion4a.RevID, "")
var body1 db.Body
var body2 db.Body
require.NoError(t, base.JSONUnmarshal(response1.Body.Bytes(), &body1))
require.NoError(t, base.JSONUnmarshal(response2.Body.Bytes(), &body2))
assert.NotEqual(t, body1["_attachments"], body2["_attachments"])
}
func TestAttachmentsWithTombstonedConflict(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{PersistentConfig: true})
defer rt.Close()
dbConfig := rt.NewDbConfig()
dbConfig.AllowConflicts = base.Ptr(true)
RequireStatus(t, rt.CreateDatabase("db", dbConfig), http.StatusCreated)
version := rt.CreateTestDoc("doc1")
// Add an attachment at rev 2
var body db.Body
rev2Attachment := `aGVsbG8gd29ybGQ=` // hello.txt
docVersion2 := rt.storeAttachment("doc1", version, "attach1", rev2Attachment)
// Create rev 3, preserve the attachment
rev3Body := `{"_id": "doc1", "mod":"mod_3", "_attachments": {"attach1": {"content_type": "content/type", "digest": "sha1-b7fDq/pHG8Nf5F3fe0K2nu0xcw0=", "length": 16, "revpos": 2, "stub":true}}}`
docVersion3 := rt.UpdateDoc("doc1", docVersion2, rev3Body)
// Add another attachment at rev 4
rev4Attachment := `Z29vZGJ5ZSBjcnVlbCB3b3JsZA==` // bye.txt
docVersion4 := rt.storeAttachment("doc1", docVersion3, "attach2", rev4Attachment)
// Create rev 5, preserve the attachments
rev5Body := `{"_id": "doc1",` +
`"mod":"mod_5",` +
`"_attachments": ` +
`{"attach1": {"content_type": "content/type", "digest": "sha1-b7fDq/pHG8Nf5F3fe0K2nu0xcw0=", "length": 16, "revpos": 2, "stub":true},` +
` "attach2": {"content_type": "content/type", "digest": "sha1-rdfKyt3ssqPHnWBUxl/xauXXcUs=", "length": 28, "revpos": 4, "stub":true}}` +
`}`
docVersion5 := rt.UpdateDoc("doc1", docVersion4, rev5Body)
// Create rev 6, preserve the attachments
rev6Body := `{"_id": "doc1",` +
`"mod":"mod_5",` +
`"_attachments": ` +
`{"attach1": {"content_type": "content/type", "digest": "sha1-b7fDq/pHG8Nf5F3fe0K2nu0xcw0=", "length": 16, "revpos": 2, "stub":true},` +
` "attach2": {"content_type": "content/type", "digest": "sha1-rdfKyt3ssqPHnWBUxl/xauXXcUs=", "length": 28, "revpos": 4, "stub":true}}` +
`}`
_ = rt.UpdateDoc("doc1", docVersion5, rev6Body)
response := rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1?atts_since=[\""+version.RevID+"\"]", "")
log.Printf("Rev6 GET: %s", response.Body.Bytes())
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
_, attachmentsPresent := body["_attachments"]
assert.True(t, attachmentsPresent)
// Create conflicting rev 6 that doesn't have attachments
reqBodyRev6a := `{"_rev": "6-a", "_revisions": {"ids": ["a", "` + docVersion5.RevID + `"], "start": 6}}`
response = rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1?new_edits=false", reqBodyRev6a)
RequireStatus(t, response, http.StatusCreated)
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &body))
docRevId2a := body["rev"].(string)
assert.Equal(t, "6-a", docRevId2a)
var rev6Response db.Body
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1?atts_since=[\""+version.RevID+"\"]", "")
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &rev6Response))
_, attachmentsPresent = rev6Response["_attachments"]
assert.False(t, attachmentsPresent)
// Tombstone revision 6-a, leaves 6-7368e68932e8261dba7ad831e3cd5a5e as winner
response = rt.SendAdminRequest("DELETE", "/{{.keyspace}}/doc1?rev=6-a", "")
RequireStatus(t, response, http.StatusOK)
// Retrieve current winning rev with attachments
var rev7Response db.Body
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1?atts_since=[\""+version.RevID+"\"]", "")
log.Printf("Rev6 GET: %s", response.Body.Bytes())
require.NoError(t, base.JSONUnmarshal(response.Body.Bytes(), &rev7Response))
_, attachmentsPresent = rev7Response["_attachments"]
assert.True(t, attachmentsPresent)
}
func TestAttachmentGetReplicator2(t *testing.T) {
rt := NewRestTester(t, nil)
defer rt.Close()
var body db.Body
// Put document as usual with attachment
response := rt.SendAdminRequest("PUT", "/{{.keyspace}}/doc1", `{"foo": "bar", "_attachments": {"hello.txt": {"data":"aGVsbG8gd29ybGQ="}}}`)
RequireStatus(t, response, http.StatusCreated)
err := base.JSONUnmarshal(response.Body.Bytes(), &body)
assert.NoError(t, err)
assert.True(t, body["ok"].(bool))
// Get a document with rev using replicator2
response = rt.SendAdminRequest("GET", "/{{.keyspace}}/doc1?replicator2=true", ``)
if base.IsEnterpriseEdition() {
RequireStatus(t, response, http.StatusOK)
err = base.JSONUnmarshal(response.Body.Bytes(), &body)
assert.NoError(t, err)
assert.Equal(t, "bar", body["foo"])
assert.Contains(t, body[db.BodyAttachments], "hello.txt")
} else {
RequireStatus(t, response, http.StatusNotImplemented)
}
}
func TestWebhookPropsWithAttachments(t *testing.T) {
const doc1 = "doc1"
wg := sync.WaitGroup{}
handler := func(w http.ResponseWriter, r *http.Request) {
defer wg.Done()
bodyBytes, err := io.ReadAll(r.Body)
require.NoError(t, err, "Error reading request body")
require.NoError(t, r.Body.Close(), "Error closing request body")
var body db.Body
require.NoError(t, base.JSONUnmarshal(bodyBytes, &body), "Error parsing document body")
assert.Equal(t, doc1, body[db.BodyId])
assert.Equal(t, "bar", body["foo"])
if strings.HasPrefix(body[db.BodyRev].(string), "1-") {
assert.Equal(t, "1-cd809becc169215072fd567eebd8b8de", body[db.BodyRev])
}
if strings.HasPrefix(body[db.BodyRev].(string), "2-") {
assert.Equal(t, "2-6433ff70e11791fcb7fdf16746f4b9e7", body[db.BodyRev])
attachments := body[db.BodyAttachments].(map[string]interface{})
attachment1 := attachments["attach1"].(map[string]interface{})
assert.Equal(t, "sha1-nq0xWBV2IEkkpY3ng+PEtFnCcVY=", attachment1["digest"])
assert.Equal(t, float64(30), attachment1["length"])
assert.Equal(t, float64(2), attachment1["revpos"])
assert.True(t, attachment1["stub"].(bool))
assert.Equal(t, "content/type", attachment1["content_type"])
}
}
s := httptest.NewServer(http.HandlerFunc(handler))
defer s.Close()
rtConfig := &RestTesterConfig{
DatabaseConfig: &DatabaseConfig{DbConfig: DbConfig{
AutoImport: true,
EventHandlers: &EventHandlerConfig{
DocumentChanged: []*EventConfig{
{Url: s.URL, Filter: "function(doc){return true;}", HandlerType: "webhook"},
},
},
},
}}
rt := NewRestTester(t, rtConfig)
defer rt.Close()
// Create first revision of the document with no attachment.
wg.Add(1)
doc1Version := rt.PutDoc(doc1, `{"foo": "bar"}`)
// Add attachment to the doc.
attachmentBody := "this is the body of attachment"
wg.Add(1)
_ = rt.storeAttachment(doc1, doc1Version, "attach1", attachmentBody)
wg.Wait()
}
func TestAttachmentContentType(t *testing.T) {
rt := NewRestTester(t, &RestTesterConfig{GuestEnabled: true})
defer rt.Close()
type attTest struct {