diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7bc6b26 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: +- package-ecosystem: bundler + directory: "/backend" + schedule: + interval: weekly + open-pull-requests-limit: 10 +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f21ff86 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,35 @@ +name: CI + +on: + pull_request: + push: + branches: [ main ] + +defaults: + run: + working-directory: backend + +jobs: + backend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - uses: ruby/setup-ruby@v1 + with: + working-directory: backend + bundler-cache: true + + - name: Security scan + run: bin/brakeman --no-pager + + - name: Gem audit + run: bin/bundler-audit + + - name: Lint + run: bin/rubocop -f github + + - name: Tests + env: + RAILS_ENV: test + run: bin/rails db:test:prepare test diff --git a/backend/.rubocop.yml b/backend/.rubocop.yml new file mode 100644 index 0000000..f9d86d4 --- /dev/null +++ b/backend/.rubocop.yml @@ -0,0 +1,8 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/backend/.ruby-version b/backend/.ruby-version new file mode 100644 index 0000000..73f716f --- /dev/null +++ b/backend/.ruby-version @@ -0,0 +1 @@ +ruby-3.3.14 diff --git a/backend/Gemfile b/backend/Gemfile new file mode 100644 index 0000000..a3ff818 --- /dev/null +++ b/backend/Gemfile @@ -0,0 +1,36 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.1.4", ">= 8.1.4.1" +# Use sqlite3 as the database for Active Record +gem "sqlite3", ">= 2.1" +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# Use Redis adapter to run Action Cable in production +# gem "redis", ">= 4.0.1" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ windows jruby ] + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin Ajax possible +# gem "rack-cors" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" + + # Audits gems for known security defects (use config/bundler-audit.yml to ignore issues) + gem "bundler-audit", require: false + + # Static analysis for security vulnerabilities [https://brakemanscanner.org/] + gem "brakeman", require: false + + # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] + gem "rubocop-rails-omakase", require: false +end diff --git a/backend/Gemfile.lock b/backend/Gemfile.lock new file mode 100644 index 0000000..686e683 --- /dev/null +++ b/backend/Gemfile.lock @@ -0,0 +1,414 @@ +GEM + remote: https://rubygems.org/ + specs: + action_text-trix (2.1.19) + railties + actioncable (8.1.4.1) + actionpack (= 8.1.4.1) + activesupport (= 8.1.4.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.4.1) + actionpack (= 8.1.4.1) + activejob (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) + mail (>= 2.8.0) + actionmailer (8.1.4.1) + actionpack (= 8.1.4.1) + actionview (= 8.1.4.1) + activejob (= 8.1.4.1) + activesupport (= 8.1.4.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.4.1) + actionview (= 8.1.4.1) + activesupport (= 8.1.4.1) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.1.4.1) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.4.1) + activesupport (= 8.1.4.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6, >= 1.7.2) + activejob (8.1.4.1) + activesupport (= 8.1.4.1) + globalid (>= 0.3.6) + activemodel (8.1.4.1) + activesupport (= 8.1.4.1) + activerecord (8.1.4.1) + activemodel (= 8.1.4.1) + activesupport (= 8.1.4.1) + timeout (>= 0.4.0) + activestorage (8.1.4.1) + actionpack (= 8.1.4.1) + activejob (= 8.1.4.1) + activerecord (= 8.1.4.1) + activesupport (= 8.1.4.1) + marcel (~> 1.0) + activesupport (8.1.4.1) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + json + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + ast (2.4.3) + base64 (0.3.0) + bigdecimal (4.1.3) + bootsnap (1.26.2) + msgpack (~> 1.5) + brakeman (8.1.1) + racc + builder (3.3.0) + bundler-audit (0.9.3) + bundler (>= 1.2.0) + thor (~> 1.0) + concurrent-ruby (1.3.8) + connection_pool (3.0.3) + crass (1.0.8) + date (3.6.0) + debug (1.11.1) + irb (~> 1.10) + reline (>= 0.3.8) + drb (2.2.3) + erb (6.0.7) + erubi (1.13.1) + globalid (1.4.0) + activesupport (>= 6.1) + i18n (1.15.2) + concurrent-ruby (~> 1.0) + io-console (0.9.5) + irb (1.19.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + json (3.1.0) + language_server-protocol (3.17.0.6) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.25.3) + crass (~> 1.0.2) + nokogiri (>= 1.19.5) + mail (2.9.1) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.2.1) + mini_mime (1.1.5) + minitest (6.1.0) + drb (~> 2.0) + prism (>= 1.5, < 3) + msgpack (1.8.7) + net-imap (0.6.8) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.4.0) + timeout + net-smtp (0.5.2) + net-protocol + nio4r (2.7.5) + nokogiri (1.19.7-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.7-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.19.7-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.7-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.19.7-arm64-darwin) + racc (~> 1.4) + nokogiri (1.19.7-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.19.7-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.7-x86_64-linux-musl) + racc (~> 1.4) + parallel (2.3.0) + parser (3.3.14.0) + ast (~> 2.4.1) + racc + pp (0.6.4) + prettyprint + prettyprint (0.2.1) + prism (2.1.0-aarch64-linux-gnu) + prism (2.1.0-aarch64-linux-musl) + prism (2.1.0-arm-linux-gnu) + prism (2.1.0-arm-linux-musl) + prism (2.1.0-arm64-darwin) + prism (2.1.0-x86_64-darwin) + prism (2.1.0-x86_64-linux-gnu) + prism (2.1.0-x86_64-linux-musl) + puma (8.1.2) + nio4r (~> 2.0) + racc (1.8.1) + rack (3.2.9) + rack-session (2.1.2) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.3.0) + rack (>= 1.3) + rackup (2.3.1) + rack (>= 3) + rails (8.1.4.1) + actioncable (= 8.1.4.1) + actionmailbox (= 8.1.4.1) + actionmailer (= 8.1.4.1) + actionpack (= 8.1.4.1) + actiontext (= 8.1.4.1) + actionview (= 8.1.4.1) + activejob (= 8.1.4.1) + activemodel (= 8.1.4.1) + activerecord (= 8.1.4.1) + activestorage (= 8.1.4.1) + activesupport (= 8.1.4.1) + bundler (>= 1.15.0) + railties (= 8.1.4.1) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.7.2) + loofah (~> 2.25, >= 2.25.3) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.1.4.1) + actionpack (= 8.1.4.1) + activesupport (= 8.1.4.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.4.2) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort + rdoc (8.1.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort + regexp_parser (2.13.4) + reline (0.7.0) + io-console (~> 0.5) + rubocop (1.92.3) + json (>= 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (>= 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.11.3, < 3.0) + rubocop-ast (>= 1.49.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.53.0) + ast (~> 2.4) + parser (>= 3.3.7.2) + prism (>= 1.7) + racc + rubocop-performance (1.27.0) + lint_roller (~> 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.38.0) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + securerandom (0.4.1) + sqlite3 (2.10.2-aarch64-linux-gnu) + sqlite3 (2.10.2-aarch64-linux-musl) + sqlite3 (2.10.2-arm-linux-gnu) + sqlite3 (2.10.2-arm-linux-musl) + sqlite3 (2.10.2-arm64-darwin) + sqlite3 (2.10.2-x86_64-darwin) + sqlite3 (2.10.2-x86_64-linux-gnu) + sqlite3 (2.10.2-x86_64-linux-musl) + thor (1.5.0) + timeout (0.6.1) + tsort (0.2.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.3.0) + unicode-emoji (~> 4.3) + unicode-emoji (4.3.0) + uri (1.1.2) + useragent (0.16.11) + websocket-driver (0.9.0) + base64 + websocket-extensions (>= 0.2.0) + websocket-extensions (0.2.0) + zeitwerk (2.8.3) + +PLATFORMS + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin + x86_64-darwin + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bootsnap + brakeman + bundler-audit + debug + puma (>= 5.0) + rails (~> 8.1.4, >= 8.1.4.1) + rubocop-rails-omakase + sqlite3 (>= 2.1) + tzinfo-data + +CHECKSUMS + action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009 + actioncable (8.1.4.1) sha256=007670f7297973e94809e9f32a56624a7aa60b6e9d6696cd078064ce86d1c7fc + actionmailbox (8.1.4.1) sha256=18b43dd842bf3a3e31b8e38b7917c21e48c128fc8b263c893481cc66ee1a8f78 + actionmailer (8.1.4.1) sha256=a7b71dedf744e48dd6751e97350634edce9a2f7beeceac332dcccb91729ad066 + actionpack (8.1.4.1) sha256=8c6f2e7cbd2653ef0539bde1ff20eb3e2e264e366affe56f0ba7f06d3670cb4b + actiontext (8.1.4.1) sha256=fb59611dc16e2b6bbfcec66793acfae6cdd64b1e35ef3f9175424f31e62c38da + actionview (8.1.4.1) sha256=d25b4d9cf8d0c0195ffcfe8b2cf3fcbe6fea54fd7c17f1a9cb8182881463f12b + activejob (8.1.4.1) sha256=82c4c9311ea1016d5f7f134a0c5f9b6527cad5a6237f5f3f60aa17984ef36229 + activemodel (8.1.4.1) sha256=063caf105372fbc98b2d789e4be23de63ac5c043f7d9330f04e2caddb7012805 + activerecord (8.1.4.1) sha256=bd65599ca0b5d210937f835d42c7aff69d271741c75aab022730be6cbce67e87 + activestorage (8.1.4.1) sha256=0f4e2f114f3584723a80a2c089aacc6170e765a0b2c385c9782e26ed78f05c66 + activesupport (8.1.4.1) sha256=16ac4f341ca65c85a1fcdb8ac73f68891aae9e3c4a6f9c3a27daed8b00017ed7 + ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 + base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b + bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66 + bootsnap (1.26.2) sha256=f0d749dcda6bf5e3d324bc7e126009b2127d2b83db74273d8ded3b4c8e322bb7 + brakeman (8.1.1) sha256=a038d25ef911be910171222d2355e11ff5b5048cc4e2f08e7a4c11eccd4f418a + builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f + bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac + bundler-audit (0.9.3) sha256=81c8766c71e47d0d28a0f98c7eed028539f21a6ea3cd8f685eb6f42333c9b4e9 + concurrent-ruby (1.3.8) sha256=b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1 + connection_pool (3.0.3) sha256=e0f8ee3ee0039396753e06e8a2dde0ef028e40f7df29e97f57da7577c489cb5e + crass (1.0.8) sha256=7a0145c7a2c59f8e7923b3a69ce819c444823a00a5127d805298fea13be24efe + date (3.6.0) sha256=18ac945c4e24ebd93534f8eab8c2fd8c5604b3e977105b3798d62a1e8d27b580 + debug (1.11.1) sha256=2e0b0ac6119f2207a6f8ac7d4a73ca8eb4e440f64da0a3136c30343146e952b6 + drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373 + erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92 + erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9 + globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427 + i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5 + io-console (0.9.5) sha256=83dd9bbf4c4680416629245b39cd4212eb5f4d9a4ea91804870c1f6b846414d5 + irb (1.19.0) sha256=55ee56acbdd6c9fe06a2e6909f46a24e5c41f45f16906bab04e8049cf46f1d27 + json (3.1.0) sha256=3ce7ccf8fde58960177a3a756c31f292a4c1e1dedee884547096a5b0604e3bd8 + language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 + lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 + loofah (2.25.3) sha256=545f14eef0cc2a7de80df560530d593232b7c07e515c5c4e37532d9cb5b0185c + mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8 + marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f + mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef + minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e + msgpack (1.8.7) sha256=dfefec761b5f9047e6e8d95d2c7f8af4b3725d984a01942adc533aa819a2df33 + net-imap (0.6.8) sha256=eb30bb62227b64a3af6b518b04b2375113d69f68f15de59b0193b07d98acf6d9 + net-pop (0.1.2) sha256=848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3 + net-protocol (0.4.0) sha256=f9f90c8c6f64794a45160bf422177a336db12809de3beeeaa26b88fcd2e8c853 + net-smtp (0.5.2) sha256=35103cc04d6b2d94632f9928ede07483c24b70b9c0db1f231fea43909b678f3c + nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1 + nokogiri (1.19.7-aarch64-linux-gnu) sha256=8f5e15d299602456406e1f03a9f3456cceb33a0722811e818d2ee2214eb4c84a + nokogiri (1.19.7-aarch64-linux-musl) sha256=efe0c3602e6e54521bc21c681930ce5568e2d11203de17400710b2b3ca2e4cb4 + nokogiri (1.19.7-arm-linux-gnu) sha256=7fd1907125691aa89e838cc91161761c758b4e17bb32f0dd9b5515a82cc759af + nokogiri (1.19.7-arm-linux-musl) sha256=28d0ff0c87b6bb2e56580323a6fb049d5d4a02b94f0958fdd47e9ac146991c77 + nokogiri (1.19.7-arm64-darwin) sha256=f27d7f25f4873fbc3aa35a2cc2fb680c98555fec1925348da439d0869d541142 + nokogiri (1.19.7-x86_64-darwin) sha256=508e81e8c5f84aaa240dce981bf1c43faae60808726f0ce7024ee92effc5cafe + nokogiri (1.19.7-x86_64-linux-gnu) sha256=25865ccb462f714e712fdf8906fde07849cb6704a808e3d629d75baa5af5dd3b + nokogiri (1.19.7-x86_64-linux-musl) sha256=464d1f3dfb0d53cf54c0c6a7e23e8e91cf68ec3cafc2b27dc4a7682f2d9bf546 + parallel (2.3.0) sha256=f75a3e904101ce6a1ccb6b8dc800cbafd42166d83330192438dcf29395167a6f + parser (3.3.14.0) sha256=62f8f76af7b919425ee2d811880e9dcb8011ab40bfd59970dfb583141697e58f + pp (0.6.4) sha256=dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570 + prettyprint (0.2.1) sha256=d555d57ea6d7cf001d4774b693546a6bd88bec1e778ddffb5c60b68ceec4b7d4 + prism (2.1.0-aarch64-linux-gnu) sha256=808dddc72def68e1a0463689414c97e0ba211938eddbab05387a4844aa2b3ec2 + prism (2.1.0-aarch64-linux-musl) sha256=dd1a0732620c1e575dabb07a297a62911fabd72f8e20ce850b522a866f877930 + prism (2.1.0-arm-linux-gnu) sha256=96b2426b9dbab05448c4add735619929042be3cd7e871ff186468121b62bcfa8 + prism (2.1.0-arm-linux-musl) sha256=00ef918e42a3dc98f11a461bf473586a3424b0f78bee8a4e43b5a65a5f5e2cd0 + prism (2.1.0-arm64-darwin) sha256=2d0c2e3e011cfd89c041940907d3ff3def379d7b0f2ba158d1d42238e8ad8afc + prism (2.1.0-x86_64-darwin) sha256=6c645d8e6afc742956c7518220ce5106367727c4d9980ac9ab386d55004ddab4 + prism (2.1.0-x86_64-linux-gnu) sha256=b2b647afce09551e650b8bb3e2fc91d7d73d392a09534ca307ec0d619c33bfd4 + prism (2.1.0-x86_64-linux-musl) sha256=249f45981726923e259b927902246219fa25ad10a76f43849c9aee1a3d3ec5b8 + puma (8.1.2) sha256=3a6d9a34c9a4d0175eabd11b703939b5d43ebe08bc2534ac7dfd4df33a6ceedc + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f + rack (3.2.9) sha256=8235c1d08f0c461bedcff4413bbeba888173e5b09e1332ae951c98f0ee460dcc + rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 + rack-test (2.3.0) sha256=b118d177cc002c572fc1b6fd8d19c9ed5881a36e8d6f689f9e618f9f861241e8 + rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868 + rails (8.1.4.1) sha256=365c3a0ad2713bd6e60628e5e826622d4ca8dee60b5a7e560e9b20844e9650bc + rails-dom-testing (2.3.0) sha256=8acc7953a7b911ca44588bf08737bc16719f431a1cc3091a292bca7317925c1d + rails-html-sanitizer (1.7.2) sha256=a21ef45b7a6639fc8e2282473c547514cb86ae271616162a946bf89148fa2424 + railties (8.1.4.1) sha256=ff2ef4b5a62cbc89811f88be11c776e2ed71b14dd012eae6a494d37994aa9782 + rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a + rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 + rbs (4.2.0) sha256=51f7b886dcc05bc09e10b901daa6a81829f6adc03101d6ca9ea4aac6103e0674 + rdoc (8.1.0) sha256=befc37880a5cfd36dcb176c748b5fd5ee39dd3536a75e81824e4972ce230f60a + regexp_parser (2.13.4) sha256=1d0547814f57e6f00946957bd0ca201bc42f42cfb08eee89df60998aedcd8a3b + reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d + rubocop (1.92.3) sha256=fd77feac46e8e91c3a534f868a1702c59f5bf8173515fd00a3c6ce1198672ff6 + rubocop-ast (1.53.0) sha256=027984d28485d6502ae4c72f9341080f54f538599f5dbb54f81875a4ddcad574 + rubocop-performance (1.27.0) sha256=eeeb1374d062a368ee1c787b70eb0b0cc4b184cb1f8565f424760946146d61ce + rubocop-rails (2.38.0) sha256=6e2b7c532efa95e3050371bec20b8f5b025662acead8bc70ee31f0e3e6fa2f06 + rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d + ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 + securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 + sqlite3 (2.10.2-aarch64-linux-gnu) sha256=e9aea2c2b3476fc875dd8a89313a9a2862818519c0186bfb5b56d6f57bb08d98 + sqlite3 (2.10.2-aarch64-linux-musl) sha256=4986fc40cdf21342362b72a941df28e95cfe0e644f3ad2532d948b157c39dbee + sqlite3 (2.10.2-arm-linux-gnu) sha256=762f609ef891463226b472d3df66aea84d5466ff4376d3ccf4a059718c4ce9c9 + sqlite3 (2.10.2-arm-linux-musl) sha256=833623eaf1157b1b85d1c0830e3e8f9beb3bb95a9bec3d252f20557a50e9803a + sqlite3 (2.10.2-arm64-darwin) sha256=5b0d235ea037e6dcd1b8387a19d73be571917db9f93044d35741cf933a21a37d + sqlite3 (2.10.2-x86_64-darwin) sha256=fd2c67b49d313031af112e172c83ab321681a2b4996bf882eefac50be7bea08f + sqlite3 (2.10.2-x86_64-linux-gnu) sha256=ca92731ab464df9cae503fa1a439a549e2724f6953c8c05a7769b59366e38f15 + sqlite3 (2.10.2-x86_64-linux-musl) sha256=b9f8fc62f3e0eb8966b41de251b492b4c8e9d1b23559beb6e150ad7f8d590941 + thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73 + timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb + tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f + tzinfo (2.0.6) sha256=8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829b + unicode-display_width (3.3.0) sha256=4b7aa66a4b11db50f6f7e98411215cd0dd10eaecb665d36eec5bcacb3fa0b613 + unicode-emoji (4.3.0) sha256=11c02fa73290378c066bb0562cd4c87d8e1b706fbbe0059ca12746a4244de8ce + uri (1.1.2) sha256=89292e98eabbef6248b0a0ed5e7e398e152f83f17560023a6d94a7f492b169fb + useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844 + websocket-driver (0.9.0) sha256=4dfcc6ac0ea1b6771daf5fb54cbbca131e4d5922ea0a65ba2da980370dadbe9f + websocket-extensions (0.2.0) sha256=6fb0d0f687aa8adc8eafa5ce68db36dfd6a8ebf232515040ce27c33c1291e589 + zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5 + +BUNDLED WITH + 4.0.18 diff --git a/backend/Rakefile b/backend/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/backend/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/backend/app/channels/application_cable/channel.rb b/backend/app/channels/application_cable/channel.rb new file mode 100644 index 0000000..d672697 --- /dev/null +++ b/backend/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/backend/app/channels/application_cable/connection.rb b/backend/app/channels/application_cable/connection.rb new file mode 100644 index 0000000..0ff5442 --- /dev/null +++ b/backend/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/backend/app/channels/run_channel.rb b/backend/app/channels/run_channel.rb new file mode 100644 index 0000000..9179e4b --- /dev/null +++ b/backend/app/channels/run_channel.rb @@ -0,0 +1,8 @@ +# Live updates for one run: terminal output, alerts and metrics are pushed +# here after every command and every tick. +class RunChannel < ApplicationCable::Channel + def subscribed + run = Run.find_by(id: params[:run_id]) + run ? stream_for(run) : reject + end +end diff --git a/backend/app/controllers/api/runs_controller.rb b/backend/app/controllers/api/runs_controller.rb new file mode 100644 index 0000000..4935697 --- /dev/null +++ b/backend/app/controllers/api/runs_controller.rb @@ -0,0 +1,36 @@ +module Api + class RunsController < ApplicationController + before_action :set_run, except: :create + + def create + run = Run.start!(params.require(:scenario)) + render json: RunPresenter.new(run).full, status: :created + rescue KeyError + render json: { error: "Unknown scenario" }, status: :unprocessable_content + end + + def show + render json: RunPresenter.new(@run).full + end + + # POST /api/runs/:id/commands { input: "df -h" } + def command + input = params.require(:input).to_s + return render(json: { error: "Command too long" }, status: :unprocessable_content) if input.length > 500 + step = @run.execute!(input) + render json: RunPresenter.new(@run).update(step) + end + + # POST /api/runs/:id/tick { ticks: 1 }: time passes while the player reads. + def tick + step = @run.tick!(params.fetch(:ticks, 1).to_i) + render json: RunPresenter.new(@run).update(step) + end + + private + + def set_run + @run = Run.find(params[:id]) + end + end +end diff --git a/backend/app/controllers/api/scenarios_controller.rb b/backend/app/controllers/api/scenarios_controller.rb new file mode 100644 index 0000000..e49775e --- /dev/null +++ b/backend/app/controllers/api/scenarios_controller.rb @@ -0,0 +1,9 @@ +module Api + class ScenariosController < ApplicationController + def index + render json: Sim::Scenario.all.map { |s| + { key: s.key, title: s.title, topic: s.topic, chapter: s.chapter, summary: s.summary } + } + end + end +end diff --git a/backend/app/controllers/application_controller.rb b/backend/app/controllers/application_controller.rb new file mode 100644 index 0000000..4ac8823 --- /dev/null +++ b/backend/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/backend/app/controllers/concerns/.keep b/backend/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/jobs/application_job.rb b/backend/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /dev/null +++ b/backend/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/backend/app/models/application_record.rb b/backend/app/models/application_record.rb new file mode 100644 index 0000000..b63caeb --- /dev/null +++ b/backend/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/backend/app/models/concerns/.keep b/backend/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/app/models/run.rb b/backend/app/models/run.rb new file mode 100644 index 0000000..bb19fba --- /dev/null +++ b/backend/app/models/run.rb @@ -0,0 +1,43 @@ +# One player's attempt at a scenario. The whole simulated environment lives +# in the `world` JSON column; Sim::Engine does the work, this model just +# loads and saves it and tells listeners what changed. +class Run < ApplicationRecord + STATUSES = %w[active completed].freeze + + validates :status, inclusion: { in: STATUSES } + validate :scenario_exists + + def self.start!(scenario_key) + engine = Sim::Engine.start(scenario_key) + create!(scenario_key: scenario_key, world: engine.world.to_h) + end + + def scenario = Sim::Scenario.find(scenario_key) + + def engine + @engine ||= Sim::Engine.new(Sim::World.new(world), scenario.new) + end + + def execute!(input) = step! { engine.execute(input) } + def tick!(ticks = 1) = step! { engine.tick(ticks) } + + private + + def step! + with_lock do + @engine = nil # pick up the row as locked, not a stale copy + step = yield + self.world = engine.world.to_h + self.status = "completed" if engine.finished? + save! + RunChannel.broadcast_to(self, RunPresenter.new(self).update(step)) + step + end + end + + def scenario_exists + Sim::Scenario.find(scenario_key) + rescue KeyError + errors.add(:scenario_key, "is not a known scenario") + end +end diff --git a/backend/app/presenters/run_presenter.rb b/backend/app/presenters/run_presenter.rb new file mode 100644 index 0000000..66c3b9a --- /dev/null +++ b/backend/app/presenters/run_presenter.rb @@ -0,0 +1,53 @@ +# The JSON shape the frontend works with. `full` is the whole picture (for +# page load); `update` is what a single step changed, plus the live panels. +class RunPresenter + def initialize(run) + @run = run + @engine = run.engine + @world = @engine.world + end + + def full + scenario = @run.scenario + { + id: @run.id, + status: @run.status, + scenario: { + key: scenario.key, title: scenario.title, topic: scenario.topic, + chapter: scenario.chapter, summary: scenario.summary, briefing: scenario.briefing + } + }.merge(live) + end + + def update(step) + { + type: "step", + output: step.output, + exit_code: step.exit_code, + notices: step.notices, + completed: step.completed + }.merge(live) + end + + private + + def live + { + id: @run.id, + status: @run.status, + clock: @world.clock, + time: @world.timestamp, + prompt: @engine.prompt, + objectives: @engine.objectives, + alerts: @world.alerts, + metrics: @world.data["metrics"], + services: services + } + end + + def services + @world.data["hosts"].select { |_, h| h["monitored"] }.to_h do |name, host| + [ name, host["services"].transform_values { |s| s["state"] } ] + end + end +end diff --git a/backend/bin/brakeman b/backend/bin/brakeman new file mode 100755 index 0000000..ace1c9b --- /dev/null +++ b/backend/bin/brakeman @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +ARGV.unshift("--ensure-latest") + +load Gem.bin_path("brakeman", "brakeman") diff --git a/backend/bin/bundler-audit b/backend/bin/bundler-audit new file mode 100755 index 0000000..e2ef226 --- /dev/null +++ b/backend/bin/bundler-audit @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "bundler/audit/cli" + +ARGV.concat %w[ --config config/bundler-audit.yml ] if ARGV.empty? || ARGV.include?("check") +Bundler::Audit::CLI.start diff --git a/backend/bin/ci b/backend/bin/ci new file mode 100755 index 0000000..4137ad5 --- /dev/null +++ b/backend/bin/ci @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "active_support/continuous_integration" + +CI = ActiveSupport::ContinuousIntegration +require_relative "../config/ci.rb" diff --git a/backend/bin/dev b/backend/bin/dev new file mode 100755 index 0000000..5f91c20 --- /dev/null +++ b/backend/bin/dev @@ -0,0 +1,2 @@ +#!/usr/bin/env ruby +exec "./bin/rails", "server", *ARGV diff --git a/backend/bin/rails b/backend/bin/rails new file mode 100755 index 0000000..efc0377 --- /dev/null +++ b/backend/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/backend/bin/rake b/backend/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/backend/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/backend/bin/rubocop b/backend/bin/rubocop new file mode 100755 index 0000000..5a20504 --- /dev/null +++ b/backend/bin/rubocop @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +# Explicit RuboCop config increases performance slightly while avoiding config confusion. +ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) + +load Gem.bin_path("rubocop", "rubocop") diff --git a/backend/bin/setup b/backend/bin/setup new file mode 100755 index 0000000..81be011 --- /dev/null +++ b/backend/bin/setup @@ -0,0 +1,35 @@ +#!/usr/bin/env ruby +require "fileutils" + +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + system! "bin/rails db:reset" if ARGV.include?("--reset") + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + unless ARGV.include?("--skip-server") + puts "\n== Starting development server ==" + STDOUT.flush # flush the output before exec(2) so that it displays + exec "bin/dev" + end +end diff --git a/backend/config.ru b/backend/config.ru new file mode 100644 index 0000000..4a3c09a --- /dev/null +++ b/backend/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/backend/config/application.rb b/backend/config/application.rb new file mode 100644 index 0000000..6980066 --- /dev/null +++ b/backend/config/application.rb @@ -0,0 +1,44 @@ +require_relative "boot" + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +# require "active_storage/engine" +require "action_controller/railtie" +# require "action_mailer/railtie" +# require "action_mailbox/engine" +# require "action_text/engine" +require "action_view/railtie" +require "action_cable/engine" +require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module Backend + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.1 + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w[assets tasks]) + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/backend/config/boot.rb b/backend/config/boot.rb new file mode 100644 index 0000000..988a5dd --- /dev/null +++ b/backend/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/backend/config/bundler-audit.yml b/backend/config/bundler-audit.yml new file mode 100644 index 0000000..e74b3af --- /dev/null +++ b/backend/config/bundler-audit.yml @@ -0,0 +1,5 @@ +# Audit all gems listed in the Gemfile for known security problems by running bin/bundler-audit. +# CVEs that are not relevant to the application can be enumerated on the ignore list below. + +ignore: + - CVE-THAT-DOES-NOT-APPLY diff --git a/backend/config/cable.yml b/backend/config/cable.yml new file mode 100644 index 0000000..75df6fd --- /dev/null +++ b/backend/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: backend_production diff --git a/backend/config/ci.rb b/backend/config/ci.rb new file mode 100644 index 0000000..407cf23 --- /dev/null +++ b/backend/config/ci.rb @@ -0,0 +1,23 @@ +# Run using bin/ci + +CI.run do + step "Setup", "bin/setup --skip-server" + + step "Style: Ruby", "bin/rubocop" + + step "Security: Gem audit", "bin/bundler-audit" + step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error" + step "Tests: Rails", "bin/rails test" + step "Tests: Seeds", "env RAILS_ENV=test bin/rails db:seed:replant" + + # Optional: Run system tests + # step "Tests: System", "bin/rails test:system" + + # Optional: set a green GitHub commit status to unblock PR merge. + # Requires the `gh` CLI and `gh extension install basecamp/gh-signoff`. + # if success? + # step "Signoff: All systems go. Ready for merge and deploy.", "gh signoff" + # else + # failure "Signoff: CI failed. Do not merge or deploy.", "Fix the issues and try again." + # end +end diff --git a/backend/config/credentials.yml.enc b/backend/config/credentials.yml.enc new file mode 100644 index 0000000..446cc88 --- /dev/null +++ b/backend/config/credentials.yml.enc @@ -0,0 +1 @@ +o62rEm9DolcvtasXXRcaBnmZxVkLM9bvBOWE/gu5btsPYxQ71TYK1ubaqafR8r8P1jjcvXT6+H7EfpuUq70Q9IcRpRKEptoFvHzhuNipK/DSEuCDgJ5TqeW6WIyAwGZK4qp+N48vchRN+AwKWWIqVQuWzSriH6sHWrf2Z2efJLn8Gt3hyNXL49C0VyuG91zkKzUs4xdZdOS+efMzLPYN5lPhxe0SyQPrDb4TF0ZA/KRQjvHU7F8nYEqPkNyfQkIDaWS8McZY6tQYVchGovCpW0PthSwjGxlZt8nZq6Nkh0rj38xOKPWzELm4ZTIOxUeDECIamuChVFUfUYktA9eAT7t79eEGu/Enhj0Bswdy0+RyLFj6mniC5Pe6GdpaYcKRMXVK5zg7K16X4IWY7s+s7+9VdJ4SjHhNlW7ju2ArNEUL0fs9SIhj/+v+GNV0bnS/KROiHQrDEqgBNOzrXl+RilV6kKjRYslLoshpEen7jIHZnsKCnZieKkK9--RWOzjBnMi32qz+OJ--S1Iw8smHdl+MpBet5KBp6g== \ No newline at end of file diff --git a/backend/config/database.yml b/backend/config/database.yml new file mode 100644 index 0000000..956ab98 --- /dev/null +++ b/backend/config/database.yml @@ -0,0 +1,31 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + max_connections: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: storage/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: storage/test.sqlite3 + +# SQLite3 write its data on the local filesystem, as such it requires +# persistent disks. If you are deploying to a managed service, you should +# make sure it provides disk persistence, as many don't. +# +# Similarly, if you deploy your application as a Docker container, you must +# ensure the database is located in a persisted volume. +production: + <<: *default + # database: path/to/persistent/storage/production.sqlite3 diff --git a/backend/config/environment.rb b/backend/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/backend/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/backend/config/environments/development.rb b/backend/config/environments/development.rb new file mode 100644 index 0000000..5d5a54e --- /dev/null +++ b/backend/config/environments/development.rb @@ -0,0 +1,62 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Make code changes take effect immediately without server restart. + config.enable_reloading = true + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing. + config.server_timing = true + + # Enable/disable Action Controller caching. By default Action Controller caching is disabled. + # Run rails dev:cache to toggle Action Controller caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } + else + config.action_controller.perform_caching = false + end + + # Change to :null_store to avoid any caching. + config.cache_store = :memory_store + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Append comments with runtime information tags to SQL queries in logs. + config.active_record.query_log_tags_enabled = true + + # Highlight code that enqueued background job in logs. + config.active_job.verbose_enqueue_logs = true + + # Highlight code that triggered redirect in logs. + config.action_dispatch.verbose_redirect_logs = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # The Vite dev server (frontend/) proxies /cable from this origin. + config.action_cable.allowed_request_origins = [ %r{\Ahttp://(localhost|127\.0\.0\.1):5173\z} ] + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true + + # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. + # config.generators.apply_rubocop_autocorrect_after_generate! +end diff --git a/backend/config/environments/production.rb b/backend/config/environments/production.rb new file mode 100644 index 0000000..d9e3c4f --- /dev/null +++ b/backend/config/environments/production.rb @@ -0,0 +1,67 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). + config.eager_load = true + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = true + + # Skip http-to-https redirect for the default health check endpoint. + # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # Log to STDOUT with the current request id as a default log tag. + config.log_tags = [ :request_id ] + config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) + + # Change to "debug" to log everything (including potentially personally-identifiable information!). + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Prevent health checks from clogging up the logs. + config.silence_healthcheck_path = "/up" + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Replace the default in-process memory cache store with a durable alternative. + # config.cache_store = :mem_cache_store + + # Replace the default in-process and non-durable queuing backend for Active Job. + # config.active_job.queue_adapter = :resque + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Only use :id for inspections in production. + config.active_record.attributes_for_inspect = [ :id ] + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/backend/config/environments/test.rb b/backend/config/environments/test.rb new file mode 100644 index 0000000..14bc29e --- /dev/null +++ b/backend/config/environments/test.rb @@ -0,0 +1,42 @@ +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with cache-control for performance. + config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } + + # Show full error reports. + config.consider_all_requests_local = true + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/backend/config/initializers/cors.rb b/backend/config/initializers/cors.rb new file mode 100644 index 0000000..0c5dd99 --- /dev/null +++ b/backend/config/initializers/cors.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins "example.com" +# +# resource "*", +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/backend/config/initializers/filter_parameter_logging.rb b/backend/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..c0b717f --- /dev/null +++ b/backend/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc +] diff --git a/backend/config/initializers/inflections.rb b/backend/config/initializers/inflections.rb new file mode 100644 index 0000000..3860f65 --- /dev/null +++ b/backend/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/backend/config/locales/en.yml b/backend/config/locales/en.yml new file mode 100644 index 0000000..6c349ae --- /dev/null +++ b/backend/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/backend/config/puma.rb b/backend/config/puma.rb new file mode 100644 index 0000000..1c317b4 --- /dev/null +++ b/backend/config/puma.rb @@ -0,0 +1,39 @@ +# This configuration file will be evaluated by Puma. The top-level methods that +# are invoked here are part of Puma's configuration DSL. For more information +# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. +# +# Puma starts a configurable number of processes (workers) and each process +# serves each request in a thread from an internal thread pool. +# +# You can control the number of workers using ENV["WEB_CONCURRENCY"]. You +# should only set this value when you want to run 2 or more workers. The +# default is already 1. You can set it to `auto` to automatically start a worker +# for each available processor. +# +# The ideal number of threads per worker depends both on how much time the +# application spends waiting for IO operations and on how much you wish to +# prioritize throughput over latency. +# +# As a rule of thumb, increasing the number of threads will increase how much +# traffic a given process can handle (throughput), but due to CRuby's +# Global VM Lock (GVL) it has diminishing returns and will degrade the +# response time (latency) of the application. +# +# The default is set to 3 threads as it's deemed a decent compromise between +# throughput and latency for the average Rails application. +# +# Any libraries that use a connection pool or another resource pool should +# be configured to provide at least as many connections as the number of +# threads. This includes Active Record's `pool` parameter in `database.yml`. +threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch("PORT", 3000) + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart + +# Specify the PID file. Defaults to tmp/pids/server.pid in development. +# In other environments, only set the PID file if requested. +pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/backend/config/routes.rb b/backend/config/routes.rb new file mode 100644 index 0000000..b6ed199 --- /dev/null +++ b/backend/config/routes.rb @@ -0,0 +1,15 @@ +Rails.application.routes.draw do + get "up" => "rails/health#show", as: :rails_health_check + + namespace :api do + resources :scenarios, only: :index + resources :runs, only: %i[create show] do + member do + post :command, path: "commands" + post :tick + end + end + end + + mount ActionCable.server => "/cable" +end diff --git a/backend/db/migrate/20261120233133_create_runs.rb b/backend/db/migrate/20261120233133_create_runs.rb new file mode 100644 index 0000000..b84f047 --- /dev/null +++ b/backend/db/migrate/20261120233133_create_runs.rb @@ -0,0 +1,11 @@ +class CreateRuns < ActiveRecord::Migration[8.1] + def change + create_table :runs do |t| + t.string :scenario_key, null: false + t.json :world, null: false, default: {} + t.string :status, null: false, default: "active" + t.timestamps + end + add_index :runs, :scenario_key + end +end diff --git a/backend/db/schema.rb b/backend/db/schema.rb new file mode 100644 index 0000000..3a5721e --- /dev/null +++ b/backend/db/schema.rb @@ -0,0 +1,22 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[8.1].define(version: 2026_11_20_233133) do + create_table "runs", force: :cascade do |t| + t.string "scenario_key", null: false + t.json "world", default: {}, null: false + t.string "status", default: "active", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["scenario_key"], name: "index_runs_on_scenario_key" + end +end diff --git a/backend/db/seeds.rb b/backend/db/seeds.rb new file mode 100644 index 0000000..4fbd6ed --- /dev/null +++ b/backend/db/seeds.rb @@ -0,0 +1,9 @@ +# This file should ensure the existence of records required to run the application in every environment (production, +# development, test). The code here should be idempotent so that it can be executed at any point in every environment. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Example: +# +# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| +# MovieGenre.find_or_create_by!(name: genre_name) +# end diff --git a/backend/lib/sim/engine.rb b/backend/lib/sim/engine.rb new file mode 100644 index 0000000..aaba6c6 --- /dev/null +++ b/backend/lib/sim/engine.rb @@ -0,0 +1,78 @@ +module Sim + # Drives one run: feeds input to the Shell, advances the clock, lets the + # scenario react, and works out which objectives just got completed. + class Engine + Step = Struct.new(:output, :exit_code, :notices, :completed, keyword_init: true) + + attr_reader :world, :scenario + + def self.start(scenario_key) + scenario = Scenario.find(scenario_key).new + world = World.new(scenario.build_world) + world.record_metrics + new(world, scenario) + end + + def initialize(world, scenario) + @world = world.is_a?(World) ? world : World.new(world) + @scenario = scenario + end + + def execute(input) + world.history << { "tick" => world.clock, "host" => world.current_host, "input" => input.to_s.strip } + world.history.shift while world.history.size > 500 + result = Shell.new(world, scenario).run(input) + notices, completed = advance(1) + Step.new(output: result.output, exit_code: result.exit_code, notices: notices, completed: completed) + end + + # Let time pass without a command (the UI calls this every few seconds). + def tick(ticks = 1) + notices, completed = advance(ticks) + Step.new(output: "", exit_code: 0, notices: notices, completed: completed) + end + + def prompt + s = world.session + dir = s["cwd"] == world.home ? "~" : s["cwd"].sub(/\A#{Regexp.escape(world.home)}\//, "~/") + "#{s['user']}@#{s['host']}:#{dir}#{s['user'] == 'root' ? '#' : '$'}" + end + + def objectives + scenario.objectives.map do |o| + { id: o.id, title: o.title, done: world.data["completed"].include?(o.id) } + end + end + + def finished? = scenario.objectives.all? { |o| world.data["completed"].include?(o.id) } + + private + + # Messages the scenario wants shown (alerts, story beats) go through + # world["messages"]; we drain them here so each is delivered once. + def advance(ticks) + ticks.clamp(1, 30).times do + world.clock += 1 + scenario.tick(world) + world.record_metrics + end + notices = world.data["messages"].dup + world.data["messages"].clear + [ notices, check_objectives ] + end + + # Objectives are a story, so they complete in order: one can only tick + # off once the ones before it are done (several may finish in one step). + def check_objectives + done = world.data["completed"] + newly = [] + scenario.objectives.each do |o| + next if done.include?(o.id) + break unless o.check.call(world) + done << o.id + newly << { id: o.id, title: o.title } + end + newly + end + end +end diff --git a/backend/lib/sim/scenario.rb b/backend/lib/sim/scenario.rb new file mode 100644 index 0000000..1e0fca6 --- /dev/null +++ b/backend/lib/sim/scenario.rb @@ -0,0 +1,124 @@ +module Sim + # Base class for a chapter of the story. A scenario provides: + # - the starting World + # - objectives, each checked against the World after every step + # - time-based behaviour (#tick) that makes incidents happen and evolve + # - hooks the Shell calls so the scenario can react to what the player does + class Scenario + Objective = Struct.new(:id, :title, :hint, :check, keyword_init: true) + + class << self + def all = Scenarios::ALL.sort_by(&:chapter) + def find(key) = all.find { |s| s.key == key } || raise(KeyError, "Unknown scenario #{key}") + + attr_accessor :key, :title, :chapter, :topic, :summary, :briefing + end + + def key = self.class.key + + def objectives = [] + + def build_world + raise NotImplementedError + end + + # Called once per tick, after the player's command (or when time passes on its own). + def tick(world); end + + # Hooks the Shell calls. Defaults do the generic, realistic thing. + def on_inspect(world, kind, target) + world.history.last&.then { |h| (h["inspected"] ||= []) << [ kind.to_s, target ] } + end + + def on_file_changed(world, path); end + def on_ssh(world, host); end + + def on_kill(world, process, _signal) + world.processes.delete(process) + if process["service"] && world.service_processes(process["service"]).empty? + svc = world.service(process["service"]) + svc["state"] = "failed" + svc["failed_at"] = world.clock + world.journal(process["service"], "#{process['service']}.service: Main process exited, code=killed, status=9/KILL") + end + end + + # Returns an error message string, or nil on success. + def on_service(world, name, action) + svc = world.service(name) + case action + when "stop" + stop_service(world, name) + when "start", "restart" + stop_service(world, name) if action == "restart" + error = start_blocker(world, name) + if error + svc["state"] = "failed" + svc["failed_at"] = world.clock + world.journal(name, error) + world.journal(name, "#{name}.service: Failed with result 'exit-code'.") + return "Job for #{name}.service failed because the control process exited with error code.\n" \ + "See \"systemctl status #{name}\" and \"journalctl -u #{name}\" for details." + end + start_service(world, name) + end + nil + end + + # Return a log line explaining why the service can't start, or nil. + def start_blocker(_world, _name) = nil + + def stop_service(world, name, host: world.current_host) + world.processes(host).reject! { |p| p["service"] == name } + svc = world.service(name, host) + svc["state"] = "inactive" + world.journal(name, "Stopped #{svc['description']}.", host) + end + + def start_service(world, name, host: world.current_host) + svc = world.service(name, host) + svc["state"] = "active" + svc["started_at"] = world.clock + Array(svc["spawn"]).each do |spec| + world.processes(host) << spec.merge("pid" => world.next_pid(host), "service" => name) + end + svc["pid"] = world.service_processes(name, host).first&.dig("pid") + world.journal(name, "Started #{svc['description']}.", host) + after_start(world, name, host) + end + + def after_start(_world, _name, _host); end + + # [status, body] for curl, or nil if the host doesn't resolve. + def http(_world, _url) = nil + + def hint_for(world) + objectives.find { |o| !completed?(world, o) }&.hint + end + + def completed?(world, objective) + world.data["completed"].include?(objective.id) + end + + # --- helpers for subclasses -------------------------------------------- + + def ran?(world, pattern, host: nil, since: 0) + world.history.any? do |h| + h["tick"] >= since && (host.nil? || h["host"] == host) && h["input"].match?(pattern) + end + end + + def inspected?(world, kind, target = nil, since: 0) + world.history.any? do |h| + h["tick"] >= since && Array(h["inspected"]).any? do |k, t| + k == kind.to_s && (target.nil? || t.to_s.start_with?(target)) + end + end + end + + def empty_world(clock: 0) + { "clock" => clock, "hosts" => {}, "session" => {}, "alerts" => [], "metrics" => {}, + "history" => [], "flags" => {}, "fired" => [], "completed" => [], "messages" => [] } + end + end +end diff --git a/backend/lib/sim/scenarios.rb b/backend/lib/sim/scenarios.rb new file mode 100644 index 0000000..77d5968 --- /dev/null +++ b/backend/lib/sim/scenarios.rb @@ -0,0 +1,10 @@ +module Sim + # Every playable chapter. Each one stands on its own, so the order of the + # story can change without touching the engine. + module Scenarios + ALL = [ + LinuxDiskFull, + MonitoringMemoryLeak + ].freeze + end +end diff --git a/backend/lib/sim/scenarios/linux_disk_full.rb b/backend/lib/sim/scenarios/linux_disk_full.rb new file mode 100644 index 0000000..ae35eaa --- /dev/null +++ b/backend/lib/sim/scenarios/linux_disk_full.rb @@ -0,0 +1,116 @@ +module Sim + module Scenarios + # Chapter: the site is down because the disk filled up, and the app + # crashed trying to write its logs. The fix has to stick: if debug + # logging stays on, the disk fills up again a few minutes later. + class LinuxDiskFull < Scenario + self.key = "linux-disk-full" + self.chapter = 4 + self.topic = "Linux" + self.title = "The disk is full" + self.summary = "SSH into the server, find what filled the disk, and bring the crashed app back." + self.briefing = <<~TEXT + Your phone buzzes: "shop.example is showing 502 errors!" + You're on call. The shop runs on a server called web-01. + Read ~/on-call.md if you need a reminder, then go and fix it. + TEXT + + DEBUG_GROWTH = (1.5 * World::GB).round + WEB = "web-01" + + def build_world + data = empty_world + data["hosts"]["laptop"] = ShopWorld.laptop + data["hosts"][WEB] = ShopWorld.web01(debug_log_size: 0, log_level: "debug") + data["session"] = { "host" => "laptop", "user" => "dev", "cwd" => "/home/dev" } + world = World.new(data) + + ShopWorld.boot(self, world, "postgresql", "nginx", "shop-worker", "shop-web") + fill_disk(world) + crash_web(world, at: 0) + + world.fire_alert("SiteDown", "severity" => "critical", "summary" => "https://shop.example/health is returning 502") + data + end + + def objectives + [ + Objective.new(id: "connect", title: "Log in to web-01 over SSH", + hint: "Your laptop can't see the server's services. Run `ssh web-01`.", + check: ->(w) { w.flags.key?("visited_#{WEB}") }), + Objective.new(id: "diagnose", title: "Find out why shop-web stopped", + hint: "Ask systemd: `systemctl status shop-web`, then read more with `journalctl -u shop-web`.", + check: ->(w) { inspected?(w, :status, "shop-web") || inspected?(w, :journal, "shop-web") }), + Objective.new(id: "find-culprit", title: "Find what is filling the disk", + hint: "`df -h` shows how full the disk is. `du -sh /var/log/*` shows which folder is big. Keep drilling in.", + check: ->(w) { inspected?(w, :du, "/var/log/shop") || inspected?(w, :ls, "/var/log/shop") }), + Objective.new(id: "free-space", title: "Free up disk space (get below 80%)", + hint: "That debug.log is huge. `sudo truncate -s 0 /var/log/shop/debug.log` empties it (or `sudo rm` it).", + check: ->(w) { w.disk_percent(WEB) < 80 }), + Objective.new(id: "stop-debug", title: "Turn off debug logging so it doesn't refill", + hint: "The log level is set in /etc/shop/web.env. Try `sudo sed -i 's/LOG_LEVEL=debug/LOG_LEVEL=info/' /etc/shop/web.env`.", + check: ->(w) { w.env_value("/etc/shop/web.env", "LOG_LEVEL", WEB) != "debug" }), + Objective.new(id: "recover", title: "Restart shop-web and check the site is back", + hint: "Config is read at startup: `sudo systemctl restart shop-web`, then `curl https://shop.example/health`.", + check: lambda { |w| + svc = w.service("shop-web", WEB) + svc["state"] == "active" && svc["loaded_log_level"] != "debug" && + w.flags["last_curl_ok"].to_i >= svc["started_at"].to_i + }) + ] + end + + def on_ssh(world, host) + world.flags["visited_#{host}"] ||= world.clock + end + + def after_start(world, name, host) + return unless name == "shop-web" + world.service(name, host)["loaded_log_level"] = world.env_value("/etc/shop/web.env", "LOG_LEVEL", WEB) + end + + def start_blocker(world, name) + return unless name == "shop-web" && world.disk_full?(WEB) + "Errno::ENOSPC: No space left on device @ rb_sysopen - /srv/shop/current/tmp/pids/server.pid" + end + + def tick(world) + web = world.service("shop-web", WEB) + if web["state"] == "active" && web["loaded_log_level"] == "debug" + world.grow_file("/var/log/shop/debug.log", DEBUG_GROWTH, WEB) + if world.disk_full?(WEB) + crash_web(world, at: world.clock) + world.data["messages"] << { "kind" => "alert", "text" => "[ALERT] SiteDown: shop-web crashed again. The disk filled back up." } + end + end + + if web["state"] == "active" && world.alerts.any? { |a| a["id"] == "SiteDown" && a["state"] == "firing" } + world.resolve_alert("SiteDown") + world.data["messages"] << { "kind" => "resolved", "text" => "[RESOLVED] SiteDown: shop.example is answering again." } + elsif web["state"] != "active" + world.fire_alert("SiteDown", "severity" => "critical", "summary" => "https://shop.example/health is returning 502") + end + end + + def http(world, url) = ShopWorld.http(world, url) + + private + + def fill_disk(world) + room = world.disk(WEB)["size"] - world.disk_used(WEB) + world.grow_file("/var/log/shop/debug.log", room, WEB) + end + + def crash_web(world, at:) + world.processes(WEB).reject! { |p| p["service"] == "shop-web" } + svc = world.service("shop-web", WEB) + svc["state"] = "failed" + svc["failed_at"] = at + world.journal("shop-web", "Errno::ENOSPC: No space left on device @ io_write - /var/log/shop/debug.log", WEB) + world.journal("shop-web", "puma: shutting down after unhandled error", WEB) + world.journal("shop-web", "shop-web.service: Main process exited, code=exited, status=1/FAILURE", WEB) + world.journal("shop-web", "shop-web.service: Failed with result 'exit-code'.", WEB) + end + end + end +end diff --git a/backend/lib/sim/scenarios/monitoring_memory_leak.rb b/backend/lib/sim/scenarios/monitoring_memory_leak.rb new file mode 100644 index 0000000..d6ceb0f --- /dev/null +++ b/backend/lib/sim/scenarios/monitoring_memory_leak.rb @@ -0,0 +1,127 @@ +module Sim + module Scenarios + # Chapter: a memory alert fires. The background worker's memory keeps + # climbing because the last deploy set its report cache to unlimited. + # Restarting alone only buys time; the real fix is the config. + class MonitoringMemoryLeak < Scenario + self.key = "monitoring-memory-leak" + self.chapter = 5 + self.topic = "Monitoring" + self.title = "Memory is climbing" + self.summary = "A memory alert fires. Use the dashboard and the server to trace the cause and fix it for good." + self.briefing = <<~TEXT + It's a quiet afternoon. The site is up and the dashboard looks calm. + Keep an eye on the memory graph for web-01. Monitoring will page you + if something goes wrong. (Type `alerts` at any time.) + TEXT + + WEB = "web-01" + WORKER = "shop-worker" + LEAK_PER_TICK = 170 + # Once paged, the leak slows down so a beginner has time to investigate + # before the kernel starts killing processes. + LEAK_AFTER_ALERT = 40 + LEAK_STARTS_AT = 2 + ALERT_AT = 85 + RECOVERED_BELOW = 70 + OOM_AT = 98 + + def build_world + data = empty_world + data["hosts"]["laptop"] = ShopWorld.laptop + data["hosts"][WEB] = ShopWorld.web01(cache_max: "0 # 0 = unlimited (changed in 41e2c9a for big exports)") + data["session"] = { "host" => "laptop", "user" => "dev", "cwd" => "/home/dev" } + world = World.new(data) + ShopWorld.boot(self, world, "postgresql", "nginx", "shop-web", WORKER) + data + end + + def objectives + [ + Objective.new(id: "see-alert", title: "Look at the alert that just fired", + hint: "Wait for the memory graph to climb, then run `alerts`.", + check: ->(w) { (t = alert_fired_at(w)) && inspected?(w, :alerts, since: t) }), + Objective.new(id: "connect", title: "Log in to web-01", + hint: "The alert is about web-01. Run `ssh web-01`.", + check: ->(w) { w.current_host == WEB || w.flags.key?("visited_#{WEB}") }), + Objective.new(id: "find-process", title: "Find the process using the memory", + hint: "`free -h` shows total memory. `ps aux --sort=-%mem` or `top` shows which process is using it.", + check: ->(w) { w.history.any? { |h| h["host"] == WEB && Array(h["inspected"]).any? { |k, _| k == "ps" } } }), + Objective.new(id: "trace-cause", title: "Trace the cause in the worker's logs or config", + hint: "It's the shop-worker. Read its logs with `journalctl -u shop-worker`, and its config in /etc/shop/worker.env.", + check: ->(w) { inspected?(w, :journal, WORKER) || inspected?(w, :read, "/etc/shop/worker.env") }), + Objective.new(id: "fix-config", title: "Give the report cache a limit", + hint: "Set a real limit, for example: `sudo sed -i 's/REPORT_CACHE_MAX=0.*/REPORT_CACHE_MAX=500/' /etc/shop/worker.env`.", + check: ->(w) { cache_limit(w).positive? }), + Objective.new(id: "recover", title: "Restart the worker and watch memory recover", + hint: "`sudo systemctl restart shop-worker`, then watch the graph drop and the alert resolve.", + check: lambda { |w| + w.service(WORKER, WEB)["state"] == "active" && w.service(WORKER, WEB)["loaded_cache_max"].to_i.positive? && + w.memory_percent(WEB) < RECOVERED_BELOW && w.firing_alerts.none? { |a| a["id"] == "HighMemoryUsage" } + }) + ] + end + + def on_ssh(world, host) + world.flags["visited_#{host}"] ||= world.clock + end + + def after_start(world, name, host) + return unless name == WORKER + world.service(name, host)["loaded_cache_max"] = cache_limit(world) + world.service(name, host)["cache_entries"] = 0 + end + + def tick(world) + leak(world) if world.clock >= LEAK_STARTS_AT + percent = world.memory_percent(WEB) + + if percent >= ALERT_AT && world.firing_alerts.none? { |a| a["id"] == "HighMemoryUsage" } + world.fire_alert("HighMemoryUsage", "severity" => "warning", "host" => WEB, + "summary" => "web-01 memory usage is #{percent}% (threshold #{ALERT_AT}%)") + world.flags["alert_fired_at"] ||= world.clock + world.data["messages"] << { "kind" => "alert", "text" => "[ALERT] HighMemoryUsage on web-01: memory at #{percent}%. Run `alerts` for details." } + elsif percent < RECOVERED_BELOW && world.firing_alerts.any? { |a| a["id"] == "HighMemoryUsage" } + world.resolve_alert("HighMemoryUsage") + world.data["messages"] << { "kind" => "resolved", "text" => "[RESOLVED] HighMemoryUsage on web-01: memory back to #{percent}%." } + end + + oom_kill(world) if percent >= OOM_AT + end + + def http(world, url) = ShopWorld.http(world, url) + + private + + def alert_fired_at(world) = world.flags["alert_fired_at"] + + def cache_limit(world) + world.env_value("/etc/shop/worker.env", "REPORT_CACHE_MAX", WEB).to_s[/\A\s*(\d+)/, 1].to_i + end + + def leak(world) + svc = world.service(WORKER, WEB) + return unless svc["state"] == "active" && svc["loaded_cache_max"].to_i.zero? + worker = world.service_processes(WORKER, WEB).first or return + worker["mem_mb"] += world.flags["alert_fired_at"] ? LEAK_AFTER_ALERT : LEAK_PER_TICK + worker["cpu"] = 38.0 + svc["cache_entries"] = svc["cache_entries"].to_i + 6_000 + world.clock * 37 + world.journal(WORKER, "ReportExportJob: report cache now #{svc['cache_entries']} entries (limit: none, REPORT_CACHE_MAX=0)", WEB) + end + + # The kernel picks the biggest process and kills it; systemd restarts the + # worker, which starts leaking again from scratch. + def oom_kill(world) + victim = world.processes(WEB).max_by { |p| p["mem_mb"] } + world.processes(WEB).delete(victim) + world.append_line("/var/log/syslog", "#{world.timestamp} web-01 kernel: Out of memory: Killed process #{victim['pid']} (#{victim['command']})", WEB) + world.data["messages"] << { "kind" => "alert", "text" => "[ALERT] web-01 ran out of memory. The kernel killed PID #{victim['pid']} (#{victim['command']})." } + return unless victim["service"] + world.journal(victim["service"], "#{victim['service']}.service: A process of this unit has been killed by the OOM killer.", WEB) + world.journal(victim["service"], "#{victim['service']}.service: Scheduled restart job, restart counter is at #{world.clock}.", WEB) + stop_service(world, victim["service"], host: WEB) + start_service(world, victim["service"], host: WEB) + end + end + end +end diff --git a/backend/lib/sim/shell.rb b/backend/lib/sim/shell.rb new file mode 100644 index 0000000..e93f6b2 --- /dev/null +++ b/backend/lib/sim/shell.rb @@ -0,0 +1,562 @@ +require "shellwords" + +module Sim + # Interprets what the player types into the fake terminal. It understands a + # small, realistic subset of bash: sudo, pipes into simple filters, `&&`, + # and `>` / `>>` redirection. Every command reads and changes the World; + # nothing ever touches the real machine. + class Shell + Result = Struct.new(:output, :exit_code, keyword_init: true) + + FILTERS = %w[grep head tail sort wc].freeze + + def initialize(world, scenario) + @world = world + @scenario = scenario + end + + def run(input) + input = input.to_s.strip + return Result.new(output: "", exit_code: 0) if input.empty? + + outputs = [] + code = 0 + input.split(/\s*&&\s*/).each do |segment| + result = run_pipeline(segment) + outputs << result.output unless result.output.empty? + code = result.exit_code + break unless code.zero? + end + Result.new(output: outputs.join("\n"), exit_code: code) + end + + private + + attr_reader :world, :scenario + + def run_pipeline(segment) + stages = segment.split(/\s+\|\s+/) + first, redirect = split_redirect(stages.shift) + argv = tokenize(first) + return argv if argv.is_a?(Result) + + result = dispatch(argv, redirect: redirect) + stages.each do |stage| + filter = tokenize(stage) + return filter if filter.is_a?(Result) + result = apply_filter(filter, result.output) + end + result + end + + def tokenize(text) + Shellwords.split(text.to_s) + rescue ArgumentError + Result.new(output: "bash: syntax error: unmatched quote", exit_code: 2) + end + + def split_redirect(text) + if (m = text.match(/\A(.*?)\s*(>>?)\s*(\S+)\s*\z/)) && !text.start_with?("sed ") + [ m[1].presence || ":", { mode: m[2], path: m[3] } ] + else + [ text, nil ] + end + end + + def dispatch(argv, redirect: nil, sudo: false) + name, *args = argv + return dispatch(args, redirect: redirect, sudo: true) if name == "sudo" && args.any? + return ok("usage: sudo command") if name == "sudo" + + @sudo = sudo || root? + args = args.flat_map { |a| expand_glob(a) } unless %w[grep sed echo].include?(name) + handler = "cmd_#{name.to_s.tr('-', '_')}" + result = + if name == ":" then ok("") + elsif respond_to?(handler, true) && !command_available?(name) + fail("#{name}: this is your laptop. The services run on the servers, so `ssh web-01` first.", 127) + elsif respond_to?(handler, true) then send(handler, args) + else fail("bash: #{name}: command not found", 127) + end + redirect ? write_redirect(result, redirect) : result + end + + def command_available?(name) + remote_only = %w[systemctl journalctl] + !(remote_only.include?(name) && !world.host["linux_server"]) + end + + # `/var/log/*` style globs, matched against one directory level like bash. + def expand_glob(arg) + return [ arg ] unless arg.include?("*") || arg.include?("?") + dir, pattern = File.split(arg) + base = world.resolve(dir) + return [ arg ] unless world.directory?(base) + matches = world.children(base).map(&:first).select { |name| File.fnmatch(pattern, name) } + matches.empty? ? [ arg ] : matches.map { |name| dir == "." && !arg.start_with?("./") ? name : File.join(dir, name) } + end + + # --- result helpers ----------------------------------------------------- + + def ok(text) = Result.new(output: text.to_s, exit_code: 0) + def fail(text, code = 1) = Result.new(output: text.to_s, exit_code: code) + def root? = world.session["user"] == "root" + def host_name = world.current_host + + def writable?(path) + @sudo || path.start_with?(world.home + "/") || path.start_with?("/tmp/") + end + + def denied(cmd, path) = fail("#{cmd}: cannot open '#{path}': Permission denied\n(hint: system files need `sudo`)") + + def human(bytes) + units = %w[B K M G T] + value = bytes.to_f + unit = 0 + while value >= 1024 && unit < units.size - 1 + value /= 1024 + unit += 1 + end + return "#{bytes}" if unit.zero? + value >= 10 ? "#{value.round}#{units[unit]}" : "#{format('%.1f', value)}#{units[unit]}" + end + + def remember(flag) + world.flags[flag] = world.clock + end + + # --- redirection & filters --------------------------------------------- + + def write_redirect(result, redirect) + path = world.resolve(redirect[:path]) + return denied("bash", path) unless writable?(path) + return fail("bash: #{redirect[:path]}: Is a directory") if world.directory?(path) + + text = result.output.empty? ? "" : result.output + "\n" + if redirect[:mode] == ">>" && world.file?(path) + world.write_file(path, world.file(path)["content"].to_s + text) + else + world.write_file(path, text) + end + scenario.on_file_changed(world, path) + Result.new(output: "", exit_code: result.exit_code) + end + + def apply_filter(argv, text) + name, *args = argv + return fail("bash: #{name}: command not found", 127) unless FILTERS.include?(name) + + lines = text.lines.map(&:chomp) + case name + when "grep" + invert = args.delete("-v") + ignore = args.delete("-i") + pattern = Regexp.new(Regexp.escape(args.first.to_s), ignore ? Regexp::IGNORECASE : nil) + picked = lines.select { |l| invert ? l !~ pattern : l =~ pattern } + Result.new(output: picked.join("\n"), exit_code: picked.empty? ? 1 : 0) + when "head" then ok(lines.first(count_arg(args)).join("\n")) + when "tail" then ok(lines.last(count_arg(args)).join("\n")) + when "wc" then ok(lines.size.to_s) + when "sort" + sorted = args.any? { |a| a.include?("h") } ? lines.sort_by { |l| size_of(l.split.first) } : lines.sort + sorted = sorted.reverse if args.any? { |a| a.include?("r") } + ok(sorted.join("\n")) + end + end + + def count_arg(args) + if (i = args.index("-n")) then args[i + 1].to_i + elsif (flag = args.find { |a| a.match?(/\A-\d+\z/) }) then flag.delete("-").to_i + else 10 + end + end + + def size_of(text) + m = text.to_s.match(/\A([\d.]+)([BKMGT]?)\z/) or return 0 + m[1].to_f * 1024**"BKMGT".index(m[2].presence || "B") + end + + # --- basic commands ----------------------------------------------------- + + def cmd_help(_args) + ok(<<~TEXT.chomp) + This is a simulated Linux shell. Commands you can try: + ls, cd, pwd, cat, head, tail, grep, du, df, rm, truncate, echo, sed -i + ssh, exit, whoami, hostname, uptime, free, ps, top, kill + systemctl status|start|stop|restart , journalctl -u + curl , alerts, hint + Pipes (|), && and > redirection work for simple cases. Use sudo for system files. + TEXT + end + + def cmd_hint(_args) + ok(scenario.hint_for(world) || "No hints right now. Try `alerts` or check your objectives.") + end + + def cmd_whoami(_args) = ok(world.session["user"]) + def cmd_hostname(_args) = ok(host_name) + def cmd_pwd(_args) = ok(world.session["cwd"]) + def cmd_clear(_args) = ok("\e[2J\e[H") + + def cmd_echo(args) = ok(args.join(" ")) + + def cmd_cd(args) + target = world.resolve(args.first || "~") + return fail("bash: cd: #{args.first}: No such file or directory") unless world.directory?(target) + world.session["cwd"] = target + ok("") + end + + def cmd_ls(args) + flags = args.select { |a| a.start_with?("-") }.join + paths = args.reject { |a| a.start_with?("-") } + paths = [ "." ] if paths.empty? + long = flags.include?("l") + human_sizes = flags.include?("h") + + blocks = paths.map do |raw| + path = world.resolve(raw) + entries = + if world.file?(path) then [ [ File.basename(path), path, false ] ] + elsif world.directory?(path) then world.children(path) + else next "ls: cannot access '#{raw}': No such file or directory" + end + remember_listing(path) + lines = entries.map do |name, full, dir| + next(dir ? "#{name}/" : name) unless long + size = dir ? 4096 : world.file(full)["size"] + mode = dir ? "drwxr-xr-x" : world.file(full).fetch("mode", "-rw-r--r--") + owner = dir ? "root" : world.file(full).fetch("owner", "root") + format("%s 1 %-6s %-6s %6s %s %s", mode, owner, owner, human_sizes ? human(size) : size, world.timestamp[0, 12], name) + end + lines = [ "total #{entries.size * 4}" ] + lines if long + paths.size > 1 ? "#{raw}:\n#{lines.join("\n")}" : lines.join(long ? "\n" : " ") + end + ok(blocks.join("\n\n")) + end + + def remember_listing(path) + scenario.on_inspect(world, :ls, path) + end + + def read_file(cmd, raw) + path = world.resolve(raw) + return [ nil, fail("#{cmd}: #{raw}: Is a directory") ] if world.directory?(path) && !world.file?(path) + return [ nil, fail("#{cmd}: #{raw}: No such file or directory") ] unless world.file?(path) + f = world.file(path) + return [ nil, fail("#{cmd}: #{raw}: Permission denied") ] if f["secret"] && !@sudo + scenario.on_inspect(world, :read, path) + [ f, nil ] + end + + def file_lines(f) = f["content"].to_s.lines.map(&:chomp) + + def cmd_cat(args) + return fail("cat: missing file operand") if args.empty? + failed = false + outputs = args.map do |raw| + f, error = read_file("cat", raw) + next(failed = true) && error.output if error + if f["size"] > 50 * World::MB + "#{file_lines(f).last(8).join("\n")}\n... (#{human(f['size'])} file, showing the end. Try `tail` or `du -h`.)" + else + f["content"].to_s.chomp + end + end + Result.new(output: outputs.join("\n"), exit_code: failed ? 1 : 0) + end + + def cmd_head(args) = head_tail("head", args) { |lines, n| lines.first(n) } + def cmd_tail(args) = head_tail("tail", args) { |lines, n| lines.last(n) } + + def head_tail(cmd, args) + n = count_arg(args) + files = args.reject { |a| a.start_with?("-") || a == n.to_s } + return fail("#{cmd}: missing file operand") if files.empty? + f, error = read_file(cmd, files.first) + return error if error + ok(yield(file_lines(f), n).join("\n")) + end + + def cmd_grep(args) + ignore = args.delete("-i") + args.delete("-r") + pattern, *paths = args + return fail("usage: grep PATTERN FILE") if pattern.nil? || paths.empty? + regex = Regexp.new(Regexp.escape(pattern), ignore ? Regexp::IGNORECASE : nil) + matches = paths.flat_map do |raw| + f, error = read_file("grep", raw) + next [ error.output ] if error + file_lines(f).grep(regex).map { |l| paths.size > 1 ? "#{raw}:#{l}" : l } + end + Result.new(output: matches.join("\n"), exit_code: matches.empty? ? 1 : 0) + end + + def cmd_du(args) + flags = args.select { |a| a.start_with?("-") }.join + paths = args.reject { |a| a.start_with?("-") } + paths = [ "." ] if paths.empty? + summary = flags.include?("s") + fmt = ->(bytes) { flags.include?("h") ? human(bytes) : (bytes / 1024).to_s } + + lines = paths.flat_map do |raw| + path = world.resolve(raw) + next [ "du: cannot access '#{raw}': No such file or directory" ] unless world.file?(path) || world.directory?(path) + scenario.on_inspect(world, :du, path) + if summary || world.file?(path) + [ "#{fmt.(world.bytes_under(path))}\t#{raw}" ] + else + world.children(path).map { |name, full, _| "#{fmt.(world.bytes_under(full))}\t#{File.join(raw, name).delete_prefix('./')}" } + + [ "#{fmt.(world.bytes_under(path))}\t#{raw}" ] + end + end + ok(lines.join("\n")) + end + + def cmd_df(args) + scenario.on_inspect(world, :df, "/") + h = args.any? { |a| a.include?("h") } + d = world.disk + size = h ? human(d["size"]) : d["size"] / 1024 + used = h ? human(world.disk_used) : world.disk_used / 1024 + avail_bytes = [ d["size"] - world.disk_used, 0 ].max + avail = h ? human(avail_bytes) : avail_bytes / 1024 + ok([ + format("%-16s %6s %6s %6s %4s %s", "Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on"), + format("%-16s %6s %6s %6s %4s %s", d.fetch("device", "/dev/sda1"), size, used, avail, "#{world.disk_percent}%", "/"), + format("%-16s %6s %6s %6s %4s %s", "tmpfs", h ? "2.0G" : 2_097_152, h ? "0" : 0, h ? "2.0G" : 2_097_152, "0%", "/dev/shm") + ].join("\n")) + end + + def cmd_rm(args) + flags = args.select { |a| a.start_with?("-") }.join + targets = args.reject { |a| a.start_with?("-") } + return fail("rm: missing operand") if targets.empty? + errors = targets.filter_map do |raw| + path = world.resolve(raw) + if world.directory?(path) && !world.file?(path) + next "rm: cannot remove '#{raw}': Is a directory" unless flags.include?("r") + next "rm: refusing to remove '#{raw}' in this simulator" if path.count("/") < 3 + next "rm: cannot remove '#{raw}': Permission denied" unless writable?(path) + world.files.keys.select { |p| p.start_with?(path + "/") }.each { |p| world.delete_file(p) } + elsif world.file?(path) + next "rm: cannot remove '#{raw}': Permission denied" unless writable?(path) + world.delete_file(path) + else + next(flags.include?("f") ? nil : "rm: cannot remove '#{raw}': No such file or directory") + end + scenario.on_file_changed(world, path) + nil + end + errors.empty? ? ok("") : fail(errors.join("\n")) + end + + def cmd_truncate(args) + size_index = args.index("-s") + return fail("usage: truncate -s 0 FILE") unless size_index && args[size_index + 1] == "0" + targets = args.each_with_index.reject { |_, i| i == size_index || i == size_index + 1 }.map(&:first) + targets.each do |raw| + path = world.resolve(raw) + return fail("truncate: cannot open '#{raw}' for writing: No such file or directory") unless world.file?(path) + return fail("truncate: cannot open '#{raw}' for writing: Permission denied") unless writable?(path) + world.write_file(path, "") + scenario.on_file_changed(world, path) + end + ok("") + end + + # Supports the one form beginners need: sed -i 's/old/new/' FILE + def cmd_sed(args) + in_place = args.delete("-i") + expr, raw = args + m = expr.to_s.match(%r{\As/((?:[^/\\]|\\.)*)/((?:[^/\\]|\\.)*)/(g?)\z}) + return fail("sed: only `sed -i 's/old/new/' FILE` is supported here") unless m && raw + f, error = read_file("sed", raw) + return error if error + path = world.resolve(raw) + pattern = begin + Regexp.new(m[1], timeout: 0.2) + rescue RegexpError + Regexp.new(Regexp.escape(m[1])) + end + replacement = m[2].gsub("\\/", "/") + updated = m[3] == "g" ? f["content"].gsub(pattern, replacement) : f["content"].lines.map { |l| l.sub(pattern, replacement) }.join + return ok(updated.chomp) unless in_place + return fail("sed: couldn't open temporary file #{File.dirname(path)}/sedXXXX: Permission denied") unless writable?(path) + world.write_file(path, updated) + scenario.on_file_changed(world, path) + ok("") + end + + # --- hosts -------------------------------------------------------------- + + def cmd_ssh(args) + target = args.reject { |a| a.start_with?("-") }.first + return fail("usage: ssh [user@]host") unless target + user, name = target.include?("@") ? target.split("@", 2) : [ nil, target ] + unless world.host?(name) && world.host(name)["ssh"] + return fail("ssh: Could not resolve hostname #{name}: Name or service not known", 255) + end + user ||= world.host(name)["ssh"]["user"] + return fail("#{user}@#{name}: Permission denied (publickey).", 255) unless world.host(name)["ssh"]["user"] == user + + (world.session["stack"] ||= []) << world.session.slice("host", "user", "cwd") + world.session.merge!("host" => name, "user" => user, "cwd" => "/home/#{user}") + scenario.on_ssh(world, name) + ok(world.host(name)["motd"].to_s) + end + + def cmd_exit(_args) + previous = (world.session["stack"] || []).pop + return ok("logout (this is your own machine, there is nowhere to exit to)") unless previous + leaving = host_name + world.session.merge!(previous) + ok("logout\nConnection to #{leaving} closed.") + end + alias cmd_logout cmd_exit + + def cmd_uptime(_args) + load = world.host.fetch("load", [ 0.21, 0.18, 0.15 ]).map { |l| format("%.2f", l) }.join(", ") + ok(" #{world.timestamp[7, 5]}:00 up 41 days, 3 users, load average: #{load}") + end + + # --- memory & processes ------------------------------------------------ + + def cmd_free(args) + scenario.on_inspect(world, :free, nil) + total = world.host["memory_total_mb"] + used = world.memory_used_mb.round + free = [ total - used, 0 ].max + h = args.any? { |a| a.include?("h") } + fmt = ->(mb) { h ? (mb >= 1024 ? "#{format('%.1f', mb / 1024.0)}Gi" : "#{mb}Mi") : mb.to_s } + ok([ + format("%-6s %10s %10s %10s %10s", "", "total", "used", "free", "available"), + format("%-6s %10s %10s %10s %10s", "Mem:", fmt.(total), fmt.(used), fmt.(free), fmt.(free)), + format("%-6s %10s %10s %10s %10s", "Swap:", fmt.(0), fmt.(0), fmt.(0), "") + ].join("\n")) + end + + def process_table(sorted_by_memory: false) + total = world.host["memory_total_mb"].to_f + procs = world.processes + procs = procs.sort_by { |p| -p["mem_mb"].to_f } if sorted_by_memory + rows = procs.map do |p| + format("%-8s %6d %5.1f %5.1f %8d %s", p["user"], p["pid"], p.fetch("cpu", 0.3), p["mem_mb"] * 100 / total, (p["mem_mb"] * 1024).round, p["command"]) + end + [ format("%-8s %6s %5s %5s %8s %s", "USER", "PID", "%CPU", "%MEM", "RSS", "COMMAND") ] + rows + end + + def cmd_ps(args) + sorted = args.any? { |a| a.include?("mem") } + scenario.on_inspect(world, :ps, nil) + ok(process_table(sorted_by_memory: sorted).join("\n")) + end + + def cmd_top(_args) + scenario.on_inspect(world, :ps, nil) + header = [ + "top - #{world.timestamp[7, 5]}:00 up 41 days, load average: #{world.host.fetch('load', [ 0.2 ]).first}", + "MiB Mem : #{world.host['memory_total_mb']} total, #{world.memory_used_mb.round} used (#{world.memory_percent}%)", + "(snapshot, sorted by memory; real top would keep refreshing)", + "" + ] + ok((header + process_table(sorted_by_memory: true)).join("\n")) + end + + def cmd_kill(args) + signal = args.find { |a| a.start_with?("-") } + pids = args.reject { |a| a.start_with?("-") }.map(&:to_i) + return fail("kill: usage: kill [-9] pid") if pids.empty? + pids.each do |pid| + proc = world.processes.find { |p| p["pid"] == pid } + return fail("kill: (#{pid}) - No such process") unless proc + return fail("kill: (#{pid}) - Operation not permitted") unless @sudo || proc["user"] == world.session["user"] + scenario.on_kill(world, proc, signal) + end + ok("") + end + + # --- services ----------------------------------------------------------- + + def cmd_systemctl(args) + action, name = args.reject { |a| a.start_with?("-") } + name = name.to_s.delete_suffix(".service") + return ok(list_units) if action.nil? || action == "list-units" + return fail("Unknown command verb #{action}.") unless %w[status start stop restart].include?(action) + return fail("Too few arguments.") if name.empty? + svc = world.service(name) + return fail("Unit #{name}.service could not be found.", 4) unless svc + + if action == "status" + scenario.on_inspect(world, :status, name) + return Result.new(output: service_status(name, svc), exit_code: svc["state"] == "active" ? 0 : 3) + end + return fail("Failed to #{action} #{name}.service: Interactive authentication required.\n(hint: try `sudo systemctl #{action} #{name}`)") unless @sudo + + message = scenario.on_service(world, name, action) + message ? fail(message) : ok("") + end + + def list_units + rows = world.services.map do |name, svc| + format("%-24s loaded %-8s %-8s %s", "#{name}.service", svc["state"] == "active" ? "active" : "failed", + svc["state"] == "active" ? "running" : "failed", svc["description"]) + end + ([ format("%-24s %-6s %-8s %-8s %s", "UNIT", "LOAD", "ACTIVE", "SUB", "DESCRIPTION") ] + rows).join("\n") + end + + def service_status(name, svc) + dot = svc["state"] == "active" ? "●" : "×" + active = + if svc["state"] == "active" then "active (running) since #{world.timestamp(svc.fetch('started_at', 0))}" + else "failed (Result: exit-code) since #{world.timestamp(svc.fetch('failed_at', 0))}" + end + mem = world.service_processes(name).sum { |p| p["mem_mb"] } + lines = [ + "#{dot} #{name}.service - #{svc['description']}", + " Loaded: loaded (/etc/systemd/system/#{name}.service; enabled)", + " Active: #{active}" + ] + lines << " Memory: #{mem.round}M" if svc["state"] == "active" + lines << "" + lines.concat(Array(svc["journal"]).last(5)) + lines.join("\n") + end + + def cmd_journalctl(args) + unit_index = args.index("-u") + return fail("Specify a unit with -u, for example: journalctl -u shop-web") unless unit_index + name = args[unit_index + 1].to_s.delete_suffix(".service") + svc = world.service(name) + return ok("-- No entries --") unless svc + scenario.on_inspect(world, :journal, name) + n = args.index("-n") ? args[args.index("-n") + 1].to_i : 20 + ok(Array(svc["journal"]).last(n).join("\n").presence || "-- No entries --") + end + + # --- network ------------------------------------------------------------ + + def cmd_curl(args) + url = args.reject { |a| a.start_with?("-") }.first + return fail("curl: try 'curl https://shop.example/health'") unless url + status, body = scenario.http(world, url) + return fail("curl: (6) Could not resolve host: #{url}", 6) unless status + verbose = args.any? { |a| %w[-i -I -v].include?(a) } + ok(verbose ? "HTTP/1.1 #{status}\n\n#{body}" : body) + end + + def cmd_alerts(args) + scenario.on_inspect(world, :alerts, nil) + if args.first == "ack" + alert = world.alerts.find { |a| a["id"] == args[1] && a["state"] == "firing" } + return fail("alerts: no firing alert with id #{args[1]}") unless alert + alert["acknowledged"] = true + return ok("Acknowledged #{alert['id']}. You own this incident now.") + end + return ok("No alerts. All quiet.") if world.alerts.empty? + ok(world.alerts.map { |a| + "[#{a['state'].upcase}] #{a['id']} #{a['severity']} #{a['summary']}#{' (acked)' if a['acknowledged']}" + }.join("\n")) + end + end +end diff --git a/backend/lib/sim/shop_world.rb b/backend/lib/sim/shop_world.rb new file mode 100644 index 0000000..9006727 --- /dev/null +++ b/backend/lib/sim/shop_world.rb @@ -0,0 +1,131 @@ +module Sim + # The shared setting for the story: a small online shop ("shop.example") + # running on one Linux server, web-01, that you reach from your laptop. + module ShopWorld + GB = World::GB + MB = World::MB + + module_function + + def laptop + { + "linux_server" => false, + "fs" => { + "/home/dev/on-call.md" => text(<<~MD) + # On-call cheat sheet + - The shop runs on one server: web-01 (log in with `ssh web-01`) + - Services: nginx (front door), shop-web (the Rails app), shop-worker (background jobs) + - Health check: curl https://shop.example/health + - Alerts: run `alerts` to see what's firing + MD + }, + "dirs" => [ "/home/dev", "/tmp" ], + "services" => {}, + "processes" => [], + "disk" => { "size" => 256 * GB, "base_used" => 90 * GB, "device" => "/dev/nvme0n1p2" }, + "memory_total_mb" => 16_384 + } + end + + def web01(debug_log_size: 40 * MB, log_level: "info", cache_max: "500") + { + "linux_server" => true, + "monitored" => true, + "ssh" => { "user" => "deploy" }, + "motd" => "Welcome to Ubuntu 24.04 LTS (web-01)\n\n This server runs shop.example. Be careful, it's production!\n", + "fs" => { + "/home/deploy/README.txt" => text("Deploys land in /srv/shop/current. Config lives in /etc/shop.\n"), + "/etc/shop/web.env" => text("RAILS_ENV=production\nPORT=3000\nLOG_LEVEL=#{log_level}\n"), + "/etc/shop/worker.env" => text("RAILS_ENV=production\nQUEUES=default,reports\nREPORT_CACHE_MAX=#{cache_max}\n"), + "/srv/shop/current/REVISION" => text("41e2c9a\n"), + "/srv/shop/current/config/puma.rb" => text("workers 2\nthreads 3, 5\nport ENV.fetch(\"PORT\", 3000)\n"), + "/var/log/shop/production.log" => sized(180 * MB, production_log), + "/var/log/shop/debug.log" => sized(debug_log_size, debug_log), + "/var/log/nginx/access.log" => sized(350 * MB, access_log), + "/var/log/nginx/error.log" => sized(2 * MB, ""), + "/var/log/syslog" => sized(60 * MB, "Nov 20 08:59:01 web-01 CRON[2211]: (root) CMD (logrotate /etc/logrotate.conf)\n"), + "/var/lib/postgresql/16/main/PG_VERSION" => sized(900 * MB, "16\n") + }, + "dirs" => [ "/home/deploy", "/tmp", "/var/tmp", "/etc", "/srv/shop/releases" ], + "disk" => { "size" => 20 * GB, "base_used" => (3.2 * GB).round, "device" => "/dev/vda1" }, + "memory_total_mb" => 4096, + "services" => { + "nginx" => service("nginx", "A high performance web server and a reverse proxy server", [ + process_spec("root", "nginx: master process /usr/sbin/nginx", 12), + process_spec("www-data", "nginx: worker process", 18) + ]), + "shop-web" => service("shop-web", "Shop web app (puma)", [ + process_spec("deploy", "puma 6.4 (tcp://0.0.0.0:3000) [shop]", 310), + process_spec("deploy", "puma: cluster worker 0 [shop]", 420), + process_spec("deploy", "puma: cluster worker 1 [shop]", 410) + ]), + "shop-worker" => service("shop-worker", "Shop background jobs", [ + process_spec("deploy", "ruby bin/jobs --queues=default,reports [shop-worker]", 290) + ]), + "postgresql" => service("postgresql", "PostgreSQL 16 database server", [ + process_spec("postgres", "postgres: 16/main: checkpointer", 160) + ]) + }, + "processes" => [ + { "pid" => 1, "user" => "root", "command" => "/sbin/init", "mem_mb" => 12 }, + { "pid" => 712, "user" => "root", "command" => "sshd: /usr/sbin/sshd -D", "mem_mb" => 8 }, + { "pid" => 845, "user" => "root", "command" => "/usr/bin/node_exporter", "mem_mb" => 22 } + ], + "next_pid" => 4100 + } + end + + def service(name, description, spawn) + { "state" => "inactive", "description" => description, "spawn" => spawn, "journal" => [], "unit_name" => name } + end + + def process_spec(user, command, mem_mb) = { "user" => user, "command" => command, "mem_mb" => mem_mb, "cpu" => 1.2 } + + def text(content) = { "content" => content, "size" => content.bytesize, "mode" => "-rw-r--r--", "owner" => "root" } + def sized(size, content) = text(content).merge("size" => size) + + def production_log + <<~LOG + I, [2026-11-20T08:58:12] INFO -- : Started GET "/products/42" for 203.0.113.9 + I, [2026-11-20T08:58:12] INFO -- : Completed 200 OK in 38ms + I, [2026-11-20T08:58:40] INFO -- : Started POST "/cart" for 198.51.100.4 + I, [2026-11-20T08:58:40] INFO -- : Completed 302 Found in 21ms + LOG + end + + def debug_log + <<~LOG + D, [2026-11-20T08:59:58] DEBUG -- : SQL (0.4ms) SELECT "products".* FROM "products" WHERE "id" = 42 + D, [2026-11-20T08:59:58] DEBUG -- : Rendered products/show.html.erb (12.1ms) + D, [2026-11-20T08:59:59] DEBUG -- : SQL (0.3ms) SELECT "carts".* FROM "carts" WHERE "id" = 991 + D, [2026-11-20T08:59:59] DEBUG -- : Cache read: views/products/42-20261120 (0.1ms) + LOG + end + + def access_log + <<~LOG + 203.0.113.9 - - [20/Nov/2026:08:58:12] "GET /products/42 HTTP/1.1" 200 5123 + 198.51.100.4 - - [20/Nov/2026:08:58:40] "POST /cart HTTP/1.1" 302 0 + LOG + end + + # Boot the services that should be running at the start of a chapter. + def boot(scenario, world, *names, host: "web-01") + names.each { |name| scenario.start_service(world, name, host: host) } + end + + # Shared HTTP behaviour: the site is up when nginx and shop-web are running. + def http(world, url) + return nil unless url.match?(%r{\A(https?://)?(shop\.example|localhost|127\.0\.0\.1|web-01)(:\d+)?(/.*)?\z}) + up = world.service("nginx", "web-01")["state"] == "active" && world.service("shop-web", "web-01")["state"] == "active" + world.flags["last_curl_ok"] = up ? world.clock : nil + if !up + [ "502 Bad Gateway", "502 Bad Gateway

