Skip to content

feature: implement basic querystring params validation (resolves #3055) #3393

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
45 changes: 32 additions & 13 deletions api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,36 @@ import {
renderError,
} from "../src/common/utils.js";
import { fetchStats } from "../src/fetchers/stats-fetcher.js";
import { isLocaleAvailable } from "../src/translations.js";
import { validateQueryStringParams } from "../src/common/validate.js";

const QUERYSTRING_PARAMS_DATA_TYPE_MAP = new Map([
["username", "string"],
["hide", "enum-array"],
["hide_title", "boolean"],
["hide_border", "boolean"],
["card_width", "number"],
["hide_rank", "boolean"],
["show_icons", "boolean"],
["include_all_commits", "boolean"],
["line_height", "number"],
["title_color", "string"],
["ring_color", "string"],
["icon_color", "string"],
["text_color", "string"],
["text_bold", "boolean"],
["bg_color", "string"],
["theme", "enum"],
["cache_seconds", "number"],
["exclude_repo", "array"],
["custom_title", "string"],
["locale", "enum"],
["disable_animations", "boolean"],
["border_radius", "number"],
["border_color", "string"],
["number_format", "enum"],
["rank_icon", "enum"],
["show", "enum-array"],
]);

export default async (req, res) => {
const {
Expand Down Expand Up @@ -53,19 +82,9 @@ export default async (req, res) => {
);
}

if (locale && !isLocaleAvailable(locale)) {
return res.send(
renderError("Something went wrong", "Language not found", {
title_color,
text_color,
bg_color,
border_color,
theme,
}),
);
}

try {
validateQueryStringParams(req.query, QUERYSTRING_PARAMS_DATA_TYPE_MAP);

const showStats = parseArray(show);
const stats = await fetchStats(
username,
Expand Down
22 changes: 22 additions & 0 deletions src/common/validate.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export type DataTypes =
| "enum"
| "enum-array"
| "array"
| "string"
| "boolean"
| "number";

export function validateQueryStringParam(
expectedDataType: DateTypes,
param: string,
value: string,
): boolean;

export function validateQueryStringParams(
queryStringParams: object,
queryStringParamsDataTypeMap: Map<string, DataTypes>,
): void;

export class InvalidQueryStringParamsError extends Error {
constructor(message: string, secondaryMessage: string);
}
128 changes: 128 additions & 0 deletions src/common/validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// @ts-check

import { availableLocales } from "../translations.js";
import { themes } from "../../themes/index.js";
import { parseArray } from "./utils.js";

/**
* Class for handling invalid query string param errors.
*/
export class InvalidQueryStringParamsError extends Error {
/**
* Constructor for InvalidQueryStringParamsError.
*
* @param {string} message - The error message.
* @param {string} secondaryMessage - The secondary error message.
*/
constructor(message, secondaryMessage) {
super(message);
this.secondaryMessage = secondaryMessage;
}
}

const QUERYSTRING_PARAMS_ENUM_VALUES = {
hide: ["stars", "commits", "prs", "issues", "contribs"],
theme: Object.keys(themes),
locale: availableLocales,
number_format: ["short", "long"],
rank_icon: ["github", "percentile", "default"],
show: [
"reviews",
"discussions_started",
"discussions_answered",
"prs_merged",
"prs_merged_percentage",
],
};

/**
* @typedef {import("./validate").DataTypes} DataTypes The data types.
*/

/**
* Returns the secondary error message for an invalid query string param.
*
* @param {string} param - The invalid query string param.
* @param {Map<string, DataTypes>} queryStringParamsDataTypeMap - The query string params data type map.
* @returns {string} The secondary error message.
*/
const getInvalidQueryStringParamsErrorSecondaryMessage = (
param,
queryStringParamsDataTypeMap,
) => {
const expectedDataType = queryStringParamsDataTypeMap.get(param);
if (expectedDataType === "enum" || expectedDataType === "enum-array") {
return `Expected: ${QUERYSTRING_PARAMS_ENUM_VALUES[param].join(", ")}`;
} else if (expectedDataType === "number") {
return "Expected: a number";
} else if (expectedDataType === "boolean") {
return "Expected: true or false";
} else if (expectedDataType === "array") {
return "Expected: an array";
} else if (expectedDataType === "string") {
return "Expected: a string";
} else {
throw new Error("Unexpected behavior");
}
};

/**
* Validates a query string param.
*
* @param {DataTypes} expectedDataType - The expected data type of the query string param.
* @param {string} param - The query string param.
* @param {string} value - The query string param value.
* @returns {boolean} Whether the query string param is valid.
*/
export const validateQueryStringParam = (expectedDataType, param, value) => {
if (expectedDataType === "enum") {
return QUERYSTRING_PARAMS_ENUM_VALUES[param].includes(value);
} else if (expectedDataType === "enum-array") {
return parseArray(value).every((value) =>
QUERYSTRING_PARAMS_ENUM_VALUES[param].includes(value),
);
} else if (expectedDataType === "number") {
return !isNaN(parseFloat(value));
} else if (expectedDataType === "boolean") {
return value === "true" || value === "false";
} else if (expectedDataType === "array") {
return Array.isArray(parseArray(value));
} else if (expectedDataType === "string") {
return typeof value === "string";
} else {
return false;
}
};

/**
* Validates the query string params.
* Throws an error if a query string param is invalid.
* Does not return anything.
*
* @param {object} queryStringParams - The query string params.
* @param {Map<string, DataTypes>} queryStringParamsDataTypeMap - The query string params data type map.
* @returns {void}
*/
export const validateQueryStringParams = (
queryStringParams,
queryStringParamsDataTypeMap,
) => {
for (const [param, value] of Object.entries(queryStringParams)) {
const expectedDataType = queryStringParamsDataTypeMap.get(param);
if (!expectedDataType) {
// Absence of data type means that the query string param is not supported.
// Currently we allow addition of extra query string params.
continue;
}
if (validateQueryStringParam(expectedDataType, param, value)) {
continue;
}
throw new InvalidQueryStringParamsError(
`Invalid query string param \`${param}\` value: ${value}`,
getInvalidQueryStringParamsErrorSecondaryMessage(
param,
queryStringParamsDataTypeMap,
),
);
}
};
16 changes: 10 additions & 6 deletions tests/api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { calculateRank } from "../src/calculateRank.js";
import { renderStatsCard } from "../src/cards/stats-card.js";
import { CONSTANTS, renderError } from "../src/common/utils.js";
import { expect, it, describe, afterEach } from "@jest/globals";
import { availableLocales } from "../src/translations.js";

const stats = {
name: "Anurag Hazra",
Expand Down Expand Up @@ -140,8 +141,8 @@ describe("Test /api/", () => {
{
username: "anuraghazra",
hide: "issues,prs,contribs",
show_icons: true,
hide_border: true,
show_icons: "true",
hide_border: "true",
line_height: 100,
title_color: "fff",
icon_color: "fff",
Expand Down Expand Up @@ -270,8 +271,8 @@ describe("Test /api/", () => {
{
username: "anuraghazra",
hide: "issues,prs,contribs",
show_icons: true,
hide_border: true,
show_icons: "true",
hide_border: "true",
line_height: 100,
title_color: "fff",
ring_color: "0000ff",
Expand Down Expand Up @@ -318,7 +319,10 @@ describe("Test /api/", () => {

expect(res.setHeader).toBeCalledWith("Content-Type", "image/svg+xml");
expect(res.send).toBeCalledWith(
renderError("Something went wrong", "Language not found"),
renderError(
"Invalid query string param `locale` value: asdf",
`Expected: ${availableLocales.join(", ")}`,
),
);
});

Expand All @@ -328,7 +332,7 @@ describe("Test /api/", () => {
.reply(200, { error: "Some test error message" });

const { req, res } = faker(
{ username: "anuraghazra", include_all_commits: true },
{ username: "anuraghazra", include_all_commits: "true" },
data_stats,
);

Expand Down
Loading