Compare commits

..
25 Commits
Author SHA1 Message Date
Chris Troutner 86a58e9ff3 Merge pull request #59 from Permissionless-Software-Foundation/ct-unstable
fix(auth): Fixing typo that was breaking basic authentication
2020-11-11 19:58:11 -08:00
Chris Troutner d7d722b27b Merge branch 'master' into ct-unstable 2020-11-11 19:55:58 -08:00
Chris Troutner d439165dd2 fix(auth): Fixing typo that was breaking basic authentication 2020-11-11 19:55:15 -08:00
Chris Troutner 65356051f8 Merge pull request #58 from Permissionless-Software-Foundation/ct-unstable
fix(rate limits): Adding local server back to whitelist
2020-11-11 19:16:07 -08:00
Chris Troutner 9728b64edb fix(rate limits): Adding local server back to whitelist 2020-11-11 18:59:48 -08:00
Chris Troutner 7e71d355ba Merge pull request #57 from Permissionless-Software-Foundation/ct-unstable
Basic Authentication
2020-11-11 17:53:38 -08:00
Chris Troutner fe9f40e847 linting 2020-11-11 17:52:19 -08:00
Chris Troutner 28f0a1de56 feat(Basic Authentication): Adding back in for controlling access 2020-11-11 14:56:24 -08:00
Chris Troutner b8589a54aa Trying to reinstate basic auth 2020-11-11 07:48:40 -08:00
Chris Troutner 0d05803462 Update README 2020-11-08 19:19:21 -08:00
Chris Troutner 69d125ad24 fixing README 2020-11-08 17:30:55 -08:00
Chris Troutner 7631a25f4b Merge pull request #56 from Permissionless-Software-Foundation/ct-unstable
Removing Blockbook documentation
2020-11-08 17:26:39 -08:00
Chris Troutner f41f9d33c8 feat(blockbook): Removing Blockbook documentation 2020-11-08 17:25:05 -08:00
Chris Troutner 3475255444 Updating diagram 2020-11-08 17:22:57 -08:00
Chris Troutner bcc5c95bd6 Updating README 2020-11-08 17:20:58 -08:00
Chris Troutner 15fe66bdf3 Merge branch 'master' into ct-unstable 2020-11-08 17:19:43 -08:00
Chris Troutner 8ce0209e9a Updating README 2020-11-08 17:19:30 -08:00
Chris Troutner c7c19d1c2b Merge pull request #55 from Permissionless-Software-Foundation/ct-unstable
Updating README
2020-11-08 17:17:15 -08:00
Chris Troutner f36146ef24 Updating README 2020-11-08 17:15:53 -08:00
Chris Troutner edae956742 Updating README 2020-11-08 17:13:03 -08:00
Chris Troutner 3f2890661c Updating README 2020-11-08 17:04:17 -08:00
Chris Troutner 46c9e00fe1 Merge pull request #54 from Permissionless-Software-Foundation/ct-unstable
Updating deployment for bchn
2020-11-08 13:42:48 -08:00
Chris Troutner a1c19e8e0a Merge branch 'master' into ct-unstable 2020-11-08 13:40:08 -08:00
Chris Troutner fea8546bd2 fix(deployment): Updating deployment script 2020-11-08 13:39:10 -08:00
Chris Troutner c6d98380b1 Updating gitignore 2020-11-08 12:54:28 -08:00
11 changed files with 209 additions and 250 deletions
+2
View File
@@ -25,6 +25,8 @@ start-sweet-main.sh
test-sweet-main.sh
test-fullstack-abc.sh
test-fullstack-bchn.sh
start-fullstack-abc.sh
start-fullstack-bchn.sh
coverage
start-my-infra
+20 -25
View File
@@ -1,19 +1,12 @@
# bch-api
This is a node.js JavaScript REST API server using Express.js. The purpose of this code is to create a REST API server that provides a common interface for working with a Bitcoin Cash full node and various indexers. See [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) to learn about the 'Cash Stack'. Visit [FullStack.cash](https://fullstack.cash), sign up for a free account, and use this REST API right away with the [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js) JavaScript library.
[![Build Status](https://travis-ci.org/christroutner/bch-api.svg?branch=master)](https://travis-ci.org/christroutner/bch-api)
This repository is intended to be paired with [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js), an npm JavaScript library for building Bitcoin Cash apps.
This is a fork and alternative implementation of
the [rest.bitcoin.com](https://github.com/Bitcoin-com/rest.bitcoin.com) repository.
The purpose of this code is to create a REST API server that provides a common
interface for working with a Bitcoin Cash full node and various indexers. See [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) to learn about the 'Cash Stack'. Visit [FullStack.cash](https://fullstack.cash), sign up for a free account, and use this REST API right away with the [bch-js](https://github.com/christroutner/bch-js) JavaScript library.
![Cash Stack Network Diagram](./generic-network-diagram.png)
This repository is intended to be paired with [bch-js](https://github.com/christroutner/bch-js),
an npm JavaScript library, and an alternative implementation
of [BITBOX SDK](https://github.com/Bitcoin-com/bitbox-sdk).
Both bch-api and bch-js are part of the
[full stack of BCH software](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
Both bch-api and bch-js are part of the 'Cash Stack' [full stack of BCH software](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
- [API Documentation](https://fullstack.cash/documentation)
- [Example Code](https://fullstack.cash/examples)
@@ -24,32 +17,29 @@ Have questions? Need help? Join our community support:
## Features
The following features set this repository apart from rest.bitcoin.com:
- Address balance and UTXO queries use the [Blockbook](https://github.com/trezor/blockbook)
indexer instead of Insight.
- Fine grain access is controlled with a JWT token using
[this back end auth server](https://github.com/Permissionless-Software-Foundation/jwt-bch-api) and [this front end](https://github.com/Permissionless-Software-Foundation/jwt-bch-frontend).
- Default rate limits are set to 3 RPM for anonymous connections, 10 RPM for [free accounts](https://fullstack.cash/pricing), up to 100 RPM if a full-access JWT token is used.
[this back end auth server](https://github.com/Permissionless-Software-Foundation/jwt-bch-api) and [this front end](https://github.com/Permissionless-Software-Foundation/jwt-bch-frontend). Can be used to monetize access to the REST API.
- Typescript removed and ES8 JavaScript used instead.
- npm audit run on all dependencies.
- [Greenkeeper](https://greenkeeper.io/) implemented for automatic dependency management
and security updates.
## Live Demo
You can test a live demo of the REST API by running the
[bch-js examples](https://github.com/Permissionless-Software-Foundation/bch-js-examples).
Rate limits are 3 requests per minute, but you can increase them to 10 with a [free account](https://fullstack.cash/pricing).
This is fast enough to try out the examples
but these servers are not intended as a freemium service. You can run your own
REST server by purchasing the hard drive at [bchjs.cash](https://bchjs.cash).
Rate limits are 20 requests per minute, but you can increase them to 100 with a [paid account](https://fullstack.cash/pricing).
You can bootstrap your own REST API server by downloading and installing the infrastructure listed on the [CashStrap](https://fullstack.cash/cashstrap) page.
- Mainnet REST API server: https://api.fullstack.cash/v3/
- Testnet REST API server: https://tapi.fullstack.cash/v3/
### Configure bch-js
The live servers can be used by [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js) by settings the `restURL` config property to one of these servers:
- BCHN Mainnet REST API server: https://bchn.fullstack.cash/v3/
- ABC Mainnet REST API server: https://abc.fullstack.cash/v3/
- Testnet3 REST API server: https://testnet3.fullstack.cash/v3/
- Check server status: https://metrics.fullstack.cash
## Installation
There are two installation paths, depending if you want a *development* or
*production* environment. You'll also need to set up the underlying infrastructure
described [this page](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
described on [this page](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
This code targets the Ubuntu 18.04 LTS Linux OS.
@@ -58,7 +48,7 @@ This is a standard node.js project. The installation is as follows:
- Clone this repository:
`git clone https://github.com/christroutner/bch-api && cd bch-api`
`git clone https://github.com/Permissionless-Software-Foundation/bch-api && cd bch-api`
- Install dependencies:
@@ -93,5 +83,10 @@ installation.
Have questions? Need help? Join our community support
[Telegram channel](https://t.me/bch_js_toolkit)
## IPFS
Copies of this repository will occasionally be uploaded and hosted on [IPFS](https://ipfs.io):
- v1.15.4: QmSAerFmDJm6KQp2HC8jsRR5MdL5X39hoUsJYvWNDvrD8m
## License
[MIT](./LICENSE.md)
+3 -2
View File
@@ -16,8 +16,9 @@ if [[ $GIT_BRANCH =~ "master" ]]
curl -X POST http://fullstack.cash:9000/hooks/bch-api-mainnet -H "Content-Type: application/json" -d $DATA
curl -X POST http://fullstack.cash:9000/hooks/bch-api-testnet -H "Content-Type: application/json" -d $DATA
curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-testnet -H "Content-Type: application/json" -d $DATA
curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-mainnet -H "Content-Type: application/json" -d $DATA
#curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-testnet -H "Content-Type: application/json" -d $DATA
#curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-mainnet -H "Content-Type: application/json" -d $DATA
curl -X POST http://$BCHN_BCHAPI:9000/hooks/bch-api-bchn -H "Content-Type: application/json" -d $DATA
echo "...Finished deploying to production."
+6
View File
@@ -24,4 +24,10 @@ export REDIS_HOST=172.17.0.1
# JWT Token Secret
export TOKENSECRET=somelongsecretvalue
# So that bch-api can call bch-js locally.
export LOCAL_RESTURL=http://127.0.0.1:3000/v3/
# slp-api alternative SLP validator.
export SLP_API_URL=http://10.0.0.5:5001/
npm start
+6
View File
@@ -21,4 +21,10 @@ export REDIS_HOST=172.17.0.1
# JWT Token Secret
export TOKENSECRET=somelongsecretvalue
# So that bch-api can call bch-js locally.
export LOCAL_RESTURL=http://127.0.0.1:3000/v3/
# slp-api alternative SLP validator.
export SLP_API_URL=http://10.0.0.5:5001/
npm start
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+55 -49
View File
@@ -22,9 +22,9 @@
'use strict'
const passport = require('passport')
// const BasicStrategy = require('passport-http').BasicStrategy
const BasicStrategy = require('passport-http').BasicStrategy
const AnonymousStrategy = require('passport-anonymous')
// const wlogger = require('../util/winston-logging')
const wlogger = require('../util/winston-logging')
// Used for debugging and iterrogating JS objects.
const util = require('util')
@@ -33,9 +33,11 @@ util.inspect.defaultOptions = { depth: 1 }
// let _this
// Set default rate limit value for testing
// const PRO_PASSES = process.env.PRO_PASS ? process.env.PRO_PASS : 'BITBOX'
const PRO_PASSES = process.env.PRO_PASS
? process.env.PRO_PASS
: 'testpassword'
// Convert the pro-tier password string into an array split by ':'.
// const PRO_PASS = PRO_PASSES.split(':')
const PRO_PASS = PRO_PASSES.split(':')
// wlogger.verbose(`PRO_PASS set to: ${PRO_PASS}`)
@@ -47,56 +49,60 @@ class AuthMW {
// Initialize passport for 'anonymous' authentication.
passport.use(new AnonymousStrategy())
console.log(`PRO_PASS: ${JSON.stringify(PRO_PASS, null, 2)}`)
// Initialize passport for 'basic' authentication.
// passport.use(
// new BasicStrategy({ passReqToCallback: true }, function (
// req,
// username,
// password,
// done
// ) {
// // console.log(`req: ${util.inspect(req)}`)
// // console.log(`username: ${username}`)
// // console.log(`password: ${password}`)
//
// // Create the req.locals property if it does not yet exist.
// if (!req.locals) {
// req.locals = {
// // default values
// proLimit: false,
// apiLevel: 0
// }
// }
//
// // Set pro-tier rate limit to flag to false by default.
// req.locals.proLimit = false
//
// // Evaluate the username and password and set the rate limit accordingly.
// // if (username === "BITBOX" && password === PRO_PASS) {
// if (username === 'BITBOX') {
// for (let i = 0; i < PRO_PASS.length; i++) {
// const thisPass = PRO_PASS[i]
//
// if (password === thisPass) {
// wlogger.verbose(`${req.url} called by ${password.slice(0, 6)}`)
//
// // Success
// req.locals.proLimit = true
// break
// }
// }
// }
//
// // console.log(`req.locals: ${util.inspect(req.locals)}`)
//
// return done(null, true)
// })
// )
passport.use(
new BasicStrategy({ passReqToCallback: true }, function (
req,
username,
password,
done
) {
// console.log(`req: ${util.inspect(req)}`)
// console.log(`username: ${username}`)
// console.log(`password: ${password}`)
// Create the req.locals property if it does not yet exist.
if (!req.locals) {
req.locals = {
// default values
proLimit: false,
apiLevel: 0
}
}
// Set pro-tier rate limit to flag to false by default.
req.locals.proLimit = false
// Evaluate the username and password and set the rate limit accordingly.
// if (username === "BITBOX" && password === PRO_PASS) {
if (username === 'fullstackcash') {
for (let i = 0; i < PRO_PASS.length; i++) {
const thisPass = PRO_PASS[i]
if (password === thisPass) {
wlogger.verbose(`${req.url} called by ${password.slice(0, 6)}`)
// Success
req.locals.proLimit = true
console.log(`User ${req.ip} authenticated using Basic Auth`)
break
}
}
}
// console.log(`req.locals: ${util.inspect(req.locals)}`)
return done(null, true)
})
)
}
// Middleware called by the route.
mw () {
return passport.authenticate(['anonymous'], {
console.log('Initializing passport')
return passport.authenticate(['basic', 'anonymous'], {
session: false
})
}
+70 -64
View File
@@ -113,74 +113,80 @@ class RateLimits {
// Default value is 50 points per request = 20 RPM
let rateLimit = 50
// Code here for the rate limiter is adapted from this example:
// https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users
try {
// The resource being consumed: full node, indexer, SLPDB, etc.
const resource = _this.getResource(req.url)
wlogger.debug(`resource: ${resource}`)
// Only evaluate the JWT token if the user is not using Basic Authentication.
if (!req.locals.proLimit) {
// Code here for the rate limiter is adapted from this example:
// https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users
try {
// The resource being consumed: full node, indexer, SLPDB, etc.
const resource = _this.getResource(req.url)
wlogger.debug(`resource: ${resource}`)
let key = userId || req.ip
res.locals.key = key // Feedback for tests.
let key = userId || req.ip
res.locals.key = key // Feedback for tests.
// const pointsToConsume = userId ? 1 : 30
decoded.resource = resource
let pointsToConsume = _this.calcPoints(decoded)
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
// Retrieve the origin.
let origin = req.get('origin')
// Handle calls coming from the intranet.
if (origin === undefined && key.indexOf('10.0.0.5') > -1) {
origin = 'slp-api'
}
wlogger.info(`origin: ${origin}`)
// If the request originates from one of the approved wallet apps, then
// apply paid-access rate limits.
if (
origin &&
(origin.toString().indexOf('wallet.fullstack.cash') > -1 ||
origin.toString().indexOf('sandbox.fullstack.cash') > -1 ||
origin === 'slp-api')
) {
pointsToConsume = 10
// const pointsToConsume = userId ? 1 : 30
decoded.resource = resource
let pointsToConsume = _this.calcPoints(decoded)
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
// Retrieve the origin.
let origin = req.get('origin')
// Handle calls coming from the intranet.
if (origin === undefined && key.indexOf('10.0.0.5') > -1) {
origin = 'slp-api'
}
wlogger.info(`origin: ${origin}`)
// If the request originates from one of the approved wallet apps, then
// apply paid-access rate limits.
if (
origin &&
(origin.toString().indexOf('wallet.fullstack.cash') > -1 ||
origin.toString().indexOf('sandbox.fullstack.cash') > -1 ||
origin === 'slp-api')
) {
pointsToConsume = 10
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
}
// For internal calls, increase rate limits to as fast as possible.
if (
// Comment out the line below when running bch-js e2e rate limit tests.
key.toString().indexOf('::ffff:127.0.0.1') > -1 ||
// Do not comment out this line.
key.toString().indexOf('172.17.') > -1
) {
pointsToConsume = 1
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
}
wlogger.info(
`User ${key} consuming ${pointsToConsume} point for resource ${resource}.`
)
rateLimit = Math.floor(1000 / pointsToConsume)
// Update the key so that rate limits track both the user and the resource.
key = `${key}-${resource}`
await _this.rateLimiter.consume(key, pointsToConsume)
} catch (err) {
// console.log('err: ', err)
// Used for returning data for tests.
res.locals.rateLimitTriggered = true
// console.log('res.locals: ', res.locals)
// Rate limited was triggered
res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: `Too many requests. Your limits are currently ${rateLimit} requests per minute. Increase rate limits at https://fullstack.cash`
})
}
// For internal calls, increase rate limits to as fast as possible.
if (
key.toString().indexOf('172.17.') > -1 ||
key.toString().indexOf('::ffff:127.0.0.1') > -1
) {
pointsToConsume = 1
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
}
wlogger.info(
`User ${key} consuming ${pointsToConsume} point for resource ${resource}.`
)
rateLimit = Math.floor(1000 / pointsToConsume)
// Update the key so that rate limits track both the user and the resource.
key = `${key}-${resource}`
await _this.rateLimiter.consume(key, pointsToConsume)
} catch (err) {
// console.log('err: ', err)
// Used for returning data for tests.
res.locals.rateLimitTriggered = true
// console.log('res.locals: ', res.locals)
// Rate limited was triggered
res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: `Too many requests. Your limits are currently ${rateLimit} requests per minute. Increase rate limits at https://fullstack.cash`
})
}
} catch (err) {
wlogger.error('Error in route-ratelimit.js/newRateLimit(): ', err)
-70
View File
@@ -96,18 +96,6 @@ class Blockbook {
}
}
/**
* @api {get} /blockbook/balance/{addr} Get balance for a single address.
* @apiName Balance for a single address
* @apiGroup Blockbook
* @apiDescription Returns an object with balance and details about an address.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/blockbook/balance/bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" -H "accept: application/json"
*
*/
// GET handler for single balance
async balanceSingle (req, res, next) {
try {
const address = req.params.address
@@ -165,18 +153,6 @@ class Blockbook {
}
}
/**
* @api {post} /blockbook/balance Get balance for an array of addresses.
* @apiName Balance for an array of addresses
* @apiGroup Blockbook
* @apiDescription Return balances and details for an array of addresses.
* Limited to 20 items per request.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/blockbook/balance" -H "accept: application/json" -H "Content-Type: application/json" -d '{"addresses":["bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf","bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"]}'
*
*
*/
// POST handler for bulk queries on address details
async balanceBulk (req, res, next) {
try {
@@ -284,17 +260,6 @@ class Blockbook {
}
}
/**
* @api {get} /blockbook/utxos/{addr} Get utxos for a single address.
* @apiName UTXOs for a single address
* @apiGroup Blockbook
* @apiDescription Returns an object with UTXOs associated with an address.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/blockbook/utxos/bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur3" -H "accept: application/json"
*
*/
// GET handler for single balance
async utxosSingle (req, res, next) {
try {
@@ -352,18 +317,6 @@ class Blockbook {
}
}
/**
* @api {post} /blockbook/utxos Get UTXOs for an array of addresses.
* @apiName UTXOs for an array of addresses
* @apiGroup Blockbook
* @apiDescription Return UTXOs associate with an array of addresses.
* Limited to 20 items per request.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/blockbook/utxos" -H "accept: application/json" -H "Content-Type: application/json" -d '{"addresses":["bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur3","bitcoincash:qzy8wnj0dz927eu6kvh8v2pqsr5w8jh33ys757tdtq"]}'
*
*
*/
// POST handler for bulk queries on address utxos
async utxosBulk (req, res, next) {
try {
@@ -461,17 +414,6 @@ class Blockbook {
}
}
/**
* @api {get} /blockbook/tx/{txid} Get details for a single transaction.
* @apiName Details for a single transaction
* @apiGroup Blockbook
* @apiDescription Returns an object with details for a single transaction
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/blockbook/tx/6181c669614fa18039a19b23eb06806bfece1f7514ab457c3bb82a40fe171a6d" -H "accept: application/json"
*
*/
// GET handler for single transaction details.
async txSingle (req, res, next) {
try {
@@ -514,18 +456,6 @@ class Blockbook {
}
}
/**
* @api {post} /blockbook/tx Get details for an array of transactions.
* @apiName Details for an array of transactions
* @apiGroup Blockbook
* @apiDescription Return details for an array of transactions.
* Limited to 20 items per request.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/blockbook/tx" -H "accept: application/json" -H "Content-Type: application/json" -d '{"txids":["6181c669614fa18039a19b23eb06806bfece1f7514ab457c3bb82a40fe171a6d","6181c669614fa18039a19b23eb06806bfece1f7514ab457c3bb82a40fe171a6d"]}'
*
*
*/
// POST handler for bulk queries on tx details
async txBulk (req, res, next) {
try {
+9
View File
@@ -20,4 +20,13 @@ export FULCRUM_PORT=50002
export TOKENSECRET=somelongpassword
# So that bch-api can call bch-js locally.
export LOCAL_RESTURL=http://127.0.0.1:3000/v3/
# slp-api alternative SLP validator.
export SLP_API_URL=http://10.0.0.5:5001/
# Basic Authentication password
export PRO_PASS=somerandomepassword:someotherrandompassword:aThirdPassword
npm start
+38 -40
View File
@@ -1,7 +1,6 @@
/*
This integration tests should be run against a live bch-api REST server. It
tests to ensure the rate-limits are working as expected. Adjust the values
in the tests below to match the rate limit setting in your own installation.
These tests have been deprecated. To test bch-api rate limits, run the e2e
tests in the bch-js repository.
*/
'use strict'
@@ -17,11 +16,11 @@ util.inspect.defaultOptions = { depth: 1 }
// const SERVER = `http://192.168.0.36:12400/v3/`
const SERVER = 'http://localhost:3000/v3/'
// const SERVER = 'https://api.fullstack.cash/v3/'
//
// const TEST_JWT =
// 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMDYyODk1MSwiZXhwIjoxNjAzMjIwOTUxfQ.JPXDJQsxJFtCGZjHOd-hRfJuY41Ef_FQ4ET06CtYdNk'
const TEST_JWT =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMDYyODk1MSwiZXhwIjoxNjAzMjIwOTUxfQ.JPXDJQsxJFtCGZjHOd-hRfJuY41Ef_FQ4ET06CtYdNk'
describe('#rate limits', () => {
describe('#JWT rate limits', () => {
it('should get control/getNetworkInfo() with no auth', async () => {
const options = {
method: 'GET',
@@ -36,25 +35,24 @@ describe('#rate limits', () => {
assert.hasAnyKeys(result.data, ['version'])
})
it('should trigger rate-limit handler if rate limits exceeds 5 request per minute', async () => {
it('should trigger rate-limit handler if rate limits exceeds 20 request per minute', async () => {
try {
// Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
const options = {
method: 'GET',
url: `${SERVER}control/getNetworkInfo`
}
const promises = []
for (let i = 0; i < 5; i++) {
for (let i = 0; i < 30; i++) {
const promise = axios(options)
promises.push(promise)
}
await Promise.all(promises)
assert.equal(true, false, 'Unexpected result!')
assert.fail('Unexpected result!')
} catch (err) {
// console.log(`err.response: ${util.inspect(err.response)}`)
console.log('err: ', err)
assert.equal(err.response.status, 429)
assert.include(err.response.data.error, 'Too many requests')
@@ -135,32 +133,32 @@ describe('#rate limits', () => {
// }
// })
it('should unlock pro-tier for a valid JWT token', async () => {
try {
// Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
const options = {
method: 'GET',
url: `${SERVER}control/`,
headers: {
Authorization: `Token ${TEST_JWT}`
}
}
const promises = []
for (let i = 0; i < 60; i++) {
const promise = axios(options)
promises.push(promise)
}
await Promise.all(promises)
// assert.equal(true, false, "Unexpected result!")
assert.equal(true, true, 'Not throwing an error is a pass!')
} catch (err) {
console.log(`err.response: ${util.inspect(err.response)}`)
assert.equal(true, false, 'Unexpected result!')
}
// Override default timeout for this test.
}).timeout(20000)
// it('should unlock pro-tier for a valid JWT token', async () => {
// try {
// // Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
// const options = {
// method: 'GET',
// url: `${SERVER}control/`,
// headers: {
// Authorization: `Token ${TEST_JWT}`
// }
// }
//
// const promises = []
// for (let i = 0; i < 60; i++) {
// const promise = axios(options)
// promises.push(promise)
// }
//
// await Promise.all(promises)
//
// // assert.equal(true, false, "Unexpected result!")
// assert.equal(true, true, 'Not throwing an error is a pass!')
// } catch (err) {
// console.log(`err.response: ${util.inspect(err.response)}`)
//
// assert.equal(true, false, 'Unexpected result!')
// }
// // Override default timeout for this test.
// }).timeout(20000)
})