Files
mctf/delamain/guard/main.go
T

177 lines
4.9 KiB
Go

package main
import (
"bytes"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"time"
)
type apiGuard struct {
upstream *url.URL
client *http.Client
proxy *httputil.ReverseProxy
notesMu sync.Mutex
notes map[noteHandle]exportedNote
}
func main() {
upstream := &url.URL{Scheme: "http", Host: "go-server:8080"}
server := &http.Server{
Addr: ":8080",
Handler: newGuard(upstream),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
log.Fatal(server.ListenAndServe())
}
func newGuard(upstream *url.URL) *apiGuard {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.ResponseHeaderTimeout = 15 * time.Second
guard := &apiGuard{
upstream: upstream,
notes: make(map[noteHandle]exportedNote),
client: &http.Client{
Transport: transport,
Timeout: 5 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
},
proxy: &httputil.ReverseProxy{
Transport: transport,
Rewrite: func(request *httputil.ProxyRequest) {
request.SetURL(upstream)
request.Out.URL.RawPath = ""
},
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) {
writeError(w, http.StatusBadGateway, "service unavailable")
},
},
}
guard.proxy.ModifyResponse = guard.rememberExport
return guard
}
func (g *apiGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/health", "/api/users", "/api/login", "/api/estimate", "/api/trips":
g.proxy.ServeHTTP(w, r)
return
case "/api/packages":
if r.Method != http.MethodPost {
break
}
if normalizePackage(w, r) {
g.proxy.ServeHTTP(w, r)
}
return
case "/api/slices":
if r.Method == http.MethodPost {
g.readSlice(w, r)
return
}
}
if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/trips/") {
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/trips/"), "/")
if parts[0] != "" && parts[0] != "." && parts[0] != ".." {
if len(parts) == 1 {
g.proxy.ServeHTTP(w, r)
return
}
if parts[1] == "versions" && (len(parts) == 2 || (len(parts) == 3 && parts[2] != "")) {
if g.requireTripOwner(w, r, parts[0]) {
g.proxy.ServeHTTP(w, r)
}
return
}
}
}
writeError(w, http.StatusNotFound, "not found")
}
func (g *apiGuard) requireTripOwner(w http.ResponseWriter, r *http.Request, tripID string) bool {
// Reuse the legacy trip detail endpoint's session and ownership checks.
target := *g.upstream
target.Path = "/api/trips/" + tripID
request, err := http.NewRequestWithContext(r.Context(), http.MethodGet, target.String(), nil)
if err != nil {
writeError(w, http.StatusBadGateway, "service unavailable")
return false
}
request.Header.Set("Authorization", r.Header.Get("Authorization"))
response, err := g.client.Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "service unavailable")
return false
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 32<<10))
switch response.StatusCode {
case http.StatusOK:
return true
case http.StatusUnauthorized:
writeError(w, http.StatusUnauthorized, "authentication required")
case http.StatusForbidden:
writeError(w, http.StatusForbidden, "not your trip")
case http.StatusNotFound:
writeError(w, http.StatusNotFound, "trip not found")
default:
writeError(w, http.StatusBadGateway, "service unavailable")
}
return false
}
func normalizePackage(w http.ResponseWriter, r *http.Request) bool {
const maxPackageRequest = 1 << 20
defer r.Body.Close()
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxPackageRequest))
if err != nil {
var limit *http.MaxBytesError
if errors.As(err, &limit) {
writeError(w, http.StatusRequestEntityTooLarge, "request body too large")
} else {
writeError(w, http.StatusBadRequest, "invalid body")
}
return false
}
// Forward only the trip ID so the backend constructs the export manifest.
var fields map[string]json.RawMessage
var tripID string
if json.Unmarshal(body, &fields) != nil || len(fields) != 1 ||
json.Unmarshal(fields["trip_id"], &tripID) != nil || tripID == "" {
writeError(w, http.StatusBadRequest, "provide a trip_id to export")
return false
}
body, _ = json.Marshal(map[string]string{"trip_id": tripID})
r.Body = io.NopCloser(bytes.NewReader(body))
r.ContentLength = int64(len(body))
r.TransferEncoding = nil
r.Trailer = nil
r.Header.Set("Content-Type", "application/json")
return true
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}