|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/sha256" |
| 5 | + "encoding/hex" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + |
| 11 | + "github.com/gin-gonic/gin" |
| 12 | + "github.com/kevingruber/gradle-cache/internal/storage" |
| 13 | + "go.opentelemetry.io/otel/attribute" |
| 14 | + "go.opentelemetry.io/otel/metric" |
| 15 | +) |
| 16 | + |
| 17 | +// PutAC handles PUT requests to store Bazel action cache entries. |
| 18 | +func (h *BazelHandler) PutAC(c *gin.Context) { |
| 19 | + h.put(c, h.acStorage, "ac", false) |
| 20 | +} |
| 21 | + |
| 22 | +// PutCAS handles PUT requests to store Bazel CAS entries. |
| 23 | +// If verifyCAS is enabled, the content hash is verified against the URL hash. |
| 24 | +func (h *BazelHandler) PutCAS(c *gin.Context) { |
| 25 | + h.put(c, h.casStorage, "cas", h.verifyCAS) |
| 26 | +} |
| 27 | + |
| 28 | +func (h *BazelHandler) put(c *gin.Context, store storage.Storage, cacheType string, verifyHash bool) { |
| 29 | + hash := c.Param("hash") |
| 30 | + if !isValidSHA256Hex(hash) { |
| 31 | + c.Status(http.StatusBadRequest) |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + attrs := metric.WithAttributes(attribute.String("cache_type", cacheType)) |
| 36 | + |
| 37 | + // Early rejection if Content-Length is known and too large |
| 38 | + contentLength := c.Request.ContentLength |
| 39 | + if contentLength > h.maxEntrySize { |
| 40 | + h.logger.Warn(). |
| 41 | + Str("hash", hash). |
| 42 | + Str("cache_type", cacheType). |
| 43 | + Int64("size", contentLength). |
| 44 | + Int64("max_size", h.maxEntrySize). |
| 45 | + Msg("bazel cache entry too large") |
| 46 | + c.Status(http.StatusRequestEntityTooLarge) |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + if verifyHash { |
| 51 | + h.putWithVerify(c, store, hash, cacheType, attrs) |
| 52 | + } else { |
| 53 | + h.putDirect(c, store, hash, cacheType, contentLength, attrs) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +// putDirect streams the request body to storage without hash verification. |
| 58 | +// If Content-Length is known, streams directly. Otherwise spools to a temp file. |
| 59 | +func (h *BazelHandler) putDirect(c *gin.Context, store storage.Storage, hash, cacheType string, contentLength int64, attrs metric.MeasurementOption) { |
| 60 | + if contentLength >= 0 { |
| 61 | + // Content-Length known: stream directly to storage |
| 62 | + limited := io.LimitReader(c.Request.Body, contentLength) |
| 63 | + h.metrics.EntrySize.Record(c.Request.Context(), float64(contentLength), attrs) |
| 64 | + |
| 65 | + if err := store.Put(c.Request.Context(), hash, limited, contentLength); err != nil { |
| 66 | + h.logger.Error().Err(err).Str("hash", hash).Str("cache_type", cacheType).Msg("failed to store bazel cache entry") |
| 67 | + c.Status(http.StatusInternalServerError) |
| 68 | + return |
| 69 | + } |
| 70 | + c.Status(http.StatusOK) |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + // Chunked transfer: spool to temp file to determine size |
| 75 | + size, reader, cleanup, err := h.spoolToTempFile(c.Request.Body) |
| 76 | + if cleanup != nil { |
| 77 | + defer cleanup() |
| 78 | + } |
| 79 | + if err != nil { |
| 80 | + h.logger.Error().Err(err).Str("hash", hash).Str("cache_type", cacheType).Msg("failed to read request body") |
| 81 | + c.Status(http.StatusInternalServerError) |
| 82 | + return |
| 83 | + } |
| 84 | + if size > h.maxEntrySize { |
| 85 | + c.Status(http.StatusRequestEntityTooLarge) |
| 86 | + return |
| 87 | + } |
| 88 | + |
| 89 | + h.metrics.EntrySize.Record(c.Request.Context(), float64(size), attrs) |
| 90 | + |
| 91 | + if err := store.Put(c.Request.Context(), hash, reader, size); err != nil { |
| 92 | + h.logger.Error().Err(err).Str("hash", hash).Str("cache_type", cacheType).Msg("failed to store bazel cache entry") |
| 93 | + c.Status(http.StatusInternalServerError) |
| 94 | + return |
| 95 | + } |
| 96 | + c.Status(http.StatusOK) |
| 97 | +} |
| 98 | + |
| 99 | +// putWithVerify spools the upload to a temp file while computing the SHA-256 hash, |
| 100 | +// then verifies the hash before storing. |
| 101 | +func (h *BazelHandler) putWithVerify(c *gin.Context, store storage.Storage, hash, cacheType string, attrs metric.MeasurementOption) { |
| 102 | + f, err := os.CreateTemp("", "bazel-cas-*") |
| 103 | + if err != nil { |
| 104 | + h.logger.Error().Err(err).Msg("failed to create temp file for CAS verification") |
| 105 | + c.Status(http.StatusInternalServerError) |
| 106 | + return |
| 107 | + } |
| 108 | + defer os.Remove(f.Name()) |
| 109 | + defer f.Close() |
| 110 | + |
| 111 | + hasher := sha256.New() |
| 112 | + limited := io.LimitReader(c.Request.Body, h.maxEntrySize+1) |
| 113 | + tee := io.TeeReader(limited, hasher) |
| 114 | + |
| 115 | + written, err := io.Copy(f, tee) |
| 116 | + if err != nil { |
| 117 | + h.logger.Error().Err(err).Str("hash", hash).Str("cache_type", cacheType).Msg("failed to read request body") |
| 118 | + c.Status(http.StatusInternalServerError) |
| 119 | + return |
| 120 | + } |
| 121 | + |
| 122 | + if written > h.maxEntrySize { |
| 123 | + c.Status(http.StatusRequestEntityTooLarge) |
| 124 | + return |
| 125 | + } |
| 126 | + |
| 127 | + computedHex := hex.EncodeToString(hasher.Sum(nil)) |
| 128 | + if computedHex != hash { |
| 129 | + h.metrics.HashMismatches.Add(c.Request.Context(), 1, attrs) |
| 130 | + h.logger.Warn(). |
| 131 | + Str("expected", hash). |
| 132 | + Str("computed", computedHex). |
| 133 | + Msg("bazel CAS hash mismatch") |
| 134 | + c.Status(http.StatusBadRequest) |
| 135 | + return |
| 136 | + } |
| 137 | + |
| 138 | + if _, err := f.Seek(0, io.SeekStart); err != nil { |
| 139 | + h.logger.Error().Err(err).Msg("failed to seek temp file") |
| 140 | + c.Status(http.StatusInternalServerError) |
| 141 | + return |
| 142 | + } |
| 143 | + |
| 144 | + h.metrics.EntrySize.Record(c.Request.Context(), float64(written), attrs) |
| 145 | + |
| 146 | + if err := store.Put(c.Request.Context(), hash, f, written); err != nil { |
| 147 | + h.logger.Error().Err(err).Str("hash", hash).Str("cache_type", cacheType).Msg("failed to store bazel cache entry") |
| 148 | + c.Status(http.StatusInternalServerError) |
| 149 | + return |
| 150 | + } |
| 151 | + c.Status(http.StatusOK) |
| 152 | +} |
| 153 | + |
| 154 | +// spoolToTempFile copies from r (limited to maxEntrySize+1) into a temp file |
| 155 | +// and returns the written size, a reader seeked to start, and a cleanup function. |
| 156 | +func (h *BazelHandler) spoolToTempFile(r io.Reader) (int64, io.Reader, func(), error) { |
| 157 | + f, err := os.CreateTemp("", "bazel-spool-*") |
| 158 | + if err != nil { |
| 159 | + return 0, nil, nil, fmt.Errorf("create temp file: %w", err) |
| 160 | + } |
| 161 | + cleanup := func() { |
| 162 | + f.Close() |
| 163 | + os.Remove(f.Name()) |
| 164 | + } |
| 165 | + |
| 166 | + limited := io.LimitReader(r, h.maxEntrySize+1) |
| 167 | + written, err := io.Copy(f, limited) |
| 168 | + if err != nil { |
| 169 | + return 0, nil, cleanup, fmt.Errorf("spool to temp file: %w", err) |
| 170 | + } |
| 171 | + |
| 172 | + if _, err := f.Seek(0, io.SeekStart); err != nil { |
| 173 | + return 0, nil, cleanup, fmt.Errorf("seek temp file: %w", err) |
| 174 | + } |
| 175 | + |
| 176 | + return written, f, cleanup, nil |
| 177 | +} |
0 commit comments