forked from cloudflare/privacy-gateway-server-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gateway.go
150 lines (125 loc) · 4.54 KB
/
gateway.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
// Copyright (c) 2022 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
package main
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"time"
"github.com/chris-wood/ohttp-go"
)
type gatewayResource struct {
verbose bool
legacyKeyID uint8
gateway ohttp.Gateway
encapsulationHandlers map[string]EncapsulationHandler
debugResponse bool
metricsFactory MetricsFactory
}
const (
ohttpRequestContentType = "message/ohttp-req"
ohttpResponseContentType = "message/ohttp-res"
twelveHours = 12 * 3600
twentyFourHours = 24 * 3600
// Metrics constants
metricsEventGatewayRequest = "gateway_request"
metricsEventConfigsRequest = "configs_request"
metricsResultConfigsUnavalable = "configs_unavailable"
metricsResultInvalidMethod = "invalid_method"
metricsResultInvalidContentType = "invalid_content_type"
metricsResultInvalidContent = "invalid_content"
)
func (s *gatewayResource) httpError(w http.ResponseWriter, status int, debugMessage string, metrics Metrics, metricsPrefix string) {
if s.verbose {
log.Println(debugMessage)
}
if s.debugResponse {
http.Error(w, debugMessage, status)
} else {
http.Error(w, http.StatusText(status), status)
}
metrics.ResponseStatus(metricsPrefix, status)
}
func (s *gatewayResource) gatewayHandler(w http.ResponseWriter, r *http.Request) {
if s.verbose {
log.Printf("%s Handling %s\n", r.Method, r.URL.Path)
}
metrics := s.metricsFactory.Create(metricsEventGatewayRequest)
if r.Method != http.MethodPost {
metrics.Fire(metricsResultInvalidMethod)
s.httpError(w, http.StatusBadRequest, fmt.Sprintf("Invalid method: %s", r.Method), metrics, r.Method)
return
}
if r.Header.Get("Content-Type") != ohttpRequestContentType {
metrics.Fire(metricsResultInvalidContentType)
s.httpError(w, http.StatusBadRequest, fmt.Sprintf("Invalid content type: %s", r.Header.Get("Content-Type")), metrics, r.Method)
return
}
var encapHandler EncapsulationHandler
var ok bool
if encapHandler, ok = s.encapsulationHandlers[r.URL.Path]; !ok {
s.httpError(w, http.StatusBadRequest, fmt.Sprintf("Unknown handler"), metrics, r.Method)
return
}
defer r.Body.Close()
encryptedMessageBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
metrics.Fire(metricsResultInvalidContent)
s.httpError(w, http.StatusBadRequest, fmt.Sprintf("Reading request body failed"), metrics, r.Method)
return
}
encapsulatedReq, err := ohttp.UnmarshalEncapsulatedRequest(encryptedMessageBytes)
if err != nil {
metrics.Fire(metricsResultInvalidContent)
s.httpError(w, http.StatusBadRequest, fmt.Sprintf("Reading request body failed"), metrics, r.Method)
return
}
encapsulatedResp, err := encapHandler.Handle(r, encapsulatedReq, metrics)
if err != nil {
if s.verbose {
log.Printf(err.Error())
}
errorCode := encapsulationErrorToGatewayStatusCode(err)
s.httpError(w, errorCode, http.StatusText(errorCode), metrics, r.Method)
return
}
packedResponse := encapsulatedResp.Marshal()
w.Header().Set("Content-Type", ohttpResponseContentType)
w.Header().Set("Connection", "Keep-Alive")
w.Write(packedResponse)
metrics.ResponseStatus(r.Method, http.StatusOK)
}
func (s *gatewayResource) legacyConfigHandler(w http.ResponseWriter, r *http.Request) {
if s.verbose {
log.Printf("%s Handling %s\n", r.Method, r.URL.Path)
}
metrics := s.metricsFactory.Create(metricsEventConfigsRequest)
config, err := s.gateway.Config(s.legacyKeyID)
if err != nil {
log.Printf("Config unavailable")
metrics.Fire(metricsResultConfigsUnavalable)
s.httpError(w, http.StatusInternalServerError, "Config unavailable", metrics, r.Method)
return
}
// Make expiration time even/random throughout interval 12-36h
rand.Seed(time.Now().UnixNano())
maxAge := twelveHours + rand.Intn(twentyFourHours)
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, private", maxAge))
w.Write(config.Marshal())
metrics.ResponseStatus(r.Method, http.StatusOK)
}
func (s *gatewayResource) configHandler(w http.ResponseWriter, r *http.Request) {
if s.verbose {
log.Printf("%s Handling %s\n", r.Method, r.URL.Path)
}
metrics := s.metricsFactory.Create(metricsEventConfigsRequest)
// Make expiration time even/random throughout interval 12-36h
rand.Seed(time.Now().UnixNano())
maxAge := twelveHours + rand.Intn(twentyFourHours)
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, private", maxAge))
w.Header().Set("Content-Type", "application/ohttp-keys")
w.Write(s.gateway.MarshalConfigs())
metrics.ResponseStatus(r.Method, http.StatusOK)
}