Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/remote key manager #202

Open
wants to merge 17 commits into
base: feature/p2pmessaging
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
modified remoteKeyManager, remoteKeyHost, remoteKeyClient functionali…
…ties
indramalav committed Jun 2, 2020
commit 4444029c2f369ccdb20f2f43ab9c6c5e569d1887
4 changes: 2 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@
"jsdom-global/register",
"--allow-uncaught",
"--colors",
"--timeout 50000",
"--timeout 100000",
// "--reporter",
// "mocha-reporter",
"${workspaceFolder}/src/test/*.ts"
@@ -35,7 +35,7 @@
"request": "attach",
"port": 9229,
"protocol": "inspector",
"timeout": 30000,
"timeout": 100000,
"stopOnEntry": false
}
]
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
},
"mochaExplorer.files": ["src/test/*.ts", "src/test/crux-messenger/*.ts", "src/test/integration-tests/crux-messenger/*.ts"],
"mochaExplorer.require": ["ts-node/register", "mock-local-storage", "jsdom-global/register"],
"mochaExplorer.timeout": 80000,
"mochaExplorer.timeout": 100000,
"testExplorer.codeLens": true,
"testExplorer.gutterDecoration": true,
"testExplorer.onStart": "reset",
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@
"test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 50000 src/test/*.ts src/test/crux-messenger/*.ts",
"start-bridge-server": "node dist/crux-gateway-bridge-without-auth.js &",
"stop-bridge-server": "pkill -- signal SIGINT crux-gateway-bridge-server-without-auth",
"integration-test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 50000 src/test/integration-tests/crux-messenger/*.ts",
"integration-test": "TS_NODE_PROJECT='./src/test/tsconfig.commonjs.json' TS_NODE_TRANSPILE_ONLY=true ./node_modules/.bin/mocha --exit --require ts-node/register --require mock-local-storage --require jsdom-global/register --allow-uncaught --colors --reporter mocha-reporter --timeout 80000 src/test/integration-tests/crux-messenger/*.ts",
"integration": "npm run build-crux-bridge-server-without-auth && npm run start-bridge-server && npm run integration-test && npm run stop-bridge-server",
"copy-latest-docs": "cp -a docs/$npm_package_version/. docs/",
"version-docs": "./node_modules/.bin/typedoc --out docs/$npm_package_version src/index.ts",
4 changes: 2 additions & 2 deletions src/application/clients/crux-gateway-bridge-config.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"HOST_URL": {
"BROKER_HOST": "127.0.0.1"
"BROKER_HOST": "broker.hivemq.com"
},
"PORTS": {
"BROKER_PORT": 1883,
"BROKER_PORT": 8000,
"TCP_PORT": 4005
}
}
14 changes: 9 additions & 5 deletions src/application/clients/crux-service-client.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import { RemoteKeyManager, SecureCruxIdMessenger } from "../../core/domain-services";
import { RemoteKeyManager, SecureCruxNetwork } from "../../core/domain-services";
import { CruxId, InMemStorage } from "../../packages/";
import { CruxWalletClient } from "./crux-wallet-client";

