-
Notifications
You must be signed in to change notification settings - Fork 565
Expand file tree
/
Copy pathclover_admin.rb
More file actions
1372 lines (1204 loc) · 46.4 KB
/
clover_admin.rb
File metadata and controls
1372 lines (1204 loc) · 46.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
require_relative "model"
require "roda"
require "tilt"
require "tilt/erubi"
require "openssl"
class CloverAdmin < Roda
include AuditLog
TableLink = Data.define(:value, :link)
def table_link(...)
TableLink.new(...)
end
TableFormButton = Data.define(:text, :attributes)
def table_form_button(text, **attributes)
TableFormButton.new(text, attributes)
end
Unreloader.record_dependency("lib/audit_log.rb", __FILE__)
MIN_AUDIT_LOG_END_DATE = Date.new(2025, 6)
AUDIT_LOG_PARAM_MAP = Hash.new("object")
AUDIT_LOG_PARAM_MAP["Project"] = "project"
AUDIT_LOG_PARAM_MAP["Account"] = "subject"
AUDIT_LOG_PARAM_MAP.freeze
# :nocov:
if Config.development?
plugin :exception_page
class RodaRequest
def assets
exception_page_assets
super
end
end
end
default_fixed_locals = if Config.production? || Config.frozen_test?
"()"
# :nocov:
else
"(_no_kw: nil)"
end
plugin :render, views: "views/admin", escape: true, assume_fixed_locals: true, template_opts: {
chain_appends: !defined?(SimpleCov),
freeze: true,
skip_compiled_encoding_detection: true,
scope_class: self,
default_fixed_locals:,
extract_fixed_locals: true,
}
# :nocov:
if Config.test? && defined?(SimpleCov)
plugin :render_coverage, dir: "coverage/views/admin"
end
plugin :ip_from_header, Config.ip_from_header if Config.ip_from_header
# :nocov:
plugin :part
plugin :public
plugin :flash
plugin :h
plugin :content_security_policy do |csp|
csp.default_src :none
csp.style_src :self
csp.img_src :self # /favicon.ico
csp.script_src :self # webauthn
csp.form_action :self
csp.base_uri :none
csp.frame_ancestors :none
end
plugin :sessions,
key: "_CloverAdmin.session",
env_key: "clover.admin.session",
cookie_options: {secure: !(Config.development? || Config.test?)},
secret: OpenSSL::HMAC.digest("SHA512", Config.clover_session_secret, "admin-site")
UBID_REGEXP = /\A[a-tv-z0-9]{26}\z/
UUID_REGEXP = /\A[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\z/i
plugin :typecast_params_sized_integers, sizes: [64], default_size: 64
plugin :typecast_params do
handle_type(:ubid) do
it if UBID_REGEXP.match?(it)
end
handle_type(:uuid) do
it if UUID_REGEXP.match?(it)
end
handle_type(:ubid_uuid) do
UBID.to_uuid(it) if UBID_REGEXP.match?(it)
end
end
plugin :symbol_matchers
symbol_matcher(:ubid, /([a-tv-z0-9]{26})/, segment: true)
symbol_matcher(:ubid_uuid, :ubid) { UBID.to_uuid(it) }
plugin :not_found do
raise "admin route not handled: #{request.path}" if Config.test? && !ENV["DONT_RAISE_ADMIN_ERRORS"]
@page_title = "File Not Found"
if (ubid = request.path.split("/").find { UBID_REGEXP.match?(it) })
view(content: "<p>Try <a href=\"/archived-record-by-id?id=#{h ubid}\">searching archived records</a></p>")
else
view(content: "")
end
end
plugin :route_csrf do |token|
flash.now["error"] = "An invalid security token submitted with this request, please try again"
@page_title = "Invalid Security Token"
view(content: "")
end
plugin :error_handler do |e|
# :nocov:
next exception_page(e, assets: true) if Config.development?
# :nocov:
raise e if Config.test? && !ENV["DONT_RAISE_ADMIN_ERRORS"]
@page_title = if e.is_a?(CloverError)
"#{e.type}: #{e.message}"
else
Clog.emit("admin route exception", Util.exception_to_hash(e))
"Internal Server Error"
end
view(content: "")
end
plugin :forme_route_csrf
Forme.register_config(:clover_admin, base: :default, labeler: :explicit)
Forme.default_config = :clover_admin
def self.create_admin_account(login)
if Config.production? && defined?(Pry)
raise "cannot create admin account in production via pry as it would log the password"
end
password = SecureRandom.urlsafe_base64(16)
rodauth.create_account(login:, password:)
Clog.emit("Created admin account", {admin_account_created: login})
password
end
def linkify_ubids(body)
h(body).gsub(/\b[a-tv-z0-9]{26}\b/) do
if (klass = UBID.class_for_ubid(it))
"<a href=\"/model/#{klass}/#{it}\">#{it}</a>"
else
it
end
end
end
def format_bytes(bytes)
if bytes < 1024
"#{bytes.round}B"
elsif bytes < 1024**2
"#{(bytes / 1024.0).round(1)}KiB"
elsif bytes < 1024**3
"#{(bytes / 1024.0**2).round(1)}MiB"
else
"#{(bytes / 1024.0**3).round(1)}GiB"
end
end
def format_seconds(s)
m, s = s.divmod(60)
h, m = m.divmod(60)
"%02d:%02d:%02d" % [h, m, s]
end
def _classes
classes = []
Sequel::Model.subclasses.each do |c|
classes << c if yield c
c.subclasses.each do |sc|
classes << sc if yield sc
end
end
classes.sort_by!(&:name)
end
def available_classes
_classes { it < ResourceMethods::InstanceMethods }
end
def semaphore_classes
_classes { it.respond_to?(:semaphore_names) }
end
skip_webauthn_requirement = Config.development? && Config.clover_admin_development_no_webauthn?
plugin :rodauth, route_csrf: true do
enable :argon2, :login, :logout, :webauthn, :change_password, :close_account, :internal_request,
:audit_logging
internal_request_configuration do
enable :create_account
require_email_address_logins? false
password_meets_requirements? do |password|
# uses a randomly generated password
true
end
end
uses_instance_variables(:@_webauthn_credential_id)
accounts_table :admin_account
password_hash_table :admin_password_hash
webauthn_keys_table :admin_webauthn_key
webauthn_user_ids_table :admin_webauthn_user_id
login_column :login
audit_logging_table :admin_account_authentication_audit_log
# :nocov:
unless skip_webauthn_requirement
# :nocov:
login_redirect do
uses_two_factor_authentication? ? "/webauthn-auth" : "/webauthn-setup"
end
remove_webauthn_key do |webauthn_id|
@_webauthn_credential_id = webauthn_id
super(webauthn_id)
end
add_webauthn_credential do |webauthn_credential|
@_webauthn_credential_id = webauthn_credential.id
super(webauthn_credential)
end
end
audit_log_metadata do |action|
hash = {}
if (ip = request.ip || session[:ip])
hash["ip"] = ip
end
case action
when :two_factor_authentication
webauthn_credential_id = authenticated_webauthn_id
when :webauthn_setup, :webauthn_remove
webauthn_credential_id = @_webauthn_credential_id
when :close_account
if (closer = session[:closer])
hash["closer"] = closer
end
end
if webauthn_credential_id
hash["token"] = webauthn_credential_id[0...8]
end
hash
end
check_csrf? false
require_bcrypt? false
skip_status_checks? true
title_instance_variable :@page_title
argon2_secret OpenSSL::HMAC.digest("SHA256", Config.clover_session_secret, "admin-argon2-secret")
hmac_secret OpenSSL::HMAC.digest("SHA512", Config.clover_session_secret, "admin-rodauth-hmac-secret")
function_name(&{
rodauth_get_salt: :rodauth_admin_get_salt,
rodauth_valid_password_hash: :rodauth_admin_valid_password_hash,
}.to_proc)
close_account_redirect "/login"
before_close_account do
login = account_from_session[:login]
closer = session[:closer] || login
Clog.emit("Admin account closed", {admin_account_closed: {account_closed: login, closer:}})
end
password_minimum_length 16
password_maximum_bytes 72
password_meets_requirements? do |password|
super(password) && password.match?(/[a-z]/) && password.match?(/[A-Z]/) && password.match?(/[0-9]/)
end
end
ObjectAction = Data.define(:label, :flash, :params, :type, :action) do
def self.define(label, flash: nil, params: {}, type: :normal, &action)
new(label, flash, params.dup.freeze, type, action)
end
def call(...)
action.call(...)
end
end
def self.object_action(...)
ObjectAction.define(...)
end
github_page_action = object_action("GitHub Page", type: :direct) do |obj|
"http://github.com/#{obj.name}"
end
OBJECT_ACTIONS = {
"Account" => {
"suspend" => object_action("Suspend", flash: "Account suspended", &:suspend),
"unsuspend" => object_action("Unsuspend", flash: "Account unsuspended", &:unsuspend),
},
"BootImage" => {
"remove_boot_image" => object_action("Remove Boot Image", flash: "Boot image removal scheduled", &:remove_boot_image),
"activate_boot_image" => object_action("Activate Boot Image", flash: "Boot image activated") do |obj|
obj.update(activated_at: Time.now)
end,
"disable_boot_image" => object_action("Disable Boot Image", flash: "Boot image disabled") do |obj|
obj.update(activated_at: nil)
end,
},
"DnsZone" => {
"add_record" => object_action("Add DNS Record", flash: "Added DNS Record",
params: {
name: {typecast: :nonempty_str!, label: "name (without zone)"},
type: {typecast: :nonempty_str!},
data: {typecast: :nonempty_str!},
ttl: {typecast: :pos_int!, type: :number, attr: {min: 60, max: 3600}, value: 600},
}) do |obj, record_name, type, data, ttl|
record_name += ".#{obj.name}."
obj.insert_record(record_name:, type:, ttl:, data:)
end,
},
"DnsRecord" => {
"delete" => object_action("Delete DNS Record", flash: "Deleted DNS Record") do |obj|
dns_zone = DnsZone.with_pk!(obj.dns_zone_id)
dns_zone.delete_record(record_name: obj.name, type: obj.type, data: obj.data)
end,
},
"GithubInstallation" => {
"github_page" => github_page_action,
},
"GithubRepository" => {
"github_page" => github_page_action,
"show_job_log" => object_action("Show Job Log", params: {job_id: {typecast: :pos_int!, type: "number", attr: {min: 1, max: 2**63 - 1}}}, type: :content) do |obj, job_id|
url = obj.installation.client.workflow_run_job_logs(obj.name, job_id)
"<a href=\"#{Erubi.h(url)}\">Download Job Log</a>"
rescue Octokit::NotFound
"Job not found"
rescue Octokit::Error => e
"GitHub error: #{e.message}"
end,
},
"GithubRunner" => {
"provision" => object_action("Provision Spare Runner", flash: "Spare runner provisioned", type: :form, &:provision_spare_runner),
},
"Invoice" => {
"download_pdf" => object_action("Download PDF", type: :direct) do |obj|
obj.generate_download_link
end,
},
"OidcProvider" => {
"add_allowed_domain" => object_action("Add Allowed Domain", flash: "Added allowed domain", params: {domain: {typecast: :nonempty_str!}}) do |obj, domain|
obj.add_allowed_domain(domain)
end,
"remove_allowed_domain" => object_action("Remove Allowed Domain", flash: "Removed allowed domain",
params: ->(obj) {
{domain: {typecast: :nonempty_str!, type: "select", add_blank: true, required: true, options: obj.allowed_domains}}
}) do |obj, domain|
obj.remove_allowed_domain(domain)
end,
},
"Page" => {
"resolve" => object_action("Resolve", flash: "Resolve scheduled for Page", &:incr_resolve),
"retrigger" => object_action("Retrigger", flash: "Retrigger scheduled for Page", &:incr_retrigger),
},
"PostgresResource" => {
"restart" => object_action("Restart", flash: "Restart scheduled for PostgresResource") do |obj|
obj.server_incr("restart")
end,
},
"PostgresServer" => {
"recycle" => object_action("Recycle", flash: "Recycle scheduled for PostgresServer", &:incr_recycle),
},
"Project" => {
"add_credit" => object_action("Add credit", flash: "Added credit", params: {credit: {typecast: :float!, type: "number", attr: {min: -10**6, max: 10**6}}}) do |obj, credit|
obj.this.update(credit: Sequel[:credit] + credit)
end,
"set_feature_flag" => object_action("Set Feature Flag", flash: "Set feature flag", params: {
name: {
typecast: :str!,
type: "select",
add_blank: true,
options: Project.instance_methods.grep(/\Aset_ff_/).map! { it[7...] }.sort!,
},
value: {
typecast: :nonempty_str,
placeholder: "JSON",
required: nil,
},
}) do |obj, name, value|
begin
value = JSON.parse(value) if value
rescue JSON::ParserError
fail CloverError.new(400, "InvalidRequest", "invalid JSON for feature flag value")
end
obj.send("set_ff_#{name}", value)
end,
"set_quota" => object_action("Set Quota", flash: "Set quota", params: {
resource_type: {
typecast: :str!,
type: "select",
add_blank: true,
options: ProjectQuota.default_quotas.keys,
},
value: {
typecast: :int,
type: "number",
placeholder: "blank to reset to default",
required: nil,
},
}) do |obj, resource_type, value|
quota_id = ProjectQuota.default_quotas[resource_type]["id"]
if (existing_quota = obj.quotas_dataset.first(quota_id:))
if value
existing_quota.update(value:)
else
existing_quota.destroy
end
elsif value
obj.add_quota(quota_id:, value:)
end
end,
},
"Strand" => {
"subject" => object_action("Subject", type: :direct) do |obj|
"/model/#{obj.subject.class}/#{obj.subject.ubid}"
end,
"schedule" => object_action("Schedule Strand to Run Immediately", flash: "Scheduled strand to run immediately", type: :form) do |obj|
obj.this.update(schedule: Sequel::CURRENT_TIMESTAMP)
end,
"extend" => object_action("Extend Schedule", flash: "Extended schedule", params: {minutes: {typecast: :pos_int!, type: "number", attr: {min: 1, max: 1440}}}) do |obj, minutes|
obj.this.update(schedule: Sequel.date_add(:schedule, minutes:))
end,
"incr_semaphore" => object_action("Increment Semaphore", flash: "Incremented semaphore", params: ->(obj) {
subject_class = obj.subject.class
options = subject_class.respond_to?(:semaphore_names) ? subject_class.semaphore_names.map(&:name).sort! : [].freeze
{
name: {typecast: :nonempty_str!, type: "select", add_blank: true, required: true, options:},
name_confirmation: {typecast: :nonempty_str!, type: "select", add_blank: true, required: true, options:},
}
}) do |obj, name, name_confirmation|
fail CloverError.new(400, "InvalidRequest", "Semaphore name confirmation does not match") unless name == name_confirmation
Semaphore.incr(obj.id, name)
end,
"decr_semaphore" => object_action("Decrement Semaphore", flash: "Decremented semaphore", params: ->(obj) {
options = obj.semaphores_dataset.distinct.select_order_map(:name)
{
name: {typecast: :nonempty_str!, type: "select", add_blank: true, required: true, options:},
name_confirmation: {typecast: :nonempty_str!, type: "select", add_blank: true, required: true, options:},
}
}) do |obj, name, name_confirmation|
fail CloverError.new(400, "InvalidRequest", "Semaphore name confirmation does not match") unless name == name_confirmation
Semaphore.where(strand_id: obj.id, name:).destroy
end,
},
"Vm" => {
"restart" => object_action("Restart", flash: "Restart scheduled for Vm", &:incr_restart),
"stop" => object_action("Stop", flash: "Stop scheduled for Vm") do |obj|
DB.transaction do
obj.incr_admin_stop
obj.incr_stop
end
end,
},
"VmHost" => {
"accept" => object_action("Move to Accepting", flash: "Host allocation state changed to accepting") do |obj|
obj.update(allocation_state: "accepting")
end,
"drain" => object_action("Move to Draining", flash: "Host allocation state changed to draining") do |obj|
obj.update(allocation_state: "draining")
end,
"reset" => object_action("Hardware Reset", flash: "Hardware reset scheduled for VmHost", &:incr_hardware_reset),
"reboot" => object_action("Reboot", flash: "Reboot scheduled for VmHost", &:incr_reboot),
"move_location" => object_action("Move to Location", flash: "Location updated and missing boot image downloads started", params: {
location: {
typecast: :ubid_uuid!,
type: "select",
add_blank: true,
required: true,
options: Location
.where(project_id: nil, provider: %w[hetzner leaseweb])
.or(id: Location::GITHUB_RUNNERS_ID)
.select_order_map([:display_name, :id])
.each { it[1] = UBID.to_ubid(it[1]) },
},
}) do |obj, target_location_id|
obj.move_to_location(target_location_id)
end,
"force_create_vm" => object_action("Force Create VM", flash: "VM creation scheduled", params: ->(obj) {
{
project_id: {typecast: :ubid_uuid!, required: true, placeholder: "Project UBID"},
public_key: {typecast: :nonempty_str!, required: true},
name: {typecast: :nonempty_str, required: nil, placeholder: "auto-generated if blank"},
size: {
typecast: :nonempty_str!,
type: "select",
required: true,
options: Option::VmSizes.select { it.arch == obj.arch && (it.family == obj.family || (it.family == "burstable" && obj.accepts_slices)) }.map(&:name),
},
boot_image: {
typecast: :nonempty_str!,
type: "select",
required: true,
options: obj.boot_images_dataset.exclude(activated_at: nil).distinct.select_order_map(:name),
},
}
}) do |obj, project_id, public_key, name, size, boot_image|
Prog::Vm::Nexus.assemble(public_key, project_id, name:, size:, boot_image:,
location_id: obj.location_id, arch: obj.arch, force_host_id: obj.id, enable_ip4: true)
end,
},
}.freeze
OBJECT_ACTIONS.each_value(&:freeze)
SEARCH_QUERIES = {
"Account" => [:email, :name],
"BillingInfo" => [:stripe_id],
"GithubInstallation" => [:name],
"GithubRepository" => [:name],
"Invoice" => [:invoice_number],
"KubernetesCluster" => [:name],
"PostgresResource" => [:name],
"Vm" => [:name],
}.freeze
SEARCH_QUERIES.each_value(&:freeze)
SEARCH_PREFIXES = SEARCH_QUERIES.map { "#{Object.const_get(it[0]).ubid_type} (#{it[0]})" }.join(", ").freeze
OBJECTS_WITH_UI = {
"Vm" => lambda { |vm| "project/#{vm.project.ubid}/location/#{vm.location.display_name}/vm/#{vm.ubid}/overview" },
"PostgresResource" => lambda { |pg| "project/#{pg.project.ubid}/location/#{pg.location.display_name}/postgres/#{pg.name}/overview" },
}.freeze
OBJECTS_WITH_EXTRAS = Dir["views/admin/extras/*.erb"]
.map { File.basename(it, ".erb") }
.each_with_object({}) { |name, h| h[name] = true }
.freeze
OBJECT_ASSOC_TABLE_PARAMS = {
["GithubInstallation", :runners] => "installation",
["GithubInstallation", :repositories] => "installation",
["GithubRepository", :runners] => "repository",
["Project", :vms] => "project",
["Project", :postgres_resources] => "project",
["Project", :invoices] => "project",
["PostgresResource", :servers] => "resource",
["VmHost", :boot_images] => "vm_host",
}.freeze
ROLLOUT_PROGS = %w[
RolloutRhizome
RolloutSemaphore
].freeze
LOCAL_E2E_PROGS = Prog::Test::LocalE2eLoop::ALLOWED_PROGS
LOCAL_E2E_PROVIDERS = %w[
aws
metal
].freeze
plugin :autoforme do
# :nocov:
register_by_name if Config.development?
# :nocov:
framework = self
pagination_strategy :filter
order [:id]
supported_actions [:browse, :search]
form_options(wrapper: :div)
link = lambda do |obj, label: "admin_label"|
return "" unless obj
"<a href=\"/model/#{obj.class}/#{obj.ubid}\">#{Erubi.h(obj.send(label))}</a>"
end
show_html do |obj, column|
case column
when :name, :ubid, :invoice_number
link.call(obj, label: column)
when :project, :location, :vm_host, :billing_info, :resource, :parent, :installation
link.call(obj.send(column))
when :vm
link.call(obj.send(column), label: :ubid)
when :subtotal, :cost
"$%0.02f" % (obj.send(column) || 0)
end
end
column_grep = lambda do |ds, column, value|
ds.where(Sequel.cast(column, :text).ilike("%#{ds.escape_like(value)}%"))
end
ubid_uuid_grep = lambda do |ds, column, value|
uuid = if UBID_REGEXP.match?(value)
UBID.to_uuid(value)
elsif UUID_REGEXP.match?(value)
value
end
ds.where(column => uuid)
end
column_search_filter do |model, ds, column, value|
case column
when :created_at
column_grep.call(ds, :created_at, value)
when :project
ubid_uuid_grep.call(ds, :project_id, value)
end
end
ubid_input = lambda do |name|
{type: "text", placeholder: "#{name} UBID/UUID", maxlength: 36, minlength: 26}
end
model Firewall do
eager [:project, :location]
columns [:name, :project, :location, :description]
end
model Account do
order Sequel.desc(Sequel[:accounts][:created_at])
eager_graph [:identities]
columns [:name, :email, :status_id, :provider_names, :created_at, :suspended_at]
column_options email: {type: "text"},
status_id: {type: "select", options: {Unverified: 1, Verified: 2, Closed: 3}, add_blank: true},
provider_names: {label: "Providers", type: "select", options: ["google", "github"], add_blank: true},
created_at: {type: "text"},
suspended_at: {label: "Suspended", type: "boolean", value: nil}
column_search_filter do |ds, column, value|
case column
when :provider_names
ds.where(provider: value)
when :created_at
column_grep.call(ds, Sequel[:accounts][:created_at], value)
when :suspended_at
ds.send((value == "t") ? :exclude : :where, suspended_at: nil)
end
end
end
model BillingInfo do
order Sequel.desc(:created_at)
eager_graph [:project]
columns do |type_symbol, request|
cs = [:stripe_id, :project, :valid_vat, :created_at]
cs.prepend(:ubid) unless type_symbol == :search_form
cs
end
column_options project: ubid_input.call("Project"),
created_at: {type: "text"}
column_search_filter do |ds, column, value|
case column
when :project
ubid_uuid_grep.call(ds, Sequel[:project][:id], value)
when :created_at
column_grep.call(ds, Sequel[:billing_info][:created_at], value)
end
end
end
model GithubInstallation do
order Sequel.desc(:created_at)
columns [:name, :installation_id, :type, :cache_enabled, :premium_runner_enabled?, :created_at, :allocator_preferences]
column_options type: {type: "select", options: ["Organization", "User"], add_blank: true},
premium_runner_enabled?: {label: "Premium enabled", type: "boolean", value: nil},
created_at: {type: "text"}
column_search_filter do |ds, column, value|
case column
when :premium_runner_enabled?
family_filter = Sequel.pg_jsonb(:allocator_preferences).get("family_filter")
cond = family_filter.contains(["premium"])
if value == "t"
ds.where(cond)
else
ds.where(~cond | {family_filter => nil})
end
when :allocator_preferences, :created_at
column_grep.call(ds, column, value)
end
end
end
model GithubRepository do
order Sequel.desc(:created_at)
eager [:installation]
columns do |type_symbol, request|
if type_symbol == :search_form
[:installation, :name, :created_at]
else
[:name, :created_at, :last_job_at]
end
end
column_options installation: ubid_input.call("Installation"),
created_at: {type: "text"}
column_search_filter do |ds, column, value|
case column
when :installation
ubid_uuid_grep.call(ds, :installation_id, value)
else
framework
end
end
end
model GithubRunner do
order Sequel.desc(:created_at)
eager_graph [:strand]
eager [:installation]
columns do |type_symbol, request|
cs = [:repository_name, :label, :strand_label, :created_at]
cs.prepend(:repository, :installation) if type_symbol == :search_form
cs.prepend(:ubid) unless type_symbol == :search_form
cs
end
column_options strand_label: {type: "text"},
created_at: {type: "text"},
installation: ubid_input.call("Installation"),
repository: ubid_input.call("Repository")
column_search_filter do |ds, column, value|
case column
when :strand_label
column_grep.call(ds, Sequel[:strand][:label], value)
when :installation, :repository
ubid_uuid_grep.call(ds, :"#{column}_id", value)
else
framework
end
end
end
model Invoice do
order Sequel.desc(:invoice_number)
eager_graph [:project]
columns do |type_symbol, request|
if type_symbol == :search_form
[:invoice_number, :project, :status]
else
[:invoice_number, :project, :status, :subtotal, :cost]
end
end
column_options status: {type: "select", options: %w[unpaid paid fraud waiting_transfer below_minimum_threshold], add_blank: true},
project: ubid_input.call("Project")
column_search_filter do |ds, column, value|
case column
when :project
ubid_uuid_grep.call(ds, Sequel[:project][:id], value)
end
end
end
model PaymentMethod do
order Sequel.desc(:created_at)
eager [:billing_info]
columns do |type_symbol, request|
if type_symbol == :search_form
[:stripe_id, :fraud, :created_at]
else
[:ubid, :stripe_id, :billing_info, :fraud, :created_at]
end
end
column_options fraud: {type: "boolean", value: nil},
created_at: {type: "text"}
column_search_filter do |ds, column, value|
case column
when :fraud
ds.where(fraud: value == "t")
else
framework
end
end
end
model PostgresResource do
order Sequel.desc(:created_at)
eager do |type, _request|
[:location, :parent, :project] unless type == :association
end
columns [:name, :project, :location, :flavor, :target_vm_size, :target_storage_size_gib, :ha_type, :target_version, :parent, :created_at]
column_options flavor: {type: "select", options: %w[standard paradedb lantern], add_blank: true},
ha_type: {type: "select", options: %w[none async sync], add_blank: true},
target_version: {type: "select", options: Option::POSTGRES_VERSION_OPTIONS[PostgresResource::Flavor::STANDARD], add_blank: true},
target_storage_size_gib: {type: "number"},
project: ubid_input.call("Project"),
parent: ubid_input.call("Parent"),
created_at: {type: "text"}
column_search_filter do |ds, column, value|
case column
when :parent
ubid_uuid_grep.call(ds, :parent_id, value)
else
framework
end
end
end
model PostgresServer do
order Sequel.desc(:created_at)
eager [:resource, :vm]
columns do |type_symbol, request|
cs = [:resource, :timeline_access, :synchronization_status, :version, :is_representative, :created_at]
unless type_symbol == :search_form
cs.prepend(:vm)
cs.prepend(:ubid)
end
cs
end
column_options resource: ubid_input.call("Resource"),
timeline_access: {type: "select", options: %w[push fetch], add_blank: true},
synchronization_status: {type: "select", options: %w[ready catching_up], add_blank: true},
version: {type: "select", options: Option::POSTGRES_VERSION_OPTIONS[PostgresResource::Flavor::STANDARD], add_blank: true},
created_at: {type: "text"}
column_search_filter do |ds, column, value|
case column
when :resource
ubid_uuid_grep.call(ds, :resource_id, value)
else
framework
end
end
end
model Project do
order Sequel.desc(:created_at)
columns [:name, :reputation, :billing_info_id, :credit, :created_at]
column_options reputation: {type: "select", options: %w[new verified limited], add_blank: true},
created_at: {type: "text"}
end
model Strand do
order Sequel.desc(:try)
columns do |type_symbol, request|
if type_symbol == :search_form
[:prog, :label, :try]
else
[:ubid, :prog, :label, :schedule, :try]
end
end
column_options try: {type: "number", value: nil}
end
model Vm do
order Sequel.desc(:created_at)
eager do |type, _request|
[:location, :vm_host, :project, :strand, :semaphores] unless type == :association
end
columns [:name, :display_state, :project, :vm_host, :location, :arch, :boot_image, :family, :vcpus, :created_at]
column_options display_state: {type: "select", options: ["running", "creating", "starting", "rebooting", "deleting"], add_blank: true},
arch: {type: "select", options: ["x64", "arm64"], add_blank: true},
family: {type: "select", options: Option::VmFamilies.map(&:name), add_blank: true},
vcpus: {type: "number"},
created_at: {type: "text"},
project: ubid_input.call("Project")
end
model BootImage do
order Sequel.desc(:created_at)
eager [:vm_host]
columns [:name, :version, :vm_host, :size_gib, :activated_at, :created_at]
column_options vm_host: ubid_input.call("VmHost"),
created_at: {type: "text"},
activated_at: {type: "text"}
column_search_filter do |ds, column, value|
case column
when :vm_host
ubid_uuid_grep.call(ds, :vm_host_id, value)
when :activated_at
column_grep.call(ds, :activated_at, value)
else
framework
end
end
end
model VmHost do
order Sequel[:vm_host][:id]
eager [:location]
eager_graph [:sshable]
columns do |type_symbol, request|
cs = [:sshable_host, :allocation_state, :arch, :location, :data_center, :family, :total_cores, :total_hugepages_1g]
cs.prepend(:ubid) unless type_symbol == :search_form
cs
end
column_options sshable_host: {label: "Sshable", type: :text, value: ""},
allocation_state: {type: "select", options: ["accepting", "draining", "unprepared"], add_blank: true},
arch: {type: "select", options: ["x64", "arm64"], add_blank: true},
family: {type: "select", options: Option::VmFamilies.map(&:name), add_blank: true},
total_cores: {type: "number"},
total_hugepages_1g: {type: "number"}
column_search_filter do |ds, column, value|
if column == :sshable_host
column_grep.call(ds, Sequel[:sshable][:host], value)
end
end
end
end
def audit_log_paginate
if @pagination_key
@next_page_params["pagination_key"] = @pagination_key
"Next Page"
elsif @next_end_date
@next_page_params["end"] = @next_end_date
"Older Results"
end
end
def strand_semaphore_action(strand_ds, allowed_progs, additional_semaphores: {}.freeze)
r = request
matched_path = r.matched_path
semaphores = allowed_semaphores = %w[pause unpause destroy].freeze
semaphores += additional_semaphores.values.flatten unless additional_semaphores.empty?
r.post :ubid_uuid, semaphores do |strand_id, action|
unless (strand = strand_ds.with_pk(strand_id))
flash["error"] = "Strand not found, it was probably already deleted"
r.redirect matched_path
end
prog = strand.prog.split("::").last
if (!additional_semaphores[prog]&.include?(action) && !allowed_semaphores.include?(action)) ||
!allowed_progs.include?(prog)
raise "invalid strand"
end
case action
when "unpause"
Semaphore.where(strand_id: strand.id, name: "pause").destroy
strand.this.update(schedule: Sequel::CURRENT_TIMESTAMP)
else
Semaphore.incr(strand.id, action)
end
flash_action = case action
when "destroy"
"destroyed"
when "pause", "unpause"
action + "d"
else
"updated"
end
flash["notice"] = "Strand #{strand.ubid} #{flash_action}"
r.redirect matched_path
end
end
route do |r|
r.public
check_csrf!
r.rodauth
rodauth.require_authentication
rodauth.require_account
# :nocov:
rodauth.require_two_factor_setup unless skip_webauthn_requirement
r.exception_page_assets if Config.development?
# :nocov:
r.on "model", /([A-Z][a-zA-Z]+)/ do |model_name|
begin
@klass = Object.const_get(model_name)
rescue NameError
next
end
next unless @klass.is_a?(Class) && @klass < ResourceMethods::InstanceMethods