jeffdeville

jeffdeville

@schrockwell - I wasn’t sure if it’d be better to ask this here, or as a github issues, but thought more input would be sourced this way.

v2 of Bodyguard was recently released GitHub - schrockwell/bodyguard: Simple authorization conventions for Phoenix apps · GitHub

It’s AWESOME for authorization in phoenix 1.3. Highly recommended.

I do have one question that’s more about the docs and the 1.3 Phoenix release than anything else though.

Where do you CALL your authorization logic? The examples for bodyguard suggest doing so in the controller. That’s how things were done before, and it certainly keeps methods that otherwise don’t have any need for the user object to not require it. But it also makes it really easy to skip your authorization calls (inside or outside of your phoenix app). So it seems like forcing authorization would be ideal.

One other option would be to look at authorization from an AoP point of view. To do that effectively in phoenix, I think you’d need to find a way to store the current user on each call, and then wrap all of your auth-requiring methods in macros that will check your policies before executing the underlying code.

I saw a great article on Function Decorators here that could be used.

The negative to this approach is just that part about having to set ‘invisible’ data as context to a function. It never bothered me in OOP land, but it feels anti-functional here.

Showing Posts 1 to 10

OvermindDL1

OvermindDL1

I perform validation right on the line before accessing a DB call or refining data based on some permission. I have a lot of lines like this scattered about (copy/pasted):

    conn =
      conn
      |> Perms.verify(%Perms.SomeSection.Report{action: :view, report: report})
      |> ensure!()
      # Strip other things working on `conn`
jeffdeville

jeffdeville OP

Interesting.

I prefer not to have to see the same code repeated everywhere, particularly when it’s orthogonal to what the controller is really trying to do.

In a pre 1.3 world, you could probably do pretty well with a solution like this:

plug :load_user
plug :load_resource
plug :authorize

That would assume a fairly standard, RESTful layout, but for most web apps, it wouldn’t be far off. However, in a context world I’m pretty sure the right direction is to enforce security at your context boundaries.

jeffdeville

jeffdeville OP

Ok, here’s a compromise option between AoP and functional.

defauth create_user(user_params) do
  User.changeset(%User{}, user_params) |> Repo.insert
end

This would get compiled to this:

  @spec create_user(User.t, map)
  def create_user(%User{}=user, user_params) do
    with :ok <- UserPolicy.authorize(:create_user, user, user_params) do
      User.changeset(%User{}, user_params) |> Repo.insert
    end
  end

That way, the controller and everyone else is forced to provide that user for authorization, but doesn’t hide the user parameter and obfuscate how things work. And the context method gets to have a single responsibility.

OvermindDL1

OvermindDL1

Oh I don’t have it in the controller’s, it is in the modules that handle that necessary work. ^.^

Yeah that would not even remotely work here. I have to verify they have access to very specific things. Like even when I get rows back from a database I have to verify that they have permission to access specific rows so I Enum.filter a lot. Plugs entirely fail there.

tmbb

tmbb

Just to add to the point: I feel like I’ve gained superpowers the day I discovered I could check for permissions wherever I wanted and that a permission check is just an function that returns true or false (this was a long time ago, in python-land).

“Declarative permissions” and friends and all fine and good when it makes sense, but sometimes you just have to ask (the DB, the rules, the world, etc) if this user can do that, and often you only know exactly which question to ask just before you ask it.

schrockwell

schrockwell

Hi @jeffdeville – you’ve raised a good question. I went back-and-forth internally for a while about this. I think we can at least agree that, whether called internally or externally, the authorize/3 callback should exist directly on the context module itself, since it’s a context-specific API that determines what user can do.

Off the top of my head, here are some arguments for performing authorization in a controller action:

  • Reinforces the concept of controllers being the interface INTO your app – the first line of defense
  • Easier to call context methods from a privileged position (e.g. scheduled task, testing, etc) where we don’t care about authorization
  • Don’t need to pass the user (e.g. conn.assigns[:current_user]) into every context function if not needed (although lots of the time, we end up doing that anyway)
  • Easier to compose multiple context actions together
  • Leaner context functions that just “do the thing”

… and some arguments for performing authorization in a context function:

  • Strictly enforces authorization rules at application level – can’t skip it, no matter what. Arguably this is better design, and forces you to think about non-user-account cases like “guest” or “background task” users
  • Leaner controller actions
  • More flexibility to perform complex authorization rules, or change authorization rules without having to track down every context caller

So while I did pick controller-level authorization for the code examples, I don’t think it’s the One True Way, and the overall design is certainly up to you.

I think there is room in Bodyguard for a design element that gives you the best of both worlds – a way to perform authorization from within a context function (better design) but doesn’t require repetitive auth checks and passing the user model around everywhere (more convenient). I haven’t thought it through so I’m open to suggestions.

jeffdeville

jeffdeville OP

@schrockwell, if I took a stab at the macro described above (msg 4), and had it check the policies the way you have laid out, would you be interested in incorporating it into bodyguard? I believe it would meet the pros of both strategies with out the cons of either.

jeffdeville

jeffdeville OP

Implementation question. I can implement this as 1 method where the auth is baked in as in my description above, or I can implement it like this:

defauth create_user(user_params), do: stuff

compiling to:

def create_user(%User{} = user, user_params) do
  with :ok <- authorize(:create_user, user, user_params) do
    __create_user(user_params)
  end
end
def __create_user__(user_params) do
  User.changeset(%User{}, user_params) |> Repo.insert
end

Pros

Testing is easier, because you can write specs against __create_user__ for that functionality, and test the policy for the security separately.

Cons

It is possible to skip the auth check, but it’s pretty obvious you’re doing it.

I’m leaning toward this approach because I don’t worry about malicious developers using my libraries, and it feels like a reasonable balance of productivity and security, but I’m open to critiques.

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
widianto
I think I’ve found a small improvement I could contribute to &lt;%= web_namespace %&gt;.CoreComponents (installer/templates/phx_web/compo...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews