|
| 1 | +require "test_helper" |
| 2 | + |
| 3 | +class Slack::PuzzlesControllerTest < ActionDispatch::IntegrationTest |
| 4 | + setup do |
| 5 | + ENV["SLACK_SIGNING_SECRET"] = "test_signing_secret" |
| 6 | + end |
| 7 | + |
| 8 | + test "rejects request with invalid Slack signature" do |
| 9 | + post slack_puzzle_path, params: { payload: puzzle_payload }, |
| 10 | + headers: slack_headers(secret: "wrong_secret") |
| 11 | + |
| 12 | + assert_response :unauthorized |
| 13 | + end |
| 14 | + |
| 15 | + test "rejects request with expired Slack timestamp" do |
| 16 | + post slack_puzzle_path, params: { payload: puzzle_payload }, |
| 17 | + headers: slack_headers(timestamp: Time.now.to_i - 400) |
| 18 | + |
| 19 | + assert_response :unauthorized |
| 20 | + end |
| 21 | + |
| 22 | + test "renders ok when puzzle fails validation" do |
| 23 | + params = { payload: puzzle_payload(question: "") } |
| 24 | + |
| 25 | + post slack_puzzle_path, params: params, |
| 26 | + headers: slack_headers(body: params.to_query) |
| 27 | + |
| 28 | + assert_response :ok |
| 29 | + end |
| 30 | + |
| 31 | + test "renders ok even when Slack notification fails after puzzle is saved" do |
| 32 | + original = Slack::ApplicationController.instance_method(:send_message) |
| 33 | + Slack::ApplicationController.define_method(:send_message) { |*| nil } |
| 34 | + |
| 35 | + params = { payload: puzzle_payload(question: "What is unique about Ruby's blocks?") } |
| 36 | + |
| 37 | + post slack_puzzle_path, params: params, |
| 38 | + headers: slack_headers(body: params.to_query) |
| 39 | + |
| 40 | + assert_response :ok |
| 41 | + ensure |
| 42 | + Slack::ApplicationController.define_method(:send_message, original) |
| 43 | + end |
| 44 | + |
| 45 | + private |
| 46 | + |
| 47 | + def puzzle_payload(question: "What is Ruby?") |
| 48 | + { |
| 49 | + user: { id: "U123" }, |
| 50 | + view: { |
| 51 | + state: { |
| 52 | + values: { |
| 53 | + question: { question: { value: question } }, |
| 54 | + answer: { answer: { selected_option: { value: "ruby" } } }, |
| 55 | + explanation: { explanation: { value: "It is a programming language." } }, |
| 56 | + link: { link: { value: nil } } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + }.to_json |
| 61 | + end |
| 62 | + |
| 63 | + def slack_headers(secret: ENV["SLACK_SIGNING_SECRET"], timestamp: Time.now.to_i, body: "") |
| 64 | + ts = timestamp.to_s |
| 65 | + sig = "v0=" + OpenSSL::HMAC.hexdigest("SHA256", secret, "v0:#{ts}:#{body}") |
| 66 | + { "X-Slack-Request-Timestamp" => ts, "X-Slack-Signature" => sig } |
| 67 | + end |
| 68 | +end |
0 commit comments