Skip to content

String interpolation #4733

@anderseknert

Description

@anderseknert

Having string interpolation similar to Python f-strings in Rego would allow for more succint policy, while arguably improving readability by removing the ceremony associated with sprintf.

Another issue potentially addressed by this would be the common mistake of not handling undefined when referencing input/data in sprintf arguments. These will halt evaluation as any other undefined reference, but in the likely most common use case for sprintf — building a "message" or "reason" string to populate a partial rule set, whether a value is undefined or not is likely not interesting enough that you'd want it to affect the actual outcome of the evalutation.

deny[reason] {
    not "developer" in input.user.groups

    # fails if input.user.name is undefined, and the anonymous user will not be denied
    # this is likely not what the policy author intended
    reason := sprintf("%v must have role 'developer'", [input.user.name])
}
# less ceremony, and always evaluates if conditions in the body holds
# interpolation step could handle undefined (similar to `print`)
deny["{input.user.name} must have role 'developer'"] {
    not "developer" in input.user.groups
}

This would arguably improve string handling not just with regards to sprintf, but improve things like simple concatenation, which is currently somewhat verbose:

name := concat(", ", [input.first_name, input.last_name])

# vs.

name := "{input.first_name}, {input.last_name}"

Some design decisions would obviously need to be made here, like how to differentiate an "interpolation string" from a regular one, whether (simple?) expressions should be allowed in the interpolated values or only direct references, and perhaps there could be an "interpolation form" where undefined does fail evaluation, etc..

I don't have all the answers, but here's at least a starting point :)

Sub-issues

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions