Skip to content

feat: add auth to inspector #736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
134 changes: 67 additions & 67 deletions packages/actor-core-cli/src/commands/deploy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -210,83 +210,83 @@ export const deploy = new Command()
);
}

if (managers.length > 0) {
for (const manager of managers) {
await Rivet.actor.upgrade(manager.id, {
project: projectName,
environment: envName,
body: {
buildTags: {
name: "manager",
current: "true",
},
},
});
}

const manager = managers.find(
(m) => !!createActorEndpoint(m.network),
);

if (!manager) {
throw ctx.error("Failed to find Actor Core Endpoint.", {
hint: "Any existing manager actor is not running or not accessible.",
});
}
// if (managers.length > 0) {
// for (const manager of managers) {
// await Rivet.actor.upgrade(manager.id, {
// project: projectName,
// environment: envName,
// body: {
// buildTags: {
// name: "manager",
// current: "true",
// },
// },
// });
// }

// const manager = managers.find(
// (m) => !!createActorEndpoint(m.network),
// );

// if (!manager) {
// throw ctx.error("Failed to find Actor Core Endpoint.", {
// hint: "Any existing manager actor is not running or not accessible.",
// });
// }

// return manager;
// } else {
const serviceToken = await getServiceToken(RivetHttp, {
project: projectName,
env: envName,
});

return manager;
} else {
const serviceToken = await getServiceToken(RivetHttp, {
project: projectName,
env: envName,
});
const { regions } = await Rivet.actor.regions.list({
project: projectName,
environment: envName,
});

const { regions } = await Rivet.actor.regions.list({
project: projectName,
environment: envName,
});
// find closest region
const region = regions.find(
(r) => r.id === "atl" || r.id === "local",
);

// find closest region
const region = regions.find(
(r) => r.id === "atl" || r.id === "local",
if (!region) {
throw ctx.error(
"No closest region found. Please contact support.",
);
}

if (!region) {
throw ctx.error(
"No closest region found. Please contact support.",
);
}

const { actor } = await Rivet.actor.create({
project: projectName,
environment: envName,
body: {
region: region.id,
tags: { name: "manager", owner: "rivet" },
buildTags: { name: "manager", current: "true" },
runtime: {
environment: {
RIVET_SERVICE_TOKEN: serviceToken,
},
const { actor } = await Rivet.actor.create({
project: projectName,
environment: envName,
body: {
region: region.id,
tags: { name: "manager", owner: "rivet" },
buildTags: { name: "manager", current: "true" },
runtime: {
environment: {
RIVET_SERVICE_TOKEN: serviceToken,
},
network: {
mode: "bridge",
ports: {
http: {
protocol: "https",
routing: {
guard: {},
},
},
network: {
mode: "bridge",
ports: {
http: {
protocol: "https",
routing: {
guard: {},
},
},
},
lifecycle: {
durable: true,
},
},
});
return actor;
}
lifecycle: {
durable: true,
},
},
});
return actor;
// }
},
);

Expand Down
20 changes: 16 additions & 4 deletions packages/actor-core/src/actor/runtime/actor_router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,10 +352,22 @@ export function createActorRouter(
}
});

app.route(
"/inspect",
createInspectorRouter(handler.upgradeWebSocket, handler.onConnectInspector),
);
if (
(typeof config.inspector === "object" &&
config.inspector.enabled === true) ||
config.inspector === true
) {
app.route(
"/inspect",
createInspectorRouter(
handler.upgradeWebSocket,
handler.onConnectInspector,
typeof config.inspector === "object"
? config.inspector.validateRequest
: undefined,
),
);
}

app.notFound(handleRouteNotFound);
app.onError(handleRouteError);
Expand Down
6 changes: 5 additions & 1 deletion packages/actor-core/src/actor/runtime/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
Handler as HonoHandler,
} from "hono";
import type { cors } from "hono/cors";
import { InspectorConfigSchema } from "./inspect";

// Define CORS options schema
type CorsOptions = NonNullable<Parameters<typeof cors>[0]>;
Expand Down Expand Up @@ -56,7 +57,7 @@ export type GetUpgradeWebSocket = (
/** Base config used for the actor config across all platforms. */
export const BaseConfigSchema = z.object({
actors: z.record(z.string(), z.custom<AnyActorConstructor>()),
topology: TopologySchema.optional(), // Default value depends on the platform selected
topology: TopologySchema.optional(), // Default value depends on the platform selected
drivers: z
.object({
manager: z.custom<ManagerDriver>().optional(),
Expand All @@ -82,5 +83,8 @@ export const BaseConfigSchema = z.object({

/** Peer configuration for coordinated topology. */
actorPeer: ActorPeerConfigSchema.optional().default({}),

/** Inspector configuration */
inspector: InspectorConfigSchema.optional().default(false),
});
export type BaseConfig = z.infer<typeof BaseConfigSchema>;
24 changes: 21 additions & 3 deletions packages/actor-core/src/actor/runtime/inspect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { AnyActor } from "@/actor/runtime/actor";
import type { Connection, ConnectionId } from "@/actor/runtime/connection";
import { throttle } from "@/actor/runtime/utils";
import type { UpgradeWebSocket, WSContext } from "hono/ws";
import { Hono, type HonoRequest } from "hono";
import { Hono, type HonoRequest, type Context as HonoContext } from "hono";
import * as errors from "@/actor/errors";
import { deconstructError, safeStringify } from "@/common/utils";
import {
Expand All @@ -11,20 +11,30 @@ import {
} from "@/actor/protocol/inspector/to_server";
import type { ToClient } from "@/actor/protocol/inspector/to_client";
import { logger } from "./log";
import { z } from "zod";

export type ValidateInspectorRequest = (c: HonoContext) => Promise<boolean>;

export const InspectorConfigSchema = z
.object({
enabled: z.boolean().optional().default(false),
validateRequest: z.custom<ValidateInspectorRequest>().optional(),
})
.or(z.boolean());

export interface ConnectInspectorOpts {
req: HonoRequest;
}

export interface ConnectInspectortOutput {
export interface ConnectInspectorOutput {
onOpen: (ws: WSContext) => Promise<void>;
onMessage: (message: ToServer) => Promise<void>;
onClose: () => Promise<void>;
}

export type InspectorConnectionHandler = (
opts: ConnectInspectorOpts,
) => Promise<ConnectInspectortOutput>;
) => Promise<ConnectInspectorOutput>;

/**
* Create a router for the inspector.
Expand All @@ -33,6 +43,7 @@ export type InspectorConnectionHandler = (
export function createInspectorRouter(
upgradeWebSocket: UpgradeWebSocket | undefined,
onConnect: InspectorConnectionHandler | undefined,
validateRequest: ValidateInspectorRequest | undefined,
) {
const app = new Hono();

Expand All @@ -45,6 +56,13 @@ export function createInspectorRouter(
}
return app.get(
"/",
async (c, next) => {
const result = (await validateRequest?.(c)) ?? true;
if (!result) {
return c.json({ error: "Unauthorized" }, 403);
}
await next();
},
upgradeWebSocket(async (c) => {
try {
const handler = await onConnect({ req: c.req });
Expand Down
37 changes: 32 additions & 5 deletions packages/platforms/rivet/src/actor_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import type { RivetHandler } from "./util";
import { PartitionTopologyActor } from "actor-core/topologies/partition";
import { ConfigSchema, type InputConfig } from "./config";
import { RivetActorDriver } from "./actor_driver";
import { rivetRequest } from "./rivet_client";

export function createActorHandler(
inputConfig: InputConfig,
): RivetHandler {
export function createActorHandler(inputConfig: InputConfig): RivetHandler {
const config = ConfigSchema.parse(inputConfig);

const handler = {
Expand All @@ -31,7 +30,36 @@ export function createActorHandler(
if (!config.drivers.actor) {
config.drivers.actor = new RivetActorDriver(ctx);
}


// Setup inspector
config.inspector = {
enabled: true,
async validateRequest(c) {
const token = c.req.query("token");

if (!token) {
return false;
}

try {
await rivetRequest(
{
endpoint: "http://rivet-server:8080",
token,
project: ctx.metadata.project.slug,
environment: ctx.metadata.environment.slug,
},
"GET",
"/cloud/auth/inspect",
);
return true;
} catch (e) {
console.log("error", e);
return false;
}
},
};

// Setup WebSocket upgrader
if (!config.getUpgradeWebSocket) {
config.getUpgradeWebSocket = () => upgradeWebSocket;
Expand Down Expand Up @@ -70,4 +98,3 @@ export function createActorHandler(

return handler;
}

2 changes: 1 addition & 1 deletion packages/platforms/rivet/src/manager_handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export function createManagerHandler(inputConfig: InputConfig): RivetHandler {
if (!token) throw new Error("missing RIVET_SERVICE_TOKEN");

const clientConfig: RivetClientConfig = {
endpoint,
endpoint: "http://rivet-server:8080",
token,
project: ctx.metadata.project.slug,
environment: ctx.metadata.environment.slug,
Expand Down