From c5c8aee8a7981f770512a0def7722288d19d1ab7 Mon Sep 17 00:00:00 2001 From: John Finberg Date: Wed, 21 Aug 2024 22:07:28 -0700 Subject: [PATCH] feat: ruby sdk --- .github/workflows/release.yaml | 47 +++++++++ .gitignore | 8 ++ Gemfile | 11 +++ Gemfile.lock | 53 +++++++++++ LICENSE | 21 +++++ README.md | 69 ++++++++++++++ Rakefile | 4 + bin/console | 11 +++ bin/setup | 8 ++ examples/test.rb | 27 ++++++ fortress.gemspec | 40 ++++++++ lib/crypto.rb | 68 +++++++++++++ lib/fortress.rb | 168 +++++++++++++++++++++++++++++++++ lib/fortress/version.rb | 5 + 14 files changed, 540 insertions(+) create mode 100644 .github/workflows/release.yaml create mode 100644 .gitignore create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 LICENSE create mode 100644 README.md create mode 100644 Rakefile create mode 100755 bin/console create mode 100755 bin/setup create mode 100644 examples/test.rb create mode 100644 fortress.gemspec create mode 100644 lib/crypto.rb create mode 100644 lib/fortress.rb create mode 100644 lib/fortress/version.rb diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..81d83f0 --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,47 @@ +name: Create Release + +on: + push: + tags: + - "v*.*.*" + +jobs: + build: + name: Build + Publish + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - uses: actions/checkout@v4 + - name: Set up Ruby 3.1.2 + # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, + # change this to (see https://github.com/ruby/setup-ruby#versioning): + # uses: ruby/setup-ruby@v1 + uses: ruby/setup-ruby@55283cc23133118229fd3f97f9336ee23a179fcf # v1.146.0 + with: + ruby-version: 3.1.2 + + - name: Publish to GPR + run: | + mkdir -p $HOME/.gem + touch $HOME/.gem/credentials + chmod 0600 $HOME/.gem/credentials + printf -- "---\n:github: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials + gem build *.gemspec + gem push --KEY github --host https://rubygems.pkg.github.com/${OWNER} *.gem + env: + GEM_HOST_API_KEY: "Bearer ${{secrets.GIT_TOKEN}}" + OWNER: ${{ github.repository_owner }} + + - name: Publish to RubyGems + run: | + mkdir -p $HOME/.gem + touch $HOME/.gem/credentials + chmod 0600 $HOME/.gem/credentials + printf -- "---\n:rubygems_api_key: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials + gem build *.gemspec + gem push *.gem + env: + GEM_HOST_API_KEY: "${{secrets.RUBYGEMS_AUTH_TOKEN}}" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9106b2a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..a8d07c3 --- /dev/null +++ b/Gemfile @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' + +# Specify your gem's dependencies in fortress.gemspec +gemspec + +gem 'pg' +gem 'rake', '~> 13.0' +gem 'rubocop', '~> 1.0', require: false +gem 'ruby-hmac' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..8ccedf4 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,53 @@ +PATH + remote: . + specs: + fortress (0.1.0) + +GEM + remote: https://rubygems.org/ + specs: + ast (2.4.2) + json (2.7.2) + language_server-protocol (3.17.0.3) + parallel (1.26.3) + parser (3.3.4.2) + ast (~> 2.4.1) + racc + pg (1.5.7) + racc (1.8.1) + rainbow (3.1.1) + rake (13.2.1) + regexp_parser (2.9.2) + rexml (3.3.5) + strscan + rubocop (1.65.1) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.4, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.31.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.32.1) + parser (>= 3.3.1.0) + ruby-hmac (0.4.0) + ruby-progressbar (1.13.0) + strscan (3.1.0) + unicode-display_width (2.5.0) + +PLATFORMS + arm64-darwin-23 + ruby + +DEPENDENCIES + fortress! + pg + rake (~> 13.0) + rubocop (~> 1.0) + ruby-hmac + +BUNDLED WITH + 2.5.17 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..78c40e7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Fortress + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..38fca50 --- /dev/null +++ b/README.md @@ -0,0 +1,69 @@ +# Fortress Ruby SDK + +Welcome to the Fortress Ruby SDK. This SDK provides a way for you to leverage the power of the Fortress platform in your Ruby applications. + +## Installation + +You can install the SDK using Gem. Simply run the following command: + +```bash +gem install fortress_sdk_ruby +``` + +## Quick Start + +Here is a quick example to get you started with the SDK: + +```ruby +require 'fortress_sdk_ruby' + +# Initialize the client +client = Fortress::Client.new(api_key, organization_id) + +# Create a new tenant +client.create_tenant("tenant_name", "alias") + +# Connect to the tenant +conn = client.connect_tenant("tenant_name") + +conn.exec('CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50))') +conn.exec("INSERT INTO users (name) VALUES ('Alice')") +conn.exec('SELECT * FROM users') do |result| + result.each do |row| + print "User: #{row['name']}\n" + end +end + +# Delete the tenant +client.delete_tenant("tenant_name") +``` + +## Documentation + +Below is a list of the available functionality in the SDK. Using the SDK you can create a new tenants and point them to existing or new databases. You can also easily route data requests based on tenant names. For more detailed information, please refer to the [Fortress API documentation](https://docs.fortress.build). + +Database Management: + +- `create_database(database_name: str, alias: str)`: Creates a new database. +- `delete_database(database_name: str)`: Deletes to a database. +- `list_databases()`: Lists all databases. +- `connect_database(database_id: str)`: Connects to a database and turns into SQL connection. + +Tenant Management: + +- `create_tenant(tenant_name: str, alias: str, database_id: str = "")`: Creates a new tenant. +- `delete_tenant(tenant_name: str)`: Deletes a tenant. +- `list_tenants()`: Lists all tenants. +- `connect_tenant(tenant_name: str)`: Connects to a tenant and turns into SQL connection. + +## Configuration + +To use the SDK, generate an API key from the Fortress dashboard to initialize the client. Also, provide the organization ID, which is available under the API Keys page on the platform website. + +## License + +This SDK is licensed under the MIT License. + +## Support + +If you have any questions or need help, don't hesitate to get in touch with our support team at founders@fortress.build. diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..cd510a0 --- /dev/null +++ b/Rakefile @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +task default: %i[] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..3980aa0 --- /dev/null +++ b/bin/console @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require "fortress" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +require "irb" +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/examples/test.rb b/examples/test.rb new file mode 100644 index 0000000..ea418f0 --- /dev/null +++ b/examples/test.rb @@ -0,0 +1,27 @@ +require_relative 'lib/fortress' + +# Create a client +client = Fortress::Fortress.new('orgId', 'apiKey') + +# Create a database +id = client.create_database('Client 1') + +# Create a tenant in that database +client.create_tenant('client1', 'Client 1', id) + +# List all tenants +client.list_tenants.each do |tenant| + print "Tenant: #{tenant.name} (#{tenant.alias})\n" +end + +# Connect to the tenant +conn = client.connect_tenant('client1') +conn.exec('CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50))') +conn.exec("INSERT INTO users (name) VALUES ('Alice')") +conn.exec("INSERT INTO users (name) VALUES ('Bob')") +conn.exec("INSERT INTO users (name) VALUES ('Charlie')") +conn.exec('SELECT * FROM users') do |result| + result.each do |row| + print "User: #{row['name']}\n" + end +end diff --git a/fortress.gemspec b/fortress.gemspec new file mode 100644 index 0000000..ea21963 --- /dev/null +++ b/fortress.gemspec @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require_relative 'lib/fortress/version' + +Gem::Specification.new do |spec| + spec.name = 'fortress' + spec.version = Fortress::VERSION + spec.authors = ['Fortress'] + spec.email = ['founder@fortress.build'] + + spec.summary = 'The Fortress SDK for Ruby' + spec.description = 'This is the official Ruby SDK for Fortress. It provides a simple way to interact with the Fortress API.' + spec.homepage = 'https://fortress.build' + spec.required_ruby_version = '>= 3.0.0' + + spec.metadata['allowed_push_host'] = 'https://rubygems.pkg.github.com/fortress-build' + + spec.metadata['homepage_uri'] = spec.homepage + spec.metadata['source_code_uri'] = 'https://github.com/fortress-build/sdk-ruby' + spec.metadata['changelog_uri'] = 'https://github.com/fortress-build/sdk-python' + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + gemspec = File.basename(__FILE__) + spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| + ls.readlines("\x0", chomp: true).reject do |f| + (f == gemspec) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git appveyor Gemfile]) + end + end + spec.bindir = 'exe' + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ['lib'] + + # Uncomment to register a new dependency of your gem + # spec.add_dependency "example-gem", "~> 1.0" + + # For more information and examples about making a new gem, check out our + # guide at: https://bundler.io/guides/creating_gem.html +end diff --git a/lib/crypto.rb b/lib/crypto.rb new file mode 100644 index 0000000..3c7a3f3 --- /dev/null +++ b/lib/crypto.rb @@ -0,0 +1,68 @@ +require 'openssl' +require 'base64' +require 'digest' +require 'hmac' +require 'hmac-sha1' + +module Fortress + # Crypto provides methods to encrypt and decrypt data using the ECIES algorithm. + module Crypto + # Decrypts the ciphertext using the provided private key. + def self.decrypt(private_key, ciphertext) + # Format the private key + formated_private_key = "-----BEGIN EC PRIVATE KEY-----\n#{private_key}\n-----END EC PRIVATE KEY-----" + + # Load the private key + private_key = OpenSSL::PKey::EC.new(formated_private_key) + private_key.check_key + + # Decode the ciphertext + ciphertext = Base64.decode64(ciphertext) + + # Extract the ephemeral public key + ephemeral_size = ciphertext[0].ord + ephemeral_public_key = ciphertext[1, ephemeral_size] + + # Extract the MAC and AES-GCM ciphertext + sha1_size = 20 + aes_size = 16 + ciphertext = ciphertext[(1 + ephemeral_size)..-1] + + # Verify the ciphertext length + raise 'Invalid ciphertext' if ciphertext.length < sha1_size + aes_size + + # Derive the public key + eph_pub = OpenSSL::PKey::EC::Point.new(OpenSSL::PKey::EC::Group.new('prime256v1'), + OpenSSL::BN.new(ephemeral_public_key, 2)) + + # Perform the ECDH key exchange + shared_key = private_key.dh_compute_key(eph_pub) + + # Derive the shared key + shared = Digest::SHA256.digest(shared_key) + + # Verify the MAC + tag_start = ciphertext.length - sha1_size + hmac = HMAC::SHA1.new(shared[16, 16]) + hmac.update(ciphertext[0, tag_start]) + mac = hmac.digest + + raise 'Invalid MAC' unless mac == ciphertext[tag_start..-1] + + # Decrypt the ciphertext using AES-CBC + cipher = OpenSSL::Cipher.new('aes-128-cbc') + cipher.decrypt + cipher.key = shared[0, 16] + cipher.iv = ciphertext[0, aes_size] + cipher.padding = 0 + + plaintext = cipher.update(ciphertext[aes_size, tag_start - aes_size]) + cipher.final + + # Remove padding + padding_length = plaintext[-1].ord + plaintext = plaintext[0...-padding_length] + + plaintext.force_encoding('UTF-8') + end + end +end diff --git a/lib/fortress.rb b/lib/fortress.rb new file mode 100644 index 0000000..f4955df --- /dev/null +++ b/lib/fortress.rb @@ -0,0 +1,168 @@ +# frozen_string_literal: true + +require_relative 'fortress/version' +require_relative 'crypto' +require 'uri' +require 'net/http' +require 'json' +require 'base64' +require 'pg' + +# Fortress is a Ruby client for the Fortress API. +# +# It provides methods to manage tenants and databases in the Fortress platform. +# +# @example +# fortress = Fortress.new('org_id', 'api_key') +# +module Fortress + class Error < StandardError; end + + # Define the Tenant struct here + Tenant = Struct.new(:name, :alias, :database_id, :date_created) do + def to_json(*_args) + { id:, alias: self.alias }.to_json + end + end + + # Define the Database struct here + Database = Struct.new(:id, :alias, :bytes_size, :average_read_iops, :average_write_iops, :date_created) do + def to_json(*_args) + { id:, alias: self.alias }.to_json + end + end + + # Client provides methods to interact with the Fortress API. + # It requires an organization ID and an API key to authenticate requests. + class Fortress + BASE_URL = 'https://api.fortress.build' + attr_reader :org_id, :api_key + + # Create a new Fortress client. + # @param org_id [String] The organization ID. + # @param api_key [String] The API key. + # @return [Fortress] The Fortress client. + def initialize(org_id, api_key) + @org_id = org_id + @api_key = api_key + end + + # Connect to a tenant. + # @param id [String] The tenant ID. + # @return [PG::Connection] The connection to the tenant database. + def connect_tenant(id) + connection_details = get_connection_uri(id, 'tenant') + PG::Connection.new(dbname: connection_details.database, user: connection_details.username, + password: connection_details.password, host: connection_details.url, port: connection_details.port) + end + + # Create a tenant in a database. + # @param id [String] The tenant ID. + # @param tenant_alias [String] The tenant alias. + # @param database_id [String] The database ID. (optional) + # @return [void] + def create_tenant(id, tenant_alias, database_id = nil) + endpoint = "#{BASE_URL}/v1/organization/#{@org_id}/tenant/#{id}" + body = { alias: tenant_alias } + body[:databaseId] = database_id if database_id + _ = make_request(:post, endpoint, body) + end + + # List all tenants in the organization. + # @return [Array] The list of tenants. + def list_tenants + endpoint = "#{BASE_URL}/v1/organization/#{@org_id}/tenants" + response = make_request(:get, endpoint) + tenants = response['tenants'] + tenants.map do |tenant| + Tenant.new(tenant['name'], tenant['alias'], tenant['databaseId'], tenant['dateCreated']) + end + end + + # Delete a tenant. + # @param id [String] The tenant ID. + # @return [void] + def delete_tenant(id) + endpoint = "#{BASE_URL}/v1/organization/#{@org_id}/tenant/#{id}" + _ = make_request(:delete, endpoint) + end + + def connect_database(id) + connection_details = get_connection_uri(id, 'database') + PG::Connection.new(dbname: connection_details.database, user: connection_details.username, + password: connection_details.password, host: connection_details.url, port: connection_details.port) + end + + # Create a database. + # @param database_alias [String] The database alias. + # @return [String] The database ID. + def create_database(database_alias) + endpoint = "#{BASE_URL}/v1/organization/#{@org_id}/database" + response = make_request(:post, endpoint, { alias: database_alias }) + response['id'] + end + + # List all databases in the organization. + # @return [Array] The list of databases. + def list_databases + endpoint = "#{BASE_URL}/v1/organization/#{@org_id}/databases" + response = make_request(:get, endpoint) + databases = response['databases'] + databases.map do |database| + Database.new(database['id'], database['alias'], database['bytesSize'], + database['averageReadIOPS'], database['averageWriteIOPS'], database['dateCreated']) + end + end + + # Delete a database. + # @param id [String] The database ID. + def delete_database(id) + endpoint = "#{BASE_URL}/v1/organization/#{@org_id}/database/#{id}" + _ = make_request(:delete, endpoint) + end + + private + + ConnectionDetails = Struct.new(:database_id, :url, :port, :username, :password, :database) do + def to_json(*_args) + { database_id:, url:, port:, username:, password:, database: }.to_json + end + end + + def get_connection_uri(id, type) + endpoint = "#{BASE_URL}/v1/organization/#{@org_id}/#{type}/#{id}/uri" + + response = make_request(:get, endpoint) + connection_details_encrypted = response['connectionDetails'] + connection_details_decrypted = Crypto.decrypt(@api_key, connection_details_encrypted) + connection_details = JSON.parse(connection_details_decrypted) + ConnectionDetails.new(connection_details['databaseId'].to_i, connection_details['url'], + connection_details['port'].to_i, connection_details['username'], connection_details['password'], connection_details['database']) + end + + def make_request(method, url, body = nil) + uri = URI.parse(url) + + request = Net::HTTP.const_get(method.capitalize).new(uri) + request['Content-Type'] = 'application/json' + request['Api-Key'] = @api_key + http = Net::HTTP.new(uri.host, uri.port) + + # TODO: Enable SSL + http.use_ssl = true + + request.body = body.to_json if body + + parse_response(http.request(request)) + end + + def parse_response(response) + case response + when Net::HTTPSuccess + JSON.parse(response.body) + else + raise Error, "Request failed with response code #{response.code}: #{response.message}" + end + end + end +end diff --git a/lib/fortress/version.rb b/lib/fortress/version.rb new file mode 100644 index 0000000..40c6bc4 --- /dev/null +++ b/lib/fortress/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Fortress + VERSION = "0.1.0" +end