diff --git a/delamain/guard/Dockerfile b/delamain/guard/Dockerfile index 3cdcccf..767745a 100644 --- a/delamain/guard/Dockerfile +++ b/delamain/guard/Dockerfile @@ -1,6 +1,6 @@ FROM golang:1.27.4-alpine AS build WORKDIR /src -COPY go.mod main.go ./ +COPY go.mod main.go slices.go ./ RUN CGO_ENABLED=0 go build -trimpath -o /api-guard . FROM scratch diff --git a/delamain/guard/main.go b/delamain/guard/main.go index d7af61a..19ebc05 100644 --- a/delamain/guard/main.go +++ b/delamain/guard/main.go @@ -10,6 +10,7 @@ import ( "net/http/httputil" "net/url" "strings" + "sync" "time" ) @@ -17,6 +18,8 @@ type apiGuard struct { upstream *url.URL client *http.Client proxy *httputil.ReverseProxy + notesMu sync.Mutex + notes map[noteHandle]exportedNote } func main() { @@ -35,8 +38,9 @@ func main() { func newGuard(upstream *url.URL) *apiGuard { transport := http.DefaultTransport.(*http.Transport).Clone() transport.ResponseHeaderTimeout = 15 * time.Second - return &apiGuard{ + guard := &apiGuard{ upstream: upstream, + notes: make(map[noteHandle]exportedNote), client: &http.Client{ Transport: transport, Timeout: 5 * time.Second, @@ -55,6 +59,8 @@ func newGuard(upstream *url.URL) *apiGuard { }, }, } + guard.proxy.ModifyResponse = guard.rememberExport + return guard } func (g *apiGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -70,6 +76,11 @@ func (g *apiGuard) ServeHTTP(w http.ResponseWriter, r *http.Request) { 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/") { @@ -155,7 +166,11 @@ func normalizePackage(w http.ResponseWriter, r *http.Request) bool { } 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(map[string]string{"error": message}) + _ = json.NewEncoder(w).Encode(body) } diff --git a/delamain/guard/slices.go b/delamain/guard/slices.go new file mode 100644 index 0000000..5090fa8 --- /dev/null +++ b/delamain/guard/slices.go @@ -0,0 +1,110 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "time" +) + +type noteHandle struct { + Slot uint64 `json:"base_slot"` + Generation uint64 `json:"base_generation"` +} + +type exportedNote struct { + tripID string + data string + created time.Time +} + +const noteLifetime = 2 * time.Minute + +func (g *apiGuard) rememberExport(response *http.Response) error { + if response.Request.URL.Path != "/api/packages" || response.StatusCode != http.StatusOK { + return nil + } + const maxExport = 1 << 20 + body, err := io.ReadAll(io.LimitReader(response.Body, maxExport+1)) + response.Body.Close() + if err != nil { + return err + } + if len(body) > maxExport { + return errors.New("export response too large") + } + response.Body = io.NopCloser(bytes.NewReader(body)) + + var result struct { + TripID string `json:"trip_id"` + Slot *uint64 `json:"note_slot"` + Generation uint64 `json:"note_generation"` + Size int `json:"note_size"` + Data string `json:"data"` + } + if json.Unmarshal(body, &result) != nil || result.TripID == "" || result.Slot == nil || + result.Generation == 0 || result.Size != len(result.Data) || result.Size > 16<<10 { + return nil + } + + key := noteHandle{Slot: *result.Slot, Generation: result.Generation} + now := time.Now() + g.notesMu.Lock() + defer g.notesMu.Unlock() + if len(g.notes) >= 1024 { + var oldestKey noteHandle + var oldest time.Time + for k, note := range g.notes { + if now.Sub(note.created) >= noteLifetime { + delete(g.notes, k) + } else if oldest.IsZero() || note.created.Before(oldest) { + oldestKey, oldest = k, note.created + } + } + if len(g.notes) >= 1024 { + delete(g.notes, oldestKey) + } + } + g.notes[key] = exportedNote{tripID: result.TripID, data: result.Data, created: now} + return nil +} + +func (g *apiGuard) readSlice(w http.ResponseWriter, r *http.Request) { + var request struct { + noteHandle + Offset uint64 `json:"offset"` + Length uint64 `json:"length"` + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096)) + if err != nil || json.Unmarshal(body, &request) != nil || request.Generation == 0 { + writeError(w, http.StatusBadRequest, "invalid slice request") + return + } + if r.Header.Get("Authorization") == "" { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + g.notesMu.Lock() + note, found := g.notes[request.noteHandle] + g.notesMu.Unlock() + if !found || time.Since(note.created) >= noteLifetime { + writeError(w, http.StatusForbidden, "note unavailable") + return + } + if !g.requireTripOwner(w, r, note.tripID) { + return + } + size := uint64(len(note.data)) + if request.Offset > size || request.Length > size-request.Offset { + writeError(w, http.StatusBadRequest, "slice out of bounds") + return + } + data := note.data[request.Offset : request.Offset+request.Length] + writeJSON(w, http.StatusOK, struct { + Status int `json:"status"` + Generation uint64 `json:"generation"` + Data string `json:"data,omitempty"` + }{Status: 0, Generation: request.Generation + 1, Data: data}) +}