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

Make api endpoints type safe at runtime #814

Open
pmarsh-scottlogic opened this issue Feb 5, 2024 · 0 comments
Open

Make api endpoints type safe at runtime #814

pmarsh-scottlogic opened this issue Feb 5, 2024 · 0 comments
Labels
backend Requires work on the backend

Comments

@pmarsh-scottlogic
Copy link
Contributor

pmarsh-scottlogic commented Feb 5, 2024

Since Typescript only operates at compile time, and our endpoints receive arbitrary JSON at runtime, a client could pass in JSON with all the wrong types and our code will happily consume it. Take handleAddToChatHistory as an example.

function handleAddToChatHistory(req: OpenAiAddHistoryRequest, res: Response) {
	const infoMessage = req.body.message;
	const chatMessageType = req.body.chatMessageType;
	const level = req.body.level;
	if (
		infoMessage &&
		chatMessageType &&
		level !== undefined &&
		level >= LEVEL_NAMES.LEVEL_1
	) {
		req.session.levelState[level].chatHistory = pushMessageToHistory(
			req.session.levelState[level].chatHistory,
			{
				chatMessageType,
				infoMessage,
			} as ChatMessage
		);
		res.send();
	} else {
		res.status(400);
		res.send();
	}
}

where

type OpenAiAddHistoryRequest = Request<
	never,
	never,
	{
		chatMessageType?: CHAT_MESSAGE_TYPE;
		message?: string;
		level?: LEVEL_NAMES;
	},
	never,
	never
>;

At the moment we check that stuff exists, but we don't check the type. Here's a nonsense request body that would be happily consumed at runtime (resulting in a 500 error):

{
    "level": 1000,
    "message": true,
    "chatMessageType": "hello!"
}
@pmarsh-scottlogic pmarsh-scottlogic added the backend Requires work on the backend label Mar 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend Requires work on the backend
Projects
None yet
Development

No branches or pull requests

1 participant