ruby-grape / ruby-grape/grape

`before` block called before valid route is checked for.

Open
#1,402 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

discuss! needs info
Dominant language
Ruby
Stars
10k
Forks
1.2k
Avg merge
14h 38m
Merged PRs (30d)
92

Description

On version 0.16.2, I have the following configured;

class Foos < Grape::API
  include AuthCheck
  ...
  resource :foo do
    ...
    get '/:foo/:id' do
      ...
    end

    # But no POST route
  end
end
module AuthCheck
  extend ActiveSupport::Concern

  included do
    before do
      error!('Unauthorized', 401) unless headers_has_secret
    end
  end
end

A GET request to foo/<foo-id> will either respond with a 200 or a 400 as expected. A POST however will 500;

ArgumentError (uncaught throw :error):
  app/api/my_auth_check.rb:8:in `block (2 levels) in <module:AuthCheck>'

Because it's a throw, this is the only line of the stack trace. If I force a throw and send a GET request I do get a big stack trace, which means the throw is caught in that case. If I write a post block, I get the expected behavior.

It seems like grape is running the before block before it checks to see whether the request has a matching route. Is this the intended behaviour?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the shown API in app/api/my_auth_check.rb and compare the GET request with the POST request for a missing route. Trace Grape's route-matching and before-hook entry points to determine why the unauthorized throw is uncaught; done means the missing POST route follows the expected error behavior and the regression is covered by a test.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
api, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.