Skip to content

Any way to enforce strict mode on all maps by default? #932

Open

Description

@ar-sematell

I'm handling a dynamic env, which is represented by a map[string]any.
When using expr.Env, it only enforces the strict mode to the immediate map, but not any nested maps.
I want to enforce that any path or reference to this dynamic environment is accessible and valid, pretty much like a strict validation.

  • Only allow accessing existing variables and their nested attributes, erroring otherwise, like in the existing expr.Env behavior
  • Only allow accessing slice indexes that are given in the expr.Env or any nested attribute

Example:

// This compiles without error, but should error:
_, err := expr.Compile(`var1.attr2`,
	expr.Env(map[string]any{
		"var1": map[string]any{
			"attr1": 1,
		},
	}),
)
require.Error(t, err)

Activity

  1. antonmedv commented on Feb 19, 2026

    @antonmedv
    Member

    If a map-like structure is required, use types.Map instead of map[string]any. types.Map defines a closed set of allowed keys.

    env := types.Map{
        "var1": types.Map{
            "attr1": types.Int,
        },
    }
    
    _, err := expr.Compile(`var1.attr2`, expr.Env(env))
    require.Error(t, err)

    If additional dynamic keys are needed, types.Extra can be used to define a fallback type for unspecified keys.

  2. ar-sematell commented on Feb 20, 2026

    @ar-sematell
    Author

    I will test it, but I don't know if a dynamically parsed json structure would default to a custom map type.

    I don't control the input nor the program, but I want it to be strictly validated.

    All I receive is a json parsed object and a program.

  3. antonmedv commented on Feb 20, 2026

    @antonmedv
    Member

    You can construct typed env from you JSON document. Traverse the JSON and generate types.Map.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions