Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/daemon/src/__tests__/support/session-factories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,13 @@ export function authoringPublication(
? { kind: 'explicit', path: opts.path, force: opts?.force === true }
: { kind: 'default', force: opts?.force === true },
...(opts?.remote
? { remoteDelivery: { publicationId: 'publication-0001', revision: 0, tenantId: undefined } }
? {
remoteDelivery: {
publicationId: 'publication-0001',
revision: 0,
owner: { tenantId: undefined, leaseVerifier: null },
},
}
: {}),
};
}
Expand Down
16 changes: 16 additions & 0 deletions packages/daemon/src/__tests__/support/track-test-artifact.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {
type DownloadableArtifactRegistration,
trackDownloadableArtifact,
} from '../../resources/artifact-tracking.ts';

/** Registers an artifact for a producer named by its tenant and lease verifier; both default to none. */
export function trackTestArtifact({
tenantId,
leaseVerifier = null,
...registration
}: Omit<DownloadableArtifactRegistration, 'owner'> & {
tenantId?: string;
leaseVerifier?: string | null;
}): string {
return trackDownloadableArtifact({ ...registration, owner: { tenantId, leaseVerifier } });
}
15 changes: 11 additions & 4 deletions packages/daemon/src/core/__tests__/tenant-owned-entry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,21 @@ function captureAppError(fn: () => unknown): AppError {
throw new Error('expected an AppError to be thrown');
}

