Files

236 lines
6.4 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strings"
"sync"
"time"
)
type apiGuard struct {
upstream *url.URL
client *http.Client
proxy *httputil.ReverseProxy
notesMu sync.Mutex
notes map[noteHandle]exportedNote
}
type exportSourceKey struct{}
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 source := g.normalizePackage(w, r); source != "" {
ctx := context.WithValue(r.Context(), exportSourceKey{}, source)
g.proxy.ServeHTTP(w, r.WithContext(ctx))
}
return
case "/api/slices":
if r.Method == http.MethodPost {
g.readSlice(w, r)
return
}
case "/api/pool":
if r.Method == http.MethodGet {
g.poolMetadata(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
}
var (
manifestTripID = regexp.MustCompile(`^[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$`)
manifestVersion = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
)
type exportManifest struct {
Source string `json:"source"`
Sections []struct {
Segments []struct {
Type string `json:"type"`
Version string `json:"version,omitempty"`
} `json:"segments"`
} `json:"sections"`
}
func (g *apiGuard) normalizePackage(w http.ResponseWriter, r *http.Request) string {
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 ""
}
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 != "" {
body, _ = json.Marshal(map[string]string{"trip_id": tripID})
} else {
manifest, valid := parseManifest(body)
if !valid {
writeError(w, http.StatusBadRequest, "invalid export manifest")
return ""
}
tripID = manifest.Source
if !g.requireTripOwner(w, r, tripID) {
return ""
}
body, _ = json.Marshal(manifest)
}
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 tripID
}
func parseManifest(body []byte) (exportManifest, bool) {
var manifest exportManifest
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if decoder.Decode(&manifest) != nil || decoder.Decode(new(any)) != io.EOF ||
!manifestTripID.MatchString(manifest.Source) {
return manifest, false
}
hasRoute := false
for _, section := range manifest.Sections {
if len(section.Segments) == 0 {
return manifest, false
}
for _, segment := range section.Segments {
switch {
case segment.Type == "route" && segment.Version == "":
hasRoute = true
case segment.Type == "note" && manifestVersion.MatchString(segment.Version):
default:
return manifest, false
}
}
}
return manifest, hasRoute
}
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)
}