Class: Kirei::Routing::Base

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/kirei/routing/base.rb

Direct Known Subclasses

App, Controller

Constant Summary collapse

NOT_FOUND =

rubocop:disable Style/MutableConstant

T.let([404, {}, ["Not Found"]], RackResponseType)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params: {}) ⇒ Base

Returns a new instance of Base.



14
15
16
17
# File 'lib/kirei/routing/base.rb', line 14

def initialize(params: {})
  @router = T.let(Router.instance, Router)
  @params = T.let(params, T::Hash[String, T.untyped])
end

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



20
21
22
# File 'lib/kirei/routing/base.rb', line 20

def params
  @params
end

Instance Method Details

#add_cors_headers(headers, env) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/kirei/routing/base.rb', line 175

def add_cors_headers(headers, env)
  origin = T.cast(env.fetch("HTTP_ORIGIN", nil), T.nilable(String))
  return if origin.nil?

  allowed_origins = Kirei::App.config.allowed_origins
  return unless allowed_origins.include?(origin)

  headers["Access-Control-Allow-Origin"] = origin
  headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
  headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, Referer"
  headers["Access-Control-Allow-Credentials"] = "true"
end

#call(env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/kirei/routing/base.rb', line 26

def call(env)
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
  status = 500 # we use it in the "ensure" block, so we need to define early (Sorbet doesn't like `status ||= 418`)

  http_verb = Verb.deserialize(env.fetch("REQUEST_METHOD"))
  req_path = T.cast(env.fetch("REQUEST_PATH"), String)
  #
  # TODO: reject requests from unexpected hosts -> allow configuring allowed hosts in a `cors.rb` file
  #   ( offer a scaffold for this file )
  # -> use https://github.com/cyu/rack-cors ?
  #

  lookup_verb = http_verb == Verb::HEAD ? Verb::GET : http_verb
  route = router.get(lookup_verb, req_path)
  return NOT_FOUND if route.nil?

  router.current_env = env # expose the env to the controller

  params = case http_verb
           when Verb::GET
             query = T.cast(env.fetch("QUERY_STRING"), String)
             query.split("&").to_h do |p|
               k, v = p.split("=")
               k = T.cast(k, String)
               [k, v]
             end
           when Verb::POST, Verb::PUT, Verb::PATCH
             # TODO: based on content-type, parse the body differently
             #       built-in support for JSON & XML
             body = T.cast(env.fetch("rack.input"), T.any(IO, StringIO))
             res = Oj.load(body.read, Kirei::OJ_OPTIONS)
             body.rewind # TODO: maybe don't rewind if we don't need to?
             T.cast(res, T::Hash[String, T.untyped])
           when Verb::HEAD, Verb::DELETE, Verb::OPTIONS, Verb::TRACE, Verb::CONNECT
             {}
           else
             T.absurd(http_verb)
  end

  req_id = T.cast(env["HTTP_X_REQUEST_ID"], T.nilable(String))
  req_id ||= "req_#{App.environment}_#{SecureRandom.uuid}"
  Thread.current[:request_id] = req_id

  controller = route.controller
  before_hooks = collect_hooks(controller, :before_hooks)
  run_hooks(before_hooks)

  Kirei::Logging::Logger.call(
    level: Kirei::Logging::Level::INFO,
    label: "Request Started",
    meta: {
      "http.method" => route.verb.serialize,
      "http.route" => route.path,
      "http.host" => env.fetch("HTTP_HOST"),
      "http.request_params" => params,
      "http.client_ip" => env.fetch("CF-Connecting-IP", env.fetch("REMOTE_ADDR")),
    },
  )

  statsd_timing_tags = {
    "controller" => controller.name,
    "route" => route.action,
  }
  Logging::Metric.inject_defaults(statsd_timing_tags)

  status, headers, response_body = case http_verb
                                   when Verb::HEAD, Verb::OPTIONS, Verb::TRACE, Verb::CONNECT
                                     [200, {}, []]
                                   when Verb::GET, Verb::POST, Verb::PUT, Verb::PATCH, Verb::DELETE
                                     T.cast(
                                       controller.new(params: params).public_send(route.action),
                                       RackResponseType,
                                     )
                                   else
                                     T.absurd(http_verb)
  end

  after_hooks = collect_hooks(controller, :after_hooks)
  run_hooks(after_hooks)

  headers["X-Request-Id"] ||= req_id

  default_headers.each do |header_name, default_value|
    headers[header_name] ||= default_value
  end

  add_cors_headers(headers, env)

  [
    status,
    headers,
    response_body,
  ]
ensure
  stop = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
  if start # early return for 404
    latency_in_ms = stop - start
    ::StatsD.measure("request", latency_in_ms, tags: statsd_timing_tags)

    Kirei::Logging::Logger.call(
      level: status >= 500 ? Kirei::Logging::Level::ERROR : Kirei::Logging::Level::INFO,
      label: "Request Finished",
      meta: { "response.body" => response_body, "response.latency_in_ms" => latency_in_ms },
    )
  end

  # reset global variables after the request has been served
  # and after all "after" hooks have run to avoid leaking
  Thread.current[:enduser_id] = nil
  Thread.current[:request_id] = nil
end

#default_headersObject



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/kirei/routing/base.rb', line 158

def default_headers
  {
    # security relevant headers
    "X-Frame-Options" => "DENY",
    "X-Content-Type-Options" => "nosniff",
    "X-XSS-Protection" => "1; mode=block", # for legacy clients/browsers
    "Strict-Transport-Security" => "max-age=31536000; includeSubDomains", # for HTTPS
    "Cache-Control" => "no-store", # the user should set that if caching is needed
    "Referrer-Policy" => "strict-origin-when-cross-origin",
    "Content-Security-Policy" => "default-src 'none'; frame-ancestors 'none'",

    # other headers
    "Content-Type" => "application/json; charset=utf-8",
  }
end

#render(body, status: 200, headers: {}) ⇒ Object



149
150
151
152
153
154
155
# File 'lib/kirei/routing/base.rb', line 149

def render(body, status: 200, headers: {})
  [
    status,
    headers,
    [body],
  ]
end