From d71b30b686d6d9b50bd1e57ad6bb1f77895b65bc Mon Sep 17 00:00:00 2001 From: Michal Bajer Date: Wed, 27 Dec 2023 11:22:22 +0000 Subject: [PATCH] chore(cactus-plugin-ledger-connector-cdl-socketio): remove old connector - Remove old connector cactus-plugin-ledger-connector-cdl-socketio. It's been replaced with socketio-based cactus-plugin-ledger-connector-cdl. Depends on #2962 Signed-off-by: Michal Bajer --- jest.config.js | 1 - .../CHANGELOG.md | 10 - .../Dockerfile | 13 - .../README.md | 90 ---- .../package.json | 87 ---- .../sample-config/default.yaml | 16 - .../src/main/typescript/common/core/app.ts | 53 -- .../main/typescript/common/core/bin/www.ts | 176 ------- .../src/main/typescript/common/core/config.ts | 37 -- .../main/typescript/connector/ServerPlugin.ts | 197 ------- .../connector/ValidatorAuthentication.ts | 31 -- .../main/typescript/connector/cdl-request.ts | 146 ------ .../main/typescript/connector/type-defs.ts | 63 --- .../src/main/typescript/index.ts | 1 - .../src/main/typescript/public-api.ts | 1 - .../cdl-connector-socketio-manual.test.ts | 482 ------------------ .../tsconfig.json | 29 -- tsconfig.json | 3 - yarn.lock | 39 -- 19 files changed, 1475 deletions(-) delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/CHANGELOG.md delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/Dockerfile delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/README.md delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/package.json delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/sample-config/default.yaml delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/app.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/bin/www.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/config.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ServerPlugin.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ValidatorAuthentication.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/cdl-request.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/type-defs.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/index.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/public-api.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/src/test/typescript/integration/cdl-connector-socketio-manual.test.ts delete mode 100644 packages/cactus-plugin-ledger-connector-cdl-socketio/tsconfig.json diff --git a/jest.config.js b/jest.config.js index 4bb1c5947e..b3d39c5399 100644 --- a/jest.config.js +++ b/jest.config.js @@ -99,7 +99,6 @@ module.exports = { `./packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation-go.test.ts`, `./packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation.test.ts`, `./packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/unit/identity-internal-crypto-utils.test.ts`, - `./packages/cactus-plugin-ledger-connector-cdl-socketio/src/test/typescript/integration/cdl-connector-manual.test.ts`, `./packages/cactus-plugin-keychain-vault/src/test/typescript/integration/cactus-keychain-vault-server.test.ts`, `./packages/cactus-plugin-keychain-vault/src/test/typescript/integration/plugin-keychain-vault.test.ts`, `./packages/cactus-plugin-keychain-vault/src/test/typescript/integration/openapi/openapi-validation.test.ts`, diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/CHANGELOG.md b/packages/cactus-plugin-ledger-connector-cdl-socketio/CHANGELOG.md deleted file mode 100644 index df8430d362..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/CHANGELOG.md +++ /dev/null @@ -1,10 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. -See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. - -# [2.0.0-alpha.2](https://github.com/hyperledger/cacti/compare/v2.0.0-alpha.1...v2.0.0-alpha.2) (2023-09-27) - -### Features - -* **cactus-plugin-ledger-connector-cdl-socketio:** add new connector plugin ([aee28fe](https://github.com/hyperledger/cacti/commit/aee28fee8ac6f386c8b95560f085daf2ec4965f8)), closes [#2455](https://github.com/hyperledger/cacti/issues/2455) diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/Dockerfile b/packages/cactus-plugin-ledger-connector-cdl-socketio/Dockerfile deleted file mode 100644 index b1a951028e..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -# TODO -# Install connector as yarn package like in @hyperledger/cactus-plugin-ledger-connector-besu - -FROM node:18 - -WORKDIR /root/cactus/ - -COPY ./dist ./dist/ -COPY ./dist/yarn.lock ./package.json ./ -RUN yarn install --production --ignore-engines --non-interactive --cache-folder ./.yarnCache; rm -rf ./.yarnCache - -EXPOSE 5061 -CMD [ "npm", "run", "start" ] diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/README.md b/packages/cactus-plugin-ledger-connector-cdl-socketio/README.md deleted file mode 100644 index 4aff23a30f..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# `@hyperledger/cactus-plugin-ledger-connector-cdl-socketio` - -This plugin provides `Cacti` a way to interact with Fujitsu CDL networks. Using this we can perform: - -- `sendSyncRequest`: Send sync-typed requests to the API. -- `sendAsyncRequest`: Send async-typed requests to the API. - -## Getting started - -### Required software components - -- OS: Linux (recommended Ubuntu20.04,18.04 or CentOS7) -- Docker (recommend: v17.06.2-ce or greater) -- node.js v12 (recommend: v12.20.2 or greater) - -## Boot methods - -### Common setup - -1. Always run configure command first, from the project root directory: - - ```bash - pushd ../.. - npm run configure - popd - ``` - -1. Copy default configuration - -- **Remember to replace default CA and to adjust the `default.yaml` configuration on production deployments!** - ```bash - mkdir -p /etc/cactus/connector-cdl-socketio - rm -r /etc/cactus/connector-cdl-socketio/* - cp -rf ./sample-config/* /etc/cactus/connector-cdl-socketio/ - ``` - -#### Configuring CDL API Gateway Access - -- Set the base URL of GW service in `cdlApiGateway.url` (when using JWT access token - DEFAULT) and/or `cdlApiSubscriptionGateway.url` (when using subscription-key) - - Example: `"http://localhost:3000"` -- If the service certificate is signed with a known CA (node uses Mozilla DB), then you can skip the next steps. -- If the service is signed with unknown CA, you can specify the gateway certificate to trust manually: - - Set `cdlApiGateway.caPath`/`cdlApiSubscriptionGateway.caPath` to path of API Gateway certificate (in PEM format). (example: `"/etc/cactus/connector-cdl-socketio/CA/cdl-api-gateway-ca.pem"`) - - (optional) If server name in cert doesn't match the one in `url`, you can overwrite it in `cdlApiGateway.serverName`/`cdlApiSubscriptionGateway.serverName` -- (not recommended - only for development): To ignore certificate rejection (e.g. use self-signed certificate) set `cdlApiGateway.skipCertCheck`/`cdlApiSubscriptionGateway.skipCertCheck` to `true`. - -### Docker - -- Docker build process will use artifacts from the latest build. Make sure `./dist` contains the version you want to dockerize. - -``` -# Build -DOCKER_BUILDKIT=1 docker build ./packages/cactus-plugin-ledger-connector-cdl-socketio -t cactus-plugin-ledger-connector-cdl-socketio - -# Run -docker run -v/etc/cactus/:/etc/cactus -p 5061:5061 cactus-plugin-ledger-connector-cdl-socketio -``` - -### Manual - -``` -npm run start -``` - -## Configuration - -- Validator can be configured in `/etc/cactus/connector-cdl-socketio/default.yaml` (see [sample-config](./sample-config/default.yaml) for details). - -## Manual Tests - -- There are no automatic tests for this plugin because there's no private instance of CDL available at a time. -- `cdl-connector-manual.test` contains a Jest test script that will check every implemented operation on a running CDL service. -- **You need access to a running instance of CDL in order to run this script.** -- Before running the script you must update the following variables in it: - - `authInfo` - either `accessToken` or `subscriptionKey` based configuration. - - `VALIDATOR_KEY_PATH` - Path to validator public certificate. -- Script can be used as a quick reference for using this connector plugin. -- Since script is not part of project jest suite, to run in execute the following commands from a package dir: - - `npm run build` - - `npx jest dist/lib/test/typescript/integration/cdl-connector-manual.test.js` - -## Contributing - -We welcome contributions to Hyperledger Cacti in many forms, and there's always plenty to do! - -Please review [CONTIRBUTING.md](../../CONTRIBUTING.md) to get started. - -## License - -This distribution is published under the Apache License Version 2.0 found in the [LICENSE](../../LICENSE) file. diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/package.json b/packages/cactus-plugin-ledger-connector-cdl-socketio/package.json deleted file mode 100644 index cc6a9f798b..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "name": "@hyperledger/cactus-plugin-ledger-connector-cdl-socketio", - "version": "2.0.0-alpha.2", - "description": "Allows Cacti nodes to connect to Fujitsu CDL.", - "keywords": [ - "Hyperledger", - "Cacti", - "Integration", - "Blockchain", - "Distributed Ledger Technology" - ], - "homepage": "https://github.com/hyperledger/cacti#readme", - "bugs": { - "url": "https://github.com/hyperledger/cacti/issues" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/hyperledger/cacti.git" - }, - "license": "Apache-2.0", - "author": { - "name": "Hyperledger Cacti Contributors", - "email": "cacti@lists.hyperledger.org", - "url": "https://www.hyperledger.org/use/cacti" - }, - "contributors": [ - { - "name": "Please add yourself to the list of contributors", - "email": "your.name@example.com", - "url": "https://example.com" - }, - { - "name": "Michal Bajer", - "email": "michal.bajer@fujitsu.com", - "url": "https://www.fujitsu.com/global/" - } - ], - "main": "dist/index.js", - "module": "dist/index.js", - "types": "dist/index.d.ts", - "files": [ - "dist/*" - ], - "scripts": { - "build": "npm run build-ts && npm run build:dev:backend:postbuild", - "build-ts": "tsc", - "build:dev:backend:postbuild": "npm run init-cdl", - "debug": "nodemon --inspect ./dist/lib/main/typescript/common/core/bin/www.js", - "init-cdl": "cp -af ../../yarn.lock ./dist/yarn.lock", - "start": "node ./dist/lib/main/typescript/common/core/bin/www.js" - }, - "dependencies": { - "axios": "1.6.0", - "body-parser": "1.20.2", - "config": "3.3.7", - "cookie-parser": "1.4.6", - "express": "4.18.2", - "fast-safe-stringify": "2.1.1", - "http-errors": "1.6.3", - "js-yaml": "3.14.1", - "jsonwebtoken": "9.0.0", - "log4js": "6.4.1", - "sanitize-html": "2.7.0", - "socket.io": "4.5.4" - }, - "devDependencies": { - "@hyperledger/cactus-api-client": "2.0.0-alpha.2", - "@hyperledger/cactus-common": "2.0.0-alpha.2", - "@types/config": "0.0.41", - "@types/cookie-parser": "1.4.3", - "@types/express": "4.17.19", - "@types/http-errors": "2.0.1", - "@types/jsonwebtoken": "9.0.2", - "@types/node": "14.18.54", - "@types/sanitize-html": "2.6.2", - "jest-extended": "4.0.1", - "uuid": "8.3.2" - }, - "engines": { - "node": ">=18", - "npm": ">=8" - }, - "publishConfig": { - "access": "public" - }, - "watch": {} -} diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/sample-config/default.yaml b/packages/cactus-plugin-ledger-connector-cdl-socketio/sample-config/default.yaml deleted file mode 100644 index 3224f5220a..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/sample-config/default.yaml +++ /dev/null @@ -1,16 +0,0 @@ -sslParam: - port: 5061 - key: "/etc/cactus/connector-cdl-socketio/CA/connector.priv" - cert: "/etc/cactus/connector-cdl-socketio/CA/connector.crt" -logLevel: "debug" -userAgent: "CactiCDLConnector" -cdlApiGateway: - url: "http://localhost:3000" - #skipCertCheck: true # Set to true to ignore self-signed and other rejected certificates - #caPath: "/etc/cactus/connector-cdl-socketio/CA/cdl-api-gateway-ca.pem" # CA of CDL API gateway server in PEM format to use - #serverName: "cdl.fujitsu" # Overwrite server name from cdlApiGateway.url to match one specified in CA -cdlApiSubscriptionGateway: - url: "http://localhost:3000" - #skipCertCheck: true # Set to true to ignore self-signed and other rejected certificates - #caPath: "/etc/cactus/connector-cdl-socketio/CA/cdl-api-gateway-ca.pem" # CA of CDL API gateway server in PEM format to use - #serverName: "cdl.fujitsu" # Overwrite server name from cdlApiGateway.url to match one specified in CA diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/app.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/app.ts deleted file mode 100644 index d3af06b09d..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/app.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2023 Hyperledger Cacti Contributors - * SPDX-License-Identifier: Apache-2.0 - * - * app.js - */ - -/* Summary: - * - */ - -import type { NextFunction, Request, Response, RequestHandler } from "express"; -import createError from "http-errors"; -import express from "express"; -import cookieParser from "cookie-parser"; -import bodyParser from "body-parser"; - -const app: express.Express = express(); - -app.use(bodyParser.json()); -app.use(bodyParser.urlencoded({ extended: false })); -app.use(cookieParser() as RequestHandler); - -// catch 404 and forward to error handler -app.use((req: Request, res: Response, next: NextFunction) => { - next(createError(404)); -}); - -// error handler -app.use( - ( - err: { message: string; status?: number }, - req: Request, - res: Response, - next: NextFunction, - ) => { - // set locals, only providing error in development - res.locals.message = err.message; - res.locals.error = req.app.get("env") === "development" ? err : {}; - - // set erreor response - const errorResponse: {} = { - statusCode: err.status || 500, - message: err.message, - }; - - // render the error page - res.status(err.status || 500); - res.send(errorResponse); - }, -); - -export default app; diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/bin/www.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/bin/www.ts deleted file mode 100644 index 181ed024a4..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/bin/www.ts +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env node - -import app from "../app"; -import { read as configRead } from "../config"; - -import axios from "axios"; -import https from "https"; -import fs from "fs"; -import { Server } from "socket.io"; -import safeStringify from "fast-safe-stringify"; -import sanitizeHtml from "sanitize-html"; - -// Log settings -import { getLogger } from "log4js"; -const logger = getLogger("connector_main[" + process.pid + "]"); -logger.level = configRead("logLevel", "info"); - -// implementation class of a part dependent of end-chains (server plugin) -import { ServerPlugin } from "../../../connector/ServerPlugin"; -import { ValidatorAuthentication } from "../../../connector/ValidatorAuthentication"; - -// Normalize a port into a number, string, or false. -function normalizePort(val: string) { - const port = parseInt(val, 10); - - if (isNaN(port)) { - // named pipe - return val; - } - - if (port >= 0) { - // port number - return port; - } - - return false; -} - -/** - * Return secure string representation of error from the input. - * Handles circular structures and removes HTML. - * - * @param error Any object to return as an error, preferable `Error` - * @returns Safe string representation of an error. - */ -export function safeStringifyException(error: unknown): string { - if (axios.isAxiosError(error)) { - return safeStringify(error.toJSON()); - } - - if (error instanceof Error) { - return sanitizeHtml(error.stack || error.message); - } - - return sanitizeHtml(safeStringify(error)); -} - -export async function startCDLSocketIOConnector() { - const Splug = new ServerPlugin(); - - // Get port from environment and store in Express. - const sslport = normalizePort( - process.env.PORT || configRead("sslParam.port"), - ); - app.set("port", sslport); - - // Specify private key and certificate - let keyString: string; - let certString: string; - try { - keyString = configRead("sslParam.keyValue"); - certString = configRead("sslParam.certValue"); - } catch { - keyString = fs.readFileSync(configRead("sslParam.key"), "ascii"); - certString = fs.readFileSync(configRead("sslParam.cert"), "ascii"); - } - - // Create HTTPS server. - const server = https.createServer( - { - key: keyString, - cert: certString, - }, - app, - ); // Start as an https server. - const io = new Server(server); - - // Event listener for HTTPS server "error" event. - server.on("error", (error: any) => { - if (error.syscall !== "listen") { - throw error; - } - - const bind = - typeof sslport === "string" ? "Pipe " + sslport : "Port " + sslport; - - // handle specific listen errors with friendly messages - switch (error.code) { - case "EACCES": - console.error(bind + " requires elevated privileges"); - process.exit(1); - break; - case "EADDRINUSE": - console.error(bind + " is already in use"); - process.exit(1); - break; - default: - throw error; - } - }); - - io.on("connection", (client) => { - logger.info("Client " + client.id + " connected."); - - client.on("request2", async (data) => { - try { - const result = await Splug.executeFunction({ - method: data.method, - args: data.args, - reqID: data.reqID, - }); - const response = { - resObj: { - status: 200, - data: ValidatorAuthentication.sign({ result }), - }, - id: data.reqID, - }; - logger.info("Client ID :" + client.id); - logger.info("Response:", JSON.stringify(response)); - client.emit("response", response); - } catch (error: unknown) { - const errorObj = { - resObj: { - status: 504, - errorDetail: safeStringifyException(error), - }, - id: data.reqID, - }; - logger.error("request2 connector_error:", JSON.stringify(errorObj)); - client.emit("connector_error", errorObj); - } - }); - - client.on("disconnect", function (reason) { - // Unexpected disconnect as well as explicit disconnect request can be received here - logger.info("Client", client.id, "disconnected."); - logger.info("Reason :", reason); - }); - }); - - // Listen on provided port, on all network interfaces. - return new Promise((resolve) => - server.listen(sslport, () => resolve(server)), - ); -} - -if (require.main === module) { - // When this file executed as a script, not loaded as module - run the connector - startCDLSocketIOConnector() - .then((server) => { - const addr = server.address(); - - if (!addr) { - logger.error("Could not get running server address - exit."); - process.exit(1); - } - - const bind = - typeof addr === "string" ? "pipe " + addr : "port " + addr.port; - logger.debug("Listening on " + bind); - }) - .catch((err) => { - logger.error("Could not start cdl-socketio connector:", err); - }); -} diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/config.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/config.ts deleted file mode 100644 index ffada9f71c..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/common/core/config.ts +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2021 Hyperledger Cactus Contributors - * SPDX-License-Identifier: Apache-2.0 - * - * config.js - */ - -// TODO - Common - -export const DEFAULT_NODE_CONFIG_DIR = "/etc/cactus/connector-cdl-socketio/"; -if (!process.env["NODE_CONFIG_DIR"]) { - // Must be set before import config - process.env["NODE_CONFIG_DIR"] = DEFAULT_NODE_CONFIG_DIR; -} - -import config from "config"; - -/** - * Get configuration entry (uses node-config setup) - * - * @param key : Key to retrieve - * @param defaultValue : Value to return if key is not present in the config. - * @returns : Configuration value - */ -export function read(key: string, defaultValue?: T): T { - if (config.has(key)) { - return config.get(key); - } - - if (typeof defaultValue !== "undefined") { - return defaultValue; - } - - throw Error( - `Missing configuration entry '${key}', config dir = ${process.env["NODE_CONFIG_DIR"]}`, - ); -} diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ServerPlugin.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ServerPlugin.ts deleted file mode 100644 index 36f467138d..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ServerPlugin.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { FunctionArgsType } from "./type-defs"; -import { read as configRead } from "../common/core/config"; -import { cdlRequest } from "./cdl-request"; -import sanitizeHtml from "sanitize-html"; -import safeStringify from "fast-safe-stringify"; - -// Log settings -import { getLogger } from "log4js"; -const logger = getLogger("ServerPlugin[" + process.pid + "]"); -logger.level = configRead("logLevel", "info"); - -/* - * ServerPlugin - * Class definition for server plugins - */ -export class ServerPlugin { - /** - * Dispatch function that runs method with name from `args.method.type` with `args` arguments. - */ - async executeFunction(args: FunctionArgsType): Promise { - switch (args.method.type) { - case "registerHistoryData": - return this.registerHistoryData(args); - case "getLineage": - return this.getLineage(args); - case "searchByHeader": - return this.searchByHeader(args); - case "searchByGlobalData": - return this.searchByGlobalData(args); - case "status": - return this.status(args); - default: - const _unknownMethod: never = args.method.type; - throw new Error(`Unknown CDL ServerPlugin method: ${_unknownMethod}`); - } - } - - /** - * Throws if any property in an object starts with `cdl:` (not allowed by the API) - * @param properties object with string fields. - */ - private checkPropertyNames(properties?: Record) { - const invalidProps = Object.keys(properties ?? {}).filter((k) => - k.startsWith("cdl:"), - ); - if (invalidProps.length > 0) { - throw new Error( - `Properties can't start with 'cdl:'. Invalid properties provided: ${invalidProps}`, - ); - } - } - - /** - * Send request to `trail_registration` CDL endpoint. - */ - async registerHistoryData(args: FunctionArgsType): Promise { - logger.debug( - "ServerPlugin:registerHistoryData() args:", - JSON.stringify(args), - ); - - // Check args - const typedArgs = args.args as { - eventId?: string; - lineageId?: string; - tags?: Record; - properties?: Record; - }; - this.checkPropertyNames(typedArgs.tags); - this.checkPropertyNames(typedArgs.properties); - - const responseData = await cdlRequest( - `trail_registration`, - args.method.authInfo, - {}, - { - "cdl:EventId": typedArgs.eventId ?? "", - "cdl:LineageId": typedArgs.lineageId ?? "", - "cdl:Tags": typedArgs.tags, - ...typedArgs.properties, - }, - ); - - if (responseData.result !== "OK") { - throw new Error(sanitizeHtml(safeStringify(responseData))); - } - - logger.debug("registerHistoryData results:", responseData); - return responseData; - } - - /** - * Get data from `trail_acquisition` CDL endpoint. - */ - async getLineage(args: FunctionArgsType): Promise { - logger.debug("ServerPlugin:getLineage() args:", JSON.stringify(args)); - - // Check args - const typedArgs = args.args as { - eventId: string; - direction?: "backward" | "forward" | "both"; - depth?: string; - }; - - if (!typedArgs.eventId) { - throw new Error("Missing eventId in getLineage args!"); - } - const direction = (typedArgs.direction ?? "backward").toUpperCase(); - let depth = parseInt(typedArgs.depth ?? "-1", 10); - if (isNaN(depth)) { - logger.warn( - "Could not parse depth from the argument, using default (-1). Wrong input:", - typedArgs.depth, - ); - depth = -1; - } - - const responseData = await cdlRequest( - `trail_acquisition/${sanitizeHtml(typedArgs.eventId)}`, - args.method.authInfo, - { - direction, - depth, - }, - ); - - if (responseData.result !== "OK") { - throw new Error(sanitizeHtml(safeStringify(responseData))); - } - logger.debug("getLineage results:", responseData); - - return responseData; - } - - /** - * Search data using `trail_search_headers` CDL endpoint. - */ - async searchByHeader(args: FunctionArgsType): Promise { - logger.debug("ServerPlugin:searchByHeader() args:", JSON.stringify(args)); - return await searchRequest("trail_search_headers", args); - } - - /** - * Search data using `trail_search_globaldata` CDL endpoint. - */ - async searchByGlobalData(args: FunctionArgsType): Promise { - logger.debug( - "ServerPlugin:searchByGlobalData() args:", - JSON.stringify(args), - ); - return await searchRequest("trail_search_globaldata", args); - } - - /** - * Simple method to get current status of the connector plugin. - */ - async status(args: FunctionArgsType): Promise { - logger.debug("ServerPlugin:status() args:", JSON.stringify(args)); - return { - status: "OK.", - }; - } -} - -/** - * Common logic for sending trail search requests - */ -async function searchRequest( - searchType: "trail_search_headers" | "trail_search_globaldata", - args: FunctionArgsType, -) { - // Check args - const typedArgs = args.args as { - searchType: "exactmatch" | "partialmatch" | "regexpmatch"; - fields: Record; - }; - - if (!typedArgs.searchType || !typedArgs.fields) { - throw new Error("Missing required searchByHeader args!"); - } - - const responseData = await cdlRequest( - searchType, - args.method.authInfo, - {}, - { - searchType: typedArgs.searchType, - body: typedArgs.fields, - }, - ); - - if (responseData.result !== "OK") { - throw new Error(sanitizeHtml(safeStringify(responseData))); - } - - return responseData; -} diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ValidatorAuthentication.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ValidatorAuthentication.ts deleted file mode 100644 index 86179338f8..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/ValidatorAuthentication.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2023 Hyperledger Cacti Contributors - * SPDX-License-Identifier: Apache-2.0 - * - * ValidatorAuthentication.ts - */ - -import * as config from "../common/core/config"; - -import fs from "fs"; -import path from "path"; -import jwt from "jsonwebtoken"; - -import { getLogger } from "log4js"; -const logger = getLogger("ValidatorAuthentication[" + process.pid + "]"); -logger.level = config.read("logLevel", "info"); - -const privateKey = fs.readFileSync( - path.resolve(__dirname, config.read("sslParam.key")), -); - -export class ValidatorAuthentication { - static sign(payload: object): string { - const signature: string = jwt.sign(payload, privateKey, { - algorithm: "ES256", - expiresIn: "10000", - }); - logger.debug(`signature: OK`); - return signature; - } -} diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/cdl-request.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/cdl-request.ts deleted file mode 100644 index c9c6085687..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/cdl-request.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { - AuthInfoArgsType, - HTTP_HEADER_SUBSCRIPTION_KEY, - HTTP_HEADER_TRUST_USER_ID, - HTTP_HEADER_TRUST_USER_ROLE, - HTTP_HEADER_TRUST_AGENT_ID, - HTTP_HEADER_TRUST_AGENT_ROLE, - isAuthInfoAccessTokenArgsType, - isAuthInfoSubscriptionKeyArgsType, -} from "./type-defs"; -import { read as configRead } from "../common/core/config"; -import axios from "axios"; -import https from "https"; - -// Log settings -import { getLogger } from "log4js"; -import { readFileSync } from "fs"; -const logger = getLogger("cdl-request[" + process.pid + "]"); -logger.level = configRead("logLevel", "info"); - -type HTTPAuthHeadersType = Record; - -function createHttpsGatewayConfig( - gatewayKey: "cdlApiGateway" | "cdlApiSubscriptionGateway", -) { - const agentOptions: https.AgentOptions = {}; - - const skipCertCheck = configRead( - `${gatewayKey}.skipCertCheck`, - false, - ); - if (skipCertCheck) { - logger.info( - `Allowing self signed CDL API GW certificates (skipCertCheck=${skipCertCheck})`, - ); - agentOptions.rejectUnauthorized = !skipCertCheck; - } - - const caPath = configRead(`${gatewayKey}.caPath`, ""); - if (caPath) { - logger.info(`Using CDL API GW CA ${caPath}`); - const gatewayCAString = readFileSync(caPath, "ascii"); - logger.debug("CDL Gateway certificate read:", gatewayCAString); - agentOptions.ca = gatewayCAString; - } - - const serverName = configRead(`${gatewayKey}.serverName`, ""); - if (serverName) { - logger.info(`Overwrite CDL API GW server name with '${serverName}'`); - agentOptions.servername = serverName; - } - - return { - baseURL: configRead(`${gatewayKey}.url`), - httpsAgent: new https.Agent(agentOptions), - }; -} - -const API_GATEWAY_CONFIG = createHttpsGatewayConfig("cdlApiGateway"); -const API_SUBSCRIPTION_GATEWAY_CONFIG = createHttpsGatewayConfig( - "cdlApiSubscriptionGateway", -); - -function getHttpsGatewayConfigForHeaders(headers: HTTPAuthHeadersType) { - if (HTTP_HEADER_SUBSCRIPTION_KEY in headers) { - logger.debug("Using subscription key gateway for this request"); - return API_SUBSCRIPTION_GATEWAY_CONFIG; - } - - logger.debug("Using access token gateway for this request"); - return API_GATEWAY_CONFIG; -} - -export async function cdlRequest( - url: string, - authInfo: AuthInfoArgsType, - queryParams?: any, - dataPayload?: any, -) { - let httpMethod = "get"; - if (dataPayload) { - httpMethod = "post"; - } - - logger.debug(`cdlRequest ${httpMethod} ${url} executed`); - - const authHeaders = getAuthorizationHeaders(authInfo); - const { httpsAgent, baseURL } = getHttpsGatewayConfigForHeaders(authHeaders); - - try { - const requestResponse = await axios({ - httpsAgent, - method: httpMethod, - baseURL, - url, - responseType: "json", - headers: { - "User-Agent": configRead("userAgent", "CactiCDLConnector"), - "Content-Type": "application/json;charset=UTF-8", - ...authHeaders, - }, - params: queryParams, - data: dataPayload, - }); - - return requestResponse.data; - } catch (error: any) { - if ("toJSON" in error) { - logger.error("CDL API request failed:", error.toJSON()); - } - - throw error; - } -} - -function getAuthorizationHeaders( - authInfo: AuthInfoArgsType, -): HTTPAuthHeadersType { - if ( - isAuthInfoAccessTokenArgsType(authInfo) && - isAuthInfoSubscriptionKeyArgsType(authInfo) - ) { - throw new Error( - "Mixed authInfo configuration detected - use either accessToken or subscriptionKey!", - ); - } - - if (isAuthInfoAccessTokenArgsType(authInfo)) { - return { - Authorization: `Bearer ${authInfo.accessToken}`, - [HTTP_HEADER_TRUST_AGENT_ID]: authInfo.trustAgentId, - }; - } else if (isAuthInfoSubscriptionKeyArgsType(authInfo)) { - return { - [HTTP_HEADER_SUBSCRIPTION_KEY]: authInfo.subscriptionKey, - [HTTP_HEADER_TRUST_USER_ID]: authInfo.trustUserId, - [HTTP_HEADER_TRUST_USER_ROLE]: authInfo.trustUserRole, - [HTTP_HEADER_TRUST_AGENT_ID]: authInfo.trustAgentId, - [HTTP_HEADER_TRUST_AGENT_ROLE]: authInfo.trustAgentRole, - }; - } else { - throw new Error( - "Missing authInfo information or information not complete!", - ); - } -} diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/type-defs.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/type-defs.ts deleted file mode 100644 index 111c2f6bf0..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/connector/type-defs.ts +++ /dev/null @@ -1,63 +0,0 @@ -export type SupportedFunctions = - | "registerHistoryData" - | "getLineage" - | "searchByHeader" - | "searchByGlobalData" - | "status"; - -export type AuthInfoAccessTokenArgsType = { - accessToken: string; - trustAgentId: string; -}; - -export type AuthInfoSubscriptionKeyArgsType = { - subscriptionKey: string; - trustAgentId: string; - trustAgentRole: string; - trustUserId: string; - trustUserRole: string; -}; - -export type AuthInfoArgsType = - | AuthInfoAccessTokenArgsType - | AuthInfoSubscriptionKeyArgsType; - -export function isAuthInfoAccessTokenArgsType( - authInfo: AuthInfoArgsType, -): authInfo is AuthInfoAccessTokenArgsType { - const typedAuthInfo = authInfo as AuthInfoAccessTokenArgsType; - return ( - typedAuthInfo && - typeof typedAuthInfo.accessToken !== "undefined" && - typeof typedAuthInfo.trustAgentId !== "undefined" - ); -} - -export function isAuthInfoSubscriptionKeyArgsType( - authInfo: AuthInfoArgsType, -): authInfo is AuthInfoSubscriptionKeyArgsType { - const typedAuthInfo = authInfo as AuthInfoSubscriptionKeyArgsType; - return ( - typedAuthInfo && - typeof typedAuthInfo.subscriptionKey !== "undefined" && - typeof typedAuthInfo.trustAgentId !== "undefined" && - typeof typedAuthInfo.trustAgentRole !== "undefined" && - typeof typedAuthInfo.trustUserId !== "undefined" && - typeof typedAuthInfo.trustUserRole !== "undefined" - ); -} - -export type FunctionArgsType = { - method: { - type: SupportedFunctions; - authInfo: AuthInfoArgsType; - }; - args: any; - reqID?: string; -}; - -export const HTTP_HEADER_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; -export const HTTP_HEADER_TRUST_USER_ID = "Trust-User-Id"; -export const HTTP_HEADER_TRUST_USER_ROLE = "Trust-User-Role"; -export const HTTP_HEADER_TRUST_AGENT_ID = "Trust-Agent-Id"; -export const HTTP_HEADER_TRUST_AGENT_ROLE = "Trust-Agent-Role"; diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/index.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/index.ts deleted file mode 100644 index 87cb558397..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./public-api"; diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/public-api.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/public-api.ts deleted file mode 100644 index 136baee164..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/main/typescript/public-api.ts +++ /dev/null @@ -1 +0,0 @@ -export { startCDLSocketIOConnector } from "./common/core/bin/www"; diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/test/typescript/integration/cdl-connector-socketio-manual.test.ts b/packages/cactus-plugin-ledger-connector-cdl-socketio/src/test/typescript/integration/cdl-connector-socketio-manual.test.ts deleted file mode 100644 index 56fe65e8c2..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/src/test/typescript/integration/cdl-connector-socketio-manual.test.ts +++ /dev/null @@ -1,482 +0,0 @@ -/** - * Manual tests for CDL connector. - * Must be exectued with access to CDL service. - * Check out CDL connector readme for instructions on how to run these tests. - */ - -////////////////////////////////// -// Constants -////////////////////////////////// - -// Setup: Start validator first and store it's crt under this path -const VALIDATOR_KEY_PATH = - "/etc/cactus/connector-cdl-socketio/CA/connector.crt"; - -// Setup: Obtain eitehr accessToken or subscription key and fill matching authInfo structure below. -// const authInfo = { -// accessToken: "_____accessToken_____" -// trustAgentId: "_____trustAgentId_____", -// }; -const authInfo = { - subscriptionKey: "_____subscriptionKey_____", - trustAgentId: "_____trustAgentId_____", - trustAgentRole: "_____trustAgentRole_____", - trustUserId: "_____trustUserId_____", - trustUserRole: "_____trustUserRole_____", -}; - -const testLogLevel: LogLevelDesc = "info"; -const sutLogLevel: LogLevelDesc = "info"; -const setupTimeout = 1000 * 60; // 1 minute timeout for setup - -// ApiClient settings -const syncReqTimeout = 1000 * 10; // 10 seconds - -import { - LogLevelDesc, - LoggerProvider, - Logger, -} from "@hyperledger/cactus-common"; -import { SocketIOApiClient } from "@hyperledger/cactus-api-client"; - -import "jest-extended"; -import { Server as HttpsServer } from "https"; -import { v4 as uuidv4 } from "uuid"; - -import * as cdlConnector from "../../../main/typescript/index"; - -// Logger setup -const log: Logger = LoggerProvider.getOrCreate({ - label: "cdl-connector-manual.test", - level: testLogLevel, -}); - -describe("CDL Connector manual tests", () => { - let connectorServer: HttpsServer; - let apiClient: SocketIOApiClient; - - ////////////////////////////////// - // Helper Methods - ////////////////////////////////// - - async function registerHistoryDataOnCDL(args: any = {}) { - const response = await apiClient.sendSyncRequest( - {}, - { - type: "registerHistoryData", - authInfo, - }, - args, - ); - - log.debug("registerHistoryData response:", JSON.stringify(response)); - - expect(response.status).toEqual(200); - expect(response.data.result).toEqual("OK"); - const event = response.data.detail; - expect(event).toBeTruthy(); - expect(event["cdl:Lineage"]).toBeTruthy(); - expect(event["cdl:Lineage"]["cdl:EventId"]).toBeTruthy(); - expect(event["cdl:Lineage"]["cdl:LineageId"]).toBeTruthy(); - expect(event["cdl:Tags"]).toBeTruthy(); - expect(event["cdl:Verification"]).toBeTruthy(); - return event; - } - - async function getLineageFromCDL(args: any = {}): Promise { - const response = await apiClient.sendSyncRequest( - {}, - { - type: "getLineage", - authInfo, - }, - args, - ); - - log.debug("getLineage response:", JSON.stringify(response)); - - expect(response.status).toEqual(200); - expect(response.data.result).toEqual("OK"); - const eventList = response.data.detail; - expect(eventList).toBeTruthy(); - expect(eventList.length).toBeGreaterThan(0); - return eventList; - } - - async function searchByHeaderOnCDL(args: any = {}): Promise { - const response = await apiClient.sendSyncRequest( - {}, - { - type: "searchByHeader", - authInfo, - }, - args, - ); - - log.debug("searchByHeaderOnCDL response:", JSON.stringify(response)); - - expect(response.status).toEqual(200); - expect(response.data.result).toEqual("OK"); - const eventList = response.data.detail; - expect(eventList).toBeTruthy(); - return eventList; - } - - async function searchByGlobalDataOnCDL(args: any = {}): Promise { - const response = await apiClient.sendSyncRequest( - {}, - { - type: "searchByGlobalData", - authInfo, - }, - args, - ); - - log.debug("searchByGlobalData response:", JSON.stringify(response)); - - expect(response.status).toEqual(200); - expect(response.data.result).toEqual("OK"); - const eventList = response.data.detail; - expect(eventList).toBeTruthy(); - return eventList; - } - - ////////////////////////////////// - // Environment Setup - ////////////////////////////////// - - beforeAll(async () => { - // Run the connector - connectorServer = await cdlConnector.startCDLSocketIOConnector(); - expect(connectorServer).toBeTruthy(); - const connectorAddress = connectorServer.address(); - if (!connectorAddress || typeof connectorAddress === "string") { - throw new Error("Unexpected CDL connector AddressInfo type"); - } - log.info( - "CDL-SocketIO Connector started on:", - `${connectorAddress.address}:${connectorAddress.port}`, - ); - - // Create ApiClient instance - const apiConfigOptions = { - validatorID: "cdl-connector-manual.test", - validatorURL: `https://127.0.0.1:${connectorAddress.port}`, - validatorKeyPath: VALIDATOR_KEY_PATH, - logLevel: sutLogLevel, - maxCounterRequestID: 1000, - syncFunctionTimeoutMillisecond: syncReqTimeout, - socketOptions: { - rejectUnauthorized: false, - reconnection: false, - timeout: syncReqTimeout * 2, - }, - }; - log.debug("ApiClient config:", apiConfigOptions); - apiClient = new SocketIOApiClient(apiConfigOptions); - }, setupTimeout); - - afterAll(async () => { - log.info("FINISHING THE TESTS"); - - if (apiClient) { - log.info("Close ApiClient connection..."); - apiClient.close(); - } - - if (connectorServer) { - log.info("Stop the CDL connector..."); - await new Promise((resolve) => - connectorServer.close(() => resolve()), - ); - } - - // SocketIOApiClient has timeout running for each request which is not cancellable at the moment. - // Wait timeout amount of seconds to make sure all handles are closed. - await new Promise((resolve) => setTimeout(resolve, syncReqTimeout)); - }, setupTimeout); - - ////////////////////////////////// - // Tests - ////////////////////////////////// - - /** - * Test if connector was started correctly and communication is possible - */ - test("Get connector status", async () => { - const argsParam = { - args: ["test1", "test2"], - }; - - const response = await apiClient.sendSyncRequest( - {}, - { - type: "status", - }, - argsParam, - ); - - log.debug("Status response:", response); - expect(response.status).toEqual(200); - expect(response.data.status).toEqual("OK."); - }); - - test( - "Request fails when authInfo is missing", - async () => { - const response = await apiClient.sendSyncRequest( - {}, - { - type: "registerHistoryData", - }, - { - eventId: "", - lineageId: "", - tags: {}, - properties: { - prop1: "shouldFail", - prop2: "shouldFail", - }, - }, - ); - expect(response.status).toEqual(504); - }, - syncReqTimeout * 2, - ); - - test( - "Request fails when mixed authInfo is used", - async () => { - const response = await apiClient.sendSyncRequest( - {}, - { - type: "registerHistoryData", - authInfo: { - accessToken: "foo-accessToken", - subscriptionKey: "foo-subscriptionKey", - trustAgentId: "foo-trustAgentId", - trustAgentRole: "foo-trustAgentRole", - trustUserId: "foo-trustUserId", - trustUserRole: "foo-trustUserRole", - }, - }, - { - eventId: "", - lineageId: "", - tags: {}, - properties: { - prop1: "shouldFail", - prop2: "shouldFail", - }, - }, - ); - expect(response.status).toEqual(504); - }, - syncReqTimeout * 2, - ); - - test("Register single history data", async () => { - const newEvent = await registerHistoryDataOnCDL({ - eventId: "", - lineageId: "", - tags: { - test: "abc", - }, - properties: { - prop1: "abc", - prop2: "cba", - }, - }); - - // Check custom properties and tags - expect(newEvent["cdl:Event"]["prop1"]).toEqual("abc"); - expect(newEvent["cdl:Event"]["prop2"]).toEqual("cba"); - expect(newEvent["cdl:Tags"]["test"]).toEqual("abc"); - }); - - test("Register history data in signle lineage", async () => { - const firstEvent = await registerHistoryDataOnCDL(); - const firstEventId = firstEvent["cdl:Lineage"]["cdl:EventId"]; - - const secondEvent = await registerHistoryDataOnCDL({ - lineageId: firstEventId, - }); - - // Check if two events belong to same lineage - expect(secondEvent["cdl:Lineage"]["cdl:LineageId"]).toEqual(firstEventId); - }); - - /** - * Tests for getLineage endpoint - */ - describe("Get lineage tests", () => { - const eventsInLineage: string[] = []; - - beforeAll(async () => { - const firstEvent = await registerHistoryDataOnCDL(); - const firstEventId = firstEvent["cdl:Lineage"]["cdl:EventId"]; - log.info("First eventId (lineageId):", firstEventId); - eventsInLineage.push(firstEventId); - - for (let i = 0; i < 2; i++) { - const event = await registerHistoryDataOnCDL({ - lineageId: firstEventId, - }); - eventsInLineage.push(event["cdl:Lineage"]["cdl:EventId"]); - } - - log.info("Events in test lineage:", eventsInLineage); - }); - - // both middle - test("Get lineage forward all (default) on the first event (lineageId)", async () => { - const eventList = await getLineageFromCDL({ - eventId: eventsInLineage[0], - direction: "forward", - depth: "-1", - }); - - // Forward from first should return all events in lineage - expect(eventList.length).toEqual(eventsInLineage.length); - }); - - test("Get lineage forward all (default) on the last event", async () => { - const eventList = await getLineageFromCDL({ - eventId: eventsInLineage[eventsInLineage.length - 1], - direction: "forward", - depth: "-1", - }); - - // Forward from last should return only one event - expect(eventList.length).toEqual(1); - }); - - test("Get lineage backward all on the last event", async () => { - const eventList = await getLineageFromCDL({ - eventId: eventsInLineage[eventsInLineage.length - 1], - direction: "backward", - depth: "-1", - }); - - // Backward from last should return all events in lineage - expect(eventList.length).toEqual(eventsInLineage.length); - }); - - test("Get lineage both all on the middle event", async () => { - const eventList = await getLineageFromCDL({ - eventId: eventsInLineage[1], - direction: "both", - depth: "-1", - }); - - // Both on middle event should return all events in lineage - expect(eventList.length).toEqual(eventsInLineage.length); - }); - }); - - /** - * Tests for searchByHeader and searchByGlobalData endpoints - */ - describe("Search data tests", () => { - const privateTagValue = uuidv4(); - const customEventPropValue = uuidv4(); - let searchedEvent: any; - let searchedEventTimestamp: string; - - beforeAll(async () => { - searchedEvent = await registerHistoryDataOnCDL({ - tags: { - privateTag: privateTagValue, - }, - properties: { - customEventProp: customEventPropValue, - }, - }); - log.info("Event to search for:", searchedEvent); - - searchedEventTimestamp = - searchedEvent["cdl:Lineage"]["cdl:DataRegistrationTimeStamp"]; - }); - - test("Search header data using exact match", async () => { - log.info( - "Search for events with exact timestamp:", - searchedEventTimestamp, - ); - const events = await searchByHeaderOnCDL({ - searchType: "exactmatch", - fields: { - "cdl:DataRegistrationTimeStamp": searchedEventTimestamp, - }, - }); - - expect(events).toBeTruthy(); - expect(events.length).toBeGreaterThan(0); - for (const e of events) { - expect(e["cdl:Lineage"]["cdl:DataRegistrationTimeStamp"]).toEqual( - searchedEventTimestamp, - ); - } - }); - - test("Search header data using partial match", async () => { - const datePart = searchedEventTimestamp.split("T")[0]; - log.info("Search for events with partialmatch (date):", datePart); - - const events = await searchByHeaderOnCDL({ - searchType: "partialmatch", - fields: { - "cdl:DataRegistrationTimeStamp": datePart, - }, - }); - - expect(events).toBeTruthy(); - expect(events.length).toBeGreaterThan(0); - for (const e of events) { - expect(e["cdl:Lineage"]["cdl:DataRegistrationTimeStamp"]).toMatch( - datePart, - ); - } - }); - - test("Search header data using regex match", async () => { - const datePart = searchedEventTimestamp.split("T")[0]; - const dateRegex = `^${datePart}.*$`; - log.info("Search for events with regexpmatch:", dateRegex); - - const events = await searchByHeaderOnCDL({ - searchType: "regexpmatch", - fields: { - "cdl:DataRegistrationTimeStamp": dateRegex, - }, - }); - - expect(events).toBeTruthy(); - expect(events.length).toBeGreaterThan(0); - for (const e of events) { - expect(e["cdl:Lineage"]["cdl:DataRegistrationTimeStamp"]).toMatch( - datePart, - ); - } - }); - - test("Search global data using exact match", async () => { - log.info( - "Search for events with exact customEventProp:", - customEventPropValue, - ); - const events = await searchByGlobalDataOnCDL({ - searchType: "exactmatch", - fields: { - customEventProp: customEventPropValue, - }, - }); - - expect(events).toBeTruthy(); - expect(events.length).toEqual(1); - for (const e of events) { - expect(e["cdl:Event"]["customEventProp"]).toEqual(customEventPropValue); - } - }); - }); -}); diff --git a/packages/cactus-plugin-ledger-connector-cdl-socketio/tsconfig.json b/packages/cactus-plugin-ledger-connector-cdl-socketio/tsconfig.json deleted file mode 100644 index ac1f3bd372..0000000000 --- a/packages/cactus-plugin-ledger-connector-cdl-socketio/tsconfig.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "composite": true, - "outDir": "./dist/lib", - "declarationDir": "./dist/lib", - "rootDir": "./src", - "sourceMap": false, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "tsBuildInfoFile": "../../.build-cache/cactus-plugin-ledger-connector-cdl-socketio.tsbuildinfo" - }, - "include": [ - "./src/main/typescript/common/core/*.ts", - "./src/main/typescript/common/core/bin/*.ts", - "./src/main/typescript/common/core/config/*.ts", - "./src/main/typescript/connector/*.ts", - "./src/main/typescript/*.ts", - "./src/test/typescript/integration/*.ts" - ], - "references": [ - { - "path": "../cactus-common/tsconfig.json" - }, - { - "path": "../cactus-api-client/tsconfig.json" - } - ] -} diff --git a/tsconfig.json b/tsconfig.json index 3eead32f3c..1596e77339 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -70,9 +70,6 @@ { "path": "./packages/cactus-plugin-ledger-connector-cdl/tsconfig.json" }, - { - "path": "./packages/cactus-plugin-ledger-connector-cdl-socketio/tsconfig.json" - }, { "path": "./packages/cactus-plugin-ledger-connector-iroha/tsconfig.json" }, diff --git a/yarn.lock b/yarn.lock index e3ef7dad67..63f7c46c17 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7812,36 +7812,6 @@ __metadata: languageName: unknown linkType: soft -"@hyperledger/cactus-plugin-ledger-connector-cdl-socketio@workspace:packages/cactus-plugin-ledger-connector-cdl-socketio": - version: 0.0.0-use.local - resolution: "@hyperledger/cactus-plugin-ledger-connector-cdl-socketio@workspace:packages/cactus-plugin-ledger-connector-cdl-socketio" - dependencies: - "@hyperledger/cactus-api-client": 2.0.0-alpha.2 - "@hyperledger/cactus-common": 2.0.0-alpha.2 - "@types/config": 0.0.41 - "@types/cookie-parser": 1.4.3 - "@types/express": 4.17.19 - "@types/http-errors": 2.0.1 - "@types/jsonwebtoken": 9.0.2 - "@types/node": 14.18.54 - "@types/sanitize-html": 2.6.2 - axios: 1.6.0 - body-parser: 1.20.2 - config: 3.3.7 - cookie-parser: 1.4.6 - express: 4.18.2 - fast-safe-stringify: 2.1.1 - http-errors: 1.6.3 - jest-extended: 4.0.1 - js-yaml: 3.14.1 - jsonwebtoken: 9.0.0 - log4js: 6.4.1 - sanitize-html: 2.7.0 - socket.io: 4.5.4 - uuid: 8.3.2 - languageName: unknown - linkType: soft - "@hyperledger/cactus-plugin-ledger-connector-cdl@workspace:packages/cactus-plugin-ledger-connector-cdl": version: 0.0.0-use.local resolution: "@hyperledger/cactus-plugin-ledger-connector-cdl@workspace:packages/cactus-plugin-ledger-connector-cdl" @@ -13075,15 +13045,6 @@ __metadata: languageName: node linkType: hard -"@types/cookie-parser@npm:1.4.3": - version: 1.4.3 - resolution: "@types/cookie-parser@npm:1.4.3" - dependencies: - "@types/express": "*" - checksum: f390f3af1b1711190dee2c2ecd9af33af81fbde8d81ee820dadb6fe1e0d80c3faba40af37c6ed36fb88b04b64870f6a021f7e9edceecd17c42fe22abe0af5005 - languageName: node - linkType: hard - "@types/cookie-parser@npm:1.4.5": version: 1.4.5 resolution: "@types/cookie-parser@npm:1.4.5"