test('requireTenantOwnedEntry returns entries readable by the tenant', () => {
test('requireTenantOwnedEntry returns entries only to their own tenant', () => {
const map = new Map([
['shared', {}],
['untenanted', {}],
['owned', { tenantId: 'tenant-a' }],
]);
assert.equal(requireTenantOwnedEntry(map, 'shared', undefined, RESOURCE), map.get('shared'));
assert.equal(requireTenantOwnedEntry(map, 'shared', 'tenant-b', RESOURCE), map.get('shared'));
assert.equal(
requireTenantOwnedEntry(map, 'untenanted', undefined, RESOURCE),
map.get('untenanted'),
);
assert.equal(requireTenantOwnedEntry(map, 'owned', 'tenant-a', RESOURCE), map.get('owned'));
const refused = captureAppError(() =>
requireTenantOwnedEntry(map, 'untenanted', 'tenant-b', RESOURCE),
);
assert.equal(refused.code, 'UNAUTHORIZED');
assert.equal(refused.details?.reason, 'TENANT_OUTPUT_MISMATCH');
});

test('missing entries surface as expired resources with a recovery hint', () => {
Expand Down
38 changes: 15 additions & 23 deletions packages/daemon/src/core/capture-output-ownership.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import type { DaemonArtifact, DaemonResponseData } from '@agent-device/kernel/contracts';
import type { ArtifactOwner } from './tenant-owned-entry.ts';

const CAPTURE_OUTPUT_OWNERSHIP = Symbol('captureOutputOwnership');
type CaptureOutputOwnership = 'daemon' | 'caller';
type CaptureOutputOwner = Readonly<{
ownership: CaptureOutputOwnership;
tenantId?: string;
/** Null records an unleased producer. Undefined leaves ownership to the request. */
leaseVerifier?: string | null;
}>;
type CaptureOutputData = DaemonResponseData & {
[CAPTURE_OUTPUT_OWNERSHIP]?: CaptureOutputOwner;
[CAPTURE_OUTPUT_OWNERSHIP]?: Readonly<{
ownership: CaptureOutputOwnership;
owner: ArtifactOwner;
}>;
};

/** Producer-owned capture facts stay private when the response is serialized. */
export function withCaptureOutputOwnership(
data: DaemonResponseData,
ownership: CaptureOutputOwnership,
tenantId?: string,
leaseVerifier?: string | null,
owner: ArtifactOwner,
): DaemonResponseData {
return { ...data, [CAPTURE_OUTPUT_OWNERSHIP]: { ownership, tenantId, leaseVerifier } };
return { ...data, [CAPTURE_OUTPUT_OWNERSHIP]: { ownership, owner } };
}

export function captureOutputOwnership(
Expand All @@ -29,39 +26,34 @@ export function captureOutputOwnership(
return capture[CAPTURE_OUTPUT_OWNERSHIP]?.ownership;
}

export function captureOutputTenantId(data: DaemonResponseData): string | undefined {
export function captureOutputOwner(data: DaemonResponseData): ArtifactOwner | undefined {
const capture: CaptureOutputData = data;
return capture[CAPTURE_OUTPUT_OWNERSHIP]?.tenantId;
}

export function captureOutputLeaseVerifier(data: DaemonResponseData): string | null | undefined {
const capture: CaptureOutputData = data;
return capture[CAPTURE_OUTPUT_OWNERSHIP]?.leaseVerifier;
return capture[CAPTURE_OUTPUT_OWNERSHIP]?.owner;
}

const DAEMON_DELIVERED_ARTIFACT = Symbol('daemonDeliveredArtifact');
type DeliveredArtifact = DaemonArtifact & {
[DAEMON_DELIVERED_ARTIFACT]?: Readonly<{ tenantId: string | undefined }>;
[DAEMON_DELIVERED_ARTIFACT]?: ArtifactOwner;
};

/**
* Marks an artifact the daemon produced for the caller itself, such as a remote recording's script
* version. It is registered for download for `tenantId` alone, whatever the request's tenant,
* version. It is registered for download for `owner` alone, whatever the request's tenant, lease,
* capture filters, or network marker say. The mark stays private when the response is serialized.
*/
export function asDaemonDeliveredArtifact(
artifact: DaemonArtifact,
tenantId: string | undefined,
owner: ArtifactOwner,
): DaemonArtifact {
const delivered: DeliveredArtifact = artifact;
delivered[DAEMON_DELIVERED_ARTIFACT] = { tenantId };
delivered[DAEMON_DELIVERED_ARTIFACT] = owner;
return delivered;
}

/** The delivery of a daemon-delivered artifact, or `undefined` for any other artifact. */
/** The owner of a daemon-delivered artifact, or `undefined` for any other artifact. */
export function daemonDeliveredArtifact(
artifact: DaemonArtifact | undefined,
): Readonly<{ tenantId: string | undefined }> | undefined {
): ArtifactOwner | undefined {
const delivered: DeliveredArtifact | undefined = artifact;
return delivered?.[DAEMON_DELIVERED_ARTIFACT];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ test.each(['perf-capture', 'trace-log'] as const)(
const owned = kind === 'perf-capture' ? seedExistingCapture(world, kind) : undefined;
if (kind === 'trace-log') {
world.sessionStore.update(world.ref, {
trace: { outPath: '/tmp/owned.trace', startedAt: 1 },
trace: {
outPath: '/tmp/owned.trace',
startedAt: 1,
owner: { tenantId: undefined, leaseVerifier: null },
},
});
}
const before = owned ? fs.readFileSync(owned.resourcePath, 'utf8') : undefined;
Expand All @@ -42,6 +46,7 @@ test.each(['perf-capture', 'trace-log'] as const)(
expect(world.sessionStore.requireCurrent(world.ref).trace).toEqual({
outPath: '/tmp/owned.trace',
startedAt: 1,
owner: { tenantId: undefined, leaseVerifier: null },
});
}
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,15 @@ export function armAuthoringOnOpen(
);
}

/**
* The remote delivery an `open --save-script` asks for: the publication ID its client minted, when
* well formed, and the tenant that opens it.
*/
/** The publication ID that the client of an `open --save-script` minted, when well formed. */
export function remoteScriptOpen(
meta: DaemonRequestMeta | undefined,
): Omit<RemoteScriptDelivery, 'revision'> | undefined {
): Pick<RemoteScriptDelivery, 'publicationId'> | undefined {
const publicationId = meta?.scriptPublicationId;
if (typeof publicationId !== 'string' || !/^[A-Za-z0-9-]{16,64}$/.test(publicationId)) {
return undefined;
}
return { publicationId, tenantId: meta?.tenantId };
return { publicationId };
}

/**
Expand Down Expand Up @@ -244,7 +241,7 @@ function stampNextRevision(session: SessionState): RemoteScriptDelivery | undefi
/**
* Adds one script version of a remote recording to a successful response. The artifact carries the
* publication ID and its revision, so the caller writes it only to the destination it recorded and
* keeps the newest version. It registers for the tenant that opened the recording, whoever sent
* keeps the newest version. It registers for the tenant and lease that opened the recording, whoever sent
* this request. A failed version keeps the response successful and carries a typed
* `scriptDeliveryFailure` with the same publication ID and a warning.
*/
Expand Down Expand Up @@ -280,7 +277,7 @@ function withRemoteScriptVersion(
scriptPublicationId: publicationId,
scriptRevision: delivery.revision,
},
delivery.tenantId,
delivery.owner,
);
const artifacts = Array.isArray(data.artifacts) ? data.artifacts : [];
return { ok: true, data: { ...data, artifacts: [...artifacts, artifact] } };
Expand Down
9 changes: 5 additions & 4 deletions packages/daemon/src/core/session-script-publication-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
* engine can reach any of them.
*/

import type { ArtifactOwner } from './tenant-owned-entry.ts';

/**
* Where a script publishes.
*
Expand All @@ -29,14 +31,13 @@ export type SessionScriptTarget =
* A remote caller cannot read the daemon target, so each script version is returned as a
* `session-script` artifact. `publicationId` is the ID the caller minted for its open, so the caller
* writes a version only to the destination it recorded under that ID. `revision` numbers the
* versions, so the caller keeps the newest when downloads finish out of order. Only `tenantId`, the
* tenant that opened the recording, can download a version; an open without a tenant registers its
* versions like every other tenant-less artifact.
* versions, so the caller keeps the newest when downloads finish out of order. Only `owner`, the
* tenant and lease that opened the recording, can download a version.
*/
export type RemoteScriptDelivery = Readonly<{
publicationId: string;
revision: number;
tenantId: string | undefined;
owner: ArtifactOwner;
}>;

/**
Expand Down
6 changes: 3 additions & 3 deletions packages/daemon/src/core/session-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type { PostGesturePreActionBaseline } from '@agent-device/capture-kit/pos
import type { SnapshotFreshnessWindow } from '@agent-device/capture-kit/snapshot-freshness';
import type { RefFrame } from './ref-frame-slot.ts';
import type { SessionLease } from './lease-context.ts';
import type { ArtifactOwner } from './tenant-owned-entry.ts';
import type { SessionScriptPublicationState } from './session-script-publication-state.ts';

/**
Expand Down Expand Up @@ -243,8 +244,7 @@ export type SessionState = {
/** Remote traces accept request-scoped diagnostics instead of persistent runner streams. */
trace?: {
clientOutPath?: string;
remoteCaptureTenantId?: string;
leaseVerifier?: string | null;
owner: ArtifactOwner;
startedAt: number;
} & (
| { outPath: string; remoteCaptureOutputPath?: never }
Expand All @@ -259,7 +259,7 @@ export type SessionState = {
/** Last stopped CPU-profile coordinates retained for report in the same live session. */
lastPerfProfile?: {
profile: PerfProfileHandoff;
leaseVerifier: string | null;
owner: ArtifactOwner;
};
/** Native sampler mechanics stay behind the adopted runtime handle. */
audioProbe?: {
Expand Down
28 changes: 19 additions & 9 deletions packages/daemon/src/core/tenant-owned-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,24 @@ import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
export const TENANT_RESOURCE_REASONS = {
// The artifact, upload, or path id expired or never existed; the daemon cannot tell which.
expired: { reason: 'RESOURCE_EXPIRED' },
// The artifact, upload, path, or capture belongs to another tenant than the one the request sends.
tenantMismatch: { reason: 'TENANT_OUTPUT_MISMATCH' },
} as const satisfies ReasonTable<'daemon resources'>;

type TenantOwnedEntry = { tenantId?: string | null };
type TenantOwnedEntry = { tenantId?: string };

/** An explicit null owner restricts access to the shared, unnamed tenant scope. */
/** The tenant and lease of the request that produced an output. Null records an unleased producer. */
export type ArtifactOwner = Readonly<{
tenantId: string | undefined;
leaseVerifier: string | null;
}>;

/** An entry serves only its own tenant. An entry without a tenant serves only tenant-less requests. */
export function matchesTenantOwnedEntry(
entry: TenantOwnedEntry,
tenantId: string | undefined,
): boolean {
return entry.tenantId === null
? tenantId === undefined
: !entry.tenantId || entry.tenantId === tenantId;
return entry.tenantId === tenantId;
Comment thread
thymikee marked this conversation as resolved.
Resolved
}

export type TenantOwnedResourceKind = {
Expand Down Expand Up @@ -46,10 +52,14 @@ export function requireTenantOwnedEntry<T extends TenantOwnedEntry>(
throw expiredTenantOwnedEntryError(kind, id);
}
if (!matchesTenantOwnedEntry(entry, tenantId)) {
throw new AppError(
'UNAUTHORIZED',
`${kind.label} ${kind.plural ? 'belong' : 'belongs'} to a different tenant`,
);
throw tenantOutputRefusal(`${kind.label} ${kind.plural ? 'belong' : 'belongs'}`);
Comment thread
thymikee marked this conversation as resolved.
Resolved
}
return entry;
}

/** `subject` names the resource and its verb, such as "Trace belongs". */
export function tenantOutputRefusal(subject: string): AppError {
return new AppError('UNAUTHORIZED', `${subject} to a different tenant`, {
reason: TENANT_RESOURCE_REASONS.tenantMismatch.reason,
});
}
6 changes: 5 additions & 1 deletion packages/daemon/src/execution/generic-settle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,11 @@ for (const change of ['rebuild', 'retire'] as const) {
});
try {
await reached;
const trace = { outPath: 'latest-trace', startedAt: 1 };
const trace = {
outPath: 'latest-trace',
startedAt: 1,
owner: { tenantId: undefined, leaseVerifier: null },
};
const successor = makeIosSession(name);
if (change === 'rebuild') store.update(ref, { trace });
else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,11 @@ test.each(['rebuild', 'retire'] as const)(
if (transition === 'rebuild')
current = sessionStore.update(ref, {
actions: [],
trace: { outPath: '/latest.trace', startedAt: 1 },
trace: {
outPath: '/latest.trace',
startedAt: 1,
owner: { tenantId: undefined, leaseVerifier: null },
},
});
else {
sessionStore.retire(ref);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,13 @@ test('held touch settle publishes refs into the current record of its scoped lif
try {
await entered;
expect(refFrameState(ref.session)).toBe('expired');
sessionStore.update(ref, { trace: { outPath: 'rebuilt-trace', startedAt: 1 } });
sessionStore.update(ref, {
trace: {
outPath: 'rebuilt-trace',
startedAt: 1,
owner: { tenantId: undefined, leaseVerifier: null },
},
});
release();
const settle = expectOkData(await running).settle as SettlePayload;
const current = sessionStore.requireCurrent(ref);
Expand Down
Loading
Loading