Skip to content
Closed
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
72 changes: 72 additions & 0 deletions apps/server/src/auth/SessionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
import * as SqlClient from "effect/unstable/sql/SqlClient";
Expand Down Expand Up @@ -276,6 +277,77 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
}).pipe(Effect.provide(makeSessionStoreLayer())),
);

it.effect("completes awaitRevoked when the session is revoked", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const issued = yield* sessions.issue({
subject: "await-revoked",
method: "bearer-access-token",
});
const fiber = yield* sessions
.awaitRevoked(issued.sessionId)
.pipe(Effect.forkChild({ startImmediately: true }));

yield* sessions.revoke(issued.sessionId);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(makeSessionStoreLayer())),
);

it.effect("completes awaitRevoked immediately when the session is already revoked", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const issued = yield* sessions.issue({
subject: "already-revoked",
method: "bearer-access-token",
});
yield* sessions.revoke(issued.sessionId);
yield* sessions.awaitRevoked(issued.sessionId);
}).pipe(Effect.provide(makeSessionStoreLayer())),
);

it.effect("completes awaitRevoked when other sessions are revoked", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const keep = yield* sessions.issue({
subject: "keep",
method: "bearer-access-token",
});
const drop = yield* sessions.issue({
subject: "drop",
method: "bearer-access-token",
});
const fiber = yield* sessions
.awaitRevoked(drop.sessionId)
.pipe(Effect.forkChild({ startImmediately: true }));

yield* sessions.revokeAllExcept(keep.sessionId);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(makeSessionStoreLayer())),
);

it.effect("does not complete awaitRevoked for a different session", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const watched = yield* sessions.issue({
subject: "watched",
method: "bearer-access-token",
});
const other = yield* sessions.issue({
subject: "other",
method: "bearer-access-token",
});
const fiber = yield* sessions
.awaitRevoked(watched.sessionId)
.pipe(Effect.forkChild({ startImmediately: true }));

yield* sessions.revoke(other.sessionId);
expect(fiber.pollUnsafe()).toBeUndefined();

yield* sessions.revoke(watched.sessionId);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(makeSessionStoreLayer())),
);

