quicsilver-rails 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +31 -0
  3. data/LICENSE +21 -0
  4. data/README.md +167 -0
  5. data/app/javascript/quicsilver/action_cable.js +216 -0
  6. data/app/javascript/quicsilver/cable_boot.js +23 -0
  7. data/app/javascript/quicsilver/web_transport.js +120 -0
  8. data/config/importmap.rb +6 -0
  9. data/docs/action-cable.md +203 -0
  10. data/docs/local-certificates.md +119 -0
  11. data/docs/webtransport-endpoints.md +254 -0
  12. data/lib/generators/quicsilver/install/install_generator.rb +95 -0
  13. data/lib/generators/quicsilver/install/templates/Procfile.http3.dev.tt +8 -0
  14. data/lib/generators/quicsilver/install/templates/dev-http3.tt +15 -0
  15. data/lib/generators/quicsilver/install/templates/quicsilver.tt +5 -0
  16. data/lib/quicsilver/action_cable/cookie_bridge.rb +70 -0
  17. data/lib/quicsilver/action_cable/socket.rb +213 -0
  18. data/lib/quicsilver/action_cable.rb +83 -0
  19. data/lib/quicsilver/engine.rb +53 -0
  20. data/lib/quicsilver/middleware/alt_svc.rb +32 -0
  21. data/lib/quicsilver/rails/cable_credential_helper.rb +27 -0
  22. data/lib/quicsilver/rails/dev_web_transport_certificate.rb +155 -0
  23. data/lib/quicsilver/rails/meta_tags_helper.rb +47 -0
  24. data/lib/quicsilver/rails/port.rb +15 -0
  25. data/lib/quicsilver/rails/request_protocol.rb +16 -0
  26. data/lib/quicsilver/rails/server.rb +83 -0
  27. data/lib/quicsilver/rails/transport_logger.rb +62 -0
  28. data/lib/quicsilver/rails/version.rb +7 -0
  29. data/lib/quicsilver/rails/web_transport_certificate_helper.rb +20 -0
  30. data/lib/quicsilver/rails.rb +3 -0
  31. data/lib/quicsilver/routes.rb +27 -0
  32. data/lib/quicsilver/web_transport/channel/dispatcher.rb +76 -0
  33. data/lib/quicsilver/web_transport/channel.rb +69 -0
  34. data/lib/quicsilver/web_transport/codec.rb +43 -0
  35. data/lib/quicsilver/web_transport/datagram_endpoint.rb +40 -0
  36. data/lib/quicsilver/web_transport/endpoint.rb +137 -0
  37. data/lib/quicsilver/web_transport/framed_stream.rb +59 -0
  38. data/lib/quicsilver/web_transport/message_codec.rb +29 -0
  39. data/lib/quicsilver/web_transport/message_stream_endpoint.rb +54 -0
  40. data/lib/quicsilver/web_transport/rpc_endpoint.rb +53 -0
  41. data/lib/quicsilver/web_transport/server_streaming_endpoint.rb +72 -0
  42. data/lib/quicsilver/web_transport/stream_handler.rb +65 -0
  43. data/lib/quicsilver/web_transport/thread_runner.rb +18 -0
  44. data/lib/quicsilver/web_transport.rb +21 -0
  45. data/lib/quicsilver-rails.rb +17 -0
  46. data/lib/tasks/quicsilver.rake +16 -0
  47. metadata +161 -0
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env sh
2
+ # Runs the app in development over HTTPS on TCP and HTTP/3 on UDP, both on QUICSILVER_PORT. Browsers
3
+ # reach HTTP/3 through the HTTPS server: its Alt-Svc header tells them where to find it.
4
+
5
+ if ! gem list foreman -i --silent; then
6
+ echo "Installing foreman..."
7
+ gem install foreman
8
+ fi
9
+
10
+ export QUICSILVER_PORT="${QUICSILVER_PORT:-3443}"
11
+
12
+ # Once, before either server starts, so both serve the same certificate.
13
+ bin/rails quicsilver:certificate || exit 1
14
+
15
+ exec foreman start -f Procfile.http3.dev "$@"
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+ # Serves the app over HTTP/3 (QUIC, on UDP), next to its HTTPS server on TCP.
3
+ require_relative "../config/environment"
4
+
5
+ Quicsilver::Rails::Server.start
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext/integer/time"
5
+ require "active_support/message_encryptor"
6
+ require "rack/utils"
7
+
8
+ module Quicsilver
9
+ module ActionCable
10
+ # Gives a WebTransport cable the cookies the browser leaves out.
11
+ #
12
+ # Browsers send no cookies on a WebTransport CONNECT, so an app's usual lookup in
13
+ # ApplicationCable::Connection#connect finds nobody. The page that opens the cable did arrive
14
+ # with cookies, though. The bridge encrypts the allowlisted ones into a token the page renders,
15
+ # the socket sends it back in its handshake frame, and the adapter restores them as the
16
+ # request's Cookie header before #connect runs. The app authenticates the cable exactly as it
17
+ # does over a WebSocket.
18
+ #
19
+ # Only the cookies named in config.quicsilver.cable_cookies travel, so unrelated cookies stay
20
+ # out of the page. Without it, the ones Rails apps sign in with by default (see .default_names).
21
+ # The token is encrypted, expires, and is only read on a cable handshake.
22
+ #
23
+ # It carries a snapshot: a cookie rotated after the page rendered arrives stale until the next
24
+ # page load. Revoking access on logout depends on the app's lookup: a database-backed session
25
+ # stops working when its row goes, but a cookie-store session keeps working until the token
26
+ # expires, as a copied cookie would.
27
+ class CookieBridge
28
+ PURPOSE = "quicsilver.action_cable.cookies"
29
+ EXPIRES_IN = 1.day
30
+
31
+ def self.from_rails
32
+ app = ::Rails.application if defined?(::Rails)
33
+ return unless app
34
+
35
+ names = app.config.quicsilver.cable_cookies || default_names(app)
36
+ new(secret: app.key_generator.generate_key(PURPOSE, 32), names: names)
37
+ end
38
+
39
+ # The session cookie, which holds a Devise or session[:user_id] sign-in, and session_id, the
40
+ # cookie Rails' authentication generator signs users in with. Only those present travel.
41
+ def self.default_names(app)
42
+ [ app.config.session_options.to_h[:key], "session_id" ].compact
43
+ end
44
+
45
+ def initialize(secret:, names:)
46
+ @encryptor = ActiveSupport::MessageEncryptor.new(secret)
47
+ @names = Array(names).map(&:to_s)
48
+ end
49
+
50
+ # The token for a request's cookies, or nil when none of the allowlisted ones are present.
51
+ def token_for(cookies)
52
+ selected = cookies.to_h.slice(*@names)
53
+ @encryptor.encrypt_and_sign(cookie_header(selected), purpose: PURPOSE, expires_in: EXPIRES_IN) if selected.any?
54
+ end
55
+
56
+ # The Cookie header a token carries, or nil when it is missing, forged or expired.
57
+ def read(token)
58
+ @encryptor.decrypt_and_verify(token, purpose: PURPOSE) if token.is_a?(String) && !token.empty?
59
+ rescue ActiveSupport::MessageEncryptor::InvalidMessage
60
+ nil
61
+ end
62
+
63
+ private
64
+ # Escaped the way Rack escapes a value it sets, so Rack parses back exactly what the browser sent.
65
+ def cookie_header(cookies)
66
+ cookies.map { |name, value| "#{::Rack::Utils.escape(name)}=#{::Rack::Utils.escape(value)}" }.join("; ")
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,213 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "quicsilver/web_transport"
5
+ require "quicsilver/web_transport/framed_stream"
6
+
7
+ module Quicsilver
8
+ module ActionCable
9
+ # Action Cable socket adapter backed by a Quicsilver WebTransport session.
10
+ #
11
+ # This implements the same small transport surface as Action Cable's own WebSocket wrapper
12
+ # (ActionCable::Connection::WebSocket on Rails 8.0 and 8.1, ActionCable::Server::Socket::WebSocket
13
+ # on later Rails):
14
+ #
15
+ # - possible?
16
+ # - alive?
17
+ # - transmit
18
+ # - close
19
+ # - protocol
20
+ # - rack_response
21
+ #
22
+ # It intentionally uses one reliable WebTransport bidirectional stream.
23
+ # Action Cable keeps its own channel multiplexing and JSON protocol.
24
+ #
25
+ # Browsers send no cookies on a WebTransport CONNECT, so cookie-based
26
+ # Action Cable authentication sees an anonymous request and rejects it.
27
+ # The client therefore opens the stream with one handshake frame carrying
28
+ # a credential the page rendered, and the connection's #connect reads it
29
+ # through Quicsilver::ActionCable.credential. It travels in the stream,
30
+ # not the URL, so it stays out of request logs.
31
+ class Socket
32
+ HANDSHAKE_KEY = "quicsilver_handshake"
33
+
34
+ attr_reader :session, :stream
35
+
36
+ def initialize(env, event_target, event_loop = nil, protocols: self.class.default_protocols)
37
+ @env = env
38
+ @event_target = event_target
39
+ @event_loop = event_loop
40
+ @protocols = protocols
41
+ @session = Quicsilver::WebTransport.from_env(env)
42
+ @raw_stream = nil
43
+ @stream = nil
44
+ @reader = nil
45
+ @open = false
46
+ end
47
+
48
+ def possible?
49
+ !!session
50
+ end
51
+
52
+ def alive?
53
+ @open && session&.open?
54
+ end
55
+
56
+ def transmit(message)
57
+ return false unless alive? && stream
58
+
59
+ stream.write_message(message)
60
+ true
61
+ end
62
+
63
+ def close(_code = nil, _reason = nil)
64
+ @open = false
65
+ stream&.close
66
+ ensure
67
+ session&.close
68
+ end
69
+
70
+ def protocol
71
+ @protocols.first
72
+ end
73
+
74
+ def rack_response
75
+ return [404, {}, []] unless possible?
76
+
77
+ session.accept!
78
+ session.on_stream { |raw_stream| attach_stream(raw_stream) }
79
+
80
+ [200, {}, []]
81
+ rescue => error
82
+ @event_target.on_error(error.message) if @event_target.respond_to?(:on_error)
83
+ close
84
+ [500, {}, []]
85
+ end
86
+
87
+ def self.default_protocols
88
+ if ::ActionCable.const_defined?(:INTERNAL)
89
+ ::ActionCable::INTERNAL[:protocols]
90
+ else
91
+ ["actioncable-v1-json"]
92
+ end
93
+ end
94
+
95
+ private
96
+
97
+ attr_reader :event_target
98
+
99
+ def attach_stream(raw_stream)
100
+ # One stream carries the cable protocol. A client that opens another
101
+ # is told so rather than left waiting on a stream nothing reads.
102
+ # Checked against the stream rather than @open, which only flips once
103
+ # the handshake has been read on the reader thread.
104
+ if @stream
105
+ raw_stream.close
106
+ return
107
+ end
108
+
109
+ @raw_stream = raw_stream
110
+ @stream = Quicsilver::WebTransport::FramedStream.new(@raw_stream)
111
+ start_reader
112
+ end
113
+
114
+ def start_reader
115
+ @reader = Thread.new do
116
+ # The handshake is read before on_open, because on_open is what
117
+ # runs the connection's #connect — authentication has to find the
118
+ # credential already in place. It also means nothing is transmitted
119
+ # until the client has a stream to receive it on.
120
+ pending = read_handshake
121
+
122
+ @open = true
123
+ event_target.on_open
124
+ event_target.on_message(pending) if pending
125
+
126
+ while alive? && (message = stream.read_message)
127
+ event_target.on_message(message)
128
+ end
129
+ rescue => error
130
+ unless session_ended?(error)
131
+ event_target.on_error(error.message) if event_target.respond_to?(:on_error)
132
+ end
133
+ ensure
134
+ @open = false
135
+ event_target.on_close("", 1000)
136
+ end
137
+ end
138
+
139
+ # WT_SESSION_GONE is how a stream learns its session closed: the spec resets every stream of
140
+ # a session that ends, including when the server closes it on shutdown. That is the cable
141
+ # closing, not failing, so it reaches #on_close without an error.
142
+ def session_ended?(error)
143
+ defined?(Quicsilver::Server::WebTransportStream::ResetError) &&
144
+ error.is_a?(Quicsilver::Server::WebTransportStream::ResetError) &&
145
+ error.http_error_code == Quicsilver::Protocol::WebTransport::SESSION_GONE
146
+ end
147
+
148
+ # Reads the client's first frame. The handshake is required: the server
149
+ # waits for it before running #connect, so a client that waits for
150
+ # `welcome` first will never get one. A first frame that is not a
151
+ # handshake is still delivered as a cable message rather than eaten.
152
+ def read_handshake
153
+ first = stream.read_message
154
+ return nil unless first
155
+
156
+ payload = JSON.parse(first)
157
+
158
+ if payload.is_a?(Hash) && payload.key?(HANDSHAKE_KEY)
159
+ handshake = payload[HANDSHAKE_KEY]
160
+ store_cookies(handshake["cookies"])
161
+ store_credential(handshake["credential"])
162
+ nil
163
+ else
164
+ first
165
+ end
166
+ rescue JSON::ParserError
167
+ first
168
+ end
169
+
170
+ # Written to the request the connection reads, not only to env. Under
171
+ # Rails, Socket#request is Rails.application.env_config.merge(env) — a
172
+ # copy — and the tagged logger memoizes it when "Started CONNECT" is
173
+ # logged, long before the handshake arrives. A credential written to
174
+ # env alone is invisible to #connect, and every cable is rejected.
175
+ def store_credential(credential)
176
+ request_envs.each { |env| env[Quicsilver::ActionCable::CREDENTIAL_ENV_KEY] = credential }
177
+ end
178
+
179
+ # Restores the cookies the page sent, which WebTransport left off the CONNECT, so the app's
180
+ # own cookie lookup in #connect finds the session. Written where the credential goes, for the
181
+ # same reason, and the memoized cookie jar is dropped too: anything that read cookies before
182
+ # the handshake arrived, such as a log tag, built an empty jar that would otherwise stick.
183
+ #
184
+ # Never replaces cookies the request really carried.
185
+ def store_cookies(token)
186
+ # A signed-out page renders no token: an ordinary anonymous cable.
187
+ return if token.blank?
188
+
189
+ header = Quicsilver::ActionCable.cookie_bridge&.read(token)
190
+ unless header
191
+ Quicsilver.logger.warn "A WebTransport cable sent a cookie token that has expired or was not issued by " \
192
+ "this app, so it connects without cookies. A page reload issues a new one."
193
+ return
194
+ end
195
+
196
+ Quicsilver.logger.debug { "WebTransport cable restored cookies: #{header.split("; ").map { _1.split("=", 2).first }.join(", ")}" }
197
+ request_envs.each do |env|
198
+ next if env["HTTP_COOKIE"].present?
199
+
200
+ env["HTTP_COOKIE"] = header
201
+ env.delete("action_dispatch.cookies")
202
+ end
203
+ end
204
+
205
+ def request_envs
206
+ envs = [ @env ]
207
+ # Private on Rails 8.0 and 8.1, where the event target is the connection itself.
208
+ envs << event_target.send(:request).env if event_target.respond_to?(:request, true)
209
+ envs.uniq(&:object_id)
210
+ end
211
+ end
212
+ end
213
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_cable"
4
+
5
+ # Loads ActionCable::Server::Socket on Rails versions that have it; see .socket_owner.
6
+ begin
7
+ require "action_cable/server/socket"
8
+ rescue LoadError
9
+ end
10
+
11
+ require "quicsilver/action_cable/cookie_bridge"
12
+
13
+ module Quicsilver
14
+ module ActionCable
15
+ # Where the WebTransport socket puts the credential from the client's
16
+ # handshake frame. Read it through .credential rather than by key.
17
+ CREDENTIAL_ENV_KEY = "quicsilver.cable.credential"
18
+
19
+ # The credential the client sent when it opened a WebTransport cable, or
20
+ # nil over a TCP WebSocket. Call from ApplicationCable::Connection#connect,
21
+ # alongside whatever cookie lookup the app already does:
22
+ #
23
+ # def find_session
24
+ # Session.find_signed(cookies.signed[:session_token]) ||
25
+ # Session.find_signed(quicsilver_cable_credential, purpose: :cable)
26
+ # end
27
+ def self.credential(request)
28
+ request.env[CREDENTIAL_ENV_KEY].presence
29
+ end
30
+
31
+ # Included into ActionCable::Connection::Base, so a connection can write
32
+ #
33
+ # Session.find_signed(quicsilver_cable_credential, purpose: :cable)
34
+ module Connection
35
+ private
36
+ def quicsilver_cable_credential
37
+ Quicsilver::ActionCable.credential(request)
38
+ end
39
+ end
40
+
41
+ # Swaps Action Cable's WebSocket wrapper for the WebTransport socket when the request is a
42
+ # WebTransport session. Every other request keeps its WebSocket.
43
+ module SocketSelection
44
+ def initialize(server, env, coder: ActiveSupport::JSON)
45
+ super
46
+
47
+ return unless Quicsilver::WebTransport.from_env(env)
48
+
49
+ @websocket = Quicsilver::ActionCable::Socket.new(env, self, event_loop)
50
+ end
51
+ end
52
+
53
+ module_function
54
+
55
+ # The class that builds a request's socket, in #initialize(server, env, coder:), as
56
+ # `@websocket = WebSocket.new(env, self, event_loop)`. Rails 8.0 and 8.1 do it in the connection;
57
+ # later Rails moved it into ActionCable::Server::Socket. Asked of Rails rather than inferred from
58
+ # its version number, so a release that moves it again fails loudly in the tests.
59
+ def socket_owner
60
+ defined?(::ActionCable::Server::Socket) ? ::ActionCable::Server::Socket : ::ActionCable::Connection::Base
61
+ end
62
+
63
+ # Shared by the page helper, which issues the token, and the socket, which reads it. Built from
64
+ # the Rails app on first use; nil outside one, where there is no secret to encrypt with.
65
+ def cookie_bridge
66
+ @cookie_bridge ||= CookieBridge.from_rails
67
+ end
68
+
69
+ def cookie_bridge=(bridge)
70
+ @cookie_bridge = bridge
71
+ end
72
+
73
+ def install!
74
+ return if @installed
75
+
76
+ ::ActionCable::Connection::Base.include(Connection)
77
+ socket_owner.prepend(SocketSelection)
78
+ @installed = true
79
+ end
80
+ end
81
+ end
82
+
83
+ require "quicsilver/action_cable/socket"
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/engine"
4
+ require "quicsilver/routes"
5
+
6
+ module Quicsilver
7
+ class Engine < ::Rails::Engine
8
+ config.quicsilver = ActiveSupport::OrderedOptions.new
9
+
10
+ # Runs each WebTransport endpoint's long-lived work; swap in another runner (fibers, say) here.
11
+ initializer "quicsilver.webtransport_runner" do
12
+ config.quicsilver.webtransport_runner ||= Quicsilver::WebTransport::ThreadRunner.new
13
+ end
14
+
15
+ initializer "quicsilver.routes" do
16
+ ActionDispatch::Routing::Mapper.include Quicsilver::Routes
17
+ end
18
+
19
+ initializer "quicsilver.assets" do |app|
20
+ app.config.assets.paths << root.join("app/javascript").to_s if app.config.respond_to?(:assets)
21
+ end
22
+
23
+ initializer "quicsilver.importmap", before: "importmap" do |app|
24
+ app.config.importmap.paths << root.join("config/importmap.rb") if app.config.respond_to?(:importmap)
25
+ end
26
+
27
+ initializer "quicsilver.alt_svc" do |app|
28
+ if (options = Quicsilver::Middleware::AltSvc.options_for(app.config.quicsilver.alt_svc))
29
+ app.middleware.insert_before 0, Quicsilver::Middleware::AltSvc, **options
30
+ end
31
+ end
32
+
33
+ initializer "quicsilver.request_protocol" do
34
+ ActiveSupport.on_load(:action_dispatch_request) do
35
+ include Quicsilver::Rails::RequestProtocol
36
+ end
37
+ end
38
+
39
+ initializer "quicsilver.web_transport_certificate_helper" do
40
+ ActiveSupport.on_load(:action_view) do
41
+ include Quicsilver::Rails::WebTransportCertificateHelper
42
+ include Quicsilver::Rails::CableCredentialHelper
43
+ include Quicsilver::Rails::MetaTagsHelper
44
+ end
45
+ end
46
+
47
+ initializer "quicsilver.action_cable", after: "action_cable.set_configs" do
48
+ ActiveSupport.on_load(:action_cable) do
49
+ Quicsilver::ActionCable.install!
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../rails/port"
4
+
5
+ module Quicsilver
6
+ module Middleware
7
+ # Injects Alt-Svc so browsers can discover the HTTP/3 endpoint served by
8
+ # Quicsilver over UDP. Advertises the port the listener binds unless told otherwise.
9
+ class AltSvc
10
+ # The middleware's options for a config.quicsilver.alt_svc setting, or nil to leave it out.
11
+ # Unset, it is on whenever QUICSILVER_PORT names an HTTP/3 listener, so starting one is all it
12
+ # takes for browsers to find it. false turns it off; true or a hash of options turns it on.
13
+ def self.options_for(setting, env: ENV)
14
+ setting = !env["QUICSILVER_PORT"].to_s.empty? if setting.nil?
15
+ return unless setting
16
+
17
+ setting == true ? {} : setting
18
+ end
19
+
20
+ def initialize(app, port: Quicsilver::Rails.port, max_age: 86_400)
21
+ @app = app
22
+ @alt_svc_value = %(h3=":#{port}"; ma=#{max_age})
23
+ end
24
+
25
+ def call(env)
26
+ status, headers, body = @app.call(env)
27
+ headers["alt-svc"] = @alt_svc_value
28
+ [status, headers, body]
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Quicsilver
4
+ module Rails
5
+ # Renders the credential a WebTransport cable sends in its handshake frame.
6
+ #
7
+ # Browsers send no cookies on a WebTransport CONNECT, so the page has to
8
+ # hand the cable something to authenticate with. The app decides what: it
9
+ # should be short-lived and purpose-scoped, so it cannot stand in for the
10
+ # session cookie if it leaks, e.g.
11
+ #
12
+ # <%= quicsilver_cable_credential_meta_tag Current.session&.signed_id(purpose: :cable, expires_in: 1.day) %>
13
+ #
14
+ # Renders nothing for a nil credential, so signed-out pages need no guard, and
15
+ # nothing unless this page arrived over HTTP/3. A page served over TCP gets a
16
+ # WebSocket cable, which authenticates with cookies and needs no credential.
17
+ module CableCredentialHelper
18
+ META_NAME = "quicsilver-cable-credential"
19
+
20
+ def quicsilver_cable_credential_meta_tag(credential)
21
+ if credential.present? && request.http3?
22
+ tag.meta(name: META_NAME, content: credential)
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "base64"
4
+ require "fileutils"
5
+ require "ipaddr"
6
+ require "openssl"
7
+ require "pathname"
8
+ require "securerandom"
9
+
10
+ module Quicsilver
11
+ module Rails
12
+ class DevWebTransportCertificate
13
+ # WebTransport's serverCertificateHashes rejects a certificate valid for more than two weeks
14
+ # (W3C WebTransport, "the total length of the validity period MUST NOT exceed two weeks").
15
+ # A day short of that leaves room for clock skew.
16
+ VALIDITY_SECONDS = 13 * 24 * 60 * 60
17
+ REGENERATE_WITHIN_SECONDS = 24 * 60 * 60
18
+
19
+ # Relative to Rails.root. Puma's SSL bind reads the same files, so the install generator writes
20
+ # these into Procfile.http3.dev rather than its own copy.
21
+ DIRECTORY = "tmp/quicsilver/webtransport"
22
+ CERT_FILE_NAME = "localhost.pem"
23
+ KEY_FILE_NAME = "localhost-key.pem"
24
+
25
+ attr_reader :directory
26
+
27
+ def self.fetch(directory: default_directory)
28
+ new(directory: directory).tap(&:ensure!)
29
+ end
30
+
31
+ def self.default_directory
32
+ ::Rails.root.join(DIRECTORY)
33
+ end
34
+
35
+ def initialize(directory:)
36
+ @directory = Pathname(directory)
37
+ end
38
+
39
+ def cert_file
40
+ directory.join(CERT_FILE_NAME).to_s
41
+ end
42
+
43
+ def key_file
44
+ directory.join(KEY_FILE_NAME).to_s
45
+ end
46
+
47
+ def sha256
48
+ ensure!
49
+ Base64.strict_encode64(OpenSSL::Digest::SHA256.digest(certificate.to_der))
50
+ end
51
+
52
+ # Signed by itself rather than a local CA such as mkcert's: browsers reject it, so the HTTPS page
53
+ # shows a warning and its Alt-Svc is ignored.
54
+ def self_signed?
55
+ certificate.issuer == certificate.subject
56
+ end
57
+
58
+ def ensure!
59
+ return if usable?
60
+
61
+ generate!
62
+ end
63
+
64
+ private
65
+ def usable?
66
+ return false unless File.exist?(cert_file) && File.exist?(key_file)
67
+
68
+ certificate.not_after > Time.now + REGENERATE_WITHIN_SECONDS
69
+ rescue OpenSSL::X509::CertificateError
70
+ false
71
+ end
72
+
73
+ def certificate
74
+ OpenSSL::X509::Certificate.new(File.read(cert_file))
75
+ end
76
+
77
+ DEFAULT_HOSTS = %w[localhost 127.0.0.1 ::1].freeze
78
+
79
+ def generate!
80
+ FileUtils.mkdir_p(directory)
81
+
82
+ key = OpenSSL::PKey::EC.generate("prime256v1")
83
+ root_cert, root_key = mkcert_root
84
+ issuer = root_cert ? root_cert.subject : OpenSSL::X509::Name.parse("/CN=localhost")
85
+ signing_key = root_key || key
86
+
87
+ cert = OpenSSL::X509::Certificate.new
88
+ cert.version = 2
89
+ cert.serial = SecureRandom.random_number(2**64)
90
+ cert.subject = OpenSSL::X509::Name.parse("/CN=localhost")
91
+ cert.issuer = issuer
92
+ cert.public_key = key
93
+ cert.not_before = Time.now - 60
94
+ cert.not_after = Time.now + VALIDITY_SECONDS
95
+
96
+ extensions = OpenSSL::X509::ExtensionFactory.new
97
+ extensions.subject_certificate = cert
98
+ extensions.issuer_certificate = root_cert || cert
99
+ cert.add_extension extensions.create_extension("basicConstraints", "CA:FALSE", true)
100
+ cert.add_extension extensions.create_extension("keyUsage", "digitalSignature", true)
101
+ cert.add_extension extensions.create_extension("extendedKeyUsage", "serverAuth", false)
102
+ cert.add_extension extensions.create_extension("subjectAltName", subject_alt_name, false)
103
+ cert.sign(signing_key, OpenSSL::Digest::SHA256.new)
104
+
105
+ File.write(cert_file, cert.to_pem)
106
+ File.write(key_file, key.to_pem)
107
+ end
108
+
109
+ def subject_alt_name
110
+ dev_hosts.map { |host| ip_address?(host) ? "IP:#{host}" : "DNS:#{host}" }.join(",")
111
+ end
112
+
113
+ def dev_hosts
114
+ ENV.fetch("QUICSILVER_DEV_HOSTS", DEFAULT_HOSTS.join(",")).split(",").map(&:strip).reject(&:empty?)
115
+ end
116
+
117
+ def ip_address?(host)
118
+ IPAddr.new(host)
119
+ true
120
+ rescue IPAddr::InvalidAddressError
121
+ false
122
+ end
123
+
124
+ def mkcert_root
125
+ root = mkcert_caroot
126
+ return [nil, nil] unless root
127
+
128
+ cert_path = File.join(root, "rootCA.pem")
129
+ key_path = File.join(root, "rootCA-key.pem")
130
+ return [nil, nil] unless File.exist?(cert_path) && File.exist?(key_path)
131
+
132
+ [
133
+ OpenSSL::X509::Certificate.new(File.read(cert_path)),
134
+ OpenSSL::PKey.read(File.read(key_path))
135
+ ]
136
+ rescue StandardError => error
137
+ # The fallback is a certificate browsers reject, so say why rather than leave it to be found.
138
+ # Rails' logger rather than Quicsilver's: this runs before Server.start routes the latter.
139
+ ::Rails.logger&.warn "Could not use the mkcert CA at #{root}: #{error.class}: #{error.message}. " \
140
+ "Using a self-signed certificate instead, which browsers reject; run `mkcert -install`."
141
+ [nil, nil]
142
+ end
143
+
144
+ def mkcert_caroot
145
+ return ENV["CAROOT"] if ENV["CAROOT"] && !ENV["CAROOT"].empty?
146
+ return unless system("which mkcert > /dev/null 2>&1")
147
+
148
+ root = `mkcert -CAROOT 2>/dev/null`.strip
149
+ root unless root.empty?
150
+ rescue StandardError
151
+ nil
152
+ end
153
+ end
154
+ end
155
+ end