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
2 changes: 2 additions & 0 deletions .fernignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ WASM_VERSION
conformance/
custom.gemspec.rb
lib/schematic/cache.rb
lib/schematic/context_signature.rb
lib/schematic/credits/leases/
lib/schematic/datastream/
lib/schematic/event_buffer.rb
Expand All @@ -20,6 +21,7 @@ lib/schematic/wasm/
lib/schematic/webhook_verification.rb
lib/schematichq.rb
scripts/
test/context_signature_test.rb
test/conformance_test.rb
test/credits_test.rb
test/custom.test.rb
Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,31 @@ SCHEMATIC_WEBHOOK_SECRET=your-secret ruby scripts/webhook_test_server.rb

This starts a WEBrick server on port 8080 (configurable via `PORT` env var) that listens for POST requests at `/webhook`, verifies signatures, and prints the payload.

## Context Signatures

A browser SDK uses a publishable key, which anyone can read from your page, so on its own it can't prove which company or user it's acting for. When an environment requires context signatures, the API only accepts a publishable-key request whose company and user your backend has signed with the environment's secret API key. The browser SDK asks your backend for the signature through its `getContextSignature` option and sends it in the `X-Schematic-Context-Sig` header.

### Signing a context

Sign the logged-in user's own company and user, read from your session. Don't sign whatever company or user the browser asks for, or anyone could get a signature for another company.

```ruby
require "schematichq"

# In a Rails controller
def schematic_signature
signature = Schematic::ContextSignature.sign(
ENV.fetch("SCHEMATIC_SECRET_KEY"),
company: { "id" => current_user.company_id },
user: { "id" => current_user.id.to_s }
)

render json: { signature: signature }
end
```

The company and user keys must match the context you give the browser SDK exactly, or the API rejects the signature. Values must be strings. A signature is valid for 10 minutes by default; set a different lifetime, up to an hour, with `lifetime_seconds:`, and the start time with `issued_at:`. The browser SDK reuses a signature until shortly before it expires, then asks for a new one. `sign` raises `Schematic::ContextSignature::ContextSignatureError` when the secret is missing, the lifetime is out of range, or a key's value isn't a string.

## DataStream

DataStream enables local flag evaluation by maintaining a WebSocket connection to Schematic and caching flag rules, company, and user data locally. Flag checks are evaluated using a local WASM rules engine, significantly reducing latency and network calls.
Expand Down
113 changes: 113 additions & 0 deletions lib/schematic/context_signature.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# frozen_string_literal: true

require "json"
require "openssl"

module Schematic
# Signs the context a browser SDK sends with a publishable key, for
# environments that require context signatures.
#
# A publishable key is public, so the API can't trust the company and user a
# browser names with it. When the environment requires signatures, your
# backend, which holds the secret API key, signs the logged-in user's own
# company and user, and the browser SDK sends that signature in the
# X-Schematic-Context-Sig header. Sign the context from your own
# authenticated session, never from what the browser asks for.
#
# The signature is `iat.exp.sig`, where `sig` is the unpadded base64url
# HMAC-SHA256 of `canonical(context).iat.exp` keyed with the secret API key,
# and `canonical` is the context's JSON with keys sorted by code point and no
# whitespace.
module ContextSignature
# Request header the browser SDK sends the signature in.
HEADER = "X-Schematic-Context-Sig"

# How long a signature is valid for unless lifetime_seconds says
# otherwise. It matches how long the browser SDK reuses one.
DEFAULT_LIFETIME_SECONDS = 600

# The longest the API accepts a signature as valid for.
MAX_LIFETIME_SECONDS = 3600

# Raised when a context can't be signed.
class ContextSignatureError < StandardError; end

module_function

# Returns the X-Schematic-Context-Sig value for the company and user.
#
# secret is the secret API key for the environment the browser SDK's
# publishable key belongs to. company and user are the logged-in user's
# keys, as given to the browser SDK; leave one out when it's absent. Keys
# may be strings or symbols; values must be strings. issued_at is when the
# signature is valid from, now by default, and lifetime_seconds how long
# for, from 1 up to MAX_LIFETIME_SECONDS.
def sign(secret, company: nil, user: nil, lifetime_seconds: DEFAULT_LIFETIME_SECONDS, issued_at: nil)
raise ContextSignatureError, "lifetime_seconds must be a whole number from 1 to #{MAX_LIFETIME_SECONDS}" unless lifetime_seconds.is_a?(Integer) && lifetime_seconds.between?(1, MAX_LIFETIME_SECONDS)

iat = (issued_at || Time.now).to_i
sign_at(secret, iat, iat + lifetime_seconds, company: company, user: user)
end

# Signs for an explicit iat and exp, in unix seconds. For tests; use sign.
# @api private
def sign_at(secret, iat, exp, company: nil, user: nil)
raise ContextSignatureError, "a secret API key is required to sign a context" if secret.nil? || secret.empty?

payload = "#{canonicalize(company: company, user: user)}.#{iat}.#{exp}"
# Unpadded base64url, without the base64 gem, which Ruby 3.4 stopped
# bundling by default.
sig = [OpenSSL::HMAC.digest("SHA256", secret, payload)].pack("m0").tr("+/", "-_").delete("=")
"#{iat}.#{exp}.#{sig}"
end

# Encodes a context the way the API does before verifying it: keys sorted
# by code point, no whitespace, "<", ">", "&" and "/" left literal, and
# U+2028 and U+2029 escaped.
# @api private
def canonicalize(company: nil, user: nil)
parts = []
# "company" sorts before "user".
parts << "\"company\":#{canonicalize_keys(company)}" unless company.nil?
parts << "\"user\":#{canonicalize_keys(user)}" unless user.nil?
"{#{parts.join(",")}}"
end

def canonicalize_keys(keys)
raise ContextSignatureError, "company and user keys must be a hash" unless keys.is_a?(Hash)

entries = {}
keys.each do |name, value|
raise ContextSignatureError, "context key names must be strings or symbols" unless name.is_a?(String) || name.is_a?(Symbol)
raise ContextSignatureError, "the value of context key #{name.inspect} must be a string" unless value.is_a?(String)

name = utf8(name.to_s)
raise ContextSignatureError, "context key #{name.inspect} is given twice" if entries.key?(name)

entries[name] = utf8(value)
end

# String#<=> compares bytes, which for UTF-8 is code point order, the
# order the API sorts keys in.
body = entries.keys.sort.map { |name| "#{encode_string(name)}:#{encode_string(entries[name])}" }
"{#{body.join(",")}}"
end

# The API reads each byte of invalid UTF-8 as U+FFFD.
def utf8(value)
value = value.dup.force_encoding(Encoding::UTF_8) if value.encoding == Encoding::BINARY
value = value.encode(Encoding::UTF_8) unless value.encoding == Encoding::UTF_8
value.scrub("\uFFFD")
end

# The stdlib generator escapes quotes, backslashes and control characters
# the way the API does, and leaves "<", ">", "&" and "/" alone, unlike
# ActiveSupport's encoder. It leaves U+2028 and U+2029 raw, which the API
# escapes.
def encode_string(value)
JSON.generate(value).gsub("\u2028", "\\u2028").gsub("\u2029", "\\u2029")
end

private_class_method :canonicalize_keys, :utf8, :encode_string
end
end
1 change: 1 addition & 0 deletions lib/schematichq.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
require_relative "schematic/cache"
require_relative "schematic/redis_cache"
require_relative "schematic/event_buffer"
require_relative "schematic/context_signature"
require_relative "schematic/webhook_verification"
require_relative "schematic/rules_engine"
require_relative "schematic/datastream/merge"
Expand Down
101 changes: 101 additions & 0 deletions test/context_signature_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# frozen_string_literal: true

require "json"
require "minitest/autorun"
require_relative "../lib/schematic/context_signature"

# testdata/context-signing.json is copied verbatim from
# api/lib/contextsig/testdata in the Schematic API, which generates it from the
# verifier and checks it in its own tests. Don't edit it here.
class ContextSignatureVectorsTest < Minitest::Test
VECTORS = JSON.parse(File.read(File.join(__dir__, "testdata", "context-signing.json")))

