-
Notifications
You must be signed in to change notification settings - Fork 342
/
Copy pathapi.go
911 lines (793 loc) · 25.9 KB
/
api.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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package api provides the functionality of the Bee
// client-facing HTTP API.
package api
import (
"context"
"crypto/ecdsa"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/big"
"mime"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/accounting"
"github.com/ethersphere/bee/pkg/auth"
"github.com/ethersphere/bee/pkg/crypto"
"github.com/ethersphere/bee/pkg/feeds"
"github.com/ethersphere/bee/pkg/file/pipeline"
"github.com/ethersphere/bee/pkg/file/pipeline/builder"
"github.com/ethersphere/bee/pkg/jsonhttp"
"github.com/ethersphere/bee/pkg/log"
"github.com/ethersphere/bee/pkg/p2p"
"github.com/ethersphere/bee/pkg/pingpong"
"github.com/ethersphere/bee/pkg/postage"
"github.com/ethersphere/bee/pkg/postage/postagecontract"
"github.com/ethersphere/bee/pkg/pss"
"github.com/ethersphere/bee/pkg/resolver"
"github.com/ethersphere/bee/pkg/resolver/client/ens"
"github.com/ethersphere/bee/pkg/sctx"
"github.com/ethersphere/bee/pkg/settlement"
"github.com/ethersphere/bee/pkg/settlement/swap"
"github.com/ethersphere/bee/pkg/settlement/swap/chequebook"
"github.com/ethersphere/bee/pkg/settlement/swap/erc20"
"github.com/ethersphere/bee/pkg/status"
"github.com/ethersphere/bee/pkg/steward"
storage "github.com/ethersphere/bee/pkg/storage"
"github.com/ethersphere/bee/pkg/storageincentives"
"github.com/ethersphere/bee/pkg/storageincentives/staking"
storer "github.com/ethersphere/bee/pkg/storer"
"github.com/ethersphere/bee/pkg/swarm"
"github.com/ethersphere/bee/pkg/topology"
"github.com/ethersphere/bee/pkg/topology/lightnode"
"github.com/ethersphere/bee/pkg/tracing"
"github.com/ethersphere/bee/pkg/transaction"
"github.com/go-playground/validator/v10"
"github.com/gorilla/mux"
"github.com/hashicorp/go-multierror"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/semaphore"
)
// loggerName is the tree path name of the logger for this package.
const loggerName = "api"
const (
SwarmPinHeader = "Swarm-Pin"
SwarmTagHeader = "Swarm-Tag"
SwarmEncryptHeader = "Swarm-Encrypt"
SwarmIndexDocumentHeader = "Swarm-Index-Document"
SwarmErrorDocumentHeader = "Swarm-Error-Document"
SwarmFeedIndexHeader = "Swarm-Feed-Index"
SwarmFeedIndexNextHeader = "Swarm-Feed-Index-Next"
SwarmCollectionHeader = "Swarm-Collection"
SwarmPostageBatchIdHeader = "Swarm-Postage-Batch-Id"
SwarmDeferredUploadHeader = "Swarm-Deferred-Upload"
ImmutableHeader = "Immutable"
GasPriceHeader = "Gas-Price"
GasLimitHeader = "Gas-Limit"
ETagHeader = "ETag"
AuthorizationHeader = "Authorization"
AcceptEncodingHeader = "Accept-Encoding"
ContentTypeHeader = "Content-Type"
ContentDispositionHeader = "Content-Disposition"
ContentLengthHeader = "Content-Length"
RangeHeader = "Range"
OriginHeader = "Origin"
)
// The size of buffer used for prefetching content with Langos.
// Warning: This value influences the number of chunk requests and chunker join goroutines
// per file request.
// Recommended value is 8 or 16 times the io.Copy default buffer value which is 32kB, depending
// on the file size. Use lookaheadBufferSize() to get the correct buffer size for the request.
const (
smallFileBufferSize = 8 * 32 * 1024
largeFileBufferSize = 16 * 32 * 1024
largeBufferFilesizeThreshold = 10 * 1000000 // ten megs
)
const (
multiPartFormData = "multipart/form-data"
contentTypeTar = "application/x-tar"
boolHeaderSetValue = "true"
)
var (
errInvalidNameOrAddress = errors.New("invalid name or bzz address")
errNoResolver = errors.New("no resolver connected")
errInvalidRequest = errors.New("could not validate request")
errInvalidContentType = errors.New("invalid content-type")
errDirectoryStore = errors.New("could not store directory")
errFileStore = errors.New("could not store file")
errInvalidPostageBatch = errors.New("invalid postage batch id")
errBatchUnusable = errors.New("batch not usable")
errUnsupportedDevNodeOperation = errors.New("operation not supported in dev mode")
errOperationSupportedOnlyInFullMode = errors.New("operation is supported only in full mode")
)
// Storer interface provides the functionality required from the local storage
// component of the node.
type Storer interface {
storer.UploadStore
storer.PinStore
storer.CacheStore
storer.NetStore
storer.LocalStore
storer.RadiusChecker
storer.Debugger
}
type Service struct {
auth auth.Authenticator
storer Storer
resolver resolver.Interface
pss pss.Interface
steward steward.Interface
logger log.Logger
loggerV1 log.Logger
tracer *tracing.Tracer
feedFactory feeds.Factory
signer crypto.Signer
post postage.Service
postageContract postagecontract.Interface
probe *Probe
metricsRegistry *prometheus.Registry
stakingContract staking.Contract
Options
http.Handler
router *mux.Router
metrics metrics
wsWg sync.WaitGroup // wait for all websockets to close on exit
quit chan struct{}
// from debug API
overlay *swarm.Address
publicKey ecdsa.PublicKey
pssPublicKey ecdsa.PublicKey
ethereumAddress common.Address
chequebookEnabled bool
swapEnabled bool
topologyDriver topology.Driver
p2p p2p.DebugService
accounting accounting.Interface
chequebook chequebook.Service
pseudosettle settlement.Interface
pingpong pingpong.Interface
batchStore postage.Storer
stamperStore storage.Store
syncStatus func() (bool, error)
swap swap.Interface
transaction transaction.Service
lightNodes *lightnode.Container
blockTime time.Duration
statusSem *semaphore.Weighted
postageSem *semaphore.Weighted
stakingSem *semaphore.Weighted
cashOutChequeSem *semaphore.Weighted
beeMode BeeNodeMode
chainBackend transaction.Backend
erc20Service erc20.Service
chainID int64
preMapHooks map[string]func(v string) (string, error)
validate *validator.Validate
redistributionAgent *storageincentives.Agent
statusService *status.Service
}
func (s *Service) SetP2P(p2p p2p.DebugService) {
if s != nil {
s.p2p = p2p
}
}
func (s *Service) SetSwarmAddress(addr *swarm.Address) {
if s != nil {
s.overlay = addr
}
}
func (s *Service) SetRedistributionAgent(redistributionAgent *storageincentives.Agent) {
if s != nil {
s.redistributionAgent = redistributionAgent
}
}
type Options struct {
CORSAllowedOrigins []string
WsPingPeriod time.Duration
Restricted bool
}
type ExtraOptions struct {
Pingpong pingpong.Interface
TopologyDriver topology.Driver
LightNodes *lightnode.Container
Accounting accounting.Interface
Pseudosettle settlement.Interface
Swap swap.Interface
Chequebook chequebook.Service
BlockTime time.Duration
Storer Storer
Resolver resolver.Interface
Pss pss.Interface
FeedFactory feeds.Factory
Post postage.Service
PostageContract postagecontract.Interface
Staking staking.Contract
Steward steward.Interface
SyncStatus func() (bool, error)
NodeStatus *status.Service
}
func New(
publicKey, pssPublicKey ecdsa.PublicKey,
ethereumAddress common.Address,
logger log.Logger,
transaction transaction.Service,
batchStore postage.Storer,
beeMode BeeNodeMode,
chequebookEnabled bool,
swapEnabled bool,
chainBackend transaction.Backend,
cors []string,
stamperStore storage.Store,
) *Service {
s := new(Service)
s.CORSAllowedOrigins = cors
s.beeMode = beeMode
s.logger = logger.WithName(loggerName).Register()
s.loggerV1 = s.logger.V(1).Register()
s.chequebookEnabled = chequebookEnabled
s.swapEnabled = swapEnabled
s.publicKey = publicKey
s.pssPublicKey = pssPublicKey
s.ethereumAddress = ethereumAddress
s.transaction = transaction
s.batchStore = batchStore
s.chainBackend = chainBackend
s.metricsRegistry = newDebugMetrics()
s.preMapHooks = map[string]func(v string) (string, error){
"mimeMediaType": func(v string) (string, error) {
typ, _, err := mime.ParseMediaType(v)
return typ, err
},
"decBase64url": func(v string) (string, error) {
buf, err := base64.URLEncoding.DecodeString(v)
return string(buf), err
},
"decHex": func(v string) (string, error) {
buf, err := hex.DecodeString(v)
return string(buf), err
},
}
s.validate = validator.New()
s.validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get(mapStructureTagName), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
s.stamperStore = stamperStore
return s
}
// Configure will create a and initialize a new API service.
func (s *Service) Configure(signer crypto.Signer, auth auth.Authenticator, tracer *tracing.Tracer, o Options, e ExtraOptions, chainID int64, erc20 erc20.Service) {
s.auth = auth
s.signer = signer
s.Options = o
s.tracer = tracer
s.metrics = newMetrics()
s.quit = make(chan struct{})
s.storer = e.Storer
s.resolver = e.Resolver
s.pss = e.Pss
s.feedFactory = e.FeedFactory
s.post = e.Post
s.postageContract = e.PostageContract
s.steward = e.Steward
s.stakingContract = e.Staking
s.pingpong = e.Pingpong
s.topologyDriver = e.TopologyDriver
s.accounting = e.Accounting
s.chequebook = e.Chequebook
s.swap = e.Swap
s.lightNodes = e.LightNodes
s.pseudosettle = e.Pseudosettle
s.blockTime = e.BlockTime
s.statusSem = semaphore.NewWeighted(1)
s.postageSem = semaphore.NewWeighted(1)
s.stakingSem = semaphore.NewWeighted(1)
s.cashOutChequeSem = semaphore.NewWeighted(1)
s.chainID = chainID
s.erc20Service = erc20
s.syncStatus = e.SyncStatus
s.statusService = e.NodeStatus
s.preMapHooks["resolve"] = func(v string) (string, error) {
switch addr, err := s.resolveNameOrAddress(v); {
case err == nil:
return addr.String(), nil
case errors.Is(err, ens.ErrNotImplemented):
return v, nil
default:
return "", err
}
}
}
func (s *Service) SetProbe(probe *Probe) {
s.probe = probe
}
// Close hangs up running websockets on shutdown.
func (s *Service) Close() error {
s.logger.Info("api shutting down")
close(s.quit)
done := make(chan struct{})
go func() {
defer close(done)
s.wsWg.Wait()
}()
select {
case <-done:
case <-time.After(1 * time.Second):
return errors.New("api shutting down with open websockets")
}
return nil
}
// getOrCreateSessionID attempts to get the session if an tag id is supplied, and returns an error
// if it does not exist. If no id is supplied, it will attempt to create a new session and return it.
func (s *Service) getOrCreateSessionID(tagUid uint64) (uint64, error) {
var (
tag storer.SessionInfo
err error
)
// if tag ID is not supplied, create a new tag
if tagUid == 0 {
tag, err = s.storer.NewSession()
} else {
tag, err = s.storer.Session(tagUid)
}
return tag.TagID, err
}
func (s *Service) resolveNameOrAddress(str string) (swarm.Address, error) {
// Try and mapStructure the name as a bzz address.
addr, err := swarm.ParseHexAddress(str)
if err == nil {
s.loggerV1.Debug("resolve name: parsing bzz address successful", "string", str, "address", addr)
return addr, nil
}
// If no resolver is not available, return an error.
if s.resolver == nil {
return swarm.ZeroAddress, errNoResolver
}
// Try and resolve the name using the provided resolver.
s.logger.Debug("resolve name: attempting to resolve string to address", "string", str)
addr, err = s.resolver.Resolve(str)
if err == nil {
s.loggerV1.Debug("resolve name: address resolved successfully", "string", str, "address", addr)
return addr, nil
}
return swarm.ZeroAddress, fmt.Errorf("%w: %w", errInvalidNameOrAddress, err)
}
type securityTokenRsp struct {
Key string `json:"key"`
}
type securityTokenReq struct {
Role string `json:"role"`
Expiry int `json:"expiry"` // duration in seconds
}
func (s *Service) authHandler(w http.ResponseWriter, r *http.Request) {
_, pass, ok := r.BasicAuth()
if !ok {
s.logger.Error(nil, "auth handler: missing basic auth")
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
jsonhttp.Unauthorized(w, "Unauthorized")
return
}
if !s.auth.Authorize(pass) {
s.logger.Error(nil, "auth handler: unauthorized")
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
jsonhttp.Unauthorized(w, "Unauthorized")
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.logger.Debug("auth handler: read request body failed", "error", err)
s.logger.Error(nil, "auth handler: read request body failed")
jsonhttp.BadRequest(w, "Read request body")
return
}
var payload securityTokenReq
if err = json.Unmarshal(body, &payload); err != nil {
s.logger.Debug("auth handler: unmarshal request body failed", "error", err)
s.logger.Error(nil, "auth handler: unmarshal request body failed")
jsonhttp.BadRequest(w, "Unmarshal json body")
return
}
key, err := s.auth.GenerateKey(payload.Role, time.Duration(payload.Expiry)*time.Second)
if errors.Is(err, auth.ErrExpiry) {
s.logger.Debug("auth handler: generate key failed", "error", err)
s.logger.Error(nil, "auth handler: generate key failed")
jsonhttp.BadRequest(w, "Expiry duration must be a positive number")
return
}
if err != nil {
s.logger.Debug("auth handler: add auth token failed", "error", err)
s.logger.Error(nil, "auth handler: add auth token failed")
jsonhttp.InternalServerError(w, "Error generating authorization token")
return
}
jsonhttp.Created(w, securityTokenRsp{
Key: key,
})
}
func (s *Service) refreshHandler(w http.ResponseWriter, r *http.Request) {
reqToken := r.Header.Get(AuthorizationHeader)
if !strings.HasPrefix(reqToken, "Bearer ") {
jsonhttp.Forbidden(w, "Missing bearer token")
return
}
keys := strings.Split(reqToken, "Bearer ")
if len(keys) != 2 || strings.Trim(keys[1], " ") == "" {
jsonhttp.Forbidden(w, "Missing security token")
return
}
authToken := keys[1]
body, err := io.ReadAll(r.Body)
if err != nil {
s.logger.Debug("auth handler: read request body failed", "error", err)
s.logger.Error(nil, "auth handler: read request body failed")
jsonhttp.BadRequest(w, "Read request body")
return
}
var payload securityTokenReq
if err = json.Unmarshal(body, &payload); err != nil {
s.logger.Debug("auth handler: unmarshal request body failed", "error", err)
s.logger.Error(nil, "auth handler: unmarshal request body failed")
jsonhttp.BadRequest(w, "Unmarshal json body")
return
}
key, err := s.auth.RefreshKey(authToken, time.Duration(payload.Expiry)*time.Second)
if errors.Is(err, auth.ErrTokenExpired) {
s.logger.Debug("auth handler: refresh key failed", "error", err)
s.logger.Error(nil, "auth handler: refresh key failed")
jsonhttp.BadRequest(w, "Token expired")
return
}
if err != nil {
s.logger.Debug("auth handler: refresh token failed", "error", err)
s.logger.Error(nil, "auth handler: refresh token failed")
jsonhttp.InternalServerError(w, "Error refreshing authorization token")
return
}
jsonhttp.Created(w, securityTokenRsp{
Key: key,
})
}
func (s *Service) newTracingHandler(spanName string) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, err := s.tracer.WithContextFromHTTPHeaders(r.Context(), r.Header)
if err != nil && !errors.Is(err, tracing.ErrContextNotFound) {
s.logger.Debug("extract tracing context failed", "span_name", spanName, "error", err)
// ignore
}
span, _, ctx := s.tracer.StartSpanFromContext(ctx, spanName, s.logger)
defer span.Finish()
err = s.tracer.AddContextHTTPHeader(ctx, r.Header)
if err != nil {
s.logger.Debug("inject tracing context failed", "span_name", spanName, "error", err)
// ignore
}
h.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func (s *Service) contentLengthMetricMiddleware() func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
now := time.Now()
h.ServeHTTP(w, r)
switch r.Method {
case http.MethodGet:
hdr := w.Header().Get(ContentLengthHeader)
if hdr == "" {
s.logger.Debug("content length header not found")
return
}
contentLength, err := strconv.Atoi(hdr)
if err != nil {
s.logger.Debug("int conversion failed", "content_length", hdr, "error", err)
return
}
if contentLength > 0 {
s.metrics.ContentApiDuration.WithLabelValues(strconv.FormatInt(toFileSizeBucket(int64(contentLength)), 10), r.Method).Observe(time.Since(now).Seconds())
}
case http.MethodPost:
if r.ContentLength > 0 {
s.metrics.ContentApiDuration.WithLabelValues(strconv.FormatInt(toFileSizeBucket(r.ContentLength), 10), r.Method).Observe(time.Since(now).Seconds())
}
}
})
}
}
// gasConfigMiddleware can be used by the APIs that allow block chain transactions to set
// gas price and gas limit through the HTTP API headers.
func (s *Service) gasConfigMiddleware(handlerName string) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger := s.logger.WithName(handlerName).Build()
headers := struct {
GasPrice *big.Int `map:"Gas-Price"`
GasLimit uint64 `map:"Gas-Limit"`
}{}
if response := s.mapStructure(r.Header, &headers); response != nil {
response("invalid header params", logger, w)
return
}
ctx := r.Context()
ctx = sctx.SetGasPrice(ctx, headers.GasPrice)
ctx = sctx.SetGasLimit(ctx, headers.GasLimit)
h.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func lookaheadBufferSize(size int64) int {
if size <= largeBufferFilesizeThreshold {
return smallFileBufferSize
}
return largeFileBufferSize
}
// corsHandler sets CORS headers to HTTP response if allowed origins are configured.
func (s *Service) corsHandler(h http.Handler) http.Handler {
allowedHeaders := []string{
"User-Agent", "Accept", "X-Requested-With", "Access-Control-Request-Headers", "Access-Control-Request-Method", "Accept-Ranges", "Content-Encoding",
AuthorizationHeader, AcceptEncodingHeader, ContentTypeHeader, ContentDispositionHeader, RangeHeader, OriginHeader,
SwarmTagHeader, SwarmPinHeader, SwarmEncryptHeader, SwarmIndexDocumentHeader, SwarmErrorDocumentHeader, SwarmCollectionHeader, SwarmPostageBatchIdHeader, SwarmDeferredUploadHeader,
GasPriceHeader, GasLimitHeader, ImmutableHeader,
}
allowedHeadersStr := strings.Join(allowedHeaders, ", ")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if o := r.Header.Get(OriginHeader); o != "" && s.checkOrigin(r) {
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Origin", o)
w.Header().Set("Access-Control-Allow-Headers", allowedHeadersStr)
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE")
w.Header().Set("Access-Control-Max-Age", "3600")
}
h.ServeHTTP(w, r)
})
}
// checkOrigin returns true if the origin is not set or is equal to the request host.
func (s *Service) checkOrigin(r *http.Request) bool {
origin := r.Header[OriginHeader]
if len(origin) == 0 {
return true
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
hosts := append(s.CORSAllowedOrigins, scheme+"://"+r.Host)
for _, v := range hosts {
if equalASCIIFold(origin[0], v) || v == "*" {
return true
}
}
return false
}
// validationError is a custom error type for validation errors.
type validationError struct {
Entry string
Value interface{}
Cause error
}
// Error implements the error interface.
func (e *validationError) Error() string {
return fmt.Sprintf("`%s=%v`: %v", e.Entry, e.Value, e.Cause)
}
// mapStructure maps the input into output struct and validates the output.
// It's a helper method for the handlers, which reduces the chattiness
// of the code.
func (s *Service) mapStructure(input, output interface{}) func(string, log.Logger, http.ResponseWriter) {
// response unifies the response format for parsing and validation errors.
response := func(err error) func(string, log.Logger, http.ResponseWriter) {
return func(msg string, logger log.Logger, w http.ResponseWriter) {
var merr *multierror.Error
if !errors.As(err, &merr) {
logger.Debug("mapping and validation failed", "error", err)
logger.Error(err, "mapping and validation failed")
jsonhttp.InternalServerError(w, err)
return
}
logger.Debug(msg, "error", err)
logger.Error(err, msg)
resp := jsonhttp.StatusResponse{
Message: msg,
Code: http.StatusBadRequest,
}
for _, err := range merr.Errors {
var perr *parseError
if errors.As(err, &perr) {
resp.Reasons = append(resp.Reasons, jsonhttp.Reason{
Field: perr.Entry,
Error: perr.Cause.Error(),
})
}
var verr *validationError
if errors.As(err, &verr) {
resp.Reasons = append(resp.Reasons, jsonhttp.Reason{
Field: verr.Entry,
Error: verr.Cause.Error(),
})
}
}
jsonhttp.BadRequest(w, resp)
}
}
if err := mapStructure(input, output, s.preMapHooks); err != nil {
return response(err)
}
if err := s.validate.Struct(output); err != nil {
var errs validator.ValidationErrors
if !errors.As(err, &errs) {
return response(err)
}
vErrs := &multierror.Error{ErrorFormat: flattenErrorsFormat}
for _, err := range errs {
val := err.Value()
switch v := err.Value().(type) {
case []byte:
val = string(v)
}
vErrs = multierror.Append(vErrs,
&validationError{
Entry: strings.ToLower(err.Field()),
Value: val,
Cause: fmt.Errorf("want %s:%s", err.Tag(), err.Param()),
})
}
return response(vErrs.ErrorOrNil())
}
return nil
}
// equalASCIIFold returns true if s is equal to t with ASCII case folding as
// defined in RFC 4790.
func equalASCIIFold(s, t string) bool {
for s != "" && t != "" {
sr, size := utf8.DecodeRuneInString(s)
s = s[size:]
tr, size := utf8.DecodeRuneInString(t)
t = t[size:]
if sr == tr {
continue
}
if 'A' <= sr && sr <= 'Z' {
sr = sr + 'a' - 'A'
}
if 'A' <= tr && tr <= 'Z' {
tr = tr + 'a' - 'A'
}
if sr != tr {
return false
}
}
return s == t
}
type putterOptions struct {
BatchID []byte
TagID uint64
Deferred bool
Pin bool
}
type putterSessionWrapper struct {
storer.PutterSession
stamper postage.Stamper
save func() error
}
func (p *putterSessionWrapper) Put(ctx context.Context, chunk swarm.Chunk) error {
stamp, err := p.stamper.Stamp(chunk.Address())
if err != nil {
return err
}
return p.PutterSession.Put(ctx, chunk.WithStamp(stamp))
}
func (p *putterSessionWrapper) Done(ref swarm.Address) error {
err := p.PutterSession.Done(ref)
if err != nil {
return err
}
return p.save()
}
func (p *putterSessionWrapper) Cleanup() error {
return errors.Join(p.PutterSession.Cleanup(), p.save())
}
func (s *Service) getStamper(batchID []byte) (postage.Stamper, func() error, error) {
exists, err := s.batchStore.Exists(batchID)
if err != nil {
return nil, nil, fmt.Errorf("batch exists: %w", err)
}
issuer, save, err := s.post.GetStampIssuer(batchID)
if err != nil {
return nil, nil, fmt.Errorf("stamp issuer: %w", err)
}
if usable := exists && s.post.IssuerUsable(issuer); !usable {
return nil, nil, errBatchUnusable
}
return postage.NewStamper(s.stamperStore, issuer, s.signer), save, nil
}
func (s *Service) newStamperPutter(ctx context.Context, opts putterOptions) (storer.PutterSession, error) {
if !opts.Deferred && s.beeMode == DevMode {
return nil, errUnsupportedDevNodeOperation
}
stamper, save, err := s.getStamper(opts.BatchID)
if err != nil {
return nil, fmt.Errorf("get stamper: %w", err)
}
var session storer.PutterSession
if opts.Deferred || opts.Pin {
session, err = s.storer.Upload(ctx, opts.Pin, opts.TagID)
} else {
session = s.storer.DirectUpload()
}
if err != nil {
return nil, fmt.Errorf("failed creating session: %w", err)
}
return &putterSessionWrapper{
PutterSession: session,
stamper: stamper,
save: save,
}, nil
}
type pipelineFunc func(context.Context, io.Reader) (swarm.Address, error)
func requestPipelineFn(s storage.Putter, encrypt bool) pipelineFunc {
return func(ctx context.Context, r io.Reader) (swarm.Address, error) {
pipe := builder.NewPipelineBuilder(ctx, s, encrypt)
return builder.FeedPipeline(ctx, pipe, r)
}
}
func requestPipelineFactory(ctx context.Context, s storage.Putter, encrypt bool) func() pipeline.Interface {
return func() pipeline.Interface {
return builder.NewPipelineBuilder(ctx, s, encrypt)
}
}
type cleanupOnErrWriter struct {
http.ResponseWriter
logger log.Logger
onErr func() error
}
func (r *cleanupOnErrWriter) WriteHeader(statusCode int) {
// if there is an error status returned, cleanup.
if statusCode >= http.StatusBadRequest {
err := r.onErr()
if err != nil {
r.logger.Debug("failed cleaning up", "err", err)
}
}
r.ResponseWriter.WriteHeader(statusCode)
}
// CalculateNumberOfChunks calculates the number of chunks in an arbitrary
// content length.
func CalculateNumberOfChunks(contentLength int64, isEncrypted bool) int64 {
if contentLength <= swarm.ChunkSize {
return 1
}
branchingFactor := swarm.Branches
if isEncrypted {
branchingFactor = swarm.EncryptedBranches
}
dataChunks := math.Ceil(float64(contentLength) / float64(swarm.ChunkSize))
totalChunks := dataChunks
intermediate := dataChunks / float64(branchingFactor)
for intermediate > 1 {
totalChunks += math.Ceil(intermediate)
intermediate = intermediate / float64(branchingFactor)
}
return int64(totalChunks) + 1
}
// defaultUploadMethod returns true for deferred when the defered header is not present.
func defaultUploadMethod(deffered *bool) bool {
if deffered == nil {
return true
}
return *deffered
}