From 56dca328191c93f5603b72984b7d8424dcdfac5d Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Wed, 18 Nov 2026 14:02:37 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20hub:=20edit=20a=20v1=20registration?= =?UTF-8?q?=20in=20place=20with=20PATCH,=20key=20kept?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PATCH /api/hub/v1/registrations/{id} changes repos (full list or add and remove) and dashboard_url with the heartbeat key untouched. If-Match is required (428 missing, 412 stale). Only added repos are proven, read only, with the owner's stored token. org, owner and keys are not editable. Owner session only, gated by HIVE_HUB_SELFSERVICE_REGISTRATION, listed in v1 discovery. Nothing writes to GitHub. Refs #19056 Signed-off-by: Andrew Anderson --- .../added-19056-hub-v1-patch-registration.md | 1 + src/docs/api-reference/hub-server.md | 1 + src/docs/audit-log.md | 3 +- src/docs/hub-deployment.md | 16 +- src/pkg/hub/selfservice_api.go | 1 + src/pkg/hub/selfservice_v1_api.go | 18 +- src/pkg/hub/selfservice_v1_api_test.go | 10 +- src/pkg/hub/selfservice_v1_patch.go | 323 +++++++++++++ src/pkg/hub/selfservice_v1_patch_test.go | 451 ++++++++++++++++++ 9 files changed, 813 insertions(+), 11 deletions(-) create mode 100644 changelog.d/added-19056-hub-v1-patch-registration.md create mode 100644 src/pkg/hub/selfservice_v1_patch.go create mode 100644 src/pkg/hub/selfservice_v1_patch_test.go diff --git a/changelog.d/added-19056-hub-v1-patch-registration.md b/changelog.d/added-19056-hub-v1-patch-registration.md new file mode 100644 index 0000000000..d285e4c4f6 --- /dev/null +++ b/changelog.d/added-19056-hub-v1-patch-registration.md @@ -0,0 +1 @@ +- Hub registration protocol v1: a registration can now be edited in place with `PATCH /api/hub/v1/registrations/{id}`, so adding a repo or moving the dashboard URL no longer means deleting the registration (which revoked its key and took the spoke offline) and registering again. The heartbeat key is never touched. The body changes `repos` (a full list, or `{add, remove}`) and/or `dashboard_url`; `If-Match` with the record's `ETag` is required (`428` when missing, `412` when stale), only the repos an edit adds are checked against GitHub with the owner's own stored token (read only), and a repo list over `HIVE_HUB_SELFSERVICE_MAX_REPOS` answers `413` naming the limit. `org`, the owner and the keys are not editable. It is owner-only by hub session, writes nothing to GitHub, is gated by `HIVE_HUB_SELFSERVICE_REGISTRATION` like the rest of v1, and is listed in `GET /api/hub/v1` discovery (`operations` and `patch_fields`); the v6 `/api/hub/selfservice/*` routes are unchanged. Each edit writes a `selfservice_hive_updated` audit line with counts and no key ([#19056](https://github.com/hivecommons/hive/issues/19056)). diff --git a/src/docs/api-reference/hub-server.md b/src/docs/api-reference/hub-server.md index 821f90605a..1e143399da 100644 --- a/src/docs/api-reference/hub-server.md +++ b/src/docs/api-reference/hub-server.md @@ -62,6 +62,7 @@ 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`. `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` | | `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. `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). `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:1791` | diff --git a/src/docs/audit-log.md b/src/docs/audit-log.md index 90f78247b3..be1fc3d346 100644 --- a/src/docs/audit-log.md +++ b/src/docs/audit-log.md @@ -204,10 +204,11 @@ a key hash, the master secret or the user's GitHub token. | Action | Written when | Keys | | --- | --- | --- | | `selfservice_hive_registered` | A registration passed every check and the key was minted | `user`, `hive`, `repos` (count), `org` | +| `selfservice_hive_updated` | The owner changed `repos` and/or `dashboard_url` with `PATCH /api/hub/v1/registrations/{id}`; the heartbeat key is untouched. A request that changes nothing writes no line | `user`, `hive`, `repos_added` (count), `repos_removed` (count), `dashboard_changed`, `revision` | | `selfservice_hive_rotated` | The owner rotated the heartbeat key | `user`, `hive`, `overlap` (how long the previous key keeps authenticating) | | `selfservice_hive_revoked` | The owner or a hub admin revoked the hive; the registry entry is removed in the same request and `registry entry removed` follows | `user`, `hive`, `owner`, `by_admin` | | `selfservice_hive_expired` | The expiry sweep (`pkg/hub/selfservice_expiry.go`, every `HIVE_HUB_SELFSERVICE_SWEEP_INTERVAL`) removed a hive that went longer than `HIVE_HUB_SELFSERVICE_EXPIRY` without an accepted heartbeat; the key is revoked and `registry entry removed` (with `by=selfservice-expiry-sweep`) follows | `id`, `owner`, `last_heartbeat` (RFC 3339, or `never` when no heartbeat was ever accepted), `expiry` | -| `selfservice_hive_refused` | A registration was turned away and nothing was stored | `user`, `hive`, `reason` (`invalid_name`, `invalid_login`, `reserved_prefix`, `duplicate_id`, `invalid_repos`, `invalid_dashboard_url`, `per_user_cap` with `max_per_user`, `no_github_token`, `no_github_login`, `not_repo_admin` with `repo`, `ownership_check_error` with `repo`) | +| `selfservice_hive_refused` | A registration was turned away and nothing was stored | `user`, `hive`, `reason` (`invalid_name`, `invalid_login`, `reserved_prefix`, `duplicate_id`, `invalid_repos`, `invalid_dashboard_url`, `invalid_update` (a `PATCH` body the hub refused), `per_user_cap` with `max_per_user`, `no_github_token`, `no_github_login`, `not_repo_admin` with `repo`, `ownership_check_error` with `repo`) | ## Rotation and retention diff --git a/src/docs/hub-deployment.md b/src/docs/hub-deployment.md index 0be54f6de0..e58264fd5e 100644 --- a/src/docs/hub-deployment.md +++ b/src/docs/hub-deployment.md @@ -125,6 +125,19 @@ The registry entry becomes a `self-hosted` hive in Active Hives and the fleet vi - The owner never receives `HIVE_HUB_SECRET`. The hub never consults it in the self-service routes and never returns it. - Everything the fence withholds still applies: the hub sends the hive no GitHub App config, gateway, cluster ID, authorized users, upgrade or branch-switch instructions, restarts or fleet-breaker actions. Listing is directory metadata only. +#### Editing a registration + +`PATCH /api/hub/v1/registrations/{id}` changes `repos` and `dashboard_url` in place, so adding a repo no longer means deleting the registration and registering again (which revoked the key and took the spoke offline). The heartbeat key is not touched: the spoke keeps heartbeating with the key it has. + +- **Who:** the owner, signed in to the hub. A registration key cannot edit its own record, and a hub admin who does not own the hive gets `404`. +- **`If-Match` is required.** `GET /api/hub/v1/registrations/{id}` returns the `ETag`; send it back on the `PATCH`. A missing header is `428`, a stale one is `412` with the current `ETag`, so two operators editing at once cannot silently overwrite each other. Heartbeats do not change the `ETag`. +- **`repos`:** a full list replaces the repos, or `{"add": [...], "remove": [...]}` changes them. Only the repos an edit adds are checked against GitHub (the same read-only `permissions.admin` check as registration, with the owner's own stored token); one failing repo refuses the whole edit and nothing is applied. Kept repos keep their proof time, and removed repos lose theirs. At least one repo must remain, and `HIVE_HUB_SELFSERVICE_MAX_REPOS` applies (`413 {limit: "max_repos"}`). +- **`dashboard_url`:** an `https` URL to a public address, or `""` to clear it. +- **Not editable:** `org`, the owner, the ID and the keys. To change the `org`, delete the registration and register it again. +- **No GitHub writes.** The edit changes the hub's own registry only. + +The route is part of the v1 registration protocol and follows the same switch as the rest of it, `HIVE_HUB_SELFSERVICE_REGISTRATION`; discovery (`GET /api/hub/v1`) lists it under `operations` with `if_match: "required"` and its fields under `patch_fields`, so a hub that does not offer it does not advertise it. The v6 `/api/hub/selfservice/*` routes are unchanged. + #### Rotation The owner can rotate from the **Self-hosted hives** list or with `POST /api/hub/selfservice/hives/{id}/rotate`. The hub mints a new key and keeps the previous hash live for a 10 minute overlap so a running spoke can pick up the new value without a gap. After the overlap only the new key is accepted. Only the owner can rotate; a hub admin who does not own the hive gets `404`, the same answer as for a missing hive. @@ -144,7 +157,8 @@ Every decision writes one structured log line, documented in [audit-log.md](audi | Event | When | |---|---| | `selfservice_hive_registered` | A registration passed every check and a key was minted. | -| `selfservice_hive_refused` | A registration was turned away; `reason` is one of `invalid_name`, `reserved_prefix`, `duplicate_id`, `invalid_repos`, `invalid_dashboard_url`, `per_user_cap`, `no_github_token`, `no_github_login`, `not_repo_admin`, `ownership_check_error`. | +| `selfservice_hive_refused` | A registration was turned away; `reason` is one of `invalid_name`, `reserved_prefix`, `duplicate_id`, `invalid_repos`, `invalid_dashboard_url`, `invalid_update` (a `PATCH` body that was refused), `per_user_cap`, `no_github_token`, `no_github_login`, `not_repo_admin`, `ownership_check_error`. | +| `selfservice_hive_updated` | The owner edited the repos or dashboard URL with `PATCH`; the line counts repos added and removed and carries no key. | | `selfservice_hive_rotated` | The owner rotated the key; `overlap` is how long the old key keeps working. | | `selfservice_hive_revoked` | The owner or an admin removed the hive; `by_admin` tells which. | | `selfservice_hive_expired` | The sweep removed a hive; `last_heartbeat` is RFC 3339 or `never`. | diff --git a/src/pkg/hub/selfservice_api.go b/src/pkg/hub/selfservice_api.go index e9f42c9429..c262fef53a 100644 --- a/src/pkg/hub/selfservice_api.go +++ b/src/pkg/hub/selfservice_api.go @@ -102,6 +102,7 @@ const ( selfServiceRefusedDuplicateID = "duplicate_id" selfServiceRefusedInvalidRepos = "invalid_repos" selfServiceRefusedInvalidURL = "invalid_dashboard_url" + selfServiceRefusedInvalidUpdate = "invalid_update" selfServiceRefusedCap = "per_user_cap" selfServiceRefusedNoToken = "no_github_token" selfServiceRefusedNotAdmin = "not_repo_admin" diff --git a/src/pkg/hub/selfservice_v1_api.go b/src/pkg/hub/selfservice_v1_api.go index 5cc47627eb..35d6bcb788 100644 --- a/src/pkg/hub/selfservice_v1_api.go +++ b/src/pkg/hub/selfservice_v1_api.go @@ -5,9 +5,10 @@ package hub // /api/hub/v1 is a versioned resource view of the self-service (byo-) // registry that selfservice_api.go already serves under /api/hub/selfservice. // It adds discovery (GET /api/hub/v1) and the registry as resources: create, -// list, get, delete and key rotation, with an ETag on every record and an -// optional If-Match on every write. In-place edits (PATCH) are a later PR of -// the same rollout. The legacy routes keep their bodies and status codes. +// list, get, update (PATCH, selfservice_v1_patch.go), delete and key rotation, +// with an ETag on every record and an If-Match on every write (required on +// PATCH, optional on delete and rotate). The legacy routes keep their bodies +// and status codes. // // Invariants (in addition to selfservice_api.go's): // - Nothing here writes to GitHub. The only GitHub call is the read-only @@ -56,13 +57,15 @@ var hubV1Operations = []hubV1Operation{ {Name: "create", Method: http.MethodPost, Path: hubV1BasePath + "/registrations"}, {Name: "list", Method: http.MethodGet, Path: hubV1BasePath + "/registrations"}, {Name: "get", Method: http.MethodGet, Path: hubV1BasePath + "/registrations/{id}"}, + {Name: "update", Method: http.MethodPatch, Path: hubV1BasePath + "/registrations/{id}", IfMatch: "required"}, {Name: "rotate_key", Method: http.MethodPost, Path: hubV1BasePath + "/registrations/{id}/keys", IfMatch: "optional"}, {Name: "delete", Method: http.MethodDelete, Path: hubV1BasePath + "/registrations/{id}", IfMatch: "optional"}, } -// hubV1PatchFields are the registration fields an update may change. Empty -// until the update operation exists. -var hubV1PatchFields = []string{} +// hubV1PatchFields are the registration fields an update may change. org is +// not one of them: changing it would mean re-proving every repo, so a client +// deletes and registers again (#18642). +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 @@ -73,6 +76,7 @@ func (s *HubServer) registerHubV1Routes() { 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("DELETE "+hubV1BasePath+"/registrations/{id}", s.requireAuth(s.handleHubV1Delete)) s.mux.HandleFunc("POST "+hubV1BasePath+"/registrations/{id}/keys", s.requireAuth(s.handleHubV1RotateKey)) } @@ -111,7 +115,7 @@ func (s *HubServer) hubV1View(h SelfServiceHive) hubV1RegistrationView { } } -// writeHubV1RepoCapError is the v1 over-cap answer for create (and, later, PATCH): 413 +// writeHubV1RepoCapError is the v1 over-cap answer for create and PATCH: 413 // naming the limit, so a client can read it without parsing the message. func writeHubV1RepoCapError(w http.ResponseWriter, err error, maxRepos int) { writeHubV1JSON(w, http.StatusRequestEntityTooLarge, "", hubV1RepoCapBody(err, maxRepos)) diff --git a/src/pkg/hub/selfservice_v1_api_test.go b/src/pkg/hub/selfservice_v1_api_test.go index 6844306290..366f910732 100644 --- a/src/pkg/hub/selfservice_v1_api_test.go +++ b/src/pkg/hub/selfservice_v1_api_test.go @@ -144,6 +144,7 @@ func TestHubV1Discovery(t *testing.T) { "create": "POST /api/hub/v1/registrations", "list": "GET /api/hub/v1/registrations", "get": "GET /api/hub/v1/registrations/{id}", + "update": "PATCH /api/hub/v1/registrations/{id}", "rotate_key": "POST /api/hub/v1/registrations/{id}/keys", "delete": "DELETE /api/hub/v1/registrations/{id}", } @@ -156,8 +157,11 @@ func TestHubV1Discovery(t *testing.T) { t.Errorf("operation %s = %+v, want %s", name, op, route) } } - if len(d.PatchFields) != 0 { - t.Fatalf("patch_fields = %v, want none until update exists", d.PatchFields) + if !reflect.DeepEqual(d.PatchFields, []string{"repos", "dashboard_url"}) { + t.Fatalf("patch_fields = %v, want repos and dashboard_url (org is not editable)", d.PatchFields) + } + if got["update"].IfMatch != "required" { + t.Fatalf("update if_match = %q, want required", got["update"].IfMatch) } if got := rec.Header().Get("Content-Type"); got != "application/json" { t.Fatalf("Content-Type = %q", got) @@ -510,6 +514,7 @@ func TestHubV1FlagOffHidesEveryRoute(t *testing.T) { {"create", http.MethodPost, path, env.s.handleHubV1Create}, {"list", http.MethodGet, path, env.s.handleHubV1List}, {"get", http.MethodGet, path + "/" + id, env.s.handleHubV1Get}, + {"update", http.MethodPatch, path + "/" + id, env.s.handleHubV1Patch}, {"rotate", http.MethodPost, path + "/" + id + "/keys", env.s.handleHubV1RotateKey}, {"delete", http.MethodDelete, path + "/" + id, env.s.handleHubV1Delete}, } @@ -539,6 +544,7 @@ func TestHubV1RoutesRequireSession(t *testing.T) { {"create", http.MethodPost, path, env.s.handleHubV1Create}, {"list", http.MethodGet, path, env.s.handleHubV1List}, {"get", http.MethodGet, path + "/" + id, env.s.handleHubV1Get}, + {"update", http.MethodPatch, path + "/" + id, env.s.handleHubV1Patch}, {"rotate", http.MethodPost, path + "/" + id + "/keys", env.s.handleHubV1RotateKey}, {"delete", http.MethodDelete, path + "/" + id, env.s.handleHubV1Delete}, } diff --git a/src/pkg/hub/selfservice_v1_patch.go b/src/pkg/hub/selfservice_v1_patch.go new file mode 100644 index 0000000000..4ca649ac53 --- /dev/null +++ b/src/pkg/hub/selfservice_v1_patch.go @@ -0,0 +1,323 @@ +package hub + +// Hub registration protocol v1, rollout step 1: PATCH of a registration's +// repos and dashboard_url (hivecommons/hive#18642, #19056). +// +// PATCH /api/hub/v1/registrations/{id} edits a registration in place. The +// heartbeat key is never touched, so an edit causes no outage: before this, +// adding a repo meant deleting the registration (revoking its key) and +// 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. +// - 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 +// GET /repos/{owner}/{repo} as create, with the owner's stored token). +// Repos that stay keep their proof time; removed repos lose theirs. +// - org, the owner, the ID, the keys and every timestamp are not editable: +// a body naming any other field is a 400, and the store restores them +// after the edit regardless. +// - The response and the audit line carry no key and no hash. Nothing here +// writes to GitHub. + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "sort" + "strings" +) + +const ( + hubV1PatchFieldRepos = "repos" + hubV1PatchFieldDashboardURL = "dashboard_url" + hubV1PatchFieldOrg = "org" +) + +// hubV1RepoDelta is the {add, remove} form of the repos field. The other form +// is a full list that replaces the registration's repos. +type hubV1RepoDelta struct { + Add []string `json:"add"` + Remove []string `json:"remove"` +} + +// hubV1PatchRefusal is a refusal the planning step produces: a status and the +// JSON body to send with it. +type hubV1PatchRefusal struct { + status int + body map[string]any +} + +func hubV1Refuse(status int, format string, args ...any) *hubV1PatchRefusal { + return &hubV1PatchRefusal{status: status, body: map[string]any{"error": fmt.Sprintf(format, args...)}} +} + +// hubV1PatchPlan is a validated edit, relative to the record it was planned +// against. +type hubV1PatchPlan struct { + repos []string + added []string + removed []string + dashboardURL string + dashboardChanged bool +} + +func (p hubV1PatchPlan) changed() bool { + return len(p.added) > 0 || len(p.removed) > 0 || p.dashboardChanged +} + +// hubV1PlanPatch validates a PATCH body against the record h and returns the +// edit it describes. It makes no GitHub call and writes nothing. +func hubV1PlanPatch(ctx context.Context, h SelfServiceHive, data []byte) (hubV1PatchPlan, *hubV1PatchRefusal) { + plan := hubV1PatchPlan{repos: h.Repos, dashboardURL: h.DashboardURL} + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil || fields == nil { + return plan, hubV1Refuse(http.StatusBadRequest, "the body must be a JSON object with %q and/or %q", hubV1PatchFieldRepos, hubV1PatchFieldDashboardURL) + } + names := make([]string, 0, len(fields)) + for name := range fields { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + switch name { + case hubV1PatchFieldRepos, hubV1PatchFieldDashboardURL: + case hubV1PatchFieldOrg: + return plan, hubV1Refuse(http.StatusBadRequest, "org cannot be changed on a registration: changing it would mean proving every repo again; delete the registration and register it again") + default: + return plan, hubV1Refuse(http.StatusBadRequest, "field %q cannot be changed; a registration accepts %q and %q", name, hubV1PatchFieldRepos, hubV1PatchFieldDashboardURL) + } + } + if len(fields) == 0 { + return plan, hubV1Refuse(http.StatusBadRequest, "send %q and/or %q", hubV1PatchFieldRepos, hubV1PatchFieldDashboardURL) + } + + if raw, ok := fields[hubV1PatchFieldRepos]; ok { + if refusal := hubV1PlanRepos(&plan, h, raw); refusal != nil { + return plan, refusal + } + } + if raw, ok := fields[hubV1PatchFieldDashboardURL]; ok { + var requested string + if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) || json.Unmarshal(raw, &requested) != nil { + return plan, hubV1Refuse(http.StatusBadRequest, "%s must be a string; send an empty string to clear it", hubV1PatchFieldDashboardURL) + } + validated, err := selfServiceValidateDashboardURL(ctx, requested) + if err != nil { + return plan, hubV1Refuse(http.StatusBadRequest, "%s", err.Error()) + } + plan.dashboardURL = validated + plan.dashboardChanged = validated != h.DashboardURL + } + return plan, nil +} + +// hubV1PlanRepos fills plan's repo list and its added and removed sets from +// the repos field: a JSON list replaces the repos, an {add, remove} object +// changes them. Existing repos keep their stored spelling. +func hubV1PlanRepos(plan *hubV1PatchPlan, h SelfServiceHive, raw json.RawMessage) *hubV1PatchRefusal { + shapeError := hubV1Refuse(http.StatusBadRequest, "%s must be a list of owner/name repos or an object with add and remove lists", hubV1PatchFieldRepos) + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 { + return shapeError + } + var requested []string + switch trimmed[0] { + case '[': + if err := json.Unmarshal(trimmed, &requested); err != nil { + return shapeError + } + case '{': + var delta hubV1RepoDelta + if err := decodeStrict(trimmed, &delta); err != nil { + return hubV1Refuse(http.StatusBadRequest, "%s takes only add and remove lists of owner/name repos", hubV1PatchFieldRepos) + } + var refusal *hubV1PatchRefusal + requested, refusal = hubV1ApplyRepoDelta(h.Repos, delta) + if refusal != nil { + return refusal + } + default: + return shapeError + } + + if maxRepos := selfServiceMaxRepos(); len(requested) > maxRepos { + return &hubV1PatchRefusal{ + status: http.StatusRequestEntityTooLarge, + body: hubV1RepoCapBody(fmt.Errorf("at most %d repos per registration", maxRepos), maxRepos), + } + } + validated, err := selfServiceValidateRepos(requested) + if err != nil { + return hubV1Refuse(http.StatusBadRequest, "%s", err.Error()) + } + + current := make(map[string]string, len(h.Repos)) + for _, repo := range h.Repos { + current[strings.ToLower(repo)] = repo + } + keep := make(map[string]struct{}, len(validated)) + plan.repos = make([]string, 0, len(validated)) + plan.added = nil + for _, repo := range validated { + key := strings.ToLower(repo) + keep[key] = struct{}{} + if existing, ok := current[key]; ok { + plan.repos = append(plan.repos, existing) + continue + } + plan.repos = append(plan.repos, repo) + plan.added = append(plan.added, repo) + } + plan.removed = nil + for _, repo := range h.Repos { + if _, ok := keep[strings.ToLower(repo)]; !ok { + plan.removed = append(plan.removed, repo) + } + } + return nil +} + +// hubV1ApplyRepoDelta returns the repo list after applying delta to current. +// A removal of a repo the registration does not list is ignored, so a retried +// request is harmless; adding and removing the same repo is refused. +func hubV1ApplyRepoDelta(current []string, delta hubV1RepoDelta) ([]string, *hubV1PatchRefusal) { + remove := make(map[string]struct{}, len(delta.Remove)) + for _, repo := range delta.Remove { + remove[strings.ToLower(strings.TrimSpace(repo))] = struct{}{} + } + out := make([]string, 0, len(current)+len(delta.Add)) + for _, repo := range current { + if _, drop := remove[strings.ToLower(repo)]; !drop { + out = append(out, repo) + } + } + for _, raw := range delta.Add { + repo := strings.TrimSpace(raw) + if _, drop := remove[strings.ToLower(repo)]; drop { + return nil, hubV1Refuse(http.StatusBadRequest, "repo %q is in both add and remove", repo) + } + if !hubV1ContainsFold(out, repo) { + out = append(out, repo) + } + } + return out, nil +} + +func hubV1ContainsFold(repos []string, repo string) bool { + for _, existing := range repos { + if strings.EqualFold(existing, repo) { + return true + } + } + return false +} + +// hubV1SameRepos reports whether two repo lists name the same repos in the +// same order, ignoring case. +func hubV1SameRepos(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if !strings.EqualFold(a[i], b[i]) { + return false + } + } + return true +} + +// writeHubV1Stale answers 412 with the current ETag so the client can retry. +func (s *HubServer) writeHubV1Stale(w http.ResponseWriter, id string) { + current, _ := s.selfService.get(id) + writeHubV1JSON(w, http.StatusPreconditionFailed, selfServiceETag(current), map[string]any{ + "error": "the registration changed since you read it; GET it again and retry", + }) +} + +// handleHubV1Patch is PATCH /api/hub/v1/registrations/{id}: change repos +// and/or dashboard_url with the key kept. 200 {registration} with the new +// ETag; an edit that changes nothing answers 200 with the current ETag and +// does not bump the revision. +func (s *HubServer) handleHubV1Patch(w http.ResponseWriter, r *http.Request) { + if !s.requireSelfServiceEnabled(w) { + return + } + login := s.getAuthUser(r) + h, ok := s.selfServiceOwnedHive(w, r, login, false) + if !ok { + return + } + ifMatch := strings.TrimSpace(r.Header.Get("If-Match")) + if ifMatch == "" { + writeHubV1JSON(w, http.StatusPreconditionRequired, selfServiceETag(h), map[string]any{ + "error": "If-Match is required: GET the registration and send its ETag", + }) + return + } + if !selfServiceETagMatches(h, ifMatch) { + s.writeHubV1Stale(w, h.ID) + return + } + data, err := io.ReadAll(io.LimitReader(r.Body, selfServiceRequestBodyLimit())) + if err != nil { + writeJSONError(w, http.StatusBadRequest, "could not read the request body") + return + } + plan, refusal := hubV1PlanPatch(r.Context(), h, data) + if refusal != nil { + s.auditSelfServiceRefused(login, h.ID, selfServiceRefusedInvalidUpdate) + writeHubV1JSON(w, refusal.status, "", refusal.body) + return + } + if !plan.changed() { + writeHubV1JSON(w, http.StatusOK, selfServiceETag(h), map[string]any{"registration": s.hubV1View(h)}) + return + } + if len(plan.added) > 0 { + user := loadSaaSUser(login) + if user == nil { + writeJSONError(w, http.StatusUnauthorized, "not authenticated") + return + } + if !s.selfServiceProveOwnership(w, r, login, h.ID, user, plan.added) { + return + } + } + + now := s.selfService.clock().UTC() + stored, err := s.selfService.update(h.ID, ifMatch, func(n *SelfServiceHive) error { + // An If-Match of "*" skips the ETag comparison, so make sure the repos + // this plan was computed from are still the stored ones. + if !hubV1SameRepos(n.Repos, h.Repos) { + return errSelfServiceStale + } + n.Repos = plan.repos + n.RepoProofs = selfServiceProofTimes(n.RepoProofs, plan.repos, n.OwnershipCheckedAt, now, plan.added) + n.DashboardURL = plan.dashboardURL + return nil + }) + if err != nil { + switch { + case errors.Is(err, errSelfServiceNotFound): + writeJSONError(w, http.StatusNotFound, "self-hosted hive not found") + case errors.Is(err, errSelfServiceStale): + s.writeHubV1Stale(w, h.ID) + default: + s.logger.Error("self-service update: store write failed", "user", login, "hive", h.ID, "error", err) + writeJSONError(w, http.StatusInternalServerError, "could not persist the change") + } + return + } + s.logger.Info("audit: selfservice_hive_updated", "user", login, "hive", h.ID, + "repos_added", len(plan.added), "repos_removed", len(plan.removed), + "dashboard_changed", plan.dashboardChanged, "revision", stored.Revision) + writeHubV1JSON(w, http.StatusOK, selfServiceETag(stored), map[string]any{"registration": s.hubV1View(stored)}) +} diff --git a/src/pkg/hub/selfservice_v1_patch_test.go b/src/pkg/hub/selfservice_v1_patch_test.go new file mode 100644 index 0000000000..aae7f31b52 --- /dev/null +++ b/src/pkg/hub/selfservice_v1_patch_test.go @@ -0,0 +1,451 @@ +package hub + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +// Tests for PATCH /api/hub/v1/registrations/{id} (#18642, #19056). They reuse +// the v1 test env: stubbed GitHub, temp stores, the flag on. The GitHub stub +// answers admin for alice/lab, alice/tools and alice/bulk-*, not-admin for +// alice/readonly and 404 for anything else. + +func (env *selfServiceTestEnv) v1Patch(t *testing.T, user, id, ifMatch, body string) *httptest.ResponseRecorder { + t.Helper() + var headers map[string]string + if ifMatch != "" { + headers = map[string]string{"If-Match": ifMatch} + } + return env.v1(t, user, http.MethodPatch, hubV1BasePath+"/registrations/"+id, body, headers, env.s.handleHubV1Patch) +} + +// countProofs counts ownership calls the stub receives from now on. +func (env *selfServiceTestEnv) countProofs() *atomic.Int64 { + var n atomic.Int64 + env.repoCheckGate = func() { n.Add(1) } + return &n +} + +func repoNames(v hubV1RegistrationView) []string { + return v.Repos +} + +func sameStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestHubV1PatchAddRepoKeepsKeyAndProvesOnlyTheAddedRepo(t *testing.T) { + env := newHubV1TestEnv(t) + id, key := env.registerHappy(t) + before, _ := env.s.selfService.get(id) + etag := env.etagOf(t, id) + calls := env.countProofs() + *env.now = env.now.Add(time.Hour) + + rec := env.v1Patch(t, selfServiceTestUser, id, etag, `{"repos":{"add":["alice/bulk-01"]}}`) + if rec.Code != http.StatusOK { + t.Fatalf("patch: %d %s", rec.Code, rec.Body.String()) + } + if got := calls.Load(); got != 1 { + t.Fatalf("ownership calls = %d, want 1 (only the added repo is proven)", got) + } + view := decodeV1Registration(t, rec) + if want := []string{"alice/lab", "alice/tools", "alice/bulk-01"}; !sameStrings(repoNames(view), want) { + t.Fatalf("repos = %v, want %v", view.Repos, want) + } + newETag := rec.Header().Get("ETag") + if newETag == "" || newETag == etag || view.ETag != newETag { + t.Fatalf("etag header %q, body %q, old %q", newETag, view.ETag, etag) + } + if _, ok := env.s.verifyHeartbeatBearerGeneration(key, id); !ok { + t.Fatal("the registration key stopped authenticating after PATCH") + } + after, _ := env.s.selfService.get(id) + if after.KeyHash != before.KeyHash || after.PrevKeyHash != before.PrevKeyHash || after.Owner != before.Owner || after.Org != before.Org { + t.Fatal("PATCH changed the key, owner or org") + } + if after.Revision != before.Revision+1 { + t.Fatalf("revision = %d, want %d", after.Revision, before.Revision+1) + } + proofs := map[string]bool{} + for _, p := range view.RepoProofs { + proofs[p.Repo] = p.CheckedAt.Equal(before.OwnershipCheckedAt) + if p.Repo == "alice/bulk-01" && !p.CheckedAt.Equal(*env.now) { + t.Fatalf("added repo proof time = %v, want %v", p.CheckedAt, *env.now) + } + } + if !proofs["alice/lab"] || !proofs["alice/tools"] { + t.Fatalf("existing repos lost their proof time: %v", view.RepoProofs) + } + if strings.Contains(rec.Body.String(), key) || strings.Contains(rec.Body.String(), "key_hash") { + t.Fatal("PATCH response leaked key material") + } + logs := env.logs.String() + if !strings.Contains(logs, "audit: selfservice_hive_updated") || strings.Contains(logs, key) || strings.Contains(logs, after.KeyHash) { + t.Fatalf("audit line missing or leaking: %s", logs) + } + // The stale ETag from before the edit no longer applies. + if stale := env.v1Patch(t, selfServiceTestUser, id, etag, `{"repos":{"add":["alice/bulk-02"]}}`); stale.Code != http.StatusPreconditionFailed || stale.Header().Get("ETag") != newETag { + t.Fatalf("stale PATCH: %d etag %q", stale.Code, stale.Header().Get("ETag")) + } +} + +func TestHubV1PatchReplaceAndRemoveNeedNoProof(t *testing.T) { + env := newHubV1TestEnv(t) + id, key := env.registerHappy(t) + calls := env.countProofs() + + rec := env.v1Patch(t, selfServiceTestUser, id, env.etagOf(t, id), `{"repos":["alice/lab"]}`) + if rec.Code != http.StatusOK { + t.Fatalf("replace: %d %s", rec.Code, rec.Body.String()) + } + view := decodeV1Registration(t, rec) + if !sameStrings(view.Repos, []string{"alice/lab"}) || len(view.RepoProofs) != 1 { + t.Fatalf("after replace: repos %v proofs %v", view.Repos, view.RepoProofs) + } + rec = env.v1Patch(t, selfServiceTestUser, id, rec.Header().Get("ETag"), `{"repos":{"add":["alice/tools"],"remove":["ALICE/LAB"]}}`) + if rec.Code != http.StatusOK { + t.Fatalf("swap: %d %s", rec.Code, rec.Body.String()) + } + if got := decodeV1Registration(t, rec).Repos; !sameStrings(got, []string{"alice/tools"}) { + t.Fatalf("after swap repos = %v", got) + } + // Replace proved nothing; the swap proved only alice/tools. + if got := calls.Load(); got != 1 { + t.Fatalf("ownership calls = %d, want 1", got) + } + stored, _ := env.s.selfService.get(id) + if _, ok := stored.RepoProofs["alice/lab"]; ok || len(stored.RepoProofs) != 1 { + t.Fatalf("removed repo kept a proof: %v", stored.RepoProofs) + } + if _, ok := env.s.verifyHeartbeatBearerGeneration(key, id); !ok { + t.Fatal("key stopped authenticating") + } +} + +func TestHubV1PatchDashboardURL(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + calls := env.countProofs() + + rec := env.v1Patch(t, selfServiceTestUser, id, env.etagOf(t, id), `{"dashboard_url":"https://new.example.org/dash"}`) + if rec.Code != http.StatusOK { + t.Fatalf("set: %d %s", rec.Code, rec.Body.String()) + } + if got := decodeV1Registration(t, rec).DashboardURL; got != "https://new.example.org/dash" { + t.Fatalf("dashboard_url = %q", got) + } + if calls.Load() != 0 { + t.Fatal("a dashboard_url edit made a GitHub call") + } + rec = env.v1Patch(t, selfServiceTestUser, id, rec.Header().Get("ETag"), `{"dashboard_url":""}`) + if rec.Code != http.StatusOK || decodeV1Registration(t, rec).DashboardURL != "" { + t.Fatalf("clear: %d %s", rec.Code, rec.Body.String()) + } + for name, body := range map[string]string{ + "http scheme": `{"dashboard_url":"http://new.example.org/"}`, + "credentials": `{"dashboard_url":"https://user:pw@new.example.org/"}`, + "not a url": `{"dashboard_url":"lab"}`, + "null": `{"dashboard_url":null}`, + "number": `{"dashboard_url":7}`, + } { + t.Run(name, func(t *testing.T) { + bad := env.v1Patch(t, selfServiceTestUser, id, env.etagOf(t, id), body) + if bad.Code != http.StatusBadRequest { + t.Fatalf("%s: %d %s", name, bad.Code, bad.Body.String()) + } + }) + } +} + +func TestHubV1PatchRequiresAFreshIfMatch(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + etag := env.etagOf(t, id) + calls := env.countProofs() + body := `{"repos":{"add":["alice/bulk-01"]}}` + + missing := env.v1Patch(t, selfServiceTestUser, id, "", body) + if missing.Code != http.StatusPreconditionRequired || missing.Header().Get("ETag") != etag { + t.Fatalf("missing If-Match: %d etag %q", missing.Code, missing.Header().Get("ETag")) + } + for name, header := range map[string]string{ + "wrong tag": `"0000000000000000000000000"`, + "weak tag": "W/" + etag, + } { + rec := env.v1Patch(t, selfServiceTestUser, id, header, body) + if rec.Code != http.StatusPreconditionFailed || rec.Header().Get("ETag") != etag { + t.Fatalf("%s: %d etag %q", name, rec.Code, rec.Header().Get("ETag")) + } + } + if calls.Load() != 0 { + t.Fatal("a refused precondition still reached GitHub") + } + if after, _ := env.s.selfService.get(id); len(after.Repos) != 2 { + t.Fatalf("a refused PATCH changed the repos: %v", after.Repos) + } + // A list of tags is accepted when one matches. + if rec := env.v1Patch(t, selfServiceTestUser, id, `"abc", `+etag, body); rec.Code != http.StatusOK { + t.Fatalf("tag list: %d %s", rec.Code, rec.Body.String()) + } +} + +func TestHubV1PatchTwoEditorsOneWins(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + etag := env.etagOf(t, id) + first := env.v1Patch(t, selfServiceTestUser, id, etag, `{"dashboard_url":"https://one.example.org/"}`) + second := env.v1Patch(t, selfServiceTestUser, id, etag, `{"dashboard_url":"https://two.example.org/"}`) + if first.Code != http.StatusOK || second.Code != http.StatusPreconditionFailed { + t.Fatalf("first %d, second %d", first.Code, second.Code) + } + if stored, _ := env.s.selfService.get(id); stored.DashboardURL != "https://one.example.org/" { + t.Fatalf("dashboard_url = %q: the second editor overwrote the first", stored.DashboardURL) + } +} + +func TestHubV1PatchWildcardStillRefusesAConcurrentRepoChange(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + // While the ownership proof is in flight, someone else edits the repos. + env.repoCheckGate = func() { + env.repoCheckGate = nil + _, err := env.s.selfService.update(id, "", func(h *SelfServiceHive) error { + h.Repos = []string{"alice/lab"} + return nil + }) + if err != nil { + t.Errorf("concurrent edit: %v", err) + } + } + rec := env.v1Patch(t, selfServiceTestUser, id, "*", `{"repos":{"add":["alice/bulk-01"]}}`) + if rec.Code != http.StatusPreconditionFailed { + t.Fatalf("PATCH after a concurrent repo change: %d %s", rec.Code, rec.Body.String()) + } + if stored, _ := env.s.selfService.get(id); !sameStrings(stored.Repos, []string{"alice/lab"}) { + t.Fatalf("repos = %v: the stale plan was applied", stored.Repos) + } +} + +func TestHubV1PatchNoChangeKeepsTheETag(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + etag := env.etagOf(t, id) + calls := env.countProofs() + for name, body := range map[string]string{ + "same dashboard": `{"dashboard_url":"https://lab.example.org/"}`, + "re-add existing": `{"repos":{"add":["alice/lab"]}}`, + "re-add with other case": `{"repos":{"add":["Alice/Lab"]}}`, + "remove an unlisted repo": `{"repos":{"remove":["alice/never"]}}`, + "same list": `{"repos":["alice/lab","alice/tools"]}`, + "empty delta": `{"repos":{}}`, + } { + rec := env.v1Patch(t, selfServiceTestUser, id, etag, body) + if rec.Code != http.StatusOK || rec.Header().Get("ETag") != etag { + t.Fatalf("%s: %d etag %q (%s)", name, rec.Code, rec.Header().Get("ETag"), rec.Body.String()) + } + } + if calls.Load() != 0 { + t.Fatal("a no-op PATCH made a GitHub call") + } + if strings.Contains(env.logs.String(), "selfservice_hive_updated") { + t.Fatal("a no-op PATCH wrote an update audit line") + } +} + +func TestHubV1PatchRefusals(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + cases := []struct { + name string + body string + status int + want string + }{ + {"org is not editable", `{"org":"someone-else"}`, http.StatusBadRequest, "org cannot be changed"}, + {"org with a valid field", `{"org":"x","dashboard_url":""}`, http.StatusBadRequest, "org cannot be changed"}, + {"owner", `{"owner":"bob"}`, http.StatusBadRequest, `"owner" cannot be changed`}, + {"key", `{"key":"anything"}`, http.StatusBadRequest, `"key" cannot be changed`}, + {"empty object", `{}`, http.StatusBadRequest, "send"}, + {"not an object", `[]`, http.StatusBadRequest, "JSON object"}, + {"not json", `nope`, http.StatusBadRequest, "JSON object"}, + {"null body", `null`, http.StatusBadRequest, "JSON object"}, + {"repos null", `{"repos":null}`, http.StatusBadRequest, "must be a list"}, + {"repos string", `{"repos":"alice/lab"}`, http.StatusBadRequest, "must be a list"}, + {"repos list of numbers", `{"repos":[1]}`, http.StatusBadRequest, "must be a list"}, + {"delta unknown key", `{"repos":{"drop":["alice/lab"]}}`, http.StatusBadRequest, "add and remove"}, + {"add and remove the same repo", `{"repos":{"add":["alice/tools"],"remove":["Alice/Tools"]}}`, http.StatusBadRequest, "both add and remove"}, + {"remove every repo", `{"repos":{"remove":["alice/lab","alice/tools"]}}`, http.StatusBadRequest, "at least one"}, + {"replace with nothing", `{"repos":[]}`, http.StatusBadRequest, "at least one"}, + {"bare org repo", `{"repos":{"add":["alice"]}}`, http.StatusBadRequest, "owner/name"}, + {"path escape repo", `{"repos":{"add":["alice/.."]}}`, http.StatusBadRequest, "owner/name"}, + } + calls := env.countProofs() + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := env.v1Patch(t, selfServiceTestUser, id, env.etagOf(t, id), tc.body) + if rec.Code != tc.status || !strings.Contains(decodeError(t, rec)["error"], tc.want) { + t.Fatalf("%s: %d %s, want %d containing %q", tc.name, rec.Code, rec.Body.String(), tc.status, tc.want) + } + }) + } + if calls.Load() != 0 { + t.Fatal("a refused body reached GitHub") + } + stored, _ := env.s.selfService.get(id) + if stored.Revision != 1 || !sameStrings(stored.Repos, []string{"alice/lab", "alice/tools"}) || stored.Org != "alice" { + t.Fatalf("a refused PATCH changed the record: %+v", stored) + } + if !strings.Contains(env.logs.String(), "reason=invalid_update") { + t.Fatal("refusals are not audited as invalid_update") + } +} + +func TestHubV1PatchOwnershipProofFailures(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + etag := env.etagOf(t, id) + + rec := env.v1Patch(t, selfServiceTestUser, id, etag, `{"repos":{"add":["alice/readonly"]}}`) + if rec.Code != http.StatusForbidden || decodeError(t, rec)["repo"] != "alice/readonly" { + t.Fatalf("not admin: %d %s", rec.Code, rec.Body.String()) + } + rec = env.v1Patch(t, selfServiceTestUser, id, etag, `{"repos":{"add":["alice/bulk-01","alice/unknown"]},"dashboard_url":"https://moved.example.org/"}`) + if rec.Code != http.StatusForbidden { + t.Fatalf("one unproven repo in a batch: %d %s", rec.Code, rec.Body.String()) + } + stored, _ := env.s.selfService.get(id) + if stored.Revision != 1 || len(stored.Repos) != 2 || stored.DashboardURL != "https://lab.example.org/" { + t.Fatalf("a failed proof still applied part of the edit: %+v", stored) + } + if got := env.etagOf(t, id); got != etag { + t.Fatal("a failed proof changed the ETag") + } + if !strings.Contains(env.logs.String(), "reason=not_repo_admin") { + t.Fatal("proof failure not audited") + } +} + +func TestHubV1PatchOverTheRepoCap(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + t.Setenv(selfServiceMaxReposEnv, "2") + calls := env.countProofs() + etag := env.etagOf(t, id) + + for name, body := range map[string]string{ + "delta": `{"repos":{"add":["alice/bulk-01"]}}`, + "replacement": `{"repos":["alice/lab","alice/tools","alice/bulk-01"]}`, + } { + rec := env.v1Patch(t, selfServiceTestUser, id, etag, body) + var resp struct { + Limit string `json:"limit"` + MaxRepos int `json:"max_repos"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if rec.Code != http.StatusRequestEntityTooLarge || resp.Limit != "max_repos" || resp.MaxRepos != 2 { + t.Fatalf("%s: %d %s", name, rec.Code, rec.Body.String()) + } + } + if calls.Load() != 0 { + t.Fatal("an over-cap PATCH reached GitHub") + } + // Staying at the cap is fine: swap one repo for another. + rec := env.v1Patch(t, selfServiceTestUser, id, etag, `{"repos":{"add":["alice/bulk-01"],"remove":["alice/tools"]}}`) + if rec.Code != http.StatusOK { + t.Fatalf("swap at the cap: %d %s", rec.Code, rec.Body.String()) + } +} + +func TestHubV1PatchIsOwnerSessionOnly(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + etag := env.etagOf(t, id) + body := `{"dashboard_url":"https://other.example.org/"}` + + for name, user := range map[string]string{"another user": selfServiceTestOther, "hub admin who is not the owner": selfServiceTestAdmin} { + if rec := env.v1Patch(t, user, id, etag, body); rec.Code != http.StatusNotFound { + t.Fatalf("%s: %d, want 404", name, rec.Code) + } + } + if rec := env.v1Patch(t, "", id, etag, body); rec.Code != http.StatusUnauthorized { + t.Fatalf("anonymous: %d, want 401", rec.Code) + } + if rec := env.v1Patch(t, selfServiceTestUser, "byo-alice--missing", etag, body); rec.Code != http.StatusNotFound { + t.Fatalf("missing hive: %d, want 404", rec.Code) + } + // The registration key is not a credential for PATCH. + _, key := env.registerHappy2(t) + req := httptest.NewRequest(http.MethodPatch, hubV1BasePath+"/registrations/"+id, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+key) + req.Header.Set("If-Match", etag) + req.SetPathValue("id", id) + rec := httptest.NewRecorder() + env.s.requireAuth(env.s.handleHubV1Patch)(rec, req) + if rec.Code == http.StatusOK { + t.Fatalf("a registration key edited a registration: %d", rec.Code) + } + if stored, _ := env.s.selfService.get(id); stored.DashboardURL != "https://lab.example.org/" { + t.Fatal("an unauthorized PATCH changed the record") + } +} + +// registerHappy2 registers a second hive for alice and returns its ID and key. +func (env *selfServiceTestEnv) registerHappy2(t *testing.T) (string, string) { + t.Helper() + rec := env.v1(t, selfServiceTestUser, http.MethodPost, hubV1BasePath+"/registrations", `{"name":"second","repos":["alice/lab"]}`, nil, env.s.handleHubV1Create) + if rec.Code != http.StatusCreated { + t.Fatalf("second registration: %d %s", rec.Code, rec.Body.String()) + } + var resp struct { + Registration hubV1RegistrationView `json:"registration"` + Key string `json:"key"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + return resp.Registration.ID, resp.Key +} + +// A PATCH shows up through the v6 list route unchanged in shape: the legacy +// view carries the new repos and dashboard_url and no v1-only fields. +func TestHubV1PatchIsVisibleThroughTheLegacyList(t *testing.T) { + env := newHubV1TestEnv(t) + id, _ := env.registerHappy(t) + rec := env.v1Patch(t, selfServiceTestUser, id, env.etagOf(t, id), `{"repos":{"add":["alice/bulk-01"]},"dashboard_url":"https://moved.example.org/"}`) + if rec.Code != http.StatusOK { + t.Fatalf("patch: %d %s", rec.Code, rec.Body.String()) + } + list := env.list(t, selfServiceTestUser) + var resp struct { + Hives []map[string]any `json:"hives"` + } + if err := json.Unmarshal(list.Body.Bytes(), &resp); err != nil || len(resp.Hives) != 1 { + t.Fatalf("legacy list: %v %s", err, list.Body.String()) + } + hive := resp.Hives[0] + repos, ok := hive["repos"].([]any) + if hive["dashboard_url"] != "https://moved.example.org/" || !ok || len(repos) != 3 { + t.Fatalf("legacy view = %v", hive) + } + for _, v1Only := range []string{"etag", "repo_proofs"} { + if _, ok := hive[v1Only]; ok { + t.Fatalf("legacy view gained %q", v1Only) + } + } +}