-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauthorization.go
More file actions
166 lines (142 loc) · 4.74 KB
/
authorization.go
File metadata and controls
166 lines (142 loc) · 4.74 KB
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
package api
import (
"context"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/golang/glog"
"github.com/livepeer/livepeer-data/metrics"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
authorizationHeaders = []string{"Authorization", "Cookie", "Origin"}
// the response headers proxied from the auth request are basically cors headers
proxiedResponseHeaders = []string{
"Access-Control-Allow-Origin",
"Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Headers",
"Access-Control-Expose-Headers",
"Access-Control-Max-Age",
}
authTimeout = 3 * time.Second
authRequestDuration = metrics.Factory.NewSummaryVec(
prometheus.SummaryOpts{
Name: metrics.FQName("auth_request_duration_seconds"),
Help: "Duration of performed authorization requests in seconds",
},
[]string{"code", "method"},
)
httpClient = &http.Client{
Transport: promhttp.InstrumentRoundTripperDuration(authRequestDuration, http.DefaultTransport),
}
userIdContextKey = &contextKeys{"userId"}
projectIdContextKey = &contextKeys{"projectId"}
isCallerAdminContextKey = &contextKeys{"isCallerAdmin"}
)
type contextKeys struct {
str string
}
func authorization(authUrl string) middleware {
return inlineMiddleware(func(rw http.ResponseWriter, r *http.Request, next http.Handler) {
ctx, cancel := context.WithTimeout(r.Context(), authTimeout)
defer cancel()
authReq, err := http.NewRequestWithContext(ctx, r.Method, authUrl, nil)
if err != nil {
respondError(rw, http.StatusInternalServerError, err)
return
}
authReq.Header.Set("X-Original-Uri", originalReqUri(r))
setAuthHeaderFromAPIParam(r, authReq.Header, streamIDParam, "X-Livepeer-Stream-Id")
setAuthHeaderFromAPIParam(r, authReq.Header, assetIDParam, "X-Livepeer-Asset-Id")
setAuthHeaderFromAPIParam(r, authReq.Header, playbackIDParam, "X-Livepeer-Playback-Id")
copyHeaders(authorizationHeaders, r.Header, authReq.Header)
authRes, err := httpClient.Do(authReq)
if err != nil {
respondError(rw, http.StatusInternalServerError, fmt.Errorf("error authorizing request: %w", err))
return
}
defer authRes.Body.Close()
copyHeaders(proxiedResponseHeaders, authRes.Header, rw.Header())
// if this is an OPTIONS request, we just proxy the CORS logic from the auth server
if r.Method == http.MethodOptions && authRes.StatusCode == http.StatusNoContent {
rw.WriteHeader(http.StatusNoContent)
return
}
// It not found, we just pass NotFound to the client
if authRes.StatusCode == http.StatusNotFound {
rw.WriteHeader(http.StatusNotFound)
return
}
if authRes.StatusCode != http.StatusOK && authRes.StatusCode != http.StatusNoContent {
if contentType := authRes.Header.Get("Content-Type"); contentType != "" {
rw.Header().Set("Content-Type", contentType)
}
rw.WriteHeader(authRes.StatusCode)
if _, err := io.Copy(rw, authRes.Body); err != nil {
glog.Errorf("Error writing auth error response. err=%q, status=%d, headers=%+v", err, authRes.StatusCode, authRes.Header)
}
return
}
if userID := authRes.Header.Get("X-Livepeer-User-Id"); userID != "" {
ctx := context.WithValue(r.Context(), userIdContextKey, userID)
r = r.WithContext(ctx)
}
if projectID := authRes.Header.Get("X-Livepeer-Project-Id"); projectID != "" {
ctx := context.WithValue(r.Context(), projectIdContextKey, projectID)
r = r.WithContext(ctx)
}
if isCallerAdmin, err := strconv.ParseBool(authRes.Header.Get("X-Livepeer-Is-Caller-Admin")); err == nil {
ctx := context.WithValue(r.Context(), isCallerAdminContextKey, isCallerAdmin)
r = r.WithContext(ctx)
}
next.ServeHTTP(rw, r)
})
}
func originalReqUri(r *http.Request) string {
proto := "http"
if r.TLS != nil {
proto = "https"
}
if fwdProto := r.Header.Get("X-Forwarded-Proto"); fwdProto != "" {
proto = fwdProto
}
return fmt.Sprintf("%s://%s%s", proto, r.Host, r.URL.RequestURI())
}
func setAuthHeaderFromAPIParam(r *http.Request, headers http.Header, param string, header string) {
val := apiParam(r, param)
if val == "" {
val = r.URL.Query().Get(param)
}
if val != "" {
headers.Set(header, val)
}
}
func copyHeaders(headers []string, src, dest http.Header) {
for _, header := range headers {
if vals := src[header]; len(vals) > 0 {
dest[header] = vals
}
}
}
func callerUserId(r *http.Request) string {
if val, ok := r.Context().Value(userIdContextKey).(string); ok {
return val
}
return ""
}
func callerProjectId(r *http.Request) string {
if val, ok := r.Context().Value(projectIdContextKey).(string); ok {
return val
}
return ""
}
func isCallerAdmin(r *http.Request) bool {
if val, ok := r.Context().Value(isCallerAdminContextKey).(bool); ok {
return val
}
return false
}