Skip to content

Commit a3f92c8

Browse files
fix(auth): show connection permissions and enforce session lifetime
Adapt the live-session revocation approach from Bear Huddleston in #13844, adding expiry and a subscribe-before-check invalidation watcher. Co-authored-by: Bear Huddleston <[email protected]>
1 parent 48b71f0 commit a3f92c8

16 files changed

Lines changed: 425 additions & 116 deletions

‎apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ import {
99
connectionRoutes,
1010
isLearned,
1111
} from "@t3tools/client-runtime/connection";
12-
import type { EnvironmentId } from "@t3tools/contracts";
12+
import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
13+
import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
14+
import { AsyncResult } from "effect/reactivity";
1315
import * as Option from "effect/Option";
1416
import { useEffect, useMemo, useRef, useState } from "react";
1517
import { Alert, Platform, Pressable, View } from "react-native";
@@ -56,6 +58,9 @@ export function EnvironmentRoutesSection({
5658
}) {
5759
const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);
5860
const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));
61+
const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));
62+
const session = Option.getOrNull(AsyncResult.value(sessionResult));
63+
const [permissionsOpen, setPermissionsOpen] = useState(false);
5964
const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");
6065
const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");
6166
const [editing, setEditing] = useState(false);
@@ -146,6 +151,36 @@ export function EnvironmentRoutesSection({
146151
) : undefined
147152
}
148153
>
154+
<SettingsActionRow
155+
icon="checkmark.circle"
156+
label="Your permissions"
157+
onPress={() => setPermissionsOpen((open) => !open)}
158+
/>
159+
{permissionsOpen ? (
160+
<View className="gap-2 px-4 py-3">
161+
{activeRouteId !== null &&
162+
sessionResult._tag !== "Failure" &&
163+
!sessionResult.waiting &&
164+
session?.authenticated ? (
165+
<>
166+
<Text className="text-sm text-foreground-muted">
167+
Applies to the route marked In use. Other routes may have different permissions and
168+
have not been checked.
169+
</Text>
170+
{AUTH_SCOPE_OPTIONS.map(({ scope, title }) => (
171+
<Text key={scope} className="text-sm text-foreground">
172+
{title}: {sessionGrantsScope(session, scope) ? "Allowed" : "Not granted"}
173+
</Text>
174+
))}
175+
</>
176+
) : (
177+
<Text className="text-sm text-foreground-muted">
178+
Permissions not checked. Connect to this environment to view this session’s
179+
permissions.
180+
</Text>
181+
)}
182+
</View>
183+
) : null}
149184
{routes.map((route, index) => {
150185
const id = connectionRouteId(route.target);
151186
// Rows between the lifted row and its drop slot shift to make room.

‎apps/server/src/auth/SessionStore.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
33
import { expect, it } from "@effect/vitest";
44
import * as Duration from "effect/Duration";
55
import * as Effect from "effect/Effect";
6+
import * as Fiber from "effect/Fiber";
7+
import * as Deferred from "effect/Deferred";
68
import * as FileSystem from "effect/FileSystem";
79
import * as Layer from "effect/Layer";
810
import * as Option from "effect/Option";
@@ -113,6 +115,57 @@ const layerFailingSessionLookupCredential = Layer.effect(
113115
);
114116

115117
it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
118+
it.effect.each(["revoke", "revokeAllExcept", "replace"] as const)(
119+
"invalidates every connection for a session on %s and leaves other sessions active",
120+
(operation) =>
121+
Effect.gen(function* () {
122+
const sessions = yield* SessionStore.SessionStore;
123+
const owner = yield* sessions.issue({ subject: "owner" });
124+
const client = yield* sessions.issue(relaySessionInput);
125+
const ownerInvalidated = yield* Deferred.make<void>();
126+
yield* sessions
127+
.awaitInvalidation(owner.sessionId)
128+
.pipe(
129+
Effect.andThen(Deferred.succeed(ownerInvalidated, undefined)),
130+
Effect.forkScoped({ startImmediately: true }),
131+
);
132+
const first = yield* sessions
133+
.awaitInvalidation(client.sessionId)
134+
.pipe(Effect.forkScoped({ startImmediately: true }));
135+
const second = yield* sessions
136+
.awaitInvalidation(client.sessionId)
137+
.pipe(Effect.forkScoped({ startImmediately: true }));
138+
if (operation === "revoke") yield* sessions.revoke(client.sessionId);
139+
else if (operation === "revokeAllExcept") yield* sessions.revokeAllExcept(owner.sessionId);
140+
else yield* sessions.issue({ ...relaySessionInput, replaceSessionId: client.sessionId });
141+
yield* Fiber.join(first);
142+
yield* Fiber.join(second);
143+
expect(yield* Deferred.isDone(ownerInvalidated)).toBe(false);
144+
// A connection whose upgrade authenticated just before revocation must also stop.
145+
yield* sessions.awaitInvalidation(client.sessionId);
146+
}).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
147+
);
148+
149+
it.effect("expires a connected session at its credential deadline", () =>
150+
Effect.gen(function* () {
151+
const sessions = yield* SessionStore.SessionStore;
152+
const client = yield* sessions.issue(relaySessionInput);
153+
yield* sessions.markConnected(client.sessionId);
154+
const invalidated = yield* Deferred.make<void>();
155+
const watcher = yield* sessions
156+
.awaitInvalidation(client.sessionId)
157+
.pipe(
158+
Effect.andThen(Deferred.succeed(invalidated, undefined)),
159+
Effect.forkScoped({ startImmediately: true }),
160+
);
161+
yield* TestClock.adjust(Duration.minutes(59));
162+
expect(yield* Deferred.isDone(invalidated)).toBe(false);
163+
yield* TestClock.adjust(Duration.minutes(1));
164+
yield* Fiber.join(watcher);
165+
yield* sessions.awaitInvalidation(client.sessionId);
166+
}).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),
167+
);
168+
116169
it.effect("keys remote cookies by environment identity instead of state directory", () =>
117170
Effect.gen(function* () {
118171
const cookieName = (stateDir: string, environmentId: EnvironmentId) =>

‎apps/server/src/auth/SessionStore.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,9 @@ export class SessionStore extends Context.Service<
407407
SessionCredentialInternalError
408408
>;
409409
readonly streamChanges: Stream.Stream<SessionCredentialChange>;
410+
readonly awaitInvalidation: (
411+
sessionId: AuthSessionId,
412+
) => Effect.Effect<void, SessionCredentialVerificationError>;
410413
readonly revoke: (
411414
sessionId: AuthSessionId,
412415
) => Effect.Effect<boolean, SessionCredentialInternalError>;
@@ -1047,6 +1050,35 @@ export const make = Effect.gen(function* () {
10471050
return revokedSessionIds.length;
10481051
});
10491052

1053+
const awaitInvalidation = Effect.fn(function* (sessionId: AuthSessionId) {
1054+
return yield* Effect.scoped(
1055+
Effect.gen(function* () {
1056+
// Subscribe before reading: revocation can race with the WebSocket upgrade.
1057+
const subscription = yield* PubSub.subscribe(changesPubSub);
1058+
const row = yield* authSessions
1059+
.getById({ sessionId })
1060+
.pipe(
1061+
Effect.mapError(
1062+
(cause) => new SessionCredentialVerificationError({ sessionId, cause }),
1063+
),
1064+
);
1065+
if (Option.isNone(row) || row.value.revokedAt !== null) return;
1066+
const now = yield* DateTime.now;
1067+
const remaining = row.value.expiresAt.epochMilliseconds - now.epochMilliseconds;
1068+
if (remaining <= 0) return;
1069+
yield* Effect.raceFirst(
1070+
Stream.fromSubscription(subscription).pipe(
1071+
Stream.filter(
1072+
(change) => change.type === "clientRemoved" && change.sessionId === sessionId,
1073+
),
1074+
Stream.runHead,
1075+
),
1076+
Effect.sleep(Duration.millis(remaining)),
1077+
);
1078+
}),
1079+
);
1080+
});
1081+
10501082
return SessionStore.of({
10511083
cookieName,
10521084
legacyCookieName,
@@ -1055,6 +1087,7 @@ export const make = Effect.gen(function* () {
10551087
issueWebSocketToken,
10561088
verifyWebSocketToken,
10571089
listActive,
1090+
awaitInvalidation,
10581091
get streamChanges() {
10591092
return Stream.fromPubSub(changesPubSub);
10601093
},

‎apps/server/src/ws.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3223,7 +3223,17 @@ export const layer = Layer.unwrap(
32233223
);
32243224
return yield* Effect.acquireUseRelease(
32253225
sessions.markConnected(session.sessionId),
3226-
() => rpcWebSocketHttpEffect,
3226+
() =>
3227+
Effect.raceFirst(
3228+
rpcWebSocketHttpEffect,
3229+
sessions.awaitInvalidation(session.sessionId).pipe(
3230+
Effect.as(HttpServerResponse.empty()),
3231+
Effect.catchTags({
3232+
SessionCredentialVerificationError: (error) =>
3233+
failEnvironmentInternal("internal_error", error),
3234+
}),
3235+
),
3236+
),
32273237
() => sessions.markDisconnected(session.sessionId),
32283238
);
32293239
}).pipe(

‎apps/web/src/components/settings/ConnectionsSettings.tsx‎

Lines changed: 10 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { SessionPermissions } from "./SessionPermissions";
2+
import { AUTH_SCOPE_OPTIONS as PAIRING_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
13
import {
24
ChevronRightIcon,
35
ChevronsLeftRightEllipsisIcon,
@@ -23,20 +25,13 @@ import {
2325
import {
2426
AuthAccessReadScope,
2527
AuthAccessWriteScope,
26-
AuthSettingsWriteScope,
27-
AuthProvidersManageScope,
2828
AuthEnvironmentMaintainScope,
2929
AuthDiagnosticsReadScope,
30-
AuthOrchestrationOperateScope,
3130
AuthOrchestrationReadScope,
32-
AuthPreviewOperateScope,
3331
AuthRelayReadScope,
3432
AuthRelayWriteScope,
35-
AuthSourceControlWriteScope,
3633
AuthFilesystemReadScope,
37-
AuthFilesystemWriteScope,
3834
AuthStandardClientScopes,
39-
AuthTerminalOperateScope,
4035
AuthTerminalReadScope,
4136
type AuthClientSession,
4237
type AuthEnvironmentScope,
@@ -231,93 +226,6 @@ function formatAccessTimestamp(value: string): string {
231226
return accessTimestampFormatter.format(parsed);
232227
}
233228

234-
const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{
235-
readonly scope: AuthGrantScope;
236-
readonly title: string;
237-
readonly description: string;
238-
}> = [
239-
{
240-
scope: AuthOrchestrationReadScope,
241-
title: "View environment",
242-
description: "Read threads, status, checkpoints, and configuration.",
243-
},
244-
{
245-
scope: AuthOrchestrationOperateScope,
246-
title: "Operate tasks",
247-
description: "Start, update, and stop tasks.",
248-
},
249-
{
250-
scope: AuthSettingsWriteScope,
251-
title: "Change environment settings",
252-
description: "Edit environment preferences and keybindings.",
253-
},
254-
{
255-
scope: AuthProvidersManageScope,
256-
title: "Manage providers",
257-
description: "Configure, install, sign in to, and update providers and usage sources.",
258-
},
259-
{
260-
scope: AuthEnvironmentMaintainScope,
261-
title: "Maintain environment",
262-
description: "Update the server and control environment processes.",
263-
},
264-
{
265-
scope: AuthPreviewOperateScope,
266-
title: "Control previews",
267-
description: "Open browser previews and host browser automation.",
268-
},
269-
{
270-
scope: AuthDiagnosticsReadScope,
271-
title: "View diagnostics and usage",
272-
description: "Read process diagnostics, resource history, and usage totals.",
273-
},
274-
{
275-
scope: AuthTerminalReadScope,
276-
title: "View terminals",
277-
description: "Read existing terminal output and status.",
278-
},
279-
{
280-
scope: AuthTerminalOperateScope,
281-
title: "Use terminals",
282-
description: "Create terminals and send input to running shells.",
283-
},
284-
{
285-
scope: AuthSourceControlWriteScope,
286-
title: "Change source control",
287-
description: "Commit, push, manage branches and repositories, and change pull requests.",
288-
},
289-
{
290-
scope: AuthFilesystemReadScope,
291-
title: "Read files",
292-
description: "Browse host files, search workspaces, and inspect local changes.",
293-
},
294-
{
295-
scope: AuthFilesystemWriteScope,
296-
title: "Write files",
297-
description: "Edit workspace files and save plans to disk.",
298-
},
299-
{
300-
scope: AuthAccessReadScope,
301-
title: "View access",
302-
description: "Inspect pairing links and authorized clients.",
303-
},
304-
{
305-
scope: AuthAccessWriteScope,
306-
title: "Manage access",
307-
description: "Issue and revoke credentials for other clients.",
308-
},
309-
{
310-
scope: AuthRelayReadScope,
311-
title: "View relay",
312-
description: "Inspect managed relay connectivity.",
313-
},
314-
{
315-
scope: AuthRelayWriteScope,
316-
title: "Manage relay",
317-
description: "Change managed tunnel connectivity.",
318-
},
319-
];
320-
321229
function AccessScopeSummary({
322230
scopes,
323231
label,
@@ -3776,6 +3684,14 @@ export function ConnectionsSettings() {
37763684
) : null}
37773685
</SettingsSection>
37783686

3687+
{primaryEnvironment ? (
3688+
<SessionPermissions
3689+
environmentId={primaryEnvironment.environmentId}
3690+
label={primaryEnvironment.label}
3691+
connected={primaryEnvironment.connection.phase === "connected"}
3692+
/>
3693+
) : null}
3694+
37793695
{canReadAccess || canWriteAccess ? (
37803696
<FoldedSettingsSection
37813697
id="authorized-clients"

‎apps/web/src/components/settings/EnvironmentRoutesList.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { SessionPermissions } from "./SessionPermissions";
12
import {
23
DndContext,
34
type DragEndEvent,
@@ -104,6 +105,12 @@ export function EnvironmentRoutesList({
104105

105106
return (
106107
<div className="mt-2 rounded-md border border-border/70">
108+
<SessionPermissions
109+
environmentId={environment.environmentId}
110+
label={environment.label}
111+
connected={activeRouteId !== null}
112+
routeContext
113+
/>
107114
<DndContext
108115
sensors={sensors}
109116
collisionDetection={closestCenter}

0 commit comments

Comments
 (0)