alertmanager icon indicating copy to clipboard operation
alertmanager copied to clipboard

Add urldecode and safeURL template functions

Open tennisleng opened this issue 1 month ago • 0 comments

This PR adds two new template functions to address double-encoding issues when working with URLs in Alertmanager templates, as described in issue #4710.

Changes

  • urldecode: Decodes URL-encoded strings using url.QueryUnescape. Useful for extracting and manipulating query parameters from URLs (e.g., extracting expr from Prometheus GeneratorURL for Grafana Explore links).

  • safeURL: Marks a URL string as safe to prevent double-encoding by html/template. This provides an alias for safeUrl with capital URL naming for consistency.

Use Cases

These functions solve the problem where .GeneratorURL from Prometheus is already URL-encoded, but html/template escapes it again, resulting in double-encoded output (e.g., %2520 instead of %20).

Example Usage

{{ $expr := ( reReplaceAll ".*expr=([^&]+).*" "$1" (urldecode .GeneratorURL) ) }}
<a href="https://grafana.com/explore?expr={{ $expr }}">See in Grafana</a>

Or for trusted URLs:

<a href="{{ .GeneratorURL | safeURL }}">See in Prometheus</a>

Testing

  • Added unit tests for both urldecode and safeURL functions
  • Tests verify correct URL decoding and prevention of double-encoding

Fixes #4710

tennisleng avatar Nov 09 '25 20:11 tennisleng