Skip to content

Commit

Permalink
feat: ruby sdk
Browse files Browse the repository at this point in the history
  • Loading branch information
John2360 committed Aug 22, 2024
0 parents commit c5c8aee
Show file tree
Hide file tree
Showing 14 changed files with 540 additions and 0 deletions.
47 changes: 47 additions & 0 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -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}}"
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
11 changes: 11 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -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'
53 changes: 53 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
69 changes: 69 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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 [email protected].
4 changes: 4 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# frozen_string_literal: true

require "bundler/gem_tasks"
task default: %i[]
11 changes: 11 additions & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -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__)
8 changes: 8 additions & 0 deletions bin/setup
Original file line number Diff line number Diff line change
@@ -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
27 changes: 27 additions & 0 deletions examples/test.rb
Original file line number Diff line number Diff line change
@@ -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
40 changes: 40 additions & 0 deletions fortress.gemspec
Original file line number Diff line number Diff line change
@@ -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 = ['[email protected]']

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
68 changes: 68 additions & 0 deletions lib/crypto.rb
Original file line number Diff line number Diff line change
@@ -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
Loading

0 comments on commit c5c8aee

Please sign in to comment.