@citrineos/util
Version:
The OCPP util module which supplies helpful utilities like cache and queue connectors, etc.
141 lines • 5.54 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RbacRulesLoader = void 0;
const fs = __importStar(require("fs"));
//TODO fix import
const types_1 = require("@citrineos/base/dist/config/types");
const UrlMatcher_1 = require("./UrlMatcher");
const path_1 = __importDefault(require("path"));
/**
* Class to load and validate RBAC rules
*/
class RbacRulesLoader {
/**
* Creates a new RBAC rules loader
*
* @param rulesFilePath Path to the JSON rules file
* @param logger Logger instance
*/
constructor(rulesFilePath, logger) {
this._rules = {};
this._logger = logger.getSubLogger({ name: 'RbacRulesLoader' });
this.loadRules(rulesFilePath);
}
/**
* Load and validate rules from a JSON file
*
* @param filePath Path to the JSON rules file
*/
loadRules(filePath) {
const absoluteFilePath = path_1.default.join(process.cwd(), filePath);
try {
if (!fs.existsSync(absoluteFilePath)) {
this._logger.warn(`Rules file not found at ${absoluteFilePath}, using empty rules`);
return;
}
const rulesContent = fs.readFileSync(absoluteFilePath, 'utf8');
const parsedRules = JSON.parse(rulesContent);
// Validate rules against the schema
const validationResult = types_1.RbacRulesSchema.safeParse(parsedRules);
if (!validationResult.success) {
this._logger.error('Invalid RBAC rules format:', validationResult.error);
throw new Error('Invalid RBAC rules format');
}
// Store the validated rules
this._rules = validationResult.data;
this._logger.info(`Successfully loaded RBAC rules from ${filePath}`);
this._logger.debug(`Loaded ${Object.keys(this._rules).length} tenants with rules`);
}
catch (error) {
if (error instanceof Error && error.message === 'Invalid RBAC rules format') {
throw error; // Re-throw validation errors
}
this._logger.error('Failed to load RBAC rules:', error);
throw new Error(`Failed to load RBAC rules: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Get the required roles for a specific tenant, URL, and HTTP method
*
* @param tenantId Tenant identifier
* @param url URL path
* @param method HTTP method
* @returns Array of required roles or null if no matching rule
*/
getRequiredRoles(tenantId, url, method) {
// Normalize method to uppercase
method = method.toUpperCase();
const cleanUrl = this.normalizeUrl(url);
const tenantRules = this._rules[tenantId];
if (!tenantRules) {
return null;
}
// Try exact URL match first
const exactUrlRules = tenantRules[cleanUrl];
if (exactUrlRules) {
return exactUrlRules[method] || exactUrlRules['*'] || null;
}
// Pattern matching
for (const pattern in tenantRules) {
if (UrlMatcher_1.UrlMatcher.match(cleanUrl, pattern)) {
const methodRules = tenantRules[pattern];
const roles = methodRules[method] || methodRules['*'];
if (roles) {
return roles;
}
}
}
return null;
}
normalizeUrl(url) {
// Remove query parameters and fragments
let cleanUrl = url.split('?')[0].split('#')[0];
// Remove trailing slash (optional, depends on your URL patterns)
if (cleanUrl.length > 1 && cleanUrl.endsWith('/')) {
cleanUrl = cleanUrl.slice(0, -1);
}
// Ensure it starts with /
if (!cleanUrl.startsWith('/')) {
cleanUrl = '/' + cleanUrl;
}
return cleanUrl;
}
}
exports.RbacRulesLoader = RbacRulesLoader;
//# sourceMappingURL=RbacRulesLoader.js.map