Search code examples
crystal-langkemal

Embedded Crystal variables in templating


I’m new to Crystal (and never really used ruby) so apologies for the ignorance here! I've looked at the ecr docs but can't seem to find an answer there.

I’m looking at using Embedded Crystal for dynamic templates in Kemal. Can I confirm - can templates only render variables that are available in the scope of the call, or can one make method/function calls from within the template itself? I.E. is there any possibility/risk of being able to execute “malicious” crystal code from within a template (in this case malicious refers to I/O or file access etc)?

To take an example from the Kemal docs:

get "/:name" do |env|
  name = env.params.url["name"]
  render "src/views/hello.ecr"
end

In the view hello.ecr - is name the only item that will be available in the template, or could one call File.delete("./foo")from within the template for example?


Solution

  • A template is compiled into Crystal code, you can write any kind of code in there, like File.delete("./foo"), for example if you write <% File.delete("./foo") %> inside of your template.

    If your worry is that name will contain code and that will somehow get executed, then don't worry, that's not going to happen. Dynamic runtime code execution in Crystal is not possible, so there's no way someone will inject malicious code into your templates.