2016-11-24 11 views
1

當我使用Brakeman的工具掃描我的代碼時,我收到一條警告消息。據指出,有以的無作用域調用下面的查詢:Brakeman中的「Unscoped call to」警告是什麼?

@applicant = Applicant.find(params[:id]) 

下面是實際的錯誤消息:

+------------+----------------------+---------+---------------+-----------------------------------------------------------------------------------------------------------------------------------------+ 
| Confidence | Class    | Method | Warning Type | Message                                 | 
+------------+----------------------+---------+---------------+-----------------------------------------------------------------------------------------------------------------------------------------+ 
| Weak  | ApplicantsController | show | Unscoped Find | Unscoped call to Applicant#find near line 25: Applicant.find(+params[:id]+)                |              | 
+------------+----------------------+---------+---------------+-----------------------------------------------------------------------------------------------------------------------------------------+ 

但是,當我用下面的替代上面的查詢,然後它的罰款:

@applicant = Applicant.where("id = ?", params[:id]).first 

我不明白第一個查詢有什麼問題。

+0

你能發佈實際的錯誤信息嗎? – mysmallidea

+0

@mysmallidea我有更新的問題,請檢查 –

回答

6

Brakeman只是警告您,您正在查詢整個申請人表格,而不是在另一個模型(如current_tenant.applicants.find...)下查找它。 From Brakeman's docs

未搜索到的查找(和相關方法)是直接對象引用的一種形式。通常應該通過作用域查詢來訪問屬於另一個模型的模型。

例如,如果一個帳戶所屬的用戶,那麼這可能是不安全的未範圍的發現:

Account.find(params[:id]) 

根據不同的動作,這可能允許攻擊者訪問他們想要的任何賬戶。

相反,它應該作用域爲當前登錄的用戶:

current_user = User.find(session[:user_id]) 
current_user.accounts.find(params[:id]) 

如果這是你想要的行爲,可以通過配置來司閘員忽略此警告爲誤報。爲此,請使用-I標誌(或--interactive-ignore)運行brakeman。按照Ignoring False Positives上的說明逐步完成所有警告,並將此特定的警告添加到您的忽略文件中。

一言以蔽之:

$ brakeman -I 
Input file: |config/brakeman.ignore| 
# press Enter to accept the default ignore file 
No such file. Continue with empty config? 
# press Enter to create the file 
> 
1. Inspect all warnings 
2. Hide previously ignored warnings 
3. Skip - use current ignore configuration 
# press 2 to step through all warnings, skipping previously ignored 
# Brakeman will now step through each warning, prompting you to for each one. 
# Press i to add this warning to the ignore list. 
# When finished, Brakeman will ask you what to do. 
# Press 1 to save changes to the ignore file. 

運行司閘員下一次,這樣的警告應該不會出現。

+0

非常感謝這個信息,是我試圖在我的第二個查詢中使用的方式是正確的嗎? –

+0

我會使用第一個查詢('@applicant = Applicant.find(params [:id])') - 這樣做第二種方式('where..first')如果沒有找到記錄,將不會引發404錯誤。這樣做的第一種方法將引發ActiveRecord :: RecordNotFound異常,這是你想要的。 – mysmallidea

+0

這裏有一個類似的答案:http://stackoverflow.com/questions/32102172/ruby-on-rails-what-do-these-brakeman-warnings-mean – mysmallidea