Safe expression evaluation in Ruby for user submitted formulas

Ruby has a robust library of functions to evaluate mathematical expressions. However, this library is not as good as it could be when it comes to dealing with user-submitted mathematical formulas. This is how Keisan helps.

Arnaud Lachaume
Arnaud Lachaume LinkedIn
• 4 min read
Safe expression evaluation in Ruby for user submitted formulas

TL;DR; checkout Keisan for evaluation of user-submitted expressions and formulas. The gem has plenty of built-in functions and can be easily extended.

Our reporting API powers all the data driven results on Keypup, such as the Priority Inbox, Team Board and Data Explorer. Recently we decided to try out a small MVP allowing us to pass dynamic expressions as part our report API calls to perform post-processing (~ data mapping/formatting).

Our objective with that MVP was to allow report queries to become self-contained (e.g. chart queries) and reduce the amount of data massage we have to do in frontend.

The main problem with any kind of user input evaluation is security of course. You do not want to use Ruby eval or give expression evaluators access to the context of your app (i.e. give access to Rails.application.credentials for instance).

So we needed a purely interpreted expression processor with no direct connection to Ruby when evaluating expressions. A few Google searches later we ended up finding...

Keisan, expression parser and evaluator

This gem provides an expression evaluator which is close enough to Ruby but without running expressions in the Ruby context.

Instead expressions provided to Keisan are parsed as an Abstract Syntax Tree (AST) then each node in the tree gets evaluated. Each evaluation is done on primitive values without access to the Ruby context. Invoking a function which is not defined in the evaluator (e.g. Rails.application.credentials) will raise an error.

Because expressions are interpreted from scratch using a string parser and a whitelist of functions, this is considerably safer than any form of eval.

Thanks to Keisan we can safely allow our reporting API to accept dynamic processors:

Image

Getting started with Keisan

First install the gem

Then open an irb console and start playing with the evaluator. Keisan provides a whole lot of base functions to play with, so don't be shy.

Convenient isn't it? Now let's move onto Keisan's most powerful feature.

Defining your own functions

Keisan allows you to extend its functionalities with custom functions.

Custom functions can be defined within the evaluator or in Ruby directly.

Because Keisan can be extended with custom functions, you can create very powerful and flexible calculators.

Let's say you wish to give your app administrators a web UI allowing them to derive stats from your data. You could go as far as providing Keisan functions retrieving data from your database and let them play with them. Let's see what this would look like in Rails.

Creating your own calculator

Alright, you know almost everything there is to know about Keisan. So what about creating your own calculator?

Below is an example of custom calculator with predefined functions.

You may note two things about the calculator above which are related to security. I said earlier Keisan was safe...it is, mostly...except for Denial of Service (DoS) attacks using infinite loops. Fortunately there is way to disable them.

First we disable recursive functions. This prevents users from defining functions looping indefinitely.

Second we disable the while loop. This also prevents users from entering never ending expressions.

That's it. Now feel free to get creative!

I think Keisan can be particularly appealing for any app / admin UI where formulas must be maintained and saved in database (think tax calculations, premium calculation etc..). Keisan provides a safe and extensible way of handling these use cases.

About us

Keypup's SaaS solution allows engineering teams and all software development stakeholders to gain a better understanding of their engineering efforts by combining real-time insights from their development and project management platforms. The solution integrates multiple data sources into a unified database along with a user-friendly dashboard and insights builder interface. Keypup users can customize tried-and-true templates or create their own reports, insights and dashboards to get a full picture of their development operations at a glance, tailored to their specific needs.


Code snippets hosted with ❤ by GitHub‍ Thumbnail designed by Vexels.com Banner designed by pngtree.com

Ready to Transform Your Analytics?

Join teams already using AI to make data-driven decisions faster than ever.

Most Recent Articles

The Stale Board: Why Jira Is Always Two Days Behind Your Code

The Stale Board: Why Jira Is Always Two Days Behind Your Code

In a typical enterprise, the Jira board trails Git by almost two business days per issue: code is written before tickets reach "In Progress", and tickets stay open days after their pull requests merge. Learn what engineering leaders on Reddit say about stale boards, status-chasing standups and sprint carryover that exists only on paper, and how Keypup MCP compares each issue's workflow timeline with the commits and merges of its linked pull requests to measure the lag and list the tickets to close.

Thomas Williams
The Time Zone Tax: Why Distributed Teams Lose a Day on Every Code Review

The Time Zone Tax: Why Distributed Teams Lose a Day on Every Code Review

In a typical distributed enterprise, a pull request reviewed from another hub waits 4.1 times longer for a first review, and each round of requested changes costs a day instead of a few hours. Learn what engineering leaders on Reddit say about code review across time zones, and how Keypup MCP measures the time zone tax, from the hour a review request is sent to the teams that review locally and the cross-hub pull requests to hand off before logging off.

Stephane Ibos
The Inner Source Tax: Why Pull Requests to Another Team's Repository Wait Days

The Inner Source Tax: Why Pull Requests to Another Team's Repository Wait Days

In a typical enterprise, a pull request sent to another team's repository waits 3.8 times longer for a first review, takes almost five working days to merge and is three times more likely to be abandoned. Learn what engineering leaders on Reddit say about cross-team contributions, and how Keypup MCP measures the inner source tax, from which owning teams are bottlenecks to which cross-team pull requests to unblock today.

Liam Davis