This repository has been archived by the owner on Oct 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmiddleware.go
184 lines (151 loc) · 5.4 KB
/
middleware.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
// Copyright 2020 dfuse Platform 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 eosws
import (
"compress/gzip"
"context"
"encoding/json"
rateLimiter "github.com/streamingfast/dauth/ratelimiter"
"net/http"
"strings"
stackdriverPropagation "contrib.go.opencensus.io/exporter/stackdriver/propagation"
"github.com/eoscanada/eos-go"
"github.com/eoscanada/eos-go/eoserr"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/streamingfast/dauth/authenticator"
"github.com/streamingfast/derr"
"github.com/streamingfast/logging"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/trace"
"go.uber.org/zap"
)
type AuthFeatureChecker = func(ctx context.Context, credentials authenticator.Credentials) error
type AuthFeatureMiddleware struct {
checker AuthFeatureChecker
}
type RateLimiterMiddleware struct {
rateLimiter rateLimiter.RateLimiter
}
func CompressionMiddleware(next http.Handler) http.Handler {
return handlers.CompressHandlerLevel(next, gzip.BestSpeed)
}
func OpenCensusMiddleware(next http.Handler) http.Handler {
return &ochttp.Handler{
Handler: next,
Propagation: &stackdriverPropagation.HTTPFormat{},
}
}
func LoggingMiddleware(next http.Handler) http.Handler {
return &logging.Handler{
Next: next,
Propagation: &stackdriverPropagation.HTTPFormat{},
RootLogger: zlog,
}
}
func RESTTrackingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
TrackUserEvent(ctx, "rest_request",
"method", r.Method,
"host", r.Host,
"path", r.URL.Path,
"encoded_query", r.URL.Query().Encode(),
)
next.ServeHTTP(w, r)
})
}
func PreTrackingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
zlogger := logging.Logger(r.Context(), zlog)
zlogger.Debug("handling HTTP request",
zap.String("method", r.Method),
zap.Any("host", r.Host),
zap.Any("url", r.URL),
zap.Any("headers", r.Header),
)
ctx := r.Context()
span := trace.FromContext(ctx)
if span == nil {
zlogger.Error("trace is not present in request but should have been")
}
spanContext := span.SpanContext()
traceID := spanContext.TraceID.String()
w.Header().Set("X-Trace-ID", traceID)
next.ServeHTTP(w, r)
})
}
func NewCORSMiddleware() mux.MiddlewareFunc {
allowedHeaders := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "X-Eos-Push-Guarantee"})
allowedOrigins := handlers.AllowedOrigins([]string{"*"})
allowedMethods := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "OPTIONS"})
maxAge := handlers.MaxAge(86400) // 24 hours - hard capped by Firefox / Chrome is max 10 minutes
return handlers.CORS(allowedHeaders, allowedOrigins, allowedMethods, maxAge)
}
func NewAuthFeatureMiddleware(checker AuthFeatureChecker) *AuthFeatureMiddleware {
return &AuthFeatureMiddleware{
checker: checker,
}
}
func (middleware *AuthFeatureMiddleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
credentials := authenticator.GetCredentials(ctx)
if credentials == nil {
derr.WriteError(ctx, w, "credentials unavailable from context but should have been", derr.UnexpectedError(ctx, nil))
return
}
err := middleware.checker(ctx, credentials)
if err != nil {
derr.WriteError(ctx, w, "request not authorized to perform this action", err)
return
}
next.ServeHTTP(w, r)
})
}
func NewRateLimiterMiddleware(rateLimiter rateLimiter.RateLimiter) *RateLimiterMiddleware {
return &RateLimiterMiddleware{
rateLimiter: rateLimiter,
}
}
func (middleware *RateLimiterMiddleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
credentials := authenticator.GetCredentials(ctx)
if credentials == nil {
derr.WriteError(ctx, w, "credentials unavailable from context but should have been", derr.UnexpectedError(ctx, nil))
return
}
method := "rest"
if strings.Contains(r.URL.Path, "/v1/stream") {
method = "eosws"
} else if strings.Contains(r.URL.Path, "/v0/state") {
method = "state"
}
if !middleware.rateLimiter.Gate(credentials.GetUserID(), method) {
derr.WriteError(ctx, w, "request not authorized to perform this action", RateLimitTooManyRequests(ctx))
return
}
next.ServeHTTP(w, r)
})
}
func DfuseErrorHandler(w http.ResponseWriter, ctx context.Context, err error) {
derr.WriteError(ctx, w, "unable to authorize request", AuthInvalidTokenError(ctx, err, ""))
}
func EOSChainErrorHandler(w http.ResponseWriter, ctx context.Context, err error) {
apiError := eos.NewAPIError(401, "this feature requires a dfuse API key (https://dfuse.io)", eoserr.ErrUnhandledException)
zlog.Warn("chain Error", zap.Error(apiError))
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(apiError)
}