cybertrain 0.2.0 → 0.3.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.
@@ -0,0 +1,1528 @@
1
+ # `cybertrain generate authentication`: email-and-password sign-in, the way
2
+ # Rails 8's `bin/rails generate authentication` writes it, as code the
3
+ # application owns (docs/design.md D15):
4
+ #
5
+ # db/migrate/*_create_users.rb, *_create_sessions.rb
6
+ # app/models/user.rb, app/models/session.rb
7
+ # app/controllers/sessions_controller.rb, registrations_controller.rb
8
+ # app/views/sessions/new.html.erb, _nav.html.erb, registrations/new.html.erb
9
+ # test/authentication.rb, test/support/app_test.rb
10
+ #
11
+ # and three edits: `before_action`s and the sign-in helpers into
12
+ # app/controllers/application_controller.rb, the routes into
13
+ # config/routes.rb and the nav partial into the layout (plus a sign-in in
14
+ # any test/attachment_*.rb written before it, which now needs one). Every
15
+ # file is written once (Templates.write never overwrites) and every edit is
16
+ # made once, so running the generator again is harmless.
17
+ #
18
+ # Sign-in attempts are rate limited as in Rails' generator (`rate_limit to:
19
+ # 10, within: 3 * 60, only: [:create]`, per client address, per process;
20
+ # docs/design.md D26), and AppTest.sign_in resets the counts so a test
21
+ # suite never reaches the limit.
22
+ #
23
+ # What it leaves out, and why: password reset (needs a mailer, which
24
+ # cybertrain does not have) and a `Current` object (templates read `@current_user` instead, an ivar
25
+ # `resume_session` sets on every controller). What it adds that Rails'
26
+ # does not: a sign-up page, because there is no console to create the first
27
+ # user in (Spinel has no `eval`).
28
+ #
29
+ # `--invite-only` (docs/design.md D29) writes no sign-up page. Instead:
30
+ #
31
+ # app/commands/user_command.rb `./<app> user EMAIL [PASSWORD]`, a
32
+ # Main.command that creates a user or sets
33
+ # its password (from stdin when not given),
34
+ # and the boot warning while no user exists
35
+ # app/controllers/setup_controller.rb, app/views/setup/new.html.erb
36
+ # /setup, the first user's form: only while
37
+ # no user exists, only with the one-time
38
+ # token the boot warning prints, only from
39
+ # loopback unless <APP>_SETUP_OPEN=1
40
+ #
41
+ # plus two more edits: the require and the warning into bin/<app>.rb
42
+ # (before `exit(Cybertrain::Main.run(`), and the `setup_open` setting into
43
+ # config/app.rb's configure block.
44
+ require "cybertrain/cli/templates"
45
+ require "cybertrain/cli/scaffold"
46
+ require "cybertrain/cli/build"
47
+
48
+ module Cybertrain
49
+ module CLI
50
+ module Authentication
51
+ CLASS_LINE = "class ApplicationController < Cybertrain::Controller"
52
+ ROUTE_MARK = "resource :session"
53
+ NAV_LINE = "<%= render \"sessions/nav\" %>"
54
+ # What an app test's new_client needs once the app has authentication:
55
+ # empty the two tables, then a user signed in through the form.
56
+ # `generate attachment` writes them into its test when app/models/user.rb
57
+ # exists; add_sign_in_to_attachment_tests adds them to a test written
58
+ # before this generator ran.
59
+ TEST_RESET_LINES = " Session.all.delete_all\n User.all.delete_all\n"
60
+ TEST_SIGN_IN_LINES = " AppTest.user\n AppTest.sign_in(client)\n"
61
+ NEW_CLIENT_LINE = "def new_client"
62
+ TEST_CLIENT_LINE = " client = Cybertrain::Test::Client.new(APP)"
63
+ # --invite-only's two edits: bin/<app>.rb gets the command file and the
64
+ # boot warning before this line, config/app.rb the setting after this one.
65
+ MAIN_RUN_LINE = "exit(Cybertrain::Main.run("
66
+ CONFIGURE_LINE = "Cybertrain.configure do |c|"
67
+ COMMAND_REQUIRE = "require_relative \"../app/commands/user_command\""
68
+
69
+ # Returns the paths it created. Raises InvalidArgument, before anything
70
+ # is written, when `root` is not an application (no config/routes.rb
71
+ # with the draw line, no app/controllers/application_controller.rb
72
+ # with the class line; with `invite_only`, no bin/<app>.rb with the
73
+ # Main.run line or no config/app.rb with the configure line).
74
+ def self.generate(root, invite_only = false)
75
+ routes_path = File.join(root, "config/routes.rb")
76
+ raise InvalidArgument, "#{routes_path} not found: run this inside a cybertrain app" unless File.exist?(routes_path)
77
+ raise InvalidArgument, "#{routes_path} has no `#{Scaffold::DRAW_LINE}` line" if File.read(routes_path).index(Scaffold::DRAW_LINE).nil?
78
+
79
+ controller_path = File.join(root, "app/controllers/application_controller.rb")
80
+ raise InvalidArgument, "#{controller_path} not found: run this inside a cybertrain app" unless File.exist?(controller_path)
81
+ raise InvalidArgument, "#{controller_path} has no `#{CLASS_LINE}` line" if File.read(controller_path).index(CLASS_LINE).nil?
82
+
83
+ app = ""
84
+ if invite_only
85
+ app = Build.app_name(root)
86
+ raise InvalidArgument, "#{root}/spin.toml has no [package] name: run this inside a cybertrain app" if app == ""
87
+
88
+ bin_path = File.join(root, "bin/#{app}.rb")
89
+ raise InvalidArgument, "#{bin_path} not found: run this inside a cybertrain app" unless File.exist?(bin_path)
90
+ raise InvalidArgument, "#{bin_path} has no line starting with `#{MAIN_RUN_LINE}`" if line_start(File.read(bin_path), MAIN_RUN_LINE) < 0
91
+
92
+ config_path = File.join(root, "config/app.rb")
93
+ raise InvalidArgument, "#{config_path} not found: run this inside a cybertrain app" unless File.exist?(config_path)
94
+ raise InvalidArgument, "#{config_path} has no `#{CONFIGURE_LINE}` line" if File.read(config_path).index(CONFIGURE_LINE).nil?
95
+ end
96
+
97
+ created = Array.new(0) { "" }
98
+ users = migration_path(root, "users")
99
+ record(created, root, users, users_migration)
100
+ record(created, root, migration_path(root, "sessions"), sessions_migration)
101
+ record(created, root, "app/models/user.rb", user_model)
102
+ record(created, root, "app/models/session.rb", session_model)
103
+ record(created, root, "app/controllers/sessions_controller.rb", sessions_controller)
104
+ if invite_only
105
+ record(created, root, "app/controllers/setup_controller.rb", setup_controller(app))
106
+ record(created, root, "app/commands/user_command.rb", user_command(app))
107
+ else
108
+ record(created, root, "app/controllers/registrations_controller.rb", registrations_controller)
109
+ end
110
+ record(created, root, "app/views/sessions/new.html.erb", sessions_new_view(invite_only))
111
+ record(created, root, "app/views/sessions/_nav.html.erb", nav_partial)
112
+ if invite_only
113
+ record(created, root, "app/views/setup/new.html.erb", setup_new_view)
114
+ else
115
+ record(created, root, "app/views/registrations/new.html.erb", registrations_new_view)
116
+ end
117
+ record(created, root, "test/support/app_test.rb", app_test_support)
118
+ record(created, root, "test/authentication.rb", invite_only ? invite_only_test(app) : authentication_test)
119
+ add_to_application_controller(controller_path)
120
+ add_routes(routes_path, invite_only)
121
+ add_nav_to_layout(File.join(root, "app/views/layouts/application.html.erb"))
122
+ add_sign_in_to_attachment_tests(root)
123
+ if invite_only
124
+ add_command_to_bin(File.join(root, "bin/#{app}.rb"), app)
125
+ add_setting_to_config(File.join(root, "config/app.rb"), app)
126
+ end
127
+ created
128
+ end
129
+
130
+ def self.record(created, root, path, content)
131
+ created << path if Templates.write(root, path, content) == "create"
132
+ nil
133
+ end
134
+
135
+ # db/migrate/<version>_create_<table>.rb, or the existing one; the
136
+ # second table's version follows the first's (Scaffold.next_version).
137
+ def self.migration_path(root, table)
138
+ suffix = "_create_#{table}.rb"
139
+ existing = Dir.glob(File.join(root, "db/migrate/*#{suffix}")).sort
140
+ return "db/migrate/#{File.basename(existing[0])}" unless existing.empty?
141
+
142
+ "db/migrate/#{Scaffold.next_version(root, Scaffold.timestamp)}#{suffix}"
143
+ end
144
+
145
+ # Inserts the authentication block right after the class line, once
146
+ # (the block's own `def require_authentication` marks a file that has
147
+ # it). Returns true when the file was changed.
148
+ def self.add_to_application_controller(path)
149
+ source = File.read(path)
150
+ unless source.index("def require_authentication").nil?
151
+ puts "identical app/controllers/application_controller.rb (authentication already added)"
152
+ return false
153
+ end
154
+
155
+ File.write(path, insert_after_line(source, CLASS_LINE, indent(application_controller_block)))
156
+ puts "insert app/controllers/application_controller.rb (authentication)"
157
+ true
158
+ end
159
+
160
+ # Inserts the sign-in and sign-up (or setup) routes after the draw
161
+ # line, once.
162
+ def self.add_routes(path, invite_only = false)
163
+ source = File.read(path)
164
+ unless source.index(ROUTE_MARK).nil?
165
+ puts "identical route #{ROUTE_MARK}"
166
+ return false
167
+ end
168
+
169
+ File.write(path, insert_after_line(source, Scaffold::DRAW_LINE, indent(routes_block(invite_only))))
170
+ puts "route #{ROUTE_MARK}, get/post #{invite_only ? "/setup" : "/sign_up"}"
171
+ true
172
+ end
173
+
174
+ # --invite-only: requires app/commands/user_command.rb (which registers
175
+ # the `user` command) and runs its boot warning, just before the
176
+ # Main.run line of bin/<app>.rb, once.
177
+ def self.add_command_to_bin(path, app)
178
+ name = "bin/#{app}.rb"
179
+ source = File.read(path)
180
+ unless source.index(COMMAND_REQUIRE).nil?
181
+ puts "identical #{name} (user command already required)"
182
+ return false
183
+ end
184
+
185
+ File.write(path, insert_before_line(source, MAIN_RUN_LINE, bin_block(app)))
186
+ puts "insert #{name} (./#{app} user, the first-run warning)"
187
+ true
188
+ end
189
+
190
+ # --invite-only: declares the setup_open setting at the top of
191
+ # config/app.rb's configure block, once.
192
+ def self.add_setting_to_config(path, app)
193
+ source = File.read(path)
194
+ unless source.index("setting_bool :setup_open").nil?
195
+ puts "identical config/app.rb (setup_open already declared)"
196
+ return false
197
+ end
198
+
199
+ File.write(path, insert_after_line(source, CONFIGURE_LINE, indent(config_block(app))))
200
+ env = setup_env(app)
201
+ puts "insert config/app.rb (#{env})"
202
+ true
203
+ end
204
+
205
+ # The environment variable that opens /setup to any address:
206
+ # SHOP_SETUP_OPEN for the app shop.
207
+ def self.setup_env(app)
208
+ "#{app.upcase}_SETUP_OPEN"
209
+ end
210
+
211
+ # Renders the nav partial at the top of <main> in the layout, once;
212
+ # a layout without a `<main>` line is left alone with a note.
213
+ def self.add_nav_to_layout(path)
214
+ unless File.exist?(path)
215
+ puts "skip app/views/layouts/application.html.erb (not found): render \"sessions/nav\" in your layout"
216
+ return false
217
+ end
218
+
219
+ source = File.read(path)
220
+ unless source.index("sessions/nav").nil?
221
+ puts "identical app/views/layouts/application.html.erb (nav already rendered)"
222
+ return false
223
+ end
224
+ at = source.index("<main>")
225
+ if at.nil?
226
+ puts "skip app/views/layouts/application.html.erb (no <main>): add #{NAV_LINE} to your layout"
227
+ return false
228
+ end
229
+
230
+ File.write(path, insert_after_line(source, "<main>", " #{NAV_LINE}\n"))
231
+ puts "insert app/views/layouts/application.html.erb (#{NAV_LINE})"
232
+ true
233
+ end
234
+
235
+ # A test/attachment_*.rb written by `generate attachment` before this
236
+ # generator ran drives the forms anonymously, which every action now
237
+ # redirects to the sign-in page. Its new_client gets the reset and
238
+ # sign-in lines, once (AppTest.sign_in marks a test that has them); a
239
+ # new_client rewritten past recognition is left alone with a note.
240
+ def self.add_sign_in_to_attachment_tests(root)
241
+ Dir.glob(File.join(root, "test/attachment_*.rb")).sort.each do |path|
242
+ name = "test/#{File.basename(path)}"
243
+ source = File.read(path)
244
+ unless source.index("AppTest.sign_in(").nil?
245
+ puts "identical #{name} (signs in already)"
246
+ next
247
+ end
248
+ if source.index(NEW_CLIENT_LINE).nil? || source.index(TEST_CLIENT_LINE).nil?
249
+ puts "skip #{name} (no new_client): sign in there with AppTest.user and AppTest.sign_in(client)"
250
+ next
251
+ end
252
+
253
+ source = insert_after_line(source, NEW_CLIENT_LINE, TEST_RESET_LINES)
254
+ File.write(path, insert_after_line(source, TEST_CLIENT_LINE, TEST_SIGN_IN_LINES))
255
+ puts "insert #{name} (sign in first)"
256
+ end
257
+ nil
258
+ end
259
+
260
+ # `text` with two spaces in front of every non-blank line: the heredocs
261
+ # below are written flush (`<<~` strips their indentation), and what
262
+ # goes inside a class body or a draw block is indented here.
263
+ def self.indent(text)
264
+ out = +""
265
+ text.each_line { |line| out << (line == "\n" ? line : " #{line}") }
266
+ out
267
+ end
268
+
269
+ # `source` with `block` (its own lines, each ending in a newline)
270
+ # inserted right after the first line containing `marker`.
271
+ def self.insert_after_line(source, marker, block)
272
+ at = source.index(marker)
273
+ raise InvalidArgument, "no `#{marker}` line to insert after" if at.nil?
274
+
275
+ eol = source.index("\n", at)
276
+ eol = source.size if eol.nil?
277
+ updated = +""
278
+ updated << source[0, eol] << "\n"
279
+ updated << block
280
+ rest = source[eol + 1, source.size - eol - 1].to_s
281
+ updated << rest
282
+ updated << "\n" unless updated.end_with?("\n")
283
+ updated
284
+ end
285
+
286
+ # Where the first line that starts with `marker` starts, or -1.
287
+ def self.line_start(source, marker)
288
+ return 0 if source.start_with?(marker)
289
+
290
+ found = source.index("\n#{marker}")
291
+ found.nil? ? -1 : found + 1
292
+ end
293
+
294
+ # `source` with `block` inserted right before the first line that
295
+ # starts with `marker`.
296
+ def self.insert_before_line(source, marker, block)
297
+ start = line_start(source, marker)
298
+ raise InvalidArgument, "no line starting with `#{marker}` to insert before" if start < 0
299
+
300
+ updated = +""
301
+ updated << source[0, start].to_s
302
+ updated << block
303
+ updated << source[start, source.size - start].to_s
304
+ updated
305
+ end
306
+
307
+ # ---- the files ----------------------------------------------------
308
+
309
+ def self.users_migration
310
+ <<~RUBY
311
+ class CreateUsers < Cybertrain::Migration::Base
312
+ def change
313
+ create_table "users" do |t|
314
+ t.string "email_address", null: false
315
+ t.string "password_digest", null: false
316
+ t.timestamps
317
+ end
318
+ add_index "users", ["email_address"], unique: true
319
+ end
320
+ end
321
+ RUBY
322
+ end
323
+
324
+ def self.sessions_migration
325
+ <<~RUBY
326
+ class CreateSessions < Cybertrain::Migration::Base
327
+ def change
328
+ create_table "sessions" do |t|
329
+ t.references :user
330
+ t.string "ip_address"
331
+ t.string "user_agent"
332
+ t.timestamps
333
+ end
334
+ end
335
+ end
336
+ RUBY
337
+ end
338
+
339
+ def self.user_model
340
+ <<~RUBY
341
+ # Columns (email_address, password_digest), the Cybertrain::Model
342
+ # superclass and `sessions` (from the sessions table's foreign key) come
343
+ # from gen/models/user.rb, generated from db/schema.rb by `spin run gen`.
344
+ #
345
+ # Written by `cybertrain generate authentication`; it is yours to change.
346
+ # The password is hashed by Cybertrain::Password (PBKDF2-HMAC-SHA256) into
347
+ # password_digest; the plain text lives only in @password until the
348
+ # record is saved. `password=` and `authenticate` are what Rails'
349
+ # `has_secure_password` would define (Spinel cannot define methods at
350
+ # run time, so they are written out).
351
+ class User
352
+ MIN_PASSWORD_LENGTH = 8
353
+
354
+ validates :email_address, presence: true
355
+
356
+ # Normalizes the address, refuses a taken one, and checks the password
357
+ # on a new record or whenever one was given. Errors added here make
358
+ # the record invalid (Cybertrain::Model.before_validation).
359
+ before_validation do |user|
360
+ user.email_address = User.normalize_email_address(user.email_address)
361
+ user.validate_email_address_taken
362
+ user.validate_password
363
+ end
364
+
365
+ # The address lowercased and trimmed: " Ann@Example.COM " is
366
+ # "ann@example.com", so a visitor signs in however they type it.
367
+ def self.normalize_email_address(value)
368
+ value.to_s.strip.downcase
369
+ end
370
+
371
+ # The user with this address and password, or nil. A missing address
372
+ # costs a verification too (against Cybertrain::Password.dummy_digest),
373
+ # so the response time does not say which of the two was wrong.
374
+ def self.authenticate_by(email_address:, password:)
375
+ user = User.find_by(email_address: User.normalize_email_address(email_address))
376
+ if user.nil?
377
+ Cybertrain::Password.verify_serialized(password.to_s, Cybertrain::Password.dummy_digest)
378
+ return nil
379
+ end
380
+ user.authenticate(password) ? user : nil
381
+ end
382
+
383
+ # The plain-text password given to `password=` in this request ("" when
384
+ # none was), for the validations; never stored.
385
+ def password
386
+ plain = @password
387
+ plain.nil? ? "" : plain
388
+ end
389
+
390
+ # Hashes the password into password_digest. A blank password clears
391
+ # the digest, which `validate_password` reports.
392
+ def password=(plain)
393
+ text = plain.to_s
394
+ @password = text
395
+ self.password_digest = text.empty? ? "" : Cybertrain::Password.hash(text)
396
+ end
397
+
398
+ # What the sign-up form sends back a second time; nil until set, so a
399
+ # form without the field is not asked to match.
400
+ def password_confirmation
401
+ @password_confirmation
402
+ end
403
+
404
+ def password_confirmation=(plain)
405
+ @password_confirmation = plain.to_s
406
+ end
407
+
408
+ # Whether `plain` is this user's password. A digest hashed with fewer
409
+ # iterations than Cybertrain::Password.iterations is rehashed and
410
+ # saved on the way, so raising the cost in config/app.rb upgrades
411
+ # everyone as they sign in (and, the digest being new, signs their
412
+ # other browsers out once). verify_serialized runs one verification
413
+ # at a time, so a burst of sign-ins does not hold every worker.
414
+ def authenticate(plain)
415
+ return false unless Cybertrain::Password.verify_serialized(plain.to_s, password_digest)
416
+
417
+ if Cybertrain::Password.needs_rehash?(password_digest)
418
+ self.password_digest = Cybertrain::Password.hash(plain.to_s)
419
+ save
420
+ end
421
+ true
422
+ end
423
+
424
+ # Public so the before_validation block above (which receives the
425
+ # record, not an implicit self) can call them.
426
+
427
+ def validate_email_address_taken
428
+ address = email_address
429
+ return nil if address.nil? || address.empty?
430
+
431
+ taken = User.where(email_address: address).where_sql("id != ?", [id]).exists?
432
+ errors.add(:email_address, "has already been taken") if taken
433
+ nil
434
+ end
435
+
436
+ def validate_password
437
+ given = password
438
+ if password_digest.to_s.empty?
439
+ errors.add(:password, "can't be blank")
440
+ elsif !given.empty? && given.size < MIN_PASSWORD_LENGTH
441
+ errors.add(:password, "is too short (minimum is \#{MIN_PASSWORD_LENGTH} characters)")
442
+ end
443
+ confirmation = @password_confirmation
444
+ errors.add(:password_confirmation, "doesn't match Password") if !confirmation.nil? && confirmation != given
445
+ nil
446
+ end
447
+ end
448
+ RUBY
449
+ end
450
+
451
+ def self.session_model
452
+ <<~RUBY
453
+ # One signed-in browser: a row the cookie session points at by id
454
+ # (ApplicationController#resume_session), with the address and user
455
+ # agent that created it, so a user can be signed out everywhere by
456
+ # deleting their rows. Columns, the Cybertrain::Model superclass and
457
+ # `user` (from the user_id foreign key) come from gen/models/session.rb.
458
+ #
459
+ # Not to be confused with Cybertrain::Session, the signed cookie that
460
+ # holds this row's id as `session[:session_id]`.
461
+ class Session
462
+ end
463
+ RUBY
464
+ end
465
+
466
+ # Inserted (indented) after the class line of
467
+ # app/controllers/application_controller.rb.
468
+ def self.application_controller_block
469
+ <<~RUBY
470
+ # ---- Authentication (cybertrain generate authentication) -------------
471
+ # Every action needs a signed-in user unless its controller opens it:
472
+ # `allow_unauthenticated_access only: [:new, :create]`. resume_session
473
+ # sets @current_user (and @current_session), which templates can read.
474
+ before_action :resume_session
475
+ before_action :require_authentication
476
+
477
+ def self.allow_unauthenticated_access(only: [], except: [])
478
+ skip_before_action(:require_authentication, only: only, except: except)
479
+ end
480
+
481
+ # @return [Boolean] whether this request has a signed-in user
482
+ def authenticated?
483
+ !@current_user.nil?
484
+ end
485
+
486
+ # Loads the Session row the cookie names (and its user); a stale or
487
+ # expired id is dropped. Cookie Max-Age alone cannot stop replay:
488
+ # authentication expires session_absolute_max_age seconds after
489
+ # sign-in (SessionStore enforces the same on the cookie). A cookie
490
+ # whose password key no longer matches (the password changed since
491
+ # it signed in) ends its Session row.
492
+ def resume_session
493
+ @current_session = nil
494
+ @current_user = nil
495
+ id = session[:session_id]
496
+ return nil if id.nil? || id.empty? || id.size > 18
497
+
498
+ found = Session.find_by(id: id.to_i)
499
+ if found.nil?
500
+ session.delete(:session_id)
501
+ return nil
502
+ end
503
+ created_at = found.created_at
504
+ lifetime = Cybertrain.config.session_absolute_max_age
505
+ if created_at.nil? || (lifetime > 0 && created_at.to_i + lifetime <= Time.now.to_i)
506
+ session.delete(:session_id)
507
+ return nil
508
+ end
509
+ user = found.user
510
+ if user.nil? || !Cybertrain::Password.session_key_matches?(session[:password_key], user.password_digest)
511
+ found.destroy
512
+ session.delete(:session_id)
513
+ return nil
514
+ end
515
+ @current_session = found
516
+ @current_user = user
517
+ nil
518
+ end
519
+
520
+ # Sends a visitor to the sign-in page, remembering a GET to come back to.
521
+ def require_authentication
522
+ return nil if authenticated?
523
+
524
+ session[:return_to_after_authenticating] = request.path if request.method == "GET"
525
+ redirect_to new_session_path, status: :see_other
526
+ nil
527
+ end
528
+
529
+ # Also stores the password key resume_session compares, and restarts
530
+ # the cookie's absolute lifetime. After a password change, call
531
+ # `session[:password_key] = Cybertrain::Password.session_key(user.password_digest)`
532
+ # to keep the browser that changed it signed in.
533
+ def start_new_session_for(user)
534
+ started = Session.create(user_id: user.id, ip_address: request.client_ip,
535
+ user_agent: request.header("user-agent").to_s)
536
+ session.restart_lifetime!
537
+ session[:session_id] = started.id
538
+ session[:password_key] = Cybertrain::Password.session_key(user.password_digest)
539
+ @current_session = started
540
+ @current_user = user
541
+ nil
542
+ end
543
+
544
+ # Deletes the Session row and empties the cookie session (the CSRF
545
+ # token with it, so forms rendered before no longer submit).
546
+ def terminate_session
547
+ current = @current_session
548
+ current.destroy unless current.nil?
549
+ session.clear
550
+ @current_session = nil
551
+ @current_user = nil
552
+ nil
553
+ end
554
+
555
+ # Where to go after signing in: the page that asked for it, if it is a
556
+ # local path (Cybertrain::Controller#safe_redirect_path), or /.
557
+ def after_authentication_url
558
+ safe_redirect_path(session.delete(:return_to_after_authenticating), "/")
559
+ end
560
+ # ---- end of authentication ------------------------------------------
561
+
562
+ RUBY
563
+ end
564
+
565
+ def self.sessions_controller
566
+ <<~RUBY
567
+ # Sign in and out (cybertrain generate authentication).
568
+ class SessionsController < ApplicationController
569
+ allow_unauthenticated_access only: [:new, :create]
570
+ # Ten sign-in attempts per client address every three minutes, then
571
+ # back to the form until the window closes. Behind a reverse proxy on
572
+ # this host, set CYBERTRAIN_TRUSTED_PROXY=1 so that each visitor is
573
+ # counted rather than the proxy (README, "Rate limiting").
574
+ rate_limit to: 10, within: 3 * 60, only: [:create],
575
+ redirect_to: "/session/new", alert: "Try again later."
576
+
577
+ # GET /session/new
578
+ # (named new_action: a `new` method would shadow SessionsController.new)
579
+ def new_action
580
+ end
581
+
582
+ # POST /session
583
+ def create
584
+ user = User.authenticate_by(email_address: params[:email_address].to_s, password: params[:password].to_s)
585
+ if user.nil?
586
+ flash[:alert] = "Try another email address or password."
587
+ redirect_to new_session_path, status: :see_other
588
+ else
589
+ start_new_session_for(user)
590
+ redirect_to after_authentication_url, status: :see_other
591
+ end
592
+ end
593
+
594
+ # DELETE /session
595
+ def destroy
596
+ terminate_session
597
+ flash[:notice] = "You have been signed out."
598
+ redirect_to new_session_path, status: :see_other
599
+ end
600
+ end
601
+ RUBY
602
+ end
603
+
604
+ def self.registrations_controller
605
+ <<~RUBY
606
+ # Sign up (cybertrain generate authentication). Rails' generator has no
607
+ # sign-up page and expects the first user to be created in the console;
608
+ # cybertrain has no console, so this is how the first user gets in.
609
+ # Delete it (and its routes) for an invitation-only application.
610
+ class RegistrationsController < ApplicationController
611
+ allow_unauthenticated_access only: [:new, :create]
612
+
613
+ # GET /sign_up
614
+ def new_action
615
+ @user = User.new
616
+ end
617
+
618
+ # POST /sign_up
619
+ def create
620
+ fields = params.require(:user)
621
+ @user = User.new(fields.permit(:email_address))
622
+ @user.password = fields[:password].to_s
623
+ @user.password_confirmation = fields[:password_confirmation].to_s
624
+ if @user.save
625
+ start_new_session_for(@user)
626
+ flash[:notice] = "Welcome! You have signed up."
627
+ redirect_to after_authentication_url, status: :see_other
628
+ else
629
+ render :new, status: :unprocessable_entity
630
+ end
631
+ end
632
+ end
633
+ RUBY
634
+ end
635
+
636
+ # With --invite-only there is no sign-up page to link to.
637
+ def self.sessions_new_view(invite_only = false)
638
+ view = <<~ERB
639
+ <h1>Sign in</h1>
640
+
641
+ <%= form_with(url: session_path) do |f| %>
642
+ <div class="field">
643
+ <%= f.label :email_address %>
644
+ <%= f.email_field :email_address, autocomplete: "username", autofocus: true %>
645
+ </div>
646
+
647
+ <div class="field">
648
+ <%= f.label :password %>
649
+ <%= f.password_field :password, autocomplete: "current-password" %>
650
+ </div>
651
+
652
+ <div class="actions">
653
+ <%= f.submit "Sign in" %>
654
+ </div>
655
+ <% end %>
656
+ ERB
657
+ return view if invite_only
658
+
659
+ "#{view}\n<p><%= link_to \"Sign up\", sign_up_path %></p>\n"
660
+ end
661
+
662
+ def self.nav_partial
663
+ <<~ERB
664
+ <%# locals: () %>
665
+ <nav class="session">
666
+ <% if @current_user %>
667
+ <span><%= @current_user.email_address %></span>
668
+ <%= button_to "Sign out", session_path, method: :delete %>
669
+ <% else %>
670
+ <%= link_to "Sign in", new_session_path %>
671
+ <% end %>
672
+ </nav>
673
+ ERB
674
+ end
675
+
676
+ def self.registrations_new_view
677
+ <<~ERB
678
+ <h1>Sign up</h1>
679
+
680
+ <%= form_with(model: @user, url: sign_up_path) do |f| %>
681
+ <% if @user.errors.any? %>
682
+ <div id="error_explanation">
683
+ <h2><%= pluralize(@user.errors.count, "error") %> prohibited this account from being created:</h2>
684
+ <ul>
685
+ <% @user.errors.full_messages.each do |message| %>
686
+ <li><%= message %></li>
687
+ <% end %>
688
+ </ul>
689
+ </div>
690
+ <% end %>
691
+
692
+ <div class="field">
693
+ <%= f.label :email_address %>
694
+ <%= f.email_field :email_address, autocomplete: "username" %>
695
+ </div>
696
+
697
+ <div class="field">
698
+ <%= f.label :password %>
699
+ <%= f.password_field :password, autocomplete: "new-password" %>
700
+ </div>
701
+
702
+ <div class="field">
703
+ <%= f.label :password_confirmation %>
704
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
705
+ </div>
706
+
707
+ <div class="actions">
708
+ <%= f.submit "Sign up" %>
709
+ </div>
710
+ <% end %>
711
+
712
+ <p><%= link_to "Sign in", new_session_path %></p>
713
+ ERB
714
+ end
715
+
716
+ # ---- --invite-only ------------------------------------------------
717
+
718
+ # The first user's page (--invite-only).
719
+ def self.setup_controller(app)
720
+ env = setup_env(app)
721
+ <<~RUBY
722
+ # First-run setup (cybertrain generate authentication --invite-only):
723
+ # the form that creates the first user and signs them in. It answers
724
+ # only while no user exists, only with the one-time token the server
725
+ # prints at boot (/setup?token=..., carried back by the form in a
726
+ # hidden field), and only to a connection from this machine
727
+ # (request.loopback?, the socket's peer address) that did not come
728
+ # through a proxy (no X-Forwarded-For header). #{env}=1
729
+ # (config/app.rb) lifts the address check (never the token) while no
730
+ # user exists, for a first run behind a proxy on another host; unset
731
+ # it again afterwards. Anyone else gets a 404, as if there were no
732
+ # such page. Later users are created with `./#{app} user EMAIL`
733
+ # (app/commands/user_command.rb).
734
+ class SetupController < ApplicationController
735
+ allow_unauthenticated_access only: [:new, :create]
736
+ before_action :require_first_run
737
+
738
+ # The one-time token: 32 random hex characters, made when the
739
+ # program starts and the same until it exits (a restart makes a new
740
+ # one). The address check alone is not enough: a proxy on this host
741
+ # that adds no X-Forwarded-For makes every client a loopback one.
742
+ # Printed only by the boot [WARN] (UserCommand.warn_if_no_user) and
743
+ # rendered only into the form's hidden field. A constant, which
744
+ # Spinel keeps alive (a class variable it would not).
745
+ SETUP_TOKEN = Cybertrain::Crypto.random_token(16)
746
+
747
+ # The token /setup asks for: the boot warning prints it, the app's
748
+ # test passes it.
749
+ def self.setup_token
750
+ SETUP_TOKEN
751
+ end
752
+
753
+ # GET /setup
754
+ def new_action
755
+ @user = User.new
756
+ end
757
+
758
+ # POST /setup
759
+ def create
760
+ fields = params.require(:user)
761
+ @user = User.new(fields.permit(:email_address))
762
+ @user.password = fields[:password].to_s
763
+ @user.password_confirmation = fields[:password_confirmation].to_s
764
+ # The no-user check and the insert are one write transaction
765
+ # (BEGIN IMMEDIATE takes the lock first), so two requests that
766
+ # both passed require_first_run cannot both create "the first"
767
+ # account: the second finds a user and saves nothing.
768
+ saved = false
769
+ User.transaction(immediate: true) do |c|
770
+ saved = @user.save unless User.all.exists?
771
+ end
772
+ if saved
773
+ start_new_session_for(@user)
774
+ flash[:notice] = "Welcome! Your account has been created."
775
+ redirect_to "/", status: :see_other
776
+ else
777
+ render :new, status: :unprocessable_entity
778
+ end
779
+ end
780
+
781
+ private
782
+
783
+ # A missing or wrong token is the same 404 as the other refusals;
784
+ # the comparison takes as long however much of it matched.
785
+ def require_first_run
786
+ @setup_token = params[:token].to_s
787
+ head :not_found unless setup_open? && Cybertrain::Crypto.secure_compare(@setup_token, SetupController.setup_token)
788
+ nil
789
+ end
790
+
791
+ # A header never opens the page; it can only close it: behind a proxy
792
+ # on this host every request is a loopback one, and the proxy adds
793
+ # X-Forwarded-For.
794
+ def setup_open?
795
+ return false if User.all.exists?
796
+ return true if Cybertrain.config.bool_setting(:setup_open)
797
+
798
+ request.loopback? && request.header("x-forwarded-for").nil?
799
+ end
800
+ end
801
+ RUBY
802
+ end
803
+
804
+ def self.setup_new_view
805
+ <<~ERB
806
+ <h1>Set up</h1>
807
+
808
+ <p>Create the first account. This page is only shown on this machine,
809
+ with the link the server printed when it started, and only until an
810
+ account exists.</p>
811
+
812
+ <%= form_with(model: @user, url: setup_path) do |f| %>
813
+ <input type="hidden" name="token" value="<%= @setup_token %>">
814
+
815
+ <% if @user.errors.any? %>
816
+ <div id="error_explanation">
817
+ <h2><%= pluralize(@user.errors.count, "error") %> prohibited this account from being created:</h2>
818
+ <ul>
819
+ <% @user.errors.full_messages.each do |message| %>
820
+ <li><%= message %></li>
821
+ <% end %>
822
+ </ul>
823
+ </div>
824
+ <% end %>
825
+
826
+ <div class="field">
827
+ <%= f.label :email_address %>
828
+ <%= f.email_field :email_address, autocomplete: "username", autofocus: true %>
829
+ </div>
830
+
831
+ <div class="field">
832
+ <%= f.label :password %>
833
+ <%= f.password_field :password, autocomplete: "new-password" %>
834
+ </div>
835
+
836
+ <div class="field">
837
+ <%= f.label :password_confirmation %>
838
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
839
+ </div>
840
+
841
+ <div class="actions">
842
+ <%= f.submit "Create account" %>
843
+ </div>
844
+ <% end %>
845
+ ERB
846
+ end
847
+
848
+ # app/commands/user_command.rb (--invite-only): the `user` command and
849
+ # the boot warning, required from bin/<app>.rb (and from the app's
850
+ # test, which runs the command through Main.run).
851
+ def self.user_command(app)
852
+ <<~RUBY
853
+ # `./#{app} user EMAIL [PASSWORD]` (cybertrain generate authentication
854
+ # --invite-only): creates the user with this address, or sets the
855
+ # password of the one that has it (which signs that user's browsers
856
+ # out: their sessions' password key no longer matches). Without
857
+ # PASSWORD it is read from standard input, one line, so that it stays
858
+ # out of `ps` and the shell history:
859
+ #
860
+ # ./#{app} user ann@example.com # type it, then Enter (it is echoed)
861
+ # printf '%s' "$PASSWORD" | ./#{app} user ann@example.com
862
+ #
863
+ # Registered with Cybertrain::Main.command, which connects the database
864
+ # first (README, "Application commands"). Required by bin/#{app}.rb,
865
+ # which also calls UserCommand.warn_if_no_user before serving.
866
+ # Written by the generator; it is yours to change.
867
+ module UserCommand
868
+ USAGE = "usage: ./#{app} user EMAIL [PASSWORD] (without PASSWORD, it is read from standard input)"
869
+
870
+ # The exit status: 0 when the user was created or updated, 1 for bad
871
+ # arguments, an empty password or a record that does not validate.
872
+ def self.run(argv)
873
+ if argv.empty? || argv.size > 2 || argv[0].start_with?("-")
874
+ puts USAGE
875
+ return 1
876
+ end
877
+ password = argv.size == 2 ? argv[1] : UserCommand.read_password
878
+ if password.empty?
879
+ puts "error: the password is empty"
880
+ return 1
881
+ end
882
+
883
+ address = User.normalize_email_address(argv[0])
884
+ found = User.find_by(email_address: address)
885
+ created = found.nil?
886
+ user = found.nil? ? User.new(email_address: address) : found
887
+ user.password = password
888
+ unless user.save
889
+ user.errors.full_messages.each { |message| puts "error: \#{message}" }
890
+ return 1
891
+ end
892
+ puts created ? "created \#{address}" : "updated \#{address}"
893
+ 0
894
+ end
895
+
896
+ # One line of standard input, with a prompt when it is a terminal.
897
+ def self.read_password
898
+ if STDIN.tty?
899
+ STDOUT.print("Password: ")
900
+ STDOUT.flush
901
+ end
902
+ line = STDIN.gets
903
+ UserCommand.password_from(line.nil? ? "" : line)
904
+ end
905
+
906
+ # The text without one trailing newline ("\\n" or "\\r\\n"), which a
907
+ # terminal or `echo` adds. Anything else, spaces too, is the password.
908
+ def self.password_from(text)
909
+ s = text.to_s
910
+ s = s[0, s.size - 1].to_s if s.end_with?("\\n")
911
+ s = s[0, s.size - 1].to_s if s.end_with?("\\r")
912
+ s
913
+ end
914
+
915
+ # Called by bin/#{app}.rb before the server boots: a [WARN] while no
916
+ # user exists, which is while /setup is open, with the page's
917
+ # one-time token (SetupController.setup_token, this process's own).
918
+ # Says nothing when the users table is not there yet (`./#{app}
919
+ # migrate` comes first).
920
+ def self.warn_if_no_user
921
+ Cybertrain.logger.warn("no user exists yet: run ./#{app} user EMAIL, or open /setup?token=\#{SetupController.setup_token} from this machine") if UserCommand.no_user?
922
+ nil
923
+ end
924
+
925
+ # Connects for the question only: Application#boot connects the
926
+ # server's own pool afterwards.
927
+ def self.no_user?
928
+ begin
929
+ Cybertrain::DB.connect(Cybertrain.config.database_path, size: 1)
930
+ !User.all.exists?
931
+ rescue Cybertrain::DB::Error
932
+ false
933
+ ensure
934
+ Cybertrain::DB.disconnect
935
+ end
936
+ end
937
+ end
938
+
939
+ Cybertrain::Main.command("user", "EMAIL [PASSWORD]: create a user or set its password") do |argv|
940
+ UserCommand.run(argv)
941
+ end
942
+ RUBY
943
+ end
944
+
945
+ # Inserted before the Main.run line of bin/<app>.rb (--invite-only).
946
+ def self.bin_block(app)
947
+ <<~RUBY
948
+ # `./#{app} user EMAIL [PASSWORD]`, and a [WARN] at boot while no user
949
+ # exists (cybertrain generate authentication --invite-only).
950
+ #{COMMAND_REQUIRE}
951
+ UserCommand.warn_if_no_user if Cybertrain::Main.server?(ARGV)
952
+
953
+ RUBY
954
+ end
955
+
956
+ # Inserted (indented) after the configure line of config/app.rb
957
+ # (--invite-only).
958
+ def self.config_block(app)
959
+ env = setup_env(app)
960
+ <<~RUBY
961
+ # /setup (the first user's page) answers only to this machine, with the
962
+ # token the boot warning prints, while no user exists; #{env}=1
963
+ # opens it to any address (the token is still needed), for a first
964
+ # run behind a proxy on another host. Unset it once the user exists.
965
+ c.setting_bool :setup_open, env: "#{env}", default: false
966
+
967
+ RUBY
968
+ end
969
+
970
+ # Inserted (indented) after the draw line of config/routes.rb.
971
+ def self.routes_block(invite_only = false)
972
+ if invite_only
973
+ return <<~RUBY
974
+ resource :session, only: [:new, :create, :destroy]
975
+ get "/setup", to: "setup#new", as: "setup"
976
+ post "/setup", to: "setup#create"
977
+ RUBY
978
+ end
979
+
980
+ <<~RUBY
981
+ resource :session, only: [:new, :create, :destroy]
982
+ get "/sign_up", to: "registrations#new", as: "sign_up"
983
+ post "/sign_up", to: "registrations#create"
984
+ RUBY
985
+ end
986
+
987
+ # ---- tests --------------------------------------------------------
988
+
989
+ # The same shape as examples/blog/test/support/blog_test.rb: boots the
990
+ # app on a fresh test database. Shared by every test file; copy
991
+ # helpers into it as the app grows.
992
+ def self.app_test_support
993
+ <<~RUBY
994
+ # Shared setup for the integration tests (test/*.rb): the app booted in
995
+ # the test environment on a fresh storage/test.sqlite3. Required by the
996
+ # test files, not run (`spin test` runs test/*.rb only).
997
+ ENV["CYBERTRAIN_ENV"] = "test"
998
+
999
+ require "cybertrain"
1000
+ require "cybertrain/test/client"
1001
+ require_relative "../../config/app"
1002
+ require_relative "../../gen/app"
1003
+ require_relative "../../gen/migrations"
1004
+
1005
+ # No request log: `spin test` diffs the whole output against the
1006
+ # snapshot, and "Completed 303 in 246ms" is never the same twice.
1007
+ Cybertrain.config.log_level = :none
1008
+
1009
+ # Webhooks and e-mail the app sends are received in-process: require
1010
+ # "cybertrain/test/http_receiver" or "cybertrain/test/smtp_receiver",
1011
+ # then `port = receiver.start`, point the app at 127.0.0.1:port
1012
+ # (HttpClient needs `Cybertrain.config.http_allow_private = true`, the
1013
+ # Mailer `tls: "none"`), and read `receiver.received_request` /
1014
+ # `received_message` before `receiver.stop`. Every wait is bounded.
1015
+
1016
+ module AppTest
1017
+ # Deletes the test database (and its WAL files), migrates a new one
1018
+ # and boots the application on it.
1019
+ def self.boot
1020
+ path = Cybertrain.config.database_path
1021
+ [path, "\#{path}-wal", "\#{path}-shm"].each { |f| File.delete(f) if File.exist?(f) }
1022
+ connection = Cybertrain::DB::Connection.new(path)
1023
+ Cybertrain::DB::Migrator.new(connection).migrate(Cybertrain::Migration.all)
1024
+ connection.close
1025
+
1026
+ app = Cybertrain::Application.new(
1027
+ router: Gen::Routes.build(Cybertrain::Router.new),
1028
+ url_resolver: Gen::Routes.url_resolver
1029
+ )
1030
+ app.boot
1031
+ end
1032
+
1033
+ # The authenticity_token of the first form in the last response, as
1034
+ # a browser would submit it back.
1035
+ def self.form_token(client)
1036
+ body = client.response.body
1037
+ marker = "name=\\"authenticity_token\\" value=\\""
1038
+ at = body.index(marker)
1039
+ raise "no authenticity_token in the last response" if at.nil?
1040
+
1041
+ start = at + marker.size
1042
+ stop = body.index("\\"", start)
1043
+ raise "unterminated authenticity_token" if stop.nil?
1044
+
1045
+ body[start, stop - start].to_s
1046
+ end
1047
+
1048
+ # A user with this address and password (both normalized the way the
1049
+ # forms are).
1050
+ def self.user(email_address = "ann@example.com", password = "s3cr3t-s3cr3t")
1051
+ user = User.new(email_address: email_address)
1052
+ user.password = password
1053
+ user.save!
1054
+ user
1055
+ end
1056
+
1057
+ # Signs `client` in through the form, as a browser would. Every test
1058
+ # client has the same address, so the sign-in rate limit's counts
1059
+ # are forgotten first: a suite signs in far more than ten times.
1060
+ def self.sign_in(client, email_address = "ann@example.com", password = "s3cr3t-s3cr3t")
1061
+ Cybertrain::RateLimit.reset_all!
1062
+ client.get("/session/new")
1063
+ client.post("/session", { "authenticity_token" => form_token(client),
1064
+ "email_address" => email_address,
1065
+ "password" => password })
1066
+ end
1067
+ end
1068
+
1069
+ APP = AppTest.boot
1070
+ RUBY
1071
+ end
1072
+
1073
+ # test/authentication.rb: the head (requires, new_client, the sign-in
1074
+ # form), the sign-up or first-run tests, then the sign-in and sign-out
1075
+ # tests both variants share.
1076
+ # The pieces go through locals and `<<`: an interpolation of three
1077
+ # method calls could free one result while building the next under
1078
+ # Spinel (spikes/NOTES.md rule 65), and the CLI compiles there too.
1079
+ def self.authentication_test
1080
+ head = authentication_test_head(false)
1081
+ middle = sign_up_tests
1082
+ join_three(head, middle, authentication_test_tail)
1083
+ end
1084
+
1085
+ # --invite-only's test/authentication.rb.
1086
+ def self.invite_only_test(app)
1087
+ head = authentication_test_head(true)
1088
+ middle = setup_tests(app)
1089
+ join_three(head, middle, authentication_test_tail)
1090
+ end
1091
+
1092
+ def self.join_three(first, second, third)
1093
+ out = +""
1094
+ out << first << second << third
1095
+ out
1096
+ end
1097
+
1098
+ def self.authentication_test_head(invite_only)
1099
+ what = invite_only ? "First-run setup, the user command, sign-in" : "Sign-up, sign-in"
1100
+ command = invite_only ? "require_relative \"../app/commands/user_command\"\n" : ""
1101
+ open_actions = invite_only ? "sign-in and setup" : "sign-in and sign-up"
1102
+ link = if invite_only
1103
+ 'refute res.body.include?("/sign_up")'
1104
+ else
1105
+ 'assert_includes res.body, "<a href=\"/sign_up\">Sign up</a>"'
1106
+ end
1107
+ <<~RUBY
1108
+ # #{what} and sign-out through the full stack (session cookie,
1109
+ # CSRF, method override, router). Run with `cybertrain spin test`; its
1110
+ # snapshot comes from the compiled binary (the database is FFI):
1111
+ # `script/regen-snapshot`-style, see README "Testing an app".
1112
+ require_relative "support/app_test"
1113
+ #{command}
1114
+ def new_client
1115
+ Session.all.delete_all
1116
+ User.all.delete_all
1117
+ Cybertrain::Test::Client.new(APP)
1118
+ end
1119
+
1120
+ # Every action but #{open_actions} needs a user: DELETE /session is
1121
+ # the one such action this test can rely on before the app has pages
1122
+ # of its own (a `root` route, a scaffold).
1123
+ test "a visitor is sent to the sign-in page" do
1124
+ client = new_client
1125
+ client.get("/session/new")
1126
+ res = client.post("/session", { "_method" => "delete", "authenticity_token" => AppTest.form_token(client) })
1127
+ assert_redirected_to res, "/session/new"
1128
+ assert_response res, :see_other
1129
+ end
1130
+
1131
+ test "GET /session/new renders the sign-in form" do
1132
+ client = new_client
1133
+ res = client.get("/session/new")
1134
+ assert_response res, :ok
1135
+ assert_includes res.body, "<h1>Sign in</h1>"
1136
+ assert_includes res.body, "<form action=\\"/session\\" method=\\"post\\">"
1137
+ assert_includes res.body, "name=\\"email_address\\""
1138
+ assert_includes res.body, "type=\\"password\\" name=\\"password\\""
1139
+ #{link}
1140
+ end
1141
+
1142
+ RUBY
1143
+ end
1144
+
1145
+ # --invite-only: /setup and `./<app> user` in place of the sign-up tests.
1146
+ def self.setup_tests(app)
1147
+ env = setup_env(app)
1148
+ <<~RUBY
1149
+ # The form /setup posts, filled in, with the page's one-time token
1150
+ # in its hidden field.
1151
+ def setup_form(authenticity_token, password, confirmation)
1152
+ { "authenticity_token" => authenticity_token,
1153
+ "token" => SetupController.setup_token,
1154
+ "user[email_address]" => " Ann@Example.com ",
1155
+ "user[password]" => password,
1156
+ "user[password_confirmation]" => confirmation }
1157
+ end
1158
+
1159
+ # /setup with this process's token, the link the boot warning prints.
1160
+ def setup_link
1161
+ "/setup?token=\#{SetupController.setup_token}"
1162
+ end
1163
+
1164
+ # `./#{app} ARGS...` in-process. Main.run connects a pool of one for
1165
+ # the command and disconnects it, so the tests' pool is connected
1166
+ # again afterwards (the database file is the same).
1167
+ def run_command(argv)
1168
+ status = Cybertrain::Main.run("#{app}", argv, router: Gen::Routes.build(Cybertrain::Router.new),
1169
+ url_resolver: Gen::Routes.url_resolver,
1170
+ views: Cybertrain::Application.no_views)
1171
+ reconnect
1172
+ status
1173
+ end
1174
+
1175
+ def reconnect
1176
+ Cybertrain::DB.connect(Cybertrain.config.database_path, size: Cybertrain.config.pool_size)
1177
+ nil
1178
+ end
1179
+
1180
+ test "GET /setup with the token shows the form to this machine while no user exists" do
1181
+ client = new_client
1182
+ res = client.get(setup_link)
1183
+ assert_response res, :ok
1184
+ assert_includes res.body, "<h1>Set up</h1>"
1185
+ assert_includes res.body, "<form action=\\"/setup\\" method=\\"post\\">"
1186
+ assert_includes res.body, "<input type=\\"hidden\\" name=\\"token\\" value=\\"\#{SetupController.setup_token}\\">"
1187
+ assert_includes res.body, "name=\\"user[password_confirmation]\\""
1188
+ end
1189
+
1190
+ test "/setup without the token, or with a wrong one, is a 404" do
1191
+ client = new_client
1192
+ assert_equal 32, SetupController.setup_token.size
1193
+ res = client.get("/setup")
1194
+ assert_response res, :not_found
1195
+ res = client.get("/setup?token=")
1196
+ assert_response res, :not_found
1197
+ res = client.get("/setup?token=0123456789abcdef0123456789abcdef")
1198
+ assert_response res, :not_found
1199
+ res = client.get("/setup?token=\#{SetupController.setup_token}x")
1200
+ assert_response res, :not_found
1201
+ refute res.body.include?(SetupController.setup_token)
1202
+ end
1203
+
1204
+ test "/setup is a 404 to another machine, through a proxy, and once a user exists" do
1205
+ client = new_client
1206
+ client.peer_address = "203.0.113.7"
1207
+ res = client.get(setup_link)
1208
+ assert_response res, :not_found
1209
+ client.peer_address = "127.0.0.1"
1210
+ res = client.get(setup_link, { "x-forwarded-for" => "203.0.113.7" })
1211
+ assert_response res, :not_found
1212
+ res = client.get(setup_link)
1213
+ assert_response res, :ok
1214
+ AppTest.user
1215
+ res = client.get(setup_link)
1216
+ assert_response res, :not_found
1217
+ end
1218
+
1219
+ test "POST /setup from another machine, or without the token, creates nothing" do
1220
+ client = new_client
1221
+ client.get(setup_link)
1222
+ authenticity_token = AppTest.form_token(client)
1223
+ client.peer_address = "203.0.113.7"
1224
+ res = client.post("/setup", setup_form(authenticity_token, "s3cr3t-s3cr3t", "s3cr3t-s3cr3t"))
1225
+ assert_response res, :not_found
1226
+ client.peer_address = "127.0.0.1"
1227
+ form = setup_form(authenticity_token, "s3cr3t-s3cr3t", "s3cr3t-s3cr3t")
1228
+ form["token"] = "0123456789abcdef0123456789abcdef"
1229
+ res = client.post("/setup", form)
1230
+ assert_response res, :not_found
1231
+ form.delete("token")
1232
+ res = client.post("/setup", form)
1233
+ assert_response res, :not_found
1234
+ assert_equal 0, User.count
1235
+ end
1236
+
1237
+ test "#{env} opens /setup to any address with the token until a user exists" do
1238
+ client = new_client
1239
+ client.peer_address = "203.0.113.7"
1240
+ Cybertrain.config.set_bool_setting(:setup_open, true)
1241
+ res = client.get(setup_link)
1242
+ without = client.get("/setup")
1243
+ Cybertrain.config.set_bool_setting(:setup_open, false)
1244
+ assert_response res, :ok
1245
+ assert_response without, :not_found
1246
+ AppTest.user
1247
+ Cybertrain.config.set_bool_setting(:setup_open, true)
1248
+ res = client.get(setup_link)
1249
+ Cybertrain.config.set_bool_setting(:setup_open, false)
1250
+ assert_response res, :not_found
1251
+ end
1252
+
1253
+ test "POST /setup with the token creates the first user and signs them in" do
1254
+ client = new_client
1255
+ client.get(setup_link)
1256
+ res = client.post("/setup", setup_form(AppTest.form_token(client), "s3cr3t-s3cr3t", "s3cr3t-s3cr3t"))
1257
+ assert_redirected_to res, "/"
1258
+ assert_equal 1, User.count
1259
+ assert_equal "ann@example.com", User.first.email_address
1260
+ assert_equal 1, Session.count
1261
+ res = client.get("/session/new")
1262
+ assert_includes res.body, "<span>ann@example.com</span>"
1263
+ res = client.get(setup_link)
1264
+ assert_response res, :not_found
1265
+ end
1266
+
1267
+ test "POST /setup with a short or mismatched password re-renders the form" do
1268
+ client = new_client
1269
+ client.get(setup_link)
1270
+ res = client.post("/setup", setup_form(AppTest.form_token(client), "short", "other"))
1271
+ assert_response res, :unprocessable_entity
1272
+ assert_includes res.body, "<li>Password is too short (minimum is 8 characters)</li>"
1273
+ assert_includes res.body, "<li>Password confirmation doesn&#39;t match Password</li>"
1274
+ assert_includes res.body, "<input type=\\"hidden\\" name=\\"token\\" value=\\"\#{SetupController.setup_token}\\">"
1275
+ assert_equal 0, User.count
1276
+ end
1277
+
1278
+ test "./#{app} user creates a user, then sets its password" do
1279
+ new_client
1280
+ assert_equal 0, run_command(["user", "Bob@Example.com", "s3cr3t-s3cr3t"])
1281
+ assert_equal 1, User.count
1282
+ assert_equal "bob@example.com", User.first.email_address
1283
+ assert User.first.authenticate("s3cr3t-s3cr3t")
1284
+ assert_equal 0, run_command(["user", "bob@example.com", "another-s3cr3t"])
1285
+ assert_equal 1, User.count
1286
+ assert User.first.authenticate("another-s3cr3t")
1287
+ refute User.first.authenticate("s3cr3t-s3cr3t")
1288
+ end
1289
+
1290
+ test "./#{app} user refuses bad arguments and an empty or short password" do
1291
+ new_client
1292
+ assert_equal 1, run_command(["user"])
1293
+ assert_equal 1, run_command(["user", "ann@example.com", "s3cr3t-s3cr3t", "extra"])
1294
+ assert_equal 1, run_command(["user", "--help"])
1295
+ assert_equal 1, run_command(["user", "ann@example.com", ""])
1296
+ assert_equal 1, run_command(["user", "ann@example.com", "short"])
1297
+ assert_equal 0, User.count
1298
+ end
1299
+
1300
+ test "a password read from standard input loses one trailing newline" do
1301
+ assert_equal "s3cr3t s3cr3t", UserCommand.password_from("s3cr3t s3cr3t\\n")
1302
+ assert_equal "s3cr3t", UserCommand.password_from("s3cr3t\\r\\n")
1303
+ assert_equal "s3cr3t\\n", UserCommand.password_from("s3cr3t\\n\\n")
1304
+ assert_equal "", UserCommand.password_from("")
1305
+ end
1306
+
1307
+ test "the boot warning is due while no user exists" do
1308
+ new_client
1309
+ assert UserCommand.no_user?
1310
+ reconnect
1311
+ AppTest.user
1312
+ refute UserCommand.no_user?
1313
+ reconnect
1314
+ end
1315
+
1316
+ RUBY
1317
+ end
1318
+
1319
+ def self.sign_up_tests
1320
+ <<~RUBY
1321
+ test "POST /sign_up creates the user and signs them in" do
1322
+ client = new_client
1323
+ client.get("/sign_up")
1324
+ res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1325
+ "user[email_address]" => " Ann@Example.com ",
1326
+ "user[password]" => "s3cr3t-s3cr3t",
1327
+ "user[password_confirmation]" => "s3cr3t-s3cr3t" })
1328
+ assert_redirected_to res, "/"
1329
+ assert_equal 1, User.count
1330
+ assert_equal "ann@example.com", User.first.email_address
1331
+ assert User.first.password_digest.start_with?("$pbkdf2-sha256$")
1332
+ assert_equal 1, Session.count
1333
+ res = client.get("/session/new")
1334
+ assert_includes res.body, "<span>ann@example.com</span>"
1335
+ assert_includes res.body, "Sign out"
1336
+ end
1337
+
1338
+ test "POST /sign_up with a short or mismatched password re-renders the form" do
1339
+ client = new_client
1340
+ client.get("/sign_up")
1341
+ res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1342
+ "user[email_address]" => "ann@example.com",
1343
+ "user[password]" => "short",
1344
+ "user[password_confirmation]" => "other" })
1345
+ assert_response res, :unprocessable_entity
1346
+ assert_includes res.body, "<li>Password is too short (minimum is 8 characters)</li>"
1347
+ assert_includes res.body, "<li>Password confirmation doesn&#39;t match Password</li>"
1348
+ assert_equal 0, User.count
1349
+ res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1350
+ "user[email_address]" => "ann@example.com",
1351
+ "user[password]" => "",
1352
+ "user[password_confirmation]" => "" })
1353
+ assert_includes res.body, "<li>Password can&#39;t be blank</li>"
1354
+ end
1355
+
1356
+ test "an email address can be registered once" do
1357
+ client = new_client
1358
+ AppTest.user("ann@example.com")
1359
+ client.get("/sign_up")
1360
+ res = client.post("/sign_up", { "authenticity_token" => AppTest.form_token(client),
1361
+ "user[email_address]" => "ANN@example.com",
1362
+ "user[password]" => "another-one",
1363
+ "user[password_confirmation]" => "another-one" })
1364
+ assert_response res, :unprocessable_entity
1365
+ assert_includes res.body, "<li>Email address has already been taken</li>"
1366
+ assert_equal 1, User.count
1367
+ end
1368
+
1369
+ RUBY
1370
+ end
1371
+
1372
+ def self.authentication_test_tail
1373
+ <<~RUBY
1374
+ test "POST /session signs in with the right password" do
1375
+ client = new_client
1376
+ AppTest.user
1377
+ res = AppTest.sign_in(client)
1378
+ assert_redirected_to res, "/"
1379
+ assert_response res, :see_other
1380
+ assert_equal 1, Session.count
1381
+ assert_equal "127.0.0.1", Session.first.ip_address
1382
+ end
1383
+
1384
+ test "authentication returns to a local path once" do
1385
+ ctx = Cybertrain::Context.new(Cybertrain::Request.new("GET", "/", {}, ""))
1386
+ ctx.session = Cybertrain::Session.new
1387
+ controller = ApplicationController.new(ctx)
1388
+ assert_equal "/", controller.after_authentication_url
1389
+ ["/", "/products", "/products/1?tab=details#title", "/products//1", "/caf%C3%A9"].each do |path|
1390
+ controller.session[:return_to_after_authenticating] = path
1391
+ assert_equal path, controller.after_authentication_url
1392
+ refute controller.session.key?(:return_to_after_authenticating)
1393
+ assert_equal "/", controller.after_authentication_url
1394
+ end
1395
+ end
1396
+
1397
+ test "authentication rejects unsafe return destinations and consumes them" do
1398
+ ctx = Cybertrain::Context.new(Cybertrain::Request.new("GET", "/", {}, ""))
1399
+ ctx.session = Cybertrain::Session.new
1400
+ controller = ApplicationController.new(ctx)
1401
+ unsafe = ["", "products", "https://evil.example/", "//evil.example/", "///evil.example/",
1402
+ "/\\\\evil.example/", "/products\\\\evil", " //evil.example/", "/記事", "/" + "a" * 2048]
1403
+ (0..32).each { |byte| unsafe << "/\#{Cybertrain::Test.binary([byte])}/evil.example/" }
1404
+ unsafe << "/\#{Cybertrain::Test.binary([127])}/evil.example/"
1405
+ unsafe.each do |path|
1406
+ controller.session[:return_to_after_authenticating] = path
1407
+ assert_equal "/", controller.after_authentication_url
1408
+ refute controller.session.key?(:return_to_after_authenticating)
1409
+ end
1410
+ end
1411
+
1412
+ test "POST /session with the wrong password shows an alert" do
1413
+ client = new_client
1414
+ AppTest.user
1415
+ res = AppTest.sign_in(client, "ann@example.com", "wrong-password")
1416
+ assert_redirected_to res, "/session/new"
1417
+ res = client.follow_redirect!
1418
+ assert_includes res.body, "<p class=\\"alert\\">Try another email address or password.</p>"
1419
+ assert_equal 0, Session.count
1420
+ res = AppTest.sign_in(client, "nobody@example.com", "s3cr3t-s3cr3t")
1421
+ assert_redirected_to res, "/session/new"
1422
+ end
1423
+
1424
+ # SessionsController's rate_limit: ten attempts per address, then even
1425
+ # the right password goes back to the form until the window closes.
1426
+ test "POST /session past ten attempts is refused for a while" do
1427
+ client = new_client
1428
+ AppTest.user
1429
+ Cybertrain::RateLimit.reset_all!
1430
+ client.get("/session/new")
1431
+ wrong_password = { "authenticity_token" => AppTest.form_token(client),
1432
+ "email_address" => "ann@example.com", "password" => "wrong-password" }
1433
+ right_password = { "authenticity_token" => AppTest.form_token(client),
1434
+ "email_address" => "ann@example.com", "password" => "s3cr3t-s3cr3t" }
1435
+ 10.times { client.post("/session", wrong_password) }
1436
+ res = client.post("/session", right_password)
1437
+ assert_redirected_to res, "/session/new"
1438
+ assert_equal 0, Session.count
1439
+ res = client.follow_redirect!
1440
+ assert_includes res.body, "<p class=\\"alert\\">Try again later.</p>"
1441
+ Cybertrain::RateLimit.current_time = Time.now.to_i + 3 * 60
1442
+ res = client.post("/session", right_password)
1443
+ Cybertrain::RateLimit.current_time = -1
1444
+ assert_redirected_to res, "/"
1445
+ assert_equal 1, Session.count
1446
+ end
1447
+
1448
+ test "DELETE /session signs out and drops the Session row" do
1449
+ client = new_client
1450
+ AppTest.user
1451
+ AppTest.sign_in(client)
1452
+ client.get("/session/new")
1453
+ res = client.post("/session", { "_method" => "delete", "authenticity_token" => AppTest.form_token(client) })
1454
+ assert_redirected_to res, "/session/new"
1455
+ assert_equal 0, Session.count
1456
+ res = client.follow_redirect!
1457
+ assert_includes res.body, "<p class=\\"notice\\">You have been signed out.</p>"
1458
+ assert_includes res.body, "<a href=\\"/session/new\\">Sign in</a>"
1459
+ end
1460
+
1461
+ test "a session the database no longer has signs the browser out" do
1462
+ client = new_client
1463
+ AppTest.user
1464
+ AppTest.sign_in(client)
1465
+ Session.all.delete_all
1466
+ client.get("/session/new")
1467
+ res = client.post("/session", { "_method" => "delete", "authenticity_token" => AppTest.form_token(client) })
1468
+ assert_redirected_to res, "/session/new"
1469
+ end
1470
+
1471
+ test "changing the password signs out the sessions started before" do
1472
+ client = new_client
1473
+ user = AppTest.user
1474
+ AppTest.sign_in(client)
1475
+ res = client.get("/session/new")
1476
+ assert_includes res.body, "<span>ann@example.com</span>"
1477
+ user.password = "another-s3cr3t"
1478
+ user.save!
1479
+ res = client.get("/session/new")
1480
+ refute res.body.include?("<span>ann@example.com</span>")
1481
+ assert_equal 0, Session.count
1482
+ AppTest.sign_in(client, "ann@example.com", "another-s3cr3t")
1483
+ res = client.get("/session/new")
1484
+ assert_includes res.body, "<span>ann@example.com</span>"
1485
+ end
1486
+
1487
+ test "an expired cookie cannot restore its user or reach a protected action" do
1488
+ max_age = Cybertrain.config.session_absolute_max_age
1489
+ Cybertrain.config.session_absolute_max_age = 60
1490
+ begin
1491
+ client = new_client
1492
+ AppTest.user
1493
+ AppTest.sign_in(client)
1494
+ name = Cybertrain.config.session_cookie_name
1495
+ cookie = "\#{name}=\#{client.cookies[name]}"
1496
+ res = client.get("/session/new", { "cookie" => cookie })
1497
+ assert_includes res.body, "<span>ann@example.com</span>"
1498
+ token = AppTest.form_token(client)
1499
+
1500
+ # Keep the signed cookie and its row, but move the creation time
1501
+ # to the expiration boundary. Saving updates updated_at too;
1502
+ # neither that nor a rewritten cookie extends authentication.
1503
+ row = Session.first
1504
+ row.created_at = Time.at(Time.now.to_i - Cybertrain.config.session_absolute_max_age).utc
1505
+ row.save!
1506
+ res = client.post("/session", { "_method" => "delete", "authenticity_token" => token },
1507
+ { "cookie" => cookie })
1508
+ assert_redirected_to res, "/session/new"
1509
+ assert_equal 1, Session.count
1510
+ res = client.get("/session/new")
1511
+ refute res.body.include?("<span>ann@example.com</span>")
1512
+ assert_includes res.body, "<a href=\\"/session/new\\">Sign in</a>"
1513
+
1514
+ # Replaying the original credential again still fails, even
1515
+ # after the server removed its id from the client's cookie.
1516
+ res = client.get("/session/new", { "cookie" => cookie })
1517
+ refute res.body.include?("<span>ann@example.com</span>")
1518
+ ensure
1519
+ Cybertrain.config.session_absolute_max_age = max_age
1520
+ end
1521
+ end
1522
+
1523
+ Cybertrain::Test.run!
1524
+ RUBY
1525
+ end
1526
+ end
1527
+ end
1528
+ end