Skip to content

fix(daemon): require the session lease id on every request to a leased session - #4911

Merged
thymikee merged 12 commits into
0.22from
fix/0.22-lease-id-ownership
Nov 22, 2026
Merged

thymikee merged 12 commits into
0.22from
fix/0.22-lease-id-ownership

Conversation

@thymikee

@thymikee thymikee commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Targets 0.22. A request on a leased session must send that lease's id. The daemon filled a missing lease id from the session, so any holder of a shared proxy token who knew a session name could read, drive and close another client's session. Now a missing id fails with UNAUTHORIZED, LEASE_SESSION_MISMATCH, field: leaseId. Labels are checked when present and never grant access. Nested daemon requests (find, batch, replay) carry the parent's lease scope without overriding their own. Active provider-session artifact lookup needs the lease id. Caller-chosen allocate ids need 128 bits. Health reports session-lease-id. ADR 0007 states the trust model.

Breaking for older clients and direct RPC/SDK callers that relied on inheritance. The current CLI already sends the saved lease id.

Follow-ups: #4908, #4909, #4910, #4912, #4913. #4171 was fixed by #4177.

Before / after

raw --tenant e2b --session-isolation tenant --session agentA (proxy token, no lease id)
snapshot | press @e7 | close
base: succeed on agentA's device   head: UNAUTHORIZED LEASE_SESSION_MISMATCH (field leaseId)

Value

base head
Same-token attacks admitted (proxy test: snapshot, press, close, artifacts) 4/4 0/4
Minimum caller-chosen lease id 64 bits 128 bits

Validation

At 6eef3a85f9: full unit-core and provider-integration pass; lint, typecheck, layering and wire-compat clean. New tests fail at base; the find, batch and replay tests guard the nested hand-down. check:affected --run passed at cecfae508b (exactCommit).

Live, iOS 26.2 simulator, checkout proxy, three state dirs: C's snapshot/press/close refused. B's open got DEVICE_IN_USE. A's connect, open, snapshot, press, close and disconnect passed.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.16 MB 6.16 MB +2.6 kB
Package (unpacked) 6.16 MB 6.16 MB +2.6 kB
Package (download) 1.88 MB 1.88 MB +809 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 18.8 ms 25.8 ms +7.0 ms
CLI --help 37.5 ms 50.5 ms +13.1 ms

@apex-sentinel-staging

This comment has been minimized.

@blacksmith-sh

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Code at b414200 has blocking problems. The new lease check is the right rule, but a second independent pass found nine routes that still reach a leased session without its lease ID, or refuse it wrongly. No conflicts. The cancelled Body rules job looks like a concurrency cancel from a later edit. The diff does not touch the check, and the body passes the gate when recomputed, so a re-run should pass. Not verified here: live behavior, since no tests were run and the iOS proxy run is author-reported.

A second independent pass found that a caller with the shared proxy token and the locator of a diagnostics record in another client's leased session gets the record without a lease ID (packages/daemon/src/server/request-diagnostics-http.ts:137). The proxy forwards this route and static-token mode supplies no attested tenant. The rule: the lease ID presented on the request must match the record's owner before the file opens, and the proxy must forward the existing lease header and keep the typed refusal fields on REST errors. Should ownership travel with the record if it can outlive its session?

A second independent pass found that another client with the same proxy token and tenant label can list the artifact ID of a pending screenshot from an active leased session and download it without the lease ID (packages/daemon/src/resources/artifact-tracking.ts:245). Finalization stores only the tenant, and HTTP and RPC inventory and download check only the tenant. The rule: leased output records its producing lease, and the common inventory and download boundary applies that credential through the existing artifact header. Deliberately retained post-lease artifacts keep their current lifetime rules.

A second independent pass found that, for an active provider-backed leased session, a caller who knows the provider session ID and declares the tenant can invoke artifacts with no lease (packages/daemon/src/sessions/handlers/lease.ts:556). The provider lookup matches the tenant label only, and the handler then supplies the stored lease ID itself. The rule: active provider-session artifact lookup requires the caller to present the recorded lease ID. Post-close lookup of released provider sessions keeps its retention policy.

A second independent pass found that an explicit open of an existing proxy-leased session with the owner labels and no lease ID fails with INVALID_ARGS before the credential check can return LEASE_SESSION_MISMATCH (packages/daemon/src/sessions/request-admission.ts:200). With the right ID and a missing optional label, the same preflight contradicts the label rule in the daemon contract doc. The rule: an existing session runs the session credential assertion first, and the full proxy metadata requirement applies only to fresh opens, rechecked under the session lock.

A second independent pass found that a request arriving after the lease deadline but before background expiry settles can tear the session down before its credential is checked (packages/daemon/src/server/request-execution-scope.ts:468). For example, a close with no lease ID consumes the expired entry, and the later check rereads the store after retirement, so no mismatch is returned. A no-ID request can also reach the resource probe first. The rule: the presented credential is checked under the session lock before any request-driven teardown or session-resource inspection, and the expiry owner cleans up independently.

A second independent pass found that a devices request with no lease ID resolves the address of an active leased iOS session and refreshes its runner-backed recording (packages/daemon/src/server/request-execution-scope.ts:732). Devices ignores the lease by design, yet the refresh probes the leased device and can invalidate its recording. The rule: lease-independent commands stay detached from the resolved session for recording health, session binding and inline expiry.

A second independent pass found that a no-ID doctor request is admitted while its address is empty, and if an owner opens the leased session there before dispatch finishes, doctor returns its session and device evidence (packages/daemon/src/sessions/handlers/session-doctor.ts:67). Doctor is exempt from the session execution lock. The rule: authorize the session at the actual read, or pin an authorized reference at admission, for every unlocked route that rereads session state.

