Skip to content

Commit 456930a

Browse files
fix(auth): show connection permissions and enforce session lifetime (pingdotgg#17370)
Co-authored-by: Bear Huddleston <[email protected]>
1 parent 2c7a446 commit 456930a

16 files changed

Lines changed: 536 additions & 140 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
@@ -3224,7 +3224,17 @@ export const layer = Layer.unwrap(
32243224
);
32253225
return yield* Effect.acquireUseRelease(
32263226
sessions.markConnected(session.sessionId),
3227-
() => rpcWebSocketHttpEffect,
3227+
() =>
3228+
Effect.raceFirst(
3229+
rpcWebSocketHttpEffect,
3230+
sessions.awaitInvalidation(session.sessionId).pipe(
3231+
Effect.as(HttpServerResponse.empty()),
3232+
Effect.catchTags({
3233+
SessionCredentialVerificationError: (error) =>
3234+
failEnvironmentInternal("internal_error", error),
3235+
}),
3236+
),
3237+
),
32283238
() => sessions.markDisconnected(session.sessionId),
32293239
);
32303240
}).pipe(

0 commit comments

Comments
 (0)