mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-14 23:24:52 +09:00
Add HostManager for host records and host tokens
controller.hosts is now a HostManager wrapping the hosts datastore, the same way controller.users wraps the users datastore. It owns creating hosts (moved from HostPairingManager), revoking them (moved from ControlConnection) and signing and verifying host tokens (moved from Controller, generateHostToken is renamed signHostToken to match signUserToken). UserManager gains verifyUserToken, replacing the copies of the user token check in WsServer and routes. The WsServer copy accepted a token without iat when the user had no tokenValidAfter; the shared check always requires iat, which jsonwebtoken adds by default. Follows Cooldude2606's comment on #1161. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5d1e98dafd
commit
e6554e09c7
20 files changed
+404
-198
No files matched your search
@@ -252,30 +252,7 @@ export default class ControlConnection extends BaseConnection {
|
||||
}
|
||||
|
||||
async handleHostRevokeRequest(request: lib.HostRevokeRequest) {
|
||||
const host = this._controller.hosts.getMutable(request.hostId);
|
||||
if (!host) {
|
||||
throw new lib.NotFoundError(`Unknown host id (${request.hostId})`);
|
||||
}
|
||||
|
||||
this._controller.hosts.delete(host);
|
||||
this._controller.deleteNote("host", request.hostId, this.user.name);
|
||||
const system = this._controller.systems.getMutable(request.hostId);
|
||||
if (system) {
|
||||
this._controller.systems.delete(system);
|
||||
}
|
||||
|
||||
// Disconnected first so unassigning the instances does not depend on the host responding.
|
||||
const hostConnection = this._controller.wsServer.hostConnections.get(request.hostId);
|
||||
if (hostConnection) {
|
||||
hostConnection.connector.terminate();
|
||||
}
|
||||
const assigned = [...this._controller.instances.values()].filter(
|
||||
instance => instance.config.get("instance.assigned_host") === request.hostId
|
||||
);
|
||||
for (const instance of assigned) {
|
||||
await this._controller.instances.unassignInstance(instance.id);
|
||||
}
|
||||
logger.audit(`User ${this.user.name} revoked host ${host.name} (${host.id})`);
|
||||
await this._controller.hosts.revokeHost(request.hostId, this.user.name);
|
||||
}
|
||||
|
||||
async handleHostListRequest(): Promise<lib.HostDetails[]> {
|
||||
|
||||
@@ -11,7 +11,6 @@ import events from "events";
|
||||
import fs from "node:fs/promises";
|
||||
import http from "http";
|
||||
import https from "https";
|
||||
import jwt from "jsonwebtoken";
|
||||
import path from "path";
|
||||
import semver from "semver";
|
||||
import stream from "stream";
|
||||
@@ -28,6 +27,7 @@ import User from "./User.js";
|
||||
import UserRecord from "./UserRecord.js";
|
||||
import UserManager from "./UserManager.js";
|
||||
import WsServer from "./WsServer.js";
|
||||
import HostManager from "./HostManager.js";
|
||||
import HostRecord from "./HostRecord.js";
|
||||
import HostPairingManager from "./HostPairingManager.js";
|
||||
import { BaseControllerPlugin, ControllerHooks } from "./BaseControllerPlugin.js";
|
||||
@@ -88,6 +88,8 @@ export default class Controller {
|
||||
|
||||
/** Event subscription controller */
|
||||
subscriptions: lib.SubscriptionController;
|
||||
/** Host manager for the cluster, also contains access to the host records */
|
||||
hosts: HostManager;
|
||||
/** User manager for the cluster, also contains access to the user records */
|
||||
users: UserManager;
|
||||
/** Instance manager for the cluster, also contains access to the user records */
|
||||
@@ -272,7 +274,7 @@ export default class Controller {
|
||||
public recoveryMode: boolean = false,
|
||||
public systems = new lib.SubscribableDatastore<lib.SystemInfo>(),
|
||||
/** Mapping of host id to host record */
|
||||
public hosts = new lib.SubscribableDatastore<HostRecord>(),
|
||||
hosts = new lib.SubscribableDatastore<HostRecord>(),
|
||||
/** Mapping of instance id to instance record */
|
||||
instances = new lib.SubscribableDatastore<InstanceRecord>(),
|
||||
/** Mapping of save id to save details */
|
||||
@@ -299,6 +301,7 @@ export default class Controller {
|
||||
this.trustedProxies = this.parseTrustedProxies();
|
||||
this.wsServer = new WsServer(this);
|
||||
|
||||
this.hosts = new HostManager(hosts, this);
|
||||
this.users = new UserManager(users, roles, config);
|
||||
this.instances = new InstanceManager(instances, this);
|
||||
this.hostPairing = new HostPairingManager(this);
|
||||
@@ -324,7 +327,7 @@ export default class Controller {
|
||||
|
||||
// Handle updates for datastores
|
||||
this.systems.on("update", this.systemsUpdated.bind(this));
|
||||
this.hosts.on("update", this.hostsUpdated.bind(this));
|
||||
this.hosts.records.on("update", this.hostsUpdated.bind(this));
|
||||
this.hostPairing.records.on("update", this.hostPairingRequestsUpdated.bind(this));
|
||||
this.instances.records.on("update", this.instanceUpdated.bind(this));
|
||||
this.saves.on("update", this.savesUpdated.bind(this));
|
||||
@@ -796,7 +799,7 @@ export default class Controller {
|
||||
await Promise.all([
|
||||
this.config.save(),
|
||||
this.systems.save(),
|
||||
this.hosts.save(),
|
||||
this.hosts.records.save(),
|
||||
this.instances.records.save(),
|
||||
this.saves.save(),
|
||||
this.modPacks.save(),
|
||||
@@ -1049,40 +1052,6 @@ export default class Controller {
|
||||
return systems.length ? new lib.SystemInfoUpdateEvent(systems) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate access token for host
|
||||
*
|
||||
* @returns access token for host
|
||||
* @param hostId - ID of host to generate a token for.
|
||||
*/
|
||||
generateHostToken(hostId: number): string {
|
||||
return jwt.sign({ aud: "host", host: hostId }, this.authSecret);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a host token
|
||||
*
|
||||
* @param token - Host token to check.
|
||||
* @returns ID of the host the token was issued to.
|
||||
* @throws if the token is invalid, its host is not registered or it was issued before tokenValidAfter.
|
||||
*/
|
||||
verifyHostToken(token: string): number {
|
||||
// migrate: allow pre-rename tokens issued to hosts before alpha-14
|
||||
const payload = jwt.verify(token, this.authSecret, { audience: ["host", "slave"] });
|
||||
if (typeof payload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
const hostId = payload.host !== undefined ? payload.host : payload.slave;
|
||||
const host = this.hosts.get(hostId);
|
||||
if (!host) {
|
||||
throw new Error("host is not registered, start the host again to request to join the cluster");
|
||||
}
|
||||
if (!payload.iat || payload.iat < host.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
return hostId;
|
||||
}
|
||||
|
||||
hostsUpdated(hosts: HostRecord[]) {
|
||||
let updates = hosts.map(host => host.toHostDetails());
|
||||
this.subscriptions.broadcast(new lib.HostUpdatesEvent(updates));
|
||||
|
||||
@@ -44,7 +44,7 @@ export default class HostConnection extends BaseConnection {
|
||||
record.connected = true;
|
||||
record.remoteAddress = remoteAddress;
|
||||
this.info = record;
|
||||
this._controller.hosts.set(this.info);
|
||||
this._controller.hosts.records.set(this.info);
|
||||
|
||||
this._checkPluginVersions();
|
||||
|
||||
@@ -175,7 +175,7 @@ export default class HostConnection extends BaseConnection {
|
||||
/** Store changes to the host record, unless the host was revoked */
|
||||
private _saveInfo() {
|
||||
if (this._controller.hosts.getMutable(this.id) === this.info) {
|
||||
this._controller.hosts.set(this.info);
|
||||
this._controller.hosts.records.set(this.info);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import crypto from "node:crypto";
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { logger } from "@clusterio/lib";
|
||||
|
||||
import type Controller from "./Controller.js";
|
||||
import HostRecord from "./HostRecord.js";
|
||||
|
||||
/**
|
||||
* Access layer for hosts on the controller.
|
||||
*
|
||||
* @alias module:controller/src/HostManager
|
||||
*/
|
||||
export default class HostManager {
|
||||
constructor(
|
||||
public readonly records: lib.SubscribableDatastore<HostRecord>,
|
||||
private readonly _controller: Controller,
|
||||
) { }
|
||||
|
||||
/* ------------------------------------------------------------------------- */
|
||||
/* Basic Accessors */
|
||||
/* ------------------------------------------------------------------------- */
|
||||
|
||||
has(id: HostRecord["id"]): boolean {
|
||||
return this.records.has(id);
|
||||
}
|
||||
|
||||
getMutable(id: HostRecord["id"]): HostRecord | undefined {
|
||||
return this.records.getMutable(id);
|
||||
}
|
||||
|
||||
get(id: HostRecord["id"]): Readonly<HostRecord> | undefined {
|
||||
return this.records.get(id);
|
||||
}
|
||||
|
||||
valuesMutable(): IterableIterator<HostRecord> {
|
||||
return this.records.values();
|
||||
}
|
||||
|
||||
values(): IterableIterator<Readonly<HostRecord>> {
|
||||
return this.valuesMutable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get host by ID for a request.
|
||||
*
|
||||
* @param hostId - ID of host to get.
|
||||
* @returns The host record.
|
||||
* @throws {module:lib.NotFoundError} if the host does not exist.
|
||||
*/
|
||||
getForRequest(hostId: number): HostRecord {
|
||||
const host = this.records.getMutable(hostId);
|
||||
if (!host) {
|
||||
throw new lib.NotFoundError(`Unknown host id (${hostId})`);
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- */
|
||||
/* Lifecycle */
|
||||
/* ------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Create a host record with a new random id
|
||||
*
|
||||
* @param name - Name of the host.
|
||||
* @returns the created host record.
|
||||
*/
|
||||
createHost(name: string): HostRecord {
|
||||
let hostId;
|
||||
do {
|
||||
hostId = crypto.randomInt(1, 2 ** 31);
|
||||
} while (this.records.has(hostId));
|
||||
|
||||
const host = new HostRecord(
|
||||
hostId, name, "", new Map(), false, "", "", Math.floor(Date.now() / 1000),
|
||||
);
|
||||
this.records.set(host);
|
||||
return host;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a host, disconnect it and unassign its instances
|
||||
*
|
||||
* @param hostId - ID of host to revoke.
|
||||
* @param revokedBy - Name of the user revoking it, for logging.
|
||||
*/
|
||||
async revokeHost(hostId: number, revokedBy: string) {
|
||||
const host = this.getForRequest(hostId);
|
||||
this.records.delete(host);
|
||||
this._controller.deleteNote("host", hostId, revokedBy);
|
||||
const system = this._controller.systems.getMutable(hostId);
|
||||
if (system) {
|
||||
this._controller.systems.delete(system);
|
||||
}
|
||||
|
||||
// Disconnected first so unassigning the instances does not depend on the host responding.
|
||||
const hostConnection = this._controller.wsServer.hostConnections.get(hostId);
|
||||
if (hostConnection) {
|
||||
hostConnection.connector.terminate();
|
||||
}
|
||||
const assigned = [...this._controller.instances.values()].filter(
|
||||
instance => instance.config.get("instance.assigned_host") === hostId
|
||||
);
|
||||
for (const instance of assigned) {
|
||||
await this._controller.instances.unassignInstance(instance.id);
|
||||
}
|
||||
logger.audit(`User ${revokedBy} revoked host ${host.name} (${host.id})`);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- */
|
||||
/* Helpers */
|
||||
/* ------------------------------------------------------------------------- */
|
||||
|
||||
/**
|
||||
* Sign access token for the given host
|
||||
*
|
||||
* @param hostId - ID of host to sign token for.
|
||||
* @returns JWT access token for the host.
|
||||
*/
|
||||
signHostToken(hostId: number): string {
|
||||
return jwt.sign({ aud: "host", host: hostId }, this._controller.authSecret);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a host token
|
||||
*
|
||||
* @param token - Host token to check.
|
||||
* @returns ID of the host the token was issued to.
|
||||
* @throws if the token is invalid, its host is not registered or it was issued before tokenValidAfter.
|
||||
*/
|
||||
verifyHostToken(token: string): number {
|
||||
// migrate: allow pre-rename tokens issued to hosts before alpha-14
|
||||
const payload = jwt.verify(token, this._controller.authSecret, { audience: ["host", "slave"] });
|
||||
if (typeof payload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
const hostId = payload.host !== undefined ? payload.host : payload.slave;
|
||||
const host = this.records.get(hostId);
|
||||
if (!host) {
|
||||
throw new Error("host is not registered, start the host again to request to join the cluster");
|
||||
}
|
||||
if (!payload.iat || payload.iat < host.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
return hostId;
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,6 @@ import net from "net";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { logger } from "@clusterio/lib";
|
||||
|
||||
import HostRecord from "./HostRecord.js";
|
||||
|
||||
/** Symbols used in pairing codes, avoids 0/O and 1/I/L */
|
||||
const codeAlphabet = "23456789ABCDEFGHJKMNPQRSTUVWXYZ";
|
||||
const codeLength = 6;
|
||||
@@ -141,25 +139,6 @@ export default class HostPairingManager {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an approved host with a new id and token
|
||||
*
|
||||
* @param name - Name of the host.
|
||||
* @returns the id, token and name of the new host.
|
||||
*/
|
||||
createHost(name: string): HostPairingResult {
|
||||
const hosts = this._controller.hosts;
|
||||
let hostId;
|
||||
do {
|
||||
hostId = crypto.randomInt(1, 2 ** 31);
|
||||
} while (hosts.has(hostId));
|
||||
|
||||
hosts.set(new HostRecord(
|
||||
hostId, name, "", new Map(), false, "", "", Math.floor(Date.now() / 1000),
|
||||
));
|
||||
return { hostId, token: this._controller.generateHostToken(hostId), name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pending request
|
||||
*
|
||||
@@ -265,7 +244,8 @@ export default class HostPairingManager {
|
||||
throw new lib.ValidationError(err.message);
|
||||
}
|
||||
|
||||
const result = this.createHost(hostName);
|
||||
const host = this._controller.hosts.createHost(hostName);
|
||||
const result = { hostId: host.id, token: this._controller.hosts.signHostToken(host.id), name: host.name };
|
||||
Object.assign(request, { state: "approved", result });
|
||||
this.records.delete(request.details);
|
||||
logger.audit(
|
||||
|
||||
@@ -151,11 +151,34 @@ export default class UserManager {
|
||||
* @returns JWT access token for the user.
|
||||
*/
|
||||
signUserToken(user: UserRecord): string {
|
||||
return jwt.sign(
|
||||
{ aud: "user", user: user.id },
|
||||
// auth secret is never null after startup
|
||||
Buffer.from(this._controllerConfig.get("controller.auth_secret")!, "base64")
|
||||
);
|
||||
return jwt.sign({ aud: "user", user: user.id }, this._authSecret);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a user token
|
||||
*
|
||||
* @param token - User token to check.
|
||||
* @returns the user the token was issued to.
|
||||
* @throws if the token is invalid, its user does not exist or it was issued before tokenValidAfter.
|
||||
*/
|
||||
verifyUserToken(token: string): User {
|
||||
const payload = jwt.verify(token, this._authSecret, { audience: "user" });
|
||||
if (typeof payload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
const user = this.getByNameMutable(payload.user);
|
||||
if (!user) {
|
||||
throw new Error("invalid user");
|
||||
}
|
||||
if (!payload.iat || payload.iat < user.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
private get _authSecret() {
|
||||
// auth secret is never null after startup
|
||||
return Buffer.from(this._controllerConfig.get("controller.auth_secret")!, "base64");
|
||||
}
|
||||
|
||||
/** Clear all player stats for specific instance */
|
||||
|
||||
@@ -252,7 +252,7 @@ ${err.stack}`
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.controller.verifyHostToken(data.token) !== data.id) {
|
||||
if (this.controller.hosts.verifyHostToken(data.token) !== data.id) {
|
||||
throw new Error("missmatched host id");
|
||||
}
|
||||
} catch (err: any) {
|
||||
@@ -320,18 +320,7 @@ ${err.stack}`
|
||||
async registerControl(data: lib.RegisterControlData, socket: WebSocket, req: IncomingMessage) {
|
||||
let user;
|
||||
try {
|
||||
const tokenPayload = jwt.verify(data.token, this.controller.authSecret, { audience: "user" });
|
||||
if (typeof tokenPayload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
|
||||
user = this.controller.users.getByNameMutable(tokenPayload.user);
|
||||
if (!user) {
|
||||
throw new Error("invalid user");
|
||||
}
|
||||
if ((tokenPayload.iat || 0) < user.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
user = this.controller.users.verifyUserToken(data.token);
|
||||
user.checkPermission("core.control.connect");
|
||||
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -6,7 +6,6 @@ import busboy from "busboy";
|
||||
import crypto from "crypto";
|
||||
import events from "events";
|
||||
import fs from "node:fs/promises";
|
||||
import jwt from "jsonwebtoken";
|
||||
import path from "path";
|
||||
import nodeStream from "stream";
|
||||
import util from "util";
|
||||
@@ -189,7 +188,7 @@ function validateHostToken(req: Request, res: Response, next: any) {
|
||||
}
|
||||
|
||||
try {
|
||||
req.app.locals.controller.verifyHostToken(token);
|
||||
req.app.locals.controller.hosts.verifyHostToken(token);
|
||||
} catch (err) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
@@ -206,7 +205,7 @@ function validateUserToken(req: Request, res: Response, next: any) {
|
||||
}
|
||||
|
||||
try {
|
||||
res.locals.user = userFromToken(req.app.locals.controller, token);
|
||||
res.locals.user = req.app.locals.controller.users.verifyUserToken(token);
|
||||
} catch (err) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
@@ -215,21 +214,6 @@ function validateUserToken(req: Request, res: Response, next: any) {
|
||||
next();
|
||||
}
|
||||
|
||||
function userFromToken(controller: Controller, token: string) {
|
||||
const tokenPayload = jwt.verify(token, controller.authSecret, { audience: "user" });
|
||||
if (typeof tokenPayload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
let user = controller.users.getByName(tokenPayload.user);
|
||||
if (!user) {
|
||||
throw new Error("invalid user");
|
||||
}
|
||||
if (!tokenPayload.iat || tokenPayload.iat < user.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
// Responds with the status of a pairing error, returns false for other errors.
|
||||
function sendHostPairingError(res: Response, err: unknown) {
|
||||
if (!(err instanceof HostPairingError)) {
|
||||
@@ -271,7 +255,7 @@ function createHostPairing(req: Request, res: Response) {
|
||||
if (token !== undefined) {
|
||||
let user;
|
||||
try {
|
||||
user = userFromToken(controller, token);
|
||||
user = controller.users.verifyUserToken(token);
|
||||
} catch (err) {
|
||||
res.status(401).json({ error: "Invalid user token" });
|
||||
return;
|
||||
@@ -285,12 +269,11 @@ function createHostPairing(req: Request, res: Response) {
|
||||
res.status(403).json({ error: `User ${user.name} is not allowed to approve hosts` });
|
||||
return;
|
||||
}
|
||||
const result = controller.hostPairing.createHost(name);
|
||||
const host = controller.hosts.createHost(name);
|
||||
logger.audit(
|
||||
`User ${user.name} approved host ${result.name} (${result.hostId}) from ${remoteAddress} ` +
|
||||
"with their token"
|
||||
`User ${user.name} approved host ${host.name} (${host.id}) from ${remoteAddress} with their token`
|
||||
);
|
||||
res.status(200).json(result);
|
||||
res.status(200).json({ hostId: host.id, token: controller.hosts.signHostToken(host.id), name: host.name });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user