502 Bad Gateway


nginx
" ] + elsif url.include?("/health") + [ "200 OK", "{\"status\":\"ok\",\"revision\":\"41e2c9a\"}" ] + else + [ "200 OK", "

Ruby Shop

Today's deals...

" ] + end + end + end +end diff --git a/backend/lib/sim/world.rb b/backend/lib/sim/world.rb new file mode 100644 index 0000000..e3c1c9a --- /dev/null +++ b/backend/lib/sim/world.rb @@ -0,0 +1,204 @@ +module Sim + # The whole simulated environment for one run, kept as a plain Hash with + # string keys so it round-trips through the JSON column unchanged. + # + # hosts: name => { fs, services, processes, disk, memory_total_mb, env } + # session: where the player is (host, user, cwd) and the ssh stack + # alerts: monitoring alerts (firing / resolved) + # metrics: time series per host, one point per tick + # history: every command the player typed, with the host it ran on + # flags: scenario-specific facts ("found_big_log" etc.) + # fired: ids of scheduled events that already happened + class World + GB = 1024**3 + MB = 1024**2 + + attr_reader :data + + def initialize(data) + @data = data + end + + def to_h = data + + def host(name = current_host) = data["hosts"].fetch(name) + def host?(name) = data["hosts"].key?(name) + def session = data["session"] + def current_host = session["host"] + def flags = data["flags"] + def history = data["history"] + def alerts = data["alerts"] + def fired = data["fired"] + + # --- files -------------------------------------------------------------- + + def files(host_name = current_host) = host(host_name)["fs"] + def file(path, host_name = current_host) = files(host_name)[path] + def file?(path, host_name = current_host) = files(host_name).key?(path) + + def directory?(path, host_name = current_host) + return true if path == "/" + prefix = path.chomp("/") + "/" + files(host_name).keys.any? { |p| p.start_with?(prefix) } || + host(host_name).fetch("dirs", []).include?(path) + end + + def write_file(path, content, host_name = current_host) + entry = files(host_name)[path] ||= { "mode" => "-rw-r--r--", "owner" => "root" } + entry["content"] = content + entry["size"] = content.bytesize + entry + end + + # Append a log line without resetting the file's (possibly huge) size. + def append_line(path, line, host_name = current_host) + f = file(path, host_name) or return + f["content"] = f["content"].to_s + line + "\n" + f["size"] += line.bytesize + 1 + end + + def delete_file(path, host_name = current_host) + files(host_name).delete(path) + end + + # Immediate children of a directory: [[name, path, directory?], ...] + def children(dir, host_name = current_host) + prefix = dir == "/" ? "/" : dir.chomp("/") + "/" + names = {} + files(host_name).each_key do |p| + next unless p.start_with?(prefix) + rest = p.delete_prefix(prefix) + first, more = rest.split("/", 2) + names[first] ||= more ? :dir : :file + end + host(host_name).fetch("dirs", []).each do |d| + next unless d.start_with?(prefix) && d != dir + first, more = d.delete_prefix(prefix).split("/", 2) + names[first] ||= :dir + names[first] = :dir if more + end + names.sort.map { |name, kind| [ name, prefix + name, kind == :dir ] } + end + + def bytes_under(path, host_name = current_host) + return file(path, host_name)["size"] if file?(path, host_name) + prefix = path == "/" ? "/" : path.chomp("/") + "/" + files(host_name).sum { |p, f| p.start_with?(prefix) ? f["size"].to_i : 0 } + end + + # --- disk --------------------------------------------------------------- + + def disk(host_name = current_host) = host(host_name)["disk"] + + def disk_used(host_name = current_host) + disk(host_name)["base_used"] + bytes_under("/", host_name) + end + + def disk_percent(host_name = current_host) + [ (disk_used(host_name) * 100.0 / disk(host_name)["size"]).round, 100 ].min + end + + def disk_full?(host_name = current_host) = disk_used(host_name) >= disk(host_name)["size"] + + # Grow a file, but never past the end of the disk (like a real full disk). + def grow_file(path, bytes, host_name = current_host) + f = file(path, host_name) or return + room = disk(host_name)["size"] - disk_used(host_name) + f["size"] += [ bytes, room ].min.clamp(0, bytes) + end + + # --- services & processes ---------------------------------------------- + + def services(host_name = current_host) = host(host_name)["services"] + def service(name, host_name = current_host) = services(host_name)[name] + def processes(host_name = current_host) = host(host_name)["processes"] + + def service_processes(name, host_name = current_host) + processes(host_name).select { |p| p["service"] == name } + end + + def journal(name, line, host_name = current_host) + svc = service(name, host_name) or return + (svc["journal"] ||= []) << "#{timestamp} #{host_name} #{svc.fetch('unit_name', name)}[#{svc['pid'] || 1}]: #{line}" + end + + def memory_used_mb(host_name = current_host) + processes(host_name).sum { |p| p["mem_mb"].to_f } + end + + def memory_percent(host_name = current_host) + (memory_used_mb(host_name) * 100.0 / host(host_name)["memory_total_mb"]).round + end + + def next_pid(host_name = current_host) + host(host_name)["next_pid"] = host(host_name).fetch("next_pid", 4000) + 1 + end + + # --- env files (KEY=value) --------------------------------------------- + + def env_value(path, key, host_name = current_host) + f = file(path, host_name) or return + f["content"].each_line do |line| + k, v = line.strip.split("=", 2) + return v if k == key + end + nil + end + + # --- alerts ------------------------------------------------------------- + + def fire_alert(id, attrs) + return if alerts.any? { |a| a["id"] == id && a["state"] == "firing" } + alerts << attrs.merge("id" => id, "state" => "firing", "fired_at" => clock, "acknowledged" => false) + end + + def resolve_alert(id) + alerts.each { |a| a["state"] = "resolved" if a["id"] == id && a["state"] == "firing" } + end + + def firing_alerts = alerts.select { |a| a["state"] == "firing" } + + # --- time --------------------------------------------------------------- + + def clock = data["clock"] + def clock=(value) + data["clock"] = value + end + + # The fake wall clock: 09:00 plus one minute per tick, so logs read naturally. + def timestamp(tick = clock) + minutes = 9 * 60 + tick + format("Nov 20 %02d:%02d:%02d", minutes / 60 % 24, minutes % 60, (tick * 7) % 60) + end + + def record_metrics + data["metrics"] ||= {} + data["hosts"].each_key do |name| + next unless host(name)["monitored"] + series = (data["metrics"][name] ||= []) + series << { "t" => clock, "memory" => memory_percent(name), "disk" => disk_percent(name), + "cpu" => host(name).fetch("cpu_percent", 12) } + series.shift while series.size > 120 + end + end + + # --- paths -------------------------------------------------------------- + + def home = session["user"] == "root" ? "/root" : "/home/#{session['user']}" + + def resolve(path) + path = path.to_s + path = home + path.delete_prefix("~") if path.start_with?("~") + path = File.join(session["cwd"], path) unless path.start_with?("/") + parts = [] + path.split("/").each do |part| + case part + when "", "." then next + when ".." then parts.pop + else parts << part + end + end + "/" + parts.join("/") + end + end +end diff --git a/backend/lib/tasks/.keep b/backend/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/log/.keep b/backend/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/public/robots.txt b/backend/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/backend/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/backend/script/.keep b/backend/script/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/storage/.keep b/backend/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/test/channels/run_channel_test.rb b/backend/test/channels/run_channel_test.rb new file mode 100644 index 0000000..70d460d --- /dev/null +++ b/backend/test/channels/run_channel_test.rb @@ -0,0 +1,17 @@ +require "test_helper" + +class RunChannelTest < ActionCable::Channel::TestCase + test "streams updates for a run" do + run = Run.start!("linux-disk-full") + subscribe run_id: run.id + assert subscription.confirmed? + assert_has_stream_for run + + assert_broadcasts(run, 1) { run.execute!("whoami") } + end + + test "rejects unknown runs" do + subscribe run_id: 0 + assert subscription.rejected? + end +end diff --git a/backend/test/controllers/.keep b/backend/test/controllers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/test/fixtures/files/.keep b/backend/test/fixtures/files/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/test/integration/.keep b/backend/test/integration/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/test/integration/runs_api_test.rb b/backend/test/integration/runs_api_test.rb new file mode 100644 index 0000000..da8e587 --- /dev/null +++ b/backend/test/integration/runs_api_test.rb @@ -0,0 +1,44 @@ +require "test_helper" + +class RunsApiTest < ActionDispatch::IntegrationTest + test "lists scenarios" do + get "/api/scenarios" + assert_response :success + assert_equal %w[linux-disk-full monitoring-memory-leak], response.parsed_body.map { |s| s["key"] } + end + + test "starts a run, runs a command and saves the world" do + post "/api/runs", params: { scenario: "linux-disk-full" }, as: :json + assert_response :created + run = response.parsed_body + assert_equal "dev@laptop:~$", run["prompt"] + assert_equal 6, run["objectives"].size + + post "/api/runs/#{run['id']}/commands", params: { input: "ssh web-01" }, as: :json + assert_response :success + body = response.parsed_body + assert_equal "deploy@web-01:~$", body["prompt"] + assert_equal [ "connect" ], body["completed"].map { |c| c["id"] } + + get "/api/runs/#{run['id']}" + assert_equal "deploy@web-01:~$", response.parsed_body["prompt"] + end + + test "tick advances time" do + post "/api/runs", params: { scenario: "monitoring-memory-leak" }, as: :json + id = response.parsed_body["id"] + post "/api/runs/#{id}/tick", params: { ticks: 3 }, as: :json + assert_equal 3, response.parsed_body["clock"] + end + + test "rejects unknown scenarios" do + post "/api/runs", params: { scenario: "nope" }, as: :json + assert_response :unprocessable_content + end + + test "rejects very long commands" do + post "/api/runs", params: { scenario: "linux-disk-full" }, as: :json + post "/api/runs/#{response.parsed_body['id']}/commands", params: { input: "a" * 501 }, as: :json + assert_response :unprocessable_content + end +end diff --git a/backend/test/lib/sim/linux_disk_full_test.rb b/backend/test/lib/sim/linux_disk_full_test.rb new file mode 100644 index 0000000..f965e83 --- /dev/null +++ b/backend/test/lib/sim/linux_disk_full_test.rb @@ -0,0 +1,51 @@ +require "test_helper" + +class Sim::LinuxDiskFullTest < ActiveSupport::TestCase + setup do + @engine = Sim::Engine.start("linux-disk-full") + @world = @engine.world + end + + def completed_ids(*inputs) = inputs.flat_map { |i| @engine.execute(i).completed.map { |c| c[:id] } } + + test "starts with a full disk, a crashed app and a firing alert" do + assert_equal 100, @world.disk_percent("web-01") + assert_equal "failed", @world.service("shop-web", "web-01")["state"] + assert_equal [ "SiteDown" ], @world.firing_alerts.map { |a| a["id"] } + end + + test "the app cannot start while the disk is full" do + @engine.execute("ssh web-01") + step = @engine.execute("sudo systemctl start shop-web") + assert_match "failed", step.output + assert_match "No space left on device", @engine.execute("journalctl -u shop-web").output + end + + test "the full fix completes every objective in order" do + ids = completed_ids( + "ssh web-01", "systemctl status shop-web", "du -sh /var/log/*", "ls -lh /var/log/shop", + "sudo truncate -s 0 /var/log/shop/debug.log", + "sudo sed -i 's/LOG_LEVEL=debug/LOG_LEVEL=info/' /etc/shop/web.env", + "sudo systemctl restart shop-web", "curl https://shop.example/health" + ) + assert_equal %w[connect diagnose find-culprit free-space stop-debug recover], ids + assert @engine.finished? + assert_empty @world.firing_alerts + end + + test "restarting with debug logging still on fills the disk again" do + @engine.execute("ssh web-01") + @engine.execute("sudo truncate -s 0 /var/log/shop/debug.log") + @engine.execute("sudo systemctl start shop-web") + assert_equal "active", @world.service("shop-web", "web-01")["state"] + + notices = 15.times.flat_map { @engine.tick.notices } + assert_equal "failed", @world.service("shop-web", "web-01")["state"] + assert notices.any? { |n| n["text"].include?("crashed again") } + end + + test "the site check only counts after the app is back" do + @engine.execute("ssh web-01") + assert_match "502 Bad Gateway", @engine.execute("curl https://shop.example/").output + end +end diff --git a/backend/test/lib/sim/monitoring_memory_leak_test.rb b/backend/test/lib/sim/monitoring_memory_leak_test.rb new file mode 100644 index 0000000..9cbe6d3 --- /dev/null +++ b/backend/test/lib/sim/monitoring_memory_leak_test.rb @@ -0,0 +1,62 @@ +require "test_helper" + +class Sim::MonitoringMemoryLeakTest < ActiveSupport::TestCase + setup do + @engine = Sim::Engine.start("monitoring-memory-leak") + @world = @engine.world + end + + def wait_for_alert + 30.times do + return if @world.firing_alerts.any? + @engine.tick + end + flunk "alert never fired" + end + + test "starts calm, then memory climbs until an alert fires" do + assert_empty @world.alerts + start = @world.memory_percent("web-01") + wait_for_alert + assert_operator @world.memory_percent("web-01"), :>=, 85 + assert_operator start, :<, 60 + assert_equal "HighMemoryUsage", @world.firing_alerts.first["id"] + end + + test "metrics record one point per tick for the dashboard" do + 3.times { @engine.tick } + assert_equal 4, @world.data["metrics"]["web-01"].size + assert_equal %w[cpu disk memory t], @world.data["metrics"]["web-01"].last.keys.sort + end + + test "restarting without fixing the config only buys time" do + wait_for_alert + @engine.execute("ssh web-01") + @engine.execute("sudo systemctl restart shop-worker") + before = @world.memory_percent("web-01") + 3.times { @engine.tick } + assert_operator @world.memory_percent("web-01"), :>, before + end + + test "left alone, the kernel kills the worker and systemd restarts it" do + wait_for_alert + notices = 20.times.flat_map { @engine.tick.notices } + assert notices.any? { |n| n["text"].include?("ran out of memory") } + assert_equal "active", @world.service("shop-worker", "web-01")["state"] + assert_match "Out of memory", @world.file("/var/log/syslog", "web-01")["content"] + end + + test "the full fix completes every objective in order" do + wait_for_alert + ids = [ + "alerts", "ssh web-01", "ps aux --sort=-%mem", "journalctl -u shop-worker", + "sudo sed -i 's/REPORT_CACHE_MAX=0.*/REPORT_CACHE_MAX=500/' /etc/shop/worker.env", + "sudo systemctl restart shop-worker" + ].flat_map { |i| @engine.execute(i).completed.map { |c| c[:id] } } + + assert_equal %w[see-alert connect find-process trace-cause fix-config recover], ids + assert @engine.finished? + 5.times { @engine.tick } + assert_operator @world.memory_percent("web-01"), :<, 70 + end +end diff --git a/backend/test/lib/sim/shell_test.rb b/backend/test/lib/sim/shell_test.rb new file mode 100644 index 0000000..59aa920 --- /dev/null +++ b/backend/test/lib/sim/shell_test.rb @@ -0,0 +1,78 @@ +require "test_helper" + +class Sim::ShellTest < ActiveSupport::TestCase + setup do + @engine = Sim::Engine.start("linux-disk-full") + end + + def run_cmd(input) = @engine.execute(input) + + test "unknown commands look like bash" do + step = run_cmd("frobnicate") + assert_equal "bash: frobnicate: command not found", step.output + assert_equal 127, step.exit_code + end + + test "service commands on the laptop point the player to the server" do + assert_match "ssh web-01", run_cmd("systemctl status shop-web").output + end + + test "ssh changes the prompt and exit comes back" do + run_cmd("ssh web-01") + assert_equal "deploy@web-01:~$", @engine.prompt + run_cmd("exit") + assert_equal "dev@laptop:~$", @engine.prompt + end + + test "ssh to an unknown host fails" do + assert_match "Could not resolve hostname", run_cmd("ssh db-99").output + end + + test "system files need sudo" do + run_cmd("ssh web-01") + assert_match "Permission denied", run_cmd("rm /var/log/shop/debug.log").output + assert @engine.world.file?("/var/log/shop/debug.log") + run_cmd("sudo rm /var/log/shop/debug.log") + assert_not @engine.world.file?("/var/log/shop/debug.log") + end + + test "globs, pipes and sort -h work together" do + run_cmd("ssh web-01") + output = run_cmd("du -sh /var/log/* | sort -rh | head -1").output + assert_match %r{\A1\dG\t/var/log/shop\z}, output + end + + test "grep and wc filters" do + run_cmd("ssh web-01") + assert_equal "LOG_LEVEL=debug", run_cmd("cat /etc/shop/web.env | grep LOG").output + assert_equal "3", run_cmd("cat /etc/shop/web.env | wc -l").output + end + + test "sed -i edits a file in place with a regex" do + run_cmd("ssh web-01") + run_cmd("sudo sed -i 's/LOG_LEVEL=.*/LOG_LEVEL=warn/' /etc/shop/web.env") + assert_equal "warn", @engine.world.env_value("/etc/shop/web.env", "LOG_LEVEL") + end + + test "redirection writes into the home directory" do + run_cmd("echo hello > notes.txt") + run_cmd("echo again >> notes.txt") + assert_equal "hello\nagain", run_cmd("cat notes.txt").output + end + + test "&& stops at the first failure" do + output = run_cmd("cat nope.txt && echo should-not-print").output + assert_no_match "should-not-print", output + end + + test "cd and ls navigate the fake filesystem" do + run_cmd("ssh web-01") + run_cmd("cd /var/log") + assert_equal "deploy@web-01:/var/log$", @engine.prompt + assert_equal "nginx/ shop/ syslog", run_cmd("ls").output + end + + test "unmatched quotes are a syntax error, not a crash" do + assert_match "syntax error", run_cmd("echo 'oops").output + end +end diff --git a/backend/test/models/.keep b/backend/test/models/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/test/test_helper.rb b/backend/test/test_helper.rb new file mode 100644 index 0000000..0c22470 --- /dev/null +++ b/backend/test/test_helper.rb @@ -0,0 +1,15 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +module ActiveSupport + class TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + end +end diff --git a/backend/tmp/.keep b/backend/tmp/.keep new file mode 100644 index 0000000..e69de29 diff --git a/backend/vendor/.keep b/backend/vendor/.keep new file mode 100644 index 0000000..e69de29