Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

AGE-1506: Add RBAC on session and turn CRUD (#96)

Heer Ambavic50dbd58f670
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.json
index 3cb0d8d05..c095ce044 100644
--- a/fern/openapi/openapi.json
+++ b/fern/openapi/openapi.json
@@ -4479,7 +4479,7 @@
},
"/api/v1/sessions": {
"get": {
- "description": "List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent; optional `created_by` filters by creator identity. Pass `page_token` to fetch the next page, keeping the other query params constant.",
+ "description": "List the caller's sessions (newest first by default), token-paginated. Results are scoped to the authenticated identity via the session store's `created_by` filter (not a client query param). Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.",
"parameters": [
{
"description": "Page size. Defaults to 10, max 100.",
@@ -4545,17 +4545,6 @@
"minLength": 1,
"type": "string"
}
- },
- {
- "description": "When set, only sessions created by this identity are returned.",
- "in": "query",
- "name": "created_by",
- "required": false,
- "schema": {
- "description": "When set, only sessions created by this identity are returned.",
- "minLength": 1,
- "type": "string"
- }
}
],
"responses": {
@@ -4660,7 +4649,7 @@
},
"/api/v1/sessions/{session_id}": {
"delete": {
- "description": "Delete a session and all related turns, events, and internal state. Idempotent if already gone.",
+ "description": "Delete a session and all related turns, events, and internal state. Only the session creator (`created_by`) may delete it. Idempotent if already gone.",
"parameters": [
{
"description": "Session identifier.",
@@ -4678,6 +4667,16 @@
"responses": {
"204": {
"description": "Session and all related data deleted."
+ },
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
}
},
"summary": "Delete a session",
@@ -4690,7 +4689,7 @@
"x-fern-sdk-method-name": "delete"
},
"get": {
- "description": "Fetch a session by ID.",
+ "description": "Fetch a session by ID. Only the session creator (`created_by`) may fetch it.",
"parameters": [
{
"description": "Session identifier.",
@@ -4716,6 +4715,16 @@
},
"description": "Session data."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -4737,7 +4746,7 @@
"x-fern-sdk-method-name": "get"
},
"patch": {
- "description": "Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.",
+ "description": "Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`. Only the session creator (`created_by`) may update it.",
"parameters": [
{
"description": "Session identifier.",
@@ -4783,6 +4792,16 @@
},
"description": "Invalid request body."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -4816,7 +4835,7 @@
},
"/api/v1/sessions/{session_id}/cancel": {
"post": {
- "description": "Cancel the running last turn for a session.",
+ "description": "Cancel the running last turn for a session. Only the session creator (`created_by`) may cancel.",
"parameters": [
{
"description": "Session identifier.",
@@ -4852,6 +4871,16 @@
},
"description": "Turn cancelled."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -4885,7 +4914,7 @@
},
"/api/v1/sessions/{session_id}/events": {
"get": {
- "description": "List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.",
+ "description": "List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor. Only the session creator (`created_by`) may list events.",
"parameters": [
{
"description": "Session identifier.",
@@ -4954,6 +4983,16 @@
},
"description": "Invalid page token."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -4982,7 +5021,7 @@
},
"/api/v1/sessions/{session_id}/turns": {
"get": {
- "description": "List turns for a session (newest first by default), token-paginated.",
+ "description": "List turns for a session (newest first by default), token-paginated. Only the session creator (`created_by`) may list turns.",
"parameters": [
{
"description": "Session identifier.",
@@ -5041,6 +5080,16 @@
},
"description": "Invalid page token."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -5067,7 +5116,7 @@
"x-fern-sdk-method-name": "list_turns"
},
"post": {
- "description": "Create a turn within a session and execute it.\nWhen `stream` is true (default), respond with a Server-Sent Events stream of turn events.\nWhen `stream` is false, return the turn immediately with `state.status: \"running\"` while execution continues in the background; use get turn or subscribe to observe completion.\nUse `previous_turn_id` to chain to the session's last turn (defaults to `auto`); use `none` for a new root.",
+ "description": "Create a turn within a session and execute it.\nOnly the session creator (`created_by`) may create turns.\nWhen `stream` is true (default), respond with a Server-Sent Events stream of turn events.\nWhen `stream` is false, return the turn immediately with `state.status: \"running\"` while execution continues in the background; use get turn or subscribe to observe completion.\nUse `previous_turn_id` to chain to the session's last turn (defaults to `auto`); use `none` for a new root.",
"parameters": [
{
"description": "Session identifier.",
@@ -5118,6 +5167,16 @@
},
"description": "Invalid request body."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -5172,7 +5231,7 @@
},
"/api/v1/sessions/{session_id}/turns/{turn_id}": {
"get": {
- "description": "Fetch a single turn by ID.",
+ "description": "Fetch a single turn by ID. Only the session creator (`created_by`) may fetch it.",
"parameters": [
{
"description": "Session identifier.",
@@ -5209,6 +5268,16 @@
},
"description": "Turn data."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -5232,7 +5301,7 @@
},
"/api/v1/sessions/{session_id}/turns/{turn_id}/download": {
"get": {
- "description": "Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.",
+ "description": "Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block. Only the session creator (`created_by`) may download.",
"parameters": [
{
"description": "Session identifier.",
@@ -5299,7 +5368,7 @@
}
}
},
- "description": "Sandbox belongs to another tenant."
+ "description": "Caller is not the session creator, or sandbox belongs to another tenant."
},
"404": {
"content": {
@@ -5364,7 +5433,7 @@
},
"/api/v1/sessions/{session_id}/turns/{turn_id}/events": {
"get": {
- "description": "Paginated persisted events for a turn (insertion order by default).",
+ "description": "Paginated persisted events for a turn (insertion order by default). Only the session creator (`created_by`) may list events.",
"parameters": [
{
"description": "Session identifier.",
@@ -5443,6 +5512,16 @@
},
"description": "Invalid page token."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
@@ -5471,7 +5550,7 @@
},
"/api/v1/sessions/{session_id}/turns/{turn_id}/subscribe": {
"get": {
- "description": "Subscribe to the live SSE stream for a turn. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).",
+ "description": "Subscribe to the live SSE stream for a turn. Only the session creator (`created_by`) may subscribe. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).",
"parameters": [
{
"description": "Session identifier.",
@@ -5530,6 +5609,16 @@
},
"description": "Invalid request body."
},
+ "403": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Caller is not the session creator."
+ },
"404": {
"content": {
"application/json": {
diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.json
index fe0394ea6..836c56edb 100644
--- a/packages/sdk/.fern/metadata.json
+++ b/packages/sdk/.fern/metadata.json
@@ -27,7 +27,7 @@
"streamType": "web",
"useDefaultRequestParameterValues": true
},
- "originGitCommit": "297c5b1fc240cff72f32bffbc241701aa6a24885",
+ "originGitCommit": "c2bf45cdfbdb210568d7e01ed635e204ce04facb",
"originGitCommitIsDirty": true,
"invokedBy": "ci",
"requestedVersion": "0.0.0",
diff --git a/packages/sdk/reference.md b/packages/sdk/reference.md
index d8dadddae..48b0d4d15 100644
--- a/packages/sdk/reference.md
+++ b/packages/sdk/reference.md
@@ -687,7 +687,7 @@ await client.models.list();
<dl>
<dd>
-List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent; optional `created_by` filters by creator identity. Pass `page_token` to fetch the next page, keeping the other query params constant.
+List the caller's sessions (newest first by default), token-paginated. Results are scoped to the authenticated identity via the session store's `created_by` filter (not a client query param). Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.
</dd>
</dl>
</dd>
@@ -818,7 +818,7 @@ await client.sessions.create({
<dl>
<dd>
-Fetch a session by ID.
+Fetch a session by ID. Only the session creator (`created_by`) may fetch it.
</dd>
</dl>
</dd>
@@ -881,7 +881,7 @@ await client.sessions.get("session_id");
<dl>
<dd>
-Delete a session and all related turns, events, and internal state. Idempotent if already gone.
+Delete a session and all related turns, events, and internal state. Only the session creator (`created_by`) may delete it. Idempotent if already gone.
</dd>
</dl>
</dd>
@@ -944,7 +944,7 @@ await client.sessions.delete("session_id");
<dl>
<dd>
-Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.
+Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`. Only the session creator (`created_by`) may update it.
</dd>
</dl>
</dd>
@@ -1015,7 +1015,7 @@ await client.sessions.update("session_id");
<dl>
<dd>
-Cancel the running last turn for a session.
+Cancel the running last turn for a session. Only the session creator (`created_by`) may cancel.
</dd>
</dl>
</dd>
@@ -1086,7 +1086,7 @@ await client.sessions.cancel("session_id");
<dl>
<dd>
-List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.
+List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor. Only the session creator (`created_by`) may list events.
</dd>
</dl>
</dd>
@@ -1157,7 +1157,7 @@ await client.sessions.listEvents("session_id");
<dl>
<dd>
-List turns for a session (newest first by default), token-paginated.
+List turns for a session (newest first by default), token-paginated. Only the session creator (`created_by`) may list turns.
</dd>
</dl>
</dd>
@@ -1229,6 +1229,7 @@ await client.sessions.listTurns("session_id");
<dd>
Create a turn within a session and execute it.
+Only the session creator (`created_by`) may create turns.
When `stream` is true (default), respond with a Server-Sent Events stream of turn events.
When `stream` is false, return the turn immediately with `state.status: "running"` while execution continues in the background; use get turn or subscribe to observe completion.
Use `previous_turn_id` to chain to the session's last turn (defaults to `auto`); use `none` for a new root.
@@ -1306,6 +1307,7 @@ for await (const item of response) {
<dd>
Create a turn within a session and execute it.
+Only the session creator (`created_by`) may create turns.
When `stream` is true (default), respond with a Server-Sent Events stream of turn events.
When `stream` is false, return the turn immediately with `state.status: "running"` while execution continues in the background; use get turn or subscribe to observe completion.
Use `previous_turn_id` to chain to the session's last turn (defaults to `auto`); use `none` for a new root.
@@ -1379,7 +1381,7 @@ await client.sessions.createTurn("session_id", {});
<dl>
<dd>
-Fetch a single turn by ID.
+Fetch a single turn by ID. Only the session creator (`created_by`) may fetch it.
</dd>
</dl>
</dd>
@@ -1450,7 +1452,7 @@ await client.sessions.getTurn("session_id", "turn_id");
<dl>
<dd>
-Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.
+Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block. Only the session creator (`created_by`) may download.
</dd>
</dl>
</dd>
@@ -1531,7 +1533,7 @@ await client.sessions.downloadSandboxFile("session_id", "turn_id", {
<dl>
<dd>
-Paginated persisted events for a turn (insertion order by default).
+Paginated persisted events for a turn (insertion order by default). Only the session creator (`created_by`) may list events.
</dd>
</dl>
</dd>
@@ -1610,7 +1612,7 @@ await client.sessions.listTurnEvents("session_id", "turn_id");
<dl>
<dd>
-Subscribe to the live SSE stream for a turn. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).
+Subscribe to the live SSE stream for a turn. Only the session creator (`created_by`) may subscribe. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).
</dd>
</dl>
</dd>
diff --git a/packages/sdk/src/api/resources/sessions/client/Client.ts b/packages/sdk/src/api/resources/sessions/client/Client.ts
index bd3ab75da..1c1f2dd2d 100644
--- a/packages/sdk/src/api/resources/sessions/client/Client.ts
+++ b/packages/sdk/src/api/resources/sessions/client/Client.ts
@@ -24,7 +24,7 @@ export class SessionsClient {
}
/**
- * List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent; optional `created_by` filters by creator identity. Pass `page_token` to fetch the next page, keeping the other query params constant.
+ * List the caller's sessions (newest first by default), token-paginated. Results are scoped to the authenticated identity via the session store's `created_by` filter (not a client query param). Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.
*
* @param {TrueForge.ListSessionsRequest} request
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -44,7 +44,7 @@ export class SessionsClient {
async (
request: TrueForge.ListSessionsRequest,
): Promise<core.WithRawResponse<TrueForge.ListSessionsResponse>> => {
- const { limit = 10, order, pageToken, startTimestamp, endTimestamp, agentId, createdBy } = request;
+ const { limit = 10, order, pageToken, startTimestamp, endTimestamp, agentId } = request;
const _queryParams: Record<string, unknown> = {
limit,
order:
@@ -60,7 +60,6 @@ export class SessionsClient {
start_timestamp: startTimestamp != null ? startTimestamp?.toISOString() : undefined,
end_timestamp: endTimestamp != null ? endTimestamp?.toISOString() : undefined,
agent_id: agentId,
- created_by: createdBy,
};
const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
this._options?.headers,
@@ -254,11 +253,12 @@ export class SessionsClient {
}
/**
- * Fetch a session by ID.
+ * Fetch a session by ID. Only the session creator (`created_by`) may fetch it.
*
* @param {string} session_id - Session identifier.
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
@@ -308,6 +308,17 @@ export class SessionsClient {
if (_response.error.reason === "status-code") {
switch (_response.error.statusCode) {
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -332,11 +343,12 @@ export class SessionsClient {
}
/**
- * Delete a session and all related turns, events, and internal state. Idempotent if already gone.
+ * Delete a session and all related turns, events, and internal state. Only the session creator (`created_by`) may delete it. Idempotent if already gone.
*
* @param {string} session_id - Session identifier.
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
*
@@ -372,11 +384,25 @@ export class SessionsClient {
}
if (_response.error.reason === "status-code") {
- throw new errors.TrueForgeError({
- statusCode: _response.error.statusCode,
- body: _response.error.body,
- rawResponse: _response.rawResponse,
- });
+ switch (_response.error.statusCode) {
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
+ default:
+ throw new errors.TrueForgeError({
+ statusCode: _response.error.statusCode,
+ body: _response.error.body,
+ rawResponse: _response.rawResponse,
+ });
+ }
}
return handleNonStatusCodeError(
@@ -388,13 +414,14 @@ export class SessionsClient {
}
/**
- * Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.
+ * Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`. Only the session creator (`created_by`) may update it.
*
* @param {string} session_id - Session identifier.
* @param {TrueForge.UpdateSessionRequest} request
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link TrueForge.UnprocessableEntityError}
* @throws {@link errors.TrueForgeError}
@@ -469,6 +496,17 @@ export class SessionsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -509,12 +547,13 @@ export class SessionsClient {
}
/**
- * Cancel the running last turn for a session.
+ * Cancel the running last turn for a session. Only the session creator (`created_by`) may cancel.
*
* @param {string} session_id - Session identifier.
* @param {TrueForge.CancelSessionRequest} request
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link TrueForge.PreconditionFailedError}
* @throws {@link errors.TrueForgeError}
@@ -578,6 +617,17 @@ export class SessionsClient {
if (_response.error.reason === "status-code") {
switch (_response.error.statusCode) {
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -618,13 +668,14 @@ export class SessionsClient {
}
/**
- * List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.
+ * List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor. Only the session creator (`created_by`) may list events.
*
* @param {string} session_id - Session identifier.
* @param {TrueForge.ListEventsSessionsRequest} request
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
@@ -695,6 +746,17 @@ export class SessionsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -737,13 +799,14 @@ export class SessionsClient {
}
/**
- * List turns for a session (newest first by default), token-paginated.
+ * List turns for a session (newest first by default), token-paginated. Only the session creator (`created_by`) may list turns.
*
* @param {string} session_id - Session identifier.
* @param {TrueForge.ListTurnsSessionsRequest} request
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
@@ -813,6 +876,17 @@ export class SessionsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -856,6 +930,7 @@ export class SessionsClient {
/**
* Create a turn within a session and execute it.
+ * Only the session creator (`created_by`) may create turns.
* When `stream` is true (default), respond with a Server-Sent Events stream of turn events.
* When `stream` is false, return the turn immediately with `state.status: "running"` while execution continues in the background; use get turn or subscribe to observe completion.
* Use `previous_turn_id` to chain to the session's last turn (defaults to `auto`); use `none` for a new root.
@@ -939,6 +1014,17 @@ export class SessionsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -991,6 +1077,7 @@ export class SessionsClient {
/**
* Create a turn within a session and execute it.
+ * Only the session creator (`created_by`) may create turns.
* When `stream` is true (default), respond with a Server-Sent Events stream of turn events.
* When `stream` is false, return the turn immediately with `state.status: "running"` while execution continues in the background; use get turn or subscribe to observe completion.
* Use `previous_turn_id` to chain to the session's last turn (defaults to `auto`); use `none` for a new root.
@@ -1000,6 +1087,7 @@ export class SessionsClient {
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link TrueForge.PreconditionFailedError}
* @throws {@link TrueForge.UnprocessableEntityError}
@@ -1078,6 +1166,17 @@ export class SessionsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -1129,12 +1228,13 @@ export class SessionsClient {
}
/**
- * Fetch a single turn by ID.
+ * Fetch a single turn by ID. Only the session creator (`created_by`) may fetch it.
*
* @param {string} session_id - Session identifier.
* @param {string} turn_id - Turn identifier.
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
@@ -1186,6 +1286,17 @@ export class SessionsClient {
if (_response.error.reason === "status-code") {
switch (_response.error.statusCode) {
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -1215,7 +1326,7 @@ export class SessionsClient {
}
/**
- * Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.
+ * Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block. Only the session creator (`created_by`) may download.
*
* @throws {@link TrueForge.BadRequestError}
* @throws {@link TrueForge.ForbiddenError}
@@ -1370,7 +1481,7 @@ export class SessionsClient {
}
/**
- * Paginated persisted events for a turn (insertion order by default).
+ * Paginated persisted events for a turn (insertion order by default). Only the session creator (`created_by`) may list events.
*
* @param {string} session_id - Session identifier.
* @param {string} turn_id - Turn identifier.
@@ -1378,6 +1489,7 @@ export class SessionsClient {
* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.BadRequestError}
+ * @throws {@link TrueForge.ForbiddenError}
* @throws {@link TrueForge.NotFoundError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
@@ -1457,6 +1569,17 @@ export class SessionsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
@@ -1499,7 +1622,7 @@ export class SessionsClient {
}
/**
- * Subscribe to the live SSE stream for a turn. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).
+ * Subscribe to the live SSE stream for a turn. Only the session creator (`created_by`) may subscribe. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).
*/
public subscribeToTurn(
session_id: string,
@@ -1614,6 +1737,17 @@ export class SessionsClient {
}),
_response.rawResponse,
);
+ case 403:
+ throw new TrueForge.ForbiddenError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
case 404:
throw new TrueForge.NotFoundError(
serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
diff --git a/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
index c8bc31dd5..c839e37f2 100644
--- a/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
+++ b/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts
@@ -19,6 +19,4 @@ export interface ListSessionsRequest {
endTimestamp?: Date;
/** When set, only sessions bound to this agent id are returned. */
agentId?: string;
- /** When set, only sessions created by this identity are returned. */
- createdBy?: string;
}
diff --git a/packages/sdk/tests/wire/sessions.test.ts b/packages/sdk/tests/wire/sessions.test.ts
index 16f36a87c..6300b3307 100644
--- a/packages/sdk/tests/wire/sessions.test.ts
+++ b/packages/sdk/tests/wire/sessions.test.ts
@@ -237,6 +237,25 @@ describe("SessionsClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .get("/api/v1/sessions/session_id")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.get("session_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("get (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.get("/api/v1/sessions/session_id")
@@ -250,7 +269,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("delete", async () => {
+ test("delete (1)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
@@ -260,6 +279,25 @@ describe("SessionsClient", () => {
expect(response).toEqual(undefined);
});
+ test("delete (2)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .delete("/api/v1/sessions/session_id")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.delete("session_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
test("update (1)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
@@ -326,6 +364,26 @@ describe("SessionsClient", () => {
const rawRequestBody = {};
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .patch("/api/v1/sessions/session_id")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.update("session_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("update (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.patch("/api/v1/sessions/session_id")
@@ -340,7 +398,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("update (4)", async () => {
+ test("update (5)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
const rawRequestBody = {};
@@ -385,6 +443,26 @@ describe("SessionsClient", () => {
const rawRequestBody = {};
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .post("/api/v1/sessions/session_id/cancel")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.cancel("session_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("cancel (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+ const rawRequestBody = {};
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.post("/api/v1/sessions/session_id/cancel")
@@ -399,7 +477,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("cancel (3)", async () => {
+ test("cancel (4)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
const rawRequestBody = {};
@@ -505,6 +583,25 @@ describe("SessionsClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .get("/api/v1/sessions/session_id/events")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listEvents("session_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("list_events (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.get("/api/v1/sessions/session_id/events")
@@ -603,6 +700,25 @@ describe("SessionsClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .get("/api/v1/sessions/session_id/turns")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listTurns("session_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("list_turns (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.get("/api/v1/sessions/session_id/turns")
@@ -680,6 +796,26 @@ describe("SessionsClient", () => {
const rawRequestBody = { stream: true };
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .post("/api/v1/sessions/session_id/turns")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.createTurnStream("session_id", {});
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("create_turn_stream (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+ const rawRequestBody = { stream: true };
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.post("/api/v1/sessions/session_id/turns")
@@ -694,7 +830,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("create_turn_stream (4)", async () => {
+ test("create_turn_stream (5)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
const rawRequestBody = { stream: true };
@@ -714,7 +850,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.PreconditionFailedError);
});
- test("create_turn_stream (5)", async () => {
+ test("create_turn_stream (6)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
const rawRequestBody = { stream: true };
@@ -806,6 +942,26 @@ describe("SessionsClient", () => {
const rawRequestBody = { stream: false };
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .post("/api/v1/sessions/session_id/turns")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.createTurn("session_id", {});
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("create_turn (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+ const rawRequestBody = { stream: false };
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.post("/api/v1/sessions/session_id/turns")
@@ -820,7 +976,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("create_turn (4)", async () => {
+ test("create_turn (5)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
const rawRequestBody = { stream: false };
@@ -840,7 +996,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.PreconditionFailedError);
});
- test("create_turn (5)", async () => {
+ test("create_turn (6)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
const rawRequestBody = { stream: false };
@@ -911,6 +1067,25 @@ describe("SessionsClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .get("/api/v1/sessions/session_id/turns/turn_id")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.getTurn("session_id", "turn_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("get_turn (3)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.get("/api/v1/sessions/session_id/turns/turn_id")
@@ -1004,6 +1179,25 @@ describe("SessionsClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .get("/api/v1/sessions/session_id/turns/turn_id/events")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.listTurnEvents("session_id", "turn_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("list_turn_events (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.get("/api/v1/sessions/session_id/turns/turn_id/events")
@@ -1079,6 +1273,25 @@ describe("SessionsClient", () => {
const rawResponseBody = { error: { message: "message" } };
+ server
+ .mockEndpoint()
+ .get("/api/v1/sessions/session_id/turns/turn_id/subscribe")
+ .respondWith()
+ .statusCode(403)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.sessions.subscribeToTurn("session_id", "turn_id");
+ }).rejects.toThrow(TrueForgeTypes.ForbiddenError);
+ });
+
+ test("subscribe_to_turn (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
+
+ const rawResponseBody = { error: { message: "message" } };
+
server
.mockEndpoint()
.get("/api/v1/sessions/session_id/turns/turn_id/subscribe")
@@ -1092,7 +1305,7 @@ describe("SessionsClient", () => {
}).rejects.toThrow(TrueForgeTypes.NotFoundError);
});
- test("subscribe_to_turn (4)", async () => {
+ test("subscribe_to_turn (5)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });
diff --git a/packages/server/src/apis/auth.ts b/packages/server/src/apis/auth.ts
index 624bbde14..4e3dbb3b3 100644
--- a/packages/server/src/apis/auth.ts
+++ b/packages/server/src/apis/auth.ts
@@ -2,7 +2,8 @@ import { OpenAPIHono } from '@hono/zod-openapi';
import type { Configuration } from 'openid-client';
import type { Logger } from 'winston';
import { clearAuthCookie, ID_TOKEN_COOKIE, OAUTH_STATE_COOKIE, readOAuthStateCookie } from '../auth/cookies';
-import { authMiddleware, DEFAULT_USER_CONTEXT } from '../auth/middleware';
+import { resolveUserContext } from '../auth/identity';
+import { authMiddleware } from '../auth/middleware';
import { buildLoginAuthorization, exchangeAuthorizationCode, getOidcVerify, safeReturnTo } from '../auth/oidc';
import { authLoginRoute, authLogoutRoute, meRoute, oAuthCallbackRoute } from '../routes/authRoutes';
import type { MeResponse } from '../schemas/auth';
@@ -78,7 +79,7 @@ export function createAuthRouter(params: { oidcClient: Configuration | undefined
const gated = new OpenAPIHono();
gated.use('*', authMiddleware);
gated.openapi(meRoute, c => {
- const user = c.get('user') ?? DEFAULT_USER_CONTEXT;
+ const user = resolveUserContext(c);
const body: MeResponse = getOidcVerify()
? { type: 'oidc-connected', email: user.userRef, role: user.role }
: { type: 'default', email: user.userRef, role: user.role };
diff --git a/packages/server/src/apis/sessions.ts b/packages/server/src/apis/sessions.ts
index dbc6ba32c..9aa91e882 100644
--- a/packages/server/src/apis/sessions.ts
+++ b/packages/server/src/apis/sessions.ts
@@ -18,6 +18,7 @@ import { HTTPException } from 'hono/http-exception';
import type { RedisClientType } from 'redis';
import { ulid } from 'ulid';
import { z } from 'zod';
+import type { ResolveUserContext } from '../auth/identity';
import configuration from '../config';
import type { IAgentStore } from '../db/agentStore';
import type { IMcpServerStore } from '../db/mcpServerStore';
@@ -74,6 +75,7 @@ export interface SessionsRouterDeps {
sandboxProviderStore: ISandboxProviderStore;
redis?: RedisClientType | undefined;
requestReplyRouter: RequestReplyRouter;
+ resolveUserContext: ResolveUserContext;
}
function cancelTurnOnThisExecutor(
@@ -184,6 +186,12 @@ export async function cancelSessionTurn(
cancelTurnOnThisExecutor(deps.activeTurns, { sessionId, turnId, reason });
}
+const FORBIDDEN_SESSION_ACCESS = 'Only the session creator can access this session';
+
+function checkSessionAccess({ userRef, createdBy }: { userRef: string; createdBy: string }): boolean {
+ return userRef === createdBy;
+}
+
/** DB-backed sessions (mounted at /api/v1/sessions). */
export function createSessionsRouter(deps: SessionsRouterDeps) {
const createSessionHandler: RouteHandler<typeof createSessionRoute> = async c => {
@@ -195,10 +203,11 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
if (agent === undefined) {
return c.json({ error: { message: `Agent not found: ${body.agent.agent_id}` } }, 404);
}
+ const user = deps.resolveUserContext(c);
const session = await deps.sessions.create({
tenant_id: TENANT_ID,
session_id: sessionId,
- created_by: 'trueforge-default',
+ created_by: user.userRef,
agent: body.agent,
});
return c.json({ data: toWireSession(session.record) }, 201);
@@ -212,10 +221,11 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
});
+ const user = deps.resolveUserContext(c);
const session = await deps.sessions.create({
tenant_id: TENANT_ID,
session_id: sessionId,
- created_by: 'trueforge-default',
+ created_by: user.userRef,
agent: body.agent,
});
return c.json({ data: toWireSession(session.record) }, 201);
@@ -227,11 +237,22 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
if (!record) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
+ if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: record.created_by })) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
return c.json({ data: toWireSession(record) }, 200);
};
const deleteSessionHandler: RouteHandler<typeof deleteSessionRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
+ const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
+ if (!record) {
+ // Idempotent delete when already gone.
+ return c.body(null, 204);
+ }
+ if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: record.created_by })) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
await deps.sessionStore.deleteSession({ tenant_id: TENANT_ID, session_id: sessionId });
return c.body(null, 204);
};
@@ -239,6 +260,13 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const updateSessionHandler: RouteHandler<typeof updateSessionRoute> = async c => {
const { session_id: sessionId } = c.req.valid('param');
const body = c.req.valid('json');
+ const existing = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });
+ if (!existing) {
+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
+ }
+ if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: existing.created_by })) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
// Draft (value) sessions may replace their inline agent; named (ref) sessions
// cannot — the store rejects that with SessionStoreInvariantError → 422 below.
if (body.agent !== undefined) {
@@ -276,10 +304,11 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
const listSessionsHandler: RouteHandler<typeof listSessionsRoute> = async c => {
const query = c.req.valid('query');
+ const user = deps.resolveUserContext(c);
try {
const { data, pagination } = await deps.sessionStore.listSessions({
agent_id: query.agent_id,
- created_by: query.created_by,
+ created_by: user.userRef,
tenant_id: TENANT_ID,
limit: query.limit,
order: query.order,
@@ -302,6 +331,9 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
if (!record) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
+ if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: record.created_by })) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
const turnId = record.last_turn_id;
if (!turnId) {
return c.json({}, 200);
@@ -318,6 +350,9 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
+ if (!checkSessionAccess({ userRef: deps.resolveUserContext(c).userRef, createdBy: session.record.created_by })) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
try {
const { data, pagination } = await session.listEvents({
limit: query.limit,
diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.ts
index fee30f200..0bbf2aa1f 100644
--- a/packages/server/src/apis/turns.ts
+++ b/packages/server/src/apis/turns.ts
@@ -8,7 +8,6 @@ import {
EventType,
SessionStoreConflictError,
SessionStoreNotFoundError,
- TurnHandle,
TurnResourceResolver,
type TurnInputItem,
type TurnRecordWithoutSnapshot,
@@ -27,6 +26,7 @@ import type { Context } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { streamSSE } from 'hono/streaming';
import type { Logger } from 'winston';
+import type { ResolveUserContext, UserContext } from '../auth/identity';
import configuration from '../config';
import type { IAgentStore } from '../db/agentStore';
import type { IMcpServerStore } from '../db/mcpServerStore';
@@ -110,6 +110,7 @@ export interface TurnsRouterDeps {
eventSubscriptions: EventSubscriptionRegistry<TurnStreamingEvent>;
sandboxProviderStore: ISandboxProviderStore;
logger: Logger;
+ resolveUserContext: ResolveUserContext;
}
/**
@@ -322,6 +323,14 @@ export function resolveAfterSequenceNumber(c: Context, bodyAfterSequenceNumber?:
return bodyAfterSequenceNumber;
}
+/** True when `user` is the session creator (`created_by`). */
+function checkTurnAccess(user: UserContext, createdBy: string): boolean {
+ return createdBy === user.userRef;
+}
+
+const FORBIDDEN_SESSION_ACCESS = 'Only the session creator can access this session';
+const FORBIDDEN_CREATE_TURN = 'Only the session creator can create turns';
+
/** DB-backed turns (mounted at /api/v1/sessions). */
export function createTurnsRouter(deps: TurnsRouterDeps) {
const listTurnsHandler: RouteHandler<typeof listTurnsRoute> = async c => {
@@ -331,6 +340,9 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
+ if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
try {
const { data, pagination } = await session.listTurns({
limit: query.limit,
@@ -347,11 +359,14 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const getTurnHandler: RouteHandler<typeof getTurnRoute> = async c => {
const { session_id: sessionId, turn_id: turnId } = c.req.valid('param');
- const turn = await TurnHandle.get({
- store: deps.sessionStore,
- session_id: sessionId,
- turn_id: turnId,
- });
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ if (!session) {
+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
+ }
+ if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
+ const turn = await session.getTurn(turnId);
if (!turn) {
return c.json({ error: { message: `Turn not found: ${turnId}` } }, 404);
}
@@ -371,8 +386,11 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
+ if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
- // Loading the turn through the session is also the ownership check: a turn id from another
+ // Loading the turn through the session is also a session-binding check: a turn id from another
// session cannot be used to reach this session's sandbox.
const turn = await session.getTurn(turnId);
if (!turn) {
@@ -420,11 +438,14 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
const listTurnEventsHandler: RouteHandler<typeof listTurnEventsRoute> = async c => {
const { session_id: sessionId, turn_id: turnId } = c.req.valid('param');
const query = c.req.valid('query');
- const turn = await TurnHandle.get({
- store: deps.sessionStore,
- session_id: sessionId,
- turn_id: turnId,
- });
+ const session = await deps.sessions.get({ tenant_id: TENANT_ID, session_id: sessionId });
+ if (!session) {
+ return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
+ }
+ if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
+ const turn = await session.getTurn(turnId);
if (!turn) {
return c.json({ error: { message: `Turn not found: ${turnId}` } }, 404);
}
@@ -451,6 +472,9 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
+ if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ return c.json({ error: { message: FORBIDDEN_CREATE_TURN } }, 403);
+ }
const abortController = new AbortController();
const resolver = createTurnResolver({
@@ -572,6 +596,9 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
if (!session) {
return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);
}
+ if (!checkTurnAccess(deps.resolveUserContext(c), session.record.created_by)) {
+ return c.json({ error: { message: FORBIDDEN_SESSION_ACCESS } }, 403);
+ }
const turn = await session.getTurn(turnId);
if (!turn) {
return c.json({ error: { message: `Turn not found: ${turnId}` } }, 404);
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index c6fb602e0..ac8208836 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -18,6 +18,7 @@ import { createSessionsRouter } from './apis/sessions';
import { createSettingsRouter } from './apis/settings';
import { createAvailableSkillsRouter } from './apis/skills';
import { createTurnsRouter } from './apis/turns';
+import { resolveUserContext } from './auth/identity';
import { authMiddleware } from './auth/middleware';
import type { McpCatalog } from './catalog/McpCatalog';
import type { ModelCatalog } from './catalog/ModelCatalog';
@@ -159,6 +160,7 @@ export function createServerApp(deps: ServerDeps) {
sandboxProviderStore: deps.sandboxProviderStore,
redis: deps.redis,
requestReplyRouter: deps.requestReplyRouter,
+ resolveUserContext: resolveUserContext,
}),
),
);
@@ -177,6 +179,7 @@ export function createServerApp(deps: ServerDeps) {
eventSubscriptions: deps.eventSubscriptions,
sandboxProviderStore: deps.sandboxProviderStore,
logger: deps.logger,
+ resolveUserContext: resolveUserContext,
}),
),
);
diff --git a/packages/server/src/auth/claims.ts b/packages/server/src/auth/claims.ts
index eb28c6ce7..440a4fad1 100644
--- a/packages/server/src/auth/claims.ts
+++ b/packages/server/src/auth/claims.ts
@@ -1,15 +1,9 @@
import type { OIDCConfig } from '../config';
+import type { Role, UserContext } from './identity';
/** Raw claims from a decoded ID token; values are untyped until read here. */
export type IdTokenClaims = Record<string, unknown>;
-export type Role = 'admin' | 'user';
-
-export interface UserContext {
- userRef: string;
- role: Role;
-}
-
/**
* Normalizes a claim value into a string list to check membership against.
* OIDC doesn't fix the shape of claims like `groups`/`roles`: most IdPs
diff --git a/packages/server/src/auth/cookies.ts b/packages/server/src/auth/cookies.ts
index a7bf79373..ad06c016f 100644
--- a/packages/server/src/auth/cookies.ts
+++ b/packages/server/src/auth/cookies.ts
@@ -53,3 +53,7 @@ export function readOAuthStateCookie(params: { context: Context; logger: Logger
export function clearAuthCookie(params: { context: Context; name: string }): void {
deleteCookie(params.context, params.name, AUTH_COOKIE_ATTRIBUTES);
}
+
+export function readIdTokenCookie(params: { context: Context }): string | undefined {
+ return getCookie(params.context, ID_TOKEN_COOKIE);
+}
diff --git a/packages/server/src/auth/identity.ts b/packages/server/src/auth/identity.ts
new file mode 100644
index 000000000..d1bace889
--- /dev/null
+++ b/packages/server/src/auth/identity.ts
@@ -0,0 +1,32 @@
+import type { Context } from 'hono';
+
+export type Role = 'admin' | 'user';
+
+export interface UserContext {
+ userRef: string;
+ role: Role;
+}
+
+/**
+ * Fixed identity when no identity provider is configured (standalone / auth disabled).
+ * Stamped onto sessions as `created_by` and used for ownership checks.
+ */
+export const LOCAL_USER_CONTEXT: UserContext = {
+ userRef: 'trueforge-default',
+ role: 'admin',
+};
+
+/** Resolves the caller identity from the request context. Injected on session/turn routers. */
+export type ResolveUserContext = (c: Context) => UserContext;
+
+/**
+ * Caller {@link UserContext} for the current request.
+ * Requires auth middleware to have set `c.var.user`.
+ */
+export function resolveUserContext(c: Context): UserContext {
+ const uc = c.get('user_context');
+ if (uc === undefined) {
+ throw new Error('UserContext missing; auth middleware did not run');
+ }
+ return uc;
+}
diff --git a/packages/server/src/auth/middleware.ts b/packages/server/src/auth/middleware.ts
index a9bfaecac..10fbd4563 100644
--- a/packages/server/src/auth/middleware.ts
+++ b/packages/server/src/auth/middleware.ts
@@ -1,20 +1,14 @@
import type { Context, MiddlewareHandler } from 'hono';
-import { getCookie } from 'hono/cookie';
import { HTTPException } from 'hono/http-exception';
import { jwtVerify } from 'jose';
-import { toUserContext, type IdTokenClaims, type UserContext } from './claims';
-import { ID_TOKEN_COOKIE } from './cookies';
+import { toUserContext, type IdTokenClaims } from './claims';
+import { readIdTokenCookie } from './cookies';
+import { LOCAL_USER_CONTEXT, type UserContext } from './identity';
import { getOidcVerify } from './oidc';
-/** Used when OIDC is not configured (standalone / no IdP). */
-export const DEFAULT_USER_CONTEXT: UserContext = {
- userRef: 'default',
- role: 'user',
-};
-
declare module 'hono' {
interface ContextVariableMap {
- user?: UserContext;
+ user_context?: UserContext;
}
}
@@ -28,7 +22,7 @@ export async function resolveAuthUser(c: Context): Promise<UserContext | undefin
return undefined;
}
- const token = getCookie(c, ID_TOKEN_COOKIE);
+ const token = readIdTokenCookie({ context: c });
if (!token) {
return undefined;
}
@@ -47,10 +41,10 @@ export async function resolveAuthUser(c: Context): Promise<UserContext | undefin
return toUserContext(claims, oidcVerify.oidcConfig);
}
-/** Set `c.var.user` and continue, or throw 401. Without OIDC, sets {@link DEFAULT_USER_CONTEXT}. */
+/** Set `c.var.user` and continue, or throw 401. Without OIDC, sets {@link LOCAL_USER_CONTEXT}. */
export const authMiddleware: MiddlewareHandler = async (c, next) => {
if (!getOidcVerify()) {
- c.set('user', DEFAULT_USER_CONTEXT);
+ c.set('user_context', LOCAL_USER_CONTEXT);
return next();
}
@@ -59,7 +53,7 @@ export const authMiddleware: MiddlewareHandler = async (c, next) => {
if (!user) {
throw new HTTPException(401, { message: 'Authentication required' });
}
- c.set('user', user);
+ c.set('user_context', user);
} catch (error) {
if (error instanceof HTTPException) {
throw error;
diff --git a/packages/server/src/auth/oidc.ts b/packages/server/src/auth/oidc.ts
index c4b9db29e..0fc688ffe 100644
--- a/packages/server/src/auth/oidc.ts
+++ b/packages/server/src/auth/oidc.ts
@@ -26,6 +26,7 @@ export interface OidcVerify {
oidcConfig: OIDCConfig;
}
+/** Single instance of the OIDC verification. */
let oidcVerify: OidcVerify | null = null;
/** Enable cookie JWT verification using the IdP client + claim-mapping config from `initOidc`. */
diff --git a/packages/server/src/routes/sessionRoutes.ts b/packages/server/src/routes/sessionRoutes.ts
index 942bd4ceb..c5a463b91 100644
--- a/packages/server/src/routes/sessionRoutes.ts
+++ b/packages/server/src/routes/sessionRoutes.ts
@@ -63,7 +63,7 @@ export const getSessionRoute = createRoute({
path: '/{session_id}',
tags: [SESSIONS_TAG],
summary: 'Get a session',
- description: 'Fetch a session by ID.',
+ description: 'Fetch a session by ID. Only the session creator (`created_by`) may fetch it.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'get',
request: {
@@ -74,6 +74,10 @@ export const getSessionRoute = createRoute({
content: { 'application/json': { schema: GetSessionResponseSchema } },
description: 'Session data.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session not found.',
@@ -86,7 +90,8 @@ export const deleteSessionRoute = createRoute({
path: '/{session_id}',
tags: [SESSIONS_TAG],
summary: 'Delete a session',
- description: 'Delete a session and all related turns, events, and internal state. Idempotent if already gone.',
+ description:
+ 'Delete a session and all related turns, events, and internal state. Only the session creator (`created_by`) may delete it. Idempotent if already gone.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'delete',
request: {
@@ -96,6 +101,10 @@ export const deleteSessionRoute = createRoute({
204: {
description: 'Session and all related data deleted.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
},
});
@@ -105,7 +114,7 @@ export const updateSessionRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Update a session',
description:
- 'Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.',
+ 'Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`. Only the session creator (`created_by`) may update it.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'update',
request: {
@@ -124,6 +133,10 @@ export const updateSessionRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Invalid request body.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session not found.',
@@ -142,7 +155,7 @@ export const listSessionsRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'List sessions',
description:
- 'List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent; optional `created_by` filters by creator identity. Pass `page_token` to fetch the next page, keeping the other query params constant.',
+ "List the caller's sessions (newest first by default), token-paginated. Results are scoped to the authenticated identity via the session store's `created_by` filter (not a client query param). Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.",
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'list',
'x-fern-pagination': TOKEN_PAGINATION,
@@ -166,7 +179,7 @@ export const cancelSessionRoute = createRoute({
path: '/{session_id}/cancel',
tags: [SESSIONS_TAG],
summary: 'Cancel a running turn in a session',
- description: 'Cancel the running last turn for a session.',
+ description: 'Cancel the running last turn for a session. Only the session creator (`created_by`) may cancel.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'cancel',
request: {
@@ -181,6 +194,10 @@ export const cancelSessionRoute = createRoute({
content: { 'application/json': { schema: CancelSessionResponseSchema } },
description: 'Turn cancelled.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session not found.',
@@ -199,7 +216,7 @@ export const listSessionEventsRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'List session events',
description:
- 'List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor.',
+ 'List session events as `{ turn_id, event }` across the active turn branch (newest first), including persisted events from a running tip. Each turn contributes turn.created, content events (model.message, tool.call, …), and turn.done when terminal; streaming deltas are not included. Use `page_token` to paginate backward toward older events while retaining the original branch anchor. Only the session creator (`created_by`) may list events.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'list_events',
'x-fern-pagination': TOKEN_PAGINATION,
@@ -216,6 +233,10 @@ export const listSessionEventsRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Invalid page token.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session not found.',
diff --git a/packages/server/src/routes/turnRoutes.ts b/packages/server/src/routes/turnRoutes.ts
index 4e1e86402..7aa6013b6 100644
--- a/packages/server/src/routes/turnRoutes.ts
+++ b/packages/server/src/routes/turnRoutes.ts
@@ -30,7 +30,8 @@ export const listTurnsRoute = createRoute({
path: '/{session_id}/turns',
tags: [SESSIONS_TAG],
summary: 'List turns in a session',
- description: 'List turns for a session (newest first by default), token-paginated.',
+ description:
+ 'List turns for a session (newest first by default), token-paginated. Only the session creator (`created_by`) may list turns.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'list_turns',
'x-fern-pagination': TOKEN_PAGINATION,
@@ -47,6 +48,10 @@ export const listTurnsRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Invalid page token.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session not found.',
@@ -59,7 +64,7 @@ export const getTurnRoute = createRoute({
path: '/{session_id}/turns/{turn_id}',
tags: [SESSIONS_TAG],
summary: 'Get a turn',
- description: 'Fetch a single turn by ID.',
+ description: 'Fetch a single turn by ID. Only the session creator (`created_by`) may fetch it.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'get_turn',
request: {
@@ -70,6 +75,10 @@ export const getTurnRoute = createRoute({
content: { 'application/json': { schema: GetTurnResponseSchema } },
description: 'Turn data.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session or turn not found.',
@@ -83,7 +92,7 @@ export const downloadSandboxFileRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Download a file from the turn sandbox',
description:
- "Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block.",
+ "Download a file from the sandbox this turn ran in. Paths come from the assistant's `sandbox_artifacts` block. Only the session creator (`created_by`) may download.",
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'download_sandbox_file',
request: {
@@ -101,7 +110,7 @@ export const downloadSandboxFileRoute = createRoute({
},
403: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
- description: 'Sandbox belongs to another tenant.',
+ description: 'Caller is not the session creator, or sandbox belongs to another tenant.',
},
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
@@ -131,7 +140,8 @@ export const listTurnEventsRoute = createRoute({
path: '/{session_id}/turns/{turn_id}/events',
tags: [SESSIONS_TAG],
summary: 'List turn events',
- description: 'Paginated persisted events for a turn (insertion order by default).',
+ description:
+ 'Paginated persisted events for a turn (insertion order by default). Only the session creator (`created_by`) may list events.',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'list_turn_events',
'x-fern-pagination': TOKEN_PAGINATION,
@@ -148,6 +158,10 @@ export const listTurnEventsRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Invalid page token.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session or turn not found.',
@@ -161,6 +175,7 @@ export const createAndExecuteTurnRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Create and execute a turn in a session',
description: `Create a turn within a session and execute it.
+Only the session creator (\`created_by\`) may create turns.
When \`stream\` is true (default), respond with a Server-Sent Events stream of turn events.
When \`stream\` is false, return the turn immediately with \`state.status: "running"\` while execution continues in the background; use get turn or subscribe to observe completion.
Use \`previous_turn_id\` to chain to the session's last turn (defaults to \`auto\`); use \`none\` for a new root.`,
@@ -197,6 +212,10 @@ Use \`previous_turn_id\` to chain to the session's last turn (defaults to \`auto
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Invalid request body.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Session or prior turn not found.',
@@ -222,7 +241,7 @@ export const subscribeTurnRoute = createRoute({
tags: [SESSIONS_TAG],
summary: 'Subscribe to a running turn',
description:
- 'Subscribe to the live SSE stream for a turn. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).',
+ 'Subscribe to the live SSE stream for a turn. Only the session creator (`created_by`) may subscribe. Pass `after_sequence_number` to resume after a disconnect (exclusive — events after this sequence number are replayed).',
'x-fern-sdk-group-name': ['sessions'],
'x-fern-sdk-method-name': 'subscribe_to_turn',
'x-fern-streaming': { format: 'sse', resumable: true },
@@ -243,6 +262,10 @@ export const subscribeTurnRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Invalid request body.',
},
+ 403: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Caller is not the session creator.',
+ },
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'Turn not found.',
diff --git a/packages/server/src/schemas/session.ts b/packages/server/src/schemas/session.ts
index 5eb4721bb..9a543e2f9 100644
--- a/packages/server/src/schemas/session.ts
+++ b/packages/server/src/schemas/session.ts
@@ -43,7 +43,6 @@ export const ListSessionsRequestQuerySchema = z
'Inclusive upper bound on `created_at` (ISO-8601 / RFC 3339).',
),
agent_id: z.string().min(1).optional().describe('When set, only sessions bound to this agent id are returned.'),
- created_by: z.string().min(1).optional().describe('When set, only sessions created by this identity are returned.'),
})
.openapi('ListSessionsRequestQuery');
diff --git a/packages/server/tests/unit/apis/auth.test.ts b/packages/server/tests/unit/apis/auth.test.ts
index a8cbe6fce..babc71148 100644
--- a/packages/server/tests/unit/apis/auth.test.ts
+++ b/packages/server/tests/unit/apis/auth.test.ts
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
import type { Configuration } from 'openid-client';
import winston from 'winston';
import { createAuthRouter } from '../../../src/apis/auth';
+import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
import { disableOidcAuth, initOidc } from '../../../src/auth/oidc';
import configuration from '../../../src/config';
@@ -76,7 +77,11 @@ describe('auth router (no identity provider configured)', () => {
const res = await router.request('/me');
expect(res.status).toBe(200);
- expect(await res.json()).toEqual({ type: 'default', email: 'default', role: 'user' });
+ expect(await res.json()).toEqual({
+ type: 'default',
+ email: LOCAL_USER_CONTEXT.userRef,
+ role: LOCAL_USER_CONTEXT.role,
+ });
});
});
diff --git a/packages/server/tests/unit/apis/createTurnNonStreaming.test.ts b/packages/server/tests/unit/apis/createTurnNonStreaming.test.ts
deleted file mode 100644
index 32a746cf2..000000000
--- a/packages/server/tests/unit/apis/createTurnNonStreaming.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { OpenAPIHono } from '@hono/zod-openapi';
-import type { Sessions, TurnStreamingEvent } from '@truefoundry/utils-core/agent-session';
-import { AgentSpecSchema } from '@truefoundry/utils-core/agent-session';
-import { createLogger } from 'winston';
-import { TENANT_ID } from '../../../src/apis/sessions';
-import { createTurnsRouter, turnStreamId } from '../../../src/apis/turns';
-import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
-import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
-import { createSqliteDb } from '../../../src/db/sqlite/client';
-import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
-import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';
-import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';
-import { SqliteSessionStore } from '../../../src/db/sqlite/session-store/SqliteSessionStore';
-import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';
-import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';
-import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';
-import { EventSubscriptionRegistry } from '../../../src/runtime/event-subscription/index.js';
-
-describe('create turn non-streaming', () => {
- it('returns the running turn JSON after dual-writing turn.created so subscribe can attach', async () => {
- const logger = createLogger({ silent: true });
- const db = createSqliteDb(':memory:');
- await migrateSqliteToLatest(db);
- const modelProviderStore = new SqliteModelProviderStore(db);
- await modelProviderStore.upsertProvider({
- tenant_id: 'default',
- manifest: {
- // Caller-named, so `custom` is the only type it can be.
- type: 'custom',
- name: 'test-provider',
- base_url: 'https://llm.test.example.com/v1',
- auth: { api_key: 'sk-test' },
- models: [
- {
- model_id: 'test-model',
- name: 'test-model',
- properties: { context_length: 128000, max_output_tokens: 4096 },
- },
- ],
- },
- });
-
- let releaseRest: (() => void) | undefined;
- const restParked = new Promise<void>(resolve => {
- releaseRest = resolve;
- });
-
- const sessions = {
- get: () =>
- Promise.resolve({
- agent_spec: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } }),
- record: { last_turn_id: null },
- createTurn: () =>
- Promise.resolve({
- id: 'turn-non-stream',
- record: {
- turn_id: 'turn-non-stream',
- session_id: 's1',
- previous_turn_id: null,
- input: [],
- state: { status: 'running' },
- created_at: new Date('2026-01-01T00:00:00.000Z'),
- },
- stream: async function* stream() {
- yield {
- type: 'turn.created',
- id: 'evt_created',
- turn_id: 'turn-non-stream',
- previous_turn_id: null,
- state: { status: 'running' },
- created_at: '2026-01-01T00:00:00.000Z',
- thread_id: null,
- };
- await restParked;
- },
- }),
- }),
- } as unknown as Sessions;
-
- const eventSubscriptions = new EventSubscriptionRegistry<TurnStreamingEvent>(undefined);
- const app = new OpenAPIHono();
- app.route(
- '/',
- createTurnsRouter({
- sessions,
- sessionStore: new SqliteSessionStore(db),
- activeTurns: new ActiveTurnRegistry(),
- modelProviderStore,
- agentStore: new SqliteAgentStore(db),
- mcpServerStore: new SqliteMcpServerStore(db),
- tokenStore: new SqliteOAuthTokenStore(db),
- skillStore: new SqliteSkillStore(db),
- eventSubscriptions,
- sandboxProviderStore: new SqliteSandboxProviderStore(db),
- logger,
- }),
- );
-
- const response = await app.request('/s1/turns', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ stream: false }),
- });
-
- expect(response.status).toBe(200);
- expect(response.headers.get('content-type') ?? '').toContain('application/json');
- const body: unknown = await response.json();
- expect(body).toEqual({
- data: {
- id: 'turn-non-stream',
- session_id: 's1',
- previous_turn_id: null,
- input: [],
- state: { status: 'running' },
- created_at: '2026-01-01T00:00:00.000Z',
- },
- });
-
- // Resumable stream must exist before the JSON response returns.
- await expect(
- eventSubscriptions.get(turnStreamId(TENANT_ID, 's1', 'turn-non-stream')).assertSubscribable(),
- ).resolves.toBeUndefined();
-
- releaseRest?.();
- });
-});
diff --git a/packages/server/tests/unit/apis/deletedSessionCrud.test.ts b/packages/server/tests/unit/apis/deletedSessionCrud.test.ts
index b5a8d03a4..b64083fe5 100644
--- a/packages/server/tests/unit/apis/deletedSessionCrud.test.ts
+++ b/packages/server/tests/unit/apis/deletedSessionCrud.test.ts
@@ -5,6 +5,7 @@ import { createClient } from 'redis';
import { createLogger } from 'winston';
import { createSessionsRouter, TENANT_ID } from '../../../src/apis/sessions';
import { createTurnsRouter } from '../../../src/apis/turns';
+import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -46,6 +47,7 @@ describe('public CRUD after session deletion', () => {
sandboxProviderStore,
redis: createClient(),
requestReplyRouter: new RequestReplyRouter(),
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
}),
);
app.route(
@@ -62,13 +64,14 @@ describe('public CRUD after session deletion', () => {
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore,
logger: createLogger({ silent: true }),
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
}),
);
await sessionStore.createSession({
tenant_id: TENANT_ID,
session_id: 's1',
- created_by: 'user-1',
+ created_by: LOCAL_USER_CONTEXT.userRef,
agent: {
type: 'value',
agent_spec: AgentSpecSchema.parse({
diff --git a/packages/server/tests/unit/apis/sandboxFileDownload.test.ts b/packages/server/tests/unit/apis/sandboxFileDownload.test.ts
index d04d8dc35..f2edfcfd0 100644
--- a/packages/server/tests/unit/apis/sandboxFileDownload.test.ts
+++ b/packages/server/tests/unit/apis/sandboxFileDownload.test.ts
@@ -4,6 +4,7 @@ import { AgentSpecSchema, Sessions } from '@truefoundry/utils-core/agent-session
import { createLogger } from 'winston';
import { TENANT_ID } from '../../../src/apis/sessions';
import { createTurnsRouter, toContentDisposition } from '../../../src/apis/turns';
+import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -45,6 +46,7 @@ async function buildApp() {
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
}),
);
@@ -109,6 +111,7 @@ describe('GET /{session_id}/turns/{turn_id}/download', () => {
const session = await sessions.create({
tenant_id: TENANT_ID,
session_id: 'no-turn',
+ created_by: LOCAL_USER_CONTEXT.userRef,
agent: { type: 'value', agent_spec: agentSpec() },
});
diff --git a/packages/server/tests/unit/apis/sessionHttp.test.ts b/packages/server/tests/unit/apis/sessionHttp.test.ts
index 29bfa3119..8daba410b 100644
--- a/packages/server/tests/unit/apis/sessionHttp.test.ts
+++ b/packages/server/tests/unit/apis/sessionHttp.test.ts
@@ -3,6 +3,7 @@ import { AgentSpecSchema, Sessions } from '@truefoundry/utils-core/agent-session
import { RequestReplyRouter } from '@truefoundry/utils-core/request-reply';
import { createClient } from 'redis';
import { createSessionsRouter, TENANT_ID } from '../../../src/apis/sessions';
+import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -29,11 +30,12 @@ function jsonInit(method: string, body: unknown): RequestInit {
describe('sessions HTTP agent binding', () => {
let app: OpenAPIHono;
let agentStore: SqliteAgentStore;
+ let sessionStore: SqliteSessionStore;
beforeEach(async () => {
const db = createSqliteDb(':memory:');
await migrateSqliteToLatest(db);
- const sessionStore = new SqliteSessionStore(db);
+ sessionStore = new SqliteSessionStore(db);
const sessions = new Sessions({ sessionStore });
const modelProviderStore = new SqliteModelProviderStore(db);
const mcpServerStore = new SqliteMcpServerStore(db);
@@ -72,6 +74,7 @@ describe('sessions HTTP agent binding', () => {
sandboxProviderStore,
redis: createClient(),
requestReplyRouter: new RequestReplyRouter(),
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
}),
);
});
@@ -88,7 +91,7 @@ describe('sessions HTTP agent binding', () => {
};
expect(json.data.agent.type).toBe('value');
expect(json.data.agent.agent_spec?.instructions).toBe('draft');
- expect(json.data.created_by).toBe('trueforge-default');
+ expect(json.data.created_by).toBe(LOCAL_USER_CONTEXT.userRef);
});
it('returns 404 when creating a session for an unknown agent_id', async () => {
@@ -122,22 +125,50 @@ describe('sessions HTTP agent binding', () => {
expect(listJson.data.some(row => row.id === json.data.id)).toBe(true);
});
- it('filters list by created_by', async () => {
+ it("rejects access to another user's session on get/update/delete/cancel/events and scopes list", async () => {
+ await sessionStore.createSession({
+ tenant_id: TENANT_ID,
+ session_id: 'other-user-session',
+ created_by: 'someone-else',
+ agent: { type: 'value', agent_spec: draftSpec },
+ custom: null,
+ });
+
const created = await app.request('/', jsonInit('POST', { agent: { type: 'value', agent_spec: draftSpec } }));
expect(created.status).toBe(201);
const json = (await created.json()) as { data: { id: string; created_by: string } };
- expect(json.data.created_by).toBe('trueforge-default');
-
- const matched = await app.request('/?created_by=trueforge-default');
- expect(matched.status).toBe(200);
- const matchedJson = (await matched.json()) as { data: Array<{ id: string; created_by: string }> };
- expect(matchedJson.data.some(row => row.id === json.data.id)).toBe(true);
- expect(matchedJson.data.every(row => row.created_by === 'trueforge-default')).toBe(true);
-
- const unmatched = await app.request('/?created_by=someone-else');
- expect(unmatched.status).toBe(200);
- const unmatchedJson = (await unmatched.json()) as { data: Array<{ id: string }> };
- expect(unmatchedJson.data.some(row => row.id === json.data.id)).toBe(false);
+ expect(json.data.created_by).toBe(LOCAL_USER_CONTEXT.userRef);
+
+ const listed = await app.request('/');
+ expect(listed.status).toBe(200);
+ const listedJson = (await listed.json()) as { data: Array<{ id: string; created_by: string }> };
+ expect(listedJson.data.map(row => row.id)).toEqual([json.data.id]);
+ expect(listedJson.data.every(row => row.created_by === LOCAL_USER_CONTEXT.userRef)).toBe(true);
+
+ const forbiddenBody = { error: { message: 'Only the session creator can access this session' } };
+
+ const getForbidden = await app.request('/other-user-session');
+ expect(getForbidden.status).toBe(403);
+ expect(await getForbidden.json()).toEqual(forbiddenBody);
+
+ const patchForbidden = await app.request('/other-user-session', jsonInit('PATCH', {}));
+ expect(patchForbidden.status).toBe(403);
+ expect(await patchForbidden.json()).toEqual(forbiddenBody);
+
+ const deleteForbidden = await app.request('/other-user-session', { method: 'DELETE' });
+ expect(deleteForbidden.status).toBe(403);
+ expect(await deleteForbidden.json()).toEqual(forbiddenBody);
+
+ const cancelForbidden = await app.request('/other-user-session/cancel', { method: 'POST' });
+ expect(cancelForbidden.status).toBe(403);
+ expect(await cancelForbidden.json()).toEqual(forbiddenBody);
+
+ const eventsForbidden = await app.request('/other-user-session/events');
+ expect(eventsForbidden.status).toBe(403);
+ expect(await eventsForbidden.json()).toEqual(forbiddenBody);
+
+ const allowed = await app.request(`/${json.data.id}`);
+ expect(allowed.status).toBe(200);
});
it('rejects PATCH agent on a session bound by agent_id', async () => {
diff --git a/packages/server/tests/unit/apis/turnHarnessErrorStatus.test.ts b/packages/server/tests/unit/apis/turnHarnessErrorStatus.test.ts
index ac2d31014..e2f62ca37 100644
--- a/packages/server/tests/unit/apis/turnHarnessErrorStatus.test.ts
+++ b/packages/server/tests/unit/apis/turnHarnessErrorStatus.test.ts
@@ -3,6 +3,7 @@ import type { Sessions } from '@truefoundry/utils-core/agent-session';
import { AgentHarnessError } from '@truefoundry/utils-core/core';
import { createLogger } from 'winston';
import { createTurnsRouter } from '../../../src/apis/turns';
+import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -40,7 +41,7 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response
get: () =>
Promise.resolve({
agent_spec: { model: { name: 'test-provider/test-model' } },
- record: { last_turn_id: null },
+ record: { last_turn_id: null, created_by: LOCAL_USER_CONTEXT.userRef },
createTurn: () => Promise.reject(error),
}),
} as unknown as Sessions;
@@ -61,6 +62,7 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response
eventSubscriptions: new EventSubscriptionRegistry(undefined),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
logger: createLogger({ silent: true }),
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
}),
);
diff --git a/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts b/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts
deleted file mode 100644
index 3761e4bdd..000000000
--- a/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { OpenAPIHono } from '@hono/zod-openapi';
-import type { Sessions } from '@truefoundry/utils-core/agent-session';
-import { AgentSpecSchema, TurnNotFoundError } from '@truefoundry/utils-core/agent-session';
-import { createLogger } from 'winston';
-import { createTurnsRouter } from '../../../src/apis/turns';
-import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
-import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
-import { createSqliteDb } from '../../../src/db/sqlite/client';
-import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
-import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';
-import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';
-import { SqliteSessionStore } from '../../../src/db/sqlite/session-store/SqliteSessionStore';
-import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';
-import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';
-import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';
-import { EventSubscriptionRegistry } from '../../../src/runtime/event-subscription/index.js';
-
-describe('turn SSE after session deletion', () => {
- it('warns when the stream ends because the session/turn was removed', async () => {
- const warnings: unknown[] = [];
- const logger = createLogger({ silent: true });
- logger.warn = ((message: unknown) => {
- warnings.push(message);
- return logger;
- }) as typeof logger.warn;
-
- const db = createSqliteDb(':memory:');
- await migrateSqliteToLatest(db);
- const modelProviderStore = new SqliteModelProviderStore(db);
- await modelProviderStore.upsertProvider({
- tenant_id: 'default',
- manifest: {
- // Caller-named, so `custom` is the only type it can be.
- type: 'custom',
- name: 'test-provider',
- base_url: 'https://llm.test.example.com/v1',
- auth: { api_key: 'sk-test' },
- models: [
- {
- model_id: 'test-model',
- name: 'test-model',
- properties: { context_length: 128000, max_output_tokens: 4096 },
- },
- ],
- },
- });
-
- const agentSpec = AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } });
- const sessions = {
- get: () =>
- Promise.resolve({
- agent_spec: agentSpec,
- record: {
- session_id: 's1',
- last_turn_id: null,
- agent: { type: 'value', agent_spec: agentSpec },
- },
- createTurn: () =>
- Promise.resolve({
- id: 'turn-gone',
- stream: async function* stream() {
- throw new TurnNotFoundError('turn-gone');
- },
- }),
- }),
- } as unknown as Sessions;
-
- const app = new OpenAPIHono();
- app.route(
- '/',
- createTurnsRouter({
- sessions,
- sessionStore: new SqliteSessionStore(db),
- activeTurns: new ActiveTurnRegistry(),
- modelProviderStore,
- mcpServerStore: new SqliteMcpServerStore(db),
- tokenStore: new SqliteOAuthTokenStore(db),
- skillStore: new SqliteSkillStore(db),
- agentStore: new SqliteAgentStore(db),
- eventSubscriptions: new EventSubscriptionRegistry(undefined),
- sandboxProviderStore: new SqliteSandboxProviderStore(db),
- logger,
- }),
- );
-
- const response = await app.request('/s1/turns', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: '{}',
- });
- expect(response.status).toBe(200);
- await response.text();
-
- expect(
- warnings.some(
- message => typeof message === 'string' && message.includes('Turn stream ended after session/turn was removed'),
- ),
- ).toBe(true);
- });
-});
diff --git a/packages/server/tests/unit/apis/turns.test.ts b/packages/server/tests/unit/apis/turns.test.ts
new file mode 100644
index 000000000..d1374aefb
--- /dev/null
+++ b/packages/server/tests/unit/apis/turns.test.ts
@@ -0,0 +1,297 @@
+import { OpenAPIHono } from '@hono/zod-openapi';
+import {
+ AgentSpecSchema,
+ Sessions,
+ TurnNotFoundError,
+ type TurnStreamingEvent,
+} from '@truefoundry/utils-core/agent-session';
+import { createLogger } from 'winston';
+import { TENANT_ID } from '../../../src/apis/sessions';
+import { createTurnsRouter, turnStreamId } from '../../../src/apis/turns';
+import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
+import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';
+import { createSqliteDb } from '../../../src/db/sqlite/client';
+import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
+import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';
+import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';
+import { SqliteSessionStore } from '../../../src/db/sqlite/session-store/SqliteSessionStore';
+import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';
+import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';
+import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';
+import { EventSubscriptionRegistry } from '../../../src/runtime/event-subscription/index.js';
+
+describe('turns', () => {
+ describe('turn ownership', () => {
+ it('returns 403 for all turn routes when the caller is not the session creator', async () => {
+ const db = createSqliteDb(':memory:');
+ await migrateSqliteToLatest(db);
+ const sessionStore = new SqliteSessionStore(db);
+ const sessions = new Sessions({ sessionStore });
+
+ await sessionStore.createSession({
+ tenant_id: TENANT_ID,
+ session_id: 's1',
+ created_by: 'someone-else',
+ agent: {
+ type: 'value',
+ agent_spec: AgentSpecSchema.parse({
+ model: { name: 'test-provider/test-model' },
+ instructions: 'test',
+ }),
+ },
+ custom: null,
+ });
+
+ const app = new OpenAPIHono();
+ app.route(
+ '/',
+ createTurnsRouter({
+ sessions,
+ sessionStore,
+ activeTurns: new ActiveTurnRegistry(),
+ modelProviderStore: new SqliteModelProviderStore(db),
+ mcpServerStore: new SqliteMcpServerStore(db),
+ tokenStore: new SqliteOAuthTokenStore(db),
+ skillStore: new SqliteSkillStore(db),
+ agentStore: new SqliteAgentStore(db),
+ eventSubscriptions: new EventSubscriptionRegistry(undefined),
+ sandboxProviderStore: new SqliteSandboxProviderStore(db),
+ logger: createLogger({ silent: true }),
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
+ }),
+ );
+
+ const forbiddenAccess = { error: { message: 'Only the session creator can access this session' } };
+
+ const createResponse = await app.request('/s1/turns', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ stream: false }),
+ });
+ expect(createResponse.status).toBe(403);
+ expect(await createResponse.json()).toEqual({
+ error: { message: 'Only the session creator can create turns' },
+ });
+
+ const listResponse = await app.request('/s1/turns');
+ expect(listResponse.status).toBe(403);
+ expect(await listResponse.json()).toEqual(forbiddenAccess);
+
+ const getResponse = await app.request('/s1/turns/any-turn');
+ expect(getResponse.status).toBe(403);
+ expect(await getResponse.json()).toEqual(forbiddenAccess);
+
+ const eventsResponse = await app.request('/s1/turns/any-turn/events');
+ expect(eventsResponse.status).toBe(403);
+ expect(await eventsResponse.json()).toEqual(forbiddenAccess);
+
+ const subscribeResponse = await app.request('/s1/turns/any-turn/subscribe');
+ expect(subscribeResponse.status).toBe(403);
+ expect(await subscribeResponse.json()).toEqual(forbiddenAccess);
+
+ const downloadResponse = await app.request(
+ `/s1/turns/any-turn/download?path=${encodeURIComponent('/workspace/report.pdf')}`,
+ );
+ expect(downloadResponse.status).toBe(403);
+ expect(await downloadResponse.json()).toEqual(forbiddenAccess);
+ });
+ });
+
+ describe('create turn non-streaming', () => {
+ it('returns the running turn JSON after dual-writing turn.created so subscribe can attach', async () => {
+ const logger = createLogger({ silent: true });
+ const db = createSqliteDb(':memory:');
+ await migrateSqliteToLatest(db);
+ const modelProviderStore = new SqliteModelProviderStore(db);
+ await modelProviderStore.upsertProvider({
+ tenant_id: 'default',
+ manifest: {
+ // Caller-named, so `custom` is the only type it can be.
+ type: 'custom',
+ name: 'test-provider',
+ base_url: 'https://llm.test.example.com/v1',
+ auth: { api_key: 'sk-test' },
+ models: [
+ {
+ model_id: 'test-model',
+ name: 'test-model',
+ properties: { context_length: 128000, max_output_tokens: 4096 },
+ },
+ ],
+ },
+ });
+
+ let releaseRest: (() => void) | undefined;
+ const restParked = new Promise<void>(resolve => {
+ releaseRest = resolve;
+ });
+
+ const sessions = {
+ get: () =>
+ Promise.resolve({
+ agent_spec: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } }),
+ record: { last_turn_id: null, created_by: LOCAL_USER_CONTEXT.userRef },
+ createTurn: () =>
+ Promise.resolve({
+ id: 'turn-non-stream',
+ record: {
+ turn_id: 'turn-non-stream',
+ session_id: 's1',
+ previous_turn_id: null,
+ input: [],
+ state: { status: 'running' },
+ created_at: new Date('2026-01-01T00:00:00.000Z'),
+ },
+ stream: async function* stream() {
+ yield {
+ type: 'turn.created',
+ id: 'evt_created',
+ turn_id: 'turn-non-stream',
+ previous_turn_id: null,
+ state: { status: 'running' },
+ created_at: '2026-01-01T00:00:00.000Z',
+ thread_id: null,
+ };
+ await restParked;
+ },
+ }),
+ }),
+ } as unknown as Sessions;
+
+ const eventSubscriptions = new EventSubscriptionRegistry<TurnStreamingEvent>(undefined);
+ const app = new OpenAPIHono();
+ app.route(
+ '/',
+ createTurnsRouter({
+ sessions,
+ sessionStore: new SqliteSessionStore(db),
+ activeTurns: new ActiveTurnRegistry(),
+ modelProviderStore,
+ agentStore: new SqliteAgentStore(db),
+ mcpServerStore: new SqliteMcpServerStore(db),
+ tokenStore: new SqliteOAuthTokenStore(db),
+ skillStore: new SqliteSkillStore(db),
+ eventSubscriptions,
+ sandboxProviderStore: new SqliteSandboxProviderStore(db),
+ logger,
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
+ }),
+ );
+
+ const response = await app.request('/s1/turns', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ stream: false }),
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get('content-type') ?? '').toContain('application/json');
+ const body: unknown = await response.json();
+ expect(body).toEqual({
+ data: {
+ id: 'turn-non-stream',
+ session_id: 's1',
+ previous_turn_id: null,
+ input: [],
+ state: { status: 'running' },
+ created_at: '2026-01-01T00:00:00.000Z',
+ },
+ });
+
+ // Resumable stream must exist before the JSON response returns.
+ await expect(
+ eventSubscriptions.get(turnStreamId(TENANT_ID, 's1', 'turn-non-stream')).assertSubscribable(),
+ ).resolves.toBeUndefined();
+
+ releaseRest?.();
+ });
+ });
+
+ describe('turn SSE after session deletion', () => {
+ it('warns when the stream ends because the session/turn was removed', async () => {
+ const warnings: unknown[] = [];
+ const logger = createLogger({ silent: true });
+ logger.warn = ((message: unknown) => {
+ warnings.push(message);
+ return logger;
+ }) as typeof logger.warn;
+
+ const db = createSqliteDb(':memory:');
+ await migrateSqliteToLatest(db);
+ const modelProviderStore = new SqliteModelProviderStore(db);
+ await modelProviderStore.upsertProvider({
+ tenant_id: 'default',
+ manifest: {
+ // Caller-named, so `custom` is the only type it can be.
+ type: 'custom',
+ name: 'test-provider',
+ base_url: 'https://llm.test.example.com/v1',
+ auth: { api_key: 'sk-test' },
+ models: [
+ {
+ model_id: 'test-model',
+ name: 'test-model',
+ properties: { context_length: 128000, max_output_tokens: 4096 },
+ },
+ ],
+ },
+ });
+
+ const agentSpec = AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } });
+ const sessions = {
+ get: () =>
+ Promise.resolve({
+ agent_spec: agentSpec,
+ record: {
+ session_id: 's1',
+ last_turn_id: null,
+ created_by: LOCAL_USER_CONTEXT.userRef,
+ agent: { type: 'value', agent_spec: agentSpec },
+ },
+ createTurn: () =>
+ Promise.resolve({
+ id: 'turn-gone',
+ stream: async function* stream() {
+ throw new TurnNotFoundError('turn-gone');
+ },
+ }),
+ }),
+ } as unknown as Sessions;
+
+ const app = new OpenAPIHono();
+ app.route(
+ '/',
+ createTurnsRouter({
+ sessions,
+ sessionStore: new SqliteSessionStore(db),
+ activeTurns: new ActiveTurnRegistry(),
+ modelProviderStore,
+ mcpServerStore: new SqliteMcpServerStore(db),
+ tokenStore: new SqliteOAuthTokenStore(db),
+ skillStore: new SqliteSkillStore(db),
+ agentStore: new SqliteAgentStore(db),
+ eventSubscriptions: new EventSubscriptionRegistry(undefined),
+ sandboxProviderStore: new SqliteSandboxProviderStore(db),
+ logger,
+ resolveUserContext: () => LOCAL_USER_CONTEXT,
+ }),
+ );
+
+ const response = await app.request('/s1/turns', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: '{}',
+ });
+ expect(response.status).toBe(200);
+ await response.text();
+
+ expect(
+ warnings.some(
+ message =>
+ typeof message === 'string' && message.includes('Turn stream ended after session/turn was removed'),
+ ),
+ ).toBe(true);
+ });
+ });
+});
diff --git a/packages/server/tests/unit/auth/identity.test.ts b/packages/server/tests/unit/auth/identity.test.ts
new file mode 100644
index 000000000..2f6422bc3
--- /dev/null
+++ b/packages/server/tests/unit/auth/identity.test.ts
@@ -0,0 +1,18 @@
+import type { Context } from 'hono';
+import { LOCAL_USER_CONTEXT, resolveUserContext } from '../../../src/auth/identity';
+
+describe('resolveUserContext', () => {
+ it('returns the user set on the request context', () => {
+ const c = {
+ get: (key: string) => (key === 'user_context' ? LOCAL_USER_CONTEXT : undefined),
+ } as unknown as Context;
+ expect(resolveUserContext(c)).toEqual(LOCAL_USER_CONTEXT);
+ });
+
+ it('throws when auth middleware did not set user', () => {
+ const c = {
+ get: () => undefined,
+ } as unknown as Context;
+ expect(() => resolveUserContext(c)).toThrow('UserContext missing; auth middleware did not run');
+ });
+});
diff --git a/packages/server/tests/unit/auth/middleware.test.ts b/packages/server/tests/unit/auth/middleware.test.ts
index 0a3a3917f..61abb57f3 100644
--- a/packages/server/tests/unit/auth/middleware.test.ts
+++ b/packages/server/tests/unit/auth/middleware.test.ts
@@ -43,7 +43,7 @@ function createApp() {
const models = new OpenAPIHono();
models.use('*', authMiddleware);
- models.get('/', c => c.json({ ok: true, user: c.get('user') }));
+ models.get('/', c => c.json({ ok: true, user: c.get('user_context') }));
app.route('/api/v1/models', models);
return app;
@@ -56,7 +56,7 @@ describe('authMiddleware', () => {
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
ok: true,
- user: { userRef: 'default', role: 'user' },
+ user: { userRef: 'trueforge-default', role: 'admin' },
});
});