Merge pull request #338 from CosmWasm/check-body

Improve body checks in faucet
This commit is contained in:
mergify[bot] 2020-08-04 09:46:55 +00:00 committed by GitHub
commit 3edc1b3ce8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 32 additions and 4 deletions

View File

@ -7,6 +7,18 @@ describe("RequestParser", () => {
});
it("throws for invalid credit requests", () => {
// body not a dictionary
{
expect(() => RequestParser.parseCreditBody("foo")).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(null)).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(42)).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody([])).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(true)).toThrowError(/Request body must be a dictionary./i);
expect(() => RequestParser.parseCreditBody(undefined)).toThrowError(
/Request body must be a dictionary./i,
);
}
// address unset
{
const body = { ticker: "TKN" };

View File

@ -1,3 +1,5 @@
import { isNonNullObject } from "@cosmjs/utils";
import { HttpError } from "./httperror";
export interface CreditRequestBodyData {
@ -8,8 +10,12 @@ export interface CreditRequestBodyData {
}
export class RequestParser {
public static parseCreditBody(body: any): CreditRequestBodyData {
const { address, ticker } = body;
public static parseCreditBody(body: unknown): CreditRequestBodyData {
if (!isNonNullObject(body) || Array.isArray(body)) {
throw new HttpError(400, "Request body must be a dictionary.");
}
const { address, ticker } = body as any;
if (typeof address !== "string") {
throw new HttpError(400, "Property 'address' must be a string.");

View File

@ -1,5 +1,10 @@
/**
* Checks if data is a non-null object (i.e. matches the TypeScript object type)
* Checks if data is a non-null object (i.e. matches the TypeScript object type).
*
* Note: this returns true for arrays, which are objects in JavaScript
* even though array and object are different types in JSON.
*
* @see https://www.typescriptlang.org/docs/handbook/basic-types.html#object
*/
export function isNonNullObject(data: unknown): data is object {
return typeof data === "object" && data !== null;

View File

@ -1,5 +1,10 @@
/**
* Checks if data is a non-null object (i.e. matches the TypeScript object type)
* Checks if data is a non-null object (i.e. matches the TypeScript object type).
*
* Note: this returns true for arrays, which are objects in JavaScript
* even though array and object are different types in JSON.
*
* @see https://www.typescriptlang.org/docs/handbook/basic-types.html#object
*/
export declare function isNonNullObject(data: unknown): data is object;
/**