kevinschweikert

kevinschweikert

Ash encryption for resource attribute

Hi there,

is there a recommended way to encrypt/decrypt fields of a resource to the database?

I’ve used Cloak before, but i struggle to understand, how this would integrate into Ash.
It would be really nice if it worked like Cloak and with that I mean, that it encrypts/decrypts the data automatically when inserting/reading.

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash

In AshHq we use cloak to encrypt data. We do it with a combination of changes and calculations.

For instance:

attribute :encrypted_name, :string
attribute :encrypted_address, :string

Then, in actions we write to those attributes using arguments:

    update :update_merch_settings do
      argument :address, :string
      argument :name, :string

      accept [:shirt_size]
      change set_attribute(:encrypted_address, arg(:address))
      change set_attribute(:encrypted_name, arg(:name))
    end
  end

We don’t write to the encrypted attributes directly to prevent double encryption.

This is what our encryption change looks like:

defmodule AshHq.Changes.Encrypt do
  @moduledoc "Encrypt attributes that are being changed before submitting the action"
  use Ash.Resource.Change

  def change(changeset, opts, _) do
    Ash.Changeset.before_action(changeset, fn changeset ->
      Enum.reduce(opts[:fields], changeset, fn field, changeset ->
        case Ash.Changeset.fetch_change(changeset, field) do
          {:ok, value} when is_binary(value) ->
            new_value =
              value
              |> AshHq.Vault.encrypt!()
              |> Base.encode64()

            Ash.Changeset.force_change_attribute(changeset, field, new_value)

          _ ->
            changeset
        end
      end)
    end)
  end
end

And we apply it on every action like so:

  changes do
    ...
    change {AshHq.Changes.Encrypt, fields: [:encrypted_address, :encrypted_name]}
  end

Then, we can decrypt it on demand using calculations:

  calculations do
    calculate :address, :string, {Decrypt, field: :encrypted_address}
    calculate :name, :string, {Decrypt, field: :encrypted_name}
  end

And that calculation looks like this:

defmodule AshHq.Calculations.Decrypt do
  @moduledoc "Decrypts a given value on demand"
  use Ash.Calculation

  @impl Ash.Calculation
  def calculate(records, opts, _) do
    {:ok,
     Enum.map(records, fn record ->
       record
       |> Map.get(opts[:field])
       |> case do
         nil ->
           nil

         value ->
           value
           |> Base.decode64!()
           |> AshHq.Vault.decrypt!()
       end
     end)}
  end

  @impl Ash.Calculation
  def load(_, opts, _) do
    [opts[:field]]
  end
end

This was a very early addition to AshHq. I’d love to see an encryption extension at some point :slight_smile:

Also Liked

jimsynz

jimsynz

Ash Core Team

We also use this calculation based approach in a client app and it’s very handy because you have to explicitly ask for the decrypted value (via a load) and due to our policy configuration you have to provide an actor which also gives us a place to add audit logging at a later date.

mudspot

mudspot

Brilliant!

I managed to implement it with my custom Vault (without Cloak)

Thank you!

Where Next?

Popular in Questions Top

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44778 311
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement