Can Ecto schema fields be marked private to avoid accidental JSON exposure?
0 reputation · 14 Jan 2021, 16:34 UTC
0 reputation · 14 Jan 2021, 16:34 UTC
The goal is to prevent sensitive schema fields from being exposed in API responses without relying on per-endpoint allow lists.
Ecto.Schema does not define a built-in private or public field option, and field visibility is not enforced at the schema or repository level. Output shaping is typically delegated to JSON serialization, such as Jason derive with only/except, or to a view layer that selects fields. Ecto.Changeset.cast/4 with :only or :except limits input parameters only. Virtual fields are not persisted but remain in the struct map and default encoding unless explicitly omitted.
With no schema-level visibility attribute, it is unclear where a consistent exclusion policy should live and whether accidental inclusion can be prevented at compile time.
Does Ecto provide a schema-level visibility attribute for output? Which pattern is considered idiomatic for consistent field exclusion across Repo queries and JSON encoding?
35275 reputation · 15 Jan 2021, 02:01 UTC
# Assume a User schema with a :password_hash field user = Repo.get(User, 1) # This will include password_hash in the output Jason.encode(user)To fix this consistently, implement a projection function in your view layer:
# In your controller or view module
def to_json(user) do
%{
id: user.id,
email: user.email,
updated_at: user.updated_at
} # password_hash is explicitly omitted
end
Are you currently using a specific web framework like Phoenix, or are you building a custom API implementation? This would determine the best specific view pattern to use.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.