Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,36 @@ In the end, the decision on whether or not to use the API client or
the JavaScript snippet should be based on what works best for you.
You'll be able to integrate **fully** with [Customer.io](https://customer.io) with either approach.

### Quick start

Create a client with your secret key (`sk_…`). It sends tracking calls to the Track API and transactional messages to the App API, and picks the US or EU region from the key.

```ruby
cio = Customerio::UnifiedClient.new(ENV["CIO_API_KEY"])

cio.identify(id: "user_123", email: "[email protected]")
cio.track("user_123", "order_completed")
cio.send_email(Customerio::SendEmailRequest.new(
to: "[email protected]",
identifiers: { id: "user_123" },
transactional_message_id: 5
))
```

A `pk_` or `sk_` key belongs to one region, so passing `Customerio::Regions::US` or `Customerio::Regions::EU` when it disagrees with the key raises `ArgumentError`. A custom `Customerio::Regions::Region` is used as given. Every URL (`track_url`, `api_url` and a custom region's) must start with `https://`. Legacy App API keys also work here for transactional calls; they default to `Customerio::Regions::US` unless you pass `region:`. Tracking calls on Pipelines workspaces need a source-bound `pk_` or `sk_` key.

`identify`, `track`, `track_anonymous`, `pageview`, the `send_*` methods and `trigger_broadcast` are on the client directly. The rest of the Track and App API are on `cio.track_client` and `cio.api_client`.

If the key can't do what you asked, the call raises `Customerio::KeyCapabilityError`. A public key (`pk_…`) raises it before any request when you send a transactional message or trigger a broadcast. A 401 or 403 from the server is re-raised as a `KeyCapabilityError` too, with the original error as `cause`.

```ruby
begin
cio.send_email(request)
rescue Customerio::KeyCapabilityError => e
puts e.capability, e.message # :transactional, "The server refused this request to send transactional messages ..."
end
```

### Setup

Create an instance of the client with your [Customer.io credentials](https://fly.customer.io/settings/api_credentials).
Expand Down
1 change: 1 addition & 0 deletions lib/customerio.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ module Customerio
require "customerio/requests/send_in_app_request"
require "customerio/requests/trigger_broadcast_request"
require "customerio/api"
require "customerio/unified_client"
end
3 changes: 2 additions & 1 deletion lib/customerio/base_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ def execute(method, path, body = nil, headers = {})
uri = URI.join(@base_uri, path)
request_headers = headers.dup

session = Net::HTTP.new(uri.host, uri.port)
# hostname drops the brackets around an IPv6 address, which host keeps.
session = Net::HTTP.new(uri.hostname, uri.port)
session.use_ssl = uri.scheme == "https"
session.open_timeout = @timeout
session.read_timeout = @timeout
Expand Down
213 changes: 213 additions & 0 deletions lib/customerio/unified_client.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
# frozen_string_literal: true

module Customerio
# Raised by UnifiedClient when its key can't do what a method asks.
#
# Raised before the request when the key's type rules it out (a public `pk_`
# key can't send transactional messages or trigger broadcasts). Otherwise
# the server's 401 or 403 is re-raised as this error, with the original
# InvalidResponse as `cause`.
class KeyCapabilityError < StandardError
# What the key can't do: :track, :transactional or :broadcast.
attr_reader :capability
# The HTTP status code as an Integer, when the server refused the key.
attr_reader :code

def initialize(capability, message, code = nil)
@capability = capability
@code = code

super(message)
end
end

# One client for tracking and transactional messages, authenticated with a
# single key sent as a Bearer token.
#
# Tracking methods go to the Track API; send methods go to the App API. For
# `pk_` / `sk_` keys the region comes from the key, and Regions::US or
# Regions::EU disagreeing with it raises ArgumentError; a custom Region is
# used as given. Legacy keys take any `region` and default to Regions::US.
#
# Every URL must be https, since the key is sent as a Bearer token.
#
# Other Track and App API methods are on #track_client and #api_client.
class UnifiedClient
# Keys in the shared format look like `{type}_{us|eu}_{random}_{checksum}`,
# where type is `pk` (public) or `sk` (secret). The server checks the
# checksum; the client only reads the prefix.
KEY_PREFIX = /\A(pk|sk)_(us|eu)_/

CAPABILITY_ACTIONS = {
track: "send tracking data",
transactional: "send transactional messages",
broadcast: "trigger broadcasts"
}.freeze

KEY_REGIONS = { "us" => Regions::US, "eu" => Regions::EU }.freeze
private_constant :KEY_REGIONS

attr_reader :track_client, :region

def initialize(api_key, options = {})
api_key = api_key.to_s.strip
raise ArgumentError, "api_key is required" if api_key.empty?

match = KEY_PREFIX.match(api_key)
@key_kind = match ? match[1].to_sym : :legacy
@region = resolve_region(match && match[2], options[:region])
check_urls(options)

@track_client = BearerTrackClient.new(api_key, track_options(options))
@api_client = APIClient.new(api_key, api_options(options))
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
end

# The App API client. Raises KeyCapabilityError for a public `pk_` key.
def api_client
refuse_public_key(:transactional)
@api_client
end

def identify(attributes)
guard(:track) { track_client.identify(attributes) }
end

def track(customer_id, event_name, attributes = {}, id: nil, timestamp: nil)
guard(:track) { track_client.track(customer_id, event_name, attributes, id: id, timestamp: timestamp) }
end

def track_anonymous(anonymous_id, event_name, attributes = {}, id: nil, timestamp: nil)
guard(:track) { track_client.track_anonymous(anonymous_id, event_name, attributes, id: id, timestamp: timestamp) }
end

def pageview(customer_id, page, attributes = {})
guard(:track) { track_client.pageview(customer_id, page, attributes) }
end

def send_email(req)
guard(:transactional) { api_client.send_email(req) }
end

def send_push(req)
guard(:transactional) { api_client.send_push(req) }
end

def send_sms(req)
guard(:transactional) { api_client.send_sms(req) }
end

def send_whatsapp(req)
guard(:transactional) { api_client.send_whatsapp(req) }
end

def send_inbox_message(req)
guard(:transactional) { api_client.send_inbox_message(req) }
end

def send_in_app(req)
guard(:transactional) { api_client.send_in_app(req) }
end

def trigger_broadcast(req)
guard(:broadcast) do
refuse_public_key(:broadcast)
@api_client.trigger_broadcast(req)
end
end

private

# A prefixed key belongs to one region, so the other built-in region would
# only get a redirect or a 401 from the server. A custom Region may be a
# proxy, so it's trusted.
def resolve_region(key_region, region)
return region || Regions::US if key_region.nil?
return KEY_REGIONS[key_region] if region.nil?

name = KEY_REGIONS.key(region)
if name && name != key_region
raise ArgumentError, "region #{name} does not match the #{key_region} region of this key"
end

region
end

# The key goes out as a Bearer token, so never send it over plain http.
def check_urls(options)
check_https("track_url", options[:track_url])
check_https("api_url", options[:api_url])
return unless @region.is_a?(Regions::Region)

check_https("region track_url", @region.track_url)
check_https("region api_url", @region.api_url)
end

def check_https(name, url)
return if url.nil? || url.to_s.empty?

uri = begin
URI.parse(url.to_s)
rescue URI::InvalidURIError
raise ArgumentError, "#{name} is not a valid URL: #{url}"
end
raise ArgumentError, "#{name} must start with https://" unless uri.scheme == "https"
raise ArgumentError, "#{name} is not a valid URL: #{url}" if uri.host.to_s.empty?
end

def refuse_public_key(capability)
return unless @key_kind == :pk

raise KeyCapabilityError.new(
capability,
"This key can't use the App API: public keys (pk_) are for tracking only. Use a secret key (sk_)."
)
end

def track_options(options)
options.except(:api_url).merge(region: @region, url: options[:track_url])
end

def api_options(options)
options.except(:track_url).merge(region: @region, url: options[:api_url])
end

# Turns a 401/403 into a KeyCapabilityError so a key mismatch is never a
# bare auth failure. The original error is kept as `cause`.
def guard(capability)
yield
rescue InvalidResponse => e
raise unless %w[401 403].include?(e.code.to_s)

reason = refusal_reason(e.message)
raise KeyCapabilityError.new(
capability,
"The server refused this request to #{CAPABILITY_ACTIONS[capability]} (#{e.code}): #{reason}. " \
"Check the key type, its IP restrictions and the workspace status.",
e.code.to_i
)
end

# The App API sends `{"errors":[{"detail":…}]}` and the Track API sends
# `{"meta":{"error":…}}`; anything else is shown as it came.
def refusal_reason(body)
parsed = JSON.parse(body.to_s)
return body unless parsed.is_a?(Hash)

reason = parsed.dig("errors", 0, "detail") || parsed.dig("meta", "error")
reason.is_a?(String) && !reason.empty? ? reason : body
Comment thread
sydneycollins-cio marked this conversation as resolved.
Resolved
rescue JSON::ParserError, TypeError
body
end

# Client only speaks Basic auth, so swap in a Bearer transport.
class BearerTrackClient < Client
def initialize(api_key, options)
super(nil, nil, options)

options = options.merge(url: options[:region].track_url) if options[:url].nil? || options[:url].empty?
@client = BaseClient.new({ app_key: api_key }, options)
end
end
private_constant :BearerTrackClient
end
end
11 changes: 11 additions & 0 deletions spec/base_client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ def api_client_request_headers
end
end

describe "with an IPv6 host" do
it "connects to the address without brackets" do
client = Customerio::BaseClient.new({ app_key: app_key }, { url: "https://[::1]:8443" })
stub = stub_request(:get, "https://[::1]:8443/some/path").to_return(status: 200, body: "")

expect(Net::HTTP).to receive(:new).with("::1", 8443).and_call_original
client.request(:get, '/some/path')
expect(stub).to have_been_requested
end
end

describe "GET requests" do
describe "with a site ID and API key" do
it "sends a GET request with basic auth" do
Expand Down
Loading