carlos / platform Public

link: save a rotated key with its pending flag; clear only that rotation

Astra final re-review, item C: the home's "rotation pending" warning
could be lost or untruthful.

- registry: RotateHomeLinkKey saves the new token, rotate_pending and a
  bumped rotate_gen in one UPDATE (additive rotate_gen column), so the
  key is never saved without its flag. ClearHomeLinkRotatePending clears
  only while rotate_gen still names the rotation the caller confirmed.
  Both have remote dispatch cases; SetHomeLinkRotatePending is gone.
- console rotate door: one write; when it fails nothing was saved, and
  the door answers 500 with a new draft naming the recovery instead of
  reporting success with the warning lost.
- console status: the clear runs under homeLink.ops and names the
  rotation it read, so a status confirming rotation 1 that resumes after
  rotation 2 leaves rotation 2's flag set.
- CLI: link status prints a draft "not confirmed yet" line when it could
  not ask the serving console during a pending rotation, in place of
  "still accepts the old key"; nothing extra once confirmed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 987b337dd2fbbf11594cae10b289400b72c2eeaf parent 7f9ccae
9 files changed, +368 −64
  • internal/console/apilinks_test.go +144 −0
  • internal/console/homelink.go +33 −14
  • internal/console/links_copy.go +5 −0
  • internal/console/view.go +2 −1
  • internal/registry/homelink.go +71 −20
  • internal/registry/homelink_test.go +91 −21
  • internal/registry/remote_dispatch.go +4 −2
  • link_cli.go +6 −4
  • link_cli_test.go +12 −2
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go
index f55ee3810..a880eb67a 100644
--- a/internal/console/apilinks_test.go
+++ b/internal/console/apilinks_test.go
@@ -1309,6 +1309,150 @@ func TestRotatePendingCarriedToTheHome(t *testing.T) {
}
}
+// rotatePendingSetup is TestRotatePendingCarriedToTheHome's fixture: a real
+// serving console whose registry refuses the link's new hash while
+// fault.putFail is above zero, and a real home console holding the link.
+func rotatePendingSetup(t *testing.T, code string) (serving, home *consoleFixture, l linked, fault *linkGenFault, op string) {
+ t.Helper()
+ serving = newLinkFixture(t, "tunnel.example.com")
+ l = mintLink(t, serving, signInPaul(t, serving), "shop-home")
+ fault = &linkGenFault{consoleRegistry: linkRegistryOf(t, serving), gen: 2, putFail: 1 << 20}
+ serving.srv.linkRegistry = func() (consoleRegistry, error) { return fault, nil }
+ home = newHomeFixture(t)
+ op = cliToken(t, home, "paul@keymail.dev", code)
+ if err := homeRegistry(t, home).PutHomeLink(registry.HomeLink{ID: l.id, ServingURL: serving.ts.URL,
+ TunnelURL: "https://tunnel.example.com/register", Token: l.token, Account: serving.sqid, AppsDomain: "apps.example.com"}); err != nil {
+ t.Fatal(err)
+ }
+ return serving, home, l, fault, op
+}
+
+// setPutFail makes PutLinkChannel fail n times at generation gen or above.
+func (f *linkGenFault) setPutFail(gen uint64, n int) {
+ f.mu.Lock()
+ f.gen, f.putFail = gen, n
+ f.mu.Unlock()
+}
+
+// homeRotatePending rotates through the home and requires the pending
+// answer.
+func homeRotatePending(t *testing.T, home *consoleFixture, op string) {
+ t.Helper()
+ status, body := homeReq(t, home, http.MethodPost, "/api/cli/link/rotate", op, "")
+ var out map[string]any
+ if err := json.Unmarshal([]byte(body), &out); status != http.StatusOK || err != nil ||
+ out["rotated"] != true || out["revocation"] != "pending" {
+ t.Fatalf("home rotate = %d %s; want 200 rotated, revocation pending", status, body)
+ }
+}
+
+// TestRotationClearIsBoundToItsRotation: a status whose serving call
+// confirmed rotation 1 clears only rotation 1's flag (Astra final re-review,
+// C). The status stops at a barrier after its serving call succeeded with
+// rotation 1's key; rotation 2 runs and answers pending; the status
+// resumes. Rotation 2's flag stays set, the next status reports it while
+// the serving console still refuses the new hash, and a status that reaches
+// it clears it.
+func TestRotationClearIsBoundToItsRotation(t *testing.T) {
+ _, home, _, fault, op := rotatePendingSetup(t, "code-home-rotate-race")
+ homeRotatePending(t, home, op)
+ one, err := homeRegistry(t, home).HomeLink()
+ if err != nil || one == nil || !one.RotatePending || one.RotateGen != 1 {
+ t.Fatalf("after rotation 1 the home holds %+v, %v", one, err)
+ }
+
+ // The serving registry takes rotation 1's hash: status A's serving call
+ // succeeds, and A stops before its clear.
+ fault.setPutFail(2, 0)
+ reached, release := make(chan struct{}), make(chan struct{})
+ var once, releaseOnce sync.Once
+ letGo := func() { releaseOnce.Do(func() { close(release) }) }
+ t.Cleanup(letGo) // before the fixtures' own cleanups wait on the handler
+ home.srv.homeLink.beforeRotateClear = func() {
+ once.Do(func() {
+ close(reached)
+ <-release
+ })
+ }
+ type answer struct {
+ status int
+ body string
+ err error
+ }
+ done := make(chan answer, 1)
+ go func() {
+ req, _ := http.NewRequest(http.MethodGet, home.ts.URL+"/api/cli/link", nil)
+ req.Header.Set("Authorization", "Bearer "+op)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ done <- answer{err: err}
+ return
+ }
+ defer res.Body.Close()
+ b, err := io.ReadAll(res.Body)
+ done <- answer{res.StatusCode, string(b), err}
+ }()
+ select {
+ case <-reached:
+ case <-time.After(20 * time.Second):
+ t.Fatal("status A never reached its clear")
+ }
+
+ // Rotation 2 (the link's generation 3) while A waits, its own sync
+ // refused: pending.
+ fault.setPutFail(3, 1<<20)
+ homeRotatePending(t, home, op)
+ if two, _ := homeRegistry(t, home).HomeLink(); two == nil || !two.RotatePending || two.RotateGen != 2 {
+ t.Fatalf("after rotation 2 the home holds %+v", two)
+ }
+ letGo()
+ var a answer
+ select {
+ case a = <-done:
+ case <-time.After(20 * time.Second):
+ t.Fatal("status A never answered")
+ }
+ if a.err != nil || a.status != http.StatusOK {
+ t.Fatalf("status A = %d %s %v", a.status, a.body, a.err)
+ }
+ if after, _ := homeRegistry(t, home).HomeLink(); after == nil || !after.RotatePending || after.RotateGen != 2 {
+ t.Fatalf("status A, confirming rotation 1, cleared rotation 2's flag: %+v", after)
+ }
+ if st := homeStatus(t, home, op); st.KeyRevocation != "pending" || st.ServingError == "" {
+ t.Fatalf("status while rotation 2's sync fails = %+v; want key_revocation pending", st)
+ }
+
+ // Rotation 2's hash applies: a status that reaches the serving console
+ // clears it.
+ fault.setPutFail(3, 0)
+ if st := homeStatus(t, home, op); st.KeyRevocation != "" || st.ServingError != "" {
+ t.Fatalf("status once rotation 2 applies = %+v; want nothing pending", st)
+ }
+ if l, _ := homeRegistry(t, home).HomeLink(); l == nil || l.RotatePending {
+ t.Fatalf("rotation 2's flag not cleared: %+v", l)
+ }
+}
+
+// TestRotateSaveFailureSavesNeither: when the home cannot save the rotated
+// key, the door fails (never 200 rotated with the warning lost), it names
+// the recovery, and the home holds neither the new key nor a pending flag:
+// they are one write (Astra final re-review, C). The registry refuses the
+// write because other users can read its file.
+func TestRotateSaveFailureSavesNeither(t *testing.T) {
+ serving, home, l, _, op := rotatePendingSetup(t, "code-home-rotate-save-fails")
+ chmodHomeRegistry(t, home.regPath, 0o644)
+ status, body := homeReq(t, home, http.MethodPost, "/api/cli/link/rotate", op, "")
+ chmodHomeRegistry(t, home.regPath, 0o640)
+ want := linkCopy(copyHomeLinkRotateNotSaved, "console", serving.ts.URL)
+ if status != http.StatusInternalServerError || !strings.Contains(body, want) || strings.Contains(body, `"rotated"`) {
+ t.Fatalf("rotate with the save refused = %d %s; want 500 %q", status, body, want)
+ }
+ stored, err := homeRegistry(t, home).HomeLink()
+ if err != nil || stored == nil || stored.Token != l.token || stored.RotatePending || stored.RotateGen != 0 {
+ t.Fatalf("after the refused save the home holds %+v, %v; want the old key, nothing pending", stored, err)
+ }
+}
+
// TestRotateAndUnlinkRetryTheirSync: the rotate and unlink doors retry their
// own sync three times before returning; past that the change stands and
// linkSyncPass finishes it.
diff --git a/internal/console/homelink.go b/internal/console/homelink.go
index 39badb6f9..3d00baf1a 100644
--- a/internal/console/homelink.go
+++ b/internal/console/homelink.go
@@ -51,6 +51,12 @@ type homeLinkState struct {
// barrier that supersedes a request at the last moment.
beforeSave func(seq uint64)
+ // beforeRotateClear, when non-nil, is called by a status whose serving
+ // call confirmed a pending rotation, just before it takes ops to clear
+ // the flag. Tests only: the barrier that lets a later rotation land
+ // in between.
+ beforeRotateClear func()
+
// pollEvery, when non-zero, replaces the serving console's poll
// interval. Tests only.
pollEvery time.Duration
@@ -452,13 +458,14 @@ func (s *Server) handleAPIHomeLinkStatus(w http.ResponseWriter, r *http.Request)
urls[p.App] = p.URL
}
// The serving console answers a link door only after syncing the
- // link's channel (linkRoute), so this answer, with the new key, is
- // the rotation applied: the hub registry no longer holds the old
- // key.
+ // link's channel (linkRoute), so this answer, with the key read
+ // above, is that rotation applied: the hub registry no longer holds
+ // the key before it.
if l.RotatePending {
- if err := reg.SetHomeLinkRotatePending(l.ID, false); err != nil {
- log.Printf("console: home link %s: clear the pending rotation: %v", l.ID, err)
+ if s.homeLink.beforeRotateClear != nil {
+ s.homeLink.beforeRotateClear()
}
+ s.homeLinkConfirmRotation(reg, l)
}
}
for _, a := range apps {
@@ -471,6 +478,20 @@ func (s *Server) handleAPIHomeLinkStatus(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, out)
}
+// homeLinkConfirmRotation clears the pending rotation l read, now that a
+// serving call made with its key succeeded. The clear names that rotation
+// (l.RotateGen), so a later rotation, saved since l was read, keeps its own
+// flag; and it runs under ops, so it never interleaves with a rotation's
+// serving call and save. A failed clear leaves the flag set, and the next
+// status that reaches the serving console clears it.
+func (s *Server) homeLinkConfirmRotation(reg consoleRegistry, l *registry.HomeLink) {
+ s.homeLink.ops.Lock()
+ defer s.homeLink.ops.Unlock()
+ if _, err := reg.ClearHomeLinkRotatePending(l.ID, l.RotateGen); err != nil {
+ log.Printf("console: home link %s: clear rotation %d: %v", l.ID, l.RotateGen, err)
+ }
+}
+
// homeLinkServingSentence is homeLinkServingFailed's sentence, for a status
// that reports it rather than failing.
func homeLinkServingSentence(console string, err error) string {
@@ -736,17 +757,15 @@ func (s *Server) handleAPIHomeLinkRotate(w http.ResponseWriter, r *http.Request)
homeLinkServingFailed(w, l.ServingURL, err)
return
}
- next := *l
- next.Token = tok
- if err := reg.PutHomeLink(next); err != nil {
- log.Printf("console: home link %s: the rotated key was not saved: %v", l.ID, err)
- jsonError(w, http.StatusInternalServerError, linkCopy(copyLD49, "console", l.ServingURL))
+ // The new key and the pending flag in one write, kept in the link's
+ // row so a restarted console still reports the rotation. When it
+ // fails, neither was saved: the serving console holds a key this one
+ // does not, so the answer is the link's recovery, never a success.
+ if err := reg.RotateHomeLinkKey(l.ID, tok, pending); err != nil {
+ log.Printf("console: home link %s: the rotated key (revocation pending=%v) was not saved, nor its flag: %v", l.ID, pending, err)
+ jsonError(w, http.StatusInternalServerError, linkCopy(copyHomeLinkRotateNotSaved, "console", l.ServingURL))
return
}
- // Kept in the link's row, so a restarted console still reports it.
- if err := reg.SetHomeLinkRotatePending(l.ID, pending); err != nil {
- log.Printf("console: home link %s: record the rotation pending=%v: %v", l.ID, pending, err)
- }
if pending {
log.Printf("console: home link %s: key rotated; %s has not stopped accepting the old key yet", l.ID, l.ServingURL)
writeJSON(w, http.StatusOK, map[string]any{"rotated": true, "revocation": "pending", "console": l.ServingURL})
diff --git a/internal/console/links_copy.go b/internal/console/links_copy.go
index 34dd0470f..c83b86070 100644
--- a/internal/console/links_copy.go
+++ b/internal/console/links_copy.go
@@ -227,6 +227,11 @@ const (
// The 500 from publish when the serving console published the app but
// the home could not record it, so home does not serve it yet.
copyHomeLinkPublishSaveFailed = "{app} was published on {console} but could not be recorded here, so it isn't served yet. run carlos link publish again"
+ // The 500 from rotate when the serving console replaced the key but
+ // the home could not save the new one (nor its pending flag: they are
+ // one write), so the home holds only the old key, which the serving
+ // console no longer accepts. The recovery is LD-C49's.
+ copyHomeLinkRotateNotSaved = "{console} replaced the link's key, but the new key could not be saved here, so this deployment's link stops working. forget it here with carlos link remove --local, then unlink it on the account's Fleet tab"
// The 409 from publish with no --account when more than one account
// has an app of that name.
copyHomeLinkAmbiguousApp = "more than one account here has an app called {app}. name its account with --account"
diff --git a/internal/console/view.go b/internal/console/view.go
index 607a39ced..498cd49d7 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -560,7 +560,8 @@ type consoleRegistry interface {
HomeLink() (*registry.HomeLink, error)
PutHomeLink(registry.HomeLink) error
SetHomeLinkUnlinkPending(id string, pending bool) error
- SetHomeLinkRotatePending(id string, pending bool) error
+ RotateHomeLinkKey(id, token string, pending bool) error
+ ClearHomeLinkRotatePending(id string, gen uint64) (bool, error)
DeleteHomeLink() error
HomeLinkApps() ([]registry.HomeLinkApp, error)
PutHomeLinkApp(registry.HomeLinkApp) error
diff --git a/internal/registry/homelink.go b/internal/registry/homelink.go
index 6be15206a..5a4b63d61 100644
--- a/internal/registry/homelink.go
+++ b/internal/registry/homelink.go
@@ -38,14 +38,18 @@ import (
// not hashed by Fingerprint. RotatePending records the same for a key
// rotation: the serving console answered the new key but its registry had
// not yet stopped accepting the old one (its "revocation":"pending"); set
-// and cleared by the home console, not hashed by Fingerprint. ConnGen
+// with the new key by RotateHomeLinkKey and cleared by
+// ClearHomeLinkRotatePending, not hashed by Fingerprint. RotateGen counts
+// the link's rotations (RotateHomeLinkKey bumps it with the key), so a
+// clear names the rotation it confirmed and a later one's flag survives
+// it; not hashed either (the token's own hash moves with it). ConnGen
// counts the changes that must replace the link's
// tunnel connection (DeleteHomeLinkApp, and PutHomeLinkApp retargeting a
// name); it is hashed, so each one reloads the agent.
type HomeLink struct {
ID, ServingURL, TunnelURL, Token, Account, AppsDomain string
BoxLabel, State string
- ConnGen uint64
+ ConnGen, RotateGen uint64
UnlinkPending, RotatePending bool
CreatedAt time.Time
}
@@ -127,9 +131,10 @@ CREATE TABLE IF NOT EXISTS home_link (
);`); err != nil {
return err
}
- // unlink_pending and rotate_pending: additive, beside the brief's
- // columns (SetHomeLinkUnlinkPending, SetHomeLinkRotatePending).
- for _, col := range []string{"unlink_pending", "rotate_pending"} {
+ // unlink_pending, rotate_pending and rotate_gen: additive, beside the
+ // brief's columns (SetHomeLinkUnlinkPending, RotateHomeLinkKey,
+ // ClearHomeLinkRotatePending).
+ for _, col := range []string{"unlink_pending", "rotate_pending", "rotate_gen"} {
if _, err := r.sql.Exec(`ALTER TABLE home_link ADD COLUMN ` + col + ` INTEGER NOT NULL DEFAULT 0`); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
}
@@ -146,16 +151,17 @@ CREATE TABLE IF NOT EXISTS home_link_apps (
}
const homeLinkCols = `id, COALESCE(serving_url, ''), COALESCE(tunnel_url, ''), COALESCE(token, ''),
- COALESCE(account, ''), COALESCE(apps_domain, ''), box_label, state, conn_gen, unlink_pending, rotate_pending, COALESCE(created_at, 0)`
+ COALESCE(account, ''), COALESCE(apps_domain, ''), box_label, state, conn_gen, unlink_pending, rotate_pending, rotate_gen, COALESCE(created_at, 0)`
func scanHomeLink(scan func(...any) error) (*HomeLink, error) {
var l HomeLink
- var gen, pending, rotating, created int64
+ var gen, pending, rotating, rotateGen, created int64
if err := scan(&l.ID, &l.ServingURL, &l.TunnelURL, &l.Token, &l.Account, &l.AppsDomain,
- &l.BoxLabel, &l.State, &gen, &pending, &rotating, &created); err != nil {
+ &l.BoxLabel, &l.State, &gen, &pending, &rotating, &rotateGen, &created); err != nil {
return nil, err
}
l.ConnGen = uint64(gen)
+ l.RotateGen = uint64(rotateGen)
l.UnlinkPending = pending != 0
l.RotatePending = rotating != 0
if created != 0 {
@@ -301,24 +307,69 @@ func (r *Registry) SetHomeLinkUnlinkPending(id string, pending bool) error {
return err
}
-// SetHomeLinkRotatePending records whether link id's last key rotation is
-// still pending on the serving console (it answered the new key with
-// "revocation":"pending": its registry may still accept the old one).
-// Another ID, or no link, changes nothing. Not hashed by Fingerprint.
-func (r *Registry) SetHomeLinkRotatePending(id string, pending bool) error {
- if !ValidLinkID(id) {
+// RotateHomeLinkKey stores link id's rotated key and whether the rotation
+// is still pending on the serving console (it answered the new key with
+// "revocation":"pending": its registry may still accept the old one), and
+// counts the rotation in rotate_gen: one UPDATE, so the new key is never
+// saved without its pending flag, nor the flag without the key. Nothing
+// else of the link changes. It refuses a malformed ID, an empty token and a
+// registry file other users can read (ErrCredentialFileReadable, as
+// PutHomeLink); another ID, or no link, is ErrHomeNotLinked. On any error
+// nothing was written.
+func (r *Registry) RotateHomeLinkKey(id, token string, pending bool) error {
+ switch {
+ case !ValidLinkID(id):
return fmt.Errorf("registry: invalid link id %q", id)
+ case token == "":
+ return fmt.Errorf("registry: link %s: no token", id)
}
if r.remote != nil {
- _, err := r.remote.call(nil, remoteRequest{Method: "SetHomeLinkRotatePending", LinkID: id, On: pending}, nil)
+ _, err := r.remote.call(nil, remoteRequest{Method: "RotateHomeLinkKey",
+ HomeLink: HomeLink{ID: id, Token: token, RotatePending: pending}}, nil)
+ return err
+ }
+ if err := CheckCredentialFile(r.path); err != nil {
return err
}
v := 0
if pending {
v = 1
}
- _, err := r.sql.Exec(`UPDATE home_link SET rotate_pending = ? WHERE id = ?`, v, id)
- return err
+ res, err := r.sql.Exec(`UPDATE home_link SET token = ?, rotate_pending = ?, rotate_gen = rotate_gen + 1
+WHERE id = ? AND rotate_gen < ?`, token, v, id, int64(math.MaxInt64))
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil {
+ return err
+ } else if n == 0 {
+ return ErrHomeNotLinked
+ }
+ return nil
+}
+
+// ClearHomeLinkRotatePending clears link id's pending rotation only while
+// gen is still its rotation (rotate_gen): the rotation the caller saw
+// confirmed. A later rotation's flag, another ID or no link changes
+// nothing; it reports whether the flag was cleared. Not hashed by
+// Fingerprint.
+func (r *Registry) ClearHomeLinkRotatePending(id string, gen uint64) (bool, error) {
+ if !ValidLinkID(id) {
+ return false, fmt.Errorf("registry: invalid link id %q", id)
+ }
+ if gen > math.MaxInt64 {
+ return false, nil
+ }
+ if r.remote != nil {
+ out, err := r.remote.call(nil, remoteRequest{Method: "ClearHomeLinkRotatePending", LinkID: id, Seq: gen}, nil)
+ return out.Changed, err
+ }
+ res, err := r.sql.Exec(`UPDATE home_link SET rotate_pending = 0 WHERE id = ? AND rotate_gen = ? AND rotate_pending <> 0`, id, int64(gen))
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n > 0, err
}
// HomeLinkApps returns the published set, ordered by name. Fresh
@@ -460,9 +511,9 @@ func bumpHomeLinkConnGen(tx txer) error {
// holds no link digests as it did before the tables existed. home_link
// hashes everything the agent's link loop acts on, conn_gen and the token's
// sha256 included (never the token itself); state, unlink_pending,
-// rotate_pending and created_at are not hashed: the agent writes state on
-// every connect and disconnect, and the two pending flags are the home
-// console's own bookkeeping.
+// rotate_pending, rotate_gen and created_at are not hashed: the agent
+// writes state on every connect and disconnect, and the two pending flags
+// and the rotation count are the home console's own bookkeeping.
func fingerprintHomeLink(db *sql.DB, h hash.Hash) error {
rows, err := db.Query(`SELECT ` + homeLinkCols + ` FROM home_link ORDER BY id`)
if err != nil {
diff --git a/internal/registry/homelink_test.go b/internal/registry/homelink_test.go
index c6169e14e..26b2fffcd 100644
--- a/internal/registry/homelink_test.go
+++ b/internal/registry/homelink_test.go
@@ -413,45 +413,103 @@ func TestHomeLinkUnlinkPending(t *testing.T) {
}
}
-// TestHomeLinkRotatePending: the rotation flag round-trips on its own link
-// only, survives the rotation's own PutHomeLink, and does not move the
-// fingerprint.
+// TestHomeLinkRotatePending: RotateHomeLinkKey saves the new key and its
+// pending flag in one write, on its own link only, counting the rotation;
+// ClearHomeLinkRotatePending clears only the rotation it names, so a later
+// rotation's flag survives a clear for an earlier one (Astra final
+// re-review, C). Neither moves the fingerprint beyond the token's own hash.
func TestHomeLinkRotatePending(t *testing.T) {
reg := openHomeRegistry(t)
mustPutHomeLink(t, reg, testHomeLink())
+ if err := reg.RotateHomeLinkKey(testLinkB, "other-token", true); !errors.Is(err, ErrHomeNotLinked) {
+ t.Fatalf("rotating another link's ID = %v; want ErrHomeNotLinked", err)
+ }
+ if l, _ := reg.HomeLink(); l.RotatePending || l.RotateGen != 0 || l.Token != "secret-token" {
+ t.Fatalf("another link's ID wrote %+v", l)
+ }
+ for _, bad := range []struct{ id, token string }{{"nope", "t"}, {testLinkA, ""}} {
+ if err := reg.RotateHomeLinkKey(bad.id, bad.token, true); err == nil {
+ t.Fatalf("RotateHomeLinkKey(%q, %q) was taken", bad.id, bad.token)
+ }
+ }
+
+ // Rotation 1, pending: the key and the flag together.
+ if err := reg.RotateHomeLinkKey(testLinkA, "rotated-1", true); err != nil {
+ t.Fatal(err)
+ }
+ one, _ := reg.HomeLink()
+ if one == nil || one.Token != "rotated-1" || !one.RotatePending || one.RotateGen != 1 || one.UnlinkPending {
+ t.Fatalf("after rotation 1 HomeLink = %+v; want the new key, pending, rotation 1", one)
+ }
before, err := reg.Fingerprint()
if err != nil {
t.Fatal(err)
}
- if err := reg.SetHomeLinkRotatePending(testLinkB, true); err != nil {
+ // Rotation 2 lands before rotation 1's confirmation clears.
+ if err := reg.RotateHomeLinkKey(testLinkA, "rotated-2", true); err != nil {
t.Fatal(err)
}
- if l, _ := reg.HomeLink(); l.RotatePending {
- t.Fatal("another link's ID set the flag")
+ if cleared, err := reg.ClearHomeLinkRotatePending(testLinkA, one.RotateGen); err != nil || cleared {
+ t.Fatalf("clearing rotation 1 after rotation 2 = %v, %v; want nothing cleared", cleared, err)
+ }
+ two, _ := reg.HomeLink()
+ if !two.RotatePending || two.RotateGen != 2 || two.Token != "rotated-2" {
+ t.Fatalf("rotation 1's clear dropped rotation 2's flag: %+v", two)
+ }
+ if cleared, _ := reg.ClearHomeLinkRotatePending(testLinkB, two.RotateGen); cleared {
+ t.Fatal("another link's ID cleared the flag")
+ }
+ mid, _ := reg.Fingerprint()
+ if cleared, err := reg.ClearHomeLinkRotatePending(testLinkA, two.RotateGen); err != nil || !cleared {
+ t.Fatalf("clearing rotation 2 = %v, %v", cleared, err)
}
- if err := reg.SetHomeLinkRotatePending(testLinkA, true); err != nil {
+ if l, _ := reg.HomeLink(); l.RotatePending || l.RotateGen != 2 {
+ t.Fatalf("after rotation 2's clear HomeLink = %+v", l)
+ }
+ if after, _ := reg.Fingerprint(); after != mid || mid == before {
+ t.Fatalf("fingerprint: rotation 2 %v, the clear %v; want the key's hash to move it and the flag not", mid != before, after != mid)
+ }
+ // A rotation that is not pending clears any flag in the same write.
+ if err := reg.RotateHomeLinkKey(testLinkA, "rotated-3", true); err != nil {
t.Fatal(err)
}
- if after, _ := reg.Fingerprint(); after != before {
- t.Fatal("the rotation flag moved the fingerprint")
+ if err := reg.RotateHomeLinkKey(testLinkA, "rotated-4", false); err != nil {
+ t.Fatal(err)
}
- rotated := testHomeLink()
- rotated.Token = "rotated-token"
- mustPutHomeLink(t, reg, rotated)
- if l, _ := reg.HomeLink(); l == nil || !l.RotatePending || l.UnlinkPending || l.Token != "rotated-token" {
- t.Fatalf("after the rotation's save HomeLink = %+v; want the flag kept", l)
+ if l, _ := reg.HomeLink(); l.RotatePending || l.RotateGen != 4 || l.Token != "rotated-4" {
+ t.Fatalf("after a rotation that applied HomeLink = %+v", l)
}
- if err := reg.SetHomeLinkRotatePending(testLinkA, false); err != nil {
+ // The link's own save (same ID) keeps the count and the flag.
+ if err := reg.RotateHomeLinkKey(testLinkA, "rotated-5", true); err != nil {
t.Fatal(err)
}
- if l, _ := reg.HomeLink(); l.RotatePending {
- t.Fatal("the flag was not cleared")
+ resaved := testHomeLink()
+ resaved.Token = "rotated-5"
+ mustPutHomeLink(t, reg, resaved)
+ if l, _ := reg.HomeLink(); !l.RotatePending || l.RotateGen != 5 {
+ t.Fatalf("after PutHomeLink of the same link HomeLink = %+v; want the flag and count kept", l)
}
- if err := reg.SetHomeLinkRotatePending("nope", true); err == nil {
+ if _, err := reg.ClearHomeLinkRotatePending("nope", 1); err == nil {
t.Fatal("a malformed ID was taken")
}
}
+// TestHomeLinkRotateKeyRefusedWritesNothing: a refused RotateHomeLinkKey
+// (the registry file readable by other users) saves neither the key nor the
+// flag: there is no state with the new key and no pending warning.
+func TestHomeLinkRotateKeyRefusedWritesNothing(t *testing.T) {
+ reg := openHomeRegistry(t)
+ mustPutHomeLink(t, reg, testHomeLink())
+ chmodRegistry(t, reg.path, 0o644)
+ if err := reg.RotateHomeLinkKey(testLinkA, "rotated-token", true); !errors.Is(err, ErrCredentialFileReadable) {
+ t.Fatalf("RotateHomeLinkKey into a 0644 registry = %v; want ErrCredentialFileReadable", err)
+ }
+ chmodRegistry(t, reg.path, 0o640)
+ if l, _ := reg.HomeLink(); l == nil || l.Token != "secret-token" || l.RotatePending || l.RotateGen != 0 {
+ t.Fatalf("after the refused rotation HomeLink = %+v; want the old key, nothing pending", l)
+ }
+}
+
func TestHomeLinkCallsOverRemote(t *testing.T) {
reg, path := remoteTestRegistry(t)
chmodRegistry(t, path, 0o644)
@@ -478,11 +536,23 @@ func TestHomeLinkCallsOverRemote(t *testing.T) {
if l, _ := reg.HomeLink(); !l.UnlinkPending {
t.Fatal("remote SetHomeLinkUnlinkPending did not record the flag")
}
- if err := reg.SetHomeLinkRotatePending(testLinkA, true); err != nil {
+ if err := reg.RotateHomeLinkKey(testLinkA, "rotated-token", true); err != nil {
t.Fatal(err)
}
- if l, _ := reg.HomeLink(); !l.RotatePending {
- t.Fatal("remote SetHomeLinkRotatePending did not record the flag")
+ if l, _ := reg.HomeLink(); !l.RotatePending || l.RotateGen != 1 || l.Token != "rotated-token" {
+ t.Fatalf("remote RotateHomeLinkKey wrote %+v", l)
+ }
+ if err := reg.RotateHomeLinkKey(testLinkB, "other-token", true); !errors.Is(err, ErrHomeNotLinked) {
+ t.Fatalf("remote RotateHomeLinkKey of another link = %v; want ErrHomeNotLinked", err)
+ }
+ if cleared, err := reg.ClearHomeLinkRotatePending(testLinkA, 0); err != nil || cleared {
+ t.Fatalf("remote clear of an earlier rotation = %v, %v", cleared, err)
+ }
+ if cleared, err := reg.ClearHomeLinkRotatePending(testLinkA, 1); err != nil || !cleared {
+ t.Fatalf("remote clear of rotation 1 = %v, %v", cleared, err)
+ }
+ if l, _ := reg.HomeLink(); l.RotatePending {
+ t.Fatal("remote ClearHomeLinkRotatePending did not clear the flag")
}
shop := HomeLinkApp{Name: "shop", HomeAccount: "acct1", HomeApp: "shop", HomeHost: "h"}
if err := reg.PutHomeLinkApp(shop); err != nil {
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 11506d4ee..08272e13e 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -301,8 +301,10 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
err = r.SetHomeLinkState(q.Status)
case "SetHomeLinkUnlinkPending":
err = r.SetHomeLinkUnlinkPending(q.LinkID, q.On)
- case "SetHomeLinkRotatePending":
- err = r.SetHomeLinkRotatePending(q.LinkID, q.On)
+ case "RotateHomeLinkKey":
+ err = r.RotateHomeLinkKey(q.HomeLink.ID, q.HomeLink.Token, q.HomeLink.RotatePending)
+ case "ClearHomeLinkRotatePending":
+ out.Changed, err = r.ClearHomeLinkRotatePending(q.LinkID, q.Seq)
case "HomeLinkApps":
out.HomeLinkApps, err = r.HomeLinkApps()
case "HomeLinkAppByName":
diff --git a/link_cli.go b/link_cli.go
index 99c493d93..44f6e5d38 100644
--- a/link_cli.go
+++ b/link_cli.go
@@ -92,9 +92,11 @@ const (
// still accept the old one until its own retry gets the change through
// (Astra final review, Important 3). In place of LD-C64.
copyLinkRotatePending = "replaced the link's key here. {console} still accepts the old key until it finishes the change, which it keeps trying by itself. run carlos link status to check"
- // status: the same, until a call to the serving console shows the
- // change applied.
- copyLinkStatusRotatePending = "key rotation: {console} still accepts the old key until it finishes the change, which it keeps trying by itself"
+ // status: a rotation is pending and the serving console could not be
+ // asked whether it has finished, so the change may well have applied:
+ // only unconfirmed (Astra final re-review, C). A status that reaches
+ // the serving console confirms the change and prints nothing extra.
+ copyLinkStatusRotateUnconfirmed = "key rotation: not confirmed yet. {console} could not be asked whether it has stopped accepting the old key"
// remove: 202 with no message of the console's own.
copyLinkRemovePending = "Carloku has not cut this deployment's connection yet. run carlos link remove again to finish here"
// publish and unpublish when the console sent no URL.
@@ -354,7 +356,7 @@ func linkStatus(ctx context.Context, sess *apiSession, out io.Writer) error {
fmt.Fprintln(out, fillLinkCopy(copyLinkStatusUnlinkPending, "console", l.Console))
}
if l.KeyRevocation == "pending" {
- fmt.Fprintln(out, fillLinkCopy(copyLinkStatusRotatePending, "console", l.Console))
+ fmt.Fprintln(out, fillLinkCopy(copyLinkStatusRotateUnconfirmed, "console", l.Console))
}
if l.Box == "" {
fmt.Fprintln(out, copyLD58)
diff --git a/link_cli_test.go b/link_cli_test.go
index 5ea335da3..c05a17779 100644
--- a/link_cli_test.go
+++ b/link_cli_test.go
@@ -338,12 +338,22 @@ func TestLinkStatusStates(t *testing.T) {
"could not reach " + testServing + ". try again\n" +
"connection: connected (box box-1)\n" +
"no apps published\n"},
- {"rotation pending", map[string]any{"linked": true, "console": testServing, "account": "shop",
+ // The serving console could not be asked while a rotation is
+ // pending: the change is only unconfirmed, never "still accepts the
+ // old key" (Astra final re-review, C).
+ {"rotation pending, serving console unreachable", map[string]any{"linked": true, "console": testServing, "account": "shop",
"box": "box-1", "state": "connected", "apps": []any{}, "key_revocation": "pending",
"serving_error": "Carloku couldn't update this link just now. Try again in a minute."},
"linked to shop on " + testServing + "\n" +
"Carloku couldn't update this link just now. Try again in a minute.\n" +
- strings.ReplaceAll(copyLinkStatusRotatePending, "{console}", testServing) + "\n" +
+ strings.ReplaceAll(copyLinkStatusRotateUnconfirmed, "{console}", testServing) + "\n" +
+ "connection: connected (box box-1)\n" +
+ "no apps published\n"},
+ // The serving console confirmed the new key (the home cleared the
+ // flag and sent no key_revocation): nothing extra.
+ {"rotation confirmed", map[string]any{"linked": true, "console": testServing, "account": "shop", "name": "pi",
+ "box": "box-1", "state": "connected", "apps": []any{}},
+ "linked to shop on " + testServing + " as pi\n" +
"connection: connected (box box-1)\n" +
"no apps published\n"},
{"unlink pending", map[string]any{"linked": true, "console": testServing, "account": "shop", "name": "pi",