oficina / equipo Public

runner: renew hosted bearer and proxy certificate at half life

Session.Run renews the proxy certificate (bootstrap /renew over the
current one) and the bearer (challenge, then renew) at half their
remaining lifetime, installs each atomically, and never renews past
the job deadline. A failed renewal cancels the work contexts, sends
the token_renewal_failed report once through a hook, and returns
ErrRenewal. Tests run on the proxy harness fake clock.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4d352761647c189e7306d44b9d2ef46f9d02c09d parent 63bccac
8 files changed, +803 −27
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +20 −0
  • internal/runner/hosted/bootstrap.go +1 −0
  • internal/runner/hosted/enrol.go +27 −15
  • internal/runner/hosted/export_test.go +8 −0
  • internal/runner/hosted/guards_test.go +6 −6
  • internal/runner/hosted/redeem.go +8 −6
  • internal/runner/hosted/renew.go +261 −0
  • internal/runner/hosted/renew_test.go +472 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index a9d6ed50..a00c4bfd 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1052,3 +1052,23 @@ Mutation checks, as before (exact unique string replaced, `go test -count=1`, re
- Red: the a116d330 subtest written first: `go test ./internal/hostedctl -run TestUpgradeFromVersion5 -count=1` FAIL `TestUpgradeFromVersion5/a116d330`: `upgrade_test.go:59: Open(...) = hostedctl: apply migration schema/0006_cert_evidence_stop.sql: SQL logic error: trigger cert_evidence_needs_stop already exists`.
- Green: `go test ./internal/hostedctl/... ./internal/hostedcert ./cmd/equipo-hosted-controller -count=1`: ok. `make budget build vet`: ok. `git diff --check`: clean.
- 131. The `DROP TRIGGER IF EXISTS` line removed (`sed -i '/^DROP TRIGGER IF EXISTS cert_evidence_needs_stop;$/d'`). `go test ./internal/hostedctl -run TestUpgradeFromVersion5`: FAIL `TestUpgradeFromVersion5/a116d330`, `upgrade_test.go:59: Open(...) = ... apply migration schema/0006_cert_evidence_stop.sql: SQL logic error: trig...`. Restored from a copy; `git diff` showed only the intended four added lines.
+
+## Task 14
+
+Token renewal and expiry in the runner (`internal/runner/hosted/renew.go`, `renew_test.go`). `(*Session).Run(ctx, clock)` renews the proxy certificate (`POST /renew` on a bootstrap listener over the current certificate, same proxy key, failover to the next listener on a transport error or 5xx) and the bearer (`POST /api/runner/v2/hosted/challenge`, then `/renew` with `wire.HostedRenewRequest` signed over `wire.HostedRenewMessage` with the machine key; the answer is a `runnerproto.HostedEnrolResponse`) at half each one's remaining lifetime, the certificate first. Each is checked (same launch, VM, epoch and key for the certificate; worker role, same runner and epoch for the bearer; neither past the deadline the session learnt at enrolment, whatever the answer names) and installed atomically; idle connections carrying the old certificate are closed. A credential expiring within a second of the deadline is not renewed (certificate times are whole seconds), and a renewal that does not extend a credential is its last (a certification session knows no deadline; the controller caps it); with nothing left to renew Run returns nil. On a failure it cancels every context from `Session.Work` (cause `ErrRenewal`, and later ones are born cancelled), calls the `OnRenewalFailed` hook once with `token_renewal_failed` (Task 17 wires it to the step report when the link is up), and returns `ErrRenewal`. `acceptCert` and `acceptCredential` take the time and the error kind; `postEnrol` became `postInstance` (optional bearer, optional body). The waits go through `renewAfter` (`time.After`), which tests replace with the harness's fake clock (`SetAfter`); the tests move the clock only while Run waits, so nothing sleeps on the wall clock.
+
+Red (stub `Run` that only waited for its context): `go test ./internal/runner/hosted -run 'TestRenew|TestStepPast|TestNoRenewal' -count=1` FAIL in every test: `renew_test.go:280: Run neither set a timer nor returned` (TestRenewAtHalfLife), `:325` (TestStepPastFifteenMinutesAndAnHour), `:371` (both TestRenewalFailureStopsWork subtests), `:412`, `:426` (TestNoRenewalPastDeadline).
+
+Green: the brief's command: ok (TestRenewAtHalfLife, TestStepPastFifteenMinutesAndAnHour, TestRenewalFailureStopsWork/{the proxy certificate, the bearer}, TestNoRenewalPastDeadline/{credentials at the deadline, a certification launch, a bearer past the deadline}). `go test ./internal/runner/hosted ./internal/hostedproxy/... -count=1 -race`: ok. `make budget build vet`: ok. `go test ./cmd/equipo-runner -run Hosted`: ok. gofmt and `git diff --check`: clean.
+
+Mutation checks (each an exact unique string in renew.go replaced by a script, `go test ./internal/runner/hosted -run <tests> -count=1 -timeout 120s`, restored from a copy and checked byte-equal with `cmp`); each compiled and failed on an assertion.
+
+132. Keep working after a failed renewal (the work contexts not cancelled: the `cancel(ErrRenewal)` loop replaced by `_ = works`). `-run TestRenewalFailureStopsWork`: FAIL `renew_test.go:399: the work context still runs after the failed renewal` in both subtests. Restored.
+133. Keep running after a failed bearer renewal (`return s.stopped(...)` replaced by `bearerDue = false; continue`). Same test: FAIL `renew_test.go:394: at 30m0s after the refusal Run has returned false with <nil>, want ErrRenewal`. Restored.
+134. Renew past the deadline (the deadline check in `renewAt` replaced by `if false`). `-run TestNoRenewalPastDeadline`: FAIL `renew_test.go:438: 2 certificate and 1 bearer renewals, want 1 and 0`. Restored. (A first run of this mutation, before the bearer got the "a renewal that does not extend is the last" rule and the test its 200-timer cap, never ended: the bearer was renewed ever closer to the deadline; go test's 10-minute timeout killed it. Both were added; it now fails as above.)
+135. Accept a renewed bearer past the session's deadline (`case r.Credential.ExpiresAt.After(s.deadline):` replaced by `case false:`; the fake answer names its own later deadline, so `acceptCredential` alone passes it). Same test: FAIL `renew_test.go:463: a bearer renewed past the deadline: Run returned false with <nil>, want ErrRenewal`. Restored.
+136. The renewed certificate not installed (`s.cert.Store(&c)` replaced by `_ = c`). `-run TestStepPast`: FAIL `renew_test.go:351: minute 8: the step's call = 0 "", ... CONNECT instance.example.test:443 answered 403`. Restored.
+137. The renewed bearer not installed (`s.bearer.Store(&r.Credential)` replaced by `_ = r`). `-run 'TestStepPast|TestRenewAtHalfLife'`: FAIL `renew_test.go:305: at 1h0m0s Run set no timer (returned true, ... the instance answered the challenge 401 ...)` and `renew_test.go:348: minute 60: Run returned ... 401`. Restored.
+138. Renew at the full lifetime, not half. `-run TestRenewAtHalfLife`: FAIL `renew_test.go:305: at 15m0s Run set no timer (returned true, ... answered 403 "cert_expired")`. Restored.
+139. A certificate renewal that does not extend it is not the last (`certDue = certDue && c.Leaf.NotAfter.After(old)` replaced by `_ = old`). `-run TestNoRenewalPastDeadline`: FAIL `a_certification_launch: renew_test.go:447: Run set 201 timers, the last for 0s at 19m59.999999999s: renewing without end`. Restored.
+140. The failure not reported (`if report != nil {` replaced by `if false {`). `-run TestRenewalFailureStopsWork`: FAIL `renew_test.go:411: reports [], want one "token_renewal_failed"` in both subtests. Restored.
diff --git a/internal/runner/hosted/bootstrap.go b/internal/runner/hosted/bootstrap.go
index 03cedb07..253790d6 100644
--- a/internal/runner/hosted/bootstrap.go
+++ b/internal/runner/hosted/bootstrap.go
@@ -90,6 +90,7 @@ type Session struct {
client *http.Client
boot *http.Client
+ stop stopper // the work to stop when a renewal fails (renew.go)
}
// HTTPClient is the session's client: every connection goes through the
diff --git a/internal/runner/hosted/enrol.go b/internal/runner/hosted/enrol.go
index a1fb9556..5dc85dcf 100644
--- a/internal/runner/hosted/enrol.go
+++ b/internal/runner/hosted/enrol.go
@@ -62,10 +62,10 @@ func enrol(ctx context.Context, c *http.Client, origin string, b hostedwire.Boot
giveUp := time.Now().Add(enrolPatience)
wait := time.Second
for {
- status, out, err := postEnrol(ctx, c, origin+enrolPath, body)
+ status, out, err := postInstance(ctx, c, origin+enrolPath, "", body)
switch {
case err == nil && status == http.StatusOK:
- return acceptCredential(out, epoch)
+ return acceptCredential(out, epoch, time.Now(), ErrEnrol)
case err == nil && status != http.StatusTooManyRequests && status < 500:
return none, fmt.Errorf("%w: the instance answered %d", ErrEnrol, status)
case err == nil:
@@ -84,14 +84,25 @@ func enrol(ctx context.Context, c *http.Client, origin string, b hostedwire.Boot
}
}
-func postEnrol(ctx context.Context, c *http.Client, url string, body []byte) (int, []byte, error) {
+// postInstance posts body (none when nil) to url with c, under bearer
+// when it is not "", and returns the status and the answer.
+func postInstance(ctx context.Context, c *http.Client, url, bearer string, body []byte) (int, []byte, error) {
ctx, cancel := context.WithTimeout(ctx, enrolTimeout)
defer cancel()
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
+ var rd io.Reader
+ if body != nil {
+ rd = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, rd)
if err != nil {
return 0, nil, err
}
- req.Header.Set("Content-Type", "application/json")
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ if bearer != "" {
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ }
resp, err := c.Do(req)
if err != nil {
return 0, nil, err
@@ -101,24 +112,25 @@ func postEnrol(ctx context.Context, c *http.Client, url string, body []byte) (in
return resp.StatusCode, out, err
}
-// acceptCredential checks the instance's answer: a worker bearer that
-// fits a header, a runner ID, an epoch equal to the proxy certificate's,
-// and an expiry in the future and not past the deadline.
-func acceptCredential(out []byte, epoch int64) (runnerproto.HostedEnrolResponse, error) {
+// acceptCredential checks the instance's answer, an enrolment's or a
+// renewal's: a worker bearer that fits a header, a runner ID, an epoch
+// equal to the proxy certificate's, and an expiry after now and not past
+// the deadline. A refusal wraps kind.
+func acceptCredential(out []byte, epoch int64, now time.Time, kind error) (runnerproto.HostedEnrolResponse, error) {
var r runnerproto.HostedEnrolResponse
if err := json.Unmarshal(out, &r); err != nil {
- return r, fmt.Errorf("%w: the answer does not decode", ErrEnrol)
+ return r, fmt.Errorf("%w: the answer does not decode", kind)
}
- cred, now := r.Credential, time.Now()
+ cred := r.Credential
switch {
case cred.Token == "" || !headerSafe(cred.Token) || cred.RunnerID == "":
- return r, fmt.Errorf("%w: the answer has no usable credential", ErrEnrol)
+ return r, fmt.Errorf("%w: the answer has no usable credential", kind)
case cred.Role != wire.RoleWorker:
- return r, fmt.Errorf("%w: the credential's role is %q, not a worker's", ErrEnrol, cred.Role)
+ return r, fmt.Errorf("%w: the credential's role is %q, not a worker's", kind, cred.Role)
case r.Epoch != epoch:
- return r, fmt.Errorf("%w: the credential is for epoch %d, the proxy certificate for %d", ErrEnrol, r.Epoch, epoch)
+ return r, fmt.Errorf("%w: the credential is for epoch %d, the proxy certificate for %d", kind, r.Epoch, epoch)
case !cred.ExpiresAt.After(now) || cred.ExpiresAt.After(r.Deadline):
- return r, fmt.Errorf("%w: the credential's expiry is not within the job's deadline", ErrEnrol)
+ return r, fmt.Errorf("%w: the credential's expiry is not within the job's deadline", kind)
}
return r, nil
}
diff --git a/internal/runner/hosted/export_test.go b/internal/runner/hosted/export_test.go
index 88fe1f0f..00c372c0 100644
--- a/internal/runner/hosted/export_test.go
+++ b/internal/runner/hosted/export_test.go
@@ -22,3 +22,11 @@ func SetDial(t testing.TB, dial func(ctx context.Context, network, addr string)
dialContext = dial
t.Cleanup(func() { dialContext = d })
}
+
+// SetAfter replaces the timer Run waits on (time.After) with after, for
+// one test: a fake clock's.
+func SetAfter(t testing.TB, after func(time.Duration) <-chan time.Time) {
+ a := renewAfter
+ renewAfter = after
+ t.Cleanup(func() { renewAfter = a })
+}
diff --git a/internal/runner/hosted/guards_test.go b/internal/runner/hosted/guards_test.go
index 31a0b21a..b39ce6c8 100644
--- a/internal/runner/hosted/guards_test.go
+++ b/internal/runner/hosted/guards_test.go
@@ -41,17 +41,17 @@ func TestEnrolAnswerGuards(t *testing.T) {
"expiring past the deadline": func(r *runnerproto.HostedEnrolResponse) { r.Deadline = r.Credential.ExpiresAt.Add(-time.Second) },
}
raw, _ := json.Marshal(good())
- if _, err := acceptCredential(raw, epoch); err != nil {
+ if _, err := acceptCredential(raw, epoch, time.Now(), ErrEnrol); err != nil {
t.Fatalf("a good answer was refused: %v", err)
}
- if _, err := acceptCredential([]byte("not json"), epoch); err == nil {
+ if _, err := acceptCredential([]byte("not json"), epoch, time.Now(), ErrEnrol); err == nil {
t.Error("an answer that does not decode was accepted")
}
for name, mutate := range cases {
r := good()
mutate(&r)
raw, _ := json.Marshal(r)
- if _, err := acceptCredential(raw, epoch); err == nil {
+ if _, err := acceptCredential(raw, epoch, time.Now(), ErrEnrol); err == nil {
t.Errorf("%s: accepted", name)
}
}
@@ -92,7 +92,7 @@ func TestProxyCertGuards(t *testing.T) {
raw, _ := json.Marshal(hostedwire.RedeemResponse{Cert: der, NotAfterNS: 1})
return raw
}
- if _, epoch, err := acceptCert(answer(good()), b, "vm-1", key); err != nil || epoch != 3 {
+ if _, epoch, err := acceptCert(answer(good()), b, "vm-1", key, time.Now(), ErrRedeem); err != nil || epoch != 3 {
t.Fatalf("a good certificate: epoch %d, %v", epoch, err)
}
cases := map[string]func(*cert){
@@ -109,12 +109,12 @@ func TestProxyCertGuards(t *testing.T) {
for name, mutate := range cases {
c := good()
mutate(&c)
- if _, _, err := acceptCert(answer(c), b, "vm-1", key); err == nil {
+ if _, _, err := acceptCert(answer(c), b, "vm-1", key, time.Now(), ErrRedeem); err == nil {
t.Errorf("%s: accepted", name)
}
}
for name, raw := range map[string][]byte{"not json": []byte("{"), "not a certificate": []byte(`{"cert":"AAAA","not_after_ns":1}`)} {
- if _, _, err := acceptCert(raw, b, "vm-1", key); err == nil {
+ if _, _, err := acceptCert(raw, b, "vm-1", key, time.Now(), ErrRedeem); err == nil {
t.Errorf("%s: accepted", name)
}
}
diff --git a/internal/runner/hosted/redeem.go b/internal/runner/hosted/redeem.go
index aea385a9..49c2028c 100644
--- a/internal/runner/hosted/redeem.go
+++ b/internal/runner/hosted/redeem.go
@@ -136,7 +136,7 @@ func redeem(ctx context.Context, c *http.Client, b hostedwire.BootstrapV2, vm is
last = fmt.Errorf("bootstrap listener %s: %w", boot, err)
continue // the next proxy
case status == http.StatusOK:
- return acceptCert(out, b, vm, key)
+ return acceptCert(out, b, vm, key, time.Now(), ErrRedeem)
}
var e hostedwire.ErrorResponse
_ = json.Unmarshal(out, &e)
@@ -162,11 +162,13 @@ func redeem(ctx context.Context, c *http.Client, b hostedwire.BootstrapV2, vm is
}
}
-// acceptCert checks the controller's answer: a client certificate, valid
-// now, for key, naming exactly b's launch and attempt and vm.
-func acceptCert(out []byte, b hostedwire.BootstrapV2, vm isolatedjob.Ref, key *ecdsa.PrivateKey) (tls.Certificate, int64, error) {
+// acceptCert checks the controller's answer, a redemption's or a
+// renewal's: a client certificate, valid at now, for key, naming exactly
+// b's launch and attempt and vm. A refusal wraps kind.
+func acceptCert(out []byte, b hostedwire.BootstrapV2, vm isolatedjob.Ref, key *ecdsa.PrivateKey, now time.Time,
+ kind error) (tls.Certificate, int64, error) {
bad := func(what string) (tls.Certificate, int64, error) {
- return tls.Certificate{}, 0, fmt.Errorf("%w: the certificate %s", ErrRedeem, what)
+ return tls.Certificate{}, 0, fmt.Errorf("%w: the certificate %s", kind, what)
}
var r hostedwire.RedeemResponse
if err := hostedwire.DecodeStrict(bytes.NewReader(out), &r); err != nil {
@@ -179,7 +181,7 @@ func acceptCert(out []byte, b hostedwire.BootstrapV2, vm isolatedjob.Ref, key *e
if pub, ok := leaf.PublicKey.(*ecdsa.PublicKey); !ok || !pub.Equal(&key.PublicKey) {
return bad("is not for this VM's proxy key")
}
- if now := time.Now(); now.After(leaf.NotAfter) || !slices.Contains(leaf.ExtKeyUsage, x509.ExtKeyUsageClientAuth) {
+ if now.After(leaf.NotAfter) || !slices.Contains(leaf.ExtKeyUsage, x509.ExtKeyUsageClientAuth) {
return bad("is expired or not a client certificate")
}
if len(leaf.URIs) != 1 {
diff --git a/internal/runner/hosted/renew.go b/internal/runner/hosted/renew.go
new file mode 100644
index 00000000..31af4b0f
--- /dev/null
+++ b/internal/runner/hosted/renew.go
@@ -0,0 +1,261 @@
+package hosted
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/tls"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Renewal (plan Task 14, spec "Renewal while running"): the proxy
+// certificate (15 minutes) and the bearer (an hour) are each renewed at
+// half their remaining lifetime, never past the job's deadline. A failed
+// renewal stops the job: no work runs on credentials about to lapse.
+
+// The instance's routes for a bearer's renewal (Task 22), under the
+// runner bearer.
+const (
+ challengePath = "/api/runner/v2/hosted/challenge"
+ renewPath = "/api/runner/v2/hosted/renew"
+)
+
+// ReasonRenewalFailed is the step report's reason when a renewal fails.
+const ReasonRenewalFailed = "token_renewal_failed"
+
+// ErrRenewal is a credential the session could not renew: the job's work
+// is stopped and hosted-run exits non-zero.
+var ErrRenewal = errors.New("hosted: credential renewal failed")
+
+// errRefused is a renewal's answer the session would not install.
+var errRefused = errors.New("refused")
+
+// renewAfter is the timer Run waits on; tests use a fake clock's.
+var renewAfter = time.After
+
+// deadlineSlack: a credential expiring within this of the job's deadline
+// is not renewed. Certificate times are whole seconds, so one capped at
+// the deadline may end a fraction of a second before it.
+const deadlineSlack = time.Second
+
+// maxNonce bounds a challenge's nonce.
+const maxNonce = 1024
+
+// stopper holds the work to stop when a renewal fails, and the report to
+// send then.
+type stopper struct {
+ mu sync.Mutex
+ failed bool
+ works []context.CancelCauseFunc
+ report func(reason string)
+}
+
+// Work is parent for the job's work: cancelled, with cause ErrRenewal,
+// when a renewal fails (born cancelled after one has). The returned
+// function releases it.
+func (s *Session) Work(parent context.Context) (context.Context, context.CancelFunc) {
+ ctx, cancel := context.WithCancelCause(parent)
+ s.stop.mu.Lock()
+ if s.stop.failed {
+ cancel(ErrRenewal)
+ } else {
+ s.stop.works = append(s.stop.works, cancel)
+ }
+ s.stop.mu.Unlock()
+ return ctx, func() { cancel(context.Canceled) }
+}
+
+// OnRenewalFailed sets the report a failed renewal sends, once, after the
+// work is cancelled and before Run returns: the worker sends the step's
+// report (ReasonRenewalFailed) when its link is up.
+func (s *Session) OnRenewalFailed(report func(reason string)) {
+ s.stop.mu.Lock()
+ defer s.stop.mu.Unlock()
+ s.stop.report = report
+}
+
+// fail stops the work and sends the report, the first time only, and
+// returns err as an ErrRenewal.
+func (s *Session) fail(err error) error {
+ s.stop.mu.Lock()
+ first := !s.stop.failed
+ s.stop.failed = true
+ works, report := s.stop.works, s.stop.report
+ s.stop.works = nil
+ s.stop.mu.Unlock()
+ if first {
+ for _, cancel := range works {
+ cancel(ErrRenewal)
+ }
+ if report != nil {
+ report(ReasonRenewalFailed)
+ }
+ }
+ return fmt.Errorf("%w: %w", ErrRenewal, err)
+}
+
+// Run keeps the session's credentials current until ctx ends, on clock
+// (time.Now outside tests). Each of the proxy certificate and the bearer
+// (a certification launch has none) is renewed at half its remaining
+// lifetime and installed at once, so the next connection and the next
+// dial use it; one that already expires at the job's deadline is left to
+// expire with the job. Run returns nil when ctx ends or nothing is left
+// to renew. On a failed renewal it cancels the work (Work), sends the
+// report (OnRenewalFailed) and returns ErrRenewal.
+func (s *Session) Run(ctx context.Context, clock func() time.Time) error {
+ now := clock()
+ certAt, certDue := s.renewAt(s.cert.Load().Leaf.NotAfter, now)
+ var bearerAt time.Time
+ bearerDue := false
+ if c := s.bearer.Load(); c != nil {
+ bearerAt, bearerDue = s.renewAt(c.ExpiresAt, now)
+ }
+ for certDue || bearerDue {
+ next := certAt
+ if !certDue || bearerDue && bearerAt.Before(certAt) {
+ next = bearerAt
+ }
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-renewAfter(next.Sub(clock())):
+ }
+ now = clock()
+ // The certificate first: the bearer's renewal goes through the
+ // proxy on it.
+ if certDue && !now.Before(certAt) {
+ old := s.cert.Load().Leaf.NotAfter
+ c, err := s.renewCert(ctx, now)
+ if err != nil {
+ return s.stopped(ctx, fmt.Errorf("proxy certificate: %w", err))
+ }
+ s.cert.Store(&c)
+ s.client.CloseIdleConnections() // they carry the old certificate
+ certAt, certDue = s.renewAt(c.Leaf.NotAfter, now)
+ // Its issuer's cap reached (the job's deadline, which a
+ // certification launch's session does not know): a renewal
+ // that does not extend a credential is its last.
+ certDue = certDue && c.Leaf.NotAfter.After(old)
+ }
+ if bearerDue && !now.Before(bearerAt) {
+ old := s.bearer.Load().ExpiresAt
+ r, err := s.renewBearer(ctx, now)
+ if err != nil {
+ return s.stopped(ctx, fmt.Errorf("bearer: %w", err))
+ }
+ s.bearer.Store(&r.Credential)
+ bearerAt, bearerDue = s.renewAt(r.Credential.ExpiresAt, now)
+ bearerDue = bearerDue && r.Credential.ExpiresAt.After(old)
+ }
+ }
+ return nil
+}
+
+// stopped is a renewal's failure: none when ctx has ended (the job is
+// over), otherwise fail.
+func (s *Session) stopped(ctx context.Context, err error) error {
+ if ctx.Err() != nil {
+ return nil
+ }
+ return s.fail(err)
+}
+
+// renewAt is when a credential expiring at expiry, seen at now, is
+// renewed: half its remaining lifetime on. One that expires at the job's
+// deadline is not renewed (false).
+func (s *Session) renewAt(expiry, now time.Time) (time.Time, bool) {
+ if !s.deadline.IsZero() && expiry.Add(deadlineSlack).After(s.deadline) {
+ return time.Time{}, false
+ }
+ return now.Add(expiry.Sub(now) / 2), true
+}
+
+// renewCert renews the proxy certificate at a bootstrap listener, over the
+// current certificate, for the same key: each listener in turn while one
+// is unreachable or cannot reach the controller (5xx). The answer must
+// name the same launch, VM and epoch, and end by the job's deadline.
+func (s *Session) renewCert(ctx context.Context, now time.Time) (tls.Certificate, error) {
+ defer s.boot.CloseIdleConnections() // the next renewal goes over the next certificate
+ csr, err := csrFor(s.proxyKey)
+ if err != nil {
+ return tls.Certificate{}, err
+ }
+ body, err := json.Marshal(hostedwire.RenewCertRequest{Serial: s.cert.Load().Leaf.SerialNumber.Text(16), CSR: csr})
+ if err != nil {
+ return tls.Certificate{}, err
+ }
+ last := errors.New("no bootstrap listener")
+ for _, boot := range s.launch.ProxyBoot {
+ status, out, err := postBoot(ctx, s.boot, boot, "/renew", body)
+ if err != nil {
+ last = fmt.Errorf("bootstrap listener %s: %w", boot, err)
+ continue
+ }
+ if status == http.StatusOK {
+ c, epoch, err := acceptCert(out, s.launch, s.vm, s.proxyKey, now, errRefused)
+ switch {
+ case err != nil:
+ return c, err
+ case epoch != s.epoch:
+ return tls.Certificate{}, fmt.Errorf("the certificate is for epoch %d, the session's is %d", epoch, s.epoch)
+ case !s.deadline.IsZero() && c.Leaf.NotAfter.After(s.deadline):
+ return tls.Certificate{}, errors.New("the certificate outlives the job's deadline")
+ }
+ return c, nil
+ }
+ var e hostedwire.ErrorResponse
+ _ = json.Unmarshal(out, &e)
+ last = fmt.Errorf("bootstrap listener %s answered %d %q", boot, status, e.Code)
+ if status < 500 {
+ return tls.Certificate{}, last
+ }
+ }
+ return tls.Certificate{}, last
+}
+
+// renewBearer asks the instance for a challenge under the current bearer,
+// signs it with the machine key, and trades it for the next bearer: a
+// worker credential for the same runner and epoch, expiring by the job's
+// deadline.
+func (s *Session) renewBearer(ctx context.Context, now time.Time) (runnerproto.HostedEnrolResponse, error) {
+ var none runnerproto.HostedEnrolResponse
+ cur := s.bearer.Load()
+ status, out, err := postInstance(ctx, s.client, s.origin+challengePath, cur.Token, nil)
+ if err != nil {
+ return none, fmt.Errorf("challenge: %w", err)
+ }
+ var ch wire.HostedChallenge
+ if status != http.StatusOK || json.Unmarshal(out, &ch) != nil || len(ch.Nonce) == 0 || len(ch.Nonce) > maxNonce {
+ return none, fmt.Errorf("the instance answered the challenge %d without a usable nonce", status)
+ }
+ sig := ed25519.Sign(s.machine, wire.HostedRenewMessage(cur.RunnerID, s.epoch, ch.Nonce))
+ body, err := json.Marshal(wire.HostedRenewRequest{RunnerID: cur.RunnerID, Epoch: s.epoch, Nonce: ch.Nonce, Signature: sig})
+ if err != nil {
+ return none, err
+ }
+ status, out, err = postInstance(ctx, s.client, s.origin+renewPath, cur.Token, body)
+ if err != nil {
+ return none, fmt.Errorf("renew: %w", err)
+ }
+ if status != http.StatusOK {
+ return none, fmt.Errorf("the instance answered the renewal %d", status)
+ }
+ r, err := acceptCredential(out, s.epoch, now, errRefused)
+ switch {
+ case err != nil:
+ return none, err
+ case r.Credential.RunnerID != cur.RunnerID:
+ return none, fmt.Errorf("the credential is for runner %q, not %q", r.Credential.RunnerID, cur.RunnerID)
+ case r.Credential.ExpiresAt.After(s.deadline):
+ return none, errors.New("the credential outlives the job's deadline")
+ }
+ return r, nil
+}
diff --git a/internal/runner/hosted/renew_test.go b/internal/runner/hosted/renew_test.go
new file mode 100644
index 00000000..3f91a2cc
--- /dev/null
+++ b/internal/runner/hosted/renew_test.go
@@ -0,0 +1,472 @@
+package hosted_test
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedproxy/proxytest"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/runner/hosted"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// bearerLife is the instance's bearer lifetime (Task 22): an hour, never
+// past the job's deadline.
+const bearerLife = time.Hour
+
+// fakeInstance is the instance's side of one hosted job (Task 22) on the
+// harness's fake clock: enrolment, the challenge, the renewal, and the
+// step's own calls (GET /api/runner/protocol), each of the last three
+// checking the bearer is one it issued and has not expired.
+type fakeInstance struct {
+ h *proxytest.Harness
+ deadline time.Time
+
+ mu sync.Mutex
+ machine ed25519.PublicKey
+ tokens map[string]time.Time // bearer -> its expiry
+ issued int
+ nonces map[string]bool // nonce -> used
+ renewals int
+ refuse bool // refuse every renewal
+ lavish bool // issue renewed bearers for an hour, naming that as the deadline
+ stale []string
+}
+
+func instanceOn(h *proxytest.Harness, deadline time.Time) *fakeInstance {
+ f := &fakeInstance{h: h, deadline: deadline, tokens: map[string]time.Time{}, nonces: map[string]bool{}}
+ reply := func(w http.ResponseWriter, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(v)
+ }
+ h.Handle("/api/hosted/enrol", func(w http.ResponseWriter, r *http.Request) {
+ var q wire.HostedEnrolRequest
+ if json.NewDecoder(r.Body).Decode(&q) != nil {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ f.mu.Lock()
+ f.machine = q.MachinePublicKey
+ out := f.issueLocked(false)
+ f.mu.Unlock()
+ reply(w, out)
+ })
+ h.Handle("/api/runner/v2/hosted/challenge", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if r.Method != http.MethodPost || !f.currentLocked(r, "challenge") {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ nonce := make([]byte, 32)
+ _, _ = rand.Read(nonce)
+ f.nonces[string(nonce)] = false
+ reply(w, wire.HostedChallenge{Nonce: nonce, ExpiresAt: h.Clock.Wall().Add(time.Minute)})
+ })
+ h.Handle("/api/runner/v2/hosted/renew", func(w http.ResponseWriter, r *http.Request) {
+ var q wire.HostedRenewRequest
+ if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&q) != nil {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if !f.currentLocked(r, "renew") {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ used, known := f.nonces[string(q.Nonce)]
+ if f.refuse || !known || used || q.RunnerID != "r-1" || q.Epoch != proxytest.Epoch ||
+ !ed25519.Verify(f.machine, wire.HostedRenewMessage(q.RunnerID, q.Epoch, q.Nonce), q.Signature) {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+ f.nonces[string(q.Nonce)] = true
+ f.renewals++
+ reply(w, f.issueLocked(f.lavish))
+ })
+ h.Handle("/api/runner/protocol", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ ok := f.currentLocked(r, "step")
+ f.mu.Unlock()
+ if !ok {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ _, _ = io.WriteString(w, "ok")
+ })
+ return f
+}
+
+// currentLocked: r's bearer is one f issued, unexpired on the fake clock.
+// Anything else is recorded.
+func (f *fakeInstance) currentLocked(r *http.Request, what string) bool {
+ now := f.h.Clock.Wall()
+ tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ end, ok := f.tokens[tok]
+ if !ok || !now.Before(end) {
+ f.stale = append(f.stale, fmt.Sprintf("%s at %v: bearer %q (issued %v, expiry %v)", what, now, tok, ok, end))
+ return false
+ }
+ return true
+}
+
+// issueLocked issues the next bearer: an hour, capped at the deadline;
+// lavish, uncapped, with the answer naming its expiry as the deadline.
+func (f *fakeInstance) issueLocked(lavish bool) runnerproto.HostedEnrolResponse {
+ f.issued++
+ tok := fmt.Sprintf("bearer-%d", f.issued)
+ end, deadline := f.h.Clock.Wall().Add(bearerLife), f.deadline
+ switch {
+ case lavish:
+ deadline = end
+ case deadline.Before(end):
+ end = deadline
+ }
+ f.tokens[tok] = end
+ return runnerproto.HostedEnrolResponse{Epoch: proxytest.Epoch, Deadline: deadline,
+ Credential: runnerproto.RunnerCredential{Version: 1, Token: tok, TokenType: "Bearer", RunnerID: "r-1",
+ CredentialID: fmt.Sprintf("c-%d", f.issued), Person: "person@example.com", ExpiresAt: end, Role: wire.RoleWorker}}
+}
+
+func (f *fakeInstance) counts() (renewals int, stale []string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.renewals, slices.Clone(f.stale)
+}
+
+func (f *fakeInstance) set(fn func(*fakeInstance)) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ fn(f)
+}
+
+// renewRig is a started session whose job ends life after enrolment,
+// with Run on the harness's fake clock. The test sees every timer Run
+// sets, so it moves the clock only while Run waits: nothing here sleeps
+// on the wall clock.
+type renewRig struct {
+ t *testing.T
+ h *proxytest.Harness
+ f *fakeInstance
+ s *hosted.Session
+ start time.Time // the fake wall clock at enrolment
+
+ waits chan time.Duration
+ done chan error
+ due time.Time // when Run's timer fires; zero when it set none
+ ended bool // Run returned err
+ err error
+ wakes int // timers Run has set
+}
+
+func newRenewRig(t *testing.T, life time.Duration) *renewRig {
+ t.Helper()
+ return newRenewRigFor(t, life, hostedwire.PurposeChecks)
+}
+
+// newRenewRigFor is newRenewRig for a launch of purpose: a certification
+// launch's session does not enrol, so it has no bearer and no deadline.
+func newRenewRigFor(t *testing.T, life time.Duration, purpose string) *renewRig {
+ t.Helper()
+ h := proxytest.New(t)
+ begin := h.Clock.Wall()
+ deadline := begin.Add(life)
+ h.Controller.SetLaunch(proxytest.Launch{LaunchID: proxytest.LaunchID, AttemptID: proxytest.AttemptID, VMRef: proxytest.VMRef,
+ Epoch: proxytest.Epoch, Code: proxytest.ProxyCode, Deadline: deadline, Services: bootstrap(h).Services})
+ f := instanceOn(h, deadline)
+ b := bootstrap(h)
+ if b.Purpose = purpose; purpose == hostedwire.PurposeCertification {
+ b.InstanceCode = ""
+ }
+ s, err := start(t, b, t.TempDir())
+ if err != nil {
+ t.Fatalf("Start: %v", err)
+ }
+ r := &renewRig{t: t, h: h, f: f, s: s, start: begin, waits: make(chan time.Duration, 64), done: make(chan error, 1)}
+ hosted.SetAfter(t, func(d time.Duration) <-chan time.Time {
+ ch := h.Clock.After(d)
+ r.waits <- d
+ return ch
+ })
+ return r
+}
+
+// run starts Run and waits for its first move.
+func (r *renewRig) run() {
+ r.t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ go func() { r.done <- r.s.Run(ctx, r.h.Clock.Wall) }()
+ r.t.Cleanup(func() {
+ cancel()
+ if !r.ended {
+ select {
+ case <-r.done:
+ case <-time.After(20 * time.Second):
+ r.t.Error("Run did not return when its context ended")
+ }
+ }
+ })
+ r.settle()
+}
+
+// settle waits for Run's next move: a timer (its due time noted) or its
+// return.
+func (r *renewRig) settle() {
+ r.t.Helper()
+ select {
+ case d := <-r.waits:
+ r.due = r.h.Clock.Wall().Add(d)
+ if r.wakes++; r.wakes > 200 {
+ r.t.Fatalf("Run set %d timers, the last for %v at %v: renewing without end", r.wakes, d, r.h.Clock.Wall().Sub(r.start))
+ }
+ case r.err = <-r.done:
+ r.ended, r.due = true, time.Time{}
+ case <-time.After(20 * time.Second):
+ r.t.Fatal("Run neither set a timer nor returned")
+ }
+}
+
+// advanceTo moves the fake clock to at, a minute at most at a time and
+// stopping at Run's timer, polling the proxy's feed at each stop (as its
+// own loop does every 30 seconds), and settling Run after each timer.
+func (r *renewRig) advanceTo(at time.Time) {
+ r.t.Helper()
+ for {
+ now := r.h.Clock.Wall()
+ if !r.ended && !r.due.IsZero() && !r.due.After(now) {
+ r.settle()
+ continue
+ }
+ if !now.Before(at) {
+ return
+ }
+ next := now.Add(time.Minute)
+ if at.Before(next) {
+ next = at
+ }
+ if !r.ended && !r.due.IsZero() && r.due.Before(next) {
+ next = r.due
+ }
+ r.h.Clock.Advance(next.Sub(now))
+ if err := r.h.Proxy.Poll(context.Background()); err != nil {
+ r.t.Fatalf("Poll: %v", err)
+ }
+ }
+}
+
+// renewed is how many proxy certificate and bearer renewals were made.
+func (r *renewRig) renewed() (certs, bearers int) {
+ bearers, _ = r.f.counts()
+ return len(r.h.Controller.Received("POST /v1/proxy/renew")), bearers
+}
+
+// stepCall is one of the step's calls to the instance: a new connection
+// through the proxy with the session's current certificate and bearer.
+func stepCall(s *hosted.Session) (int, string, error) {
+ c := s.HTTPClient()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ defer c.CloseIdleConnections()
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, protocolURL, nil)
+ req.Header.Set("Authorization", "Bearer "+s.Token())
+ resp, err := c.Do(req)
+ if err != nil {
+ return 0, "", err
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(body), nil
+}
+
+// The proxy certificate (15 minutes) and the bearer (an hour) are each
+// renewed at half their remaining lifetime, not a second before, and the
+// renewed one is installed: the bearer the session hands out changes.
+func TestRenewAtHalfLife(t *testing.T) {
+ r := newRenewRig(t, 3*time.Hour)
+ r.run()
+ var got []string
+ tokens := []string{r.s.Token()}
+ certs, bearers := r.renewed()
+ for !r.due.After(r.start.Add(time.Hour)) {
+ if r.ended || r.due.IsZero() {
+ t.Fatalf("at %v Run set no timer (returned %v, %v) with the deadline hours away", r.h.Clock.Wall().Sub(r.start), r.ended, r.err)
+ }
+ at := r.due
+ r.advanceTo(at.Add(-time.Second))
+ if c, b := r.renewed(); c != certs || b != bearers {
+ t.Fatalf("renewed before %v: %d certificates, %d bearers, want %d, %d", at.Sub(r.start), c, b, certs, bearers)
+ }
+ r.advanceTo(at)
+ c, b := r.renewed()
+ what := at.Sub(r.start).String()
+ if c > certs {
+ what += fmt.Sprintf(" cert*%d", c-certs)
+ }
+ if b > bearers {
+ what += fmt.Sprintf(" bearer*%d", b-bearers)
+ tokens = append(tokens, r.s.Token())
+ }
+ got = append(got, what)
+ certs, bearers = c, b
+ }
+ want := []string{"7m30s cert*1", "15m0s cert*1", "22m30s cert*1", "30m0s cert*1 bearer*1", "37m30s cert*1",
+ "45m0s cert*1", "52m30s cert*1", "1h0m0s cert*1 bearer*1"}
+ if !slices.Equal(got, want) {
+ t.Errorf("renewals %q, want %q", got, want)
+ }
+ if !slices.Equal(tokens, []string{"bearer-1", "bearer-2", "bearer-3"}) {
+ t.Errorf("the session's bearers %q, want each renewed one in turn", tokens)
+ }
+ if _, stale := r.f.counts(); len(stale) != 0 {
+ t.Errorf("stale bearers presented: %q", stale)
+ }
+}
+
+// A step that runs past 15 minutes (the first proxy certificate's life)
+// and an hour (the first bearer's) keeps calling the instance on renewed
+// credentials: the proxy, judging certificates on the fake clock, lets
+// every call through, and the instance never sees an expired bearer.
+func TestStepPastFifteenMinutesAndAnHour(t *testing.T) {
+ r := newRenewRig(t, 2*time.Hour)
+ r.run()
+ for m := 1; m <= 75; m++ {
+ r.advanceTo(r.start.Add(time.Duration(m) * time.Minute))
+ if r.ended {
+ t.Fatalf("minute %d: Run returned %v", m, r.err)
+ }
+ if status, body, err := stepCall(r.s); err != nil || status != http.StatusOK || body != "ok" {
+ t.Fatalf("minute %d: the step's call = %d %q, %v", m, status, body, err)
+ }
+ }
+ certs, bearers := r.renewed()
+ if certs != 10 || bearers != 2 {
+ t.Errorf("%d certificate and %d bearer renewals in 75 minutes, want 10 and 2", certs, bearers)
+ }
+ if _, stale := r.f.counts(); len(stale) != 0 {
+ t.Errorf("stale bearers presented: %q", stale)
+ }
+}
+
+// A renewal that fails stops the work: the work context is cancelled
+// with ErrRenewal as its cause (and one asked for later is born
+// cancelled), the failure is reported once, Run returns ErrRenewal, and
+// nothing more is renewed.
+func TestRenewalFailureStopsWork(t *testing.T) {
+ cases := []struct {
+ name string
+ at time.Duration
+ fault func(r *renewRig)
+ }{
+ {"the proxy certificate", 7*time.Minute + 30*time.Second, func(r *renewRig) {
+ r.h.Controller.SetEpoch(proxytest.LaunchID, proxytest.Epoch+1)
+ }},
+ {"the bearer", 30 * time.Minute, func(r *renewRig) { r.f.set(func(f *fakeInstance) { f.refuse = true }) }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ r := newRenewRig(t, 3*time.Hour)
+ work, release := r.s.Work(context.Background())
+ defer release()
+ var mu sync.Mutex
+ var reports []string
+ r.s.OnRenewalFailed(func(reason string) {
+ mu.Lock()
+ defer mu.Unlock()
+ reports = append(reports, reason)
+ })
+ r.run()
+ tc.fault(r)
+ r.advanceTo(r.start.Add(tc.at))
+ if !r.ended || !errors.Is(r.err, hosted.ErrRenewal) {
+ t.Fatalf("at %v after the refusal Run has returned %v with %v, want ErrRenewal", tc.at, r.ended, r.err)
+ }
+ select {
+ case <-work.Done():
+ default:
+ t.Fatal("the work context still runs after the failed renewal")
+ }
+ if cause := context.Cause(work); !errors.Is(cause, hosted.ErrRenewal) {
+ t.Errorf("the work context's cause = %v, want ErrRenewal", cause)
+ }
+ late, release2 := r.s.Work(context.Background())
+ defer release2()
+ if late.Err() == nil {
+ t.Error("a work context asked for after the failure runs")
+ }
+ mu.Lock()
+ if !slices.Equal(reports, []string{hosted.ReasonRenewalFailed}) {
+ t.Errorf("reports %q, want one %q", reports, hosted.ReasonRenewalFailed)
+ }
+ mu.Unlock()
+ certs, bearers := r.renewed()
+ r.advanceTo(r.start.Add(2 * time.Hour))
+ if c, b := r.renewed(); c != certs || b != bearers {
+ t.Errorf("renewals went on after the failure: %d, %d then %d, %d", certs, bearers, c, b)
+ }
+ })
+ }
+}
+
+// Nothing is renewed past the job's deadline. A bearer issued to the
+// deadline is never renewed; the certificate is renewed once, to the
+// deadline, and then left to expire with the job; with nothing left to
+// renew, Run returns. A renewed bearer that would outlive the job's
+// deadline, as the session learnt it at enrolment, is refused, whatever
+// deadline the renewal's answer names.
+func TestNoRenewalPastDeadline(t *testing.T) {
+ t.Run("credentials at the deadline", func(t *testing.T) {
+ r := newRenewRig(t, 20*time.Minute)
+ r.run()
+ r.advanceTo(r.start.Add(30 * time.Minute))
+ if !r.ended || r.err != nil {
+ t.Fatalf("Run with nothing left to renew: returned %v with %v, want nil", r.ended, r.err)
+ }
+ if certs, bearers := r.renewed(); certs != 1 || bearers != 0 {
+ t.Errorf("%d certificate and %d bearer renewals, want 1 and 0", certs, bearers)
+ }
+ })
+ // A certification launch's session knows no deadline: the controller
+ // caps the certificate at it, and a renewal that does not extend the
+ // certificate is the last.
+ t.Run("a certification launch", func(t *testing.T) {
+ r := newRenewRigFor(t, 20*time.Minute, hostedwire.PurposeCertification)
+ r.run()
+ r.advanceTo(r.start.Add(30 * time.Minute))
+ if !r.ended || r.err != nil {
+ t.Fatalf("Run with the certificate at its cap: returned %v with %v, want nil", r.ended, r.err)
+ }
+ if certs, bearers := r.renewed(); certs != 2 || bearers != 0 {
+ t.Errorf("%d certificate and %d bearer renewals, want 2 (the second reaching the cap) and 0", certs, bearers)
+ }
+ })
+ t.Run("a bearer past the deadline", func(t *testing.T) {
+ r := newRenewRig(t, 70*time.Minute)
+ r.f.set(func(f *fakeInstance) { f.lavish = true })
+ work, release := r.s.Work(context.Background())
+ defer release()
+ r.run()
+ r.advanceTo(r.start.Add(30 * time.Minute))
+ if !r.ended || !errors.Is(r.err, hosted.ErrRenewal) {
+ t.Fatalf("a bearer renewed past the deadline: Run returned %v with %v, want ErrRenewal", r.ended, r.err)
+ }
+ if work.Err() == nil {
+ t.Error("the work goes on")
+ }
+ if r.s.Token() != "bearer-1" {
+ t.Errorf("the session installed %q, which outlives the deadline", r.s.Token())
+ }
+ })
+}