惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

TaoSecurity Blog
TaoSecurity Blog
T
Troy Hunt's Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
T
Threatpost
G
Google Developers Blog
T
Threat Research - Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
The Exploit Database - CXSecurity.com
H
Heimdal Security Blog
Google DeepMind News
Google DeepMind News
Cyberwarzone
Cyberwarzone
T
The Blog of Author Tim Ferriss
Know Your Adversary
Know Your Adversary
Hacker News: Ask HN
Hacker News: Ask HN
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Schneier on Security
B
Blog
V2EX - 技术
V2EX - 技术
NISL@THU
NISL@THU
C
CERT Recently Published Vulnerability Notes
W
WeLiveSecurity
C
Cybersecurity and Infrastructure Security Agency CISA
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Y
Y Combinator Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Spread Privacy
Spread Privacy
The Last Watchdog
The Last Watchdog
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
Schneier on Security
Schneier on Security
F
Fortinet All Blogs
N
News | PayPal Newsroom
Attack and Defense Labs
Attack and Defense Labs
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
S
Security @ Cisco Blogs
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
P
Privacy & Cybersecurity Law Blog
P
Proofpoint News Feed
Project Zero
Project Zero
I
Intezer
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
SecWiki News
SecWiki News
Martin Fowler
Martin Fowler

Nic Lin's Blog

謝明真 - 高效領導力的課後筆記 NFT 開發實戰!基礎智能合約入門 (3) NFT 開發實戰!基礎智能合約入門 (2) NFT 開發實戰!基礎智能合約入門 (1) 如何自我檢測 log4j CVE 漏洞 如何經營工程師 Youtube 頻道 - Part 8 營收篇 如何經營工程師 Youtube 頻道 - Part 7 酸民文化篇 如何經營工程師 Youtube 頻道 - Part 5 設備器材篇 如何經營工程師 Youtube 頻道 - Part 4 後製剪輯篇 如何經營工程師 Youtube 頻道 - Part 3 文案企劃篇 如何經營工程師 Youtube 頻道 - Part 2 設備器材篇 如何經營工程師 Youtube 頻道 - Part 1 制訂頻道方向篇 如何經營工程師 Youtube 頻道 - Part 0 Rails 中避免 race condition 的最佳實踐(二) Rails 中避免 race condition 的最佳實踐(一) 10 分鐘整合 google sheet 做自動化開發功能週報 經營 Side Project 300 天所帶來的收穫及挑戰 我的 Youtube 影片製作流程 API 設計時必須注意的 HTTP header 底線問題 如何提升你的程式可讀性之實務技巧(三) 如何提升你的程式可讀性之實務技巧(二) 如何提升你的程式可讀性之實務技巧(一) Ruby 中使用 freeze 優化效能的時機 避免 React 中的 useEffect 無限 render 在 Rails 內輕量使用 Vue Component 的最佳實踐 如何在區域網路用 Docker 架設有 SSL 的 Gitlab 從被問到問人,那些我常問的面試問題 [Rails] 如何漂亮寫出可維護的 query (Maintainable Rails Query) 在已知長度情況下優化 slice 的性能 [ReactNative] 如何在 iOS APP 上主動要求用戶評分 Rails 的 scope 為什麼用 lambda? Proc 與 lambda 不同之處 淺談 Active Record 的 Lazy load 特性 Rails 專案搭配 Github Actions 進行 RSpec 自動化測試 JavaScript 中 require, import 的差別及效能 React 效能優化基本招 ES6 箭頭函式 (Arrow functions) 2 個月擁有 6000 用戶 Side project 這樣做(一) 如何讓自己成為失敗的軟體工程師 如何用 Rack::Attack 阻擋 DDOS / 惡意流量 用 OpenSSL 自簽開發用 HTTPS SSL 憑證 為機器加上登入訊息,在 ubuntu 設置登入歡迎詞 Ruby Memoization 性能優化之記憶化 淺談 SSH agent forwarding 和 proxy command 的安全風險與應用 [Rails] Service / Library / Concern 的差異 避免過度的 Defensive Programming 防禦性程式設計 1:1 攪亂器,如何用 Ruby 做可逆推序號 Rails 中的欄位及方法命名原則 [Rails] 用 puma-dev 作為本地開發伺服器 (支援 https 自簽憑證) 將 Rails 專案從手動部屬遷移使用 Capistrano 自動化部屬 工程師提昇自己的教學和簡報技術的方法 [筆記] Rails 3.2 升級 Rails 6.beta 經驗分享 Class method 氾濫帶來什麼問題 RDBMS 課程心得與筆記 常用的 Rails 開發規範 Rest-Client 如何做 Basic Authentication 驗證 [Rails] 何為 tld_lebgth? 遵循 Semantic Versioning 軟體開發語意化版本管理 請直接在 MySQL 裡面直接用 utf8mb4 取代 utf8 如何解決在 awesome print 中遇到 ActionController::Parameters unable to convert unpermitted 如何在 Mac 上升級 PostgreSQL 並遷移資料 如何解決 Mysql2::Error: Incorrect string value 讀書心得 - 「信任因子:信任如何影響大腦運作、激勵員工、達到組織目標」 我是如何寫部落格筆記的 讀書心得 - 「先問,為什麼?:顛覆慣性思考的黃金圈理論,啟動你的感召領導力」 [Rails] 解決 Reset Password 帶來的 token 洩漏問題 我的軟體工程師生涯:如何挑選適合你的公司 Rails 中的 delegate 用法 淺述 SSR SPA 優缺點 Rails 非同步工作請用 Global ID [React] Class Component 傳遞 props 的 2 種方式 好用的隱私權政策 URL 自動生成 Rails 5.1 之後的 tag helper Rails 5.2 Encrypted Credentials 最近面試被給的建議和書單 一般架構需要用到 K8S 嗎 透過 commit SHA 找 github Pull request 從零搭建,如何讓 Rails 跑在 Kubernetes(k8s)(二) 從零搭建,如何讓 Rails 跑在 Kubernetes(k8s)(一) React Stateless Functional Components 搞懂 React 中的 state 和 props 物件導向基本原則 SOLID (Ruby Sample) 在以太坊智能合約上是可以預測隨機數的 在台灣租屋必須注意的事 Rails 5 簡單雙向加解密 如何用 ABA 培養自律型員工 不要在 rake task 中定義 method, 請用 RAKE::DSL rails 非hash只想用array輸出page 如何處理陣列裡有重複的值 [Rails] 如何重設你的專案名稱 Ruby on Rails install on Mac 安裝步驟 使用 Friendly_id 與 Babosa 美化你的Rails 網址 Junior Rails 兩個月實戰心得 Devise使用Google實作登入 [iterm2] 如何新增alias 一個新鮮人找尋Rails工作的面試經驗 如何讓兩個資料表建立關聯 routing 的 namespace strong parameter user story 的格式 user story 是什麼?
Rails 如何在資料寫入時記錄來源 IP 位置
Nic Lin · 2020-11-09 · via Nic Lin's Blog

以 Rails 的實際應用來說,大多數都是透過來源請求進 routes 後展開的生命週期 (controller, model, view)

也就是說,如果要能 call 到某一個 method,在此之前都一定會有 HTTP 請求

但也有幾個狀況例外

  1. 開發人員自己進 run time 環境,例如 rails console
  2. background job

撇除以上兩個情況來說

我們希望在呼叫 service、model 時,都能夠記錄來源的 IP 位置

那麼應該會這樣做

  1. request 進來
  2. rack 處理後進 route
  3. route 前往 controller 找到 action
  4. action method 將記錄透過參數傳遞到 method

類似這樣

class PostController
  def create
     service = Post::CreateService.new(params, request.remote_ip)
     if service.perform
       # logic
     end
  end
end

如果不只有 IP,還有 user agent 等等其他的請求訊息呢?

是把 request 繼續往下丟,還是傳遞更多這類型的參數?