it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
Expand Down
83 changes: 81 additions & 2 deletions apps/server/src/auth/SessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ import {
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";

import * as ServerConfig from "../config.ts";
import * as AuthSessions from "../persistence/AuthSessions.ts";
Expand Down Expand Up @@ -395,6 +397,12 @@ export class SessionStore extends Context.Service<
readonly revokeAllExcept: (
sessionId: AuthSessionId,
) => Effect.Effect<number, SessionCredentialInternalError>;
/**
* Completes when this session is revoked, or immediately if it already is.
* WebSocket handlers race the live socket against this so a kick closes the
* connection instead of leaving it open until TCP drops.
*/
readonly awaitRevoked: (sessionId: AuthSessionId) => Effect.Effect<void>;
readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
readonly recordClientConnection: (
Expand Down Expand Up @@ -474,6 +482,9 @@ export const make = Effect.gen(function* () {
const authSessions = yield* AuthSessions.AuthSessionRepository;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
const revocationWaitersRef = yield* Ref.make(
new Map<string, ReadonlyArray<Deferred.Deferred<void>>>(),
);
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
Expand All @@ -495,6 +506,69 @@ export const make = Effect.gen(function* () {
sessionId,
}).pipe(Effect.asVoid);

const completeRevocationWaiters = (sessionId: AuthSessionId) =>
Ref.modify(revocationWaitersRef, (current) => {
const waiters = current.get(sessionId) ?? [];
if (waiters.length === 0) {
return [waiters, current] as const;
}
const next = new Map(current);
next.delete(sessionId);
return [waiters, next] as const;
}).pipe(
Effect.flatMap((waiters) =>
Effect.forEach(
waiters,
(waiter) => Deferred.succeed(waiter, undefined).pipe(Effect.asVoid),
{ discard: true },
),
),
);

const removeRevocationWaiter = (sessionId: AuthSessionId, waiter: Deferred.Deferred<void>) =>
Ref.update(revocationWaitersRef, (current) => {
const waiters = current.get(sessionId);
if (waiters === undefined) {
return current;
}
const remaining = waiters.filter((entry) => entry !== waiter);
if (remaining.length === waiters.length) {
return current;
}
const next = new Map(current);
if (remaining.length === 0) {
next.delete(sessionId);
} else {
next.set(sessionId, remaining);
}
return next;
});

const awaitRevoked: SessionStore["Service"]["awaitRevoked"] = Effect.fn(
"SessionStore.awaitRevoked",
)(function* (sessionId) {
const waiter = yield* Deferred.make<void>();
yield* Ref.update(revocationWaitersRef, (current) => {
const next = new Map(current);
next.set(sessionId, [...(current.get(sessionId) ?? []), waiter]);
return next;
});
return yield* Effect.gen(function* () {
const lookup = yield* authSessions.getById({ sessionId }).pipe(Effect.result);
if (Result.isSuccess(lookup)) {
const row = lookup.success;
if (Option.isNone(row) || row.value.revokedAt !== null) {
yield* Deferred.succeed(waiter, undefined);
}
} else {
yield* Effect.logWarning(
"Failed to check whether a live session was already revoked.",
).pipe(Effect.annotateLogs({ sessionId, cause: lookup.failure }));
}
return yield* Deferred.await(waiter);
}).pipe(Effect.ensuring(removeRevocationWaiter(sessionId, waiter)));
});

const loadActiveSession = (sessionId: AuthSessionId) =>
Effect.gen(function* () {
const row = yield* authSessions.getById({ sessionId });
Expand Down Expand Up @@ -888,6 +962,7 @@ export const make = Effect.gen(function* () {
next.delete(sessionId);
return next;
});
yield* completeRevocationWaiters(sessionId);
yield* emitRemoved(sessionId);
}
return revoked;
Expand Down Expand Up @@ -918,7 +993,10 @@ export const make = Effect.gen(function* () {
});
yield* Effect.forEach(
revokedSessionIds,
(revokedSessionId) => emitRemoved(revokedSessionId),
(revokedSessionId) =>
completeRevocationWaiters(revokedSessionId).pipe(
Effect.andThen(emitRemoved(revokedSessionId)),
),
{
concurrency: "unbounded",
discard: true,
Expand All @@ -940,6 +1018,7 @@ export const make = Effect.gen(function* () {
},
revoke,
revokeAllExcept,
awaitRevoked,
markConnected,
markDisconnected,
recordClientConnection,
Expand Down
59 changes: 59 additions & 0 deletions apps/server/src/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4000,6 +4000,65 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("closes a live websocket when that client session is revoked", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
config: {
host: "0.0.0.0",
},
});

const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
headers: {
cookie: ownerCookie,
},
body: yield* HttpBody.json({}),
});
const pairingBody = (yield* pairingResponse.json) as {
readonly credential: string;
};
const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader(
pairingBody.credential,
);

const clientsResponse = yield* HttpClient.get("/api/auth/clients", {
headers: {
cookie: ownerCookie,
},
});
const clients = (yield* clientsResponse.json) as ReadonlyArray<{
readonly sessionId: string;
readonly current: boolean;
}>;
const pairedSessionId = clients.find((entry) => !entry.current)?.sessionId;
assert.isDefined(pairedSessionId);

const wsUrl = appendSessionCookieToWsUrl(
yield* getWsServerUrl("/ws", { authenticated: false }),
pairedSessionCookie?.split(";")[0] ?? "",
);
const streamFiber = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.runDrain),
),
).pipe(Effect.exit, Effect.forkChild({ startImmediately: true }));

yield* Effect.yieldNow;

const revokeResponse = yield* HttpClient.post("/api/auth/clients/revoke", {
headers: {
cookie: ownerCookie,
"content-type": "application/json",
},
body: HttpBody.text(jsonRequestBody({ sessionId: pairedSessionId }), "application/json"),
});
assert.equal(revokeResponse.status, 200);

yield* Fiber.join(streamFiber);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("allows reusing the desktop bootstrap credential", () =>
Effect.gen(function* () {
// The desktop-bootstrap grant is delivered over trusted IPC at
Expand Down
8 changes: 7 additions & 1 deletion apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2521,7 +2521,13 @@ export const websocketRpcRouteLayer = Layer.unwrap(
);
return yield* Effect.acquireUseRelease(
sessions.markConnected(session.sessionId),
() => rpcWebSocketHttpEffect,
() =>
rpcWebSocketHttpEffect.pipe(
// A kick stamps revoked_at but used to leave this socket open.
// Racing the live connection against awaitRevoked interrupts it
// so the client is dropped now, not whenever TCP happens to die.
Effect.raceFirst(sessions.awaitRevoked(session.sessionId)),
),
() => sessions.markDisconnected(session.sessionId),
);
}).pipe(
Expand Down
4 changes: 4 additions & 0 deletions docs/internals/environment-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ appends only that ticket to the socket URL as `wsTicket`. This keeps long-lived
tokens and browser cookies out of WebSocket URLs while letting the handshake
authenticate.

Revoking a session closes any live WebSocket that authenticated as that session.
A later upgrade is already rejected because the ticket's parent session is revoked.
The live socket used to stay open until TCP dropped.

The ticket carries its session's scopes; each RPC method then enforces
`orchestration:read`, `orchestration:operate`, `terminal:operate`,
`review:write`, `relay:write`, or `access:read` as appropriate, through
Expand Down
2 changes: 1 addition & 1 deletion docs/user/remote-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,4 +235,4 @@ controls remain in **Settings** → **Connections** on web and desktop or **Sett
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
- Use `t3 auth` to revoke credentials or sessions you no longer trust. Revoking a session also closes that client's live connection.
Loading