From 2a9632774dbf522bc99cc4363d2dada9891c4a81 Mon Sep 17 00:00:00 2001 From: takuya <1+takuya@users.noreply.git.ctfleague.ru> Date: Sun, 29 Nov 2026 13:00:36 +0300 Subject: [PATCH] Protect Delamain trip versions and package exports --- delamain/docker-compose.yml | 14 +++- delamain/guard/Dockerfile | 9 ++ delamain/guard/go.mod | 3 + delamain/guard/main.go | 161 ++++++++++++++++++++++++++++++++++++ delamain/nginx.conf | 2 +- 5 files changed, 187 insertions(+), 2 deletions(-) create mode 100644 delamain/guard/Dockerfile create mode 100644 delamain/guard/go.mod create mode 100644 delamain/guard/main.go diff --git a/delamain/docker-compose.yml b/delamain/docker-compose.yml index 392293f..6ca895c 100755 --- a/delamain/docker-compose.yml +++ b/delamain/docker-compose.yml @@ -67,6 +67,18 @@ services: - delamain_network restart: unless-stopped + api-guard: + build: ./guard + depends_on: + go-server: + condition: service_healthy + networks: + - delamain_network + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + restart: unless-stopped + nginx: image: nginx:alpine container_name: delamain_nginx @@ -76,7 +88,7 @@ services: - ./frontend:/usr/share/nginx/html:ro - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro depends_on: - - go-server + - api-guard networks: - delamain_network restart: unless-stopped diff --git a/delamain/guard/Dockerfile b/delamain/guard/Dockerfile new file mode 100644 index 0000000..3cdcccf --- /dev/null +++ b/delamain/guard/Dockerfile @@ -0,0 +1,9 @@ +FROM golang:1.27.4-alpine AS build +WORKDIR /src +COPY go.mod main.go ./ +RUN CGO_ENABLED=0 go build -trimpath -o /api-guard . + +FROM scratch +COPY --from=build /api-guard /api-guard +USER 65532:65532 +ENTRYPOINT ["/api-guard"] diff --git a/delamain/guard/go.mod b/delamain/guard/go.mod new file mode 100644 index 0000000..60c5377 --- /dev/null +++ b/delamain/guard/go.mod @@ -0,0 +1,3 @@ +module delamain/api-guard + +go 1.23 diff --git a/delamain/guard/main.go b/delamain/guard/main.go new file mode 100644 index 0000000..d7af61a --- /dev/null +++ b/delamain/guard/main.go @@ -0,0 +1,161 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "log" + "net/http" + "net/http/httputil" + "net/url" + "strings" + "time" +) + +type apiGuard struct { + upstream *url.URL + client *http.Client + proxy *httputil.ReverseProxy +} + +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 + return &apiGuard{ + upstream: upstream, + 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") + }, + }, + } +} + +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 + } + + 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) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]string{"error": message}) +} diff --git a/delamain/nginx.conf b/delamain/nginx.conf index 3cdf363..2d16cb8 100755 --- a/delamain/nginx.conf +++ b/delamain/nginx.conf @@ -8,7 +8,7 @@ server { index index.html; location /api/ { - proxy_pass http://go-server:8080/api/; + proxy_pass http://api-guard:8080/api/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr;