commit c8c91b21d9eedd93f5c22a23081b73a8582dcfec Author: Pascal Date: Wed Feb 24 03:22:52 2021 -0500 [add] initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dff662b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7664964 --- /dev/null +++ b/.gitignore @@ -0,0 +1,110 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore uploaded files in development. +/storage/* +!/storage/.keep +.byebug_history + +# Ignore master key for decrypting credentials and more. +/config/master.key + +## custom +*.sqlite3 +.volumes + +# rails bundle install location +/.vendor +/vendor + +# Created by https://www.toptal.com/developers/gitignore/api/rails +### Rails ### +*.rbc +capybara-*.html +.rspec +/db/*.sqlite3 +/db/*.sqlite3-journal +/db/*.sqlite3-[0-9]* +/public/system +/coverage/ +/spec/tmp +*.orig +rerun.txt +pickle-email-*.html + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# TODO Comment out this rule if you are OK with secrets being uploaded to the repo +config/initializers/secret_token.rb +config/master.key + +# Only include if you have production secrets in this file, which is no longer a Rails default +# config/secrets.yml + +# dotenv, dotenv-rails +# TODO Comment out these rules if environment variables can be committed +.env +.env.* + +## Environment normalization: +/.bundle +/vendor/bundle + +# these should all be checked in to normalize the environment: +# Gemfile.lock, .ruby-version, .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc + +# if using bower-rails ignore default bower_components path bower.json files +/vendor/assets/bower_components +*.bowerrc +bower.json + +# Ignore pow environment settings +.powenv + +# Ignore Byebug command history file. +.byebug_history + +# Ignore node_modules +node_modules/ + +# Ignore precompiled javascript packs +/public/packs +/public/packs-test +/public/assets + +# Ignore yarn files +/yarn-error.log +yarn-debug.log* +.yarn-integrity + +# Ignore uploaded files in development +/storage/* +!/storage/.keep diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..2eb2fe9 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-2.7.2 diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..4818a8a --- /dev/null +++ b/Gemfile @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby '2.7.2' + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' +gem 'rails', '~> 6.1.2', '>= 6.1.2.1' +# Use sqlite3 as the database for Active Record +gem 'sqlite3', '~> 1.4' +# Use Puma as the app server +gem 'puma', '~> 5.0' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +# gem 'jbuilder', '~> 2.7' + +# Use Active Storage variant +# gem 'image_processing', '~> 1.2' + +# Reduces boot times through caching; required in config/boot.rb +gem 'bootsnap', '>= 1.4.4', require: false + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible +# gem 'rack-cors' + +group :development, :test do + # Call 'byebug' anywhere in the code to stop execution and get a debugger console + gem 'byebug', platforms: %i[mri mingw x64_mingw] + gem 'rspec-rails', '~> 4.0' +end + +group :test do + gem 'database_cleaner', '~> 2.0' + gem 'factory_bot_rails', '~> 6.1' + gem 'faker', '~> 2.16' + gem 'shoulda-matchers', '~> 4.5' +end + +group :development do + gem 'listen', '~> 3.3' + # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring + gem 'spring' +end + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] + +# project dependencies +gem 'bcrypt', '~> 3.1' # secret storage +gem 'jbuilder', '~> 2.11' # json +gem 'ruby-enum', '~> 0.9.0' # enum diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..23e38ea --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,209 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (6.1.2.1) + actionpack (= 6.1.2.1) + activesupport (= 6.1.2.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (6.1.2.1) + actionpack (= 6.1.2.1) + activejob (= 6.1.2.1) + activerecord (= 6.1.2.1) + activestorage (= 6.1.2.1) + activesupport (= 6.1.2.1) + mail (>= 2.7.1) + actionmailer (6.1.2.1) + actionpack (= 6.1.2.1) + actionview (= 6.1.2.1) + activejob (= 6.1.2.1) + activesupport (= 6.1.2.1) + mail (~> 2.5, >= 2.5.4) + rails-dom-testing (~> 2.0) + actionpack (6.1.2.1) + actionview (= 6.1.2.1) + activesupport (= 6.1.2.1) + rack (~> 2.0, >= 2.0.9) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (6.1.2.1) + actionpack (= 6.1.2.1) + activerecord (= 6.1.2.1) + activestorage (= 6.1.2.1) + activesupport (= 6.1.2.1) + nokogiri (>= 1.8.5) + actionview (6.1.2.1) + activesupport (= 6.1.2.1) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (6.1.2.1) + activesupport (= 6.1.2.1) + globalid (>= 0.3.6) + activemodel (6.1.2.1) + activesupport (= 6.1.2.1) + activerecord (6.1.2.1) + activemodel (= 6.1.2.1) + activesupport (= 6.1.2.1) + activestorage (6.1.2.1) + actionpack (= 6.1.2.1) + activejob (= 6.1.2.1) + activerecord (= 6.1.2.1) + activesupport (= 6.1.2.1) + marcel (~> 0.3.1) + mimemagic (~> 0.3.2) + activesupport (6.1.2.1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + zeitwerk (~> 2.3) + bcrypt (3.1.16) + bootsnap (1.7.2) + msgpack (~> 1.0) + builder (3.2.4) + byebug (11.1.3) + concurrent-ruby (1.1.8) + crass (1.0.6) + database_cleaner (2.0.1) + database_cleaner-active_record (~> 2.0.0) + database_cleaner-active_record (2.0.0) + activerecord (>= 5.a) + database_cleaner-core (~> 2.0.0) + database_cleaner-core (2.0.1) + diff-lcs (1.4.4) + erubi (1.10.0) + factory_bot (6.1.0) + activesupport (>= 5.0.0) + factory_bot_rails (6.1.0) + factory_bot (~> 6.1.0) + railties (>= 5.0.0) + faker (2.16.0) + i18n (>= 1.6, < 2) + ffi (1.14.2) + globalid (0.4.2) + activesupport (>= 4.2.0) + i18n (1.8.9) + concurrent-ruby (~> 1.0) + jbuilder (2.11.2) + activesupport (>= 5.0.0) + listen (3.4.1) + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) + loofah (2.9.0) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.7.1) + mini_mime (>= 0.1.1) + marcel (0.3.3) + mimemagic (~> 0.3.2) + method_source (1.0.0) + mimemagic (0.3.5) + mini_mime (1.0.2) + minitest (5.14.3) + msgpack (1.4.2) + nio4r (2.5.5) + nokogiri (1.11.1-x86_64-linux) + racc (~> 1.4) + puma (5.2.1) + nio4r (~> 2.0) + racc (1.5.2) + rack (2.2.3) + rack-test (1.1.0) + rack (>= 1.0, < 3) + rails (6.1.2.1) + actioncable (= 6.1.2.1) + actionmailbox (= 6.1.2.1) + actionmailer (= 6.1.2.1) + actionpack (= 6.1.2.1) + actiontext (= 6.1.2.1) + actionview (= 6.1.2.1) + activejob (= 6.1.2.1) + activemodel (= 6.1.2.1) + activerecord (= 6.1.2.1) + activestorage (= 6.1.2.1) + activesupport (= 6.1.2.1) + bundler (>= 1.15.0) + railties (= 6.1.2.1) + sprockets-rails (>= 2.0.0) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.3.0) + loofah (~> 2.3) + railties (6.1.2.1) + actionpack (= 6.1.2.1) + activesupport (= 6.1.2.1) + method_source + rake (>= 0.8.7) + thor (~> 1.0) + rake (13.0.3) + rb-fsevent (0.10.4) + rb-inotify (0.10.1) + ffi (~> 1.0) + rspec-core (3.10.1) + rspec-support (~> 3.10.0) + rspec-expectations (3.10.1) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.10.0) + rspec-mocks (3.10.2) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.10.0) + rspec-rails (4.0.2) + actionpack (>= 4.2) + activesupport (>= 4.2) + railties (>= 4.2) + rspec-core (~> 3.10) + rspec-expectations (~> 3.10) + rspec-mocks (~> 3.10) + rspec-support (~> 3.10) + rspec-support (3.10.2) + ruby-enum (0.9.0) + i18n + shoulda-matchers (4.5.1) + activesupport (>= 4.2.0) + spring (2.1.1) + sprockets (4.0.2) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.2.2) + actionpack (>= 4.0) + activesupport (>= 4.0) + sprockets (>= 3.0.0) + sqlite3 (1.4.2) + thor (1.1.0) + tzinfo (2.0.4) + concurrent-ruby (~> 1.0) + websocket-driver (0.7.3) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.4.2) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + bcrypt (~> 3.1) + bootsnap (>= 1.4.4) + byebug + database_cleaner (~> 2.0) + factory_bot_rails (~> 6.1) + faker (~> 2.16) + jbuilder (~> 2.11) + listen (~> 3.3) + puma (~> 5.0) + rails (~> 6.1.2, >= 6.1.2.1) + rspec-rails (~> 4.0) + ruby-enum (~> 0.9.0) + shoulda-matchers (~> 4.5) + spring + sqlite3 (~> 1.4) + tzinfo-data + +RUBY VERSION + ruby 2.7.2p137 + +BUNDLED WITH + 2.2.9 diff --git a/README.md b/README.md new file mode 100644 index 0000000..7db80e4 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# README + +This README would normally document whatever steps are necessary to get the +application up and running. + +Things you may want to cover: + +* Ruby version + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..488c551 --- /dev/null +++ b/Rakefile @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +# 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/api.yml b/api.yml new file mode 100644 index 0000000..1610d3d --- /dev/null +++ b/api.yml @@ -0,0 +1,360 @@ +openapi: "3.0.0" +info: + description: "Simple dynDNS via Rest-API." + version: "1.0" + title: "rynDNS" + +servers: + - url: "https://api.pdev.dev/rynDNS/v1" + description: "" + +security: + - api_key: [] + +paths: + /admin/client: + post: + tags: + - "admin" + summary: "Create or update a client and retrieve a new API key" + description: "" + operationId: "create_client" + parameters: + - $ref: "#/components/parameters/api_key" + requestBody: + description: "An existing clients properties wil only be updated if the parameter is present." + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/client" + responses: + "200": + description: "Client updated" + content: + application/json: + schema: + $ref: "#/components/schemas/admin_client_api_key" + "201": + description: "Client created" + content: + application/json: + schema: + $ref: "#/components/schemas/admin_client_api_key" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + "405": + description: "Invalid input" + "406": + description: "Not Acceptable - Can not remove last admin account permissions" + put: + tags: + - "admin" + summary: "Update an existing client" + description: "" + operationId: "update_client" + parameters: + - $ref: "#/components/parameters/api_key" + requestBody: + description: "An existing clients properties wil only be updated if the parameter is present." + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/client" + responses: + "200": + description: "Client updated" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + "404": + $ref: "#/components/responses/not_found" + "405": + description: "Invalid input" + "406": + description: "Not Acceptable - Can not remove last admin account permissions" + /admin/clients: + get: + tags: + - "admin" + summary: "Retrieve all clients information" + description: "" + operationId: "get_all_client" + parameters: + - $ref: "#/components/parameters/api_key" + responses: + "200": + description: "OK" + content: + application/json: + schema: + $ref: "#/components/schemas/admin_client_info_array" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + /admin/clients/{client_name}: + parameters: + - $ref: "#/components/parameters/api_key" + - $ref: "#/components/parameters/client_name" + get: + tags: + - "admin" + summary: "Retrieve client information" + description: "" + operationId: "get_client" + responses: + "200": + description: "OK" + content: + application/json: + schema: + $ref: "#/components/schemas/admin_client_info" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + "404": + $ref: "#/components/responses/not_found" + delete: + tags: + - "admin" + summary: "Delete an existing client" + description: "" + operationId: "delete_client" + responses: + "200": + description: "Client deleted" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + "404": + $ref: "#/components/responses/not_found" + "406": + description: "Not Acceptable - Can not delete last admin account" + + /client: + parameters: + - $ref: "#/components/parameters/api_key" + put: + tags: + - "client (write)" + summary: "Update ipv4 client information based on request IP or body if present" + description: "If body is present, it will take precedence over the request IP. Response contains the newly set `ipv4` value." + operationId: "update_client_ip" + requestBody: + description: "An existing clients properties wil only be updated if the parameter is present." + required: false + content: + application/json: + schema: + $ref: "#/components/schemas/client_update" + responses: + "200": + description: "OK" + content: + application/json: + schema: + $ref: "#/components/schemas/client_info" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + "406": + description: "Not Acceptable - IPv4 Address is invalid" + delete: + tags: + - "client (write)" + summary: "Delete an existing ipv4 client information" + description: "Response contains the previously set `ipv4` value before deletion." + operationId: "delete_client_ip" + responses: + "200": + description: "IP deleted" + content: + application/json: + schema: + $ref: "#/components/schemas/client_info" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + + /clients/{client_name}: + parameters: + - $ref: "#/components/parameters/api_key" + - $ref: "#/components/parameters/client_name" + get: + tags: + - "client (read)" + summary: "Get ipv4 client information" + description: "" + operationId: "get_client_ip" + responses: + "200": + description: "OK" + content: + application/json: + schema: + $ref: "#/components/schemas/client_info" + "401": + $ref: "#/components/responses/unauthorized" + "403": + $ref: "#/components/responses/forbidden" + "404": + $ref: "#/components/responses/not_found" + + /public/{client_name}: + parameters: + - $ref: "#/components/parameters/client_name" + get: + tags: + - "public" + summary: "Get ipv4 client information" + description: "" + operationId: "get_public_client_ip" + security: [] + responses: + "200": + description: "OK" + content: + application/json: + schema: + $ref: "#/components/schemas/client_info" + "401": + $ref: "#/components/responses/unauthorized_public" + +components: + + # security + securitySchemes: + api_key: + in: "header" + type: "apiKey" + name: "X-API-Key" + + # parameters + parameters: + api_key: + in: "header" + name: "X-API-Key" + required: true + schema: + type: "string" + client_name: + in: "path" + name: "client_name" + required: true + schema: + $ref: "#/components/schemas/client_name" + + # responses: + responses: + ## 401 + unauthorized: + description: "Unauthorized - api_key must be present in Header" + unauthorized_public: + description: "Unauthorized - Ressource is not public" + ## 403 + forbidden: + description: "Forbidden - api_key not unauthorized" + ## 404 + not_found: + description: "Client not found" + + # schemas: + schemas: + # objects + client: + type: "object" + required: + - "name" + properties: + name: + $ref: "#/components/schemas/client_name" + description: + $ref: "#/components/schemas/client_description" + permission: + $ref: "#/components/schemas/client_permission" + public_ip: + $ref: "#/components/schemas/client_public" + admin_client_api_key: + type: "object" + properties: + name: + $ref: "#/components/schemas/client_name" + api_key: + $ref: "#/components/schemas/client_api_key" + admin_client_info_array: + type: "array" + items: + $ref: "#/components/schemas/admin_client_info" + admin_client_info: + type: "object" + properties: + name: + $ref: "#/components/schemas/client_name" + description: + $ref: "#/components/schemas/client_description" + permission: + $ref: "#/components/schemas/client_permission" + public_ip: + $ref: "#/components/schemas/client_public" + ipv4: + $ref: "#/components/schemas/client_ipv4" + client_info: + type: "object" + properties: + name: + $ref: "#/components/schemas/client_name" + ipv4: + $ref: "#/components/schemas/client_ipv4" + client_update: + type: "object" + properties: + ipv4: + $ref: "#/components/schemas/client_ipv4" + # vars + client_name: + type: "string" + minLength: 3 + maxLength: 20 + example: "clientA" + description: "Unique client identifier" + client_permission: + type: "string" + example: "rw" + pattern: "^r?w?x?$" + description: | + Set permission of client. + `r`: `client (read)` access + `w`: `client (write)` access + `x`: `admin` access + *default: w* + client_description: + type: "string" + maxLength: 200 + example: "Client across the river" + description: "default: ''" + client_public: + type: "boolean" + example: "false" + description: | + Set `true` to enable public read access + *default: false* + client_api_key: + type: "string" + example: "kakJwkejfiJkadkjhou35oi902ijsfli" + client_ipv4: + type: "string" + format: "ipv4" + example: "115.16.0.99" + pattern: "^(((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(.(?!$)|$)){4})?$" +externalDocs: + description: "Source" + url: "https://git.pdev.dev" diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 0000000..4ac8823 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::API +end diff --git a/app/controllers/clients_controller.rb b/app/controllers/clients_controller.rb new file mode 100644 index 0000000..1b4b814 --- /dev/null +++ b/app/controllers/clients_controller.rb @@ -0,0 +1,220 @@ +# frozen_string_literal: true + +require 'resolv' + +class ClientsController < ApplicationController + before_action :parse_api_key_header, except: [:show_public_ipv4] + before_action :authenticate_client, except: [:show_public_ipv4] + before_action :authorize_perm_r, only: [:show_ipv4] + before_action :authorize_perm_w, only: %i[update_ipv4 destroy_ipv4] + before_action :authorize_perm_x, only: %i[create update index show destroy] + before_action :client_authorized, except: [:show_public_ipv4] + + # URL Methods + # POST /admin/client + def create + client_params = params.permit(:name, :description, :permission, :public_ip) + return head(405) unless client_params.key?(:name) + + client = Client.find_by name: client_params[:name] + status_code = client ? 200 : 201 + + # create new client or update existing + if client.nil? + client ||= Client.new_client(client_params) + else + # return 406 if request is trying to remove perm_x from last admin account to prevent lockout + # TODO: move this into the model (update) + return head(406) if removing_last_admin?(client, client_params) + + client.update_client(client_params) + end + + api_key = client.gen_api_key + client.save + json_response({ name: client.name, api_key: api_key }, status_code) + end + + # PUT /admin/client + def update + client_params = params.permit(:name, :description, :permission, :public_ip) + return head(405) unless client_params.key?(:name) + + client = Client.find_by name: client_params[:name] + return head(404) unless client + + # return 406 if request is trying to remove perm_x from last admin account to prevent lockout + # TODO: move this into the model (update) + return head(406) if removing_last_admin?(client, client_params) + + # update client + client.update_client(client_params) + + client.save + head(200) + end + + # GET /admin/clients + def index + clients = [] + Client.find_each do |client| + clients.append admin_read_object(client) + end + json_response(clients) + end + + # GET /admin/clients/:name + def show + # return 404 if requested client does not exist + client = Client.find_by name: params[:name] + return head(404) if client.nil? + + json_response(admin_read_object(client)) + end + + # DELETE /admin/clients/:name + def destroy + client = Client.find_by(name: params[:name]) + + # return 404 if requested client does not exist + return head(404) unless client + + # return 406 if request is trying to remove last admin account to prevent lockout + # TODO: move this into the model (delete) + return head(406) if client.admin? && Client.number_of_admins <= 1 + + client.delete + + head(200) + end + + # PUT /client + def update_ipv4 + ipv4 = request_ip + + # return 406 if body with invalid ipv4 is present + # TODO: move this into the model (update) + return head(406) unless ipv4 + + @requesting_client.ipv4 = ipv4 + @requesting_client.save + json_response(client_read_object(@requesting_client)) + end + + # DELETE /client + def destroy_ipv4 + prev_data = client_read_object(@requesting_client) + @requesting_client.ipv4 = '' + @requesting_client.save + json_response(prev_data) + end + + # GET /clients/:id + def show_ipv4 + # return 404 if requested client does not exist + client = Client.find_by name: params[:name] + return head(404) if client.nil? + + json_response(client_read_object(client)) + end + + # GET /public/:id + def show_public_ipv4 + # check if client exist and is public else return 401 (don't leak existence) + client = Client.find_by name: params[:name] + return head(401) if client.nil? || !client.public_ip + + json_response(client_read_object(client)) + end + + private + + # helper methods + + # respond with json object and status + def json_response(object, status = :ok) + render json: object, status: status + end + + # checks if request is trying to remove the last admin + def removing_last_admin?(client, params) + return false unless params[:permission].is_a?(String) + + client.admin? && !Client.parse_perm_string(params[:permission])[:x] && Client.number_of_admins <= 1 + end + + def client_read_object(client) + { + name: client.name, + ipv4: client.ipv4 + } + end + + def admin_read_object(client) + { + name: client.name, + description: client.description, + permission: client.permission, + public_ip: client.public_ip, + ipv4: client.ipv4 + } + end + + def request_ip + ipv4_params = params.permit(:ipv4) + if ipv4_params.key?(:ipv4) + return nil unless ipv4_params[:ipv4].match(Resolv::IPv4::Regex) + + ipv4_params[:ipv4] + else + request.remote_ip + end + end + + # before_action methods + + # check if the api is valid and has the appropriate prefix + def parse_api_key_header + # TODO: move api_key checks and formatting to helper class + # check if api key is present and can be split into 3 parts: .. + # NOTE: .compact is more for got measure than really necessary, but this ensures no nil values in the array + api_key_header = request.headers[RynDNS::Application::API_KEY_HEADER].split('.').compact unless + request.headers[RynDNS::Application::API_KEY_HEADER].nil? + return head(401) if api_key_header.nil? || api_key_header.length < 3 + + prefix, @name_id, @api_key = api_key_header + # check if prefix matches (do this securely to prevent timing attacks on the prefix) + return head(403) unless ActiveSupport::SecurityUtils.secure_compare(prefix, + RynDNS::Application::API_KEY_PREFIX) + end + + # authenticate the client with the supplied api key + def authenticate_client + # load the request client else return 403 + @requesting_client = Client.find_by name_id: @name_id + return head(403) unless @requesting_client + + # compare api_key with hash value else return 403 + return head(403) unless @requesting_client.api_key == @api_key + end + + # check if requesting client has read permission + def authorize_perm_r + @authorized = @requesting_client.read? + end + + # check if requesting client has write permission + def authorize_perm_w + @authorized = @requesting_client.write? + end + + # check if requesting client has admin permission + def authorize_perm_x + @authorized = @requesting_client.admin? + end + + # check if request is authorized + def client_authorized + return head(403) unless @authorized + end +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /dev/null +++ b/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/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 0000000..10a4cba --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true +end diff --git a/app/models/client.rb b/app/models/client.rb new file mode 100644 index 0000000..c37cfdb --- /dev/null +++ b/app/models/client.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +class Client < ApplicationRecord + + def self.new_client(params) + perm_string = params[:permission] || 'w' # create write client by default + perm_rwx = Client.parse_perm_string(perm_string) + + new(params.except(:permission)).tap do |client| + client.name_id = Digest::SHA1.hexdigest(client.name + SecureRandom.base64(8))[0, 8] + client.perm_r = perm_rwx[:r] + client.perm_w = perm_rwx[:w] + client.perm_x = perm_rwx[:x] + end + end + + def update_client(params) + perm_rwx = Client.parse_perm_string(params[:permission]) + + update(params.except(:permission)) + return unless perm_rwx + + self.perm_r = perm_rwx[:r] + self.perm_w = perm_rwx[:w] + self.perm_x = perm_rwx[:x] + end + + def gen_api_key + api_key = SecureRandom.hex(32) + self.api_key = api_key + "#{RynDNS::Application::API_KEY_PREFIX}.#{self.name_id}.#{api_key}" + end + + def api_key + @api_key ||= BCrypt::Password.new(api_key_hash) + end + + def api_key=(new_api_key) + @api_key = BCrypt::Password.create(new_api_key) # TODO: benchmark cost on target hw + self.api_key_hash = @api_key + end + + def permission + "#{'r' if perm_r}#{'w' if perm_w}#{'x' if perm_x}" + end + + def read? + perm_r + end + + def write? + perm_w + end + + def admin? + perm_x + end + + def self.number_of_admins + Client.where({ perm_x: true }).count + end + + def self.admins? + Client.number_of_admins >= 1 + end + + # helper functions + def self.parse_perm_string(perm_string) + return nil unless perm_string.is_a?(String) + + perm_rwx = { r: false, w: false, x: false } + return perm_rwx unless perm_string + + perm_string.each_char { |c| perm_rwx[c.to_sym] = true unless perm_rwx[c.to_sym].nil? } + perm_rwx + end + + # validations + validates_presence_of :name, :name_id, :api_key_hash + validates :name, length: { in: 3..20 }, uniqueness: true + validates :name_id, length: { is: 8 }, uniqueness: true + validates :description, length: { maximum: 200 } + validates :ipv4, length: { maximum: 15 } + validates_format_of :name, with: /\A([0-9a-zA-z_\-.@]){3,20}\z/i + +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/app/views/layouts/.keep b/app/views/layouts/.keep new file mode 100644 index 0000000..e69de29 diff --git a/bin/rails b/bin/rails new file mode 100755 index 0000000..21d3e02 --- /dev/null +++ b/bin/rails @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +load File.expand_path("spring", __dir__) +APP_PATH = File.expand_path('../config/application', __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake new file mode 100755 index 0000000..7327f47 --- /dev/null +++ b/bin/rake @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +load File.expand_path("spring", __dir__) +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..5792302 --- /dev/null +++ b/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path('..', __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +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! 'gem install bundler --conservative' + 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' + + puts "\n== Removing old logs and tempfiles ==" + system! 'bin/rails log:clear tmp:clear' + + puts "\n== Restarting application server ==" + system! 'bin/rails restart' +end diff --git a/bin/spring b/bin/spring new file mode 100755 index 0000000..9675cce --- /dev/null +++ b/bin/spring @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +if !defined?(Spring) && [nil, "development", "test"].include?(ENV["RAILS_ENV"]) + gem "bundler" + require "bundler" + + # Load Spring without loading other gems in the Gemfile, for speed. + Bundler.locked_gems.specs.find { |spec| spec.name == "spring" }&.tap do |spring| + Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path + gem "spring", spring.version + require "spring/binstub" + rescue Gem::LoadError + # Ignore when Spring is not installed. + end +end diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..6dc8321 --- /dev/null +++ b/config.ru @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +# 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/config/application.rb b/config/application.rb new file mode 100644 index 0000000..addd7c6 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,62 @@ +# frozen_string_literal: true + +require_relative 'boot' + +require 'rails' +# Pick the frameworks you want: +require 'active_model/railtie' +require 'active_job/railtie' +require 'active_record/railtie' +require 'action_controller/railtie' +require 'action_view/railtie' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module RynDNS + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 6.1 + # 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 + + # FIXME: move this out of the application class + prefix_valid = lambda { |prefix| + error_msg = nil + error_msg = 'WARNING: prefix is not set' unless prefix + error_msg = 'WARNING: prefix needs to have eight characters' unless error_msg || prefix.length >= 8 + error_msg = 'WARNING: prefix needs to be alphanumeric' unless error_msg || prefix.match(/\A[a-zA-Z0-9]*\z/) + puts error_msg if error_msg + + error_msg.nil? + } + + # global constants + API_VERSION = '1.0.0' + API_VERSION_NAMESPACE = "v#{API_VERSION.split('.')[0]}" + RELATIVE_URL_ROOT = ENV['RAILS_RELATIVE_URL_ROOT'].to_s || '/' + # TODO: add configuration model to save prefix and use ENV to overwrite it + prefix = ENV['RAILS_API_KEY_PREFIX'] + if prefix_valid.call(prefix) + API_KEY_PREFIX = prefix[0, 8] + else + puts "WARNING: ENV['RAILS_API_KEY_PREFIX'] is invalid" + puts 'WARNING: Generating random prefix which will reset each server start' + API_KEY_PREFIX = SecureRandom.alphanumeric(8) + puts "Generated prefix: #{API_KEY_PREFIX}" + puts "WARNING: Please modify api_key -> #{API_KEY_PREFIX}.########.############" + end + API_KEY_HEADER = ENV['RAILS_API_KEY_HEADER'] || 'X-API-Key' + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 0000000..3cda23b --- /dev/null +++ b/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/config/database.yml b/config/database.yml new file mode 100644 index 0000000..8ba4edd --- /dev/null +++ b/config/database.yml @@ -0,0 +1,25 @@ +# 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 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: db/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: db/test.sqlite3 + +production: + <<: *default + database: data/rynDNS.sqlite3 diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 0000000..7572f39 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,66 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp', 'caching-dev.txt').exist? + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + #config.active_storage.service = :local + + # Don't care if the mailer can't send. + #config.action_mailer.raise_delivery_errors = false + + # config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # 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 + + + # 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 + + # Use an evented file watcher to asynchronously detect changes in source code, + # routes, locales, etc. This feature depends on the listen gem. + config.file_watcher = ActiveSupport::EventedFileUpdateChecker + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 0000000..e0d0d43 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,116 @@ +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.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + #config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "pdev_api_production" + + #config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # 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 + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Log disallowed deprecations. + config.active_support.disallowed_deprecation = :log + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV['RAILS_LOG_TO_STDOUT'].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Inserts middleware to perform automatic connection switching. + # The `database_selector` hash is used to pass options to the DatabaseSelector + # middleware. The `delay` is used to determine how long to wait after a write + # to send a subsequent read to the primary. + # + # The `database_resolver` class is used by the middleware to determine which + # database is appropriate to use based on the time delay. + # + # The `database_resolver_context` class is used by the middleware to set + # timestamps for the last write to the primary. The resolver uses the context + # class timestamps to determine how long to wait before reading from the + # replica. + # + # By default Rails will store a last write timestamp in the session. The + # DatabaseSelector middleware is designed as such you can define your own + # strategy for connection switching and pass that into the middleware through + # these configuration options. + # config.active_record.database_selector = { delay: 2.seconds } + # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver + # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session + + # since no tokens are involved this doesn't really need to be persistent + config.secret_key_base = ENV['SECRET_KEY_BASE'] || SecureRandom.hex(64) +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 0000000..980b823 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,60 @@ +require "active_support/core_ext/integer/time" + +# 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. + + config.cache_classes = false + config.action_view.cache_template_loading = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + #config.active_storage.service = :test + + #config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + #config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # 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 +end diff --git a/config/initializers/application_controller_renderer.rb b/config/initializers/application_controller_renderer.rb new file mode 100644 index 0000000..89d2efa --- /dev/null +++ b/config/initializers/application_controller_renderer.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# ActiveSupport::Reloader.to_prepare do +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) +# end diff --git a/config/initializers/backtrace_silencers.rb b/config/initializers/backtrace_silencers.rb new file mode 100644 index 0000000..33699c3 --- /dev/null +++ b/config/initializers/backtrace_silencers.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } + +# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code +# by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". +Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] diff --git a/config/initializers/cors.rb b/config/initializers/cors.rb new file mode 100644 index 0000000..3b1c1b5 --- /dev/null +++ b/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/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..4b34a03 --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,6 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 0000000..ac033bf --- /dev/null +++ b/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/config/initializers/mime_types.rb b/config/initializers/mime_types.rb new file mode 100644 index 0000000..dc18996 --- /dev/null +++ b/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/config/initializers/wrap_parameters.rb b/config/initializers/wrap_parameters.rb new file mode 100644 index 0000000..bbfc396 --- /dev/null +++ b/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 0000000..cf9b342 --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,33 @@ +# 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. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# 'true': 'foo' +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 0000000..d9b3e83 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,43 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 0000000..ac8b5c0 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +Rails.application.routes.draw do + # TODO: add version namespace (API_VERSION_NAMESPACE - v1) + # allow for subdir deployment, disable format and allow :name to have all ascii symbols except / + scope RynDNS::Application::RELATIVE_URL_ROOT, format: false, constraints: { name: %r{[^/]+} } do + scope '/admin' do + post 'client', to: 'clients#create', format: false + put 'client', to: 'clients#update', format: false + resources :clients, only: %i[index show destroy], param: :name, format: false + end + scope '/client' do + # client (write) + put '', to: 'clients#update_ipv4', format: false + delete '', to: 'clients#destroy_ipv4', format: false + end + scope '/clients' do + # client (read) + get ':name', to: 'clients#show_ipv4', format: false + end + # separate public path to allow for easier segregation and controls via reverse proxy + scope '/public' do + get ':name', to: 'clients#show_public_ipv4', format: false + end + end +end diff --git a/config/spring.rb b/config/spring.rb new file mode 100644 index 0000000..db5bf13 --- /dev/null +++ b/config/spring.rb @@ -0,0 +1,6 @@ +Spring.watch( + ".ruby-version", + ".rbenv-vars", + "tmp/restart.txt", + "tmp/caching-dev.txt" +) diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 0000000..d32f76e --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket + +# Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/db/migrate/20210218044438_create_clients.rb b/db/migrate/20210218044438_create_clients.rb new file mode 100644 index 0000000..1ec1840 --- /dev/null +++ b/db/migrate/20210218044438_create_clients.rb @@ -0,0 +1,24 @@ +class CreateClients < ActiveRecord::Migration[6.1] + def change + create_table :clients do |t| + # TODO: check performance of indexing name/name_id + # prefix: char(8) + name_id sha1(name + SecureRandom.base64(8))[0, 8] + api_key: SecureRandom.hex(32) + # -> 8 + 8 + 64 = client_api_key(80+2) (delimited with '.'): + # .. + t.string :name, limit: 20, null: false, unique: true + t.string :name_id, limit: 8, null: false, unique: true + t.string :api_key_hash, null: false, limit: 60 + t.string :description, limit: 200, default: '' + t.boolean :perm_r, default: false + t.boolean :perm_w, default: false + t.boolean :perm_x, default: false + t.boolean :public_ip, default: false + t.string :ipv4, limit: 15, default: '' + + t.timestamps + end + end +end + +# reset with all migrations with +# rake db:drop db:create db:migrate diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000..44ea810 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,29 @@ +# 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.define(version: 2021_02_18_044438) do + + create_table "clients", force: :cascade do |t| + t.string "name", limit: 20, null: false + t.string "name_id", limit: 8, null: false + t.string "api_key_hash", limit: 60, null: false + t.string "description", limit: 200, default: "" + t.boolean "perm_r", default: false + t.boolean "perm_w", default: false + t.boolean "perm_x", default: false + t.boolean "public_ip", default: false + t.string "ipv4", limit: 15, default: "" + t.datetime "created_at", precision: 6, null: false + t.datetime "updated_at", precision: 6, null: false + end + +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000..3101ea0 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,42 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) +# Character.create(name: 'Luke', movie: movies.first) + +# run `rails db:seed` or `rails db:seed RAILS_RESET_ADMIN=''` +# Rails.application.load_seed from within rails + +# reseed db with default admin account +if (!Client.admins? || ENV['RAILS_RESET_ADMIN']) && !ENV['RAILS_API_DEMO'] + output = ENV['RAILS_RESET_ADMIN'] ? 'Resetting admin account' : 'No admin accounts in Database, adding default: admin' + puts output + admin = Client.find_by name: 'admin' + admin ||= Client.new_client({ name: 'admin' }) + api_key = admin.gen_api_key + admin.update_client(({ permission: 'rwx' })) + admin.save + puts "Created default admin with api_key: #{api_key}" +end + +if ENV['RAILS_API_DEMO'] + puts 'WARNING: Clearing DB and loading demo clients' + Client.delete_all + demo_clients = [ + { name: 'admin', name_id: '41a7c846', description: 'Demo Admin', permission: 'rwx', + api_key: '23b142e6451df545d5034ca8f6050b80ff3e9689f20d5e45d72d160fa7e1cf32' }, + { name: 'read_client', name_id: '28aef5cb', description: 'Demo Read Client', permission: 'r', + api_key: 'd502cb94ba0802c6363f95ecb3a70de7e2e4b889779e435b7c033f2c72ed4f20' }, + { name: 'write_client', name_id: '3d6129cc', description: 'Demo Write Client', permission: 'w', ipv4: '127.0.0.1', + api_key: '48d41d2a28b16a9a274d3f407026aee2b82cddbb3c11a5496ffe329c78e5d54b' } + ] + demo_clients.each do |client_params| + client = Client.new_client(client_params) + client.update(client_params.slice(:name_id)) # to force name_id + client.save + puts "Client Name: #{client.name}" + puts "api_key: #{RynDNS::Application::API_KEY_PREFIX}.#{client.name_id}.#{client_params[:api_key]}" + end +end diff --git a/lib/enums/status_code.rb b/lib/enums/status_code.rb new file mode 100644 index 0000000..c0882b9 --- /dev/null +++ b/lib/enums/status_code.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +class StatusCode + include Ruby::Enum + + define :HTTP_200 + define :HTTP_201 + define :HTTP_401 + define :HTTP_403 + define :HTTP_404 + define :HTTP_405 + define :UNKNOWN +end diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/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/spec/factories/clients.rb b/spec/factories/clients.rb new file mode 100644 index 0000000..48e5151 --- /dev/null +++ b/spec/factories/clients.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +FactoryBot.define do + factory :client do + name { random_string } + name_id { Faker::Internet.base64(length: 8, padding: false) } + api_key_hash { bcrypt_fake_hash } + description { Faker::String.random(length: 0..200) } + perm_r { Faker::Boolean.boolean } + perm_w { Faker::Boolean.boolean } + perm_x { false } # dont want to create random admin accounts + public_ip { Faker::Boolean.boolean } + ipv4 { empty_or_fake(Faker::Internet.public_ip_v4_address) } + end + # premade clients + # NOTE: api key and hash are hardcoded to speed up testing + factory :admin, class: 'Client' do + name { 'admin' } + name_id { 'd5d40cd9' } + # api_key { 'e2s1BsQEqmSE5MqyHYbDBVxGr/KY4BYIV5QkdjiCOF0=' } + api_key_hash { '$2y$08$peZ67RvHVjBmfhUkE8tBtexMRka9w4CPBk7dJfSp5VM4HMWxX8p/y' } + description { 'e2s1BsQEqmSE5MqyHYbDBVxGr/KY4BYIV5QkdjiCOF0=' } # misusing description to access api key in rspec + perm_r { true } + perm_w { true } + perm_x { true } + public_ip { false } + ipv4 { '' } + end + factory :public, class: 'Client' do + name { 'public_client.com.' } + name_id { '23acfa41' } + # api_key { 'Tn32gdYAlo1yY6RerRtwCO8KNrqFbh9m0ijyHPDqQJs=' } + api_key_hash { '$2y$08$2AMXQs/VQMIxyJBLeBr1vOiSX2NnEPE7RHberXMUD2B8uNx/SpGX2' } + description { 'Public Account' } + perm_r { false } + perm_w { true } + perm_x { false } + public_ip { true } + ipv4 { '153.25.33.4' } + end + factory :read, class: 'Client' do + name { 'read_client' } + name_id { '438fc1d4' } + # api_key { 'E1JtENz4PMLlFQzM63PyWjVIk1PunZPieYueYdM8I34=' } + api_key_hash { '$2y$08$a0v8JSbnHdKPqzqoZEg0qO1KHmt5TCiJSz.ICUl/MztuRw6vuNzJm' } + description { 'E1JtENz4PMLlFQzM63PyWjVIk1PunZPieYueYdM8I34=' } # misusing description to access api key in rspec + perm_r { true } + perm_w { false } + perm_x { false } + public_ip { false } + ipv4 { '' } + end + factory :write, class: 'Client' do + name { 'write_client' } + name_id { '7490d4ea' } + # api_key { 'Ll8XPUfDfKs5WHuY0Is/MKC8Lv3ysEgQOUc+Ya3HcuY=' } + api_key_hash { '$2y$08$qoo/wj5eytLQzl6bYLpPyuERdoPizOqkaq/EPIT4R8c8CADfwIQ7C' } + description { 'Ll8XPUfDfKs5WHuY0Is/MKC8Lv3ysEgQOUc+Ya3HcuY=' } # misusing description to access api key in rspec + perm_r { false } + perm_w { true } + perm_x { false } + public_ip { false } + ipv4 { '44.2.55.12' } + end +end diff --git a/spec/models/client_spec.rb b/spec/models/client_spec.rb new file mode 100644 index 0000000..75adbf1 --- /dev/null +++ b/spec/models/client_spec.rb @@ -0,0 +1,7 @@ +require 'rails_helper' + +RSpec.describe Client, type: :model do + it { should validate_presence_of(:name) } + it { should validate_presence_of(:name_id) } + it { should validate_presence_of(:api_key_hash) } +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000..b871ab3 --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' + +ENV['RAILS_ENV'] ||= 'test' +require File.expand_path('../config/environment', __dir__) +# Prevent database truncation if the environment is production +abort('The Rails environment is running in production mode!') if Rails.env.production? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! +require 'database_cleaner' + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } + +Shoulda::Matchers.configure do |config| + config.integrate do |with| + with.library :rails + with.test_framework :rspec + end +end + +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + puts e.to_s.strip + exit 1 +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, type: :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://relishapp.com/rspec/rspec-rails/docs + config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") + config.include RequestSpecHelper, type: :request +end diff --git a/spec/requests/clients_request_spec.rb b/spec/requests/clients_request_spec.rb new file mode 100644 index 0000000..0af5d50 --- /dev/null +++ b/spec/requests/clients_request_spec.rb @@ -0,0 +1,576 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe 'Clients', type: :request do + let!(:admin_client) { create(:admin) } + let!(:public_client) { create(:public) } + let!(:read_client) { create(:read) } + let!(:write_client) { create(:write) } + let!(:clients) { create_list(:client, 20) } + let(:random_client) { clients[Faker::Number.between(from: 0, to: clients.length - 1)] } + let(:valid_client) do + { + name: 'clientA', + description: 'Client across the river', + permission: 'rw', + public_ip: false + } + end + let(:valid_client_update) do + { + name: 'clientA', + permission: 'w', + public_ip: true + } + end + let(:random_client_update) do + { + name: random_client.name, + description: 'updated description', + public_ip: !random_client.public_ip # swap boolean + } + end + let(:admin_perm_update) do + { + name: admin_client.name, + public_ip: !admin_client.public_ip, # swap boolean + permission: 'rw' + } + end + let(:invalid_client_update) { { names: 'clientA' } } + let(:non_existing_client) { 'DOES_NOT_EXIST_123546' } + + # admin + describe 'POST /admin/client' do + + context 'when sending a valid update request' do + before { post '/admin/client', params: valid_client, headers: api_key_header(admin_client) } + + it 'updates client from rw to w and returns 200' do + api_key = json_response['api_key'] + post '/admin/client', params: valid_client_update, headers: api_key_header(admin_client) + expect(json_response).not_to be_empty + expect(json_response['api_key'].length).to eq 82 + expect(json_response['api_key'].length).not_to eq api_key + expect(response).to have_http_status(200) + api_key = json_response['api_key'] + client_name = json_response['name'] + # check if request was parsed properly + get "/admin/clients/#{client_name}", headers: api_key_header(admin_client) + expect(json_response).not_to be_empty + expect(json_response['name']).to eq valid_client[:name] + expect(json_response['description']).to eq valid_client[:description] + expect(json_response['permission']).to eq valid_client_update[:permission] + expect(json_response['public_ip']).to eq valid_client_update[:public_ip] + expect(response).to have_http_status(200) + # test the new api_key write + put '/client', headers: api_key_header(nil, api_key) + expect(json_response).not_to be_empty + expect(response).to have_http_status(200) + # test the new api_key read + get "/clients/#{client_name}", headers: api_key_header(nil, api_key) + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when sending a valid request' do + before { post '/admin/client', params: valid_client, headers: api_key_header(admin_client) } + + it 'creates client that can read/write and returns 201' do + expect(json_response).not_to be_empty + expect(json_response['name']).to eq valid_client[:name] + expect(json_response['api_key'].length).to eq 82 + expect(response).to have_http_status(201) + api_key = json_response['api_key'] + # check if request was parsed properly + get "/admin/clients/#{valid_client[:name]}", headers: api_key_header(admin_client) + expect(json_response).not_to be_empty + expect(json_response['name']).to eq valid_client[:name] + expect(json_response['description']).to eq valid_client[:description] + expect(json_response['permission']).to eq valid_client[:permission] + expect(json_response['public_ip']).to eq valid_client[:public_ip] + expect(response).to have_http_status(200) + # test the new client write + put '/client', headers: api_key_header(nil, api_key) + expect(json_response).not_to be_empty + expect(response).to have_http_status(200) + ipv4 = json_response['ipv4'] + # test the new client read + get "/clients/#{valid_client[:name]}", headers: api_key_header(nil, api_key) + expect(json_response).not_to be_empty + expect(response).to have_http_status(200) + expect(json_response['ipv4']).to eq ipv4 + end + end + + context 'when sending a valid request without api_key' do + let!(:client_count) { Client.count } + before { post '/admin/client', params: valid_client } + + it 'does not create client and returns status code 401' do + expect(client_count).to eq Client.count + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'when sending a valid request with non admin api_key' do + let!(:client_count) { Client.count } + before { post '/admin/client', params: valid_client, headers: api_key_header(read_client) } + + it 'does not create client and returns status code 403' do + expect(client_count).to eq Client.count + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when sending an invalid request' do + let!(:client_count) { Client.count } + before { post '/admin/client', params: invalid_client_update, headers: api_key_header(admin_client) } + + it 'does not create client and returns status code 405' do + expect(client_count).to eq Client.count + expect(response.body).to be_empty + expect(response).to have_http_status(405) + end + end + + context 'when sending a valid update request to remove last admin permission' do + before { post '/admin/client', params: admin_perm_update, headers: api_key_header(admin_client) } + + it 'does not update admin and returns status code 406' do + expect(admin_client.reload.perm_x).to eq true + expect(response.body).to be_empty + expect(response).to have_http_status(406) + end + end + + context 'when sending a valid update request to remove non last admin permission' do + before do + post '/admin/client', params: { name: 'admin2', permission: 'x' }, headers: api_key_header(admin_client) + post '/admin/client', params: admin_perm_update, headers: api_key_header(admin_client) + end + + it 'does update admin and returns status code 200' do + expect(admin_client.reload.perm_x).to eq false + expect(response.body).not_to be_empty + expect(response).to have_http_status(200) + end + end + end + + describe 'PUT /admin/client' do + + context 'when sending a valid request' do + before do + put '/admin/client', params: random_client_update, headers: api_key_header(admin_client) + random_client.reload + end + + it 'updates client and returns 200' do + expect(random_client.description).to eq random_client_update[:description] + expect(random_client.public_ip).to eq random_client_update[:public_ip] + expect(response.body).to be_empty + expect(response).to have_http_status(200) + end + end + + context 'when sending a valid request without api_key' do + before do + put '/admin/client', params: random_client_update + random_client.reload + end + + it 'does not update client and returns 401' do + expect(random_client.description).not_to eq random_client_update[:description] + expect(random_client.public_ip).not_to eq random_client_update[:public_ip] + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'when sending a valid request with non admin api_key' do + before do + put '/admin/client', params: random_client_update, headers: api_key_header(write_client) + random_client.reload + end + + it 'does not update client and returns 403' do + expect(random_client.description).not_to eq random_client_update[:description] + expect(random_client.public_ip).not_to eq random_client_update[:public_ip] + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when sending a valid request for non existing client' do + before do + random_client_update[:name] = non_existing_client + put '/admin/client', params: random_client_update, headers: api_key_header(admin_client) + random_client.reload + end + + it 'does not update client and returns 404' do + expect(random_client.description).not_to eq random_client_update[:description] + expect(random_client.public_ip).not_to eq random_client_update[:public_ip] + expect(response.body).to be_empty + expect(response).to have_http_status(404) + end + end + + context 'when sending an invalid valid request' do + before { put '/admin/client', params: invalid_client_update, headers: api_key_header(admin_client) } + + it 'returns 405' do + expect(response.body).to be_empty + expect(response).to have_http_status(405) + end + end + + context 'when sending a valid valid request to remove last admin permission' do + before do + put '/admin/client', params: admin_perm_update, headers: api_key_header(admin_client) + admin_client.reload + end + + it 'does not update admin and returns 406' do + expect(admin_client.perm_x).to eq true + expect(admin_client.public_ip).to_not eq admin_perm_update[:public_ip] + expect(response.body).to be_empty + expect(response).to have_http_status(406) + end + end + + context 'when sending a valid update request to remove non last admin permission' do + before do + put '/admin/client', params: { name: random_client.name, permission: 'x' }, + headers: api_key_header(admin_client) + put '/admin/client', params: admin_perm_update, headers: api_key_header(admin_client) + end + + it 'does update admin and returns status code 200' do + expect(admin_client.reload.perm_x).to eq false + expect(response.body).to be_empty + expect(response).to have_http_status(200) + end + end + end + + describe 'GET /admin/clients' do + + context 'when requesting all clients' do + before { get '/admin/clients', headers: api_key_header(admin_client) } + it 'returns list of all clients and status code 200' do + expect(list_equals_db?(json_response)).to eq true + expect(response).to have_http_status(200) + end + end + + context 'when requesting all clients with no api_key' do + before { get '/admin/clients' } + it 'returns status code 401' do + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'when requesting all clients with write api_key' do + before { get '/admin/clients', headers: api_key_header(write_client) } + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when requesting all clients with read api_key' do + before { get '/admin/clients', headers: api_key_header(read_client) } + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + end + + describe 'GET /admin/clients/:name' do + + context 'when requesting random_client.name client with admin api_key' do + before { get "/admin/clients/#{random_client.name}", headers: api_key_header(admin_client) } + it 'returns info and status code 200' do + expect(json_response['name']).to eq random_client.name + expect(json_response['description']).to eq random_client.description + expect(json_response['permission']).to eq parse_permission(random_client.perm_r, random_client.perm_w, + random_client.perm_x) + expect(json_response['public_ip']).to eq random_client.public_ip + expect(json_response['ipv4']).to eq random_client.ipv4 + expect(response).to have_http_status(200) + end + end + + context 'when requesting random client with no api_key' do + before { get "/admin/clients/#{random_client.name}" } + it 'returns status code 401' do + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'when requesting random client with write api_key' do + before { get "/admin/clients/#{random_client.name}", headers: api_key_header(write_client) } + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when requesting random client with read api_key' do + before { get "/admin/clients/#{random_client.name}", headers: api_key_header(read_client) } + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when requesting non existing client' do + before { get "/admin/clients/#{non_existing_client}", headers: api_key_header(admin_client) } + it 'returns status code 404' do + expect(response.body).to be_empty + expect(response).to have_http_status(404) + end + end + end + + describe 'DELETE /admin/clients/:name' do + + context 'when sending a valid request' do + let!(:client_count) { Client.count - 1 } + before { delete "/admin/clients/#{random_client.name}", headers: api_key_header(admin_client) } + + it 'deletes client and returns 200' do + expect(Client.find_by(name: random_client.name)).to eq nil + expect(Client.count).to eq client_count + expect(response.body).to be_empty + expect(response).to have_http_status(200) + end + end + + context 'when sending a valid request without api_key' do + let!(:client_count) { Client.count } + before { delete "/admin/clients/#{random_client.name}" } + + it 'does not delete client and returns 401' do + expect(Client.find_by(name: random_client.name)).to eq random_client + expect(Client.count).to eq client_count + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'when sending a valid request with non admin api_key' do + let!(:client_count) { Client.count } + before { delete "/admin/clients/#{random_client.name}", headers: api_key_header(read_client) } + + it 'does not delete client and returns 403' do + expect(Client.find_by(name: random_client.name)).to eq random_client + expect(Client.count).to eq client_count + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when sending a valid request for non existing client' do + let!(:client_count) { Client.count } + before { delete "/admin/clients/#{non_existing_client}", headers: api_key_header(admin_client) } + + it 'does not delete client and returns 404' do + expect(Client.count).to eq client_count + expect(response.body).to be_empty + expect(response).to have_http_status(404) + end + end + + context 'when sending a valid valid request to delete last admin' do + let!(:client_count) { Client.count } + before { delete "/admin/clients/#{admin_client.name}", headers: api_key_header(admin_client) } + + it 'does not delete admin and returns 406' do + expect(Client.find_by(name: admin_client.name)).to eq admin_client + expect(Client.count).to eq client_count + expect(response.body).to be_empty + expect(response).to have_http_status(406) + end + end + + context 'when sending a valid update request to delete non last admin' do + let!(:client_count) { Client.count - 1 } + before do + put '/admin/client', params: { name: random_client.name, permission: 'x' }, + headers: api_key_header(admin_client) + delete "/admin/clients/#{admin_client.name}", headers: api_key_header(admin_client) + end + + it 'does delete admin and returns status code 200' do + expect(Client.find_by(name: admin_client.name)).to eq nil + expect(Client.count).to eq client_count + expect(response.body).to be_empty + expect(response).to have_http_status(200) + end + end + end + + # client (write) + describe 'PUT /client' do + + context 'when requesting with write api_key' do + before { put '/client', headers: api_key_header(write_client) } + it 'returns status code 200' do + expect(json_response['name']).to eq write_client.name + expect(json_response['ipv4']).to eq '127.0.0.1' + expect(response).to have_http_status(200) + end + end + + context 'when requesting with write api_key and body' do + before { put '/client', params: { ipv4: '99.55.66.2' }, headers: api_key_header(write_client) } + it 'returns status code 200' do + expect(json_response['name']).to eq write_client.name + expect(json_response['ipv4']).to eq '99.55.66.2' + expect(response).to have_http_status(200) + end + end + + context 'when requesting with no api_key' do + before { put '/client' } + it 'returns status code 401' do + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'when requesting with read api_key' do + before { put '/client', headers: api_key_header(read_client) } + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when requesting with api_key of non existing client' do + before do + write_client.delete + put '/client', headers: api_key_header(write_client) + end + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + end + + describe 'DELETE /client' do + + context 'when requesting with write api_key' do + before { delete '/client', headers: api_key_header(write_client) } + it 'deletes ipv4 value and returns previous value with status code 200' do + expect(json_response['name']).to eq write_client.name + expect(json_response['ipv4']).to eq write_client.ipv4 + expect(response).to have_http_status(200) + # check if deletion was successful + write_client.reload + expect(write_client.ipv4).to eq '' + end + end + + context 'when requesting with no api_key' do + before { delete '/client' } + it 'returns status code 401' do + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'when requesting with read api_key' do + before { delete '/client', headers: api_key_header(read_client) } + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when requesting with write api_key and invalid ip body' do + before { put '/client', params: { ipv4: '5.9.256.66' }, headers: api_key_header(write_client) } + it 'returns status code 406' do + expect(response.body).to be_empty + expect(response).to have_http_status(406) + end + end + end + + # client (read) + describe 'GET /clients/:name' do + + context 'when requesting write client with read api_key' do + before { get "/clients/#{write_client.name}", headers: api_key_header(read_client) } + it 'returns status code 200' do + expect(json_response['name']).to eq write_client.name + expect(json_response['ipv4']).to eq write_client.ipv4 + expect(response).to have_http_status(200) + end + end + + context 'when requesting write client with no api_key' do + before { get "/clients/#{write_client.name}" } + it 'returns status code 401' do + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'request write client with write api_key' do + before { get "/clients/#{write_client.name}", headers: api_key_header(write_client) } + it 'returns status code 403' do + expect(response.body).to be_empty + expect(response).to have_http_status(403) + end + end + + context 'when requesting non existing client' do + before { get "/clients/#{non_existing_client}", headers: api_key_header(read_client) } + it 'returns status code 404' do + expect(response.body).to be_empty + expect(response).to have_http_status(404) + end + end + end + + # public + describe 'GET /public/:name' do + + context 'request public client' do + before { get "/public/#{public_client.name}" } + it 'returns status code 200' do + expect(json_response['name']).to eq public_client.name + expect(json_response['ipv4']).to eq public_client.ipv4 + expect(response).to have_http_status(200) + end + end + + context 'request non existing client' do + before { get "/public/#{non_existing_client}" } + it 'returns status code 401' do + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + + context 'request non-public client' do + before { get "/public/#{write_client.name}" } + it 'returns status code 401' do + expect(response.body).to be_empty + expect(response).to have_http_status(401) + end + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..ce33d66 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,96 @@ +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/spec/support/factory_bot.rb b/spec/support/factory_bot.rb new file mode 100644 index 0000000..c7890e4 --- /dev/null +++ b/spec/support/factory_bot.rb @@ -0,0 +1,3 @@ +RSpec.configure do |config| + config.include FactoryBot::Syntax::Methods +end diff --git a/spec/support/factory_clients_helper.rb b/spec/support/factory_clients_helper.rb new file mode 100644 index 0000000..37b979f --- /dev/null +++ b/spec/support/factory_clients_helper.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +def bcrypt_fake_hash + # bcrypt output is defined as follows: + # $$$ + # with and being base64 encoded with the following alphabet: + # ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + bcrypt_alphabet = [ + %w[. /], + Array('A'..'Z'), + Array('a'..'z'), + Array('0'..'9') + ].flatten + id = "2#{Faker::Base.sample(%w[a x y], 1).join}" + cost = format('%02d', Faker::Number.between(from: 4, to: 99)) + salt = Faker::Base.sample(bcrypt_alphabet, 22).join + digest = Faker::Base.sample(bcrypt_alphabet, 31).join + "$#{id}$#{cost}$#{salt}#{digest}" +end + +def nil_or_fake(fake) + Faker::Boolean.boolean ? fake : nil +end + +def empty_or_fake(fake) + Faker::Boolean.boolean ? fake : '' +end + +# custom alphabet for name +def random_string + alphabet = [ + %w[. _ - @], + Array('A'..'Z'), + Array('a'..'z'), + Array('0'..'9') + ].flatten + Faker::Base.sample(alphabet, 20).join[0, Faker::Number.between(from: 3, to: 19)] +end diff --git a/spec/support/request_spec_helper.rb b/spec/support/request_spec_helper.rb new file mode 100644 index 0000000..019f4a7 --- /dev/null +++ b/spec/support/request_spec_helper.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +module RequestSpecHelper + def json_response + JSON.parse(response.body) + end + + def api_key_header(client, api_key = nil) + api_key ||= [RynDNS::Application::API_KEY_PREFIX, client.name_id, client.description].join('.') + { RynDNS::Application::API_KEY_HEADER => + api_key } + end + + def parse_permission(perm_r, perm_w, perm_x) + "#{'r' if perm_r}#{'w' if perm_w}#{'x' if perm_x}" + end + + def list_equals_db?(client_list) + return false unless Client.count == client_list.count + + client_list.each do |client| + db_client = Client.find_by name: client[:name.to_s] + return false unless db_client.description == client[:description.to_s] && + db_client.permission == client[:permission.to_s] && + db_client.public_ip == client[:public_ip.to_s] && + db_client.ipv4 == client[:ipv4.to_s] + end + true + end + +end diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 0000000..e69de29