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

auth layers added for multiswap endpoints and job router #14

Merged
merged 1 commit into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
35 changes: 25 additions & 10 deletions src/constants/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const VERSION = "000.004";
export const CUDOS_CHAIN_ID = "cudos-1";
let SECURITY_KEY = "";
export const THRESHOLD = 10;
export const BEARER = "Bearer ";

export const getSecurityKey = function () {
return SECURITY_KEY;
Expand All @@ -16,8 +17,13 @@ export const setSecurityKey = function (securityKey: string) {
SECURITY_KEY = securityKey;
};

export const createAuthToken = async function () {
let timelapse = 5;
export const getPrivateKey = function () {
const privateKey = process.env.PRIVATE_KEY as string;
return decrypt(privateKey, SECURITY_KEY);
};

export const createAuthTokenForMultiswapBackend = function () {
let timelapse = 1;
let currentTime = new Date();
let startDateTime = moment(currentTime)
.subtract("minutes", timelapse)
Expand All @@ -28,31 +34,40 @@ export const createAuthToken = async function () {
.utc()
.format();
let randomKey = crypto.randomBytes(512).toString("hex");
let apiKey = (global as any).environment.apiKeyForGateway;
let tokenBody: any = {};
tokenBody.startDateTime = startDateTime;
tokenBody.endDateTime = endDateTime;
tokenBody.randomKey = randomKey;
tokenBody.apiKey = apiKey;

let strTokenBody = JSON.stringify(tokenBody);
let encryptedSessionToken = encryptApiKey(strTokenBody);
let encryptedSessionToken = encrypt(
strTokenBody,
(global as any).AWS_ENVIRONMENT.API_KEY
);
return encryptedSessionToken;
};

export const encryptApiKey = function (data: any) {
export const encrypt = function (data: string, key: String) {
try {
var ciphertext = CryptoJS.AES.encrypt(
data,
(global as any).AWS_ENVIRONMENT.SECRET_KEY
).toString();
var ciphertext = CryptoJS.AES.encrypt(data, key).toString();
return ciphertext;
} catch (e) {
console.log(e);
return "";
}
};

export const decrypt = function (data: string, key: string) {
try {
var bytes = CryptoJS.AES.decrypt(data, key);
var originalText = bytes.toString(CryptoJS.enc.Utf8);
return originalText;
} catch (e) {
console.log("decrypt error", e);
return "";
}
};

export const NETWORKS = [
{
chainId: "56",
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ dotenv.config();

(async () => {
await awsSecretsManager();
transactionsJob();
// transactionsJob();
})().catch((e) => {
console.log(e);
});
Expand Down
74 changes: 71 additions & 3 deletions src/middlewares/auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Request, Response, NextFunction } from "express";
var jwt = require("jsonwebtoken");
import moment from "moment";
let authorizationError = "Authorization header missing";
let invalidToken = "Invalid token";
import { decrypt } from "../constants/constants";

const auth =
(...requiredRights: string[]) =>
Expand All @@ -11,13 +12,80 @@ const auth =
} else {
try {
const token = req.headers.authorization.split(" ")[1];
if (token && token == (global as any).AWS_ENVIRONMENT.API_KEY) {
if (validateAuth(token, req)) {
next();
} else {
return res.http401(invalidToken);
}
} catch (error) {
(global as any).log.error(error);
return res.http401(invalidToken);
}
return res.http401(invalidToken);
}
};

function validateAuth(token: string, req: any): boolean {
if (req.originalUrl.includes("securityKey")) {
return authSecurityKeyApis(token);
} else {
return authJobApis(token);
}
}

function authSecurityKeyApis(token: string): boolean {
if (
token &&
decrypt(token, (global as any).AWS_ENVIRONMENT.API_KEY) ==
(global as any).AWS_ENVIRONMENT.API_KEY
) {
return true;
}
return false;
}

function authJobApis(token: string): boolean {
if (
token &&
isAuthJobTokenValid(token, (global as any).AWS_ENVIRONMENT.API_KEY)
) {
return true;
}
return false;
}

function isAuthJobTokenValid(token: any, key: string): boolean {
let isValid = false;
try {
let decryptedToken = decrypt(token, key);
if (decryptedToken) {
let tokenIntoJsonObject = JSON.parse(decryptedToken);
if (tokenIntoJsonObject) {
let isDateValid = validateDates(tokenIntoJsonObject);
if (isDateValid) {
isValid = true;
}
}
}
} catch (e: any) {
console.log(e);
isValid = false;
}

return isValid;
}

function validateDates(data: any): boolean {
try {
if (data.startDateTime && data.endDateTime) {
let currentDate = moment().utc();
let startDate = moment(data.startDateTime).utc();
let endDate = moment(data.endDateTime).utc();
return currentDate.isBetween(startDate, endDate);
}
} catch (e: any) {
console.log(e);
}

return false;
}
export default auth;
3 changes: 2 additions & 1 deletion src/routes/job.route.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Router } from "express";
import { jobController } from "../controllers";
import auth from "../middlewares/auth.middleware";

const router = Router();

router.route("/").post(jobController.createJob);
router.route("/").post(auth(), jobController.createJob);
router.route("/health").get(jobController.getHealth);
export default router;
15 changes: 12 additions & 3 deletions src/services/axios.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
var axios = require("axios").default;
import {
createAuthTokenForMultiswapBackend,
BEARER,
} from "../constants/constants";

export let getTransactions = async function () {
try {
Expand All @@ -7,8 +11,13 @@ export let getTransactions = async function () {
if (process.env.ENVIRONMENT == "local") {
baseUrl = "http://localhost:8080";
}
let url = `${baseUrl}/api/v1/transactions/list?status=generatorSignatureCreated&address=${process.env.PUBLIC_KEY}&isPagination=false&limit=1`;
let res = await axios.get(url);
let config = {
headers: {
Authorization: BEARER + createAuthTokenForMultiswapBackend(),
},
};
let url = `${baseUrl}/api/v1/transactions/list?status=generatorSignatureCreated&address=${process.env.PUBLIC_KEY}&isPagination=false&isFrom=validator`;
let res = await axios.get(url, config);
return res.data.body.transactions;
} catch (error) {
console.log(error);
Expand All @@ -24,7 +33,7 @@ export const updateTransactionJobStatus = async (txHash: string, body: any) => {
}
let config = {
headers: {
Authorization: "",
Authorization: BEARER + createAuthTokenForMultiswapBackend(),
},
};
return axios.put(
Expand Down
8 changes: 6 additions & 2 deletions src/services/cosmWasm.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import Web3 from "web3";
import { TransactionReceipt, Transaction } from "../interfaces";
const { SigningCosmWasmClient } = require("@cosmjs/cosmwasm-stargate");
import { Wallet, ethers } from "ethers";
import { CUDOS_CHAIN_ID, THRESHOLD } from "../constants/constants";
import {
CUDOS_CHAIN_ID,
THRESHOLD,
getPrivateKey,
} from "../constants/constants";
import { recoverPersonalSignature } from "eth-sig-util";

export const getTransactionReceipt = async (
Expand Down Expand Up @@ -89,7 +93,7 @@ const createSignedPayment = async (
salt
);

const privateKey = process.env.PRIVATE_KEY as string;
const privateKey = getPrivateKey();
let provider = ethers.getDefaultProvider(job.data.sourceRpcURL);
const wallet = new Wallet(privateKey, provider);
let signature = await wallet.signMessage(payBySig.hash);
Expand Down
3 changes: 2 additions & 1 deletion src/services/web3.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
NETWORKS,
CUDOS_CHAIN_ID,
THRESHOLD,
getPrivateKey,
} from "../constants/constants";
import {
ecsign,
Expand Down Expand Up @@ -129,7 +130,7 @@ const createSignedPayment = (
salt
);

const privateKey = process.env.PRIVATE_KEY as string;
const privateKey = getPrivateKey();
const ecSign = ecsign(
Buffer.from(payBySig.hash.replace("0x", ""), "hex"),
Buffer.from(privateKey.replace("0x", ""), "hex")
Expand Down