Skip to content
Open
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
20 changes: 13 additions & 7 deletions apps/server/src/auth/SessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1014,14 +1014,20 @@ const make = Effect.gen(function* () {
revokedAt,
})
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
if (revoked) {
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
next.delete(sessionId);
return next;
});
yield* emitRemoved(sessionId);
if (!revoked) {
// Another process, such as the CLI's database fallback, can revoke the row
// without reaching this process's open connections. Signal them anyway.
const row = yield* authSessions
.getById({ sessionId })
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
if (Option.isNone(row)) return false;
}
yield* Ref.update(connectedSessionsRef, (current) => {
const next = new Map(current);
next.delete(sessionId);
return next;
});
yield* emitRemoved(sessionId);
return revoked;
},
);
Expand Down
110 changes: 104 additions & 6 deletions apps/server/src/cli/auth.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { AuthSessionId, AuthStandardClientScopes } from "@t3tools/contracts";
import {
AuthAccessWriteScope,
AuthSessionId,
AuthStandardClientScopes,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
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 References from "effect/References";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";

import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";

Expand All @@ -17,6 +25,13 @@ import {
formatSessionList,
} from "../cliAuthFormat.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
isProcessAlive,
readPersistedServerRuntimeState,
recordedProcessStartMatches,
} from "../serverRuntimeState.ts";
import { authScopesFlag } from "./authScopes.ts";
import {
authLocationFlags,
Expand All @@ -25,9 +40,9 @@ import {
resolveCliAuthConfig,
} from "./config.ts";

const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* <A, E>(
const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function* <A, E, R>(
flags: CliAuthLocationFlags,
run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E, R>,
options?: {
readonly quietLogs?: boolean;
},
Expand All @@ -40,8 +55,8 @@ const runWithEnvironmentAuth = Effect.fn("auth.runWithEnvironmentAuth")(function
return yield* run(environmentAuth);
}).pipe(
Effect.provide(
Layer.mergeAll(EnvironmentAuth.layerRuntime).pipe(
Layer.provide(ServerConfig.layer(config)),
Layer.mergeAll(EnvironmentAuth.layerRuntime, FetchHttpClient.layer).pipe(
Layer.provideMerge(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
),
),
Expand Down Expand Up @@ -298,6 +313,89 @@ const sessionListCommand = Command.make("list", {
),
);

class OtherEnvironmentAtOriginError extends Schema.TaggedError<OtherEnvironmentAtOriginError>()(
"OtherEnvironmentAtOriginError",
{ origin: Schema.String },
) {
override get message(): string {
return `The server at ${this.origin} serves another T3 home.`;
}
}

class RecordedServerProcessError extends Schema.TaggedError<RecordedServerProcessError>()(
"RecordedServerProcessError",
{ pid: Schema.Number },
) {
override get message(): string {
return `Process ${this.pid} may not be the server recorded in server-runtime.json.`;
}
}

const LIVE_SERVER_TIMEOUT = Duration.seconds(10);
// Bounds how long the helper session outlives a CLI killed before it can revoke it.
const LIVE_SERVER_SESSION_TTL = Duration.minutes(1);

// Database-only revocation cannot signal the running server's open sockets.
const revokeSession = Effect.fn("auth.revokeSession")(function* (
environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],
sessionId: AuthSessionId,
) {
const config = yield* ServerConfig.ServerConfig;
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
Comment thread
only21mil marked this conversation as resolved.
Resolved
const { origin, pid } = runtimeState.value;
const identity = yield* ServerEnvironment.ServerEnvironmentIdentity;
const environmentId = yield* identity.getEnvironmentId;
const attempted = yield* Effect.result(
Effect.gen(function* () {
// A reused PID can make a stale record look live; contact only the recorded process,
// and give a credential only to this home's server.
const matches = yield* recordedProcessStartMatches(runtimeState.value).pipe(
Effect.provide(ProcessRunner.layer),
);
if (!Option.getOrElse(matches, () => false)) {
return yield* new RecordedServerProcessError({ pid });
}
const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin });
yield* client.metadata.descriptor().pipe(
Effect.filterOrFail(
(descriptor) => descriptor.environmentId === environmentId,
Comment thread
only21mil marked this conversation as resolved.
Resolved
() => new OtherEnvironmentAtOriginError({ origin }),
),
);
return yield* Effect.acquireUseRelease(
environmentAuth.issueSession({
ttl: LIVE_SERVER_SESSION_TTL,
scopes: [AuthAccessWriteScope],
subject: "auth-cli",
label: "t3 auth cli",
}),
(issued) =>
client.auth.revokeClient({
headers: { authorization: `Bearer ${issued.token}` },
payload: { sessionId },
}),
(issued) =>
environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
);
}).pipe(Effect.timeout(LIVE_SERVER_TIMEOUT)),
);
if (attempted._tag === "Success") {
// Also revoke this home's record; a no-op when the server already did.
const revokedLocally = yield* environmentAuth.revokeSession(sessionId);
return attempted.success.revoked || revokedLocally;
}
yield* Effect.logDebug("Failed to revoke the session through the running server.", {
origin,
cause: attempted.failure,
});
yield* Console.error(
`Could not reach the T3 Code server at ${origin}. Connections already open with this session stay open until they close.`,
);
}
return yield* environmentAuth.revokeSession(sessionId);
});

const sessionRevokeCommand = Command.make("revoke", {
...authLocationFlags,
sessionId: Argument.String("session-id").pipe(
Expand All @@ -309,7 +407,7 @@ const sessionRevokeCommand = Command.make("revoke", {
Command.withHandler((flags) =>
runWithEnvironmentAuth(flags, (environmentAuth) =>
Effect.gen(function* () {
const revoked = yield* environmentAuth.revokeSession(flags.sessionId);
const revoked = yield* revokeSession(environmentAuth, flags.sessionId);
yield* Console.log(
revoked
? `Revoked session ${flags.sessionId}.\n`
Expand Down
Loading
Loading