mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
fix(pairing): keep signed-in devices when the first-seen save fails; report revoked devices on downgraded latched hosts (#39337)
- Device registry: if saving a device's first sign-in fails, keep the sign-in in memory and retry the save every minute until it lands. Before, a restart after the pairing code's expiry treated the device as an unused, expired code and refused and removed it. - Remote runtime client: when a host remembered as E2EE v2 refuses v2 and the legacy status check gets a sealed "unauthorized" reply, report that refusal instead of "update Orca on that host" with close code 4001, which managed orcad read as a different server on its port.
This commit is contained in:
@@ -14,6 +14,7 @@ import {
|
||||
import type { PairedRuntimeConnection } from '../../shared/remote-runtime/pairing/paired-runtime-connection'
|
||||
import type * as AuthValidation from './rpc/mobile-e2ee-auth-validation'
|
||||
import { E2EE_V2_TOKEN_CAPABILITIES_RUNTIME_CAPABILITY } from '../../shared/remote-runtime/pairing/device-key-capability'
|
||||
import { classifyOrcadTunnelIdentityFailure } from '../managed-server/lifecycle/orcad-managed-tunnel-identity'
|
||||
|
||||
// Hosts released between v2 and capability-carrying v2 token auth refused the extra field.
|
||||
const TOKEN_FOR_HOST_WITHOUT_V2_TOKEN_CAPABILITIES = 'device-token-v2-exact'
|
||||
@@ -45,7 +46,11 @@ type TestHost = {
|
||||
const openHosts: TestHost[] = []
|
||||
let userDataPath = ''
|
||||
|
||||
async function startHost(kind: HostKind, keyPair = nacl.box.keyPair()): Promise<TestHost> {
|
||||
async function startHost(
|
||||
kind: HostKind,
|
||||
keyPair = nacl.box.keyPair(),
|
||||
options: { revoked?: boolean } = {}
|
||||
): Promise<TestHost> {
|
||||
const publicKeyB64 = Buffer.from(keyPair.publicKey).toString('base64')
|
||||
const token =
|
||||
kind === 'v2-without-token-capabilities'
|
||||
@@ -63,7 +68,7 @@ async function startHost(kind: HostKind, keyPair = nacl.box.keyPair()): Promise<
|
||||
const channel = new E2EEChannel(ws, {
|
||||
serverSecretKey: keyPair.secretKey,
|
||||
resolveAuthenticatedDevice: (candidate) =>
|
||||
candidate === token
|
||||
candidate === token && !options.revoked
|
||||
? {
|
||||
deviceId: 'device-1',
|
||||
scope: 'runtime',
|
||||
@@ -216,4 +221,25 @@ describe('remote runtime client E2EE framing', () => {
|
||||
expect(blocked.requests).toEqual(['status.get over legacy'])
|
||||
expect(latchedHosts()).toEqual([current.connection.hostPublicKeyB64])
|
||||
})
|
||||
|
||||
it('reports a revoked device as unauthorized when a latched host was also downgraded', async () => {
|
||||
const keyPair = nacl.box.keyPair()
|
||||
const current = await startHost('current', keyPair)
|
||||
await expect(ping(current)).resolves.toBe('pong')
|
||||
await current.close()
|
||||
|
||||
const downgraded = await startHost('pre-v2', keyPair, { revoked: true })
|
||||
const error = await ping(downgraded).then(
|
||||
() => null,
|
||||
(rejection: unknown) => rejection
|
||||
)
|
||||
|
||||
expect(error).toMatchObject({ code: 'unauthorized', pairingStage: 'access-grant' })
|
||||
expect(error).not.toHaveProperty('closeCode', 4001)
|
||||
expect(String(error)).not.toContain('Update Orca')
|
||||
// Managed orcad reads this as a revoked pairing, not as a different server on its port.
|
||||
expect(classifyOrcadTunnelIdentityFailure(error).verdict).toBe('unpaired')
|
||||
expect(downgraded.requests).toEqual([])
|
||||
expect(latchedHosts()).toEqual([current.connection.hostPublicKeyB64])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -41,10 +41,13 @@ import type { NetworkSourceClass } from '../../network-source-class'
|
||||
|
||||
// Coalesce reconnect bookkeeping: each Windows save otherwise spawns synchronous ACL PowerShell twice.
|
||||
const LAST_SEEN_FLUSH_DELAY_MS = 250
|
||||
// Unpersisted, a restart would refuse and prune a signed-in row as an expired unused offer.
|
||||
const FIRST_SIGHTING_RETRY_MS = 60_000
|
||||
|
||||
export class DeviceRegistry extends DeviceRegistryStore {
|
||||
/** First sightings this session, kept even when their persist failed. */
|
||||
private readonly seenDeviceIds = new Set<string>()
|
||||
private firstSightingRetryPending = false
|
||||
|
||||
addDevice(
|
||||
name: string,
|
||||
@@ -287,13 +290,22 @@ export class DeviceRegistry extends DeviceRegistryStore {
|
||||
// Persist first sighting inline or rotation could delete a paired row still pending on disk.
|
||||
this.seenDeviceIds.add(deviceId)
|
||||
const seenAt = Date.now()
|
||||
this.replaceRow(deviceId, ({ offerExpiresAt: _paired, ...device }) => {
|
||||
const sight = ({ offerExpiresAt: _paired, ...device }: DeviceEntry): DeviceEntry => {
|
||||
const firstSighting =
|
||||
device.ticket === true && device.lastSeenAt === 0
|
||||
? { ...device, ticketFirstSeenAt: seenAt }
|
||||
: device
|
||||
return withDeviceSighting(seen(firstSighting, seenAt, sourceClass), seenAt, framing)
|
||||
})
|
||||
}
|
||||
try {
|
||||
this.replaceRow(deviceId, sight)
|
||||
} catch (error) {
|
||||
// Keep the sighting in memory so any later save writes it, and retry until one lands.
|
||||
this.devices = this.devices.map((d) => (d.deviceId === deviceId ? sight(d) : d))
|
||||
this.firstSightingRetryPending = true
|
||||
this.scheduleLastSeenFlush(FIRST_SIGHTING_RETRY_MS)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** Defer repeat sightings to avoid synchronous Windows ACL saves during E2EE auth.
|
||||
@@ -313,14 +325,14 @@ export class DeviceRegistry extends DeviceRegistryStore {
|
||||
? withDeviceSighting(seen(device, seenAt, sourceClass), seenAt, framing)
|
||||
: device
|
||||
)
|
||||
if (this.pendingLastSeenFlush) {
|
||||
return
|
||||
this.scheduleLastSeenFlush(LAST_SEEN_FLUSH_DELAY_MS)
|
||||
}
|
||||
|
||||
private scheduleLastSeenFlush(delayMs: number): void {
|
||||
if (!this.pendingLastSeenFlush) {
|
||||
this.pendingLastSeenFlush = setTimeout(() => this.flushPendingLastSeen(), delayMs)
|
||||
this.pendingLastSeenFlush.unref?.()
|
||||
}
|
||||
this.pendingLastSeenFlush = setTimeout(
|
||||
() => this.flushPendingLastSeen(),
|
||||
LAST_SEEN_FLUSH_DELAY_MS
|
||||
)
|
||||
this.pendingLastSeenFlush.unref?.()
|
||||
}
|
||||
|
||||
flushPendingLastSeen(): void {
|
||||
@@ -329,7 +341,15 @@ export class DeviceRegistry extends DeviceRegistryStore {
|
||||
}
|
||||
this.cancelPendingLastSeenFlush()
|
||||
// Failed bookkeeping must not terminate the runtime.
|
||||
this.saveOrLog({}, 'persist device lastSeen')
|
||||
try {
|
||||
this.devices = this.save(this.devices)
|
||||
this.firstSightingRetryPending = false
|
||||
} catch (error) {
|
||||
console.error('[runtime] Failed to persist device lastSeen:', error)
|
||||
if (this.firstSightingRetryPending) {
|
||||
this.scheduleLastSeenFlush(FIRST_SIGHTING_RETRY_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,12 +94,34 @@ describe('DeviceRegistry pairing offer TTL', () => {
|
||||
registry['save'] = save
|
||||
|
||||
vi.setSystemTime(1_000_000 + TTL + 1)
|
||||
expect(registry.getDevice(offer.deviceId)?.lastSeenAt).toBe(0)
|
||||
expect(registry.validateToken(offer.token)?.deviceId).toBe(offer.deviceId)
|
||||
registry.getOrCreatePendingDevice('Phone', 'mobile', 'network', [], TTL)
|
||||
expect(registry.getDevice(offer.deviceId)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('retries a failed first-seen persist so the device survives a restart after expiry', () => {
|
||||
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
|
||||
vi.setSystemTime(1_000_000)
|
||||
const registry = new DeviceRegistry(dir)
|
||||
const offer = registry.getOrCreatePendingDevice('Phone', 'mobile', 'network', [], TTL)
|
||||
const save = registry['save'].bind(registry)
|
||||
registry['save'] = vi.fn(() => {
|
||||
throw new Error('EPERM')
|
||||
})
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
expect(() => registry.updateLastSeen(offer.deviceId)).toThrow('EPERM')
|
||||
// Still failing on the first retry: keep retrying.
|
||||
vi.advanceTimersByTime(60_000)
|
||||
registry['save'] = save
|
||||
vi.advanceTimersByTime(60_000)
|
||||
|
||||
vi.setSystemTime(1_000_000 + TTL + 1)
|
||||
const restarted = new DeviceRegistry(dir)
|
||||
expect(restarted.validateToken(offer.token)?.deviceId).toBe(offer.deviceId)
|
||||
restarted.getOrCreatePendingDevice('Phone', 'mobile', 'network', [], TTL)
|
||||
expect(restarted.getDevice(offer.deviceId)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('round-trips the expiry through disk and drops it on first sighting', () => {
|
||||
const offer = new DeviceRegistry(dir).getOrCreatePendingDevice(
|
||||
'Phone',
|
||||
|
||||
@@ -163,7 +163,11 @@ async function latchedHostPredatesV2Token(
|
||||
status = await dial.readStatus(
|
||||
createRemoteRuntimeClientHandshake(hostPublicKeyB64, { latchedHostCheck: true })
|
||||
)
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// A sealed refusal of this device's credential proves the pinned host answered: it was revoked.
|
||||
if (isCredentialRefusal(error)) {
|
||||
throw error
|
||||
}
|
||||
return false
|
||||
}
|
||||
const capabilities = status.ok ? (status.result.capabilities ?? []) : null
|
||||
@@ -190,3 +194,11 @@ function latchedHostRefusalError(error: unknown): Error {
|
||||
})
|
||||
: new Error(message)
|
||||
}
|
||||
|
||||
function isCredentialRefusal(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof RemoteRuntimeClientError &&
|
||||
error.code === 'unauthorized' &&
|
||||
error.pairingStage === 'access-grant'
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user