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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FORK.md

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion apps/server/src/j5/a2a/Migrations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", ()
{ migration_id: 42, name: "EveryoneHereAsks" },
{ migration_id: 43, name: "TaskSchedulers" },
{ migration_id: 44, name: "QueuedMessageEdits" },
{ migration_id: 45, name: "McpClientApprovers" },
]);
assert.deepStrictEqual(
migrationEntries.map(([id, name]) => [id, name]),
Expand Down Expand Up @@ -146,6 +147,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", ()
[42, "EveryoneHereAsks"],
[43, "TaskSchedulers"],
[44, "QueuedMessageEdits"],
[45, "McpClientApprovers"],
],
);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
Expand Down Expand Up @@ -1394,7 +1396,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () =>
applied.map((row) => row.migration_id),
[
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
],
);
const memberColumns = yield* sql<{ readonly name: string }>`
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/j5/a2a/Migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import Migration0041 from "./migrations/041_SharedConversation.ts";
import Migration0042 from "./migrations/042_EveryoneHereAsks.ts";
import Migration0043 from "./migrations/043_TaskSchedulers.ts";
import Migration0044 from "./migrations/044_QueuedMessageEdits.ts";
import Migration0045 from "./migrations/045_McpClientApprovers.ts";

export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations";

Expand Down Expand Up @@ -100,6 +101,7 @@ export const migrationEntries = [
[42, "EveryoneHereAsks", Migration0042],
[43, "TaskSchedulers", Migration0043],
[44, "QueuedMessageEdits", Migration0044],
[45, "McpClientApprovers", Migration0045],
] as const;

const makeMigrationLoader = (throughId?: number) =>
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/j5/a2a/migrations/045_McpClientApprovers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";

// Who approved an MCP client (People and access, D33): the person whose device or pairing code
// approved it, against the session upstream issued it. Lowering or removing that person as an
// Owner ends the sessions recorded for them. Keyed by upstream's session id, as
// `j5_a2a_person_session` is, rather than a column on upstream's `auth_sessions`. A client
// approved before this, or by a code that names no one, has no row and is ended by hand.
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;

yield* sql`
CREATE TABLE j5_a2a_mcp_client_approver (
session_id TEXT PRIMARY KEY,
person_id TEXT NOT NULL,
expires_at TEXT NOT NULL
)
`;
yield* sql`
CREATE INDEX j5_a2a_mcp_client_approver_person
ON j5_a2a_mcp_client_approver (person_id)
`;
});
60 changes: 56 additions & 4 deletions apps/server/src/j5/sharing/Access.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,10 +260,14 @@ it.layer(accessLayer)("Access", (it) => {
subject: "mcp-client",
scopes: [AuthOrchestrationReadScope],
});
yield* access.issueMcpClient(yield* access.ownersGeneration, issueAgent);
const approvedNow = Effect.map(access.ownersGeneration, (generation) => ({
generation,
approver: owner.personId,
}));
yield* access.issueMcpClient(yield* approvedNow, issueAgent);

// Approved, then the Owner is lowered, then the approval is exchanged: refused.
const approved = yield* access.ownersGeneration;
const approved = yield* approvedNow;
yield* access.setLevel({
personId: owner.personId,
scope: { kind: "server" },
Expand All @@ -272,18 +276,66 @@ it.layer(accessLayer)("Access", (it) => {
const stale = yield* access.issueMcpClient(approved, issueAgent).pipe(Effect.flip);
assert.strictEqual(stale._tag, "StaleMcpApprovalError");
// One approved after the change issues, however soon.
yield* access.issueMcpClient(yield* access.ownersGeneration, issueAgent);
yield* access.issueMcpClient(yield* approvedNow, issueAgent);

const other = yield* person("Owner who leaves", [
{ scope: { kind: "server" }, level: "owner" },
]);
const beforeRemoval = yield* access.ownersGeneration;
const beforeRemoval = { generation: yield* access.ownersGeneration, approver: null };
yield* access.removePerson(other.personId);
const removed = yield* access.issueMcpClient(beforeRemoval, issueAgent).pipe(Effect.flip);
assert.strictEqual(removed._tag, "StaleMcpApprovalError");
}),
);

it.effect("ends the MCP clients a lowered or removed Owner approved, and no one else's", () =>
Effect.gen(function* () {
const access = yield* Access;
const sessions = yield* SessionStore.SessionStore;
const owner = (name: string) => person(name, [{ scope: { kind: "server" }, level: "owner" }]);
const approve = (approver: PersonAccess.Person | null) =>
Effect.gen(function* () {
const issued = yield* access.issueMcpClient(
{ generation: yield* access.ownersGeneration, approver: approver?.personId ?? null },
sessions.issue({ subject: "mcp-client", scopes: [AuthOrchestrationReadScope] }),
);
return issued.sessionId;
});
const lowered = yield* owner("Owner who is lowered");
const staying = yield* owner("Owner who stays");
const removed = yield* owner("Owner who is removed");
const loweredClient = yield* approve(lowered);
const stayingClient = yield* approve(staying);
const removedClient = yield* approve(removed);
// Approved before approvers were recorded, or by a code that names no one.
const unrecordedClient = yield* approve(null);
const waiting = { generation: yield* access.ownersGeneration, approver: staying.personId };

yield* access.setLevel({
personId: lowered.personId,
scope: { kind: "server" },
level: "collaborator",
});
assert.isFalse(yield* isLive(loweredClient));
assert.isTrue(yield* isLive(stayingClient));
assert.isTrue(yield* isLive(removedClient));
assert.isTrue(yield* isLive(unrecordedClient));
// Still waiting when the Owners changed: refused, whoever approved it.
const stale = yield* access
.issueMcpClient(
waiting,
sessions.issue({ subject: "mcp-client", scopes: [AuthOrchestrationReadScope] }),
)
.pipe(Effect.flip);
assert.strictEqual(stale._tag, "StaleMcpApprovalError");

yield* access.removePerson(removed.personId);
assert.isFalse(yield* isLive(removedClient));
assert.isTrue(yield* isLive(stayingClient));
assert.isTrue(yield* isLive(unrecordedClient));
}),
);

it.effect("renews at startup every device whose permissions its level does not give", () =>
Effect.gen(function* () {
const access = yield* Access;
Expand Down
83 changes: 71 additions & 12 deletions apps/server/src/j5/sharing/Access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ export class StaleMcpApprovalError extends Schema.TaggedError<StaleMcpApprovalEr
}
}

/**
* What an MCP client's approval was checked against, given to the exchange of its code: which
* change of the server's Owners it was, and the person whose device or pairing code approved it,
* or `null` when that names no one (the first owner's startup link, or a device no one claimed).
*/
export interface McpClientApproval {
readonly generation: number;
readonly approver: ParticipantId | null;
}

/** What changed for a person, told after it commits. */
export interface AccessChange {
readonly personId: ParticipantId;
Expand Down Expand Up @@ -149,12 +159,17 @@ export interface AccessShape {
*/
readonly ownersGeneration: Effect.Effect<number, PersonAccessStorageError>;
/**
* Issues an MCP client's session approved at `generation`, unless an Owner was lowered or
* removed since: the approval may have been an Owner's who is not one now, and is refused to be
* approved again. Held under the same lock as a change of level, so the two never cross.
* Issues an MCP client's session, unless an Owner was lowered or removed since its approval was
* checked: the approval may have been an Owner's who is not one now, and is refused to be
* approved again. The session is recorded as its approver's, so lowering or removing them as an
* Owner ends it. Held under the same lock as a change of level, so the two never cross.
*/
readonly issueMcpClient: <A, E, R>(
generation: number,
readonly issueMcpClient: <
A extends { readonly token: string; readonly expiresAt: DateTime.DateTime },
E,
R,
>(
approval: McpClientApproval,
issue: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | StaleMcpApprovalError | PersonAccessStorageError, R>;
}
Expand Down Expand Up @@ -289,12 +304,50 @@ const make = Effect.gen(function* () {

const ownersGeneration = yield* Ref.make(0);
/**
* Every MCP approval not yet issued, voided: it may have been an Owner's who is not one now.
* MCP clients already issued keep their sessions; ending only those the lowered Owner approved
* is Later.
* Every MCP approval not yet issued, voided, whoever gave it: it may have been an Owner's who
* is not one now, and the Owners who remain approve it again.
*/
const voidWaitingMcpApprovals = Ref.update(ownersGeneration, (generation) => generation + 1);

const mcpStorage = (operation: string) => (cause: unknown) =>
new PersonAccessStorageError({ operation, cause });

/** Records an issued MCP client's session as `personId`'s, and forgets those since expired. */
const recordMcpApprover = Effect.fn("j5.sharing.access.recordMcpApprover")(function* (
personId: ParticipantId,
issued: { readonly token: string; readonly expiresAt: DateTime.DateTime },
) {
const { sessionId } = yield* sessions
.verify(issued.token)
.pipe(Effect.mapError(mcpStorage("read the MCP client's session")));
const now = DateTime.formatIso(yield* DateTime.now);
yield* sql`
DELETE FROM j5_a2a_mcp_client_approver WHERE expires_at <= ${now}
`.pipe(Effect.mapError(mcpStorage("forget expired MCP clients")));
yield* sql`
INSERT INTO j5_a2a_mcp_client_approver (session_id, person_id, expires_at)
VALUES (${sessionId}, ${personId}, ${DateTime.formatIso(issued.expiresAt)})
`.pipe(Effect.mapError(mcpStorage("record who approved an MCP client")));
});

/**
* Ends the MCP clients `personId` approved, in the transaction that lowers or removes them. A
* session already ended or expired is passed over.
*/
const endApprovedMcpClients = Effect.fn("j5.sharing.access.endApprovedMcpClients")(function* (
personId: ParticipantId,
) {
const approved = yield* sql<{ readonly session_id: AuthSessionId }>`
DELETE FROM j5_a2a_mcp_client_approver WHERE person_id = ${personId}
RETURNING session_id
`.pipe(Effect.mapError(mcpStorage("read the MCP clients a person approved")));
for (const { session_id: sessionId } of approved) {
yield* sessions
.revoke(sessionId)
.pipe(Effect.mapError(mcpStorage("end an MCP client a person approved")));
}
});

/**
* Runs a change to one person and renews whichever of their devices it requires, all in one
* transaction; then tells subscribers.
Expand All @@ -315,7 +368,10 @@ const make = Effect.gen(function* () {
yield* revokeForRenewal(device.sessionId);
}
}
if (before.owner && !after.owner) yield* voidWaitingMcpApprovals;
if (before.owner && !after.owner) {
yield* voidWaitingMcpApprovals;
yield* endApprovedMcpClients(personId);
}
return result;
}),
).pipe(Effect.tap(() => tell({ personId, kind: "reach" })));
Expand Down Expand Up @@ -381,6 +437,7 @@ const make = Effect.gen(function* () {
}
yield* afterChange(personId);
if (owner) yield* voidWaitingMcpApprovals;
yield* endApprovedMcpClients(personId);
}),
);
yield* tell({ personId, kind: "removed" });
Expand Down Expand Up @@ -446,13 +503,15 @@ const make = Effect.gen(function* () {

ownersGeneration: committed(Ref.get(ownersGeneration)),

issueMcpClient: (generation, issue) =>
issueMcpClient: (approval, issue) =>
committed(
Effect.gen(function* () {
if ((yield* Ref.get(ownersGeneration)) !== generation) {
if ((yield* Ref.get(ownersGeneration)) !== approval.generation) {
return yield* new StaleMcpApprovalError({});
}
return yield* issue;
const issued = yield* issue;
if (approval.approver !== null) yield* recordMcpApprover(approval.approver, issued);
return issued;
}),
),
});
Expand Down
48 changes: 32 additions & 16 deletions apps/server/src/j5/sharing/AccessGate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import type * as SqlClient from "effect/sql/SqlClient";
import * as SqlClient from "effect/sql/SqlClient";
import * as SqlError from "effect/sql/SqlError";
import type * as RpcGroup from "effect/rpc/RpcGroup";
import type * as HttpServerRequest from "effect/http/HttpServerRequest";

Expand All @@ -51,7 +52,7 @@ import {
peopleLayer as peopleRecordsLayer,
} from "./PairingIntents.ts";
import { layer as linksLayer } from "./Links.ts";
import { McpApprovalGeneration } from "./McpApproval.ts";
import { McpExchangeApproval } from "./McpApproval.ts";
import { nameDevOwnerAtStartup } from "./devOwnerName.ts";
import { layer as peopleLayer } from "./People.ts";
import {
Expand Down Expand Up @@ -138,6 +139,8 @@ type AccessRpcRule = (
}
) & { readonly unknownToo?: true };

const isSqlError = Schema.is(SqlError.SqlError);

const field = (value: unknown, name: string): unknown =>
typeof value === "object" && value !== null && name in value
? (value as Record<string, unknown>)[name]
Expand Down Expand Up @@ -457,6 +460,7 @@ export const layerGatedEnvironmentAuth = Layer.effect(
const access = yield* PersonAccess;
const intents = yield* PairingIntents;
const changes = yield* Access;
const sql = yield* SqlClient.SqlClient;
// Upstream's own session store, to read whose browser is asking. A test that stands in for
// upstream's auth has none, and then no browser is taken for anyone's.
const sessions = yield* Effect.serviceOption(SessionStore.SessionStore);
Expand Down Expand Up @@ -502,20 +506,31 @@ export const layerGatedEnvironmentAuth = Layer.effect(
/**
* Before upstream ends a session, by any of its four ways, the session is cut loose from its
* person, and with that from any mark that would let it renew: an ended device stays ended
* (AC49, AC50). If it cannot be done, nothing is revoked, so the Owner sees the failure and
* the device is not left half ended.
* (AC49, AC50). The two commit together or not at all, so no one sees a session that is no
* one's and still live, which would make links as no one's (`PairingIntents.recordForCreator`),
* and a failure leaves the device as it was for the Owner to try again.
*/
const unbound = <A, E, R>(
unbind: Effect.Effect<unknown, PersonAccessStorageError>,
revoke: Effect.Effect<A, E, R>,
) =>
unbind.pipe(
Effect.mapError(
(cause): EnvironmentAuth.ServerAuthInternalError =>
new EnvironmentAuth.ServerAuthSessionRevocationError({ cause }),
),
Effect.andThen(revoke),
);
sql
.withTransaction(
unbind.pipe(
Effect.mapError(
(cause): EnvironmentAuth.ServerAuthInternalError =>
new EnvironmentAuth.ServerAuthSessionRevocationError({ cause }),
),
Effect.andThen(revoke),
),
)
.pipe(
Effect.mapError((cause) =>
isSqlError(cause)
? new EnvironmentAuth.ServerAuthSessionRevocationError({ cause })
: (cause as Exclude<typeof cause, SqlError.SqlError>),
),
);

/**
* What to do about the session a browser already holds when it pairs again. Upstream replaces
Expand Down Expand Up @@ -606,15 +621,16 @@ export const layerGatedEnvironmentAuth = Layer.effect(
inner.revokeOtherClientSessions(currentSessionId),
),
// An MCP client is approved by an Owner; one approved before an Owner was lowered or
// removed is refused its session, and approved again (`Access.issueMcpClient`). Upstream
// issues one only from an exchange `McpApproval` gave the approval's generation to.
// removed is refused its session, and approved again, and one issued is recorded as its
// approver's (`Access.issueMcpClient`). Upstream issues one only from an exchange
// `McpApproval` gave the approval to.
issueMcpClientSession: (input) =>
Effect.serviceOption(McpApprovalGeneration).pipe(
Effect.serviceOption(McpExchangeApproval).pipe(
Effect.flatMap(
Option.match({
onNone: () => Effect.fail(new StaleMcpApprovalError({})),
onSome: (generation) =>
changes.issueMcpClient(generation, inner.issueMcpClientSession(input)),
onSome: (approval) =>
changes.issueMcpClient(approval, inner.issueMcpClientSession(input)),
}),
),
Effect.mapError((cause) =>
Expand Down
Loading
Loading