access.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /**
  2. * Some Notes: This is a friggin complicated piece of code.
  3. *
  4. * "scope" in this file means "where did this token come from and what is using it", so 99% of the time
  5. * the "scope" is going to be "user" because it would be a user token. This is not to be confused with
  6. * the "role" which could be "user" or "admin". The scope in fact, could be "worker" or anything else.
  7. */
  8. import fs from "node:fs";
  9. import { dirname } from "node:path";
  10. import { fileURLToPath } from "node:url";
  11. import Ajv from "ajv/dist/2020.js";
  12. import _ from "lodash";
  13. import { access as logger } from "../logger.js";
  14. import proxyHostModel from "../models/proxy_host.js";
  15. import TokenModel from "../models/token.js";
  16. import userModel from "../models/user.js";
  17. import permsSchema from "./access/permissions.json" with { type: "json" };
  18. import roleSchema from "./access/roles.json" with { type: "json" };
  19. import errs from "./error.js";
  20. const __filename = fileURLToPath(import.meta.url);
  21. const __dirname = dirname(__filename);
  22. export default function (tokenString) {
  23. const Token = TokenModel();
  24. let tokenData = null;
  25. let initialised = false;
  26. const objectCache = {};
  27. let allowInternalAccess = false;
  28. let userRoles = [];
  29. let permissions = {};
  30. /**
  31. * Loads the Token object from the token string
  32. *
  33. * @returns {Promise}
  34. */
  35. this.init = async () => {
  36. if (initialised) {
  37. return;
  38. }
  39. if (!tokenString) {
  40. throw new errs.PermissionError("Permission Denied");
  41. }
  42. tokenData = await Token.load(tokenString);
  43. // At this point we need to load the user from the DB and make sure they:
  44. // - exist (and not soft deleted)
  45. // - still have the appropriate scopes for this token
  46. // This is only required when the User ID is supplied or if the token scope has `user`
  47. if (
  48. tokenData.attrs.id ||
  49. (typeof tokenData.scope !== "undefined" && _.indexOf(tokenData.scope, "user") !== -1)
  50. ) {
  51. // Has token user id or token user scope
  52. const user = await userModel
  53. .query()
  54. .where("id", tokenData.attrs.id)
  55. .andWhere("is_deleted", 0)
  56. .andWhere("is_disabled", 0)
  57. .allowGraph("[permissions]")
  58. .withGraphFetched("[permissions]")
  59. .first();
  60. if (user) {
  61. // make sure user has all scopes of the token
  62. // The `user` role is not added against the user row, so we have to just add it here to get past this check.
  63. user.roles.push("user");
  64. let ok = true;
  65. _.forEach(tokenData.scope, (scope_item) => {
  66. if (_.indexOf(user.roles, scope_item) === -1) {
  67. ok = false;
  68. }
  69. });
  70. if (!ok) {
  71. throw new errs.AuthError("Invalid token scope for User");
  72. }
  73. initialised = true;
  74. userRoles = user.roles;
  75. permissions = user.permissions;
  76. } else {
  77. throw new errs.AuthError("User cannot be loaded for Token");
  78. }
  79. }
  80. initialised = true;
  81. };
  82. /**
  83. * Fetches the object ids from the database, only once per object type, for this token.
  84. * This only applies to USER token scopes, as all other tokens are not really bound
  85. * by object scopes
  86. *
  87. * @param {String} objectType
  88. * @returns {Promise}
  89. */
  90. this.loadObjects = async (objectType) => {
  91. let objects = null;
  92. if (Token.hasScope("user")) {
  93. if (typeof tokenData.attrs.id === "undefined" || !tokenData.attrs.id) {
  94. throw new errs.AuthError("User Token supplied without a User ID");
  95. }
  96. const tokenUserId = tokenData.attrs.id ? tokenData.attrs.id : 0;
  97. if (typeof objectCache[objectType] !== "undefined") {
  98. objects = objectCache[objectType];
  99. } else {
  100. switch (objectType) {
  101. // USERS - should only return yourself
  102. case "users":
  103. objects = tokenUserId ? [tokenUserId] : [];
  104. break;
  105. // Proxy Hosts
  106. case "proxy_hosts": {
  107. const query = proxyHostModel
  108. .query()
  109. .select("id")
  110. .andWhere("is_deleted", 0);
  111. if (permissions.visibility === "user") {
  112. query.andWhere("owner_user_id", tokenUserId);
  113. }
  114. const rows = await query;
  115. objects = [];
  116. _.forEach(rows, (ruleRow) => {
  117. objects.push(ruleRow.id);
  118. });
  119. // enum should not have less than 1 item
  120. if (!objects.length) {
  121. objects.push(0);
  122. }
  123. break;
  124. }
  125. }
  126. objectCache[objectType] = objects;
  127. }
  128. }
  129. return objects;
  130. };
  131. /**
  132. * Creates a schema object on the fly with the IDs and other values required to be checked against the permissionSchema
  133. *
  134. * @param {String} permissionLabel
  135. * @returns {Object}
  136. */
  137. this.getObjectSchema = async (permissionLabel) => {
  138. const baseObjectType = permissionLabel.split(":").shift();
  139. const schema = {
  140. $id: "objects",
  141. description: "Actor Properties",
  142. type: "object",
  143. additionalProperties: false,
  144. properties: {
  145. user_id: {
  146. anyOf: [
  147. {
  148. type: "number",
  149. enum: [Token.get("attrs").id],
  150. },
  151. ],
  152. },
  153. scope: {
  154. type: "string",
  155. pattern: `^${Token.get("scope")}$`,
  156. },
  157. },
  158. };
  159. const result = await this.loadObjects(baseObjectType);
  160. if (typeof result === "object" && result !== null) {
  161. schema.properties[baseObjectType] = {
  162. type: "number",
  163. enum: result,
  164. minimum: 1,
  165. };
  166. } else {
  167. schema.properties[baseObjectType] = {
  168. type: "number",
  169. minimum: 1,
  170. };
  171. }
  172. return schema;
  173. };
  174. // here:
  175. return {
  176. token: Token,
  177. /**
  178. *
  179. * @param {Boolean} [allowInternal]
  180. * @returns {Promise}
  181. */
  182. load: async (allowInternal) => {
  183. if (tokenString) {
  184. return await Token.load(tokenString);
  185. }
  186. allowInternalAccess = allowInternal;
  187. return allowInternal || null;
  188. },
  189. reloadObjects: this.loadObjects,
  190. /**
  191. *
  192. * @param {String} permission
  193. * @param {*} [data]
  194. * @returns {Promise}
  195. */
  196. can: async (permission, data) => {
  197. if (allowInternalAccess === true) {
  198. return true;
  199. }
  200. try {
  201. await this.init();
  202. const objectSchema = await this.getObjectSchema(permission);
  203. const dataSchema = {
  204. [permission]: {
  205. data: data,
  206. scope: Token.get("scope"),
  207. roles: userRoles,
  208. permission_visibility: permissions.visibility,
  209. permission_proxy_hosts: permissions.proxy_hosts,
  210. permission_redirection_hosts: permissions.redirection_hosts,
  211. permission_dead_hosts: permissions.dead_hosts,
  212. permission_streams: permissions.streams,
  213. permission_access_lists: permissions.access_lists,
  214. permission_certificates: permissions.certificates,
  215. },
  216. };
  217. const permissionSchema = {
  218. $async: true,
  219. $id: "permissions",
  220. type: "object",
  221. additionalProperties: false,
  222. properties: {},
  223. };
  224. const rawData = fs.readFileSync(`${__dirname}/access/${permission.replace(/:/gim, "-")}.json`, {
  225. encoding: "utf8",
  226. });
  227. permissionSchema.properties[permission] = JSON.parse(rawData);
  228. const ajv = new Ajv({
  229. verbose: true,
  230. allErrors: true,
  231. breakOnError: true,
  232. coerceTypes: true,
  233. schemas: [roleSchema, permsSchema, objectSchema, permissionSchema],
  234. });
  235. const valid = ajv.validate("permissions", dataSchema);
  236. return valid && dataSchema[permission];
  237. } catch (err) {
  238. err.permission = permission;
  239. err.permission_data = data;
  240. logger.error(permission, data, err.message);
  241. throw errs.PermissionError("Permission Denied", err);
  242. }
  243. },
  244. };
  245. }