All files / backend/helpers configValidator.mjs

98.64% Statements 73/74
100% Branches 60/60
95.23% Functions 20/21
100% Lines 61/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146                                    2x 2x   2x                 93x 93x   3x 3x         10x 12x   12x 3x 3x     12x 2x 2x     12x 3x 3x     12x 2x 2x     12x 2x 2x     12x 2x 2x     12x           3x 7x 7x   7x 2x     7x           13x 1x 1x     12x   12x 21x   21x 2x 2x     21x 4x 4x     21x 1x 1x     21x 3x 2x 2x       21x         31x 31x 31x   31x   31x   31x   31x            
/*
  Copyright (C) 2022 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import {getLoggerWithTag} from '@global/logger/v2/logger.mjs';
 
const LOG_TAG =  'config-validator';
const logger = getLoggerWithTag(LOG_TAG);
 
const regex = {
    iss: /^\S+$/,                                   // iss в JWT - StringOrURI (RFC 7519): URL или строка вида access-management-service
    path: /^\/[^\s]*$/,                             // Для logoutPath
    alphanum: /^[a-zA-Z0-9_-]+$/,                   // Разрешить буквы, цифры, тире и подчеркивания
    label: /^[А-ЯЁа-яёA-Za-z0-9\-\s_]+$/            // Разрешить кириллицу, латиницу, цифры, тире, подчеркивания, пробелы
};
 
 
function parseEnvJson(key) {
    try {
        return JSON.parse(process.env[key] || '[]');
    } catch (e) {
        logger.info(() => `Invalid JSON in ${key}: ${e.message}`);
        return [];
    }
}
 
function validateAuthUserConfig(config) {
    return config.filter((entry, idx) => {
        let valid = true;
 
        if (typeof entry.iss !== 'string' || !regex.iss.test(entry.iss)) {
            logger.error(() => `Invalid "iss" in VUE_APP_DOCHUB_AUTH_USER_CONFIG (entry ${idx}): ${entry.iss}`);
            valid = false;
        }
 
        if (typeof entry.surname !== 'string' || !regex.alphanum.test(entry.surname)) {
            logger.error(() => `Invalid "surname" in VUE_APP_DOCHUB_AUTH_USER_CONFIG (entry ${idx}): ${entry.surname}`);
            valid = false;
        }
 
        if (typeof entry.name !== 'string' || !regex.alphanum.test(entry.name)) {
            logger.error(() => `Invalid "name" in VUE_APP_DOCHUB_AUTH_USER_CONFIG (entry ${idx}): ${entry.name}`);
            valid = false;
        }
 
        if (typeof entry.roles !== 'string' || !regex.alphanum.test(entry.roles)) {
            logger.error(() => `Invalid "role" in VUE_APP_DOCHUB_AUTH_USER_CONFIG (entry ${idx}): ${entry.roles}`);
            valid = false;
        }
 
        if (typeof entry.userId !== 'string' || !regex.alphanum.test(entry.userId)) {
            logger.error(() => `Invalid "userId" in VUE_APP_DOCHUB_AUTH_USER_CONFIG (entry ${idx}): ${entry.userId}`);
            valid = false;
        }
 
        if (typeof entry.sub !== 'string' || !regex.alphanum.test(entry.sub)) {
            logger.error(() => `Invalid "sub" in VUE_APP_DOCHUB_AUTH_USER_CONFIG (entry ${idx}): ${entry.sub}`);
            valid = false;
        }
 
        return valid;
    });
}
 
 
function validateRolesConfig(config) {
    return config.filter((entry, idx) => {
        const validRole = !entry.role || regex.alphanum.test(entry.role);
        const validLabel = !entry.label || regex.label.test(entry.label);
 
        if (!validRole || !validLabel) {
            logger.error(() => `Invalid configuration in .env file at parameter: VUE_APP_DOCHUB_ROLES_CONFIG (entry ${idx}). The entry value is invalid: ${JSON.stringify(entry)}. Please verify that the entry conforms to the expected structure and all required fields are provided.`);
        }
 
        return true;
    });
}
 
function validateLogoutConfig(config) {
 
    if (!Array.isArray(config)) {
        logger.error(() => `VUE_DOCHUB_AUTH_LOGOUT_CONFIG must be an array, got: ${typeof config}`);
        return [];
    }
 
    const allowedTypes = ['tokenHint', 'clientId', 'proxy'];
 
    return config.filter((entry, idx) => {
        let valid = true;
 
        if (typeof entry.iss !== 'string' || !regex.iss.test(entry.iss)) {
            logger.error(() => `Invalid "iss" in VUE_DOCHUB_AUTH_LOGOUT_CONFIG (entry ${idx}): ${entry.iss}`);
            valid = false;
        }
 
        if (typeof entry.logoutPath !== 'string' || !regex.path.test(entry.logoutPath)) {
            logger.error(() => `Invalid "logoutPath" in VUE_DOCHUB_AUTH_LOGOUT_CONFIG (entry ${idx}): ${entry.logoutPath}`);
            valid = false;
        }
 
        if (typeof entry.type !== 'string' || !allowedTypes.includes(entry.type)) {
            logger.error(() => `Invalid "type" in VUE_DOCHUB_AUTH_LOGOUT_CONFIG (entry ${idx}). Expected one of ${JSON.stringify(allowedTypes)}, got: ${entry.type}`);
            valid = false;
        }
 
        if (entry.type === 'clientId') {
            if (typeof entry.clientId !== 'string' || !regex.alphanum.test(entry.clientId)) {
                logger.error(() => `Invalid or missing "clientId" in VUE_DOCHUB_AUTH_LOGOUT_CONFIG (entry ${idx}) for type="clientId": ${entry.clientId}`);
                valid = false;
            }
        }
 
        return valid;
    });
}
 
export function loadValidatedConfigs() {
    const authUserRaw = parseEnvJson('VUE_APP_DOCHUB_AUTH_USER_CONFIG');
    const rolesRaw = parseEnvJson('VUE_APP_DOCHUB_ROLES_CONFIG');
    const logoutRaw = parseEnvJson('VUE_DOCHUB_AUTH_LOGOUT_CONFIG');
 
    const authUserConfig = authUserRaw.length ? validateAuthUserConfig(authUserRaw) : [];
 
    const rolesConfig = rolesRaw.length ? validateRolesConfig(rolesRaw) : [];
 
    const logoutConfig = logoutRaw.length ? validateLogoutConfig(logoutRaw) : [];
 
    return {
        authUserConfig,
        rolesConfig,
        logoutConfig
    };
}