| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "compress/zlib" |
| 6 | "context" |
| 7 | "crypto/sha1" |
| 8 | "crypto/sha256" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "path/filepath" |
| 17 | "slices" |
| 18 | "sort" |
| 19 | "strings" |
| 20 | |
| 21 | "the-valley/webui/export" |
| 22 | ) |
| 23 | |
| 24 | // readAttempts is how many times a pass reads the valley before it gives |
| 25 | // up on inputs that keep changing under it. |
| 26 | const readAttempts = 3 |
| 27 | |
| 28 | // The bounds on what a pass holds of a program's output. A program that |
| 29 | // prints more than its bound to stdout fails, and what it prints to stderr |
| 30 | // past its bound is dropped. |
| 31 | const ( |
| 32 | maxValleyOutput = 64 << 20 |
| 33 | maxGitOutput = 4 << 20 |
| 34 | maxStderr = 64 << 10 |
| 35 | ) |
| 36 | |
| 37 | // reading is what a pass read: the export, each exported project's mirror, |
| 38 | // and the projects it keeps private. |
| 39 | type reading struct { |
| 40 | export *export.Export |
| 41 | json []byte |
| 42 | mirrors map[string]string |
| 43 | private []string |
| 44 | } |
| 45 | |
| 46 | // collect reads the valley and builds the export. It fetches the instance |
| 47 | // repository once, and every read of the pass reads the instance at that |
| 48 | // fetch. Each knot's detail is read after the plan, so a write to the graph |
| 49 | // in between makes the two disagree; export.Build says so with |
| 50 | // ErrInconsistent, and collect reads everything again. |
| 51 | func (p *publisher) collect(ctx context.Context) (*reading, error) { |
| 52 | if err := checkSchema(ctx, p.cfg.schema); err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | inst, err := p.fetchInstance(ctx) |
| 56 | if err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | if err := p.prepareCLICaches(ctx, inst.projects); err != nil { |
| 60 | return nil, err |
| 61 | } |
| 62 | if err := p.preparePointer(ctx); err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | for attempt := 1; attempt <= readAttempts; attempt++ { |
| 66 | var r *reading |
| 67 | r, err = p.read(ctx, inst) |
| 68 | if err == nil { |
| 69 | return r, nil |
| 70 | } |
| 71 | if !errors.Is(err, export.ErrInconsistent) { |
| 72 | return nil, err |
| 73 | } |
| 74 | p.warn("%v; reading the valley again", err) |
| 75 | } |
| 76 | return nil, fmt.Errorf("the valley changed under every one of %d reads: %w", readAttempts, err) |
| 77 | } |
| 78 | |
| 79 | // planListing and pendingListing are what the publisher reads of the |
| 80 | // valley's JSON itself: which projects there are, each project's knots, |
| 81 | // and where each can be read. export.Build reads the rest. |
| 82 | type ( |
| 83 | planListing struct { |
| 84 | Projects []struct { |
| 85 | Project string `json:"project"` |
| 86 | Knots []struct { |
| 87 | ID string `json:"id"` |
| 88 | } `json:"knots"` |
| 89 | } `json:"projects"` |
| 90 | } |
| 91 | pendingListing struct { |
| 92 | Repos []pendingRepo `json:"repos"` |
| 93 | } |
| 94 | pendingRepo struct { |
| 95 | Repo string `json:"repo"` |
| 96 | URL string `json:"url"` |
| 97 | Error *string `json:"error"` |
| 98 | } |
| 99 | ) |
| 100 | |
| 101 | // read is one read of the valley, with the instance as fetchInstance read |
| 102 | // it. A project is private when the instance does not allow it, or when its |
| 103 | // own declaration is missing, invalid or private. Any other failure to read |
| 104 | // a project the instance allows ends the pass: an export without it would |
| 105 | // take it off the web. |
| 106 | func (p *publisher) read(ctx context.Context, inst instanceRead) (*reading, error) { |
| 107 | allowed := map[string]bool{} |
| 108 | decl, err := readDeclaration(ctx, p.origin, inst.tip, p.cfg.schema) |
| 109 | var bad *invalidDeclaration |
| 110 | switch { |
| 111 | case errors.Is(err, errNoDeclaration): |
| 112 | case errors.As(err, &bad): |
| 113 | p.warn("the instance's policy/web at %s is not a valid declaration, so every project is private: %v", short(inst.tip), err) |
| 114 | case err != nil: |
| 115 | return nil, fmt.Errorf("could not read the instance's policy/web at %s: %w", short(inst.tip), err) |
| 116 | case decl.Instance != nil: |
| 117 | for name, d := range decl.Instance.Projects { |
| 118 | allowed[name] = d.Visibility == string(export.Public) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | planJSON, err := p.valley(ctx, p.pointer, "plan", "--all", "--json") |
| 123 | if err != nil { |
| 124 | return nil, err |
| 125 | } |
| 126 | pendingJSON, err := p.valley(ctx, p.pointer, "pending", "--all", "--json") |
| 127 | if err != nil { |
| 128 | return nil, err |
| 129 | } |
| 130 | var plan planListing |
| 131 | if err := json.Unmarshal(planJSON, &plan); err != nil { |
| 132 | return nil, fmt.Errorf("valley plan --all --json: %w", err) |
| 133 | } |
| 134 | var pending pendingListing |
| 135 | if err := json.Unmarshal(pendingJSON, &pending); err != nil { |
| 136 | return nil, fmt.Errorf("valley pending --all --json: %w", err) |
| 137 | } |
| 138 | // The CLI lists what the instance repository publishes, and nothing |
| 139 | // else. When discovery fails it lists the repository it runs in alone, |
| 140 | // which would publish an export without the other projects. |
| 141 | var planned, listed []string |
| 142 | for _, proj := range plan.Projects { |
| 143 | planned = append(planned, proj.Project) |
| 144 | } |
| 145 | repos := map[string]pendingRepo{} |
| 146 | for _, r := range pending.Repos { |
| 147 | listed = append(listed, r.Repo) |
| 148 | repos[r.Repo] = r |
| 149 | } |
| 150 | for _, l := range []struct { |
| 151 | command string |
| 152 | names []string |
| 153 | }{{"valley plan --all", planned}, {"valley pending --all", listed}} { |
| 154 | sort.Strings(l.names) |
| 155 | if !slices.Equal(l.names, inst.projects) { |
| 156 | return nil, fmt.Errorf("%s lists %s, and the instance repository publishes %s at %s, so nothing is published", |
| 157 | l.command, listNames(l.names), listNames(inst.projects), projectsRef) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | r := &reading{mirrors: map[string]string{}} |
| 162 | in := export.Inputs{ |
| 163 | Plan: planJSON, Pending: pendingJSON, |
| 164 | Visibility: map[string]export.Visibility{}, SourceTips: map[string]string{}, |
| 165 | Principals: p.principals, |
| 166 | } |
| 167 | for _, proj := range plan.Projects { |
| 168 | name := proj.Project |
| 169 | public := false |
| 170 | if allowed[name] { |
| 171 | if public, err = p.projectVisibility(ctx, name, repos[name], in.SourceTips, r.mirrors); err != nil { |
| 172 | return nil, err |
| 173 | } |
| 174 | } |
| 175 | if !public { |
| 176 | r.private = append(r.private, name) |
| 177 | continue |
| 178 | } |
| 179 | in.Visibility[name] = export.Public |
| 180 | for _, k := range proj.Knots { |
| 181 | detail, err := p.valley(ctx, p.origin, "knot", "show", "--project", name, k.ID, "--json") |
| 182 | if err != nil { |
| 183 | return nil, err |
| 184 | } |
| 185 | in.Details = append(in.Details, detail) |
| 186 | } |
| 187 | } |
| 188 | sort.Strings(r.private) |
| 189 | if r.export, err = export.Build(in); err != nil { |
| 190 | return nil, err |
| 191 | } |
| 192 | if r.json, err = r.export.Encode(); err != nil { |
| 193 | return nil, err |
| 194 | } |
| 195 | return r, nil |
| 196 | } |
| 197 | |
| 198 | // listNames is a list of projects for a message. |
| 199 | func listNames(list []string) string { |
| 200 | if len(list) == 0 { |
| 201 | return "none" |
| 202 | } |
| 203 | return strings.Join(list, ", ") |
| 204 | } |
| 205 | |
| 206 | // projectVisibility decides whether a project the instance allows is |
| 207 | // public: its own policy/web on main says public. For a public project it |
| 208 | // records main's tip and the mirror it was fetched into. A project with no |
| 209 | // main, or whose declaration is missing, invalid or private, is private, |
| 210 | // and an invalid declaration is said. A project that cannot be read is an |
| 211 | // error. |
| 212 | func (p *publisher) projectVisibility(ctx context.Context, name string, repo pendingRepo, |
| 213 | tips, mirrors map[string]string) (bool, error) { |
| 214 | if !export.ValidName(name) { |
| 215 | p.warn("%q is not a project name, so it is private", name) |
| 216 | return false, nil |
| 217 | } |
| 218 | if repo.Error != nil { |
| 219 | return false, fmt.Errorf("%s: the pending listing could not read it: %s", name, *repo.Error) |
| 220 | } |
| 221 | if repo.URL == "" { |
| 222 | return false, fmt.Errorf("%s: the pending listing gives no URL to read it from", name) |
| 223 | } |
| 224 | mirror, tip, err := p.fetchMain(ctx, name, repo.URL) |
| 225 | if errors.Is(err, errNoMain) { |
| 226 | return false, nil |
| 227 | } |
| 228 | if err != nil { |
| 229 | return false, fmt.Errorf("%s: could not read main: %w", name, err) |
| 230 | } |
| 231 | decl, err := readDeclaration(ctx, mirror, tip, p.cfg.schema) |
| 232 | var bad *invalidDeclaration |
| 233 | switch { |
| 234 | case errors.Is(err, errNoDeclaration): |
| 235 | return false, nil |
| 236 | case errors.As(err, &bad): |
| 237 | p.warn("%s: its policy/web at %s is not a valid declaration, so it is private: %v", name, short(tip), err) |
| 238 | return false, nil |
| 239 | case err != nil: |
| 240 | return false, fmt.Errorf("%s: could not read its policy/web at %s: %w", name, short(tip), err) |
| 241 | case decl.Project == nil || decl.Project.Visibility != string(export.Public): |
| 242 | return false, nil |
| 243 | } |
| 244 | tips[name], mirrors[name] = tip, mirror |
| 245 | return true, nil |
| 246 | } |
| 247 | |
| 248 | // preparePointer makes the repository valley plan and valley pending run |
| 249 | // in: a bare repository whose origin is itself, and whose main holds one |
| 250 | // file, policy/valley, naming the instance repository. The CLI finds the |
| 251 | // instance at policy/valley on origin's main, as it does from any project, |
| 252 | // and follows it no further. So it reads the projects and the signers the |
| 253 | // instance repository publishes, and never reads the instance repository's |
| 254 | // main, where a policy/valley could land and be taken away again while the |
| 255 | // pass reads. Only the publisher writes to this repository, and main's |
| 256 | // commit is the same in every pass for the same --instance-repo. |
| 257 | func (p *publisher) preparePointer(ctx context.Context) error { |
| 258 | files, err := sharedFiles(ctx, p.cfg.instanceRepo, nil) |
| 259 | if err != nil { |
| 260 | return err |
| 261 | } |
| 262 | // Build the four small Git objects in memory so their compressed sizes |
| 263 | // are known before any cache file is written. |
| 264 | object := func(kind string, data []byte) []byte { |
| 265 | raw := append([]byte(fmt.Sprintf("%s %d\x00", kind, len(data))), data...) |
| 266 | h := sha1.New() |
| 267 | if strings.Contains(files["config"], "objectformat = sha256") { |
| 268 | h = sha256.New() |
| 269 | } |
| 270 | h.Write(raw) |
| 271 | digest := h.Sum(nil) |
| 272 | name := hex.EncodeToString(digest) |
| 273 | var compressed bytes.Buffer |
| 274 | w := zlib.NewWriter(&compressed) |
| 275 | _, _ = w.Write(raw) |
| 276 | _ = w.Close() |
| 277 | files["objects/"+name[:2]+"/"+name[2:]] = compressed.String() |
| 278 | return digest |
| 279 | } |
| 280 | blob := object("blob", []byte(p.cfg.instanceRepo+"\n")) |
| 281 | policy := object("tree", append([]byte("100644 valley\x00"), blob...)) |
| 282 | tree := object("tree", append([]byte("40000 policy\x00"), policy...)) |
| 283 | commit := object("commit", []byte(fmt.Sprintf("tree %x\nauthor valley-web-publish <operator@example.org> 0 +0000\ncommitter valley-web-publish <operator@example.org> 0 +0000\n\npolicy/valley: the instance the publisher reads\n", tree))) |
| 284 | files["refs/heads/main"] = hex.EncodeToString(commit) + "\n" |
| 285 | files["config"] = strings.Replace(files["config"], quoteGit(p.cfg.instanceRepo), quoteGit(p.pointer), 1) |
| 286 | return p.stageFiles(p.pointer, files) |
| 287 | } |
| 288 | |
| 289 | // prepareCLICaches uses the CLI's URL hash and .git layout (status/list.go). |
| 290 | // Both the project and instance objects are borrowed: the CLI reads the |
| 291 | // instance's signers while inspecting each project's records. |
| 292 | func (p *publisher) prepareCLICaches(ctx context.Context, names []string) error { |
| 293 | instance, err := sharedFiles(ctx, p.cfg.instanceRepo, nil) |
| 294 | if err != nil { |
| 295 | return err |
| 296 | } |
| 297 | reposDir := p.cliReposDir() |
| 298 | if err := os.MkdirAll(reposDir, 0o700); err != nil { |
| 299 | return err |
| 300 | } |
| 301 | // A killed pass may leave the parent sealed. Only the publisher |
| 302 | // stages repositories; the CLI may only use the current staged set. |
| 303 | if err := os.Chmod(reposDir, 0o700); err != nil { |
| 304 | return err |
| 305 | } |
| 306 | urls := make(map[string]string, len(names)) |
| 307 | staged := make(map[string]bool, len(names)) |
| 308 | for _, name := range names { |
| 309 | if !export.ValidName(name) { |
| 310 | return fmt.Errorf("invalid project name %q", name) |
| 311 | } |
| 312 | u := strings.TrimRight(p.cfg.instanceRepo, "/") |
| 313 | cut := strings.LastIndex(u, "/") + 1 |
| 314 | suffix := "" |
| 315 | if strings.HasSuffix(u[cut:], ".git") { |
| 316 | suffix = ".git" |
| 317 | } |
| 318 | url := u[:cut] + name + suffix |
| 319 | urls[name] = url |
| 320 | sum := sha256.Sum256([]byte(url)) |
| 321 | staged[hex.EncodeToString(sum[:8])+"-"+name] = true |
| 322 | } |
| 323 | entries, err := os.ReadDir(reposDir) |
| 324 | if err != nil { |
| 325 | return err |
| 326 | } |
| 327 | for _, entry := range entries { |
| 328 | if !staged[entry.Name()] { |
| 329 | if err := os.RemoveAll(filepath.Join(reposDir, entry.Name())); err != nil { |
| 330 | return err |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | for _, name := range names { |
| 335 | url := urls[name] |
| 336 | files, err := sharedFiles(ctx, url, nil) |
| 337 | if err != nil { |
| 338 | return fmt.Errorf("%s: could not prepare CLI cache: %w", name, err) |
| 339 | } |
| 340 | files["config"] = strings.Replace(files["config"], "bare = true", "bare = false", 1) + "[core]\n\tlogallrefupdates = false\n" |
| 341 | files["objects/info/alternates"] += instance["objects/info/alternates"] |
| 342 | wrapped := map[string]string{} |
| 343 | for path, data := range files { |
| 344 | wrapped[".git/"+path] = data |
| 345 | } |
| 346 | sum := sha256.Sum256([]byte(url)) |
| 347 | dir := filepath.Join(reposDir, hex.EncodeToString(sum[:8])+"-"+name) |
| 348 | if err := p.stageFiles(dir, wrapped); err != nil { |
| 349 | return err |
| 350 | } |
| 351 | } |
| 352 | // Each CLI cache can write main and its lock file. Leave room for |
| 353 | // those bounded metadata writes before invoking any collection command. |
| 354 | p.collectionRoom = int64(len(names)+1) * 4096 |
| 355 | return p.reserveStorage(p.collectionRoom) |
| 356 | } |
| 357 | |
| 358 | func (p *publisher) cliReposDir() string { |
| 359 | return filepath.Join(filepath.Dir(p.cache), "valley", "repos") |
| 360 | } |
| 361 | |
| 362 | // The instance repository's project list, and where the publisher's |
| 363 | // repository keeps what it fetched of the instance. |
| 364 | const ( |
| 365 | projectsRef = "refs/the-valley/projects" |
| 366 | originMain = "refs/remotes/origin/main" |
| 367 | originProjects = "refs/remotes/origin/projects" |
| 368 | ) |
| 369 | |
| 370 | // instanceRead is the instance repository as a pass found it: main's tip, |
| 371 | // the project list it publishes, and the projects that list names. |
| 372 | type instanceRead struct { |
| 373 | tip, list string |
| 374 | projects []string |
| 375 | } |
| 376 | |
| 377 | // fetchInstance fetches the instance repository's main and its project |
| 378 | // list into the publisher's repository, once a pass. A repository whose |
| 379 | // main carries no policy/instance is not an instance repository. One whose |
| 380 | // main carries policy/valley is refused too: it names another instance as |
| 381 | // its own. |
| 382 | func (p *publisher) fetchInstance(ctx context.Context) (instanceRead, error) { |
| 383 | var r instanceRead |
| 384 | if err := p.shareRepository(ctx, p.origin, p.cfg.instanceRepo, map[string]string{ |
| 385 | originMain: "refs/heads/main", originProjects: projectsRef, |
| 386 | }); err != nil { |
| 387 | return r, fmt.Errorf("could not read main and %s in the instance repository: %w", projectsRef, err) |
| 388 | } |
| 389 | var err error |
| 390 | if r.tip, err = revParse(ctx, p.origin, originMain+"^{commit}"); err != nil { |
| 391 | return r, err |
| 392 | } |
| 393 | if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/instance"); err != nil { |
| 394 | return r, fmt.Errorf("%s holds no policy/instance on main, so it is not an instance repository", p.cfg.instanceRepo) |
| 395 | } |
| 396 | if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/valley"); err == nil { |
| 397 | return r, fmt.Errorf("%s holds policy/valley on main, which names another instance; an instance repository the publisher reads holds policy/instance and no policy/valley", p.cfg.instanceRepo) |
| 398 | } |
| 399 | if r.list, err = revParse(ctx, p.origin, originProjects); err != nil { |
| 400 | return r, err |
| 401 | } |
| 402 | list, err := git(ctx, p.origin, "cat-file", "blob", r.list) |
| 403 | if err != nil { |
| 404 | return r, fmt.Errorf("%s in the instance repository is not a list of projects: %w", projectsRef, err) |
| 405 | } |
| 406 | for _, name := range strings.Split(string(list), "\n") { |
| 407 | if name != "" { |
| 408 | r.projects = append(r.projects, name) |
| 409 | } |
| 410 | } |
| 411 | sort.Strings(r.projects) |
| 412 | return r, nil |
| 413 | } |
| 414 | |
| 415 | // errNoMain is fetchMain's error for a project with no main. |
| 416 | var errNoMain = errors.New("no main") |
| 417 | |
| 418 | // fetchMain reads main into a cache that borrows the local repository's |
| 419 | // objects. Borrowing keeps repository history outside the storage budget: |
| 420 | // the publisher can read the host's objects but cannot write them. |
| 421 | func (p *publisher) fetchMain(ctx context.Context, name, url string) (string, string, error) { |
| 422 | if !filepath.IsAbs(url) { |
| 423 | return "", "", fmt.Errorf("repository must be an absolute local path: %q", url) |
| 424 | } |
| 425 | heads, err := git(ctx, url, "ls-remote", "--end-of-options", url, "refs/heads/main") |
| 426 | if err != nil { |
| 427 | return "", "", err |
| 428 | } |
| 429 | if !listsRef(heads, "refs/heads/main") { |
| 430 | return "", "", errNoMain |
| 431 | } |
| 432 | |
| 433 | mirror := filepath.Join(p.cache, "repos", name+".git") |
| 434 | if err := p.shareRepository(ctx, mirror, url, map[string]string{"refs/heads/main": "refs/heads/main"}); err != nil { |
| 435 | return "", "", err |
| 436 | } |
| 437 | tip, err := revParse(ctx, mirror, "refs/heads/main^{commit}") |
| 438 | return mirror, tip, err |
| 439 | } |
| 440 | |
| 441 | // shareRepository replaces a disposable cache with refs and an alternate. |
| 442 | // No fetch transport runs, so even objects added concurrently cannot be |
| 443 | // copied. All bytes to be written are known before staging starts. Old |
| 444 | // caches remain counted until the replacement is complete. |
| 445 | func (p *publisher) shareRepository(ctx context.Context, dir, source string, refs map[string]string) error { |
| 446 | files, err := sharedFiles(ctx, source, refs) |
| 447 | if err != nil { |
| 448 | return err |
| 449 | } |
| 450 | return p.stageFiles(dir, files) |
| 451 | } |
| 452 | |
| 453 | func quoteGit(s string) string { |
| 454 | return strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "\t", "\\t").Replace(s) |
| 455 | } |
| 456 | |
| 457 | func sharedFiles(ctx context.Context, source string, refs map[string]string) (map[string]string, error) { |
| 458 | if !filepath.IsAbs(source) || strings.ContainsAny(source, "\n\r") { |
| 459 | return nil, fmt.Errorf("repository must be an absolute local path: %q", source) |
| 460 | } |
| 461 | objects, err := git(ctx, source, "rev-parse", "--path-format=absolute", "--git-path", "objects") |
| 462 | if err != nil { |
| 463 | return nil, err |
| 464 | } |
| 465 | format, err := git(ctx, source, "rev-parse", "--show-object-format") |
| 466 | if err != nil { |
| 467 | return nil, err |
| 468 | } |
| 469 | config := "[core]\n\tbare = true\n\trepositoryformatversion = 0\n" |
| 470 | switch strings.TrimSpace(string(format)) { |
| 471 | case "sha1": |
| 472 | case "sha256": |
| 473 | config = "[core]\n\tbare = true\n\trepositoryformatversion = 1\n[extensions]\n\tobjectformat = sha256\n" |
| 474 | default: |
| 475 | return nil, fmt.Errorf("unsupported object format %q", format) |
| 476 | } |
| 477 | quoted := quoteGit(source) |
| 478 | config += "[remote \"origin\"]\n\turl = \"" + quoted + "\"\n" |
| 479 | files := map[string]string{ |
| 480 | "HEAD": "ref: refs/heads/main\n", "config": config, |
| 481 | "objects/info/alternates": strings.TrimSpace(string(objects)) + "\n", |
| 482 | } |
| 483 | for dest, ref := range refs { |
| 484 | tip, err := revParse(ctx, source, ref) |
| 485 | if err != nil { |
| 486 | return nil, err |
| 487 | } |
| 488 | files[dest] = tip + "\n" |
| 489 | } |
| 490 | return files, nil |
| 491 | } |
| 492 | |
| 493 | func (p *publisher) reserveStorage(added int64) error { |
| 494 | used, err := p.storageUsed() |
| 495 | if err != nil { |
| 496 | return err |
| 497 | } |
| 498 | if used > int64(p.cfg.maxStorage)-added { |
| 499 | return p.overStorage(used + added) |
| 500 | } |
| 501 | return nil |
| 502 | } |
| 503 | |
| 504 | func (p *publisher) stageFiles(dir string, files map[string]string) error { |
| 505 | used, err := p.storageUsed() |
| 506 | if err != nil { |
| 507 | return err |
| 508 | } |
| 509 | var added int64 |
| 510 | for _, content := range files { |
| 511 | added += int64(len(content)) |
| 512 | } |
| 513 | if used > int64(p.cfg.maxStorage)-added { |
| 514 | return p.overStorage(used + added) |
| 515 | } |
| 516 | if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil { |
| 517 | return err |
| 518 | } |
| 519 | stage, err := os.MkdirTemp(filepath.Dir(dir), ".shared-") |
| 520 | if err != nil { |
| 521 | return err |
| 522 | } |
| 523 | defer os.RemoveAll(stage) |
| 524 | prefix := stage |
| 525 | if _, ok := files[".git/HEAD"]; ok { |
| 526 | prefix = filepath.Join(stage, ".git") |
| 527 | } |
| 528 | if err := os.MkdirAll(filepath.Join(prefix, "refs"), 0o700); err != nil { |
| 529 | return err |
| 530 | } |
| 531 | for name, content := range files { |
| 532 | path := filepath.Join(stage, name) |
| 533 | if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| 534 | return err |
| 535 | } |
| 536 | if err := os.WriteFile(path, []byte(content), 0o600); err != nil { |
| 537 | return err |
| 538 | } |
| 539 | } |
| 540 | if err := p.checkStorage(); err != nil { |
| 541 | return err |
| 542 | } |
| 543 | if err := os.RemoveAll(dir); err != nil { |
| 544 | return err |
| 545 | } |
| 546 | return os.Rename(stage, dir) |
| 547 | } |
| 548 | |
| 549 | // listsRef reports whether ls-remote's output lists the ref. ls-remote |
| 550 | // matches a pattern against the tail of a ref name, so each name listed |
| 551 | // is compared whole. |
| 552 | func listsRef(out []byte, ref string) bool { |
| 553 | for _, line := range strings.Split(string(out), "\n") { |
| 554 | if _, name, ok := strings.Cut(line, "\t"); ok && name == ref { |
| 555 | return true |
| 556 | } |
| 557 | } |
| 558 | return false |
| 559 | } |
| 560 | |
| 561 | func revParse(ctx context.Context, repo, rev string) (string, error) { |
| 562 | out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", rev) |
| 563 | if err != nil { |
| 564 | return "", err |
| 565 | } |
| 566 | return strings.TrimSpace(string(out)), nil |
| 567 | } |
| 568 | |
| 569 | // valley runs one of the CLI's JSON commands in dir, one of the |
| 570 | // publisher's repositories, and returns what it printed, up to |
| 571 | // maxValleyOutput. What it says on stderr is passed on. |
| 572 | func (p *publisher) valley(ctx context.Context, dir string, args ...string) ([]byte, error) { |
| 573 | if err := p.reserveStorage(p.collectionRoom); err != nil { |
| 574 | return nil, err |
| 575 | } |
| 576 | // Discovery can see a newly listed project, and knot details can name |
| 577 | // an unlisted project. Deny creation in the parent before either can |
| 578 | // make an unshared cache and fetch objects. Staged .git directories |
| 579 | // remain writable for their bounded ref updates. |
| 580 | reposDir := p.cliReposDir() |
| 581 | if err := os.Chmod(reposDir, 0o500); err != nil { |
| 582 | return nil, err |
| 583 | } |
| 584 | defer os.Chmod(reposDir, 0o700) |
| 585 | cmd := exec.CommandContext(ctx, "valley", args...) |
| 586 | cmd.Dir = dir |
| 587 | cmd.Env = valleyEnvironment(os.Environ()) |
| 588 | stdout := &bounded{max: maxValleyOutput, strict: true} |
| 589 | cmd.Stdout = stdout |
| 590 | cmd.Stderr = p.stderr |
| 591 | err := cmd.Run() |
| 592 | if budget := p.checkStorage(); budget != nil { |
| 593 | return nil, budget |
| 594 | } |
| 595 | if stdout.over { |
| 596 | return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), errTooLong) |
| 597 | } |
| 598 | if err != nil { |
| 599 | return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), err) |
| 600 | } |
| 601 | return stdout.Bytes(), nil |
| 602 | } |
| 603 | |
| 604 | // valleyEnvironment is the environment the valley CLI runs in: the |
| 605 | // caller's, without the variables that would point git at another |
| 606 | // repository, and without the ones that would give the CLI verification |
| 607 | // material of their own. The CLI then reads the signers the host publishes, |
| 608 | // as it reads the projects. |
| 609 | func valleyEnvironment(environ []string) []string { |
| 610 | var env []string |
| 611 | for _, kv := range environ { |
| 612 | name, _, _ := strings.Cut(kv, "=") |
| 613 | if redirectsGit(name) || name == "VALLEY_KNOWN_SIGNERS" || name == "VALLEY_INTEGRATOR_SIGNER" { |
| 614 | continue |
| 615 | } |
| 616 | env = append(env, kv) |
| 617 | } |
| 618 | return env |
| 619 | } |
| 620 | |
| 621 | // git runs git in repo, unless it is "", and returns what it printed, up |
| 622 | // to maxGitOutput. |
| 623 | func git(ctx context.Context, repo string, args ...string) ([]byte, error) { |
| 624 | return gitInput(ctx, repo, "", args...) |
| 625 | } |
| 626 | |
| 627 | // gitInput is git with input on its stdin. With no input, stdin is the |
| 628 | // null device. |
| 629 | func gitInput(ctx context.Context, repo, input string, args ...string) ([]byte, error) { |
| 630 | var stdin io.Reader |
| 631 | if input != "" { |
| 632 | stdin = strings.NewReader(input) |
| 633 | } |
| 634 | stdout := &bounded{max: maxGitOutput, strict: true} |
| 635 | err := gitStream(ctx, repo, stdin, stdout, args...) |
| 636 | if stdout.over { |
| 637 | return nil, fmt.Errorf("git %s: %w", gitVerb(args), errTooLong) |
| 638 | } |
| 639 | if err != nil { |
| 640 | return nil, err |
| 641 | } |
| 642 | return stdout.Bytes(), nil |
| 643 | } |
| 644 | |
| 645 | // gitStream runs git in repo, unless it is "", with stdin and stdout |
| 646 | // given: with replacement refs off, git held to the transports a URL from |
| 647 | // data may use, no prompt, and a fixed date for any commit it writes. It |
| 648 | // keeps the caller's GIT_CONFIG_* variables, which carry the |
| 649 | // safe.directory entries a host gives the publisher for repositories it |
| 650 | // does not own. |
| 651 | func gitStream(ctx context.Context, repo string, stdin io.Reader, stdout io.Writer, args ...string) error { |
| 652 | if repo != "" { |
| 653 | args = append([]string{"-C", repo}, args...) |
| 654 | } |
| 655 | cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects"}, args...)...) |
| 656 | cmd.Env = gitEnvironment(os.Environ()) |
| 657 | stderr := &bounded{max: maxStderr} |
| 658 | cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr |
| 659 | if err := cmd.Run(); err != nil { |
| 660 | return fmt.Errorf("git %s: %w: %s", gitVerb(args), err, strings.TrimSpace(stderr.String())) |
| 661 | } |
| 662 | return nil |
| 663 | } |
| 664 | |
| 665 | // gitVerb is the git command args run, for messages: the first argument |
| 666 | // after -C and the options git takes before its command. |
| 667 | func gitVerb(args []string) string { |
| 668 | for i := 0; i < len(args); i++ { |
| 669 | switch args[i] { |
| 670 | case "-C", "-c": |
| 671 | i++ |
| 672 | default: |
| 673 | return args[i] |
| 674 | } |
| 675 | } |
| 676 | return "git" |
| 677 | } |
| 678 | |
| 679 | // errTooLong is the error for a program that printed more than its bound. |
| 680 | var errTooLong = errors.New("it printed more than the publisher holds of it") |
| 681 | |
| 682 | // bounded holds what a program prints, up to max bytes. Past max, a write |
| 683 | // fails when strict is set, which ends the program at its next write, and |
| 684 | // is dropped when it is not. It is no io.ReaderFrom, so os/exec copies |
| 685 | // through Write. |
| 686 | type bounded struct { |
| 687 | buf bytes.Buffer |
| 688 | max int |
| 689 | strict bool |
| 690 | over bool |
| 691 | } |
| 692 | |
| 693 | func (b *bounded) Write(p []byte) (int, error) { |
| 694 | room := max(b.max-b.buf.Len(), 0) |
| 695 | if len(p) <= room { |
| 696 | return b.buf.Write(p) |
| 697 | } |
| 698 | b.over = true |
| 699 | b.buf.Write(p[:room]) |
| 700 | if b.strict { |
| 701 | return room, errTooLong |
| 702 | } |
| 703 | return len(p), nil |
| 704 | } |
| 705 | |
| 706 | func (b *bounded) Bytes() []byte { return b.buf.Bytes() } |
| 707 | func (b *bounded) String() string { return b.buf.String() } |
| 708 | |
| 709 | func gitEnvironment(environ []string) []string { |
| 710 | var env []string |
| 711 | for _, kv := range environ { |
| 712 | name, _, _ := strings.Cut(kv, "=") |
| 713 | switch { |
| 714 | case redirectsGit(name), name == "GIT_ALLOW_PROTOCOL", name == "GIT_TERMINAL_PROMPT", |
| 715 | name == "GIT_AUTHOR_DATE", name == "GIT_COMMITTER_DATE": |
| 716 | continue |
| 717 | } |
| 718 | env = append(env, kv) |
| 719 | } |
| 720 | return append(env, |
| 721 | "GIT_ALLOW_PROTOCOL=ssh:git:https:file", |
| 722 | "GIT_TERMINAL_PROMPT=0", |
| 723 | "GIT_NO_REPLACE_OBJECTS=1", |
| 724 | "GIT_AUTHOR_DATE=@0 +0000", |
| 725 | "GIT_COMMITTER_DATE=@0 +0000", |
| 726 | ) |
| 727 | } |
| 728 | |
| 729 | // redirectsGit reports whether the variable points git at another |
| 730 | // repository, another object store or another work tree than the one it |
| 731 | // is run in. |
| 732 | func redirectsGit(name string) bool { |
| 733 | switch name { |
| 734 | case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX", |
| 735 | "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES": |
| 736 | return true |
| 737 | } |
| 738 | return false |
| 739 | } |
| 740 | |
| 741 | // readPrincipals reads the display mapping: a JSON object from principal |
| 742 | // names to the names an export shows. No file is an empty mapping, under |
| 743 | // which every principal is shown as export.Unmapped. |
| 744 | func readPrincipals(path string) (export.Principals, error) { |
| 745 | if path == "" { |
| 746 | return export.Principals{}, nil |
| 747 | } |
| 748 | data, err := os.ReadFile(path) |
| 749 | if err != nil { |
| 750 | return nil, err |
| 751 | } |
| 752 | dec := json.NewDecoder(bytes.NewReader(data)) |
| 753 | var m export.Principals |
| 754 | if err := dec.Decode(&m); err != nil { |
| 755 | return nil, fmt.Errorf("the display mapping %s is not a JSON object of names: %w", path, err) |
| 756 | } |
| 757 | if err := dec.Decode(&json.RawMessage{}); err != io.EOF { |
| 758 | return nil, fmt.Errorf("the display mapping %s holds more than its one object", path) |
| 759 | } |
| 760 | if m == nil { |
| 761 | m = export.Principals{} |
| 762 | } |
| 763 | return m, nil |
| 764 | } |