diff --git a/changelog.d/added-hub-spoke-repo-sync.md b/changelog.d/added-hub-spoke-repo-sync.md new file mode 100644 index 0000000000..9c8f2103f7 --- /dev/null +++ b/changelog.d/added-hub-spoke-repo-sync.md @@ -0,0 +1 @@ +- Hubs can opt in to spoke repository sync: a registration key updates only its own repo list, at least one proven repo must remain active, and new repos stay pending until their owner proves them ([#19236](https://github.com/hivecommons/hive/issues/19236)). diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index 3819973536..b2cddb3890 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -62,7 +62,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `POST` | `/api/hub/v1/registrations` | Hub auth | Register a self-hosted hive as a resource ([#18642](https://github.com/hivecommons/hive/issues/18642)): the same body, proof and refusals as `POST /api/hub/selfservice/hives` (including `429` over `HIVE_HUB_SELFSERVICE_MAX_PER_USER`), except that a repo list over `HIVE_HUB_SELFSERVICE_MAX_REPOS` answers `413 {error, limit: "max_repos", max_repos}` instead of `400`, and `X-Hive-Proof-Method: github-user-token` picks the per-request token proof (`400` listing `proof_methods` when the hub does not offer it; `403 {error, proof_method, reason, repo, required_scopes, granted_scopes}` when it fails). `201 {registration, key, hub_url, snippets}` with `Location` and a strong `ETag` header; `registration` is the legacy view plus `etag` and `repo_proofs[{repo, checked_at}]` (when the owner's admin permission on each repo was last proven). The raw key appears once. `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_api.go` | | `GET` | `/api/hub/v1/registrations` | Hub auth | The caller's own registrations: `{registrations[]}`, each with its `etag` and `repo_proofs`; never a key or a hash | `pkg/hub/selfservice_v1_api.go` | | `GET` | `/api/hub/v1/registrations/{id}` | Hub auth | One of the caller's registrations: `{registration}` with a strong `ETag` header; `If-None-Match` with the current ETag answers `304`. Another user's hive, a missing hive and a hub admin who does not own it all get `404`. The ETag comes from a revision counter that heartbeats do not bump, and reveals nothing about the key | `pkg/hub/selfservice_v1_api.go` | -| `PATCH` | `/api/hub/v1/registrations/{id}` | Hub auth | Owner only, by hub session (a registration key is not accepted): change `repos` and/or `dashboard_url` in place with the heartbeat key kept valid ([#18642](https://github.com/hivecommons/hive/issues/18642)). Body: `repos` is a full list (replacement) or `{add[], remove[]}`; `dashboard_url` is an `https` URL or `""` to clear it. `If-Match` is required: `428` when absent, `412` carrying the current `ETag` when stale (checked before any GitHub call and again under the store lock). Only added repos are proven (`403` naming the first refused repo, nothing applied); kept repos keep their proof time and removed repos lose theirs. `org`, the owner, the ID and the keys are not editable: a body naming `org` or any other field is `400`, as is a list that would leave no repo. Over `HIVE_HUB_SELFSERVICE_MAX_REPOS` is `413 {error, limit: "max_repos", max_repos}`. Removing a repo the registration does not list is ignored; an edit that changes nothing answers `200` with the current `ETag` and does not bump the revision. `200 {registration}` with the new `ETag`; the key never appears. `404` for a missing hive, another user's hive and a hub admin who does not own it; `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_patch.go` | +| `PATCH` | `/api/hub/v1/registrations/{id}` | Hub auth | Owner only, by hub session (a registration key is not accepted here; see the `sync-repos` row below): change `repos` and/or `dashboard_url` in place with the heartbeat key kept valid ([#18642](https://github.com/hivecommons/hive/issues/18642)). Body: `repos` is a full list (replacement) or `{add[], remove[]}`; `dashboard_url` is an `https` URL or `""` to clear it. `If-Match` is required: `428` when absent, `412` carrying the current `ETag` when stale (checked before any GitHub call and again under the store lock). Only added repos are proven (`403` naming the first refused repo, nothing applied); kept repos keep their proof time and removed repos lose theirs. Owners prove repos in `pending_proof` by adding them here. `org`, the owner, the ID and the keys are not editable: a body naming `org` or any other field is `400`, as is a list that would leave no repo. Over `HIVE_HUB_SELFSERVICE_MAX_REPOS` is `413 {error, limit: "max_repos", max_repos}`. Removing a repo the registration does not list is ignored; an edit that changes nothing answers `200` with the current `ETag` and does not bump the revision. `200 {registration}` with the new `ETag`; the key never appears. `404` for a missing hive, another user's hive and a hub admin who does not own it; `404` while `HIVE_HUB_SELFSERVICE_REGISTRATION` is off | `pkg/hub/selfservice_v1_patch.go` | +| `PATCH` | `/api/hub/v1/registrations/{id}` | Own registration bearer | `{"op":"sync-repos","repos":["owner/name"]}` replaces the desired list with the supplied nonempty list, up to `max_repos`. Retained proven repos stay active; other requested repos appear only in `registration.pending_proof` until the owner proves them. Omitted repos are removed. No GitHub calls. Requires `If-Match` (send `*` for the first sync or use the returned `ETag`; `428` missing, `412` stale). `200 {registration}` with its resulting `ETag`; `400` for a list that keeps no proven repo or for other fields or operations; `404` for a registration key used on a foreign or missing ID. Discovery advertises `sync-repos` only when `HIVE_HUB_SELFSERVICE_SYNC_REPOS` is on (off by default; also requires self-service registration to be enabled) | `pkg/hub/selfservice_v1_sync.go` | | `POST` | `/api/hub/v1/registrations/{id}/keys` | Hub auth | Owner only: rotate the heartbeat key; the previous key keeps authenticating for the 10 minute overlap, or for `HIVE_HUB_SELFSERVICE_KEY_GRACE_WINDOW` while `HIVE_HUB_SELFSERVICE_KEY_GRACE` is on, in which case a rotation inside an open window keeps the old key and replaces the pending one ([#19235](https://github.com/hivecommons/hive/issues/19235)). `201 {id, key, hub_url, overlap, snippets}` (the legacy rotate answers `200`) with the new `ETag`; the raw key appears once. Optional `If-Match` (`412` when stale). A body asking for a grace window is refused with `400`: caller-chosen grace is a later rollout step | `pkg/hub/selfservice_v1_api.go` | | `DELETE` | `/api/hub/v1/registrations/{id}` | Hub auth | Owner or hub admin: revoke the key and remove the registry entry. `200 {removed, id}`. Optional `If-Match` (`412` when stale, carrying the current `ETag`) | `pkg/hub/selfservice_v1_api.go` | | `POST` | `/api/hub/selfservice/hives/{id}/rotate` | Hub auth | Owner only: mint a new heartbeat key for `{id}`; the previous key keeps authenticating for `overlap` (10 minutes, or the grace window while `HIVE_HUB_SELFSERVICE_KEY_GRACE` is on). `200 {id, key, hub_url, overlap, snippets}`, raw key once. Another user's hive, a missing hive and a hub admin who does not own it all get `404` | `pkg/hub/server.go:1794` | diff --git a/src/pkg/hub/selfservice_registry.go b/src/pkg/hub/selfservice_registry.go index 7c463ecd62..64d3f5e19e 100644 --- a/src/pkg/hub/selfservice_registry.go +++ b/src/pkg/hub/selfservice_registry.go @@ -103,6 +103,9 @@ type SelfServiceHive struct { // removes. Records from before the field have no entries; their repos // were all proven at OwnershipCheckedAt. RepoProofs map[string]time.Time `json:"repo_proofs,omitempty"` + // PendingProof is the spoke's requested but unproven repos. Only Repos + // grants registry visibility; pending entries are kept for owner review. + PendingProof []string `json:"pending_proof,omitempty"` // LastAcceptedHeartbeatAt is the last heartbeat that passed the bearer // check. Zero until the first one; the expiry sweep (selfservice_expiry.go) // counts the window from here, or from CreatedAt while it is zero. @@ -371,6 +374,7 @@ func (st *selfServiceStore) update(id, ifMatch string, mutate func(*SelfServiceH before := *h next := *h next.Repos = append([]string(nil), h.Repos...) + next.PendingProof = append([]string(nil), h.PendingProof...) next.RepoProofs = make(map[string]time.Time, len(h.RepoProofs)) for k, v := range h.RepoProofs { next.RepoProofs[k] = v @@ -434,7 +438,12 @@ func (st *selfServiceStore) verify(id, presented string) bool { if !ok { return false } - hash := hashSelfServiceKey(presented) + return st.matchesKey(*h, hashSelfServiceKey(presented)) +} + +// matchesKey applies the heartbeat key policy to a record already loaded +// under the store lock. Mutations must check the credential under that lock. +func (st *selfServiceStore) matchesKey(h SelfServiceHive, hash string) bool { if h.KeyHash != "" && secureCompareHub(hash, h.KeyHash) { return true } diff --git a/src/pkg/hub/selfservice_v1_api.go b/src/pkg/hub/selfservice_v1_api.go index 578df88944..0dca804178 100644 --- a/src/pkg/hub/selfservice_v1_api.go +++ b/src/pkg/hub/selfservice_v1_api.go @@ -50,7 +50,7 @@ type hubV1Operation struct { IfMatch string `json:"if_match,omitempty"` } -// hubV1Operations is what this hub implements. Discovery lists exactly this. +// hubV1Operations are the operations available on every enabled hub. var hubV1Operations = []hubV1Operation{ {Name: "discovery", Method: http.MethodGet, Path: hubV1BasePath}, {Name: "create", Method: http.MethodPost, Path: hubV1BasePath + "/registrations"}, @@ -67,15 +67,16 @@ var hubV1Operations = []hubV1Operation{ var hubV1PatchFields = []string{"repos", "dashboard_url"} // registerHubV1Routes wires the v1 routes onto the hub mux. Discovery is -// public (a spoke reads it before it has a session); every other route is -// behind the hub session like the v6 routes. All of them answer 404 while -// HIVE_HUB_SELFSERVICE_REGISTRATION is off. +// public (a spoke reads it before it has a session); the registration-key +// PATCH lane is opt-in, and the remaining routes require hub auth. +// All routes answer 404 while HIVE_HUB_SELFSERVICE_REGISTRATION is off +// for callers with the appropriate credential. func (s *HubServer) registerHubV1Routes() { s.mux.HandleFunc("GET "+hubV1BasePath, s.handleHubV1Discovery) s.mux.HandleFunc("POST "+hubV1BasePath+"/registrations", s.requireAuth(s.handleHubV1Create)) s.mux.HandleFunc("GET "+hubV1BasePath+"/registrations", s.requireAuth(s.handleHubV1List)) s.mux.HandleFunc("GET "+hubV1BasePath+"/registrations/{id}", s.requireAuth(s.handleHubV1Get)) - s.mux.HandleFunc("PATCH "+hubV1BasePath+"/registrations/{id}", s.requireAuth(s.handleHubV1Patch)) + s.mux.HandleFunc("PATCH "+hubV1BasePath+"/registrations/{id}", s.routeHubV1Patch) s.mux.HandleFunc("DELETE "+hubV1BasePath+"/registrations/{id}", s.requireAuth(s.handleHubV1Delete)) s.mux.HandleFunc("POST "+hubV1BasePath+"/registrations/{id}/keys", s.requireAuth(s.handleHubV1RotateKey)) } @@ -85,8 +86,9 @@ func (s *HubServer) registerHubV1Routes() { // proof times. type hubV1RegistrationView struct { selfServiceHiveView - ETag string `json:"etag"` - RepoProofs []hubV1RepoProof `json:"repo_proofs"` + ETag string `json:"etag"` + RepoProofs []hubV1RepoProof `json:"repo_proofs"` + PendingProof []string `json:"pending_proof,omitempty"` } // hubV1RepoProof is when the owner's admin permission on one repo was last @@ -111,6 +113,7 @@ func (s *HubServer) hubV1View(h SelfServiceHive) hubV1RegistrationView { selfServiceHiveView: selfServiceView(h, s.selfServiceOnline(h.ID)), ETag: selfServiceETag(h), RepoProofs: proofs, + PendingProof: h.PendingProof, } } @@ -138,11 +141,18 @@ func (s *HubServer) handleHubV1Discovery(w http.ResponseWriter, r *http.Request) if !s.requireSelfServiceEnabled(w) { return } + operations := hubV1Operations + if hubV1SyncReposEnabled() { + operations = append(operations, hubV1Operation{ + Name: hubV1SyncReposOp, Method: http.MethodPatch, + Path: hubV1BasePath + "/registrations/{id}", IfMatch: "required", + }) + } writeHubV1JSON(w, http.StatusOK, "", map[string]any{ "protocol": hubV1Protocol, "version": hubV1ProtocolVersion, "base_path": hubV1BasePath, - "operations": hubV1Operations, + "operations": operations, "patch_fields": hubV1PatchFields, "limits": map[string]any{ "max_repos": selfServiceMaxRepos(), diff --git a/src/pkg/hub/selfservice_v1_patch.go b/src/pkg/hub/selfservice_v1_patch.go index ae7940f359..5ef4542e17 100644 --- a/src/pkg/hub/selfservice_v1_patch.go +++ b/src/pkg/hub/selfservice_v1_patch.go @@ -9,9 +9,9 @@ package hub // registering again. // // Invariants (in addition to selfservice_v1_api.go's): -// - The hub session owner is the only caller. The registration key is not a -// credential here, and a hub admin who does not own the hive gets 404, the -// same answer as for a missing hive. +// - The ordinary edit requires the hub session owner. A hub admin who does +// not own the hive gets 404, the same answer as for a missing hive. The +// separately gated sync-repos operation uses the registration key. // - If-Match is required (428 when absent, 412 when stale). The precondition // is checked before any GitHub call and again inside the store lock. // - Only repos the edit ADDS are proven (the same read-only @@ -32,6 +32,7 @@ import ( "fmt" "io" "net/http" + "slices" "sort" "strings" ) @@ -306,6 +307,11 @@ func (s *HubServer) handleHubV1Patch(w http.ResponseWriter, r *http.Request) { } n.Repos = plan.repos n.RepoProofs = selfServiceProofTimes(n.RepoProofs, plan.repos, n.OwnershipCheckedAt, now, plan.added) + if len(n.PendingProof) > 0 && (len(plan.added) > 0 || len(plan.removed) > 0) { + n.PendingProof = slices.DeleteFunc(n.PendingProof, func(repo string) bool { + return hubV1ContainsFold(plan.added, repo) || hubV1ContainsFold(plan.removed, repo) + }) + } n.DashboardURL = plan.dashboardURL return nil }) diff --git a/src/pkg/hub/selfservice_v1_sync.go b/src/pkg/hub/selfservice_v1_sync.go new file mode 100644 index 0000000000..0443321696 --- /dev/null +++ b/src/pkg/hub/selfservice_v1_sync.go @@ -0,0 +1,168 @@ +package hub + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" +) + +const ( + hubV1SyncReposEnv = "HIVE_HUB_SELFSERVICE_SYNC_REPOS" + hubV1SyncReposOp = "sync-repos" +) + +var errHubV1SyncNoWrite = errors.New("sync-repos did not change the registration") + +func hubV1SyncReposEnabled() bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv(hubV1SyncReposEnv))) { + case "1", "true", "yes", "on": + return true + } + return false +} + +func (s *HubServer) routeHubV1Patch(w http.ResponseWriter, r *http.Request) { + // Never send a registration key through the hub auth middleware, which + // validates bearer credentials against GitHub. Key shape selects the + // lane, not authority: only the addressed record's hashes authenticate it. + if key, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer "); ok && + len(key) == base64.RawURLEncoding.EncodedLen(selfServiceKeyBytes) { + var decoded [selfServiceKeyBytes]byte + if _, err := base64.RawURLEncoding.Strict().Decode(decoded[:], []byte(key)); err == nil { + s.handleHubV1SyncRepos(w, r, key) + return + } + } + s.requireAuth(s.handleHubV1Patch)(w, r) +} + +func (s *HubServer) handleHubV1SyncRepos(w http.ResponseWriter, r *http.Request, key string) { + if !s.requireSelfServiceEnabled(w) { + return + } + if !hubV1SyncReposEnabled() { + writeJSONError(w, http.StatusNotFound, "sync-repos is not enabled") + return + } + if !isNonBrowserAPIRequest(r) || !isCSRFSafe(r) { + writeJSONError(w, http.StatusForbidden, "sync-repos requires a registration bearer without a hub session cookie and must pass the CSRF check") + return + } + limit := selfServiceRequestBodyLimit() + data, err := io.ReadAll(io.LimitReader(r.Body, limit+1)) + if err != nil { + writeJSONError(w, http.StatusBadRequest, "could not read the request body") + return + } + if int64(len(data)) > limit { + writeJSONError(w, http.StatusRequestEntityTooLarge, "the request body is too large") + return + } + + id := strings.ToLower(strings.TrimSpace(r.PathValue("id"))) + hash := hashSelfServiceKey(key) + ifMatch := strings.TrimSpace(r.Header.Get("If-Match")) + var current SelfServiceHive + var refusal *hubV1PatchRefusal + stored, err := s.selfService.update(id, "", func(h *SelfServiceHive) error { + // Authenticate before exposing the current ETag. Check against the + // live record under the write lock, including after key rotation. + if !s.selfService.matchesKey(*h, hash) { + return errSelfServiceNotFound + } + current = *h + switch { + case ifMatch == "": + refusal = hubV1Refuse(http.StatusPreconditionRequired, "If-Match is required: send an ETag or '*' for the current registration") + case !selfServiceETagMatches(*h, ifMatch): + refusal = hubV1Refuse(http.StatusPreconditionFailed, "the registration changed; retry with its current ETag") + } + if refusal != nil { + return errHubV1SyncNoWrite + } + refusal = hubV1ApplySyncRepos(h, data) + if refusal != nil || (hubV1SameRepos(h.Repos, current.Repos) && hubV1SameRepos(h.PendingProof, current.PendingProof)) { + return errHubV1SyncNoWrite + } + return nil + }) + switch { + case errors.Is(err, errSelfServiceNotFound): + writeJSONError(w, http.StatusNotFound, "self-hosted hive not found") + case errors.Is(err, errHubV1SyncNoWrite): + if refusal != nil { + etag := "" + if refusal.status == http.StatusPreconditionRequired || refusal.status == http.StatusPreconditionFailed { + etag = selfServiceETag(current) + } + writeHubV1JSON(w, refusal.status, etag, refusal.body) + return + } + writeHubV1JSON(w, http.StatusOK, selfServiceETag(current), map[string]any{"registration": s.hubV1View(current)}) + case err != nil: + s.logger.Error("self-service sync-repos: store write failed", "hive", id, "error", err) + writeJSONError(w, http.StatusInternalServerError, "could not persist the change") + default: + s.logger.Info("audit: selfservice_hive_repos_synced", "hive", id, "repos", len(stored.Repos), + "pending_proof", len(stored.PendingProof), "revision", stored.Revision) + writeHubV1JSON(w, http.StatusOK, selfServiceETag(stored), map[string]any{"registration": s.hubV1View(stored)}) + } +} + +func hubV1ApplySyncRepos(h *SelfServiceHive, data []byte) *hubV1PatchRefusal { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil || fields == nil { + return hubV1Refuse(http.StatusBadRequest, "sync-repos takes a JSON object with op and repos") + } + for field := range fields { + if field != "op" && field != "repos" { + return hubV1Refuse(http.StatusBadRequest, "field %q cannot be changed by sync-repos", field) + } + } + var op string + if json.Unmarshal(fields["op"], &op) != nil || op != hubV1SyncReposOp { + return hubV1Refuse(http.StatusBadRequest, "a registration key may only PATCH with op %q", hubV1SyncReposOp) + } + var requested []string + if json.Unmarshal(fields["repos"], &requested) != nil || requested == nil { + return hubV1Refuse(http.StatusBadRequest, "repos must be a list of owner/name repos") + } + if maxRepos := selfServiceMaxRepos(); len(requested) > maxRepos { + return &hubV1PatchRefusal{ + status: http.StatusRequestEntityTooLarge, + body: hubV1RepoCapBody(fmt.Errorf("at most %d repos per registration", maxRepos), maxRepos), + } + } + repos, err := selfServiceValidateRepos(requested) + if err != nil { + return hubV1Refuse(http.StatusBadRequest, "%s", err.Error()) + } + + // Both lists are replaced. A previously active repo keeps its proof; + // everything else must go through the owner's ordinary proof path. + activeByName := make(map[string]string, len(h.Repos)) + for _, repo := range h.Repos { + activeByName[strings.ToLower(repo)] = repo + } + var active, pending []string + for _, repo := range repos { + if existing, ok := activeByName[strings.ToLower(repo)]; ok { + active = append(active, existing) + } else { + pending = append(pending, repo) + } + } + if len(active) == 0 { + return hubV1Refuse(http.StatusBadRequest, "sync-repos must keep at least one already-proven repo active") + } + h.Repos = active + h.PendingProof = pending + h.RepoProofs = selfServiceProofTimes(h.RepoProofs, active, h.OwnershipCheckedAt, time.Time{}, nil) + return nil +} diff --git a/src/pkg/hub/selfservice_v1_sync_test.go b/src/pkg/hub/selfservice_v1_sync_test.go new file mode 100644 index 0000000000..990f19ab47 --- /dev/null +++ b/src/pkg/hub/selfservice_v1_sync_test.go @@ -0,0 +1,116 @@ +package hub + +import ( + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" +) + +func (env *selfServiceTestEnv) syncRepos(id, key, etag, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPatch, hubV1BasePath+"/registrations/"+id, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("If-Match", etag) + rec := httptest.NewRecorder() + env.s.mux.ServeHTTP(rec, req) + return rec +} + +func TestHubV1SyncReposAppliesOnlyProvenRepos(t *testing.T) { + env := newHubV1TestEnv(t) + env.s.mux = http.NewServeMux() + env.s.registerHubV1Routes() + t.Setenv(hubV1SyncReposEnv, "true") + id, key := env.registerHappy(t) + before, _ := env.s.selfService.get(id) + calls := env.countProofs() + *env.now = env.now.Add(time.Hour) + + body := `{"op":"sync-repos","repos":["ALICE/LAB","alice/bulk-01","ALICE/BULK-01"]}` + rec := env.syncRepos(id, key, "*", body) + if rec.Code != http.StatusOK { + t.Fatalf("sync: %d %s", rec.Code, rec.Body.String()) + } + view := decodeV1Registration(t, rec) + if !slices.Equal(view.Repos, []string{"alice/lab"}) || !slices.Equal(view.PendingProof, []string{"alice/bulk-01"}) { + t.Fatalf("repos=%v pending=%v", view.Repos, view.PendingProof) + } + if len(view.RepoProofs) != 1 || view.RepoProofs[0].Repo != "alice/lab" || !view.RepoProofs[0].CheckedAt.Equal(before.OwnershipCheckedAt) { + t.Fatalf("proofs = %+v", view.RepoProofs) + } + etag := rec.Header().Get("ETag") + if etag == "" || etag == selfServiceETag(before) || view.ETag != etag { + t.Fatalf("sync did not publish a new ETag: %q", etag) + } + if view.Owner != before.Owner || view.Org != before.Org || view.DashboardURL != before.DashboardURL || !env.s.selfService.verify(id, key) { + t.Fatal("sync changed registration identity, dashboard or key") + } + if calls.Load() != 0 { + t.Fatal("sync attempted a GitHub ownership check") + } + if retry := env.syncRepos(id, key, etag, body); retry.Code != http.StatusOK || retry.Header().Get("ETag") != etag { + t.Fatalf("identical sync changed state: %d %s", retry.Code, retry.Body.String()) + } + + reloaded := newSelfServiceStore(env.s.selfService.path) + if err := reloaded.load(); err != nil { + t.Fatal(err) + } + stored, ok := reloaded.get(id) + if !ok || !slices.Equal(stored.PendingProof, view.PendingProof) || !slices.Equal(stored.Repos, view.Repos) { + t.Fatalf("sync not persisted: repos=%v pending=%v", stored.Repos, stored.PendingProof) + } + + approval := env.v1Patch(t, selfServiceTestUser, id, etag, `{"repos":{"add":["alice/bulk-01"]}}`) + if approval.Code != http.StatusOK { + t.Fatalf("owner proof: %d %s", approval.Code, approval.Body.String()) + } + approved := decodeV1Registration(t, approval) + if !slices.Equal(approved.Repos, []string{"alice/lab", "alice/bulk-01"}) || len(approved.PendingProof) != 0 || calls.Load() != 1 { + t.Fatalf("owner proof: repos=%v pending=%v checks=%d", approved.Repos, approved.PendingProof, calls.Load()) + } +} + +func TestHubV1SyncReposRefusesOutOfScopeRequests(t *testing.T) { + env := newHubV1TestEnv(t) + env.s.mux = http.NewServeMux() + env.s.registerHubV1Routes() + id, key := env.registerHappy(t) + foreignID, _ := env.registerHappy2(t) + etag, foreignETag := env.etagOf(t, id), env.etagOf(t, foreignID) + body := `{"op":"sync-repos","repos":["alice/readonly"]}` + + t.Setenv(hubV1SyncReposEnv, "") + if rec := env.syncRepos(id, key, etag, body); rec.Code != http.StatusNotFound { + t.Fatalf("flag off: %d %s", rec.Code, rec.Body.String()) + } + t.Setenv(hubV1SyncReposEnv, "on") + for _, target := range []string{foreignID, "byo-alice--missing"} { + if rec := env.syncRepos(target, key, etag, body); rec.Code != http.StatusNotFound || rec.Header().Get("ETag") != "" { + t.Fatalf("foreign or missing ID %q: %d %s", target, rec.Code, rec.Body.String()) + } + } + for _, field := range []string{"org", "owner", "dashboard_url", "id", "pending_proof", "repo_proofs"} { + withField := strings.TrimSuffix(body, "}") + `,"` + field + `":null}` + if rec := env.syncRepos(id, key, etag, withField); rec.Code != http.StatusBadRequest { + t.Fatalf("forbidden field %q: %d %s", field, rec.Code, rec.Body.String()) + } + } + if rec := env.syncRepos(id, key, etag, `{"repos":["alice/lab"]}`); rec.Code != http.StatusBadRequest { + t.Fatalf("ordinary PATCH with key: %d %s", rec.Code, rec.Body.String()) + } + if rec := env.syncRepos(id, key, "", body); rec.Code != http.StatusPreconditionRequired || rec.Header().Get("ETag") != etag { + t.Fatalf("missing If-Match: %d %s", rec.Code, rec.Body.String()) + } + if rec := env.syncRepos(id, key, foreignETag, body); rec.Code != http.StatusPreconditionFailed || rec.Header().Get("ETag") != etag { + t.Fatalf("stale If-Match: %d %s", rec.Code, rec.Body.String()) + } + if rec := env.syncRepos(id, key, etag, body); rec.Code != http.StatusBadRequest { + t.Fatalf("all-new repo list: %d %s", rec.Code, rec.Body.String()) + } + if env.etagOf(t, id) != etag || env.etagOf(t, foreignID) != foreignETag { + t.Fatal("refused requests changed a registration") + } +}