1659210420
Ruby gem for building and consuming JSON API documents.
jsonapi-rb is simply a bundle of:
For framework integrations, see:
# In Gemfile
gem 'jsonapi-rb'
then
$ bundle
or manually via
$ gem install jsonapi-rb
jsonapi-rb is released under the MIT License.
Author: jsonapi-rb
Source code: https://github.com/jsonapi-rb/jsonapi-rb
License: MIT license
1602851580
Recently, I worked with my team at Postman to field the 2020 State of the API survey and report. We’re insanely grateful to the folks who participated—more than 13,500 developers and other professionals took the survey, helping make this the largest and most comprehensive survey in the industry. (Seriously folks, thank you!) Curious what we learned? Here are a few insights in areas that you might find interesting:
Whether internal, external, or partner, APIs are perceived as reliable—more than half of respondents stated that APIs do not break, stop working, or materially change specification often enough to matter. Respondents choosing the “not often enough to matter” option here came in at 55.8% for internal APIs, 60.4% for external APIs, and 61.2% for partner APIs.
When asked about the biggest obstacles to producing APIs, lack of time is by far the leading obstacle, with 52.3% of respondents listing it. Lack of knowledge (36.4%) and people (35.1%) were the next highest.
#api #rest-api #apis #api-first-development #api-report #api-documentation #api-reliability #hackernoon-top-story
1659707040
Simplifying Kafka for Ruby apps!
Phobos is a micro framework and library for applications dealing with Apache Kafka.
Why Phobos? Why not ruby-kafka
directly? Well, ruby-kafka
is just a client. You still need to write a lot of code to manage proper consuming and producing of messages. You need to do proper message routing, error handling, retrying, backing off and maybe logging/instrumenting the message management process. You also need to worry about setting up a platform independent test environment that works on CI as well as any local machine, and even on your deployment pipeline. Finally, you also need to consider how to deploy your app and how to start it.
With Phobos by your side, all this becomes smooth sailing.
Add this line to your application's Gemfile:
gem 'phobos'
And then execute:
$ bundle
Or install it yourself as:
$ gem install phobos
Phobos can be used in two ways: as a standalone application or to support Kafka features in your existing project - including Rails apps. It provides a CLI tool to run it.
Standalone apps have benefits such as individual deploys and smaller code bases. If consuming from Kafka is your version of microservices, Phobos can be of great help.
To create an application with Phobos you need two things:
phobos_boot.rb
(or the name of your choice) to properly load your code into Phobos executorUse the Phobos CLI command init to bootstrap your application. Example:
# call this command inside your app folder
$ phobos init
create config/phobos.yml
create phobos_boot.rb
phobos.yml
is the configuration file and phobos_boot.rb
is the place to load your code.
In Phobos apps listeners are configured against Kafka - they are our consumers. A listener requires a handler (a ruby class where you should process incoming messages), a Kafka topic, and a Kafka group_id. Consumer groups are used to coordinate the listeners across machines. We write the handlers and Phobos makes sure to run them for us. An example of a handler is:
class MyHandler
include Phobos::Handler
def consume(payload, metadata)
# payload - This is the content of your Kafka message, Phobos does not attempt to
# parse this content, it is delivered raw to you
# metadata - A hash with useful information about this event, it contains: The event key,
# partition number, offset, retry_count, topic, group_id, and listener_id
end
end
Writing a handler is all you need to allow Phobos to work - it will take care of execution, retries and concurrency.
To start Phobos the start command is used, example:
$ phobos start
[2016-08-13T17:29:59:218+0200Z] INFO -- Phobos : <Hash> {:message=>"Phobos configured", :env=>"development"}
______ _ _
| ___ \ | | |
| |_/ / |__ ___ | |__ ___ ___
| __/| '_ \ / _ \| '_ \ / _ \/ __|
| | | | | | (_) | |_) | (_) \__ \
\_| |_| |_|\___/|_.__/ \___/|___/
phobos_boot.rb - find this file at ~/Projects/example/phobos_boot.rb
[2016-08-13T17:29:59:272+0200Z] INFO -- Phobos : <Hash> {:message=>"Listener started", :listener_id=>"6d5d2c", :group_id=>"test-1", :topic=>"test"}
By default, the start command will look for the configuration file at config/phobos.yml
and it will load the file phobos_boot.rb
if it exists. In the example above all example files generated by the init command are used as is. It is possible to change both files, use -c
for the configuration file and -b
for the boot file. Example:
$ phobos start -c /var/configs/my.yml -b /opt/apps/boot.rb
You may also choose to configure phobos with a hash from within your boot file. In this case, disable loading the config file with the --skip-config
option:
$ phobos start -b /opt/apps/boot.rb --skip-config
Messages from Kafka are consumed using handlers. You can use Phobos executors or include it in your own project as a library, but handlers will always be used. To create a handler class, simply include the module Phobos::Handler
. This module allows Phobos to manage the life cycle of your handler.
A handler is required to implement the method #consume(payload, metadata)
.
Instances of your handler will be created for every message, so keep a constructor without arguments. If consume
raises an exception, Phobos will retry the message indefinitely, applying the back off configuration presented in the configuration file. The metadata
hash will contain a key called retry_count
with the current number of retries for this message. To skip a message, simply return from #consume
.
The metadata
hash will also contain a key called headers
with the headers of the consumed message.
When the listener starts, the class method .start
will be called with the kafka_client
used by the listener. Use this hook as a chance to setup necessary code for your handler. The class method .stop
will be called during listener shutdown.
class MyHandler
include Phobos::Handler
def self.start(kafka_client)
# setup handler
end
def self.stop
# teardown
end
def consume(payload, metadata)
# consume or skip message
end
end
It is also possible to control the execution of #consume
with the method #around_consume(payload, metadata)
. This method receives the payload and metadata, and then invokes #consume
method by means of a block; example:
class MyHandler
include Phobos::Handler
def around_consume(payload, metadata)
Phobos.logger.info "consuming..."
output = yield payload, metadata
Phobos.logger.info "done, output: #{output}"
end
def consume(payload, metadata)
# consume or skip message
end
end
Note: around_consume
was previously defined as a class method. The current code supports both implementations, giving precendence to the class method, but future versions will no longer support .around_consume
.
class MyHandler
include Phobos::Handler
def self.around_consume(payload, metadata)
Phobos.logger.info "consuming..."
output = yield payload, metadata
Phobos.logger.info "done, output: #{output}"
end
def consume(payload, metadata)
# consume or skip message
end
end
Take a look at the examples folder for some ideas.
The hander life cycle can be illustrated as:
.start
-> #consume
-> .stop
or optionally,
.start
-> #around_consume
[ #consume
] -> .stop
In addition to the regular handler, Phobos provides a BatchHandler
. The basic ideas are identical, except that instead of being passed a single message at a time, the BatchHandler
is passed a batch of messages. All methods follow the same pattern as the regular handler except that they each end in _batch
and are passed an array of Phobos::BatchMessage
s instead of a single payload.
To enable handling of batches on the consumer side, you must specify a delivery method of inline_batch
in phobos.yml, and your handler must include BatchHandler
. Using a delivery method of batch
assumes that you are still processing the messages one at a time and should use Handler
.
When using inline_batch
, each instance of Phobos::BatchMessage
will contain an instance method headers
with the headers for that message.
class MyBatchHandler
include Phobos::BatchHandler
def around_consume_batch(payloads, metadata)
payloads.each do |p|
p.payload[:timestamp] = Time.zone.now
end
yield payloads, metadata
end
def consume_batch(payloads, metadata)
payloads.each do |p|
logger.info("Got payload #{p.payload}, #{p.partition}, #{p.offset}, #{p.key}, #{p.payload[:timestamp]}")
end
end
end
Note that retry logic will happen on the batch level in this case. If you are processing messages individually and an error happens in the middle, Phobos's retry logic will retry the entire batch. If this is not the behavior you want, consider using batch
instead of inline_batch
.
ruby-kafka
provides several options for publishing messages, Phobos offers them through the module Phobos::Producer
. It is possible to turn any ruby class into a producer (including your handlers), just include the producer module, example:
class MyProducer
include Phobos::Producer
end
Phobos is designed for multi threading, thus the producer is always bound to the current thread. It is possible to publish messages from objects and classes, pick the option that suits your code better. The producer module doesn't pollute your classes with a thousand methods, it includes a single method the class and in the instance level: producer
.
my = MyProducer.new
my.producer.publish(topic: 'topic', payload: 'message-payload', key: 'partition and message key')
# The code above has the same effect of this code:
MyProducer.producer.publish(topic: 'topic', payload: 'message-payload', key: 'partition and message key')
The signature for the publish
method is as follows:
def publish(topic: topic, payload: payload, key: nil, partition_key: nil, headers: nil)
When publishing a message with headers, the headers
argument must be a hash:
my = MyProducer.new
my.producer.publish(topic: 'topic', payload: 'message-payload', key: 'partition and message key', headers: { header_1: 'value 1' })
It is also possible to publish several messages at once:
MyProducer
.producer
.publish_list([
{ topic: 'A', payload: 'message-1', key: '1' },
{ topic: 'B', payload: 'message-2', key: '2' },
{ topic: 'B', payload: 'message-3', key: '3', headers: { header_1: 'value 1', header_2: 'value 2' } }
])
There are two flavors of producers: regular producers and async producers.
Regular producers will deliver the messages synchronously and disconnect, it doesn't matter if you use publish
or publish_list
; by default, after the messages get delivered the producer will disconnect.
Async producers will accept your messages without blocking, use the methods async_publish
and async_publish_list
to use async producers.
An example of using handlers to publish messages:
class MyHandler
include Phobos::Handler
include Phobos::Producer
PUBLISH_TO = 'topic2'
def consume(payload, metadata)
producer.async_publish(topic: PUBLISH_TO, payload: {key: 'value'}.to_json)
end
end
Since the handler life cycle is managed by the Listener, it will make sure the producer is properly closed before it stops. When calling the producer outside a handler remember, you need to shutdown them manually before you close the application. Use the class method async_producer_shutdown
to safely shutdown the producer.
Without configuring the Kafka client, the producers will create a new one when needed (once per thread). To disconnect from kafka call kafka_client.close
.
# This method will block until everything is safely closed
MyProducer
.producer
.async_producer_shutdown
MyProducer
.producer
.kafka_client
.close
By default, regular producers will automatically disconnect after every publish
call. You can change this behavior (which reduces connection overhead, TLS etc - which increases speed significantly) by setting the persistent_connections
config in phobos.yml
. When set, regular producers behave identically to async producers and will also need to be shutdown manually using the sync_producer_shutdown
method.
Since regular producers with persistent connections have open connections, you need to manually disconnect from Kafka when ending your producers' life cycle:
MyProducer
.producer
.sync_producer_shutdown
When running as a standalone service, Phobos sets up a Listener
and Executor
for you. When you use Phobos as a library in your own project, you need to set these components up yourself.
First, call the method configure
with the path of your configuration file or with configuration settings hash.
Phobos.configure('config/phobos.yml')
or
Phobos.configure(kafka: { client_id: 'phobos' }, logger: { file: 'log/phobos.log' })
Listener connects to Kafka and acts as your consumer. To create a listener you need a handler class, a topic, and a group id.
listener = Phobos::Listener.new(
handler: Phobos::EchoHandler,
group_id: 'group1',
topic: 'test'
)
# start method blocks
Thread.new { listener.start }
listener.id # 6d5d2c (all listeners have an id)
listener.stop # stop doesn't block
This is all you need to consume from Kafka with back off retries.
An executor is the supervisor of all listeners. It loads all listeners configured in phobos.yml
. The executor keeps the listeners running and restarts them when needed.
executor = Phobos::Executor.new
# start doesn't block
executor.start
# stop will block until all listers are properly stopped
executor.stop
When using Phobos executors you don't care about how listeners are created, just provide the configuration under the listeners
section in the configuration file and you are good to go.
The configuration file is organized in 6 sections. Take a look at the example file, config/phobos.yml.example.
The file will be parsed through ERB so ERB syntax/file extension is supported beside the YML format.
logger configures the logger for all Phobos components. It automatically outputs to STDOUT
and it saves the log in the configured file.
kafka provides configurations for every Kafka::Client
created over the application. All options supported by ruby-kafka
can be provided.
producer provides configurations for all producers created over the application, the options are the same for regular and async producers. All options supported by ruby-kafka
can be provided. If the kafka key is present under producer, it is merged into the top-level kafka, allowing different connection configuration for producers.
consumer provides configurations for all consumer groups created over the application. All options supported by ruby-kafka
can be provided. If the kafka key is present under consumer, it is merged into the top-level kafka, allowing different connection configuration for consumers.
backoff Phobos provides automatic retries for your handlers. If an exception is raised, the listener will retry following the back off configured here. Backoff can also be configured per listener.
listeners is the list of listeners configured. Each listener represents a consumer group.
In some cases it's useful to share most of the configuration between multiple phobos processes, but have each process run different listeners. In that case, a separate yaml file can be created and loaded with the -l
flag. Example:
$ phobos start -c /var/configs/my.yml -l /var/configs/additional_listeners.yml
Note that the config file must still specify a listeners section, though it can be empty.
Phobos can be configured using a hash rather than the config file directly. This can be useful if you want to do some pre-processing before sending the file to Phobos. One particularly useful aspect is the ability to provide Phobos with a custom logger, e.g. by reusing the Rails logger:
Phobos.configure(
custom_logger: Rails.logger,
custom_kafka_logger: Rails.logger
)
If these keys are given, they will override the logger
keys in the Phobos config file.
Some operations are instrumented using Active Support Notifications.
In order to receive notifications you can use the module Phobos::Instrumentation
, example:
Phobos::Instrumentation.subscribe('listener.start') do |event|
puts(event.payload)
end
Phobos::Instrumentation
is a convenience module around ActiveSupport::Notifications
, feel free to use it or not. All Phobos events are in the phobos
namespace. Phobos::Instrumentation
will always look at phobos.
events.
executor.retry_listener_error
is sent when the listener crashes and the executor wait for a restart. It includes the following payload:executor.stop
is sent when executor stopslistener.start_handler
is sent when invoking handler.start(kafka_client)
. It includes the following payload:listener.start
is sent when listener starts. It includes the following payload:listener.process_batch
is sent after process a batch. It includes the following payload:listener.process_message
is sent after processing a message. It includes the following payload:listener.process_batch_inline
is sent after processing a batch with batch_inline
mode. It includes the following payload:listener.retry_handler_error
is sent after waiting for handler#consume
retry. It includes the following payload:listener.retry_handler_error_batch
is sent after waiting for handler#consume_batch
retry. It includes the following payload:listener.retry_aborted
is sent after waiting for a retry but the listener was stopped before the retry happened. It includes the following payload:listener.stopping
is sent when the listener receives signal to stop.listener.stop_handler
is sent after stopping the handler.listener.stop
is send after stopping the listener.List of gems that enhance Phobos:
Phobos DB Checkpoint is drop in replacement to Phobos::Handler, extending it with the following features:
Phobos Checkpoint UI gives your Phobos DB Checkpoint powered app a web gui with the features below. Maintaining a Kafka consumer app has never been smoother:
Phobos Prometheus adds prometheus metrics to your phobos consumer.
/metrics
endpoit to scrape dataAfter checking out the repo:
docker
is installed and running (for windows and mac this also includes docker-compose
).docker-compose
is installed and running.bin/setup
to install dependenciesdocker-compose up -d --force-recreate kafka zookeeper
to start the required kafka containerssleep 30
docker-compose run --rm test
X examples, 0 failures
You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and tags, and push the .gem
file to rubygems.org.
Phobos exports a spec helper that can help you test your consumer. The Phobos lifecycle will conveniently be activated for you with minimal setup required.
process_message(handler:, payload:, metadata: {}, encoding: nil)
- Invokes your handler with payload and metadata, using a dummy listener (encoding and metadata are optional).### spec_helper.rb
require 'phobos/test/helper'
RSpec.configure do |config|
config.include Phobos::Test::Helper
config.before(:each) do
Phobos.configure(path_to_my_config_file)
end
end
### Spec file
describe MyConsumer do
let(:payload) { 'foo' }
let(:metadata) { Hash(foo: 'bar') }
it 'consumes my message' do
expect_any_instance_of(described_class).to receive(:around_consume).with(payload, metadata).once.and_call_original
expect_any_instance_of(described_class).to receive(:consume).with(payload, metadata).once.and_call_original
process_message(handler: described_class, payload: payload, metadata: metadata)
end
end
Version 2.0 removes deprecated ways of defining producers and consumers:
before_consume
method has been removed. You can have this behavior in the first part of an around_consume
method.around_consume
is now only available as an instance method, and it must yield the values to pass to the consume
method.publish
and async_publish
now only accept keyword arguments, not positional arguments.Example pre-2.0:
class MyHandler
include Phobos::Handler
def before_consume(payload, metadata)
payload[:id] = 1
end
def self.around_consume(payload, metadata)
metadata[:key] = 5
yield
end
end
In 2.0:
class MyHandler
include Phobos::Handler
def around_consume(payload, metadata)
new_payload = payload.dup
new_metadata = metadata.dup
new_payload[:id] = 1
new_metadata[:key] = 5
yield new_payload, new_metadata
end
end
Producer, 1.9:
producer.publish('my-topic', { payload_value: 1}, 5, 3, {header_val: 5})
Producer 2.0:
producer.publish(topic: 'my-topic', payload: { payload_value: 1}, key: 5,
partition_key: 3, headers: { header_val: 5})
Version 1.8.2 introduced a new persistent_connections
setting for regular producers. This reduces the number of connections used to produce messages and you should consider setting it to true. This does require a manual shutdown call - please see Producers with persistent connections.
Bug reports and pull requests are welcome on GitHub at https://github.com/klarna/phobos.
Phobos projects Rubocop to lint the code, and in addition all projects use Rubocop Rules to maintain a shared rubocop configuration. Updates to the shared configurations are done in phobos/shared repo, where you can also find instructions on how to apply the new settings to the Phobos projects.
Thanks to Sebastian Norde for the awesome logo!
Author: Phobos
Source Code: https://github.com/phobos/phobos
License: Apache-2.0 license
1595396220
As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.
Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.
Most APIs provide access to resources that are lists of entities such as /users
or /widgets
. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:
First Call: GET /items?skip=0&take=10
Second Call: GET /items?skip=10&take=10
However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped
A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:
skip = 0
while True: response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip), headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]}) print("Fetched 10 items") sleep(randint(100,1000)) skip += 10
To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.
Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.
The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.
APIs are used in a way that increases the probability credentials are leaked:
If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.
The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.
The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)
APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.
The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response.
There are a variety of algorithms to do this such as leaky bucket and fixed window counters.
APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.
Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs
APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.
#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys
1601381326
We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.
The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:
With regards to how the APIs are shared:
#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway
1592906522
#api #rest api #asp.net api #restful api #api tutorial #consume api