mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-16 07:24:53 +09:00
Replace host tokens with host pairing
Hosts join the cluster by running the installer, which shows a code and waits until the request is approved under Hosts > Add host in the web interface or with clusterioctl host approve. An admin can pass their user token to the installer to approve the host right away. The token is only used for that and is not saved. The controller only accepts hosts that have a record, and only approving a host creates one. Revoking a host deletes its record, so its token can no longer be used to reconnect. Hosts that have connected before keep working. Removes host generate-token, revoke-token and create-config from clusterioctl, bootstrap generate-host-token, the host token messages and the core.host.generate_token, revoke_token and create_config permissions, which are also stripped from stored roles. Adds clusterioctl host pending, approve, reject and revoke, and the core.host.approve and core.host.revoke permissions. Standalone installs add the host to the controller database directly, since the controller is not running during the install.
This commit is contained in:
49 files changed
+4855
-473
No files matched your search
@@ -81,10 +81,11 @@ export default class ControlConnection extends BaseConnection {
|
||||
this.handle(lib.ControllerConfigSetRequest, this.handleControllerConfigSetRequest.bind(this));
|
||||
this.handle(lib.ControllerConfigSetFieldRequest, this.handleControllerConfigSetFieldRequest.bind(this));
|
||||
this.handle(lib.ControllerConfigSetPropRequest, this.handleControllerConfigSetPropRequest.bind(this));
|
||||
this.handle(lib.HostRevokeTokensRequest, this.handleHostRevokeTokensRequest.bind(this));
|
||||
this.handle(lib.HostRevokeRequest, this.handleHostRevokeRequest.bind(this));
|
||||
this.handle(lib.HostListRequest, this.handleHostListRequest.bind(this));
|
||||
this.handle(lib.HostGenerateTokenRequest, this.handleHostGenerateTokenRequest.bind(this));
|
||||
this.handle(lib.HostConfigCreateRequest, this.handleHostConfigCreateRequest.bind(this));
|
||||
this.handle(lib.HostPairingListRequest, this.handleHostPairingListRequest.bind(this));
|
||||
this.handle(lib.HostPairingApproveRequest, this.handleHostPairingApproveRequest.bind(this));
|
||||
this.handle(lib.HostPairingRejectRequest, this.handleHostPairingRejectRequest.bind(this));
|
||||
this.handle(lib.InstanceDetailsGetRequest, this.handleInstanceDetailsGetRequest.bind(this));
|
||||
this.handle(lib.InstanceDetailsListRequest, this.handleInstanceDetailsListRequest.bind(this));
|
||||
this.handle(lib.InstanceCreateRequest, this.handleInstanceCreateRequest.bind(this));
|
||||
@@ -248,49 +249,49 @@ export default class ControlConnection extends BaseConnection {
|
||||
this._controller.config.setProp(field as keyof lib.ControllerConfigFields, prop, value, "control");
|
||||
}
|
||||
|
||||
async handleHostRevokeTokensRequest(request: lib.HostRevokeTokensRequest) {
|
||||
async handleHostRevokeRequest(request: lib.HostRevokeRequest) {
|
||||
const host = this._controller.hosts.getMutable(request.hostId);
|
||||
if (!host) {
|
||||
throw new Error(`Unknown host id (${request.hostId})`);
|
||||
throw new lib.NotFoundError(`Unknown host id (${request.hostId})`);
|
||||
}
|
||||
|
||||
host.tokenValidAfter = Math.floor(Date.now() / 1000);
|
||||
const assigned = [...this._controller.instances.values()].filter(
|
||||
instance => instance.config.get("instance.assigned_host") === request.hostId
|
||||
);
|
||||
if (assigned.length) {
|
||||
const names = assigned.map(instance => instance.config.get("instance.name")).join(", ");
|
||||
throw new lib.ConflictError(
|
||||
`Cannot revoke host ${host.name} while instances are assigned to it: ${names}`
|
||||
);
|
||||
}
|
||||
|
||||
this._controller.hosts.delete(host);
|
||||
this._controller.deleteNote("host", request.hostId, this.user.name);
|
||||
|
||||
// Disconnect before saving so the host is cut off even if the save fails.
|
||||
const hostConnection = this._controller.wsServer.hostConnections.get(request.hostId);
|
||||
if (hostConnection) {
|
||||
hostConnection.connector.terminate();
|
||||
}
|
||||
|
||||
this._controller.hosts.set(host);
|
||||
logger.audit(`User ${this.user.name} revoked host ${host.name} (${host.id})`);
|
||||
await this._controller.hosts.save();
|
||||
}
|
||||
|
||||
async handleHostListRequest(): Promise<lib.HostDetails[]> {
|
||||
return [...this._controller.hosts.values()].map(host => host.toHostDetails());
|
||||
}
|
||||
|
||||
async handleHostGenerateTokenRequest(message: lib.HostGenerateTokenRequest) {
|
||||
let hostId = message.hostId;
|
||||
if (hostId === undefined) {
|
||||
hostId = Math.random() * 2**31 | 0;
|
||||
}
|
||||
return this._controller.generateHostToken(hostId);
|
||||
async handleHostPairingListRequest(): Promise<lib.HostPairingDetails[]> {
|
||||
this._controller.hostPairing.prune();
|
||||
return [...this._controller.hostPairing.requests.values()];
|
||||
}
|
||||
|
||||
async handleHostConfigCreateRequest(request: lib.HostConfigCreateRequest) {
|
||||
const hostConfig = new lib.HostConfig("host");
|
||||
async handleHostPairingApproveRequest(request: lib.HostPairingApproveRequest) {
|
||||
return await this._controller.hostPairing.approve(request.code, request.name, this.user.name);
|
||||
}
|
||||
|
||||
hostConfig.set("host.controller_url", this._controller.getControllerUrl());
|
||||
if (request.id !== undefined) {
|
||||
hostConfig.set("host.id", request.id);
|
||||
}
|
||||
if (request.name !== undefined) {
|
||||
hostConfig.set("host.name", request.name);
|
||||
}
|
||||
if (request.generateToken) {
|
||||
this.user.checkPermission("core.host.generate_token");
|
||||
hostConfig.set("host.controller_token", this._controller.generateHostToken(hostConfig.get("host.id")));
|
||||
}
|
||||
return hostConfig.toJSON();
|
||||
async handleHostPairingRejectRequest(request: lib.HostPairingRejectRequest) {
|
||||
this._controller.hostPairing.reject(request.code, this.user.name);
|
||||
}
|
||||
|
||||
async handleInstanceDetailsGetRequest(request: lib.InstanceDetailsGetRequest) {
|
||||
|
||||
@@ -29,6 +29,7 @@ import UserRecord from "./UserRecord.js";
|
||||
import UserManager from "./UserManager.js";
|
||||
import WsServer from "./WsServer.js";
|
||||
import HostRecord from "./HostRecord.js";
|
||||
import HostPairingManager from "./HostPairingManager.js";
|
||||
import { BaseControllerPlugin, ControllerHooks } from "./BaseControllerPlugin.js";
|
||||
import ControllerRouter from "./ControllerRouter.js";
|
||||
import InstanceManager from "./InstanceManager.js";
|
||||
@@ -91,6 +92,8 @@ export default class Controller {
|
||||
users: UserManager;
|
||||
/** Instance manager for the cluster, also contains access to the user records */
|
||||
instances: InstanceManager;
|
||||
/** Pending requests from host installers to join the cluster */
|
||||
hostPairing: HostPairingManager;
|
||||
|
||||
// Possible states are new, starting, running, stopping, stopped
|
||||
private _state: string = "new";
|
||||
@@ -296,6 +299,7 @@ export default class Controller {
|
||||
|
||||
this.users = new UserManager(users, roles, config);
|
||||
this.instances = new InstanceManager(instances, this);
|
||||
this.hostPairing = new HostPairingManager(this);
|
||||
|
||||
this.modStore.on("change", mod => {
|
||||
this.modsUpdated([mod]);
|
||||
@@ -305,6 +309,7 @@ export default class Controller {
|
||||
this.subscriptions = new lib.SubscriptionController(config.get("controller.max_subscription_filters"));
|
||||
this.subscriptions.handle(lib.SystemInfoUpdateEvent, this.handleSystemInfoSubscription.bind(this));
|
||||
this.subscriptions.handle(lib.HostUpdatesEvent, this.handleHostSubscription.bind(this));
|
||||
this.subscriptions.handle(lib.HostPairingUpdatesEvent, this.handleHostPairingSubscription.bind(this));
|
||||
this.subscriptions.handle(lib.InstanceDetailsUpdatesEvent, this.handleInstanceDetailsSubscription.bind(this));
|
||||
this.subscriptions.handle(
|
||||
lib.InstanceSaveDetailsUpdatesEvent, this.handleInstanceSaveDetailsSubscription.bind(this)
|
||||
@@ -318,6 +323,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.hostPairing.requests.on("update", this.hostPairingRequestsUpdated.bind(this));
|
||||
this.instances.records.on("update", this.instanceUpdated.bind(this));
|
||||
this.saves.on("update", this.savesUpdated.bind(this));
|
||||
this.modPacks.on("update", this.modPacksUpdated.bind(this));
|
||||
@@ -367,6 +373,7 @@ export default class Controller {
|
||||
|
||||
async _startInternal(args: ControllerArgs) {
|
||||
this.logDirectory = args.logDirectory;
|
||||
this.hostPairing.start();
|
||||
this.clusterLogIndex = await lib.LogIndex.load(path.join(this.logDirectory, "cluster"));
|
||||
|
||||
this.clusterLogBuildInterval = setInterval(() => {
|
||||
@@ -582,6 +589,8 @@ export default class Controller {
|
||||
this.autosaveInterval = undefined;
|
||||
}
|
||||
|
||||
this.hostPairing.stop();
|
||||
|
||||
if (this.clusterLogIndex) {
|
||||
await this.clusterLogIndex.save();
|
||||
}
|
||||
@@ -869,6 +878,10 @@ export default class Controller {
|
||||
|
||||
static migrateRoles(rawJson: unknown[]): Static<typeof lib.Role.jsonSchema>[] {
|
||||
const serialized = rawJson as Static<typeof lib.Role.jsonSchema>[];
|
||||
// migrate: host token permissions were removed with host pairing in 2.1
|
||||
const removedPermissions = new Set([
|
||||
"core.host.generate_token", "core.host.revoke_token", "core.host.create_config",
|
||||
]);
|
||||
return serialized.map(json => {
|
||||
json.permissions = json.permissions.map(permission => {
|
||||
// migrate: core.instance.save.list.subscribe was renamed in alpha 17
|
||||
@@ -876,7 +889,7 @@ export default class Controller {
|
||||
return "core.instance.save.subscribe";
|
||||
}
|
||||
return permission;
|
||||
});
|
||||
}).filter(permission => !removedPermissions.has(permission));
|
||||
return lib.Role.pluginMigrations.reduce(json);
|
||||
});
|
||||
}
|
||||
@@ -1017,6 +1030,20 @@ export default class Controller {
|
||||
this.subscriptions.broadcast(new lib.HostUpdatesEvent(updates));
|
||||
}
|
||||
|
||||
hostPairingRequestsUpdated(requests: lib.HostPairingDetails[]) {
|
||||
this.subscriptions.broadcast(new lib.HostPairingUpdatesEvent(requests));
|
||||
}
|
||||
|
||||
async handleHostPairingSubscription(request: lib.SubscriptionRequest) {
|
||||
if (request.action === "unsubscribe") {
|
||||
return null;
|
||||
}
|
||||
const requests = [...this.hostPairing.requests.values()].filter(
|
||||
pairing => pairing.updatedAtMs > request.lastRequestTimeMs,
|
||||
);
|
||||
return requests.length ? new lib.HostPairingUpdatesEvent(requests) : null;
|
||||
}
|
||||
|
||||
async handleHostSubscription(request: lib.SubscriptionRequest) {
|
||||
if (request.action === "unsubscribe") {
|
||||
return null;
|
||||
|
||||
@@ -34,19 +34,16 @@ export default class HostConnection extends BaseConnection {
|
||||
|
||||
this.plugins = new Map(Object.entries(registerData.plugins));
|
||||
|
||||
const previousHostInfo = this._controller.hosts.get(registerData.id);
|
||||
this.info = new HostRecord(
|
||||
registerData.id,
|
||||
previousHostInfo?.name ?? "",
|
||||
registerData.version,
|
||||
this.plugins,
|
||||
true,
|
||||
remoteAddress,
|
||||
previousHostInfo?.publicAddress,
|
||||
previousHostInfo?.tokenValidAfter,
|
||||
0,
|
||||
false,
|
||||
);
|
||||
// Hosts are only created by approving them, WsServer rejects hosts without a record.
|
||||
const record = this._controller.hosts.getMutable(registerData.id);
|
||||
if (!record) {
|
||||
throw new Error(`Host ${registerData.id} is not registered`);
|
||||
}
|
||||
record.version = registerData.version;
|
||||
record.plugins = this.plugins;
|
||||
record.connected = true;
|
||||
record.remoteAddress = remoteAddress;
|
||||
this.info = record;
|
||||
this._controller.hosts.set(this.info);
|
||||
|
||||
this._checkPluginVersions();
|
||||
@@ -71,7 +68,7 @@ export default class HostConnection extends BaseConnection {
|
||||
this._controller.instances.records.setMany(instances);
|
||||
|
||||
this.info.connected = false;
|
||||
this._controller.hosts.set(this.info);
|
||||
this._saveInfo();
|
||||
});
|
||||
|
||||
this.handle(lib.GetFactorioCredentialsRequest, this.handleGetFactorioCredentialsRequest.bind(this));
|
||||
@@ -175,10 +172,17 @@ export default class HostConnection extends BaseConnection {
|
||||
return {};
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
}
|
||||
|
||||
async handleHostInfoUpdateEvent(event: lib.HostInfoUpdateEvent) {
|
||||
this.info.name = event.update.name;
|
||||
this.info.publicAddress = event.update.publicAddress;
|
||||
this._controller.hosts.set(this.info);
|
||||
this._saveInfo();
|
||||
}
|
||||
|
||||
async handleInstanceStatusChangedEvent(request: lib.InstanceStatusChangedEvent) {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
import type Controller from "./Controller.js";
|
||||
|
||||
import crypto from "crypto";
|
||||
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;
|
||||
|
||||
/** Time a request is kept after the last poll from the installer */
|
||||
export const pollTimeoutMs = 30e3;
|
||||
/** Maximum time a request can stay pending */
|
||||
export const maxPendingMs = 60 * 60e3;
|
||||
/** Maximum number of pending requests in total */
|
||||
export const maxPending = 50;
|
||||
/** Maximum number of pending requests from one address */
|
||||
export const maxPendingPerAddress = 3;
|
||||
/** Maximum number of requests created from one address per minute */
|
||||
export const maxCreatesPerMinute = 10;
|
||||
/** Maximum length of a host name */
|
||||
export const maxNameLength = 100;
|
||||
/** Control and bidirectional override characters refused in host names */
|
||||
const nameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u;
|
||||
|
||||
/** Result of an approved request, sent to the installer */
|
||||
export interface HostPairingResult {
|
||||
hostId: number,
|
||||
token: string,
|
||||
name: string,
|
||||
}
|
||||
|
||||
/** Error with an HTTP status code to respond to the installer with */
|
||||
export class HostPairingError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status: number,
|
||||
/** Seconds to wait before trying again, for status 429 */
|
||||
public retryAfter?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
interface PairingRequest {
|
||||
/** Secret the installer polls with, never shown to users */
|
||||
secret: string,
|
||||
details: lib.HostPairingDetails,
|
||||
/** Address with IPv6 addresses grouped by /64, used for limits */
|
||||
addressKey: string,
|
||||
lastPollMs: number,
|
||||
state: "pending" | "approving" | "approved" | "rejected",
|
||||
result?: HostPairingResult,
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips the IPv4 mapped prefix and groups IPv6 addresses by their /64
|
||||
*
|
||||
* @param address - Address to make a key for
|
||||
* @returns key used to count requests from an address.
|
||||
*/
|
||||
export function addressKey(address: string) {
|
||||
if (address.startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
|
||||
return address.slice(7);
|
||||
}
|
||||
if (!net.isIPv6(address)) {
|
||||
return address;
|
||||
}
|
||||
const [head, tail = ""] = address.split("::");
|
||||
const headParts = head ? head.split(":") : [];
|
||||
const tailParts = tail ? tail.split(":") : [];
|
||||
const missing = 8 - headParts.length - tailParts.length;
|
||||
const parts = address.includes("::")
|
||||
? [...headParts, ...new Array(missing).fill("0"), ...tailParts]
|
||||
: headParts;
|
||||
return `${parts.slice(0, 4).map(part => part.toLowerCase().replace(/^0+(?=.)/, "")).join(":")}::/64`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a pairing code typed by a user
|
||||
*
|
||||
* @param code - Code as typed, may contain dashes and lower case letters.
|
||||
* @returns code formatted as shown by the installer.
|
||||
*/
|
||||
export function normaliseCode(code: string) {
|
||||
const plain = code.toUpperCase().replace(/[^0-9A-Z]/g, "");
|
||||
return `${plain.slice(0, 3)}-${plain.slice(3)}`;
|
||||
}
|
||||
|
||||
function generateCode() {
|
||||
let code = "";
|
||||
for (let i = 0; i < codeLength; i++) {
|
||||
code += codeAlphabet[crypto.randomInt(codeAlphabet.length)];
|
||||
}
|
||||
return normaliseCode(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps track of requests from host installers to join the cluster
|
||||
*
|
||||
* Requests only live in memory, and only while the installer keeps polling
|
||||
* for the result.
|
||||
*/
|
||||
export default class HostPairingManager {
|
||||
/** Pending requests by code, broadcast to subscribed control links */
|
||||
requests = new lib.SubscribableDatastore<lib.HostPairingDetails>();
|
||||
private _bySecret = new Map<string, PairingRequest>();
|
||||
private _byCode = new Map<string, PairingRequest>();
|
||||
/** Creation times of recent requests by address key */
|
||||
private _recentCreates = new Map<string, number[]>();
|
||||
private _pruneInterval?: ReturnType<typeof setInterval>;
|
||||
|
||||
constructor(
|
||||
private _controller: Controller,
|
||||
) { }
|
||||
|
||||
start() {
|
||||
this._pruneInterval = setInterval(() => this.prune(), 5e3);
|
||||
this._pruneInterval.unref();
|
||||
}
|
||||
|
||||
stop() {
|
||||
clearInterval(this._pruneInterval);
|
||||
this._pruneInterval = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check and trim a host name given by an installer or a user
|
||||
*
|
||||
* @param name - Name to check.
|
||||
* @returns the trimmed name.
|
||||
*/
|
||||
static validateName(name: unknown) {
|
||||
if (typeof name !== "string" || !name.trim()) {
|
||||
throw new HostPairingError("Host name is required", 400);
|
||||
}
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length > maxNameLength) {
|
||||
throw new HostPairingError(`Host name must be at most ${maxNameLength} characters`, 400);
|
||||
}
|
||||
// Names come from unauthenticated requests and are printed to terminals and logs.
|
||||
if (nameControlCharacters.test(trimmed)) {
|
||||
throw new HostPairingError("Host name may not contain control characters", 400);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an approved host with a new id and token
|
||||
*
|
||||
* The host record is saved to disk before this returns.
|
||||
*
|
||||
* @param name - Name of the host.
|
||||
* @returns the id, token and name of the new host.
|
||||
*/
|
||||
async createHost(name: string): Promise<HostPairingResult> {
|
||||
const hosts = this._controller.hosts;
|
||||
let hostId;
|
||||
do {
|
||||
hostId = crypto.randomInt(1, 2 ** 31);
|
||||
} while (hosts.has(hostId));
|
||||
|
||||
const record = new HostRecord(
|
||||
hostId, name, "", new Map(), false, "", "", Math.floor(Date.now() / 1000),
|
||||
);
|
||||
hosts.set(record);
|
||||
try {
|
||||
await hosts.save();
|
||||
} catch (err) {
|
||||
hosts.delete(record);
|
||||
throw err;
|
||||
}
|
||||
return { hostId, token: this._controller.generateHostToken(hostId), name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pending request
|
||||
*
|
||||
* @param name - Name the installer asked for.
|
||||
* @param version - Version of the installer.
|
||||
* @param remoteAddress - Address the request came from.
|
||||
* @returns the secret to poll with and the code to show the user.
|
||||
*/
|
||||
create(name: string, version: string, remoteAddress: string) {
|
||||
this.prune();
|
||||
const key = addressKey(remoteAddress);
|
||||
const now = Date.now();
|
||||
const recent = (this._recentCreates.get(key) ?? []).filter(ms => ms > now - 60e3);
|
||||
if (recent.length >= maxCreatesPerMinute) {
|
||||
throw new HostPairingError(
|
||||
"Too many requests from this address", 429, Math.ceil((recent[0] + 60e3 - now) / 1000),
|
||||
);
|
||||
}
|
||||
const pendingFromAddress = [...this._bySecret.values()].filter(
|
||||
request => request.addressKey === key && request.state === "pending"
|
||||
).length;
|
||||
if (pendingFromAddress >= maxPendingPerAddress) {
|
||||
throw new HostPairingError("Too many pending requests from this address", 429, 30);
|
||||
}
|
||||
if (this.requests.size >= maxPending) {
|
||||
throw new HostPairingError("Too many pending requests", 429, 30);
|
||||
}
|
||||
recent.push(now);
|
||||
this._recentCreates.set(key, recent);
|
||||
|
||||
let code;
|
||||
do {
|
||||
code = generateCode();
|
||||
} while (this._byCode.has(code));
|
||||
|
||||
const request: PairingRequest = {
|
||||
secret: crypto.randomBytes(32).toString("base64url"),
|
||||
details: new lib.HostPairingDetails(code, name, remoteAddress, version, now),
|
||||
addressKey: key,
|
||||
lastPollMs: now,
|
||||
state: "pending",
|
||||
};
|
||||
this._bySecret.set(request.secret, request);
|
||||
this._byCode.set(code, request);
|
||||
this.requests.set(request.details);
|
||||
logger.verbose(`Host pairing request ${code} for "${name}" from ${remoteAddress}`);
|
||||
return { requestId: request.secret, code };
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll for the result of a request
|
||||
*
|
||||
* @param secret - Request id returned when the request was created.
|
||||
* @returns the result if the request was approved, or null if still pending.
|
||||
*/
|
||||
poll(secret: string): HostPairingResult | null {
|
||||
this.prune();
|
||||
const request = this._bySecret.get(secret);
|
||||
if (!request) {
|
||||
throw new HostPairingError("Request not found", 404);
|
||||
}
|
||||
request.lastPollMs = Date.now();
|
||||
if (request.state === "approved") {
|
||||
this._remove(request);
|
||||
return request.result!;
|
||||
}
|
||||
if (request.state === "rejected") {
|
||||
this._remove(request);
|
||||
throw new HostPairingError("Request was rejected", 403);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a pending request
|
||||
*
|
||||
* @param secret - Request id returned when the request was created.
|
||||
*/
|
||||
cancel(secret: string) {
|
||||
const request = this._bySecret.get(secret);
|
||||
if (request && request.state === "pending") {
|
||||
logger.verbose(`Host pairing request ${request.details.code} cancelled by the installer`);
|
||||
this._remove(request);
|
||||
}
|
||||
}
|
||||
|
||||
private _pending(code: string) {
|
||||
this.prune();
|
||||
const request = this._byCode.get(normaliseCode(code));
|
||||
if (!request || request.state !== "pending") {
|
||||
throw new lib.NotFoundError(`No pending host request with code ${code}`);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Approve a pending request, creating the host
|
||||
*
|
||||
* @param code - Code of the request.
|
||||
* @param name - Name to give the host, defaults to the requested name.
|
||||
* @param approvedBy - Name of the user approving it, for logging.
|
||||
* @returns the id of the new host.
|
||||
*/
|
||||
async approve(code: string, name: string | undefined, approvedBy: string) {
|
||||
const request = this._pending(code);
|
||||
let hostName;
|
||||
try {
|
||||
hostName = name === undefined ? request.details.name : HostPairingManager.validateName(name);
|
||||
} catch (err: any) {
|
||||
throw new lib.ValidationError(err.message);
|
||||
}
|
||||
|
||||
request.state = "approving";
|
||||
let result;
|
||||
try {
|
||||
result = await this.createHost(hostName);
|
||||
} catch (err) {
|
||||
request.state = "pending";
|
||||
throw err;
|
||||
}
|
||||
|
||||
request.state = "approved";
|
||||
request.result = result;
|
||||
this.requests.delete(request.details);
|
||||
logger.audit(
|
||||
`User ${approvedBy} approved host ${result.name} (${result.hostId}) with code ` +
|
||||
`${request.details.code} from ${request.details.remoteAddress}`
|
||||
);
|
||||
return result.hostId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject a pending request
|
||||
*
|
||||
* @param code - Code of the request.
|
||||
* @param rejectedBy - Name of the user rejecting it, for logging.
|
||||
*/
|
||||
reject(code: string, rejectedBy: string) {
|
||||
const request = this._pending(code);
|
||||
request.state = "rejected";
|
||||
this.requests.delete(request.details);
|
||||
logger.audit(
|
||||
`User ${rejectedBy} rejected host ${request.details.name} with code ` +
|
||||
`${request.details.code} from ${request.details.remoteAddress}`
|
||||
);
|
||||
}
|
||||
|
||||
private _remove(request: PairingRequest) {
|
||||
this._bySecret.delete(request.secret);
|
||||
this._byCode.delete(request.details.code);
|
||||
if (this.requests.has(request.details.code)) {
|
||||
this.requests.delete(request.details);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove requests the installer stopped polling for or that waited too long */
|
||||
prune() {
|
||||
const now = Date.now();
|
||||
for (const request of this._bySecret.values()) {
|
||||
if (request.state === "approving") {
|
||||
continue;
|
||||
}
|
||||
const expired = now - request.lastPollMs > pollTimeoutMs
|
||||
|| (request.state === "pending" && now - request.details.createdAtMs > maxPendingMs);
|
||||
if (!expired) {
|
||||
continue;
|
||||
}
|
||||
if (request.state === "approved") {
|
||||
logger.warn(
|
||||
`Approved host ${request.result!.name} (${request.result!.hostId}) was never picked up ` +
|
||||
"by its installer, revoke it on the hosts page if it is not needed"
|
||||
);
|
||||
}
|
||||
this._remove(request);
|
||||
}
|
||||
for (const [key, times] of this._recentCreates) {
|
||||
if (!times.some(ms => ms > now - 60e3)) {
|
||||
this._recentCreates.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -264,7 +264,10 @@ ${err.stack}`
|
||||
}
|
||||
|
||||
let host = this.controller.hosts.get(data.id);
|
||||
if (!tokenPayload.iat || tokenPayload.iat < (host?.tokenValidAfter ?? 0)) {
|
||||
if (!host) {
|
||||
throw new Error("host is not registered, run the installer again in the host directory");
|
||||
}
|
||||
if (!tokenPayload.iat || tokenPayload.iat < host.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
} catch (err: any) {
|
||||
@@ -303,6 +306,13 @@ ${err.stack}`
|
||||
);
|
||||
}
|
||||
|
||||
// The host may have been revoked while waiting for the old connection to close.
|
||||
if (!this.controller.hosts.has(data.id)) {
|
||||
wsRejectedConnectionsCounter.inc();
|
||||
socket.close(lib.ConnectionClosed.Unauthorized, "Authentication failed: host was revoked");
|
||||
return;
|
||||
}
|
||||
|
||||
let [connector, sessionToken] = this.createSession(new lib.Address(lib.Address.host, data.id));
|
||||
|
||||
// Handle close before HostConnection does. This avoids a host
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Application, Request, Response } from "express";
|
||||
import express, { type Application, type Request, type Response } from "express";
|
||||
import Controller from "./Controller.js";
|
||||
import HostPairingManager, { HostPairingError } from "./HostPairingManager.js";
|
||||
|
||||
import busboy from "busboy";
|
||||
import crypto from "crypto";
|
||||
@@ -215,19 +216,7 @@ function validateUserToken(req: Request, res: Response, next: any) {
|
||||
}
|
||||
|
||||
try {
|
||||
const tokenPayload = jwt.verify(token, req.app.locals.controller.authSecret, { audience: "user" });
|
||||
if (typeof tokenPayload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
let user = req.app.locals.controller.users.getByName(tokenPayload.user);
|
||||
if (!user) {
|
||||
throw new Error("invalid user");
|
||||
}
|
||||
if (!tokenPayload.iat || tokenPayload.iat < user.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
res.locals.user = user;
|
||||
|
||||
res.locals.user = userFromToken(req.app.locals.controller, token);
|
||||
} catch (err) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
@@ -236,6 +225,118 @@ 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)) {
|
||||
return false;
|
||||
}
|
||||
if (err.retryAfter !== undefined) {
|
||||
res.set("Retry-After", String(err.retryAfter));
|
||||
}
|
||||
res.status(err.status).json({ error: err.message });
|
||||
return true;
|
||||
}
|
||||
|
||||
// Checks recovery mode and the request id for the pairing endpoints, returns false if responded to.
|
||||
function checkHostPairingRequest(req: Request, res: Response, needsRequestId: boolean) {
|
||||
if (req.app.locals.controller.recoveryMode) {
|
||||
res.status(503).json({ error: "Controller is in recovery mode" });
|
||||
return false;
|
||||
}
|
||||
if (needsRequestId && typeof req.body?.requestId !== "string") {
|
||||
res.status(400).json({ error: "requestId is required" });
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Request from an installer for a host to join the cluster.
|
||||
async function createHostPairing(req: Request, res: Response) {
|
||||
if (!checkHostPairingRequest(req, res, false)) {
|
||||
return;
|
||||
}
|
||||
const controller = req.app.locals.controller;
|
||||
const remoteAddress = controller.wsServer.remoteAddr(req);
|
||||
try {
|
||||
const name = HostPairingManager.validateName(req.body?.name);
|
||||
const version = typeof req.body?.version === "string" ? req.body.version.slice(0, 64) : "";
|
||||
|
||||
// A user allowed to approve hosts can skip the wait by passing their token.
|
||||
const token = getAccessToken(req);
|
||||
if (token !== undefined) {
|
||||
let user;
|
||||
try {
|
||||
user = userFromToken(controller, token);
|
||||
} catch (err) {
|
||||
res.status(401).json({ error: "Invalid user token" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
user.checkPermission("core.host.approve");
|
||||
} catch (err) {
|
||||
res.status(403).json({ error: `User ${user.name} is not allowed to approve hosts` });
|
||||
return;
|
||||
}
|
||||
const result = await controller.hostPairing.createHost(name);
|
||||
logger.audit(
|
||||
`User ${user.name} approved host ${result.name} (${result.hostId}) from ${remoteAddress} ` +
|
||||
"with their token"
|
||||
);
|
||||
res.status(200).json(result);
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(202).json(controller.hostPairing.create(name, version, remoteAddress));
|
||||
} catch (err) {
|
||||
if (!sendHostPairingError(res, err)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Poll from an installer for the result of its request.
|
||||
function pollHostPairing(req: Request, res: Response) {
|
||||
if (!checkHostPairingRequest(req, res, true)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = req.app.locals.controller.hostPairing.poll(req.body.requestId);
|
||||
if (result) {
|
||||
res.status(200).json(result);
|
||||
} else {
|
||||
res.status(202).json({ status: "pending" });
|
||||
}
|
||||
} catch (err) {
|
||||
if (!sendHostPairingError(res, err)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel from an installer that stopped waiting.
|
||||
function cancelHostPairing(req: Request, res: Response) {
|
||||
if (!checkHostPairingRequest(req, res, true)) {
|
||||
return;
|
||||
}
|
||||
req.app.locals.controller.hostPairing.cancel(req.body.requestId);
|
||||
res.sendStatus(204);
|
||||
}
|
||||
|
||||
// Handle an uploaded export package.
|
||||
async function uploadExport(req: Request, res: Response) {
|
||||
if (req.get("Content-Type") !== "application/zip") {
|
||||
@@ -686,6 +787,21 @@ export function addRouteHandlers(app: Application) {
|
||||
);
|
||||
app.get("/api/plugins", getPlugins);
|
||||
app.get("/api/cluster-name", getClusterName);
|
||||
// Set before parsing so errors from the body parser and token check are not cached either.
|
||||
const noStore = (req: Request, res: Response, next: any) => {
|
||||
res.set("Cache-Control", "no-store");
|
||||
next();
|
||||
};
|
||||
const pairingJson = express.json({ limit: "4kb" });
|
||||
app.post("/api/host-pairing",
|
||||
noStore, pairingJson,
|
||||
(req:Request, res:Response, next:any) => createHostPairing(req, res).catch(next)
|
||||
);
|
||||
app.post("/api/host-pairing/poll", noStore, pairingJson, pollHostPairing);
|
||||
app.post("/api/host-pairing/cancel", noStore, pairingJson, cancelHostPairing);
|
||||
app.get("/api/host-pairing/check", noStore, validateHostToken, (req: Request, res: Response) => {
|
||||
res.json({ valid: true });
|
||||
});
|
||||
app.put("/api/upload-export",
|
||||
validateHostToken,
|
||||
(req:Request, res:Response, next:any) => uploadExport(req, res).catch(next)
|
||||
|
||||
Reference in new issue
Block a user