可想而知的是,接著會看到更多相關的地方,都在丟 request 進 service、model 之類的

難道都沒有辦法可以更簡單拿到這次請求的相關資訊嗎?

CurrentAttributes

Rails 5.2 之後提供的 active support 的 current attribute 更適合解決這個問題

# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
  attribute :request_id, :user_agent, :ip_address
end

# app/controllers/concerns/set_current_request_details.rb
module SetCurrentRequestDetails
  extend ActiveSupport::Concern

  included do
    before_action do
      Current.request_id = request.uuid
      Current.user_agent = request.user_agent
      Current.ip_address = request.ip
    end
  end
end

class ApplicationController < ActionController::Base
  include SetCurrentRequestDetails
end

class Event < ApplicationRecord
  before_create do
    self.request_id = Current.request_id
    self.user_agent = Current.user_agent
    self.ip_address = Current.ip_address
  end
end

只要在線程中呼叫 Current.ip_address 就可以拿到這次請求的 IP,也就是說,只要設定好,在任何的地方都可以拿到 request 資訊

追了一下原始碼,該類別主要是對於每一次進來的執行緒都會在之前和之後進行重置,去實現資訊隔離的部分

至於測試撰寫的部分,我認為可以將與 request 相關的資料儲存,例如 ip_address 欄位等部分,預設是空值 null,把它當作有就有,沒有就沒有的設計會比較來的沒有負擔一些

畢竟 IP 位置在整個商業邏輯上面本來就比較屬於「參考」的部分

全域變數帶來的問題

這個問題討論很多年了,通常我們都會得到一個觀念是,不要使用全域變數

因為全域變數會讓整個系統變得更加難以掌控及測試,我們不知道是什麼時候被建立了變數,又是在哪一段程式被改掉的

而很有趣的是,這個 CurrentAttributes 的類似需求,在 2012 年就有人提過,並希望可以在系統中更容易拿到 reqesut 的資訊,但該討論也是不建議使用全域變數,應該採用更顯式的傳遞方式去處理

不過到了 2017 年反倒是 rails creator DHH 完成了這個 PR

當中還是有人非常不建議這樣做,甚至有人寫了一篇部落格特別說明其害處 Rails’ CurrentAttributes considered harmful

不過如果你就上面那篇部落格文章所指的案例來說,我也認為像是 current_user 這個不該被放在全域變數,因為能耦合 User 的邏輯太多了,很容易被誤用而且失控

但就獲取來源 IP 這種輕量使用來說,確實提供了很方便也容易理解的做法,可以避免到處傳參數的麻煩,又或是參數丟很深的困擾

如果你仔細看文檔,是有善意提醒全域變數不要過度使用,否則會產生混亂

A word of caution: It’s easy to overdo a global singleton like Current and tangle your model as a result. Current should only be used for a few, top-level globals, like account, user, and request details. The attributes stuck in Current should be used by more or less all actions on all requests. If you start sticking controller-specific attributes in there, you’re going to create a mess.

雖然有部分人質疑 DHH 的做法,但 DHH 也有在 PR 上面說明這不是什麼新發明,其他用 Rails 的公司包含他自己也有需要這種模式來獲取資訊的經驗

DHH: This pattern is used by Basecamp, GitHub, Shopify, and many others. It’s not a new invention, but an extraction. Like almost all features in Rails.

如果繼續追下去,去看 Rails 自己本身的 ActiveStorage 的部分,也有使用到該功能來獲取當前的 host

總結

有人說 Rails 的框架 DHH 可以自己愛搞什麼就搞什麼,不必非得要聽社群的聲音

但其實我覺得沒這麼嚴重啦,每個設計本來就有其 trade off 要去辨別、理解

如果只是為了守護「不要使用全域變數」這樣的信念,為了解決拿到 IP 這個需求,又必須從 controller 出發後將參數到處傳,沒有更好辦法的時候,謹慎且有原則的使用這樣子的全域變數,又有何不可呢?