Compare commits

5 Commits

Author SHA1 Message Date
297016e799 [add] added query string support 2021-03-07 19:11:49 -05:00
c0a05f653c [mod] modified readme
- removed zero width spaces
 - added some more examples and roadmap
2021-03-07 18:41:54 -05:00
8bbd3e02f3 [add] added readme 2021-03-04 13:07:36 -05:00
a0ff5cdebb [fix][add][mod] fixed typo in api.yml, added data folder and modified compose
- [add] added existing data folder to prevent docker creating one as root
 - [mod] docker-compose.yml now uses $EUID as default user and group id
2021-03-04 13:07:28 -05:00
d5b1006d2a [fix] cleanup server pid file on ungraceful shutdown in container 2021-03-04 13:04:21 -05:00
9 changed files with 193 additions and 44 deletions

137
README.md
View File

@@ -1,24 +1,135 @@
# README
<h1 align="center">rynDNS</h1>
This README would normally document whatever steps are necessary to get the
application up and running.
<h4 align="center">
A simplistic Dynamic DNS-ish server.
</h4>
Things you may want to cover:
`rynDNS` is a simple REST-API for `name` to `ip` resolving in the spirit of Dynamic DNS. Clients can `PUT` their `ipv4` address up to be read by other clients. Access is controlled via `api_key` and permissions (`read`, `write`, `admin`). No special client side application needed, just something to do a `POST` request like `wget`, `curl` or `httpie`.
* Ruby version
<p align="center">
<strong>
<a href="https://demo.api.pdev.dev">Demo</a>
• <a href="#getting-started">Getting started</a>
• <a href="#rest-api">Rest API</a>
• <a href="#configuration">Configuration</a>
• <a href="#roadmap">Roadmap</a>
</strong>
</p>
* System dependencies
## Getting Started
* Configuration
This repo includes a [`Dockerfile`](Dockerfile) with an accompanying [`docker-compose.yml`](docker-compose.yml). To build and launch the container simply run:
```bash
docker-compose up
```
Once the container is build and running it will create a default admin account and post its randomly generated api key to the console:
```
ryndns | No admin accounts in Database, adding default: admin
ryndns | Created default admin with api_key: 3NJbP4tS.39b92576.062...
```
The API is now accessible at http://localhost:3000/rynDNS.
```bash
# using httpie
API_SERVER=http://localhost:3000/rynDNS
API_KEY=X-API-Key:3NJbP4tS.39b92576.062142e6451df545d5034ca8f6050b80ff3e9689f20d5e45d72d160fa7e1cf32
* Database creation
# list all clients
http get $API_SERVER/admin/clients $API_KEY
* Database initialization
# creating a client
JSON_REQUEST_BODY='{
"name": "clientA",
"description": "Client across the river",
"permission": "rw",
"public_ip": false
}'
http post $API_SERVER/admin/client $API_KEY <<< $JSON_REQUEST_BODY
```
Updating a write client's `ipv4`:
```bash
# using httpie
API_SERVER=http://localhost:3000/rynDNS
API_KEY=X-API-Key:zW3If4s5.3d6129cc.48d41d2a28b16a9a274d3f407026aee2b82cddbb3c11a5496ffe329c78e5d54b
* How to run the test suite
# automatically set ip based on request itself
http put $API_SERVER/client $API_KEY
* Services (job queues, cache servers, search engines, etc.)
# set a custom ip for the client
JSON_REQUEST_BODY='{
"ipv4": "115.16.0.99"
}'
http put $API_SERVER/client $API_KEY <<< $JSON_REQUEST_BODY
```
Reading a write client's `ipv4` with a read client:
```bash
# using httpie
API_SERVER=http://localhost:3000/rynDNS
API_KEY=X-API-Key:zW3If4s5.28aef5cb.d502cb94ba0802c6363f95ecb3a70de7e2e4b889779e435b7c033f2c72ed4f20
CLIENT_NAME=write_client
* Deployment instructions
http get $API_SERVER/clients/$CLIENT_NAME $ API_KEY
* ...
# returns clients name and ipv4 as json
#{
# "name": "write_client",
# "ipv4": "115.16.0.99"
#}
```
## REST API
A detailed and interactive specification can be found in the [demo](https://demo.api.pdev.dev) which is a render of the OpenAPI specification [api.yml](api.yml) with `swager-ui`.
All requests except for `/public/*` require a valid `X-API-Key` header with appropriate permission.
The following is a quick overview of the available commands.
### Admin
Permission `x`
* [`POST /admin/client`](https://demo.api.pdev.dev/#/admin/create_client) - Create or update a client and retrieve a new API key
* [`PUT /admin/client`](https://demo.api.pdev.dev/#/admin/update_client) - Update an existing client
* [`GET /admin/clients`](https://demo.api.pdev.dev/#/admin/get_all_client) - Retrieve all clients information
* [`GET /admin/clients/{client_name}`](https://demo.api.pdev.dev/#/admin/get_client) - Retrieve client information
* [`DELETE /admin/clients/{client_name}`](https://demo.api.pdev.dev/#/admin/delete_client) - Delete an existing client
### Client (write)
Permission `w`
* [`PUT /client`](https://demo.api.pdev.dev/#/client%20(write)/update_client_ip) - Update ipv4 client information based on request IP or body if present
* [`DELETE /client`](https://demo.api.pdev.dev/#/client%20(write)/delete_client_ip) - Delete the requesting client's ipv4 information
### Client (read)
Permission `r`
* [`GET /clients/{client_name}`](https://demo.api.pdev.dev/#/client%20(read)/get_client_ip) - Get ipv4 client information
### Public
Client attribute `public_ip: true`
* [`GET /public/{client_name}`](https://demo.api.pdev.dev/#/public/get_public_client_ip) - Get ipv4 client information
## Configuration
The `rynDNS` server can be configured with environment variables, these can also be set in the docker environment:
```bash
# set to run app in subdirectory [default: /]
RAILS_RELATIVE_URL_ROOT: /rynDNS
# set maximum number of clients in db [default: 250]
RAILS_MAX_CLIENTS: 250
# set custom api key prefix [default: randomly generated (saved and restored if using docker)]
API_KEY_PREFIX: zW3If4s5
# set custom header name for api key [default: X-API-Key]
API_KEY_HEADER: X-API-Key
# set to reset the admin account, this will output a new api key on the console when starting the server [default: 0]
RAILS_RESET_ADMIN: 1
# set app to run as demo [default: 0]
RAILS_API_DEMO: 1
# [DOCKER only] set cycle to reset demo data [default: 60m]
RAILS_DEMO_RESET: 60m
```
## Roadmap
* `Public Mode` - to allow for quick deployment without having to create clients/api-keys in a trusted environment (see #1)
* Support Query Strings - as alternative to api key in header and json body
* DNS Server in Docker container - resolve `client_name`s via DNS server

View File

@@ -382,4 +382,4 @@ components:
pattern: "^(((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(.(?!$)|$)){4})?$"
externalDocs:
description: "<rynDNS source code>"
url: "https://git.pdev.dev/pdev/ryndns"
url: "https://git.pdev.dev/pascal/ryndns"

View File

@@ -178,10 +178,12 @@ class ClientsController < ApplicationController
# 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: <prefix>.<name_id>.<api_key>
# check if api key is present in header or param and can be split into 3 parts: <prefix>.<name_id>.<api_key>
# 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?
api_key_header ||= params[RynDNS::Application::API_KEY_HEADER].split('.').compact if
params.has_key?(RynDNS::Application::API_KEY_HEADER)
return head(401) if api_key_header.nil? || api_key_header.length < 3
prefix, @name_id, @api_key = api_key_header

0
data/.keep Normal file
View File

View File

@@ -5,8 +5,8 @@ services:
build:
context: .
args:
USER_UID: ${UID_PROXY:-12001}
USER_GID: ${UID_PROXY:-12001}
USER_UID: ${UID_PROXY:-$EUID}
USER_GID: ${UID_PROXY:-$EUID}
environment:
# set to run app in subdirectory
RAILS_RELATIVE_URL_ROOT: /rynDNS

View File

@@ -6,6 +6,7 @@
prefix_file="${API_PREFIX_FILE:-/app/data/api_prefix}"
db_file="${RAILS_DB_PATH:-/app/data/rynDNS.sqlite3}"
default_admin_file="${API_DEFAULT_KEY_FILE:-/app/data/api_default_admin}"
server_pid_file="${RAILS_PID_FILE:-/app/tmp/pids/server.pid}"
rails_bin="${RAILS_BINARY:-/app/bin/rails}"
demo_cycle="${RAILS_DEMO_RESET:-60m}"
demo_prefix="zW3If4s5"
@@ -50,6 +51,15 @@ function random_sting()
echo -n "$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w "${1:-32}" | head -n 1)"
}
function cleanup()
{
if [ -f $server_pid_file ]; then
log WAR cleanup last server shutdown may have not been graceful
log cleanup deleting old server pid file
rm $server_pid_file
fi
}
function get_prefix_file()
{
if [ -f "$prefix_file" ]; then
@@ -113,6 +123,7 @@ function db_setup()
function main()
{
cleanup
set_api_prefix
log main prefix: $RAILS_API_KEY_PREFIX
db_setup

View File

@@ -12,7 +12,7 @@ RSpec.describe 'Clients', type: :request do
let(:valid_client) do
{
name: 'clientA',
description: 'Client across the river',
description: 'Client&across the=river', # added &= for query string test
permission: 'rw',
public_ip: false
}
@@ -78,31 +78,18 @@ RSpec.describe 'Clients', type: :request do
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
it_behaves_like 'POST /admin/client 201'
end
# TODO: add query string tests for all requests and use shared examples
context 'when sending a valid request as query string' do
before do
api_key = "#{RynDNS::Application::API_KEY_HEADER}=#{api_key_header(admin_client)[RynDNS::Application::API_KEY_HEADER]}"
body = hash_to_query_string(valid_client)
post "/admin/client?#{api_key}&#{body}"
end
it_behaves_like 'POST /admin/client 201'
end
context 'when sending a valid request without api_key' do

View File

@@ -15,6 +15,15 @@ module RequestSpecHelper
"#{'r' if perm_r}#{'w' if perm_w}#{'x' if perm_x}"
end
def hash_to_query_string(hash)
result = ''
hash.each do |k, v|
# escape value to be uri save
result += "#{k}=#{CGI.escape(v.to_s)}&"
end
result.delete_suffix('&')
end
def list_equals_db?(client_list)
return false unless Client.count == client_list.count

View File

@@ -0,0 +1,29 @@
# frozen_string_literal: true
RSpec.shared_examples 'POST /admin/client 201' do
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