def test_caps_the_lifetime_where_the_api_does
assert_equal VECTORS["max_lifetime_seconds"], Schematic::ContextSignature::MAX_LIFETIME_SECONDS
end

VECTORS["vectors"].each do |v|
define_method("test_vector_#{v["name"]}") do
company = v["context"]["company"]
user = v["context"]["user"]

assert_equal v["canonical"], Schematic::ContextSignature.canonicalize(company: company, user: user)
assert_equal v["signature"],
Schematic::ContextSignature.sign_at(v["secret"], v["iat"], v["exp"], company: company, user: user)
end
end
end

class ContextSignatureSignTest < Minitest::Test
CS = Schematic::ContextSignature
COMPANY = { "id" => "comp_1" }.freeze

def window(signature)
signature.split(".").first(2).map { |part| Integer(part) }
end

def test_signs_for_the_default_lifetime_from_now
before = Time.now.to_i
iat, exp = window(CS.sign("secret", company: COMPANY))

assert_operator iat, :>=, before
assert_operator iat, :<=, Time.now.to_i
assert_equal CS::DEFAULT_LIFETIME_SECONDS, exp - iat
end

def test_signs_from_the_time_and_for_the_lifetime_given
signature = CS.sign("secret", company: COMPANY, issued_at: Time.at(1_700_000_000.5), lifetime_seconds: 300)

assert_equal CS.sign_at("secret", 1_700_000_000, 1_700_000_300, company: COMPANY), signature
end

def test_refuses_a_lifetime_the_api_would_reject
[0, -60, 1.5, CS::MAX_LIFETIME_SECONDS + 1, 86_400, "600"].each do |lifetime_seconds|
assert_raises(CS::ContextSignatureError, lifetime_seconds.inspect) do
CS.sign("secret", company: COMPANY, lifetime_seconds: lifetime_seconds)
end
end
end

def test_refuses_a_missing_secret
assert_raises(CS::ContextSignatureError) { CS.sign("", company: COMPANY) }
assert_raises(CS::ContextSignatureError) { CS.sign(nil, company: COMPANY) }
end

def test_refuses_a_value_that_isnt_a_string
assert_raises(CS::ContextSignatureError) { CS.sign("secret", company: { "id" => 123 }) }
assert_raises(CS::ContextSignatureError) { CS.sign("secret", company: { "id" => :comp_1 }) }
end

def test_refuses_keys_that_arent_a_hash
assert_raises(CS::ContextSignatureError) { CS.sign("secret", company: "comp_1") }
end

def test_refuses_a_key_given_twice
assert_raises(CS::ContextSignatureError) { CS.sign("secret", company: { "id" => "a", id: "b" }) }
end
end

class ContextSignatureCanonicalizeTest < Minitest::Test
CS = Schematic::ContextSignature

def test_leaves_out_a_company_or_user_that_is_nil
assert_equal "{}", CS.canonicalize(company: nil, user: nil)
end

def test_signs_symbol_key_names_as_strings
assert_equal CS.canonicalize(company: { "id" => "comp_1" }), CS.canonicalize(company: { id: "comp_1" })
end

def test_signs_invalid_utf8_as_u_fffd_per_byte_as_the_api_reads_it
assert_equal "{\"company\":{\"name\":\"a\uFFFDb\"}}",
CS.canonicalize(company: { "name" => "a\xFFb".b })
assert_equal "{\"company\":{\"name\":\"a\uFFFD\uFFFD\uFFFD\"}}",
CS.canonicalize(company: { "name" => "a\xED\xA0\x80".dup.force_encoding(Encoding::UTF_8) })
end

def test_converts_other_encodings_to_utf8
assert_equal "{\"company\":{\"name\":\"Caf\u00e9\"}}",
CS.canonicalize(company: { "name" => "Caf\u00e9".encode(Encoding::ISO_8859_1) })
end
end
Loading
Loading