A second independent pass found that a replay request with the correct credential in flags.leaseId passes intake, but native replay steps inherit only the listed parent flags, which omit leaseId, so the step fails LEASE_SESSION_MISMATCH where base admitted it (packages/daemon/src/server/request-router.ts:427). The rule: the replay-scoped invoker, including its fallback, uses the same parent lease handoff as ordinary nested calls.

A second independent pass found that in a direct batch, the wrapper puts the parent's lease ID in child meta, and the parser prefers it over a different flags.leaseId on a step, so a step with an explicit mismatch now runs (packages/daemon/src/core/lease-context.ts:126). Base refused it. The rule: fill missing child scope fields from the parent only after resolving the child's meta and flags together, keeping any lease ID or labels the child supplied.

A second independent pass found that on direct daemon RPC, a replay test attempt's address can already hold a leased session, and cleanup and optional video start and stop then call the close and record handlers directly, bypassing admission (packages/daemon/src/sessions/handlers/session-replay-command.ts:325). The rule: authorize the actual attempt session with the suite's presented credential before its reads and before any direct video or cleanup call, keeping cleanup bound to the lifetime the attempt owned.

Not blocking, and each can be taken or left: the connect proxy help line and remote-proxy.md:30 say connect saves the lease ID, but open saves it (cli-help.ts:634); client-api.md:352 could add one sentence that commands on a leased session need the lease's leaseId, else UNAUTHORIZED with reason LEASE_SESSION_MISMATCH; the refusal hint in lease-context.ts:168 could name the leaseId param instead of CLI flags; the session-lease-id capability at http-server.ts:87 has no reader and HTTP_DAEMON_CAPABILITIES could be derived from DAEMON_CAPABILITIES; the find-session-lease test at request-router-find-session-lease.test.ts:87 passes at base, so the Validation line could say it guards the nested hand-down; putHostLease at lease-registry.ts:112 still accepts 64-bit ids for a credential; and request events are recorded for a leased session before admission at request-execution-scope.ts:297, which fits a follow-up issue.

After these fixes, the Body rules job needs a re-run before merge.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks. Dispositions at 6eef3a8:

Fixed here. These are regressions or ordering faults in the rule this PR adds:

  • Replay hand-down (request-router.ts): invokeReplayAction, including its fallback, now goes through the same parent lease hand-down. Test: request-router-nested-session-lease.test.ts, "a replay that sends the lease id in its flags…" fails at b414200.
  • Batch step override (lease-context.ts): the hand-down fills only the fields that the child's meta and flags leave missing together. A step that names another lease id is refused again. Test: the same file, "a batch step that names another lease id…", fails at b414200.
  • Open preflight (request-admission.ts): the fresh-open proxy metadata rule now skips a session that already holds a lease, both in preflight and under the lock. A no-ID open gets LEASE_SESSION_MISMATCH, and a reopen with the id and a missing label is admitted. Test: http-server-proxy-session-lease.test.ts, "an open of an existing leased session…", fails at b414200.
  • Active provider-session lookup (handlers/lease.ts): while the provider session's lease is active, artifacts --provider-session needs that lease id. A released session keeps its retention lookup. Test: lease-artifacts.test.ts.
  • Nits: help and remote-proxy.md now say open saves the id, client-api.md names the refusal, and the hint names the leaseId param. The find test guards the nested hand-down (it fails without the router wiring), not a base regression.

Follow-ups. These are new ownership surfaces or paths that predate this PR; the PR stays at one invariant:

Validation at 6eef3a8: full unit-core (20,905) and provider-integration (316) pass, and lint, layering and wire-compat are clean. Each new test fails at b414200.

@thymikee

Copy link
Copy Markdown
Member Author

