| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | |
| 16 | "the-valley/webui/export" |
| 17 | ) |
| 18 | |
| 19 | // readAttempts is how many times a pass reads the valley before it gives |
| 20 | // up on inputs that keep changing under it. |
| 21 | const readAttempts = 3 |
| 22 | |
| 23 | // reading is what a pass read: the export, each exported project's mirror, |
| 24 | // and the projects it keeps private. |
| 25 | type reading struct { |
| 26 | export *export.Export |
| 27 | json []byte |
| 28 | mirrors map[string]string |
| 29 | private []string |
| 30 | } |
| 31 | |
| 32 | // collect reads the valley and builds the export. Each knot's detail is |
| 33 | // read after the plan, so a write to the graph in between makes the two |
| 34 | // disagree; export.Build says so with ErrInconsistent, and collect reads |
| 35 | // everything again. |
| 36 | func (p *publisher) collect(ctx context.Context) (*reading, error) { |
| 37 | if err := p.prepareOrigin(ctx); err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | var err error |
| 41 | for attempt := 1; attempt <= readAttempts; attempt++ { |
| 42 | var r *reading |
| 43 | r, err = p.read(ctx) |
| 44 | if err == nil { |
| 45 | return r, nil |
| 46 | } |
| 47 | if !errors.Is(err, export.ErrInconsistent) { |
| 48 | return nil, err |
| 49 | } |
| 50 | p.warn("%v; reading the valley again", err) |
| 51 | } |
| 52 | return nil, fmt.Errorf("the valley changed under every one of %d reads: %w", readAttempts, err) |
| 53 | } |
| 54 | |
| 55 | // planListing and pendingListing are what the publisher reads of the |
| 56 | // valley's JSON itself: which projects there are, which could be read, |
| 57 | // each project's knots and its URL. export.Build reads the rest. |
| 58 | type ( |
| 59 | planListing struct { |
| 60 | Projects []struct { |
| 61 | Project string `json:"project"` |
| 62 | Error *string `json:"error"` |
| 63 | Knots []struct { |
| 64 | ID string `json:"id"` |
| 65 | } `json:"knots"` |
| 66 | } `json:"projects"` |
| 67 | } |
| 68 | pendingListing struct { |
| 69 | Repos []struct { |
| 70 | Repo string `json:"repo"` |
| 71 | URL string `json:"url"` |
| 72 | Error *string `json:"error"` |
| 73 | } `json:"repos"` |
| 74 | } |
| 75 | ) |
| 76 | |
| 77 | // read is one read of the valley. |
| 78 | func (p *publisher) read(ctx context.Context) (*reading, error) { |
| 79 | instanceTip, err := p.fetchInstance(ctx) |
| 80 | if err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | allowed := map[string]bool{} |
| 84 | decl, err := readDeclaration(ctx, p.origin, instanceTip, p.cfg.schema) |
| 85 | switch { |
| 86 | case errors.Is(err, errNoDeclaration): |
| 87 | case err != nil && ctx.Err() != nil: |
| 88 | return nil, err |
| 89 | case err != nil: |
| 90 | p.warn("the instance's policy/web at %s is not a valid declaration, so every project is private: %v", short(instanceTip), err) |
| 91 | case decl.Instance != nil: |
| 92 | for name, d := range decl.Instance.Projects { |
| 93 | allowed[name] = d.Visibility == string(export.Public) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | planJSON, err := p.valley(ctx, "plan", "--all", "--json") |
| 98 | if err != nil { |
| 99 | return nil, err |
| 100 | } |
| 101 | pendingJSON, err := p.valley(ctx, "pending", "--all", "--json") |
| 102 | if err != nil { |
| 103 | return nil, err |
| 104 | } |
| 105 | var plan planListing |
| 106 | if err := json.Unmarshal(planJSON, &plan); err != nil { |
| 107 | return nil, fmt.Errorf("valley plan --all --json: %w", err) |
| 108 | } |
| 109 | var pending pendingListing |
| 110 | if err := json.Unmarshal(pendingJSON, &pending); err != nil { |
| 111 | return nil, fmt.Errorf("valley pending --all --json: %w", err) |
| 112 | } |
| 113 | urls := map[string]string{} |
| 114 | for _, r := range pending.Repos { |
| 115 | if r.Error == nil { |
| 116 | urls[r.Repo] = r.URL |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | r := &reading{mirrors: map[string]string{}} |
| 121 | in := export.Inputs{ |
| 122 | Plan: planJSON, Pending: pendingJSON, |
| 123 | Visibility: map[string]export.Visibility{}, SourceTips: map[string]string{}, |
| 124 | Principals: p.principals, |
| 125 | } |
| 126 | for _, proj := range plan.Projects { |
| 127 | name := proj.Project |
| 128 | public, err := p.projectVisibility(ctx, name, allowed[name], urls[name], in.SourceTips, r.mirrors) |
| 129 | if err != nil { |
| 130 | return nil, err |
| 131 | } |
| 132 | if !public { |
| 133 | r.private = append(r.private, name) |
| 134 | continue |
| 135 | } |
| 136 | in.Visibility[name] = export.Public |
| 137 | for _, k := range proj.Knots { |
| 138 | detail, err := p.valley(ctx, "knot", "show", "--project", name, k.ID, "--json") |
| 139 | if err != nil { |
| 140 | return nil, err |
| 141 | } |
| 142 | in.Details = append(in.Details, detail) |
| 143 | } |
| 144 | } |
| 145 | sort.Strings(r.private) |
| 146 | if r.export, err = export.Build(in); err != nil { |
| 147 | return nil, err |
| 148 | } |
| 149 | if r.json, err = r.export.Encode(); err != nil { |
| 150 | return nil, err |
| 151 | } |
| 152 | return r, nil |
| 153 | } |
| 154 | |
| 155 | // projectVisibility decides whether one project is public: the instance |
| 156 | // allows it, and its own policy/web on main says public. For a public |
| 157 | // project it records main's tip and the mirror it was fetched into. A |
| 158 | // project that cannot be read, or whose declaration is missing or invalid, |
| 159 | // is private; the reason is said when it is a fault rather than a choice. |
| 160 | func (p *publisher) projectVisibility(ctx context.Context, name string, allowed bool, url string, |
| 161 | tips, mirrors map[string]string) (bool, error) { |
| 162 | if !allowed { |
| 163 | return false, nil |
| 164 | } |
| 165 | if !export.ValidName(name) { |
| 166 | p.warn("%q is not a project name, so it is private", name) |
| 167 | return false, nil |
| 168 | } |
| 169 | if url == "" { |
| 170 | p.warn("%s: the pending listing gives no URL to read it from, so it is private", name) |
| 171 | return false, nil |
| 172 | } |
| 173 | mirror, tip, err := p.fetchMain(ctx, name, url) |
| 174 | if err != nil { |
| 175 | if ctx.Err() != nil { |
| 176 | return false, err |
| 177 | } |
| 178 | p.warn("%s: main could not be read, so it is private: %v", name, err) |
| 179 | return false, nil |
| 180 | } |
| 181 | decl, err := readDeclaration(ctx, mirror, tip, p.cfg.schema) |
| 182 | switch { |
| 183 | case errors.Is(err, errNoDeclaration): |
| 184 | return false, nil |
| 185 | case err != nil: |
| 186 | if ctx.Err() != nil { |
| 187 | return false, err |
| 188 | } |
| 189 | p.warn("%s: its policy/web at %s is not a valid declaration, so it is private: %v", name, short(tip), err) |
| 190 | return false, nil |
| 191 | case decl.Project == nil || decl.Project.Visibility != string(export.Public): |
| 192 | return false, nil |
| 193 | } |
| 194 | tips[name], mirrors[name] = tip, mirror |
| 195 | return true, nil |
| 196 | } |
| 197 | |
| 198 | // prepareOrigin makes the publisher's bare repository, with origin set to |
| 199 | // the instance repository, or sets origin again when it names another. |
| 200 | func (p *publisher) prepareOrigin(ctx context.Context) error { |
| 201 | if err := os.MkdirAll(p.cache, 0o700); err != nil { |
| 202 | return err |
| 203 | } |
| 204 | if _, err := os.Stat(filepath.Join(p.origin, "HEAD")); errors.Is(err, os.ErrNotExist) { |
| 205 | if err := os.RemoveAll(p.origin); err != nil { |
| 206 | return err |
| 207 | } |
| 208 | if _, err := git(ctx, "", "init", "--quiet", "--bare", "--template=", p.origin); err != nil { |
| 209 | return err |
| 210 | } |
| 211 | } |
| 212 | got, err := git(ctx, p.origin, "config", "--get", "remote.origin.url") |
| 213 | if err == nil && strings.TrimSpace(string(got)) == p.cfg.instanceRepo { |
| 214 | return nil |
| 215 | } |
| 216 | _, _ = git(ctx, p.origin, "remote", "remove", "origin") |
| 217 | _, err = git(ctx, p.origin, "remote", "add", "--end-of-options", "origin", p.cfg.instanceRepo) |
| 218 | return err |
| 219 | } |
| 220 | |
| 221 | // fetchInstance fetches the instance repository's main into the |
| 222 | // publisher's repository, and returns its tip. A repository whose main |
| 223 | // carries no policy/instance is not an instance repository. |
| 224 | func (p *publisher) fetchInstance(ctx context.Context) (string, error) { |
| 225 | const ref = "refs/remotes/origin/main" |
| 226 | if _, err := git(ctx, p.origin, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", |
| 227 | "origin", "+refs/heads/main:"+ref); err != nil { |
| 228 | return "", fmt.Errorf("could not read the instance repository's main: %w", err) |
| 229 | } |
| 230 | tip, err := revParse(ctx, p.origin, ref) |
| 231 | if err != nil { |
| 232 | return "", err |
| 233 | } |
| 234 | if _, err := git(ctx, p.origin, "cat-file", "-e", tip+":policy/instance"); err != nil { |
| 235 | return "", fmt.Errorf("%s holds no policy/instance on main, so it is not an instance repository", p.cfg.instanceRepo) |
| 236 | } |
| 237 | return tip, nil |
| 238 | } |
| 239 | |
| 240 | // fetchMain brings a project's main into its mirror, a bare repository |
| 241 | // under the cache that holds main alone, and returns the mirror and main's |
| 242 | // tip. A mirror is first made by a clone, so it has the project's object |
| 243 | // format, and the clone is renamed into place only once it is whole. The |
| 244 | // clone copies objects through the transport, as a fetch does, and never |
| 245 | // links the project's own files. |
| 246 | func (p *publisher) fetchMain(ctx context.Context, name, url string) (string, string, error) { |
| 247 | mirror := filepath.Join(p.cache, "repos", name+".git") |
| 248 | if _, err := os.Stat(filepath.Join(mirror, "HEAD")); err == nil { |
| 249 | if _, err := git(ctx, mirror, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", |
| 250 | "--end-of-options", url, "+refs/heads/main:refs/heads/main"); err != nil { |
| 251 | return "", "", err |
| 252 | } |
| 253 | } else { |
| 254 | if err := os.MkdirAll(filepath.Dir(mirror), 0o700); err != nil { |
| 255 | return "", "", err |
| 256 | } |
| 257 | made, err := os.MkdirTemp(filepath.Dir(mirror), "."+name+".new-") |
| 258 | if err != nil { |
| 259 | return "", "", err |
| 260 | } |
| 261 | defer os.RemoveAll(made) |
| 262 | clone := filepath.Join(made, "repo.git") |
| 263 | if _, err := git(ctx, "", "clone", "--quiet", "--bare", "--no-local", "--no-tags", "--single-branch", |
| 264 | "--branch", "main", "--template=", "--end-of-options", url, clone); err != nil { |
| 265 | return "", "", err |
| 266 | } |
| 267 | if err := os.RemoveAll(mirror); err != nil { |
| 268 | return "", "", err |
| 269 | } |
| 270 | if err := os.Rename(clone, mirror); err != nil { |
| 271 | return "", "", err |
| 272 | } |
| 273 | } |
| 274 | tip, err := revParse(ctx, mirror, "refs/heads/main") |
| 275 | return mirror, tip, err |
| 276 | } |
| 277 | |
| 278 | func revParse(ctx context.Context, repo, ref string) (string, error) { |
| 279 | out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", ref+"^{commit}") |
| 280 | if err != nil { |
| 281 | return "", err |
| 282 | } |
| 283 | return strings.TrimSpace(string(out)), nil |
| 284 | } |
| 285 | |
| 286 | // valley runs one of the CLI's JSON commands in the publisher's repository |
| 287 | // and returns what it printed. What it says on stderr is passed on. |
| 288 | func (p *publisher) valley(ctx context.Context, args ...string) ([]byte, error) { |
| 289 | cmd := exec.CommandContext(ctx, "valley", args...) |
| 290 | cmd.Dir = p.origin |
| 291 | cmd.Env = valleyEnvironment(os.Environ()) |
| 292 | var stdout bytes.Buffer |
| 293 | cmd.Stdout = &stdout |
| 294 | cmd.Stderr = p.stderr |
| 295 | if err := cmd.Run(); err != nil { |
| 296 | return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), err) |
| 297 | } |
| 298 | return stdout.Bytes(), nil |
| 299 | } |
| 300 | |
| 301 | // valleyEnvironment is the environment the valley CLI runs in: the |
| 302 | // caller's, without the variables that would point git at another |
| 303 | // repository, and without the ones that would give the CLI verification |
| 304 | // material of their own. The CLI then reads the signers the host publishes, |
| 305 | // as it reads the projects. |
| 306 | func valleyEnvironment(environ []string) []string { |
| 307 | var env []string |
| 308 | for _, kv := range environ { |
| 309 | name, _, _ := strings.Cut(kv, "=") |
| 310 | if redirectsGit(name) || name == "VALLEY_KNOWN_SIGNERS" || name == "VALLEY_INTEGRATOR_SIGNER" { |
| 311 | continue |
| 312 | } |
| 313 | env = append(env, kv) |
| 314 | } |
| 315 | return env |
| 316 | } |
| 317 | |
| 318 | // git runs git in repo, unless it is "", with replacement refs off, git |
| 319 | // held to the transports a URL from data may use, and no prompt. It keeps |
| 320 | // the caller's GIT_CONFIG_* variables, which carry the safe.directory |
| 321 | // entries a host gives the publisher for repositories it does not own. |
| 322 | func git(ctx context.Context, repo string, args ...string) ([]byte, error) { |
| 323 | if repo != "" { |
| 324 | args = append([]string{"-C", repo}, args...) |
| 325 | } |
| 326 | cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects"}, args...)...) |
| 327 | cmd.Env = gitEnvironment(os.Environ()) |
| 328 | var stderr bytes.Buffer |
| 329 | cmd.Stderr = &stderr |
| 330 | out, err := cmd.Output() |
| 331 | if err != nil { |
| 332 | verb := args[0] |
| 333 | if verb == "-C" && len(args) > 2 { |
| 334 | verb = args[2] |
| 335 | } |
| 336 | return nil, fmt.Errorf("git %s: %w: %s", verb, err, strings.TrimSpace(stderr.String())) |
| 337 | } |
| 338 | return out, nil |
| 339 | } |
| 340 | |
| 341 | func gitEnvironment(environ []string) []string { |
| 342 | var env []string |
| 343 | for _, kv := range environ { |
| 344 | name, _, _ := strings.Cut(kv, "=") |
| 345 | if redirectsGit(name) || name == "GIT_ALLOW_PROTOCOL" || name == "GIT_TERMINAL_PROMPT" { |
| 346 | continue |
| 347 | } |
| 348 | env = append(env, kv) |
| 349 | } |
| 350 | return append(env, |
| 351 | "GIT_ALLOW_PROTOCOL=ssh:git:https:file", |
| 352 | "GIT_TERMINAL_PROMPT=0", |
| 353 | "GIT_NO_REPLACE_OBJECTS=1", |
| 354 | ) |
| 355 | } |
| 356 | |
| 357 | // redirectsGit reports whether the variable points git at another |
| 358 | // repository, another object store or another work tree than the one it |
| 359 | // is run in. |
| 360 | func redirectsGit(name string) bool { |
| 361 | switch name { |
| 362 | case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX", |
| 363 | "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES": |
| 364 | return true |
| 365 | } |
| 366 | return false |
| 367 | } |
| 368 | |
| 369 | // readPrincipals reads the display mapping: a JSON object from principal |
| 370 | // names to the names an export shows. No file is an empty mapping, under |
| 371 | // which every principal is shown as export.Unmapped. |
| 372 | func readPrincipals(path string) (export.Principals, error) { |
| 373 | if path == "" { |
| 374 | return export.Principals{}, nil |
| 375 | } |
| 376 | data, err := os.ReadFile(path) |
| 377 | if err != nil { |
| 378 | return nil, err |
| 379 | } |
| 380 | dec := json.NewDecoder(bytes.NewReader(data)) |
| 381 | var m export.Principals |
| 382 | if err := dec.Decode(&m); err != nil { |
| 383 | return nil, fmt.Errorf("the display mapping %s is not a JSON object of names: %w", path, err) |
| 384 | } |
| 385 | if err := dec.Decode(&json.RawMessage{}); err != io.EOF { |
| 386 | return nil, fmt.Errorf("the display mapping %s holds more than its one object", path) |
| 387 | } |
| 388 | if m == nil { |
| 389 | m = export.Principals{} |
| 390 | } |
| 391 | return m, nil |
| 392 | } |