export class CruxServiceClient {
private selfIdClaim: any;
private secureCruxIdMessenger: SecureCruxIdMessenger;
private secureCruxNetwork: SecureCruxNetwork;

constructor(selfIdClaim: any, userRepo: any, pubsubClientFactory: any) {
this.selfIdClaim = selfIdClaim;
this.secureCruxIdMessenger = new SecureCruxIdMessenger(userRepo, pubsubClientFactory, selfIdClaim);
this.secureCruxNetwork = new SecureCruxNetwork(userRepo, pubsubClientFactory, selfIdClaim);
}

public getWalletClientForUser(remoteUserId: CruxId) {
public async getWalletClientForUser(remoteUserId: CruxId) {
await this.secureCruxNetwork.initialize();
const remoteKeyManager = new RemoteKeyManager(this.secureCruxNetwork, remoteUserId);
await remoteKeyManager.initialize();
return new CruxWalletClient({
cacheStorage: new InMemStorage(),
privateKey: new RemoteKeyManager(this.secureCruxIdMessenger, remoteUserId),
// @ts-ignore
privateKey: remoteKeyManager,
walletClientName: remoteUserId.components.domain,
});
}
1 change: 1 addition & 0 deletions src/application/clients/crux-wallet-client.ts
Original file line number Diff line number Diff line change
@@ -472,6 +472,7 @@ export class CruxWalletClient {
this.paymentProtocolMessenger = new CruxProtocolMessenger(this.secureCruxNetwork, cruxPaymentProtocol);
const remoteKeyHost = new RemoteKeyHost(this.secureCruxNetwork, this.keyManager!);
this.remoteKeyHost = remoteKeyHost;
await this.remoteKeyHost.initialize();
}
}

4 changes: 3 additions & 1 deletion src/core/domain-services/crux-messenger.ts
Original file line number Diff line number Diff line change
@@ -252,7 +252,9 @@ export class SecureContext {
data,
};
const serializedSecurePacket = JSON.stringify(securePacket);

if (typeof recipientId === "string") {
recipientId = CruxId.fromString(recipientId);
}
const recipientCruxUser: CruxUser | undefined = await this.cruxUserRepo.getByCruxId(recipientId);
if (!recipientCruxUser) {
throw Error("No Such CRUX User Found");
83 changes: 41 additions & 42 deletions src/core/domain-services/remote-key-service.ts
Original file line number Diff line number Diff line change
@@ -2,55 +2,47 @@ import {makeUUID4} from "blockstack/lib";
import { createNanoEvents, DefaultEvents, Emitter } from "nanoevents";
import { CruxId } from "src/packages";
import { IKeyManager } from "../interfaces";
import { SecureCruxIdMessenger } from "./crux-messenger";
import { SecureCruxNetwork } from "./crux-messenger";

const VALID_METHODS = ["signWebToken", "getPubKey", "deriveSharedSecret", "decryptMessage"];

export class RemoteKeyClient {
private secureCruxIdMessenger: SecureCruxIdMessenger;
private secureCruxNetwork: SecureCruxNetwork;
private remoteUserId: CruxId;
private emitter: Emitter<DefaultEvents>;

constructor(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) {
this.secureCruxIdMessenger = secureCruxIdMessenger;
constructor(secureCruxNetwork: SecureCruxNetwork, remoteUserId: CruxId) {
this.secureCruxNetwork = secureCruxNetwork;
this.remoteUserId = remoteUserId;
this.emitter = createNanoEvents();
this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => {
console.log("Inside RemoteKeyClient Constructor:: ", msg, senderId);
}

public async initialize() {
this.secureCruxNetwork.receive(async (msg: any, senderId: CruxId | undefined) => {
console.log("Inside RemoteKeyClient::initialize::Msg, senderId: ", msg, senderId);
this.emitter.emit(msg.invocationId, msg, senderId);
}, (err: any) => {
});
this.secureCruxNetwork.onError((err: any) => {
console.log("errorinvocationListener", err);
this.emitter.emit("error", err);
return;
});
}

public async invoke(method: string, args: any[]) {
console.log("RemoteKeyClient::Inside Invoke");
if (!this.secureCruxIdMessenger) {
throw Error("RemoteKeyClient cannot send with no selfMessenger");
if (!this.secureCruxNetwork) {
throw Error("RemoteKeyClient cannot send with no secureCruxNetwork");
}
const methodData = this.generateMethodData(method, args);
console.log("RemoteKeyClient::Inside Invoke, RemoteUserId, MethodData", this.remoteUserId, methodData);
await this.secureCruxIdMessenger.send(methodData, this.remoteUserId);
await this.secureCruxNetwork.send(this.remoteUserId, methodData);
return methodData.invocationId;
}

public invokeResult = (resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => {
if (!this.secureCruxIdMessenger) {
throw Error("RemoteKeyClient cannot listen with no selfMessenger");
}
this.secureCruxIdMessenger.listen((msg: any, senderId: CruxId | undefined) => {
console.log("RemoteKeyClient::Inside invokeresult", msg, senderId);
resultCallback(msg, senderId);
}, (err: any) => {
errorCallback(err);
return;
});
}

public listenToInvocation = (invocationId: string, resultCallback: (msg: any, senderId: CruxId | undefined) => any, errorCallback: (err: any) => any): void => {
if (!this.secureCruxIdMessenger) {
throw Error("RemoteKeyClient cannot listen with no selfMessenger");
if (!this.secureCruxNetwork) {
throw Error("RemoteKeyClient cannot listen with no secureCruxNetwork");
}
console.log("RemoteKeyClient::ListenToInvocation::invocationId", invocationId);
this.emitter.on(invocationId, resultCallback);
@@ -67,30 +59,33 @@ export class RemoteKeyClient {
}

export class RemoteKeyHost {
private secureCruxIdMessenger: SecureCruxIdMessenger;
private secureCruxNetwork: SecureCruxNetwork;
private keyManager: IKeyManager;

constructor(secureCruxIdMessenger: SecureCruxIdMessenger, keyManager: IKeyManager) {
constructor(secureCruxNetwork: SecureCruxNetwork, keyManager: IKeyManager) {
this.keyManager = keyManager;
this.secureCruxIdMessenger = secureCruxIdMessenger;
this.secureCruxIdMessenger.listen(async (msg: any, senderId: CruxId | undefined) => {
console.log("Inside RemoteKeyHost::Constructor::Msg, senderId: ", msg, senderId);
this.secureCruxNetwork = secureCruxNetwork;
}

public async initialize() {
this.secureCruxNetwork.receive(async (msg: any, senderId: CruxId | undefined) => {
console.log("Inside RemoteKeyHost::in::Msg, senderId: ", msg, senderId);
const data = await this.handleMessage(msg);
console.log("Inside RemoteKeyHost::Constructor::Data(handleMessage): ", data);
this.sendInvocationResult(data, senderId);
}, (err: any) => {
console.log("Inside RemoteKeyHost::initialize::Data(handleMessage): ", data);
this.sendInvocationResult(data, senderId!);
});
this.secureCruxNetwork.onError((err: any) => {
console.log("errorinvocationListener", err);
return;
});
}

private async sendInvocationResult(result: any, receiverId: CruxId) {
if (!this.secureCruxIdMessenger) {
if (!this.secureCruxNetwork) {
throw Error("RemoteKeyClient cannot send with no selfMessenger");
}
const resultData = this.generateInvocationResponse(result);
console.log("RemoteKeyHost::Inside sendInvocationResult::resultData: ", resultData);
await this.secureCruxIdMessenger.send(resultData, receiverId);
await this.secureCruxNetwork.send(receiverId, resultData);
}

private async handleMessage(message: any) {
@@ -138,12 +133,16 @@ export class RemoteKeyManager implements IKeyManager {
private remoteKeyClient: RemoteKeyClient;
private remoteUserId: CruxId;

constructor(secureCruxIdMessenger: SecureCruxIdMessenger, remoteUserId: CruxId) {
this.remoteKeyClient = new RemoteKeyClient(secureCruxIdMessenger, remoteUserId);
constructor(secureCruxNetwork: SecureCruxNetwork, remoteUserId: CruxId) {
this.remoteKeyClient = new RemoteKeyClient(secureCruxNetwork, remoteUserId);
this.remoteUserId = remoteUserId;
}

public async initialize() {
await this.remoteKeyClient.initialize();
}
// @ts-ignore
public async signWebToken(token: any) {
public signWebToken = async (token: any) => {
return new Promise(async (resolve, reject) => {
const invocationId = await this.remoteKeyClient.invoke("signWebToken", [token]);
console.log("RemoteKeyManager::signWebToken::invokationId: ", invocationId);
@@ -156,7 +155,7 @@ export class RemoteKeyManager implements IKeyManager {
});
}
// @ts-ignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove ts ignore and fix errors. Let me know if you're getting confused with 'args' and how to make it generic for arguments.

public async getPubKey() {
public getPubKey = async () => {
return new Promise(async (resolve, reject) => {
const invocationId = await this.remoteKeyClient.invoke("getPubKey", []);
console.log("RemoteKeyManager::getPubKey::invokationId: ", invocationId);
@@ -169,7 +168,7 @@ export class RemoteKeyManager implements IKeyManager {
});
}
// @ts-ignore
public async deriveSharedSecret(publicKey: string) {
public deriveSharedSecret = async (publicKey: string) => {
const invocationId = await this.remoteKeyClient.invoke("deriveSharedSecret", [publicKey]);
console.log("RemoteKeyManager::deriveSharedSecret::invokationId: ", invocationId);
return new Promise(async (resolve, reject) => {
@@ -182,7 +181,7 @@ export class RemoteKeyManager implements IKeyManager {
});
}
// @ts-ignore
public async decryptMessage(encryptedMessage: string) {
public decryptMessage = async (encryptedMessage: string) => {
console.log("RemoteKeyManager::decryptMessage::entry: encryptedMessage: ", encryptedMessage);
const invocationId = await this.remoteKeyClient.invoke("decryptMessage", [encryptedMessage]);
console.log("RemoteKeyManager::decryptMessage::invokationId: ", invocationId);
14 changes: 7 additions & 7 deletions src/infrastructure/implementations/crux-messenger.ts
Original file line number Diff line number Diff line change
@@ -124,7 +124,7 @@ export class PahoClient implements IPubSubClient {
}

public connect = () => {
console.log("PahoClient trying to connect");
console.log("PahoClient trying to connect: ", this.config);
if (this.client && this.client.isConnected()) {
console.log("Already Connected, returning");
return;
@@ -140,7 +140,7 @@ export class PahoClient implements IPubSubClient {
console.log("PahoClient - trying to connect");
this.client.connect({
onSuccess: (onSuccessData: any) => {
console.log("PahoClient - connect success!");
console.log("PahoClient - connect success!", this.config);
this.emitter.emit("connectSuccess", onSuccessData);
res(onSuccessData);
},
@@ -162,7 +162,7 @@ export class PahoClient implements IPubSubClient {
}
}
private onMessageArrived = (msg: any) => {
console.log("recd message from paho library: ", msg.uniqueId, msg);
console.log("recd message from paho library: ", msg.uniqueId, msg, msg.payloadString, msg.destinationName);
this.emitter.emit(msg.destinationName, msg.destinationName, msg.payloadString);
}
private onMessageDelivered = (msg: any) => {
@@ -175,7 +175,7 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory {
private options: ICruxNetClientFactoryOptions;
private defaultSubscribeOptions: { qos: number };
private defaultClientMqttOptions: { clean: boolean };
private bufferPahoClient?: PahoClient;
private bufferPahoClient: any = {};
constructor(options: ICruxNetClientFactoryOptions) {
this.options = options;
this.defaultSubscribeOptions = {
@@ -186,9 +186,9 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory {
};
}
public getClient = (from: CruxId, keyManager: IKeyManager, to?: CruxId): IPubSubClient => {
if (this.bufferPahoClient) { return this.bufferPahoClient; }
if (this.bufferPahoClient[from.toString()]) { return this.bufferPahoClient[from.toString()]; }
const overrideOpts = this.getDomainLevelClientOptions(to ? to : from);
this.bufferPahoClient = new PahoClient({
this.bufferPahoClient[from.toString()] = new PahoClient({
clientOptions: {
clientId: from.toString(),
host: overrideOpts ? overrideOpts.host : this.options.defaultLinkServer.host,
@@ -198,7 +198,7 @@ export class CruxNetPubSubClientFactory implements IPubSubClientFactory {
},
subscribeOptions: this.defaultSubscribeOptions,
});
return this.bufferPahoClient;
return this.bufferPahoClient[from.toString()];
}
private getDomainLevelClientOptions = (cruxId: CruxId): {host: string, port: number, path: string} | undefined => {
// TODO Implement
12 changes: 7 additions & 5 deletions src/test/crux-messenger/test-key-management-protocol.ts
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@ import * as chai from "chai";
import sinon from "sinon";
import chaiAsPromised from "chai-as-promised";
import 'mocha';
import {SecureCruxIdMessenger, CertificateManager, CruxConnectProtocolMessenger} from "../../core/domain-services";
import {SecureCruxNetwork, CertificateManager, CruxProtocolMessenger} from "../../core/domain-services";
import {ICruxUserRepository, IProtocolMessage, IPubSubClientFactory} from "../../core/interfaces";
import {BasicKeyManager, cruxPaymentProtocol, keyManagementProtocol} from "../../infrastructure/implementations";
import {CruxId} from "../../packages";
@@ -31,16 +31,18 @@ describe('Test Key Management Protocol', function() {
userStore.store(user2Data.cruxUser);
const inmemUserRepo = new InMemoryCruxUserRepository(userStore);
const pubsubClientFactory = new InMemoryPubSubClientFactory();
const user1Messenger = new SecureCruxIdMessenger(inmemUserRepo, pubsubClientFactory, {
const user1Messenger = new SecureCruxNetwork(inmemUserRepo, pubsubClientFactory, {
cruxId: this.user1Data.cruxUser.cruxID,
keyManager: new BasicKeyManager(this.user1Data.pvtKey)
});
const user2Messenger = new SecureCruxIdMessenger(inmemUserRepo, pubsubClientFactory, {
const user2Messenger = new SecureCruxNetwork(inmemUserRepo, pubsubClientFactory, {
cruxId: this.user2Data.cruxUser.cruxID,
keyManager: new BasicKeyManager(this.user2Data.pvtKey)
});
this.user1KeyManagerProtocolMessenger = new CruxConnectProtocolMessenger(user1Messenger, keyManagementProtocol);
this.user2KeyManagerProtocolMessenger = new CruxConnectProtocolMessenger(user2Messenger, keyManagementProtocol);
await user1Messenger.initialize();
await user2Messenger.initialize();
this.user1KeyManagerProtocolMessenger = new CruxProtocolMessenger(user1Messenger, keyManagementProtocol);
this.user2KeyManagerProtocolMessenger = new CruxProtocolMessenger(user2Messenger, keyManagementProtocol);

});

Loading