@apex-sentinel-staging review

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 5a24fb5. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Several findings from the earlier review (b414200, #4911 (comment)) are now fixed at fd97ec9, including the flags-only parent case for nested requests, but six defects remain.

The leaseBackend comparison now exists at lease-context.ts:185, and its thread no longer applies (#4911 (comment)). The 16 checks at fd97ec9 are green, and no conflicts were reported. No tests were run for this review. The regression checks for the replay, batch, open-preflight and leaseBackend tests come from reading the b414200 code paths. The routes moved to #4912 and #4913 were not re-checked, as agreed.

A second independent pass found that a supplied scope label is dropped when the session has no value for it. lease-context.ts:193: allocate an iOS lease with tenant and run only, then open a session with it. A snapshot with the correct leaseId plus a clientId, deviceKey or leaseProvider passes the assertion, because the stored label is undefined. The projection at lease-context.ts:111-113 removes the supplied value before registry admission. Base 3925b05 kept it, and lease-registry-scope.ts:271-273 refused it. The rule: a supplied label must mismatch whenever it differs from the session lease value, including when that value is absent.

A second independent pass found that leaseBackend sent in flags is ignored. lease-scope.ts:122 reads only meta.leaseBackend, while CommandFlags carries leaseBackend through CliFlags. A named snapshot on an active iOS simulator session with the correct meta.leaseId and flags.leaseBackend set to android-instance reaches the assertion at lease-context.ts:185 with no requested backend, and the command runs. The rule: resolve leaseBackend from flags when meta does not supply it, like the other flag-backed lease fields, and use that resolution in admission and nested handoff.

A second independent pass found that equivalent backend values are now refused. lease-context.ts:185: on an ios-simulator session, send the correct leaseId with meta.leaseBackend set to IOS-SIMULATOR through agent_device.command. The RPC only checks that meta is an object (http-rpc-methods.ts:55-63). Base 3925b05 passed the value to the registry, which trims and lowercases it (lease-registry-scope.ts:171-176). Head compares the raw strings and refuses. The rule: compare supplied and stored backends through the existing backend canonicalization, and keep LEASE_SESSION_MISMATCH for a different backend.

A second independent pass found that parent metadata masks a batch step's own lease credential. batch.ts:350: send a direct batch with the session's correct leaseId in meta and a snapshot step whose flags.leaseId names another lease. The step builder copies all parent meta onto the child, so the handoff at lease-context.ts:128 sees the parent id (lease-scope.ts:119 prefers meta), and the snapshot runs. The flags-only parent test at request-router-nested-session-lease.test.ts:134 passes, but the meta case is still open. The rule: do not inherit lease metadata for any field the step supplies, and let the shared handoff fill the rest from the parent.

A second independent pass found that a devices request touches a leased session without the credential. request-execution-scope.ts:733: an active iOS leased session has a runner-backed recording with touches enabled. A devices request names the session and sends no lease id. The devices descriptor ignores the session lease (registry.ts:299), yet scope preparation resolves the session and calls its recording refresh, which can set the runner ID or invalidate the recording (request-recording-health.ts:18-36). The rule: lease-independent devices requests must not bind the session used by recording refresh. This is tracked as #4913 item 2, so the maintainer may keep it in that issue.

A second independent pass found that the active provider-session lookup validates the id but not the other labels. lease.ts:600: with no agent-device session at the request address, request artifacts by the id of an active provider session, with the correct tenant, provider and leaseId but a different runId or leaseBackend. The index keys on provider and id and checks tenant (provider-session-ownership.ts:70-77), and the guard checks only leaseId, so the request reaches the cloud artifact provider at lease.ts:555. The rule: resolve the active lease's scope and validate the supplied id and labels with the same session mismatch assertion before provider dispatch.

Fixing the five findings that are not tracked in #4913 needs a re-run of the snapshot, batch and artifact routes above, each showing LEASE_SESSION_MISMATCH. After that, merge once the maintainer accepts the #4912/#4913 split.

@thymikee

Copy link
Copy Markdown
Member Author

Dispositions at 7b08a40. Each new test fails at fd97ec9 and shows LEASE_SESSION_MISMATCH with the named field:

  • Label the session lacks (lease-context.ts): a label the request sends now mismatches when the lease does not carry it. Test: request-admission.test.ts, "a request with the lease id and a clientId / deviceKey / leaseProvider the session lease does not match is refused" (snapshot route).
  • leaseBackend in flags (lease-scope.ts): leaseScopeFromRequest reads flags.leaseBackend when meta lacks it. Admission and the nested hand-down use that same resolution. Test: the same test.each, the leaseBackend case.
  • Backend canonicalization: a new readLeaseBackend in @agent-device/kernel/contracts, next to LEASE_BACKENDS, is shared by the registry's normalizeLeaseBackend and the session comparison (core cannot import resources). IOS-SIMULATOR matches; a different backend is still refused. Test: "a lease backend that differs only in case and space matches the session lease".
  • Batch meta masking the step credential: the daemon batch handler (session-batch.ts) drops an inherited meta lease field when the step's flags carry it, so the step's own lease id applies. The tenant stays in meta, because HTTP intake may have attested it. This lives in the daemon handler, not command-registry/src/batch.ts: importing lease-scope there grew the eager-closure budget of batch.ts and the replay action runtime. Test: request-router-nested-session-lease.test.ts, "…refused when the batch sends the right one in meta".
  • Provider-session labels (handlers/lease.ts): the active-lease guard reads the active lease (LeaseRegistry.inspectActiveLease, read-only) and runs the same session mismatch assertion on the id and every label before provider dispatch. Test: lease-artifacts.test.ts, the runId and leaseBackend cases.
  • devices recording refresh: stays in Check the session lease id before teardown, probes and unlocked session reads #4913 (item 2), as agreed.

Validation at 7b08a40: provider-integration (316), lint, typecheck, layering, fallow audit and the eager-closure budgets pass. Full unit-core had 4 failures in unrelated repo guards under host load average ~28. Three passed on rerun; the fourth, a macOS helper packaging test, timed out at 5 s. Hosted CI decides those.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The five findings from the earlier review (#4911 (comment)) are fixed at 7b08a40, and the checks show 16 passing with none failing. A second independent pass found six cases where a lease label is skipped or masked, so these need a fix before merge. No conflicts.

A second independent pass found that a snapshot on an active leased session with clientId set to an empty string is admitted at lease-context.ts:207. The parser keeps the string, the falsy guard treats it as omitted, and the projection fills in the stored owner scope. The base rejected it. Empty deviceKey and leaseProvider take the same path, and the backend comparison at lease-context.ts:200 also skips an empty backend. The rule: skip a comparison only when the label is undefined, and reject an explicitly empty label with LEASE_SESSION_MISMATCH.

A second independent pass found that a batch on tenant-a's leased session can run a snapshot step with flags.tenant set to tenant-b at session-batch.ts:42. The step inherits parent meta (batch.ts:350), and lease-scope.ts:117 prefers the inherited tenant, so the step tenant is never compared. The rule: compare an explicit step tenant with the inherited tenant before child dispatch, and return UNAUTHORIZED with LEASE_SESSION_MISMATCH for tenantId when they differ. The inherited tenant stays for routing.

A second independent pass found that the proxied install_from_source RPC drops lease labels at http-rpc-methods.ts:173. In the fixture at http-server-proxy-session-lease.test.ts:178, a different valid runId still reaches device runtime admission and returns UNSUPPORTED_OPERATION instead of LEASE_SESSION_MISMATCH. The converter projects leaseId alone and loses tenantId, clientId, deviceKey and leaseProvider. The rule: every lease label an RPC supplies reaches the session lease assertion, together with the HTTP tenant trust step.

A second independent pass found that an artifacts request for an active WebDriver provider session skips label checks on the lease-ID path at lease.ts:554. With no agent-device session, the active leaseId, the right provider, a wrong runId and no providerSessionId, the resolver returns before the active guard at lease.ts:574. Dispatch then reaches runtime-session.ts:203 and lists artifacts. The rule: the active lease scope assertion covers every presented leaseId before provider dispatch. The credential check for a provider-session ID stays.

A second independent pass found that the provider-session index masks a tenant mismatch at lease.ts:575. A request with the active leaseId, the right providerSessionId and a different tenant returns PROVIDER_SESSION_NOT_OWNED at line 584 instead of UNAUTHORIZED with LEASE_SESSION_MISMATCH for tenantId. The rule: when the request presents the active provider lease ID, its labels are checked before the tenant-filtered lookup. The filter stays for unknown and released sessions.

A second independent pass found a change from base at lease-context.ts:191. An active BrowserStack providerSessionId request with the exact leaseId and a tenantId with surrounding spaces resolves through the trimming index at provider-session-ownership.ts:72 and was dispatched on base 3925b05. It now fails the raw string comparison. The rule: the shared lease assertion compares tenants through the existing tenant normalization, and a tenant that does not normalize to the lease tenant still mismatches.

Nested lease inheritance now has two owners: handDownRequestLeaseScope fills missing fields from the parent, and withoutFlaggedLeaseMeta strips the meta the batch step builder copied. Could the step builder stop copying lease fields from parent meta, using a key list exported beside LeaseScope that command-registry/batch.ts can import without pulling lease-scope into its eager closure? Then handDownRequestLeaseScope would be the one place that completes a child scope, with the tenant attested once at intake. This is optional follow-up, since the current code holds the invariant on the batch route.

The earlier inline thread on leaseBackend (#4911 (comment)) no longer applies and can be resolved: the backend is now compared through assertMatchingLeaseBackend, with the request value taken from meta or flags.

Not verified here: test runs, since none were run, and whether each regression test fails at fd97ec9, which was judged by reading the code paths. The routes deferred to #4912, #4913, #4908, #4909, #4910 and #4923 were not re-checked. Label comparison uses raw string equality except for the backend, so a whitespace variant on the provider-session path could mismatch. No production client sends such values.

Once these six are fixed and the maintainer accepts the #4912 and #4913 split, the PR is ready to merge.

@thymikee

Copy link
Copy Markdown
Member Author

Dispositions at 6e51e09. Each new test fails at 7b08a40 and passes now:

  • Empty labels (lease-context.ts): a comparison is skipped only for an undefined label. An empty clientId, deviceKey, leaseProvider or backend is LEASE_SESSION_MISMATCH. Test: request-admission.test.ts, "an empty %s differs from the session lease".
  • Batch step tenant (session-batch.ts): a step's flags.tenant must name the inherited meta tenant (normalized). Otherwise the step fails with UNAUTHORIZED, LEASE_SESSION_MISMATCH, field tenantId. The inherited tenant stays for routing. Test: request-router-nested-session-lease.test.ts, "a batch step that names another tenant is refused".
  • install_from_source labels (http-rpc-methods.ts): the converter projects tenantId/tenant, runId, leaseId, leaseProvider/provider, deviceKey and clientId, and the tenant goes through the HTTP trust step. release_materialized_paths now also reads the tenant, so a release still pairs with the tenant that the install recorded. This keeps round 1's retention concern fixed. Ledger digests and acks are updated for both converters. Test: http-server-proxy-session-lease.test.ts, where a different runId now stops at LEASE_SESSION_MISMATCH.
  • Lease-id artifacts path (handlers/lease.ts): a presented active leaseId is checked with its labels before provider dispatch, with or without providerSessionId. Test: lease-artifacts.test.ts, "artifacts by an active lease id checks its labels before provider dispatch".
  • Label check before the tenant-filtered index: the same check runs before the provider-session lookup, so a wrong tenant with the active lease id gets LEASE_SESSION_MISMATCH for tenantId. The filter still answers unknown and released sessions. Test: "artifacts with an active lease id checks the tenant before the tenant-filtered lookup".
  • Tenant normalization: the shared assertion compares tenants through normalizeTenantId. A padded tenant matches, and one that does not normalize to the lease tenant still mismatches. Same test.

Optional single-owner batch inheritance: not taken here. The current code holds the rule on the batch route, and moving the key list beside LeaseScope changes the command-registry eager closure. It fits #4910 (one typed session-lease state).

The leaseBackend inline thread is resolved. Validation at 6e51e09: unit-core over packages, src, wire-compat and eager-closure budgets (19,910), provider-integration (316), lint, layering and fallow audit pass.

@apex-sentinel-staging

This comment has been minimized.

…d session

A request on a session that holds a lease must send that lease's id.
The daemon no longer fills a missing lease id or label from the session,
so a client that holds only the shared proxy token and a session name
cannot read, drive, or close another client's session. Requests the
daemon builds inside an admitted request carry the parent's lease scope,
and install_from_source reads a leaseId param.
Caller-chosen lease ids on allocate need 128 bits. Daemons report the
session-lease-id capability.
…session lease rule

- Replay steps get the parent's lease scope, like other nested requests.
- A nested request keeps a lease id or label that it names in its flags.
- An open on an existing leased session checks the lease id before the
  fresh-open proxy metadata rule.
- An active provider-session artifact lookup needs the lease id.
- Docs: open saves the lease id; client API names the refusal.
- A label the request sends differs from a lease that does not carry it.
- leaseBackend is read from flags when meta lacks it, and compared in
  canonical form (readLeaseBackend in kernel, shared with the registry).
- A batch step's lease fields in flags win over the inherited batch meta;
  the tenant stays in meta.
- An active provider-session artifact lookup checks the id and every
  label against the active lease.
- An omitted label is not compared; an empty label differs from the lease.
- Tenants are compared after the existing tenant normalization.
- A batch step tenant must name the inherited (possibly attested) tenant.
- install_from_source reads every lease label; release_materialized_paths
  reads the tenant that the paired install recorded.
- artifacts checks a presented active lease id and its labels before the
  tenant-filtered provider-session lookup and before provider dispatch.
@thymikee

Copy link
Copy Markdown
Member Author

The earlier findings from 7b08a40 are fixed at 6e51e09: the lease backend now goes through the shared checker, and an empty backend also mismatches, so the inline thread on backend comparison (#4911 (comment)) can be resolved. Five problems remain, and a second independent pass found each of them.

A second independent pass found that http-rpc-methods.ts:210 drops a supplied lease backend on install_from_source. A request with the right leaseId and leaseBackend set to android-emulator or "" on an iOS leased session is admitted, because the check at lease-context.ts:194 sees no backend. The lease contract doc promises a differing backend is refused. Project the backend into meta.leaseBackend with the other install lease labels, and keep an explicit empty value so the shared checker returns UNAUTHORIZED with field leaseBackend.

A second independent pass found that HTTP attestation masks a conflicting tenant label (http-server.ts:682). With an auth hook that attests tenant-a, a call carrying the right leaseId and an empty or different tenantId is admitted, because intake replaces the declared tenant at lines 682-690 and lease-context.ts:193 compares only the attested value. Keep the attested tenant as the routing identity, keep the caller-declared tenant as a separate lease label, and compare it with the lease whenever the request acts on a leased session.

A second independent pass found that session-batch.ts:42 now rejects steps on unleased sessions. A batch on an unleased local session with meta tenant-a and a step carrying flags.tenant tenant-b ran on base. At head it returns UNAUTHORIZED before dispatch, because the guard runs whenever meta carries a tenant. Apply the step tenant comparison only when the child acts on a leased session.

A second independent pass found that the same check (session-batch.ts:43) drops completed work. If step one completes and step two has a different tenant, the throw reaches the outer catch at batch.ts:142, which returns no failing step, completed count, partial results or dispatch status. The batching docs promise that evidence so a caller can resume without repeating steps. Return the mismatch as the child's error response so the step failure builder at batch.ts:150 keeps it.

A second independent pass found that lease-context.ts:180 refuses equivalent spellings of the lease id on the provider-session route. For an active WebDriver provider session, an uppercase or space-padded copy of the correct hex leaseId resolved on base. At head the registry still finds the lease through its normalizer (lease-registry.ts:324), but the raw comparison then refuses it. Compare using the existing lease id canonicalization, reject missing, malformed or different ids, and pass the validated canonical id to the provider.

Not blocking, and fine to take or leave: readLeaseLabelParams (http-rpc-methods.ts:209) repeats the label aliases that toLeaseDaemonRequest writes inline, so toLeaseDaemonRequest could spread it; install_from_source and release_materialized_paths now treat a tenant param as client-declared, so a release must send the same tenant as its install, which the release ledger rationale could state; and the step tenant check at session-batch.ts:42 fits #4910's single inheritance owner.

All 16 checks pass at 6e51e09. Not verified here: tests were not run in this review, so the pass at head relies on the reported results and the green checks, and the routes deferred to #4908, #4909, #4910, #4912, #4913 and #4923 were not re-checked.

The PR has merge conflicts with main. After the five fixes above, it needs to merge cleanly before it can land.

…ngs on leased sessions

- A tenant flag is compared with the session lease at admission, so a batch
  step that names another tenant fails as that step (partial results kept),
  and a step on an unleased session is not refused.
- install_from_source reads the leaseBackend (or backend) param.
- The lease id is compared in canonical form (case, surrounding space), and
  the active provider lease's canonical id goes to the provider.
@thymikee
thymikee force-pushed the fix/0.22-lease-id-ownership branch from 6e51e09 to f86ae74 Compare November 21, 2026 20:24
@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto the rewritten 0.22 and answered the review at 6e51e09. New head f86ae74d30.

Rebase. Only this PR's commits were replayed (git rebase --onto origin/0.22 3925b05d7f). 0.22 now publishes reasons from typed tables (ReasonTable<'leases'>), so LEASE_SESSION_MISMATCH moves into LEASE_ADMISSION_REASONS in lease-context.ts, next to its only thrower. LEASE_ID_TOO_SHORT gets a typed entry, and error-reasons.md is regenerated (43f6eaf).

Fixed. Each new test fails at the rebased previous head:

  • install_from_source backend (http-rpc-methods.ts): the converter reads leaseBackend (or backend) and keeps an explicit empty value, so the shared checker refuses a different or empty backend with field leaseBackend. Test: http-server-proxy-session-lease.test.ts.
  • Batch step tenant, leased sessions only, with partial results: the check left session-batch.ts and moved into the admission assertion. A tenant flag that differs from the session lease's tenant is refused there, so it fires only for a leased session, and the failure comes back as that step's response. A step on an unleased session runs as on base. Tests: request-router-nested-session-lease.test.ts, "…refused on a leased session and keeps earlier results" (asserts step: 2 and partialResults) and "…does not refuse a step on an unleased session".
  • Lease id spelling (lease-context.ts): the id is compared in canonical form (16–128 hex digits, case and surrounding space ignored). A missing, malformed or different id is refused, and the active provider lease's canonical id goes to the provider. Test: lease-artifacts.test.ts sends a padded uppercase id and asserts that the provider got the lowercase one.

Not taken: a separate declared tenant label under HTTP attestation. An auth hook attests the tenant from the client's credential, which is a stronger identity than any label the client declares. Admission compares that attested tenant with the lease, so a request with the right lease id and a wrong attested tenant is refused. A declared tenant that the hook overrides cannot widen access, and comparing it would refuse callers whose hook maps their declared label to another tenant name. A tenant the client sends in flags is now compared on leased sessions (see the batch item), which covers the step case. If you want the meta-declared tenant kept as a label too, that belongs with the typed session-lease state in #4910.

Not blocking: the release ledger rationale now says a release sends the same tenant as its install. readLeaseLabelParams is not shared with toLeaseDaemonRequest, because that converter reads backend under a different name and its digest would move for no behavior change.

Validation at f86ae74. Format, lint, typecheck, layering, fallow and build pass, and the daemon unit suite passes (4,260 tests). The affected gate's related-tests stage had one provider-integration timeout (remote-proxy-artifact-tenant.test.ts, 5 s) at host load average ~28. It passes 4/4 when run alone, so hosted CI decides.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 11e6472. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

At 11e6472, four of the five findings from the earlier review are fixed in the existing admission owner, and the attested-tenant one is answered. A second independent pass found four remaining gaps where one supplied lease label can hide another, listed below. All 16 checks are green at this commit, and there are no conflicts. These four gaps need a fix before merge.

A second independent pass found that HTTP tenant attestation overwrites conflicting lease labels. An auth hook attests tenant-a. A command or batch targeting a tenant-a leased session sends the correct lease id but declares tenant-b in meta.tenantId or flags.tenant. install_from_source does the same with its tenantId param. Intake replaces both carriers with tenant-a before lease-context.ts checks them, and the active provider-session lookup at lease.ts sees only the replacement. ADR 0007 requires checking the label the caller supplied. Please keep the original tenant carriers in daemon-only request state before stamping identity, keep the attested tenant for routing, and compare each supplied tenant with the target lease in the shared session check and the active provider-session check.

A second independent pass found that metadata shadows other supplied lease labels. On a leased session, a request can send the correct leaseId and runId in meta and a different runId in flags. The HTTP schema accepts both objects. Scope construction keeps only the meta value, so lease-context.ts admits the request. Conflicting leaseId, leaseBackend, leaseProvider, clientId and deviceKey flags are hidden the same way, and the active provider-session artifacts check reads the same collapsed scope. Please keep meta precedence for execution scope. At leased-session and active provider-session admission, also compare every explicitly supplied value the projection hides, and return LEASE_SESSION_MISMATCH on any conflict.

A second independent pass found that install RPC aliases can hide a mismatched backend or other label. A caller installing on an iOS leased session sends the correct lease id, a matching leaseBackend, and a different backend alias. The converter projects only leaseBackend, so admission never sees the conflict. The tenantId/tenant and leaseProvider/provider pairs at lines 207 and 215 behave the same way. Please preserve both supplied values for admission, or reject contradictory aliases with the shared UNAUTHORIZED lease-field mismatch once the leased target is known.

A second independent pass found that batch steps can replace the active request scope on an unleased session. Take an existing unleased iOS session and a batch with a valid active lease id, tenant and run in its outer meta. A snapshot step carries a different, inactive lease id in flags. The base keeps the outer lease id ahead of the step flag and runs the snapshot. At head, the outer request is admitted without attaching the lease to that session (lease-lifecycle.ts), but the batch helper deletes the inherited id before the child is admitted. The child then tries the inactive id and fails UNAUTHORIZED at lease-registry.ts. Please keep the inherited meta as the step's effective request scope, and compare the step's supplied lease fields separately where the child checks a leased target, so unleased steps keep base precedence.

Not blocking, and fine to take or leave: canonicalLeaseId in lease-context.ts:197 copies normalizeLeaseId from lease-registry-scope.ts because core cannot import resources, so moving normalizeLeaseId down into core or contracts/lease-scope and deleting the copy would honor the earlier ask for the existing canonicalization; the toInstallFromSourceDaemonRequest rationale in test/wire-compat/ledger.json omits leaseBackend (or backend) from its param list; and readTenantFlag at lease-context.ts:177 casts flags to read a field that is already typed, so resolveLeaseScope({ flags: req.flags }).tenantId would do.

Not verified here: tests were not run in this review. The step 2 and partialResults response shape and the canonical-id provider call come from the added tests and a code read. The empty-string leaseBackend refusal on install_from_source was checked by reading only, and the added test covers just a different backend. The routes deferred to #4908, #4909, #4910, #4912, #4913 and #4923 were not re-checked.

Neither open inline thread still needs action. This thread on step-owned meta can be resolved: command-registry/src/batch.ts:215 refuses step keys outside command, positionals, input, flags and runtime, and line 350 sets each step's meta from the outer request, so no step-owned lease meta exists to lose. This thread on the backend label can be resolved: assertMatchingLeaseBackend at lease-context.ts:233-238 handles it, an empty backend also mismatches, and it is unchanged at head.

…elds on leased sessions

A batch step keeps the inherited batch meta as its scope again, so a step
on an unleased session runs as on base. On a leased session, admission
compares every lease field the request sends in flags with the lease, so a
step that names another lease id or tenant is still refused.
@thymikee

Copy link
Copy Markdown
Member Author

Round 5 at 11e6472. The maintainer scoped this PR to stop at its invariant: a request on a leased session must send the lease id, and labels never grant access. This round therefore fixes only the regression. The rest moves to #4935.

Fixed (regression) at fdafb13: batch step scope on an unleased session. A batch step keeps the inherited batch meta as its scope again, and the meta-stripping helper in session-batch.ts is gone. A step on an unleased session with a stale lease id in its flags runs as it did on base. On a leased session, admission compares every lease field the request sends in flags with the lease (assertSuppliedLeaseLabels in assertRequestHoldsSessionLease). A step that names another lease id or tenant is still refused, so item 2 is covered on the leased-session path. New test: request-router-nested-session-lease.test.ts, "on an unleased session a batch step keeps the batch lease over a lease id in its flags", fails at 11e6472. The other batch tests (another lease id in flags or meta, another tenant with partial results kept) still pass.

Moved to #4935:

  • tenant carriers under HTTP attestation
  • hidden flag labels on the active provider-session path
  • contradicting RPC aliases
  • the normalizeLeaseId move and the ledger rationale nit

Both open inline threads are resolved, as the review notes.

Validation at fdafb13: daemon unit (4,261) and provider-integration (318) pass; lint, typecheck, layering and fallow audit are clean.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of fdafb13

Since the review of 11e6472: 0 new · 0 still open · 1 no longer raised

No open findings.

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (d6767e0910fc).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at fdafb13. The earlier findings from #4911 (comment) are fixed: batch steps on unleased sessions again get the base scope, and on leased sessions the lease label comparison now also covers flag-carried labels. All 16 checks pass at this commit, and there are no conflicts. Not blocking, take or leave: https://github.com/callstack/agent-device/blob/fdafb13/packages/daemon/src/core/lease-context.ts#L186 checks the lease id twice (assertRequestSendsLeaseId, then assertSuppliedLeaseLabels), so assertRequestSendsLeaseId could check only that the id is present; and https://github.com/callstack/agent-device/blob/fdafb13/packages/daemon/src/core/lease-context.ts#L173 reads flags.provider as a lease label when flags.leaseProvider is absent, so a hand-built RPC on a proxy-leased session that sends the cloud provider name in flags.provider (for example for artifacts) is refused with field leaseProvider, which the CLI, Node client and MCP paths avoid because they always send flags.leaseProvider, and that alias could go into a follow-up issue. Of the open inline threads, the one on batch step meta (#4911 (comment)) no longer applies because steps cannot own meta and session-batch.ts matches the base again, and the one on the backend label check (#4911 (comment)) is fixed at this head, so both can be resolved. Not verified here: tests were not run, the author's counts (daemon unit 4,261, provider-integration 318) were not reproduced, and the claim that the new test fails at 11e6472 rests on a code read; raw JSON-RPC callers that send different lease values in flags and meta were checked by code read only.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 21, 2026
@thymikee
thymikee merged commit e431c4a into 0.22 Nov 22, 2026
16 checks passed
@thymikee
thymikee deleted the fix/0.22-lease-id-ownership branch November 22, 2026 07:02
thymikee added a commit that referenced this pull request Nov 23, 2026
…d session (#4911)

* fix(daemon): require the session lease id on every request to a leased session

A request on a session that holds a lease must send that lease's id.
The daemon no longer fills a missing lease id or label from the session,
so a client that holds only the shared proxy token and a session name
cannot read, drive, or close another client's session. Requests the
daemon builds inside an admitted request carry the parent's lease scope,
and install_from_source reads a leaseId param.
Caller-chosen lease ids on allocate need 128 bits. Daemons report the
session-lease-id capability.

* docs(proxy): keep the session sentence next to its subject

* refactor(daemon): name the session lease assertion and type the HTTP capability list

* fix(daemon): close the nested, open and provider-session gaps in the session lease rule

- Replay steps get the parent's lease scope, like other nested requests.
- A nested request keeps a lease id or label that it names in its flags.
- An open on an existing leased session checks the lease id before the
  fresh-open proxy metadata rule.
- An active provider-session artifact lookup needs the lease id.
- Docs: open saves the lease id; client API names the refusal.

* refactor(daemon): split the unleased-request decision out of lease admission

* fix(daemon): check the lease backend label against the session lease

* fix(daemon): treat every sent lease label as checked against the lease

- A label the request sends differs from a lease that does not carry it.
- leaseBackend is read from flags when meta lacks it, and compared in
  canonical form (readLeaseBackend in kernel, shared with the registry).
- A batch step's lease fields in flags win over the inherited batch meta;
  the tenant stays in meta.
- An active provider-session artifact lookup checks the id and every
  label against the active lease.

* fix(daemon): compare empty, batch and RPC lease labels against the lease

- An omitted label is not compared; an empty label differs from the lease.
- Tenants are compared after the existing tenant normalization.
- A batch step tenant must name the inherited (possibly attested) tenant.
- install_from_source reads every lease label; release_materialized_paths
  reads the tenant that the paired install recorded.
- artifacts checks a presented active lease id and its labels before the
  tenant-filtered provider-session lookup and before provider dispatch.

* refactor(daemon): publish the session lease reasons from typed reason tables

* fix(daemon): check flag tenants, install backends and lease id spellings on leased sessions

- A tenant flag is compared with the session lease at admission, so a batch
  step that names another tenant fails as that step (partial results kept),
  and a step on an unleased session is not refused.
- install_from_source reads the leaseBackend (or backend) param.
- The lease id is compared in canonical form (case, surrounding space), and
  the active provider lease's canonical id goes to the provider.

* docs(wire-compat): say a release sends the tenant its install sent

* fix(daemon): keep the batch scope for steps and compare flag lease fields on leased sessions

A batch step keeps the inherited batch meta as its scope again, so a step
on an unleased session runs as on base. On a leased session, admission
compares every lease field the request sends in flags with the lease, so a
step that names another lease id or tenant is still refused.
hannojg pushed a commit to hannojg/agent-device that referenced this pull request Nov 23, 2026
…d session (callstack#4911)

* fix(daemon): require the session lease id on every request to a leased session

A request on a session that holds a lease must send that lease's id.
The daemon no longer fills a missing lease id or label from the session,
so a client that holds only the shared proxy token and a session name
cannot read, drive, or close another client's session. Requests the
daemon builds inside an admitted request carry the parent's lease scope,
and install_from_source reads a leaseId param.
Caller-chosen lease ids on allocate need 128 bits. Daemons report the
session-lease-id capability.

* docs(proxy): keep the session sentence next to its subject

* refactor(daemon): name the session lease assertion and type the HTTP capability list

* fix(daemon): close the nested, open and provider-session gaps in the session lease rule

- Replay steps get the parent's lease scope, like other nested requests.
- A nested request keeps a lease id or label that it names in its flags.
- An open on an existing leased session checks the lease id before the
  fresh-open proxy metadata rule.
- An active provider-session artifact lookup needs the lease id.
- Docs: open saves the lease id; client API names the refusal.

* refactor(daemon): split the unleased-request decision out of lease admission

* fix(daemon): check the lease backend label against the session lease

* fix(daemon): treat every sent lease label as checked against the lease

- A label the request sends differs from a lease that does not carry it.
- leaseBackend is read from flags when meta lacks it, and compared in
  canonical form (readLeaseBackend in kernel, shared with the registry).
- A batch step's lease fields in flags win over the inherited batch meta;
  the tenant stays in meta.
- An active provider-session artifact lookup checks the id and every
  label against the active lease.

* fix(daemon): compare empty, batch and RPC lease labels against the lease

- An omitted label is not compared; an empty label differs from the lease.
- Tenants are compared after the existing tenant normalization.
- A batch step tenant must name the inherited (possibly attested) tenant.
- install_from_source reads every lease label; release_materialized_paths
  reads the tenant that the paired install recorded.
- artifacts checks a presented active lease id and its labels before the
  tenant-filtered provider-session lookup and before provider dispatch.

* refactor(daemon): publish the session lease reasons from typed reason tables

* fix(daemon): check flag tenants, install backends and lease id spellings on leased sessions

- A tenant flag is compared with the session lease at admission, so a batch
  step that names another tenant fails as that step (partial results kept),
  and a step on an unleased session is not refused.
- install_from_source reads the leaseBackend (or backend) param.
- The lease id is compared in canonical form (case, surrounding space), and
  the active provider lease's canonical id goes to the provider.

* docs(wire-compat): say a release sends the tenant its install sent

* fix(daemon): keep the batch scope for steps and compare flag lease fields on leased sessions

A batch step keeps the inherited batch meta as its scope again, so a step
on an unleased session runs as on base. On a leased session, admission
compares every lease field the request sends in flags with the lease, so a
step that names another lease id or tenant is still refused.
thymikee added a commit that referenced this pull request Nov 24, 2026
…d session (#4911)

* fix(daemon): require the session lease id on every request to a leased session

A request on a session that holds a lease must send that lease's id.
The daemon no longer fills a missing lease id or label from the session,
so a client that holds only the shared proxy token and a session name
cannot read, drive, or close another client's session. Requests the
daemon builds inside an admitted request carry the parent's lease scope,
and install_from_source reads a leaseId param.
Caller-chosen lease ids on allocate need 128 bits. Daemons report the
session-lease-id capability.

* docs(proxy): keep the session sentence next to its subject

* refactor(daemon): name the session lease assertion and type the HTTP capability list

* fix(daemon): close the nested, open and provider-session gaps in the session lease rule

- Replay steps get the parent's lease scope, like other nested requests.
- A nested request keeps a lease id or label that it names in its flags.
- An open on an existing leased session checks the lease id before the
  fresh-open proxy metadata rule.
- An active provider-session artifact lookup needs the lease id.
- Docs: open saves the lease id; client API names the refusal.

* refactor(daemon): split the unleased-request decision out of lease admission

* fix(daemon): check the lease backend label against the session lease

* fix(daemon): treat every sent lease label as checked against the lease

- A label the request sends differs from a lease that does not carry it.
- leaseBackend is read from flags when meta lacks it, and compared in
  canonical form (readLeaseBackend in kernel, shared with the registry).
- A batch step's lease fields in flags win over the inherited batch meta;
  the tenant stays in meta.
- An active provider-session artifact lookup checks the id and every
  label against the active lease.

* fix(daemon): compare empty, batch and RPC lease labels against the lease

- An omitted label is not compared; an empty label differs from the lease.
- Tenants are compared after the existing tenant normalization.
- A batch step tenant must name the inherited (possibly attested) tenant.
- install_from_source reads every lease label; release_materialized_paths
  reads the tenant that the paired install recorded.
- artifacts checks a presented active lease id and its labels before the
  tenant-filtered provider-session lookup and before provider dispatch.

* refactor(daemon): publish the session lease reasons from typed reason tables

* fix(daemon): check flag tenants, install backends and lease id spellings on leased sessions

- A tenant flag is compared with the session lease at admission, so a batch
  step that names another tenant fails as that step (partial results kept),
  and a step on an unleased session is not refused.
- install_from_source reads the leaseBackend (or backend) param.
- The lease id is compared in canonical form (case, surrounding space), and
  the active provider lease's canonical id goes to the provider.

* docs(wire-compat): say a release sends the tenant its install sent

* fix(daemon): keep the batch scope for steps and compare flag lease fields on leased sessions

A batch step keeps the inherited batch meta as its scope again, so a step
on an unleased session runs as on base. On a leased session, admission
compares every lease field the request sends in flags with the lease, so a
step that names another lease id or tenant is still refused.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant