vole
Site
Clone
Read only, no credentials:
https://rodent.software/vole.git
Write over SSH with a registered key:
git clone ssh://git@rodent.software/vole.git
Self-hosted forge that lives in your Git repo.
| 1 | package web |
| 2 | |
| 3 | // Attaching release artifacts from the browser. |
| 4 | // |
| 5 | // The CLI uploads the bytes over SSH and then pushes the pointers, and this is |
| 6 | // the same order with the web's own hands: bytes into the object store first, |
| 7 | // pointers on the metadata branch second. A published download therefore never |
| 8 | // names bytes that were never stored, and a failed upload publishes nothing. The |
| 9 | // two writers share the store, the pointer format, and the metadata function, so |
| 10 | // a file attached here is indistinguishable from one attached by |
| 11 | // `vole release attach` — including for `git clone` of the metadata branch, |
| 12 | // which carries both. |
| 13 | // |
| 14 | // A multipart body is read as a stream, not as form values: a directory upload |
| 15 | // carries its paths in each part's Content-Disposition filename, and |
| 16 | // r.ParseForm/ParseMultipartForm both flatten that to a base name. The CSRF field |
| 17 | // is checked after the parts are on disk and before anything is stored, which is |
| 18 | // the earliest point that does not require buffering the body in memory. |
| 19 | |
| 20 | import ( |
| 21 | "crypto/sha256" |
| 22 | "encoding/hex" |
| 23 | "errors" |
| 24 | "fmt" |
| 25 | "io" |
| 26 | "mime" |
| 27 | "mime/multipart" |
| 28 | "net/http" |
| 29 | "os" |
| 30 | "path/filepath" |
| 31 | "strings" |
| 32 | |
| 33 | "rodent.software/vole/core/git" |
| 34 | "rodent.software/vole/internal/format" |
| 35 | "rodent.software/vole/metadata" |
| 36 | ) |
| 37 | |
| 38 | // maxAttachParts bounds how many files one form may carry. A release is a |
| 39 | // download page, not a build cache: a hundred files is already a package tree, |
| 40 | // and a bound is what keeps one request from spending an afternoon in the |
| 41 | // metadata writer. |
| 42 | const maxAttachParts = 100 |
| 43 | |
| 44 | // maxAttachField bounds the small text fields beside the files (the CSRF token |
| 45 | // and the path prefix). |
| 46 | const maxAttachField = 4 << 10 |
| 47 | |
| 48 | // attachLimit is the most one upload request may carry. It is the object store's |
| 49 | // per-object cap when the instance sets one, because a request is a handful of |
| 50 | // files and no single file may exceed it anyway; without a configured cap, four |
| 51 | // times the per-object default is still a release artifact and not a backup. |
| 52 | func (w *Web) attachLimit() int64 { |
| 53 | if w.LFS != nil && w.LFS.MaxBytes > 0 { |
| 54 | return w.LFS.MaxBytes |
| 55 | } |
| 56 | return 1 << 30 |
| 57 | } |
| 58 | |
| 59 | // upload is one file read off the request, waiting to be stored. |
| 60 | type upload struct { |
| 61 | // name is the path the browser sent, before the prefix is applied. |
| 62 | name string |
| 63 | // temp is the spool file holding the bytes until the store takes them. |
| 64 | temp string |
| 65 | // target is the artifact path once the prefix is known. |
| 66 | target string |
| 67 | oid string |
| 68 | size int64 |
| 69 | } |
| 70 | |
| 71 | // AttachRelease is POST /<name>/releases/<tag>/attach. |
| 72 | func (w *Web) AttachRelease(rw http.ResponseWriter, r *http.Request) { |
| 73 | tag := r.PathValue("tag") |
| 74 | ctx, ok := w.beginMultipartWrite(rw, r, w.attachLimit()) |
| 75 | if !ok { |
| 76 | return |
| 77 | } |
| 78 | if !canMaintain(ctx.ACL, ctx.Name) { |
| 79 | w.notFound(rw, r) |
| 80 | return |
| 81 | } |
| 82 | if w.LFS == nil { |
| 83 | w.serverError(rw, r, "this instance has no object store, so an artifact cannot be stored") |
| 84 | return |
| 85 | } |
| 86 | m := ctx.Repo |
| 87 | g := m.Git() |
| 88 | t, err := g.Tag(tag) |
| 89 | if err != nil { |
| 90 | w.notFound(rw, r) |
| 91 | return |
| 92 | } |
| 93 | if !t.Annotated { |
| 94 | w.fail(rw, r, http.StatusBadRequest, |
| 95 | "A lightweight tag cannot carry attached files; annotate it first (`git tag -a`).", nil) |
| 96 | return |
| 97 | } |
| 98 | // The same rule the edit form applies, enforced here as well: a channel owns |
| 99 | // the URL, so the release it names does not change until the channel moves. |
| 100 | if msg := w.releaseRefusal(m, t); msg != "" { |
| 101 | w.fail(rw, r, http.StatusConflict, msg, nil) |
| 102 | return |
| 103 | } |
| 104 | |
| 105 | // A cross-origin form post is refused before the body is read: the token check |
| 106 | // needs the body, but a request the browser already says came from somewhere |
| 107 | // else should not be allowed to spend the instance's disk first. |
| 108 | if !w.sameOriginRequest(r) { |
| 109 | w.fail(rw, r, http.StatusForbidden, "bad request", nil) |
| 110 | return |
| 111 | } |
| 112 | parts, prefix, csrf, ok := w.readAttachParts(rw, r) |
| 113 | if !ok { |
| 114 | return |
| 115 | } |
| 116 | defer func() { |
| 117 | for _, u := range parts { |
| 118 | os.Remove(u.temp) |
| 119 | } |
| 120 | }() |
| 121 | if len(parts) == 0 { |
| 122 | w.fail(rw, r, http.StatusBadRequest, "Choose at least one file to attach.", nil) |
| 123 | return |
| 124 | } |
| 125 | // The token arrives inside the body, so it is checked once the body has been |
| 126 | // read and before the first byte reaches the store. |
| 127 | if !w.csrfToken(r, csrf) { |
| 128 | w.fail(rw, r, http.StatusForbidden, "bad request", nil) |
| 129 | return |
| 130 | } |
| 131 | |
| 132 | arts, err := w.prepareAttach(g, tag, prefix, parts) |
| 133 | if err != nil { |
| 134 | w.fail(rw, r, http.StatusBadRequest, err.Error(), nil) |
| 135 | return |
| 136 | } |
| 137 | if err := w.reserveAttachBytes(m.Name, parts); err != nil { |
| 138 | w.fail(rw, r, http.StatusRequestEntityTooLarge, err.Error(), nil) |
| 139 | return |
| 140 | } |
| 141 | for i := range parts { |
| 142 | if err := w.storeAttach(m.Name, parts[i], arts[i]); err != nil { |
| 143 | w.serverError(rw, r, "cannot store "+arts[i].Name+": "+err.Error()) |
| 144 | return |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Channels can move while the body is being read, so the rule is asked again |
| 149 | // where it matters: immediately before the pointers are published. |
| 150 | if msg := w.releaseRefusal(m, t); msg != "" { |
| 151 | w.fail(rw, r, http.StatusConflict, msg, nil) |
| 152 | return |
| 153 | } |
| 154 | |
| 155 | message := fmt.Sprintf("release: %s artifacts (web)", tag) |
| 156 | if err := metadata.WriteReleasePointers(g, metadata.Ref, tag, arts, message, ctx.Name); err != nil { |
| 157 | w.serverError(rw, r, "cannot write the artifact pointers: "+err.Error()) |
| 158 | return |
| 159 | } |
| 160 | w.audit("web.release.attach", ctx.Name, m.Name, fmt.Sprintf("%s: %d file(s)", tag, len(arts))) |
| 161 | w.refreshReleaseEvents(m) |
| 162 | http.Redirect(rw, r, "/"+m.Name+"/releases/"+pathURL(tag), http.StatusSeeOther) |
| 163 | } |
| 164 | |
| 165 | // readAttachParts spools every file in the body to a temporary file, hashing it |
| 166 | // as it arrives. Nothing is stored or published here: a refusal at any later step |
| 167 | // costs the upload and nothing else. |
| 168 | func (w *Web) readAttachParts(rw http.ResponseWriter, r *http.Request) (parts []upload, prefix, csrf string, ok bool) { |
| 169 | mr, err := r.MultipartReader() |
| 170 | if err != nil { |
| 171 | w.fail(rw, r, http.StatusBadRequest, "This form must be submitted as a file upload.", nil) |
| 172 | return nil, "", "", false |
| 173 | } |
| 174 | cleanup := func() { |
| 175 | for _, u := range parts { |
| 176 | os.Remove(u.temp) |
| 177 | } |
| 178 | } |
| 179 | for { |
| 180 | p, err := mr.NextPart() |
| 181 | if errors.Is(err, io.EOF) { |
| 182 | break |
| 183 | } |
| 184 | if err != nil { |
| 185 | cleanup() |
| 186 | var tooLarge *http.MaxBytesError |
| 187 | if errors.As(err, &tooLarge) { |
| 188 | w.fail(rw, r, http.StatusRequestEntityTooLarge, |
| 189 | fmt.Sprintf("The upload is larger than %d bytes; attach the files with `vole release attach`.", tooLarge.Limit), nil) |
| 190 | } else { |
| 191 | w.fail(rw, r, http.StatusBadRequest, "cannot read the upload: "+err.Error(), nil) |
| 192 | } |
| 193 | return nil, "", "", false |
| 194 | } |
| 195 | switch p.FormName() { |
| 196 | case "csrf": |
| 197 | csrf = readAttachField(p) |
| 198 | case "path": |
| 199 | prefix = readAttachField(p) |
| 200 | case "files": |
| 201 | name := attachPartName(p) |
| 202 | if name == "" { |
| 203 | p.Close() |
| 204 | continue // an empty file input sends one part with no filename |
| 205 | } |
| 206 | if len(parts) >= maxAttachParts { |
| 207 | p.Close() |
| 208 | cleanup() |
| 209 | w.fail(rw, r, http.StatusBadRequest, |
| 210 | fmt.Sprintf("A browser upload is limited to %d files; use `vole release attach` for a directory.", maxAttachParts), nil) |
| 211 | return nil, "", "", false |
| 212 | } |
| 213 | u, err := w.spoolAttach(p) |
| 214 | p.Close() |
| 215 | if err != nil { |
| 216 | cleanup() |
| 217 | var tooLarge *lfsTooLarge |
| 218 | if errors.As(err, &tooLarge) { |
| 219 | w.fail(rw, r, http.StatusRequestEntityTooLarge, |
| 220 | fmt.Sprintf("%s is larger than the %d-byte object limit; use `vole release attach`.", name, tooLarge.limit), nil) |
| 221 | } else { |
| 222 | w.fail(rw, r, http.StatusInternalServerError, "cannot buffer the upload: "+err.Error(), nil) |
| 223 | } |
| 224 | return nil, "", "", false |
| 225 | } |
| 226 | u.name = name |
| 227 | parts = append(parts, u) |
| 228 | default: |
| 229 | // A field the form does not have is ignored: a proxy or a future |
| 230 | // control adding one should not turn an upload into a 400. |
| 231 | } |
| 232 | p.Close() |
| 233 | } |
| 234 | return parts, prefix, csrf, true |
| 235 | } |
| 236 | |
| 237 | // readAttachField reads a small text part without letting a client decide how |
| 238 | // much of it the server keeps. |
| 239 | func readAttachField(p *multipart.Part) string { |
| 240 | b, _ := io.ReadAll(io.LimitReader(p, maxAttachField)) |
| 241 | return strings.TrimSpace(string(b)) |
| 242 | } |
| 243 | |
| 244 | // attachPartName is the path a browser sent for one file. Part.FileName() cannot |
| 245 | // be used: it applies filepath.Base, which is exactly the directory information a |
| 246 | // folder upload needs to keep. |
| 247 | func attachPartName(p *multipart.Part) string { |
| 248 | _, params, err := mime.ParseMediaType(p.Header.Get("Content-Disposition")) |
| 249 | if err != nil { |
| 250 | return "" |
| 251 | } |
| 252 | return params["filename"] |
| 253 | } |
| 254 | |
| 255 | // lfsTooLarge is a per-file refusal raised while spooling. |
| 256 | type lfsTooLarge struct{ limit int64 } |
| 257 | |
| 258 | func (e *lfsTooLarge) Error() string { |
| 259 | return fmt.Sprintf("file is larger than %d bytes", e.limit) |
| 260 | } |
| 261 | |
| 262 | // spoolAttach copies one part to a temporary file while hashing it, which is the |
| 263 | // only way to learn the object id the store needs without holding the file in |
| 264 | // memory or reading it twice. |
| 265 | func (w *Web) spoolAttach(p io.Reader) (upload, error) { |
| 266 | dir := filepath.Join(w.LFS.Root, "tmp") |
| 267 | if err := os.MkdirAll(dir, 0o755); err != nil { |
| 268 | return upload{}, err |
| 269 | } |
| 270 | f, err := os.CreateTemp(dir, "attach-*") |
| 271 | if err != nil { |
| 272 | return upload{}, err |
| 273 | } |
| 274 | limit := w.attachLimit() |
| 275 | h := sha256.New() |
| 276 | n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(p, limit+1)) |
| 277 | closeErr := f.Close() |
| 278 | switch { |
| 279 | case err != nil: |
| 280 | return upload{temp: f.Name()}, err |
| 281 | case closeErr != nil: |
| 282 | return upload{temp: f.Name()}, closeErr |
| 283 | case n > limit: |
| 284 | return upload{temp: f.Name()}, &lfsTooLarge{limit: limit} |
| 285 | } |
| 286 | return upload{temp: f.Name(), oid: hex.EncodeToString(h.Sum(nil)), size: n}, nil |
| 287 | } |
| 288 | |
| 289 | // prepareAttach turns the browser's paths into artifact paths, refuses the shapes |
| 290 | // a tree cannot hold, and says what would be replaced. The artifacts it returns |
| 291 | // are in the same order as parts. |
| 292 | func (w *Web) prepareAttach(g *git.Repo, tag, prefix string, parts []upload) ([]metadata.Artifact, error) { |
| 293 | prefix = strings.Trim(strings.TrimSpace(prefix), "/") |
| 294 | if prefix != "" { |
| 295 | if err := metadata.ValidArtifactPath(prefix); err != nil { |
| 296 | return nil, fmt.Errorf("path %q: %w", prefix, err) |
| 297 | } |
| 298 | } |
| 299 | seen := make(map[string]string, len(parts)) |
| 300 | for i := range parts { |
| 301 | rel := parts[i].name |
| 302 | for strings.HasPrefix(rel, "./") { |
| 303 | rel = strings.TrimPrefix(rel, "./") |
| 304 | } |
| 305 | rel = strings.TrimPrefix(rel, "/") |
| 306 | target := rel |
| 307 | if prefix != "" { |
| 308 | target = prefix + "/" + rel |
| 309 | } |
| 310 | if err := metadata.ValidArtifactPath(target); err != nil { |
| 311 | return nil, fmt.Errorf("%s: %w", target, err) |
| 312 | } |
| 313 | if _, dup := seen[target]; dup { |
| 314 | return nil, fmt.Errorf("two files would be attached as %q; rename one", target) |
| 315 | } |
| 316 | seen[target] = parts[i].temp |
| 317 | parts[i].target = target |
| 318 | } |
| 319 | |
| 320 | existing, err := metadata.ListReleaseArtifacts(g, tag) |
| 321 | if err != nil { |
| 322 | return nil, fmt.Errorf("cannot read the attached files: %w", err) |
| 323 | } |
| 324 | for _, e := range existing { |
| 325 | for _, u := range parts { |
| 326 | if u.target == e.Name { |
| 327 | continue // a replacement of one path is an edit, not a conflict |
| 328 | } |
| 329 | if strings.HasPrefix(u.target, e.Name+"/") { |
| 330 | return nil, fmt.Errorf("%s is a file on this release, so %s cannot be attached under it", e.Name, u.target) |
| 331 | } |
| 332 | if strings.HasPrefix(e.Name, u.target+"/") { |
| 333 | return nil, fmt.Errorf("%s is a directory on this release, so a file cannot be attached as %s", e.Name, u.target) |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | arts := make([]metadata.Artifact, len(parts)) |
| 339 | for i := range parts { |
| 340 | arts[i] = metadata.Artifact{Name: parts[i].target, OID: parts[i].oid, Size: parts[i].size} |
| 341 | } |
| 342 | return arts, nil |
| 343 | } |
| 344 | |
| 345 | // reserveAttachBytes refuses an upload that would take the repository past its |
| 346 | // object-store quota. It runs before the first byte is stored, so a refusal |
| 347 | // leaves the store exactly as it was. Bytes already linked to this repository |
| 348 | // cost nothing: the store is content-addressed and shared. |
| 349 | func (w *Web) reserveAttachBytes(repo string, parts []upload) error { |
| 350 | if w.Cfg == nil || w.Cfg.RepoMaxLFSBytes <= 0 { |
| 351 | return nil |
| 352 | } |
| 353 | var used int64 |
| 354 | if err := w.LFS.RepoWalk(repo, func(_ string, size int64) error { |
| 355 | used += size |
| 356 | return nil |
| 357 | }); err != nil { |
| 358 | return fmt.Errorf("cannot measure the object store to check its quota: %w", err) |
| 359 | } |
| 360 | var add int64 |
| 361 | for _, u := range parts { |
| 362 | if !w.LFS.Has(repo, u.oid) { |
| 363 | add += u.size |
| 364 | } |
| 365 | } |
| 366 | if used+add > w.Cfg.RepoMaxLFSBytes { |
| 367 | return fmt.Errorf("this repository's files take %s and this upload adds %s, over the %s limit; raise repo_max_lfs_bytes, remove a release, or attach with the CLI", |
| 368 | format.Bytes(used), format.Bytes(add), format.Bytes(w.Cfg.RepoMaxLFSBytes)) |
| 369 | } |
| 370 | return nil |
| 371 | } |
| 372 | |
| 373 | // storeAttach copies one spooled file into the store. The store re-hashes as it |
| 374 | // copies, so a spool file that changed after it was measured fails here rather |
| 375 | // than publishing a wrong checksum. |
| 376 | func (w *Web) storeAttach(repo string, u upload, art metadata.Artifact) error { |
| 377 | f, err := os.Open(u.temp) |
| 378 | if err != nil { |
| 379 | return err |
| 380 | } |
| 381 | defer f.Close() |
| 382 | _, _, err = w.LFS.Put(repo, art.OID, art.Size, f) |
| 383 | return err |
| 384 | } |
| 385 |