UNPKG

k2hr3-api

Version:

K2HR3 REST API is K2hdkc based Resource and Roles and policy Rules

696 lines (695 loc) 28.4 kB
"use strict"; /* * K2HR3 REST API * * Copyright 2017 Yahoo Japan Corporation. * * K2HR3 is K2hdkc based Resource and Roles and policy Rules, gathers * common management information for the cloud. * K2HR3 can dynamically manage information as "who", "what", "operate". * These are stored as roles, resources, policies in K2hdkc, and the * client system can dynamically read and modify these information. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: Takeshi Nakatani * CREATE: Wed Jun 8 2017 * REVISION: * */ 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.openstackapiv2 = void 0; const https = __importStar(require("https")); const http = __importStar(require("http")); const k2hr3apiutil_1 = __importDefault(require("./k2hr3apiutil")); const dbglogging_1 = __importDefault(require("./dbglogging")); const openstackep_1 = __importDefault(require("./openstackep")); // OpenStack KeyStone EndPoint(=osksep) const cacerts_1 = require("./cacerts"); // // Get Unscoped token by user name and passwd from Openstack identity v2 API // // Document: https://developer.openstack.org/api-ref/identity/v2/?expanded=authenticate-detail // // Request: { // "auth": { // "tenantName": "", // "passwordCredentials": { // "username": "user", // "password": "passphrase" // } // } // } // // Response: { // "access": { // "metadata": { // "is_admin": 0, // "roles": [] // }, // "serviceCatalog": [], // "token": { // "audit_ids": [ // "######################" // ], // "expires": "2017-06-16T07:12:01Z", (*2) // "id": "*************************......", (*1) // "issued_at": "2017-06-15T07:12:01.822673" // }, // "user": { // "id": "************************.....", (*4) // "name": "name", (*3) // "roles": [], // "roles_links": [], // "username": "user" // } // } // } // // callback(error, result): // result = { // user: user name (*3) // userid: user id (*4) // scoped: false (always false) // token: token string(id) (*1) // expire: expire string (*2) // region: region string (region name for keystone endpoint) // token_seed: seed ({publisher: 'OPENSTACKV2'}) // } // const rawGetUserUnscopedTokenV2 = (uname, passwd, callback) => { if (!k2hr3apiutil_1.default.isSafeString(uname)) { const error = new Error('some parameters are wrong : uname=' + JSON.stringify(uname)); dbglogging_1.default.elog(error.message); callback(error, null); return; } if (!k2hr3apiutil_1.default.isSafeString(passwd)) { passwd = null; } const _uname = uname; const _passwd = passwd; const _callback = callback; // get end points for keystone openstackep_1.default.getKeystoneEndpoint((err, keystone_ep) => { if (k2hr3apiutil_1.default.isSafeEntity(err) || !k2hr3apiutil_1.default.isSafeEntity(keystone_ep)) { const error = new Error('could not get keystone end point by ' + (k2hr3apiutil_1.default.isSafeEntity(err) ? k2hr3apiutil_1.default.getSafeString(err.message) : '')); dbglogging_1.default.elog(error.message); _callback(error, null); return; } // got safe endpoint for keystone //r3logger.dlog(keystone_ep); // build parameters for request const body = { 'auth': { 'tenantName': '', // unscoped token by no tenant name 'passwordCredentials': { 'username': _uname, 'password': _passwd } } }; const agent = k2hr3apiutil_1.default.compareCaseString('https:', keystone_ep.protocol) ? https : http; const strbody = JSON.stringify(body); const headers = { 'Content-Type': 'application/json', 'Content-Length': strbody.length }; const options = { 'host': keystone_ep.hostname ?? '', 'port': keystone_ep.port ?? 0, 'path': keystone_ep.pathname + '/v2.0/tokens', 'method': 'POST', 'headers': headers, 'ca': (k2hr3apiutil_1.default.compareCaseString('https:', keystone_ep.protocol) && null !== cacerts_1.ca) ? ((0, cacerts_1.ca)() ?? undefined) : undefined }; // send request const req = agent.request(options, (res) => { let body = ''; const status = res.statusCode; dbglogging_1.default.dlog('response status: ' + res.statusCode); dbglogging_1.default.dlog('response header: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', (chunk) => { //r3logger.dlog('response chunk: ' + chunk); body += chunk; }); res.on('end', () => { if (300 <= (status ?? 500)) { const error = new Error('could not get unscoped token by status=' + String(status ?? 500)); dbglogging_1.default.elog(error.message); _callback(error, null); return; } //r3logger.dlog('response body: ' + body); let res_body = body; if (k2hr3apiutil_1.default.checkSimpleJSON(body)) { res_body = JSON.parse(body); } if (!k2hr3apiutil_1.default.isPlainObject(res_body) || !k2hr3apiutil_1.default.isPlainObject(res_body.access) || !k2hr3apiutil_1.default.isPlainObject(res_body.access.user) || !k2hr3apiutil_1.default.isSafeString(res_body.access.user.name) || !k2hr3apiutil_1.default.compareCaseString(res_body.access.user.name, _uname) || !k2hr3apiutil_1.default.isSafeString(res_body.access.user.id) || !k2hr3apiutil_1.default.isPlainObject(res_body.access.token) || !k2hr3apiutil_1.default.isSafeString(res_body.access.token.id) || !k2hr3apiutil_1.default.isSafeString(res_body.access.token.expires)) { const error = new Error('could not get unscoped token by something wrong response body'); dbglogging_1.default.elog(error.message); _callback(error, null); return; } // convert openstack user id(16 bytes hex string) to UUID(not UUID4) const user_id_uuid4 = k2hr3apiutil_1.default.getSafeString(k2hr3apiutil_1.default.cvtNumberStringToUuid4(res_body.access.user.id, 16)); // build result const resobj = { user: res_body.access.user.name.toLowerCase(), userid: user_id_uuid4, scoped: false, token: res_body.access.token.id.toLowerCase(), expire: res_body.access.token.expires, region: k2hr3apiutil_1.default.getSafeString(keystone_ep.region).toLowerCase(), token_seed: JSON.stringify({ publisher: 'OPENSTACKV2' }) }; _callback(null, resobj); }); }); req.on('error', (exception) => { dbglogging_1.default.elog('problem with request: ' + exception.message); _callback(exception, null); return; }); // write data to request body req.write(strbody); req.end(); }, false); }; // // Get Scoped token by unscoped token and tenant name from Openstack identity v2 API // // Document: https://developer.openstack.org/api-ref/identity/v2/?expanded=authenticate-detail // // Request: { // "auth": { // "tenantName": "tenant", // "token" : { // "id": "**********************....." // } // } // } // // Response: { // "access": { // "metadata": { // "is_admin": 0, // "roles": [ // "************************......." // ] // }, // "serviceCatalog": [ // { // "endpoints": [ // { // "adminURL": "http://xxx.yahoo.co.jp:8776/v1/3b737f48168d32c23928b....", // "id": "*****************.......", // "internalURL": "http://xxx.yahoo.co.jp:8776/v1/3b737f48168d32c23928b....", // "publicURL": "https://yyy.yahoo.co.jp:8776/v1/3b737f48168d32c23928b55f....", // "region": "region name" (*4) // } // ], // "endpoints_links": [], // "name": "cinder", // "type": "identity" (*4) // }, // ... // ], // "token": { // "audit_ids": [ // "######################", // "######################" // ], // "expires": "2017-06-16T07:06:31Z", (*2) // "id": "********************************", (*1) // "issued_at": "2017-06-15T07:31:12.027688", // "tenant": { // "description": null, // "enabled": true, // "id": "************************...", // "name": "tenant name" (*5: tenant name) // } // }, // "user": { // "id": "************************...", (*4) // "name": "user", (*3) // "roles": [ // { // "name": "_member_" // } // ], // "roles_links": [], // "username": "user name" // } // } // } // // callback(error, result): // result = { // user: user name (*3) // userid: user id (*4) // scoped: true (always true) // token: token string(id) (*1) // expire: expire string (*2) // region: region string (identity's *4 for region name) // token_seed: seed ({publisher: 'OPENSTACKV2'}) // } // const rawGetUserScopedTokenV2 = (unscopedtoken, tenant, callback) => { if (!k2hr3apiutil_1.default.isSafeString(unscopedtoken) || !k2hr3apiutil_1.default.isSafeString(tenant)) { const error = new Error('some parameters are wrong : unscopedtoken=' + JSON.stringify(unscopedtoken) + ', tenant=' + JSON.stringify(tenant)); dbglogging_1.default.elog(error.message); callback(error, null); return; } const _unscopedtoken = unscopedtoken; const _tenant = tenant; const _callback = callback; // get end points for keystone openstackep_1.default.getKeystoneEndpoint((err, keystone_ep) => { if (null !== err || null === keystone_ep) { const error = new Error('could not get keystone end point by ' + (err?.message ?? '')); dbglogging_1.default.elog(error.message); _callback(error, null); return; } // got safe endpoint for keystone //r3logger.dlog(keystone_ep); // build parameters for request const body = { 'auth': { 'tenantName': _tenant, 'token': { 'id': _unscopedtoken } } }; const agent = k2hr3apiutil_1.default.compareCaseString('https:', keystone_ep.protocol) ? https : http; const strbody = JSON.stringify(body); const headers = { 'Content-Type': 'application/json', 'Content-Length': strbody.length }; const options = { 'host': keystone_ep.hostname ?? '', 'port': keystone_ep.port ?? 0, 'path': keystone_ep.pathname + '/v2.0/tokens', 'method': 'POST', 'headers': headers, 'ca': (k2hr3apiutil_1.default.compareCaseString('https:', keystone_ep.protocol) && null !== cacerts_1.ca) ? ((0, cacerts_1.ca)() ?? undefined) : undefined }; // send request const req = agent.request(options, (res) => { let body = ''; const status = res.statusCode; dbglogging_1.default.dlog('response status: ' + res.statusCode); dbglogging_1.default.dlog('response header: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', (chunk) => { //r3logger.dlog('response chunk: ' + chunk); body += chunk; }); res.on('end', () => { if (300 <= (status ?? 500)) { const error = new Error('could not get scoped token by status=' + String(status ?? 500)); dbglogging_1.default.elog(error.message); _callback(error, null); return; } //r3logger.dlog('response body: ' + body); let res_body = body; if (k2hr3apiutil_1.default.checkSimpleJSON(body)) { res_body = JSON.parse(body); } if (!k2hr3apiutil_1.default.isPlainObject(res_body) || !k2hr3apiutil_1.default.isPlainObject(res_body.access) || !k2hr3apiutil_1.default.isNotEmptyArray(res_body.access.serviceCatalog) || !k2hr3apiutil_1.default.isPlainObject(res_body.access.user) || !k2hr3apiutil_1.default.isSafeString(res_body.access.user.name) || !k2hr3apiutil_1.default.isSafeString(res_body.access.user.id) || !k2hr3apiutil_1.default.isPlainObject(res_body.access.token) || !k2hr3apiutil_1.default.isSafeString(res_body.access.token.id) || !k2hr3apiutil_1.default.isSafeString(res_body.access.token.expires) || !k2hr3apiutil_1.default.isPlainObject(res_body.access.token.tenant) || !k2hr3apiutil_1.default.isSafeString(res_body.access.token.tenant.name) || !k2hr3apiutil_1.default.compareCaseString(res_body.access.token.tenant.name, _tenant)) { const error = new Error('could not get scoped token by something wrong response body'); dbglogging_1.default.elog(error.message); _callback(error, null); return; } // check & get region let region = null; for (let cnt = 0; cnt < (res_body?.access?.serviceCatalog?.length ?? 0) && null === region; ++cnt) { const tmpCatalog = res_body.access.serviceCatalog[cnt]; if (!k2hr3apiutil_1.default.isPlainObject(tmpCatalog) || !k2hr3apiutil_1.default.isNotEmptyArray(tmpCatalog.endpoints) || !k2hr3apiutil_1.default.isSafeString(tmpCatalog.type)) { dbglogging_1.default.wlog('one of response for scoped token is something wrong : ' + JSON.stringify(res_body)); continue; } // target region by type=identity if (!k2hr3apiutil_1.default.compareCaseString('identity', tmpCatalog.type)) { continue; } // check region for (let cnt2 = 0; cnt2 < tmpCatalog.endpoints.length; ++cnt2) { const tmpEp = tmpCatalog.endpoints[cnt2]; if (k2hr3apiutil_1.default.isPlainObject(tmpEp) && k2hr3apiutil_1.default.isSafeString(tmpEp.region)) { if (k2hr3apiutil_1.default.compareCaseString(tmpEp.region, keystone_ep.region)) { // found region = tmpEp.region; break; } else { dbglogging_1.default.wlog('unknown region(' + tmpEp.region + '), we need to find region(' + keystone_ep.region + '), so skip this'); } } else { dbglogging_1.default.wlog('one of response endpoint for scoped token is something wrong : ' + JSON.stringify(tmpEp)); } } } if (!k2hr3apiutil_1.default.isString(region)) { const error = new Error('could not find request region in result.'); dbglogging_1.default.elog(error.message); _callback(error, null); return; } // convert openstack user id(16 bytes hex string) to UUID(not UUID4) const user_id_uuid4 = k2hr3apiutil_1.default.getSafeString(k2hr3apiutil_1.default.cvtNumberStringToUuid4(res_body.access.user.id, 16)); // build result const resobj = { user: res_body.access.user.name.toLowerCase(), userid: user_id_uuid4, scoped: false, token: res_body.access.token.id.toLowerCase(), expire: res_body.access.token.expires, region: region.toLowerCase(), token_seed: JSON.stringify({ publisher: 'OPENSTACKV2' }) }; _callback(null, resobj); }); }); req.on('error', (exception) => { dbglogging_1.default.elog('problem with request: ' + exception.message); _callback(exception, null); return; }); // write data to request body req.write(strbody); req.end(); }, false); }; // // Verify User Token for OpenStack V2 // // user : target user name for token // token : check token // token_seed : token seed data // // result : { // result: true/false // message: null or error message string // } // const rawVerifyUserTokenPublisherV2 = (token_seed) => { if (!k2hr3apiutil_1.default.isSafeString(token_seed)) { return false; } // parse seed if (!k2hr3apiutil_1.default.checkSimpleJSON(token_seed)) { return false; } const seed = k2hr3apiutil_1.default.parseJSON(token_seed); if (!k2hr3apiutil_1.default.isValTypeTokenSeed(seed)) { return false; } if (!k2hr3apiutil_1.default.isSafeString(seed.publisher) || (seed.publisher != 'OPENSTACKV2')) // publisher must be 'OPENSTACKV2' { return false; } return true; }; const rawWrapVerifyUserTokenPublisherV2 = (token_seed) => { const resobj = { result: true, message: null }; if (!rawVerifyUserTokenPublisherV2(token_seed)) { resobj.result = false; resobj.message = 'token_seed(not printable) is not safe entity.'; dbglogging_1.default.elog(resobj.message); return resobj; } return resobj; }; const rawVerifyUserTokenV2 = (user, token, token_seed) => { const resobj = { result: true, message: null }; if (!k2hr3apiutil_1.default.isSafeString(user) || !k2hr3apiutil_1.default.isSafeString(token) || !k2hr3apiutil_1.default.isSafeString(token_seed)) { resobj.result = false; resobj.message = 'some parameters are wrong : token=' + JSON.stringify(token) + ', token_seed=<not printable>, user=' + JSON.stringify(user); dbglogging_1.default.elog(resobj.message); return resobj; } // check seed if (!rawVerifyUserTokenPublisherV2(token_seed)) { resobj.result = false; resobj.message = 'token_seed(not printable) is not safe entity.'; dbglogging_1.default.elog(resobj.message); return resobj; } return resobj; }; // // Get tenant list by unscoped token from Openstack identity v2 API // // Document: https://developer.openstack.org/api-ref/identity/v2/?expanded=list-tenants-detail // // Request: X-Auth-Token: <unscoped token> // // Response: { // "tenants": [ // { // "description": null, (*1) // "enabled": true, // "id": "***************************.....", (*2) // "name": "tenant name" (*3) // }, // { // "description": null, // "enabled": true, // "id": "**************************......", // "name": "tenant name" // } // ], // "tenants_links": [] // } // // callback(error, result): // result = [ // { // name: tenant name (*3) // id: tenant id (*2) // description: tenant description (*1) // display: display name (*3) // }, // ... // ] // // [TODO] // Should not we use "tenant id" instead of "tenant name" for "name"? // We need this consideration. // const rawGetUserTenantListV2 = (unscopedtoken, callback) => { if (!k2hr3apiutil_1.default.isSafeString(unscopedtoken)) { const error = new Error('parameter is wrong : unscopedtoken=' + JSON.stringify(unscopedtoken)); dbglogging_1.default.elog(error.message); callback(error, null); return; } const _unscopedtoken = unscopedtoken; const _callback = callback; // get end points for keystone openstackep_1.default.getKeystoneEndpoint((err, keystone_ep) => { if (null !== err || null === keystone_ep) { const error = new Error('could not get keystone end point by ' + (err?.message ?? '')); dbglogging_1.default.elog(error.message); _callback(error, null); return; } // got safe endpoint for keystone //r3logger.dlog(keystone_ep); // build parameters for request const agent = k2hr3apiutil_1.default.compareCaseString('https:', keystone_ep.protocol) ? https : http; const headers = { 'Content-Type': 'application/json', 'X-Auth-Token': _unscopedtoken, 'Content-Length': 0 }; const options = { 'host': keystone_ep.hostname ?? '', 'port': keystone_ep.port ?? 0, 'path': keystone_ep.pathname + '/v2.0/tenants', 'method': 'GET', 'headers': headers, 'ca': (k2hr3apiutil_1.default.compareCaseString('https:', keystone_ep.protocol) && null !== cacerts_1.ca) ? ((0, cacerts_1.ca)() ?? undefined) : undefined }; // send request const req = agent.request(options, (res) => { let body = ''; const status = res.statusCode; dbglogging_1.default.dlog('response status: ' + res.statusCode); dbglogging_1.default.dlog('response header: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', (chunk) => { //r3logger.dlog('response chunk: ' + chunk); body += chunk; }); res.on('end', () => { if (300 <= (status ?? 500)) { const error = new Error('could not get scoped token by status=' + String(status ?? 500)); dbglogging_1.default.elog(error.message); _callback(error, null); return; } //r3logger.dlog('response body: ' + body); let res_body = body; if (k2hr3apiutil_1.default.checkSimpleJSON(body)) { res_body = JSON.parse(body); } if (!k2hr3apiutil_1.default.isPlainObject(res_body) || !k2hr3apiutil_1.default.isNotEmptyArray(res_body.tenants)) { const error = new Error('failed to get tenant list by unscoped token.'); dbglogging_1.default.elog(error.message); _callback(error, null); return; } // convert result array const resobj = []; for (let cnt = 0; cnt < res_body.tenants.length; ++cnt) { const tmpTenant = res_body.tenants[cnt]; if (!k2hr3apiutil_1.default.isPlainObject(tmpTenant) || !k2hr3apiutil_1.default.isSafeString(tmpTenant.id) || !k2hr3apiutil_1.default.isSafeString(tmpTenant.name)) { dbglogging_1.default.wlog('one of response for tenant list is something wrong : ' + JSON.stringify(tmpTenant)); continue; } const tenant = { name: tmpTenant.name.toLowerCase(), id: tmpTenant.id.toLowerCase(), description: k2hr3apiutil_1.default.getSafeString(tmpTenant.description), display: tmpTenant.name }; resobj.push(tenant); } if (0 === resobj.length) { const error = new Error('could not get any tenant list by unscoped token.'); dbglogging_1.default.elog(error.message); _callback(error, null); return; } _callback(null, resobj); }); }); req.on('error', (exception) => { dbglogging_1.default.elog('problem with request: ' + exception.message); callback(exception, null); return; }); }, false); }; //--------------------------------------------------------- // Exports //--------------------------------------------------------- exports.openstackapiv2 = { getUserUnscopedToken: rawGetUserUnscopedTokenV2, // // update token : not implemented // getUserUnscopedTokenByToken: (token, callback) => { const error = new Error('getUserUnscopedTokenByToken is not implemented'); dbglogging_1.default.elog(error.message); callback(error, null); }, // // tenantname : for keystone v2 api // tenantid : not used // getUserScopedToken: rawGetUserScopedTokenV2, // // Verify seed publisher type // verifyUserTokenPublisher: rawWrapVerifyUserTokenPublisherV2, // // Verify token // // tenant is not used. // verifyUserToken: (dkcobj_permanent, user, tenant, token, token_seed) => { return rawVerifyUserTokenV2(user, token, token_seed); }, // // userid : not used // getUserTenantList: (unscopedtoken, userid, callback) => { rawGetUserTenantListV2(unscopedtoken, callback); } }; // // Default // exports.default = exports.openstackapiv2; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noexpandtab sw=4 ts=4 fdm=marker * vim<600: noexpandtab sw=4 ts=4 */