Add user and permission system

Add users, roles and permissions and rework the authentication to use
separate user and slave tokens for control and slave connections
respectively.

Add commands for listing permissions, roles and users, and creating,
editing and deleting roles and users.
This commit is contained in:
Hornwitser committed 2020-06-15 16:47:15 +02:00
1 parent 2acf57d23d
commit cf6f2cb70a
20 files changed
+1511 -153

No files matched your search

-48
View File
@@ -1,48 +0,0 @@
const jwt = require('jsonwebtoken');
let authSecret = null;
function setAuthSecret(secret) {
authSecret = secret;
}
function middleware(req, res, next) {
// This should not happen
if (!authSecret) {
return res.status(500).send({ auth: false, message: 'Secret not set', endpoint: req.route.path });
}
var token = req.headers['x-access-token'];
if (!token) {
return res.status(401).send({ auth: false, message: 'No token provided.', endpoint: req.route.path });
}
jwt.verify(token, authSecret, function(err, decoded) {
if (err) {
return res.status(401).send({ auth: false, message: 'Failed to authenticate token.', endpoint: req.route.path });
}
next();
});
}
async function check(token) {
return new Promise((resolve, reject) => {
// This should not happen
if (!authSecret) {
resolve({ ok: false, msg: 'Secret not set' });
}
jwt.verify(token, authSecret, function(err, decoded) {
if (err) {
resolve({ok:false, msg:err})
} else {
resolve({ok:true, msg:"Successfully authenticated"});
}
});
});
}
module.exports = {
setAuthSecret,
middleware,
check,
};
+12 -4
View File
@@ -39,11 +39,11 @@ MasterGroup.define({
initial_value: 8443,
});
MasterGroup.define({
name: "web_root",
title: "Web Root",
description: "Sub-path to where the web interface is hosted. Needed when proxying the web interface.",
name: "external_address",
title: "External Address",
description: "Public facing address the master server is hosted on.",
type: "string",
initial_value: "/",
optional: true,
});
MasterGroup.define({
name: "tls_certificate",
@@ -97,6 +97,14 @@ MasterGroup.define({
type: "number",
initial_value: 30,
});
MasterGroup.define({
name: "default_role_id",
title: "Default role",
description: "ID of role assigned by default to new users",
type: "number",
optional: true,
initial_value: 1,
});
MasterGroup.finalize();
/**
+208 -1
View File
@@ -43,6 +43,9 @@ class Request extends Message {
* @param {Array<string>} links -
* Links this request is valid on. Takes an array of strings
* containing "<source>-<target>" specifications.
* @param {?string} permission -
* Permission required to send this request. Only applies to
* requests sent from control to master.
* @param {?string} forwardTo -
* Optional target to forward this request to. 'instance' add
* instance_id into the requestProperties and forward to the given
@@ -56,16 +59,24 @@ class Request extends Message {
* this requst.
*/
constructor({
type, links, forwardTo = null, requestProperties = {}, responseProperties = {}
type, permission, links, forwardTo = null, requestProperties = {}, responseProperties = {},
}) {
super();
this.type = type;
this.links = links;
this.permission = permission || null;
this.forwardTo = forwardTo;
this.requestType = type + '_request';
this.responseType = type + '_response';
if (permission === undefined && links.includes("control-master")) {
throw new Error(`permission is required for ${this.type} request over control-master links`);
}
if (permission && !links.includes("control-master")) {
throw new Error(`permission is not allowed on ${this.type} request as it is not over control-master link`);
}
if (forwardTo === 'instance') {
requestProperties = Object.assign(
{"instance_id": { type: "integer" }}, requestProperties
@@ -158,6 +169,15 @@ class Request extends Message {
throw new Error(`Missing handler for ${this.requestType} on ${link.source}-${link.target} link`);
}
// Check permission if this is a handler for a control connection on the master
if (this.permission !== null && `${link.source}-${link.target}` === "master-control") {
let origHandler = handler;
handler = async function(message, request) {
this.user.checkPermission(request.permission);
return await origHandler.call(this, message, request);
};
}
link.setHandler(this.requestType, message => {
handler.call(link, message, this).then(response => {
if (response === undefined) {
@@ -213,6 +233,7 @@ let wsLinks = ["master-control", "control-master", "master-slave", "slave-master
messages.prepareDisconnect = new Request({
type: "prepare_disconnect",
links: wsLinks,
permission: null,
});
messages.prepareMasterDisconnect = new Request({
@@ -223,11 +244,13 @@ messages.prepareMasterDisconnect = new Request({
messages.ping = new Request({
type: "ping",
links: wsLinks,
permission: null,
});
messages.debugDumpWs = new Request({
type: "debug_dump_ws",
links: ["control-master"],
permission: "core.debug.dump_ws",
});
@@ -235,6 +258,7 @@ messages.debugDumpWs = new Request({
messages.listSlaves = new Request({
type: 'list_slaves',
links: ['control-master'],
permission: "core.slave.list",
responseProperties: {
"list": {
type: "array",
@@ -256,6 +280,7 @@ messages.listSlaves = new Request({
messages.listInstances = new Request({
type: 'list_instances',
links: ['control-master'],
permission: "core.instance.list",
responseProperties: {
"list": {
type: "array",
@@ -272,9 +297,36 @@ messages.listInstances = new Request({
},
});
messages.generateSlaveToken = new Request({
type: "generate_slave_token",
links: ["control-master"],
permission: "core.slave.generate_token",
requestProperties: {
"slave_id": { type: "integer" },
},
responseProperties: {
"token": { type: "string" },
},
});
messages.createSlaveConfig = new Request({
type: "create_slave_config",
links: ["control-master"],
permission: "core.slave.create_config",
requestProperties: {
"id": { type: ["integer", "null"] },
"name": { type: ["string", "null"] },
"generate_token": { type: "boolean" },
},
responseProperties: {
"serialized_config": { type: "object" },
},
});
messages.setInstanceOutputSubscriptions = new Request({
type: 'set_instance_output_subscriptions',
links: ['control-master'],
permission: "core.instance.follow_log",
requestProperties: {
"instance_ids": {
type: "array",
@@ -286,6 +338,7 @@ messages.setInstanceOutputSubscriptions = new Request({
messages.createInstance = new Request({
type: 'create_instance',
links: ['control-master'],
permission: "core.instance.create",
requestProperties: {
"serialized_config": { type: "object" },
},
@@ -294,6 +347,7 @@ messages.createInstance = new Request({
messages.getInstanceConfig = new Request({
type: "get_instance_config",
links: ["control-master"],
permission: "core.instance.get_config",
requestProperties: {
"instance_id": { type: "integer" },
},
@@ -305,6 +359,7 @@ messages.getInstanceConfig = new Request({
messages.setInstanceConfigField = new Request({
type: "set_instance_config_field",
links: ["control-master"],
permission: "core.instance.update_config",
requestProperties: {
"instance_id": { type: "integer" },
"field": { type: "string" },
@@ -315,6 +370,7 @@ messages.setInstanceConfigField = new Request({
messages.setInstanceConfigProp = new Request({
type: "set_instance_config_prop",
links: ["control-master"],
permission: "core.instance.update_config",
requestProperties: {
"instance_id": { type: "integer" },
"field": { type: "string" },
@@ -326,6 +382,7 @@ messages.setInstanceConfigProp = new Request({
messages.assignInstanceCommand = new Request({
type: 'assign_instance_command',
links: ['control-master'],
permission: "core.instance.assign",
requestProperties: {
"instance_id": { type: "integer" },
"slave_id": { type: "integer" },
@@ -344,6 +401,7 @@ messages.assignInstance = new Request({
messages.startInstance = new Request({
type: 'start_instance',
links: ['control-master', 'master-slave', 'slave-instance'],
permission: "core.instance.start",
requestProperties: {
"save": { type: ["string", "null"] },
},
@@ -353,30 +411,35 @@ messages.startInstance = new Request({
messages.createSave = new Request({
type: 'create_save',
links: ['control-master', 'master-slave', 'slave-instance'],
permission: "core.instance.create_save",
forwardTo: 'instance',
});
messages.exportData = new Request({
type: "export_data",
links: ["control-master", "master-slave", "slave-instance"],
permission: "core.instance.export_data",
forwardTo: "instance",
});
messages.stopInstance = new Request({
type: 'stop_instance',
links: ['control-master', 'master-slave', 'slave-instance'],
permission: "core.instance.stop",
forwardTo: 'instance',
});
messages.deleteInstance = new Request({
type: 'delete_instance',
links: ['control-master', 'master-slave'],
permission: "core.instance.delete",
forwardTo: 'instance',
});
messages.sendRcon = new Request({
type: 'send_rcon',
links: ['control-master', 'master-slave', 'slave-instance'],
permission: "core.instance.send_rcon",
forwardTo: 'instance',
requestProperties: {
"command": { type: "string" },
@@ -386,6 +449,139 @@ messages.sendRcon = new Request({
}
});
messages.listPermissions = new Request({
type: "list_permissions",
links: ["control-master"],
permission: "core.permission.list",
responseProperties: {
"list": {
type: "array",
items: {
additionalProperties: false,
required: ["name", "title", "description"],
properties: {
"name": { type: "string" },
"title": { type: "string" },
"description": { type: "string" },
},
},
},
},
});
messages.listRoles = new Request({
type: "list_roles",
links: ["control-master"],
permission: "core.role.list",
responseProperties: {
"list": {
type: "array",
items: {
additionalProperties: false,
required: ["id", "name", "description", "permissions"],
properties: {
"id": { type: "integer" },
"name": { type: "string" },
"description": { type: "string" },
"permissions": { type: "array", items: { type: "string" }},
},
},
},
},
});
messages.createRole = new Request({
type: "create_role",
links: ["control-master"],
permission: "core.role.create",
requestProperties: {
"name": { type: "string" },
"description": { type: "string" },
"permissions": { type: "array", items: { type: "string" }},
},
responseProperties: {
"id": { type: "integer" },
}
});
messages.updateRole = new Request({
type: "update_role",
links: ["control-master"],
permission: "core.role.update",
requestProperties: {
"id": { type: "integer" },
"name": { type: "string" },
"description": { type: "string" },
"permissions": { type: "array", items: { type: "string" }},
},
});
messages.grantDefaultRolePermissions = new Request({
type: "grant_default_role_permissions",
links: ["control-master"],
permission: "core.role.update",
requestProperties: {
"id": { type: "integer" },
},
});
messages.deleteRole = new Request({
type: "delete_role",
links: ["control-master"],
permission: "core.role.delete",
requestProperties: {
"id": { type: "integer" },
},
});
messages.listUsers = new Request({
type: "list_users",
links: ["control-master"],
permission: "core.user.list",
responseProperties: {
"list": {
type: "array",
items: {
additionalProperties: false,
required: ["name", "roles", "instances"],
properties: {
"name": { type: "string" },
"roles": { type: "array", items: { type: "integer" }},
"instances": { type: "array", items: { type: "integer" }},
},
},
},
},
});
messages.createUser = new Request({
type: "create_user",
links: ["control-master"],
permission: "core.user.create",
requestProperties: {
"name": { type: "string" },
},
});
messages.updateUserRoles = new Request({
type: "update_user_roles",
links: ["control-master"],
permission: "core.user.update_roles",
requestProperties: {
"name": { type: "string" },
"roles": { type: "array", items: { type: "integer" }},
},
});
messages.deleteUser = new Request({
type: "delete_user",
links: ["control-master"],
permission: "core.user.delete",
requestProperties: {
"name": { type: "string" },
},
});
messages.getMetrics = new Request({
type: 'statistics_exporter:get_metrics',
links: ['master-slave', 'slave-instance'],
@@ -628,6 +824,17 @@ messages.masterConnectionEvent = new Event({
},
});
messages.playerEvent = new Event({
type: "player_event",
links: ["instance-slave", "slave-master"],
forwardTo: "master",
eventProperties: {
"instance_id": { type: "integer" },
"type": { type: "string", enum: ["join", "leave"] },
"name": { type: "string" },
},
});
/**
* Attaches all requests and events to the given link
*
+24
View File
@@ -158,6 +158,17 @@ class BaseInstancePlugin {
* The connection to the slave preparing to disconnect.
*/
async onPrepareMasterDisconnect(connection) { }
/**
* Called when a player joins or leaves the game
*
* Invoked when a player either joins or leaves the instance.
*
* @param {Object} event - Information about the event.
* @param {string} event.type - Either "join" or "leave".
* @param {string} event.name - Name of the player that joined/left.
*/
async onPlayerEvent(event) { }
}
/**
@@ -258,6 +269,19 @@ class BaseMasterPlugin {
*/
async onPrepareSlaveDisconnect(connection) { }
/**
* Called when a player joins or leaves an instance
*
* Invoked when a player either joins or leaves an instance in the
* cluster.
*
* @param {Object} instance - the instance it occured on.
* @param {Object} event - Information about the event.
* @param {string} event.type - Either "join" or "leave".
* @param {string} event.name - Name of the player that joined/left.
*/
async onPlayerEvent(instance, event) { }
/**
* Broadcast event to all connected slaves
*
+399
View File
@@ -0,0 +1,399 @@
/**
* User and permissions library
*
* Defines data types for users, roles and permissions.
*
* @author Hornwitser
* @module
*/
"use strict";
const jwt = require("jsonwebtoken");
/**
* Represents a permission that can be granted
* @static
*/
class Permission {
constructor(name, title, description, grantByDefault) {
this.name = name;
this.title = title;
this.description = description;
this.grantByDefault = grantByDefault;
}
}
const permissions = new Map();
/**
* Define a new user permission for Clusterio
*
* Defines a permission for use in Clusterio. Defined permissions can be
* granted to roles, and checked on users. Name should be `lower_case`
* style and start with the plugin name followed by a dot.
*
* @param {Object} def - The definition for the permission.
* @param {string} def.name - The internal name for the permission.
* @param {string} def.title - User facing name for permission.
* @param {string} def.description - User facing description.
* @param {boolean} def.grantByDefault -
* If true this role is granted by the generated Player role by default.
*
*/
function definePermission({ name, title, description, grantByDefault=false }) {
if (typeof name !== "string" || !name.length) {
throw new Error("Expected name to be a non-empty string");
}
if (typeof title !== "string" || !title.length) {
throw new Error("Expected title to be a non-empty string");
}
if (typeof description !== "string" || !description.length) {
throw new Error("Expected description to be a non-empty string");
}
if (typeof grantByDefault !== "boolean") {
throw new Error("Expected grantByDefault to be a boolean");
}
if (permissions.has(name)) {
throw new Error(`Permission '${name}' is already defined`)
}
permissions.set(name, new Permission(name, title, description, grantByDefault));
}
/**
* Represents a collection of granted permissions
* @static
*/
class Role {
constructor({ id, name, description, permissions }) {
this.id = id;
this.name = name;
this.description = description;
this.permissions = new Set(permissions);
}
serialize() {
return {
id: this.id,
name: this.name,
description: this.description,
permissions: [...this.permissions],
};
}
grantDefaultPermissions() {
for (let permission of permissions.values()) {
if (permission.grantByDefault) {
this.permissions.add(permission.name);
}
}
}
}
/**
* Ensure the default admin role has full access
*
* Ensures the role with id 0 exisits and has the core.admin permission.
*
* @returns {module:lib/permission.Role} the default admin role
* @static
*/
function ensureDefaultAdminRole(roles) {
let admin = roles.get(0);
if (!admin) {
admin = new Role({ id: 0, name: "Admin", description: "Cluster wide administrator." });
roles.set(0, admin);
}
admin.permissions.add("core.admin");
return admin;
}
/**
* Ensure the default player role has default accesses
*
* Ensures the role with id 1 exists and has all the permissions that are
* assigned by default. Note that this may not be the same role as the one
* that is assigned to new users by default.
*
* @returns {module:lib/permission.Role} the default player role
* @static
*/
function ensureDefaultPlayerRole(roles) {
let player = roles.get(1);
if (!player) {
player = new Role({ id: 1, name: "Player", description: "Default player role." });
roles.set(1, player);
}
player.grantDefaultPermissions();
}
/**
* Represeents a user in the cluster
*
* Holds data about a Factorio user in the cluster.
* @static
*/
class User {
constructor({ name, roles, tokenValidAfter }, loadedRoles) {
/**
* Factorio user name.
* @type {string}
*/
this.name = name;
/**
* Instances this user is online on.
* @type {Set<number>}
*/
this.instances = new Set();
/**
* Unix time in seconds the user token must be issued after to be valid.
* @type {number}
*/
this.tokenValidAfter = tokenValidAfter || 0;
/**
* Roles this user has
* @type {Set<module:lib/permissions.Role}
*/
this.roles = new Set();
if (roles) {
for (let roleId of roles) {
let role = loadedRoles.get(roleId);
if (role) {
this.roles.add(role);
}
}
}
}
serialize() {
let serialized = {
name: this.name,
roles: [...this.roles].map(role => role.id),
};
if (this.tokenValidAfter) {
serialized.tokenValidAfter = this.tokenValidAfter;
}
return serialized;
}
/**
* Generate access token for this user
*
* @param {string} secret - Secret to sign token with.
*/
createToken(secret) {
return jwt.sign({ aud: "user", user: this.name }, secret);
}
/**
* Invalidate current tokens for the user
*
* Sets the tokenValidAfter property to the current time, which causes
* all currently issued tokens for the user to become invalid.
*/
invalidateToken(secret) {
this.tokenValidAfter = Math.floor(Date.now() / 1000);
}
/**
* Check if a given permission is granted
*
* Checks the roles the user is member of for one that grants the given
* permission. If the permission is not granted for the user a
* "Permission denied" error is thrown.
*
* @throws {Error} if the user does noh have the given permission.
*/
checkPermission(permission) {
if (!permissions.has(permission)) {
throw new Error(`permission ${permission} does not exist`);
}
for (let role of this.roles) {
if (role.permissions.has("core.admin") || role.permissions.has(permission)) {
return;
}
}
throw new Error("Permission denied");
}
notifyJoin(instance_id) {
this.instances.add(instance_id);
User.onlineUsers.add(this);
}
notifyLeave(instance_id) {
this.instances.delete(instance_id);
if (!this.instances.size) {
User.onlineUsers.delete(this);
}
}
}
User.onlineUsers = new Set();
// Definitions for the built in permissions used in Clusterio.
// description should answer "this permission allows you to ___"
definePermission({
name: "core.admin",
title: "Administrator",
description: "Bypass all permission checks.",
});
definePermission({
name: "core.control.connect",
title: "Connect to WebSocket",
description: "Connect to the master's WebSocket control interface.",
grantByDefault: true,
});
definePermission({
name: "core.slave.list",
title: "List slaves",
description: "Get the full list of slaves in the cluster.",
grantByDefault: true,
});
definePermission({
name: "core.slave.generate_token",
title: "Generate slave token",
description: "Generate tokens for slaves to connect to the cluster with.",
});
definePermission({
name: "core.slave.create_config",
title: "Create slave config",
description: "Create slave configs via the master server.",
});
definePermission({
name: "core.instance.list",
title: "List instances",
description: "Get the full list of instances in the cluster.",
grantByDefault: true,
});
definePermission({
name: "core.instance.create",
title: "Create instance",
description: "Create new instances on the master server.",
});
definePermission({
name: "core.instance.get_config",
title: "Get instance config",
description: "Get the config of instances.",
});
definePermission({
name: "core.instance.update_config",
title: "Modify instance config",
description: "Modify the config or entries of the config for instances.",
});
definePermission({
name: "core.instance.assign",
title: "Assign instance",
description: "Assign or reassign instances to a slave.",
});
definePermission({
name: "core.instance.follow_log",
title: "Follow instance log",
description: "Listen for the stdout log of instances.",
});
definePermission({
name: "core.instance.create_save",
title: "Create new instance save",
description: "Create new savegames on instances.",
});
definePermission({
name: "core.instance.export_data",
title: "Export locale and icons",
description: "Export the the locale and icons from an instance and upload it to the master.",
});
definePermission({
name: "core.instance.start",
title: "Start instance",
description: "Start instances.",
});
definePermission({
name: "core.instance.stop",
title: "Stop instance",
description: "Stop instances.",
});
definePermission({
name: "core.instance.delete",
title: "Delete instance",
description: "Delete instances (includes config and all files stored like saves and logs).",
});
definePermission({
name: "core.instance.send_rcon",
title: "Send RCON",
description: "Send arbitrary RCON commands to instances.",
});
definePermission({
name: "core.permission.list",
title: "List permissions",
description: "Get the full list of permissions in the cluster.",
grantByDefault: true,
});
definePermission({
name: "core.role.list",
title: "List roles",
description: "Get the full list of roles and their permissions in the cluster.",
grantByDefault: true,
});
definePermission({
name: "core.role.create",
title: "Create role",
description: "Create new roles with permissions.",
});
definePermission({
name: "core.role.update",
title: "Update role",
description: "Edit existing roles including permissions they grant.",
});
definePermission({
name: "core.role.delete",
title: "Delete role",
description: "Permanently delete roles.",
});
definePermission({
name: "core.user.list",
title: "List users",
description: "Get the full list of users in the cluster.",
});
definePermission({
name: "core.user.create",
title: "Create users",
description: "Create user acounts with a given name.",
});
definePermission({
name: "core.user.update_roles",
title: "Update user roles",
description: "Add or remove any role to any user.",
});
definePermission({
name: "core.user.delete",
title: "Delete user",
description: "Delete users and all data stored for them.",
});
definePermission({
name: "core.debug.dump_ws",
title: "Dump WebSocket",
description: "Dump all WebSocket communicatation from the master.",
});
module.exports = {
Permission,
Role,
User,
permissions,
definePermission,
ensureDefaultAdminRole,
ensureDefaultPlayerRole,
};