From 28a7854bbc0d0c2066eb2d50c59fde8834ee9931 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Wed, 4 Nov 2026 16:40:59 +0100 Subject: [PATCH 1/8] feat: add audience collection mode --- CHANGELOG.md | 7 + README.md | 50 ++++- lib/altertable/adapters.rb | 2 +- lib/altertable/client.rb | 48 ++++- rbi/altertable.rbi | 9 + sig/altertable.rbs | 2 +- sig/altertable/client.rbs | 7 +- spec/altertable/audience_transport_spec.rb | 72 ++++++++ spec/altertable/client_audience_spec.rb | 204 +++++++++++++++++++++ 9 files changed, 395 insertions(+), 6 deletions(-) create mode 100644 spec/altertable/audience_transport_spec.rb create mode 100644 spec/altertable/client_audience_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 83bf2a4..dd0c44e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [Unreleased] + +### Features + +* Add audience collection mode for scalar, hash, and batch tracking, with identity suppression, restricted wire fields, and built-in URL sanitization. Product mode remains the default. + + ## [1.3.0](https://github.com/altertable-ai/altertable-ruby/compare/altertable/v1.2.0...altertable/v1.3.0) (2026-09-04) diff --git a/README.md b/README.md index 3969de1..e9fc9d0 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,8 @@ Altertable.init('pk_live_abc123', environment: 'production', debug: true) Record an action performed by a user. -`Altertable.track(event, distinct_id, **options)` +`Altertable.track(event, distinct_id = nil, **options)` + `Altertable.track(event_payload, **options)` `Altertable.track(event_payloads, **options)` @@ -69,6 +70,50 @@ Altertable.track([ ]) ``` +### Audience Measurement + +Product analytics is the default. Select audience measurement when creating a client: + +```ruby +Altertable.init('pk_live_abc123', mode: :audience) +Altertable.track('Docs Opened', properties: { + '$url' => 'https://example.com/docs?campaign=launch', + '$referer' => 'https://search.example/results?q=docs', + section: 'installation' +}) +Altertable.track({ event: 'Install Copied', properties: { package: 'ruby' } }) +Altertable.track([{ event: 'Docs Opened' }, { event: 'Install Copied' }]) +``` + +Audience events send only `mode: "audience"`, `event`, `timestamp`, and `properties`. +No `distinct_id`, `anonymous_id`, `device_id`, `session_id`, or `environment` is sent, +even if supplied by the caller. The API key determines the audience environment. +`identify` and `alias` return `nil` without sending a request, including for hash +and batch inputs. Enable `debug: true` during development to warn about these calls. + +The SDK reduces `$url` to its HTTP(S) origin and path, reduces `$referer` to its +origin, and removes `$viewport`. Credentials, query strings, and fragments are +removed from these built-in URLs; invalid or unsupported URLs become `nil`. +Both symbol and string property keys are supported. Library/version and configured +release metadata are retained. Custom properties and URL paths can still contain +personal information: callers are responsible for choosing appropriate values. + +Mode is fixed for each `Altertable::Client`. Create a new client or call +`Altertable.init` again to change it. Per-event options cannot override mode. +Both `:product`/`:audience` and `"product"`/`"audience"` are accepted; other values +raise `Altertable::ConfigurationError` before replacing the global client. + +This server SDK sends requests immediately. It has no persistent identity, +sessions, disk queue, consent manager, automatic page capture, or event transforms. +Failed requests are not queued for replay across clients. Gate calls according to +your application's consent policy. All HTTP transports (`:faraday`, `:httpx`, and +`:net_http`) are supported; their existing timeout, proxy, and retry behavior applies. + +Audience visitor hashing on the backend uses the IP address and User-Agent of the +SDK's HTTP request, which describe your server rather than the end user's browser. +Server-side audience events therefore cannot reliably measure distinct end-user +visitors. This SDK does not forward end-user IP/User-Agent headers. + ### Identifying Users Link a user ID to their traits (like email or name). @@ -114,7 +159,8 @@ You can configure the client by passing options during initialization. | Option | Type | Default | Description | |---|---|---|---| -| `environment` | String | `"production"` | Environment name (e.g., `production`, `development`). | +| `mode` | Symbol, String | `:product` | Collection mode: `:product` or `:audience`. Fixed for the client lifetime. | +| `environment` | String | `"production"` | Product environment name (e.g., `production`, `development`). Omitted in audience mode; the API key selects its environment. | | `base_url` | String | `"https://api.altertable.ai"` | Base URL for API requests. | | `request_timeout` | Integer | `5` | Request timeout in seconds. | | `release` | String | `nil` | Application release version (e.g., commit hash). | diff --git a/lib/altertable/adapters.rb b/lib/altertable/adapters.rb index 4ea6fff..676e642 100644 --- a/lib/altertable/adapters.rb +++ b/lib/altertable/adapters.rb @@ -60,7 +60,7 @@ def initialize(base_url:, timeout:, headers: {}, proxy: nil) @client = client.with( timeout: { operation_timeout: @timeout }, headers: @headers, - base_url: @base_url + origin: @base_url ) end diff --git a/lib/altertable/client.rb b/lib/altertable/client.rb index 007e1a8..4fd86fe 100644 --- a/lib/altertable/client.rb +++ b/lib/altertable/client.rb @@ -2,6 +2,7 @@ require "json" require "time" +require "uri" require_relative "errors" require_relative "adapters" @@ -14,6 +15,12 @@ class Client def initialize(api_key, options = {}) raise ConfigurationError, "API Key is required" if api_key.nil? || api_key.empty? + @mode = case options.fetch(:mode, :product) + when :product, "product" then :product + when :audience, "audience" then :audience + else + raise ConfigurationError, 'Invalid tracking mode. Use "product" or "audience".' + end @api_key = api_key @base_url = options[:base_url] || DEFAULT_BASE_URL @environment = options[:environment] || DEFAULT_ENVIRONMENT @@ -44,6 +51,8 @@ def track(event, distinct_id = nil, **options) end def identify(user_id, **options) + return if reject_identity_call? + case user_id when Array payloads = map_batch(user_id, "identifies") { |item| identify_payload_from_item(merge_payload(item, options)) } @@ -56,6 +65,8 @@ def identify(user_id, **options) end def alias(distinct_id, new_user_id = nil, **options) + return if reject_identity_call? + case distinct_id when Array payloads = map_batch(distinct_id, "aliases") { |item| alias_payload_from_item(merge_payload(item, options)) } @@ -69,6 +80,13 @@ def alias(distinct_id, new_user_id = nil, **options) private + def reject_identity_call? + return false unless @mode == :audience + + warn "[Altertable] identify() and alias() calls are ignored in audience mode." if @debug + true + end + def select_adapter(name, options) case name when :faraday @@ -138,7 +156,7 @@ def track_payload_from_item(item) event = item_value(item, :event) distinct_id = item_value(item, :distinct_id) raise ArgumentError, "event is required" if blank?(event) - raise ArgumentError, "distinct_id is required" if blank?(distinct_id) + raise ArgumentError, "distinct_id is required" if @mode == :product && blank?(distinct_id) track_payload(event, distinct_id, item_options(item, :properties, :anonymous_id, :device_id, :timestamp)) end @@ -172,11 +190,39 @@ def track_payload(event, distinct_id, options) }.merge(properties) } payload[:properties]["$release"] = @release if @release + return audience_payload(payload) if @mode == :audience + payload[:anonymous_id] = options[:anonymous_id] if options.key?(:anonymous_id) payload[:device_id] = options[:device_id] if options.key?(:device_id) payload end + # Select wire fields explicitly so per-event options cannot override client policy. + def audience_payload(payload) + properties = payload[:properties].transform_keys(&:to_s) + properties["$url"] = sanitize_url(properties["$url"]) + properties["$referer"] = sanitize_url(properties["$referer"], origin_only: true) + properties.delete("$viewport") + { mode: "audience", event: payload[:event], timestamp: payload[:timestamp], properties: properties } + end + + def sanitize_url(value, origin_only: false) + return unless value.is_a?(String) + + url = URI.parse(value) + return unless url.is_a?(URI::HTTP) && url.host && !url.host.empty? + return unless url.port.between?(0, 65_535) + + origin = "#{url.scheme}://#{url.host.downcase}" + origin += ":#{url.port}" if url.port != url.default_port + return origin if origin_only + + path = url.path.empty? ? "/" : url.path + "#{origin}#{path}" + rescue URI::InvalidURIError + nil + end + def identify_payload(user_id, options) payload = { timestamp: options[:timestamp] || default_timestamp, diff --git a/rbi/altertable.rbi b/rbi/altertable.rbi index 88962c1..cabe0c7 100644 --- a/rbi/altertable.rbi +++ b/rbi/altertable.rbi @@ -48,6 +48,15 @@ module Altertable sig { params(name: T.nilable(Symbol), options: T::Hash[Symbol, T.untyped]).returns(T.untyped) } def select_adapter(name, options); end + sig { returns(T::Boolean) } + def reject_identity_call?; end + + sig { params(payload: T::Hash[Symbol, T.untyped]).returns(T::Hash[Symbol, T.untyped]) } + def audience_payload(payload); end + + sig { params(value: T.untyped, origin_only: T::Boolean).returns(T.nilable(String)) } + def sanitize_url(value, origin_only: false); end + sig { params(gem_name: String).returns(T::Boolean) } def try_require(gem_name); end diff --git a/sig/altertable.rbs b/sig/altertable.rbs index 821b70e..2e1888e 100644 --- a/sig/altertable.rbs +++ b/sig/altertable.rbs @@ -3,7 +3,7 @@ module Altertable def self.init: (String api_key, ?::Hash[Symbol, untyped] options) -> Client - def self.track: (String event, String distinct_id, **untyped options) -> untyped + def self.track: (String event, ?String? distinct_id, **untyped options) -> untyped | (::Hash[Symbol | String, untyped] event_payload, **untyped options) -> untyped | (::Array[::Hash[Symbol | String, untyped]] event_payloads, **untyped options) -> untyped diff --git a/sig/altertable/client.rbs b/sig/altertable/client.rbs index b511464..935bc41 100644 --- a/sig/altertable/client.rbs +++ b/sig/altertable/client.rbs @@ -1,5 +1,6 @@ module Altertable class Client + @mode: :product | :audience @api_key: String @base_url: String @environment: String @@ -15,7 +16,7 @@ module Altertable def initialize: (String api_key, ?::Hash[Symbol, untyped] options) -> void - def track: (String event, String distinct_id, **untyped options) -> untyped + def track: (String event, ?String? distinct_id, **untyped options) -> untyped | (::Hash[Symbol | String, untyped] event_payload, **untyped options) -> untyped | (::Array[::Hash[Symbol | String, untyped]] event_payloads, **untyped options) -> untyped @@ -29,6 +30,10 @@ module Altertable private + def reject_identity_call?: () -> bool + def audience_payload: (::Hash[Symbol, untyped] payload) -> ::Hash[Symbol, untyped] + def sanitize_url: (untyped value, ?origin_only: bool) -> String? + def select_adapter: (Symbol? name, ::Hash[Symbol, untyped] options) -> untyped def try_require: (String gem_name) -> bool def post: (String path, ::Hash[Symbol | String, untyped] | ::Array[::Hash[Symbol | String, untyped]] payload) -> untyped diff --git a/spec/altertable/audience_transport_spec.rb b/spec/altertable/audience_transport_spec.rb new file mode 100644 index 0000000..ae63024 --- /dev/null +++ b/spec/altertable/audience_transport_spec.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require "spec_helper" +require "socket" +require "timeout" + +RSpec.describe "Audience HTTP delivery" do + # Exercise real serialization and all supported transports against a local HTTP sink. + def with_http_sink(count) + server = TCPServer.new("127.0.0.1", 0) + requests = [] + worker = Thread.new do + count.times do + socket = Timeout.timeout(10) { server.accept } + begin + request_line = socket.gets + headers = {} + while (line = socket.gets) && line != "\r\n" + key, value = line.split(":", 2) + headers[key.downcase] = value.strip + end + body = socket.read(Integer(headers.fetch("content-length"))) + requests << { line: request_line, headers: headers, body: JSON.parse(body) } + socket.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}") + ensure + socket.close + end + end + end + yield "http://127.0.0.1:#{server.addr[1]}", requests + expect(worker.join(10)).not_to be_nil + worker.value + ensure + worker&.kill + worker&.join + server&.close + end + + it "preserves identified product delivery through HTTPX" do + with_http_sink(1) do |base_url, requests| + client = Altertable::Client.new("test-key", adapter: :httpx, base_url: base_url) + expect(client.track("Product", "user")).to eq("ok" => true) + expect(requests.first[:body]).to include("distinct_id" => "user", "environment" => "production") + expect(requests.first[:body]).not_to have_key("mode") + end + end + + [:faraday, :httpx, :net_http].each do |adapter| + it "sends restricted scalar, hash, and batch requests over #{adapter}" do + with_http_sink(3) do |base_url, requests| + client = Altertable::Client.new("test-key", mode: :audience, adapter: adapter, base_url: base_url, proxy: false) + properties = { "$url" => "https://user:pass@site.example/docs?token=secret#hash", + "$referer" => "https://search.example/private?token=secret", "$viewport" => "123x456" } + expect(client.track("Scalar", "ignored", anonymous_id: "anon", properties: properties)).to eq("ok" => true) + expect(client.track({ event: "Hash", device_id: "device", properties: properties })).to eq("ok" => true) + expect(client.track([{ "event" => "Batch", "distinct_id" => "user", "properties" => properties }])).to eq("ok" => true) + requests.each do |request| + expect(request[:line]).to start_with("POST /track ") + expect(request[:headers]).to include("x-api-key" => "test-key", "content-type" => "application/json") + expect(request[:headers].keys).not_to include("cookie", "referer", "forwarded", "x-forwarded-for") + payloads = request[:body].is_a?(Array) ? request[:body] : [request[:body]] + payloads.each do |payload| + expect(payload.keys).to contain_exactly("mode", "event", "timestamp", "properties") + expect(payload["mode"]).to eq("audience") + expect(payload["properties"]).to include("$url" => "https://site.example/docs", "$referer" => "https://search.example") + expect(payload["properties"]).not_to have_key("$viewport") + end + end + end + end + end +end diff --git a/spec/altertable/client_audience_spec.rb b/spec/altertable/client_audience_spec.rb new file mode 100644 index 0000000..3fb0b39 --- /dev/null +++ b/spec/altertable/client_audience_spec.rb @@ -0,0 +1,204 @@ +# frozen_string_literal: true + +require "spec_helper" + +RSpec.describe Altertable::Client, "audience mode" do + let(:adapter) { instance_double(Altertable::Adapters::NetHttpAdapter) } + let(:calls) { [] } + let(:client) { build_client(mode: :audience) } + + def build_client(**options) + described_class.new("key", { adapter: :net_http }.merge(options)).tap do |instance| + instance.instance_variable_set(:@adapter, adapter) + end + end + + before do + allow(adapter).to receive(:post) do |path, body:| + calls << { path: path, body: JSON.parse(body) } + Altertable::Adapters::Response.new(200, '{"ok":true}', {}) + end + end + + def expect_audience(payload) + expect(payload.keys).to contain_exactly("mode", "event", "timestamp", "properties") + expect(payload["mode"]).to eq("audience") + expect { Time.iso8601(payload["timestamp"]) }.not_to raise_error + expect(payload["properties"]).to include("$lib" => "altertable-ruby", "$lib_version" => Altertable::VERSION) + expect(payload["properties"]).not_to have_key("$viewport") + end + + it "omits all identity fields and environment from scalar events" do + client.track("Opened", "ignored", anonymous_id: "anon", device_id: "device", session_id: "session", environment: "private", mode: "product") + expect_audience(calls.last[:body]) + expect(calls.last[:path]).to eq("/track") + end + + it "accepts events without distinct IDs in scalar, hash, and batch forms" do + expect(client.track("Scalar")).to eq("ok" => true) + client.track({ event: "Hash" }) + client.track([{ event: "Batch" }, { "event" => "String keys" }]) + payloads = calls.flat_map { |call| call[:body].is_a?(Array) ? call[:body] : [call[:body]] } + expect(payloads.map { |payload| payload["event"] }).to eq(["Scalar", "Hash", "Batch", "String keys"]) + payloads.each { |payload| expect_audience(payload) } + end + + it "enforces client mode on hash and batch overrides" do + item = { "event" => "Opened", "mode" => "product", "distinct_id" => "user", "anonymous_id" => "anon", + "device_id" => "device", "session_id" => "session", "environment" => "private" }.freeze + client.track(item, mode: :product, distinct_id: "override") + client.track([item], mode: :product, distinct_id: "override") + expect_audience(calls.first[:body]) + expect_audience(calls.last[:body].first) + end + + it "sanitizes symbol and string built-ins after merging caller properties without mutating them" do + properties = { :"$url" => "https://user:password@SITE.example:443/docs?token=secret#hash", + "$referer" => "http://user:password@search.example:8080/private?token=secret", + :"$viewport" => "1234x987", "$viewport" => "another", section: "intro" }.freeze + client.track({ event: "Opened", properties: properties }, timestamp: "2026-11-04T10:00:00.000Z") + payload = calls.last[:body] + expect(payload["timestamp"]).to eq("2026-11-04T10:00:00.000Z") + expect(payload["properties"]).to include("$url" => "https://site.example/docs", "$referer" => "http://search.example:8080", "section" => "intro") + expect(payload["properties"]).not_to have_key("$viewport") + expect(properties[:"$url"]).to include("secret") + end + + [nil, 123, "not a URL?token=secret", "javascript:secret", "/relative?token=secret", "https://", "https://host:bad/path", "https://host:99999/path"].each do |url| + it "discards unsupported URL and referrer values: #{url.inspect}" do + client.track("Opened", properties: { "$url" => url, "$referer" => url }) + expect(calls.last[:body]["properties"]).to include("$url" => nil, "$referer" => nil) + end + end + + it "preserves paths, IPv6 hosts, and non-default ports without extracting query parameters" do + client.track("Opened", properties: { "$url" => "http://[::1]:8080/a%20b?email=private#secret", "$referer" => "https://search.example" }) + expect(calls.last[:body]["properties"]).to include("$url" => "http://[::1]:8080/a%20b", "$referer" => "https://search.example") + expect(calls.last[:body]["properties"]).not_to have_key("email") + end + + it "retains caller properties and release metadata without claiming to scrub custom PII" do + build_client(mode: :audience, release: "1.2.3").track("Opened", properties: { email: "caller@example.com" }) + expect(calls.last[:body]["properties"]).to include("$release" => "1.2.3", "email" => "caller@example.com", "$url" => nil, "$referer" => nil) + end + + it "ignores scalar, hash, batch, and invalid identity calls before validation" do + ["user", {}, [], [nil], nil].each do |identity| + expect(client.identify(identity)).to be_nil + expect(client.alias(identity)).to be_nil + end + expect(calls).to be_empty + client.track("Still collecting") + expect_audience(calls.last[:body]) + end + + it "warns about ignored identity calls when debug logging is enabled" do + debug_client = build_client(mode: :audience, debug: true) + expect { debug_client.identify("user") }.to output(/ignored in audience mode/).to_stderr + expect { debug_client.alias("old", "new") }.to output(/ignored in audience mode/).to_stderr + expect { client.identify("user") }.not_to output.to_stderr + end + + it "validates events and whole batches without sending partial batches" do + expect { client.track({}) }.to raise_error(ArgumentError, /event/) + expect { client.track([{ event: "Valid" }, {}]) }.to raise_error(ArgumentError, /event/) + expect { client.track([]) }.to raise_error(ArgumentError, /empty/) + expect { client.track([nil]) }.to raise_error(ArgumentError, /Hash/) + expect(calls).to be_empty + end + + [:product, "product"].each do |mode| + it "preserves product payloads and identity validation with mode #{mode.inspect}" do + product = build_client(mode: mode, environment: "staging") + product.track("Opened", "user", anonymous_id: "anon", device_id: "device", mode: :audience, + properties: { "$url" => "https://site.example/?private=yes", "$viewport" => "100x100" }) + expect(calls.last[:body]).to include("distinct_id" => "user", "anonymous_id" => "anon", "device_id" => "device", "environment" => "staging") + expect(calls.last[:body]).not_to have_key("mode") + expect(calls.last[:body]["properties"]).to include("$url" => "https://site.example/?private=yes", "$viewport" => "100x100") + expect { product.track({ event: "No ID" }) }.to raise_error(ArgumentError, /distinct_id/) + expect { product.track([{ event: "No ID" }]) }.to raise_error(ArgumentError, /distinct_id/) + product.identify("user") + expect(calls.last[:path]).to eq("/identify") + product.alias("old", "new") + expect(calls.last[:path]).to eq("/alias") + end + end + + it "defaults to product mode" do + build_client.track("Opened", "user") + expect(calls.last[:body]).to include("distinct_id" => "user", "environment" => "production") + expect(calls.last[:body]).not_to have_key("mode") + end + + it "captures the mode value at construction" do + mode = +"audience" + instance = build_client(mode: mode) + mode.replace("product") + instance.track("Opened") + expect_audience(calls.last[:body]) + end + + it "switches global clients through init and preserves an active client after invalid initialization" do + original = Altertable.instance_variable_get(:@client) + begin + product = Altertable.init("key", adapter: :net_http) + product.instance_variable_set(:@adapter, adapter) + Altertable.track("Product", "user") + audience = Altertable.init("key", mode: "audience", adapter: :net_http) + audience.instance_variable_set(:@adapter, adapter) + expect { Altertable.init("key", mode: :invalid) }.to raise_error(Altertable::ConfigurationError, /tracking mode/) + expect(Altertable.client).to equal(audience) + Altertable.identify("ignored") + Altertable.track("Audience") + expect(calls.map { |call| call[:body]["event"] }).to eq(["Product", "Audience"]) + expect_audience(calls.last[:body]) + product.track("Independent", "user") + expect(calls.last[:body]).not_to have_key("mode") + replacement = Altertable.init("key", mode: :product, adapter: :net_http) + replacement.instance_variable_set(:@adapter, adapter) + Altertable.track("Product again", "new-user") + expect(calls.last[:body]).to include("distinct_id" => "new-user") + expect(calls.last[:body]).not_to have_key("mode") + ensure + Altertable.instance_variable_set(:@client, original) + end + end + + [nil, false, :anonymous, "", {}].each do |mode| + it "rejects invalid mode #{mode.inspect} before constructing a transport" do + expect(Altertable::Adapters::NetHttpAdapter).not_to receive(:new) + expect { build_client(mode: mode) }.to raise_error(Altertable::ConfigurationError, /tracking mode/) + end + end + + it "keeps audience policy on caller retries after a failed batch" do + on_error = spy("on_error") + instance = build_client(mode: :audience, on_error: on_error) + allow(adapter).to receive(:post) do |path, body:| + calls << { path: path, body: JSON.parse(body) } + Altertable::Adapters::Response.new(calls.length == 1 ? 503 : 200, '{}', {}) + end + items = [{ event: "Retry", distinct_id: "ignored", properties: { "$url" => "https://site.example/?secret=yes" } }] + expect { instance.track(items) }.to raise_error(Altertable::ApiError) + expect(on_error).to have_received(:call).with(an_instance_of(Altertable::ApiError)) + instance.track(items) + expect(calls.length).to eq(2) + calls.each { |call| expect_audience(call[:body].first) } + expect(calls.last[:body].first["properties"]["$url"]).to eq("https://site.example/") + end + + it "reports delivery failures and does not replay failed events into another client" do + callback = spy("on_error") + failing = build_client(mode: :product, on_error: callback) + allow(adapter).to receive(:post).and_raise(Altertable::NetworkError, "offline") + expect { failing.track("Failed product", "user") }.to raise_error(Altertable::NetworkError) + expect(callback).to have_received(:call).with(an_instance_of(Altertable::NetworkError)) + allow(adapter).to receive(:post) do |path, body:| + calls << { path: path, body: JSON.parse(body) } + Altertable::Adapters::Response.new(200, '{}', {}) + end + client.track("Fresh audience") + expect(calls.length).to eq(1) + expect_audience(calls.last[:body]) + end +end From 41496733ad2a50cb09185ea69d4d6bc97e1cc492 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Fri, 6 Nov 2026 16:10:34 +0100 Subject: [PATCH 2/8] docs: focus audience setup and collection behavior --- README.md | 49 ++++++++++++++++++------------------------------- 1 file changed, 18 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index e9fc9d0..8d7ff9b 100644 --- a/README.md +++ b/README.md @@ -72,47 +72,34 @@ Altertable.track([ ### Audience Measurement -Product analytics is the default. Select audience measurement when creating a client: +Use an environment-bound Product Analytics API key and `mode: :audience` to collect events without client identity fields: ```ruby Altertable.init('pk_live_abc123', mode: :audience) Altertable.track('Docs Opened', properties: { '$url' => 'https://example.com/docs?campaign=launch', - '$referer' => 'https://search.example/results?q=docs', section: 'installation' }) -Altertable.track({ event: 'Install Copied', properties: { package: 'ruby' } }) Altertable.track([{ event: 'Docs Opened' }, { event: 'Install Copied' }]) ``` -Audience events send only `mode: "audience"`, `event`, `timestamp`, and `properties`. -No `distinct_id`, `anonymous_id`, `device_id`, `session_id`, or `environment` is sent, -even if supplied by the caller. The API key determines the audience environment. -`identify` and `alias` return `nil` without sending a request, including for hash -and batch inputs. Enable `debug: true` during development to warn about these calls. - -The SDK reduces `$url` to its HTTP(S) origin and path, reduces `$referer` to its -origin, and removes `$viewport`. Credentials, query strings, and fragments are -removed from these built-in URLs; invalid or unsupported URLs become `nil`. -Both symbol and string property keys are supported. Library/version and configured -release metadata are retained. Custom properties and URL paths can still contain -personal information: callers are responsible for choosing appropriate values. - -Mode is fixed for each `Altertable::Client`. Create a new client or call -`Altertable.init` again to change it. Per-event options cannot override mode. -Both `:product`/`:audience` and `"product"`/`"audience"` are accepted; other values -raise `Altertable::ConfigurationError` before replacing the global client. - -This server SDK sends requests immediately. It has no persistent identity, -sessions, disk queue, consent manager, automatic page capture, or event transforms. -Failed requests are not queued for replay across clients. Gate calls according to -your application's consent policy. All HTTP transports (`:faraday`, `:httpx`, and -`:net_http`) are supported; their existing timeout, proxy, and retry behavior applies. - -Audience visitor hashing on the backend uses the IP address and User-Agent of the -SDK's HTTP request, which describe your server rather than the end user's browser. -Server-side audience events therefore cannot reliably measure distinct end-user -visitors. This SDK does not forward end-user IP/User-Agent headers. +Product mode is the default. Create a new client or call `Altertable.init` again to +change modes. Audience events omit user, anonymous, device, session, and environment +fields across scalar, hash, and batch calls. The API key selects the environment; +legacy unbound keys cannot be used. `identify` and `alias` return `nil` without +sending requests, with warnings when `debug` is enabled. + +Audience mode removes `$viewport`, reduces `$url` to HTTP(S) origin plus path, and +reduces `$referer` to origin. Invalid URLs become `nil`. Symbol and string property +keys are supported. Custom properties and URL paths can still contain personal +information; choose them accordingly. + +Gate calls on your application's consent decisions. Events are sent immediately; +failed sends are not queued for replay. Faraday, HTTPX, and Net::HTTP are supported. + +The backend derives audience visitors from the request IP and User-Agent. For this +server SDK, those describe your server, so these events cannot reliably measure +distinct browser visitors. End-user request headers are not forwarded automatically. ### Identifying Users From c8f21742d39fa7d5c5b741bc7a611ba81230aa4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 13:16:06 +0100 Subject: [PATCH 3/8] fix: prevent ambient credentials in audience mode --- README.md | 4 ++- lib/altertable/client.rb | 10 ++++++ rbi/altertable.rbi | 3 ++ sig/altertable/client.rbs | 1 + spec/altertable/audience_transport_spec.rb | 42 ++++++++++++++++++---- 5 files changed, 53 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8d7ff9b..63b5750 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,9 @@ keys are supported. Custom properties and URL paths can still contain personal information; choose them accordingly. Gate calls on your application's consent decisions. Events are sent immediately; -failed sends are not queued for replay. Faraday, HTTPX, and Net::HTTP are supported. +failed sends are not queued for replay. Audience delivery does not persist cookies +or follow redirects; redirects are delivery failures. Faraday, HTTPX, and Net::HTTP +are supported. Audience endpoints cannot include embedded HTTP credentials. The backend derives audience visitors from the request IP and User-Agent. For this server SDK, those describe your server, so these events cannot reliably measure diff --git a/lib/altertable/client.rb b/lib/altertable/client.rb index 4fd86fe..0c040f3 100644 --- a/lib/altertable/client.rb +++ b/lib/altertable/client.rb @@ -23,6 +23,7 @@ def initialize(api_key, options = {}) end @api_key = api_key @base_url = options[:base_url] || DEFAULT_BASE_URL + validate_audience_endpoint! if @mode == :audience @environment = options[:environment] || DEFAULT_ENVIRONMENT @timeout = options[:request_timeout] || DEFAULT_TIMEOUT @release = options[:release] @@ -87,6 +88,15 @@ def reject_identity_call? true end + def validate_audience_endpoint! + endpoint = URI.parse(@base_url) + return unless endpoint.user || endpoint.password + + raise ConfigurationError, "Audience endpoints cannot include credentials" + rescue URI::InvalidURIError + raise ConfigurationError, "Audience endpoint must be a valid URL" + end + def select_adapter(name, options) case name when :faraday diff --git a/rbi/altertable.rbi b/rbi/altertable.rbi index cabe0c7..2489e7a 100644 --- a/rbi/altertable.rbi +++ b/rbi/altertable.rbi @@ -51,6 +51,9 @@ module Altertable sig { returns(T::Boolean) } def reject_identity_call?; end + sig { void } + def validate_audience_endpoint!; end + sig { params(payload: T::Hash[Symbol, T.untyped]).returns(T::Hash[Symbol, T.untyped]) } def audience_payload(payload); end diff --git a/sig/altertable/client.rbs b/sig/altertable/client.rbs index 935bc41..630d942 100644 --- a/sig/altertable/client.rbs +++ b/sig/altertable/client.rbs @@ -31,6 +31,7 @@ module Altertable private def reject_identity_call?: () -> bool + def validate_audience_endpoint!: () -> void def audience_payload: (::Hash[Symbol, untyped] payload) -> ::Hash[Symbol, untyped] def sanitize_url: (untyped value, ?origin_only: bool) -> String? diff --git a/spec/altertable/audience_transport_spec.rb b/spec/altertable/audience_transport_spec.rb index ae63024..f5aa83c 100644 --- a/spec/altertable/audience_transport_spec.rb +++ b/spec/altertable/audience_transport_spec.rb @@ -6,11 +6,11 @@ RSpec.describe "Audience HTTP delivery" do # Exercise real serialization and all supported transports against a local HTTP sink. - def with_http_sink(count) + def with_http_sink(responses) server = TCPServer.new("127.0.0.1", 0) requests = [] worker = Thread.new do - count.times do + responses.each do |response| socket = Timeout.timeout(10) { server.accept } begin request_line = socket.gets @@ -21,7 +21,7 @@ def with_http_sink(count) end body = socket.read(Integer(headers.fetch("content-length"))) requests << { line: request_line, headers: headers, body: JSON.parse(body) } - socket.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}") + socket.write(response) ensure socket.close end @@ -37,7 +37,7 @@ def with_http_sink(count) end it "preserves identified product delivery through HTTPX" do - with_http_sink(1) do |base_url, requests| + with_http_sink([ok_response]) do |base_url, requests| client = Altertable::Client.new("test-key", adapter: :httpx, base_url: base_url) expect(client.track("Product", "user")).to eq("ok" => true) expect(requests.first[:body]).to include("distinct_id" => "user", "environment" => "production") @@ -47,7 +47,7 @@ def with_http_sink(count) [:faraday, :httpx, :net_http].each do |adapter| it "sends restricted scalar, hash, and batch requests over #{adapter}" do - with_http_sink(3) do |base_url, requests| + with_http_sink(Array.new(3, ok_response)) do |base_url, requests| client = Altertable::Client.new("test-key", mode: :audience, adapter: adapter, base_url: base_url, proxy: false) properties = { "$url" => "https://user:pass@site.example/docs?token=secret#hash", "$referer" => "https://search.example/private?token=secret", "$viewport" => "123x456" } @@ -57,7 +57,7 @@ def with_http_sink(count) requests.each do |request| expect(request[:line]).to start_with("POST /track ") expect(request[:headers]).to include("x-api-key" => "test-key", "content-type" => "application/json") - expect(request[:headers].keys).not_to include("cookie", "referer", "forwarded", "x-forwarded-for") + expect(request[:headers].keys).not_to include("authorization", "cookie", "referer", "forwarded", "x-forwarded-for") payloads = request[:body].is_a?(Array) ? request[:body] : [request[:body]] payloads.each do |payload| expect(payload.keys).to contain_exactly("mode", "event", "timestamp", "properties") @@ -69,4 +69,34 @@ def with_http_sink(count) end end end + + [:faraday, :httpx, :net_http].each do |adapter| + it "does not persist cookies or follow redirects over #{adapter}" do + responses = [ + "HTTP/1.1 200 OK\r\nSet-Cookie: visitor=private\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}", + "HTTP/1.1 302 Found\r\nLocation: /redirected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ] + with_http_sink(responses) do |base_url, requests| + client = Altertable::Client.new("test-key", mode: :audience, adapter: adapter, base_url: base_url, proxy: false) + expect(client.track("First")).to eq("ok" => true) + expect { client.track("Second") }.to raise_error(Altertable::ApiError, /HTTP Error: 302/) + expect(requests.length).to eq(2) + expect(requests.last[:headers]).not_to have_key("cookie") + end + end + end + + it "rejects audience endpoints with embedded credentials before delivery" do + with_http_sink([]) do |base_url, requests| + endpoint = base_url.sub("http://", "http://user:password@") + expect do + Altertable::Client.new("test-key", mode: :audience, adapter: :faraday, base_url: endpoint, proxy: false) + end.to raise_error(Altertable::ConfigurationError, /cannot include credentials/) + expect(requests).to be_empty + end + end + + def ok_response + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}" + end end From e2c9ff873851453a6b48761820a0185c50a479f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 13:23:58 +0100 Subject: [PATCH 4/8] build: support current macOS bundle platform --- Gemfile.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Gemfile.lock b/Gemfile.lock index 51709d9..220101e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -135,6 +135,7 @@ GEM yard PLATFORMS + arm64-darwin-24 arm64-darwin-25 x86_64-linux From 5504863b6d8281f313b6ba690e1c4adcde298cbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 14:30:20 +0100 Subject: [PATCH 5/8] fix: keep HTTPX adapter base_url option unchanged --- lib/altertable/adapters.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/altertable/adapters.rb b/lib/altertable/adapters.rb index 676e642..4ea6fff 100644 --- a/lib/altertable/adapters.rb +++ b/lib/altertable/adapters.rb @@ -60,7 +60,7 @@ def initialize(base_url:, timeout:, headers: {}, proxy: nil) @client = client.with( timeout: { operation_timeout: @timeout }, headers: @headers, - origin: @base_url + base_url: @base_url ) end From fa245e29c1476ee85826ec6f2699d80324e14101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 14:30:20 +0100 Subject: [PATCH 6/8] build: drop arm64-darwin-24 lockfile platform --- Gemfile.lock | 1 - 1 file changed, 1 deletion(-) diff --git a/Gemfile.lock b/Gemfile.lock index 220101e..51709d9 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -135,7 +135,6 @@ GEM yard PLATFORMS - arm64-darwin-24 arm64-darwin-25 x86_64-linux From 7b12d0c21195aaf63440787481a036617f0ce31b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 14:30:20 +0100 Subject: [PATCH 7/8] refactor: limit server audience mode to wire shape Server requests carry no visitor page context, cookies, or ambient credentials, so drop URL rewriting, endpoint credential checks, and transport tests. Caller properties now pass through unchanged. --- CHANGELOG.md | 2 +- README.md | 33 ++----- lib/altertable/client.rb | 34 +------ rbi/altertable.rbi | 6 -- sig/altertable/client.rbs | 2 - spec/altertable/audience_transport_spec.rb | 102 --------------------- spec/altertable/client_audience_spec.rb | 38 ++------ 7 files changed, 15 insertions(+), 202 deletions(-) delete mode 100644 spec/altertable/audience_transport_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index dd0c44e..20c5aee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Features -* Add audience collection mode for scalar, hash, and batch tracking, with identity suppression, restricted wire fields, and built-in URL sanitization. Product mode remains the default. +* Add `mode: :audience` to collect events without identity fields. Product mode remains the default. ## [1.3.0](https://github.com/altertable-ai/altertable-ruby/compare/altertable/v1.2.0...altertable/v1.3.0) (2026-09-04) diff --git a/README.md b/README.md index 63b5750..1505793 100644 --- a/README.md +++ b/README.md @@ -47,8 +47,7 @@ Altertable.init('pk_live_abc123', environment: 'production', debug: true) Record an action performed by a user. -`Altertable.track(event, distinct_id = nil, **options)` - +`Altertable.track(event, distinct_id = nil, **options)` `Altertable.track(event_payload, **options)` `Altertable.track(event_payloads, **options)` @@ -72,36 +71,16 @@ Altertable.track([ ### Audience Measurement -Use an environment-bound Product Analytics API key and `mode: :audience` to collect events without client identity fields: +Initialize with `mode: :audience` to collect events without identity fields: ```ruby Altertable.init('pk_live_abc123', mode: :audience) -Altertable.track('Docs Opened', properties: { - '$url' => 'https://example.com/docs?campaign=launch', - section: 'installation' -}) -Altertable.track([{ event: 'Docs Opened' }, { event: 'Install Copied' }]) +Altertable.track('Docs Opened', properties: { section: 'installation' }) ``` -Product mode is the default. Create a new client or call `Altertable.init` again to -change modes. Audience events omit user, anonymous, device, session, and environment -fields across scalar, hash, and batch calls. The API key selects the environment; -legacy unbound keys cannot be used. `identify` and `alias` return `nil` without -sending requests, with warnings when `debug` is enabled. - -Audience mode removes `$viewport`, reduces `$url` to HTTP(S) origin plus path, and -reduces `$referer` to origin. Invalid URLs become `nil`. Symbol and string property -keys are supported. Custom properties and URL paths can still contain personal -information; choose them accordingly. - -Gate calls on your application's consent decisions. Events are sent immediately; -failed sends are not queued for replay. Audience delivery does not persist cookies -or follow redirects; redirects are delivery failures. Faraday, HTTPX, and Net::HTTP -are supported. Audience endpoints cannot include embedded HTTP credentials. - -The backend derives audience visitors from the request IP and User-Agent. For this -server SDK, those describe your server, so these events cannot reliably measure -distinct browser visitors. End-user request headers are not forwarded automatically. +Audience events send only `event`, `timestamp`, and `properties`; distinct, anonymous, +device, session, and environment fields are dropped. `identify` and `alias` are ignored. +Requests come from your server, so they cannot distinguish browser visitors. ### Identifying Users diff --git a/lib/altertable/client.rb b/lib/altertable/client.rb index 0c040f3..13d976f 100644 --- a/lib/altertable/client.rb +++ b/lib/altertable/client.rb @@ -2,7 +2,6 @@ require "json" require "time" -require "uri" require_relative "errors" require_relative "adapters" @@ -23,7 +22,6 @@ def initialize(api_key, options = {}) end @api_key = api_key @base_url = options[:base_url] || DEFAULT_BASE_URL - validate_audience_endpoint! if @mode == :audience @environment = options[:environment] || DEFAULT_ENVIRONMENT @timeout = options[:request_timeout] || DEFAULT_TIMEOUT @release = options[:release] @@ -88,15 +86,6 @@ def reject_identity_call? true end - def validate_audience_endpoint! - endpoint = URI.parse(@base_url) - return unless endpoint.user || endpoint.password - - raise ConfigurationError, "Audience endpoints cannot include credentials" - rescue URI::InvalidURIError - raise ConfigurationError, "Audience endpoint must be a valid URL" - end - def select_adapter(name, options) case name when :faraday @@ -209,28 +198,7 @@ def track_payload(event, distinct_id, options) # Select wire fields explicitly so per-event options cannot override client policy. def audience_payload(payload) - properties = payload[:properties].transform_keys(&:to_s) - properties["$url"] = sanitize_url(properties["$url"]) - properties["$referer"] = sanitize_url(properties["$referer"], origin_only: true) - properties.delete("$viewport") - { mode: "audience", event: payload[:event], timestamp: payload[:timestamp], properties: properties } - end - - def sanitize_url(value, origin_only: false) - return unless value.is_a?(String) - - url = URI.parse(value) - return unless url.is_a?(URI::HTTP) && url.host && !url.host.empty? - return unless url.port.between?(0, 65_535) - - origin = "#{url.scheme}://#{url.host.downcase}" - origin += ":#{url.port}" if url.port != url.default_port - return origin if origin_only - - path = url.path.empty? ? "/" : url.path - "#{origin}#{path}" - rescue URI::InvalidURIError - nil + { mode: "audience", event: payload[:event], timestamp: payload[:timestamp], properties: payload[:properties] } end def identify_payload(user_id, options) diff --git a/rbi/altertable.rbi b/rbi/altertable.rbi index 2489e7a..c4b2415 100644 --- a/rbi/altertable.rbi +++ b/rbi/altertable.rbi @@ -51,15 +51,9 @@ module Altertable sig { returns(T::Boolean) } def reject_identity_call?; end - sig { void } - def validate_audience_endpoint!; end - sig { params(payload: T::Hash[Symbol, T.untyped]).returns(T::Hash[Symbol, T.untyped]) } def audience_payload(payload); end - sig { params(value: T.untyped, origin_only: T::Boolean).returns(T.nilable(String)) } - def sanitize_url(value, origin_only: false); end - sig { params(gem_name: String).returns(T::Boolean) } def try_require(gem_name); end diff --git a/sig/altertable/client.rbs b/sig/altertable/client.rbs index 630d942..5b96428 100644 --- a/sig/altertable/client.rbs +++ b/sig/altertable/client.rbs @@ -31,9 +31,7 @@ module Altertable private def reject_identity_call?: () -> bool - def validate_audience_endpoint!: () -> void def audience_payload: (::Hash[Symbol, untyped] payload) -> ::Hash[Symbol, untyped] - def sanitize_url: (untyped value, ?origin_only: bool) -> String? def select_adapter: (Symbol? name, ::Hash[Symbol, untyped] options) -> untyped def try_require: (String gem_name) -> bool diff --git a/spec/altertable/audience_transport_spec.rb b/spec/altertable/audience_transport_spec.rb deleted file mode 100644 index f5aa83c..0000000 --- a/spec/altertable/audience_transport_spec.rb +++ /dev/null @@ -1,102 +0,0 @@ -# frozen_string_literal: true - -require "spec_helper" -require "socket" -require "timeout" - -RSpec.describe "Audience HTTP delivery" do - # Exercise real serialization and all supported transports against a local HTTP sink. - def with_http_sink(responses) - server = TCPServer.new("127.0.0.1", 0) - requests = [] - worker = Thread.new do - responses.each do |response| - socket = Timeout.timeout(10) { server.accept } - begin - request_line = socket.gets - headers = {} - while (line = socket.gets) && line != "\r\n" - key, value = line.split(":", 2) - headers[key.downcase] = value.strip - end - body = socket.read(Integer(headers.fetch("content-length"))) - requests << { line: request_line, headers: headers, body: JSON.parse(body) } - socket.write(response) - ensure - socket.close - end - end - end - yield "http://127.0.0.1:#{server.addr[1]}", requests - expect(worker.join(10)).not_to be_nil - worker.value - ensure - worker&.kill - worker&.join - server&.close - end - - it "preserves identified product delivery through HTTPX" do - with_http_sink([ok_response]) do |base_url, requests| - client = Altertable::Client.new("test-key", adapter: :httpx, base_url: base_url) - expect(client.track("Product", "user")).to eq("ok" => true) - expect(requests.first[:body]).to include("distinct_id" => "user", "environment" => "production") - expect(requests.first[:body]).not_to have_key("mode") - end - end - - [:faraday, :httpx, :net_http].each do |adapter| - it "sends restricted scalar, hash, and batch requests over #{adapter}" do - with_http_sink(Array.new(3, ok_response)) do |base_url, requests| - client = Altertable::Client.new("test-key", mode: :audience, adapter: adapter, base_url: base_url, proxy: false) - properties = { "$url" => "https://user:pass@site.example/docs?token=secret#hash", - "$referer" => "https://search.example/private?token=secret", "$viewport" => "123x456" } - expect(client.track("Scalar", "ignored", anonymous_id: "anon", properties: properties)).to eq("ok" => true) - expect(client.track({ event: "Hash", device_id: "device", properties: properties })).to eq("ok" => true) - expect(client.track([{ "event" => "Batch", "distinct_id" => "user", "properties" => properties }])).to eq("ok" => true) - requests.each do |request| - expect(request[:line]).to start_with("POST /track ") - expect(request[:headers]).to include("x-api-key" => "test-key", "content-type" => "application/json") - expect(request[:headers].keys).not_to include("authorization", "cookie", "referer", "forwarded", "x-forwarded-for") - payloads = request[:body].is_a?(Array) ? request[:body] : [request[:body]] - payloads.each do |payload| - expect(payload.keys).to contain_exactly("mode", "event", "timestamp", "properties") - expect(payload["mode"]).to eq("audience") - expect(payload["properties"]).to include("$url" => "https://site.example/docs", "$referer" => "https://search.example") - expect(payload["properties"]).not_to have_key("$viewport") - end - end - end - end - end - - [:faraday, :httpx, :net_http].each do |adapter| - it "does not persist cookies or follow redirects over #{adapter}" do - responses = [ - "HTTP/1.1 200 OK\r\nSet-Cookie: visitor=private\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}", - "HTTP/1.1 302 Found\r\nLocation: /redirected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" - ] - with_http_sink(responses) do |base_url, requests| - client = Altertable::Client.new("test-key", mode: :audience, adapter: adapter, base_url: base_url, proxy: false) - expect(client.track("First")).to eq("ok" => true) - expect { client.track("Second") }.to raise_error(Altertable::ApiError, /HTTP Error: 302/) - expect(requests.length).to eq(2) - expect(requests.last[:headers]).not_to have_key("cookie") - end - end - end - - it "rejects audience endpoints with embedded credentials before delivery" do - with_http_sink([]) do |base_url, requests| - endpoint = base_url.sub("http://", "http://user:password@") - expect do - Altertable::Client.new("test-key", mode: :audience, adapter: :faraday, base_url: endpoint, proxy: false) - end.to raise_error(Altertable::ConfigurationError, /cannot include credentials/) - expect(requests).to be_empty - end - end - - def ok_response - "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}" - end -end diff --git a/spec/altertable/client_audience_spec.rb b/spec/altertable/client_audience_spec.rb index 3fb0b39..e8d3afb 100644 --- a/spec/altertable/client_audience_spec.rb +++ b/spec/altertable/client_audience_spec.rb @@ -25,7 +25,6 @@ def expect_audience(payload) expect(payload["mode"]).to eq("audience") expect { Time.iso8601(payload["timestamp"]) }.not_to raise_error expect(payload["properties"]).to include("$lib" => "altertable-ruby", "$lib_version" => Altertable::VERSION) - expect(payload["properties"]).not_to have_key("$viewport") end it "omits all identity fields and environment from scalar events" do @@ -52,34 +51,12 @@ def expect_audience(payload) expect_audience(calls.last[:body].first) end - it "sanitizes symbol and string built-ins after merging caller properties without mutating them" do - properties = { :"$url" => "https://user:password@SITE.example:443/docs?token=secret#hash", - "$referer" => "http://user:password@search.example:8080/private?token=secret", - :"$viewport" => "1234x987", "$viewport" => "another", section: "intro" }.freeze - client.track({ event: "Opened", properties: properties }, timestamp: "2026-11-04T10:00:00.000Z") - payload = calls.last[:body] - expect(payload["timestamp"]).to eq("2026-11-04T10:00:00.000Z") - expect(payload["properties"]).to include("$url" => "https://site.example/docs", "$referer" => "http://search.example:8080", "section" => "intro") - expect(payload["properties"]).not_to have_key("$viewport") - expect(properties[:"$url"]).to include("secret") - end - - [nil, 123, "not a URL?token=secret", "javascript:secret", "/relative?token=secret", "https://", "https://host:bad/path", "https://host:99999/path"].each do |url| - it "discards unsupported URL and referrer values: #{url.inspect}" do - client.track("Opened", properties: { "$url" => url, "$referer" => url }) - expect(calls.last[:body]["properties"]).to include("$url" => nil, "$referer" => nil) - end - end - - it "preserves paths, IPv6 hosts, and non-default ports without extracting query parameters" do - client.track("Opened", properties: { "$url" => "http://[::1]:8080/a%20b?email=private#secret", "$referer" => "https://search.example" }) - expect(calls.last[:body]["properties"]).to include("$url" => "http://[::1]:8080/a%20b", "$referer" => "https://search.example") - expect(calls.last[:body]["properties"]).not_to have_key("email") - end - - it "retains caller properties and release metadata without claiming to scrub custom PII" do - build_client(mode: :audience, release: "1.2.3").track("Opened", properties: { email: "caller@example.com" }) - expect(calls.last[:body]["properties"]).to include("$release" => "1.2.3", "email" => "caller@example.com", "$url" => nil, "$referer" => nil) + it "passes caller properties and release metadata through unchanged" do + properties = { "$url" => "https://user:password@example.com/docs?token=private#secret", + "$referer" => "https://search.example/private?token=private#secret", + "$viewport" => "1234x987", "environment" => "business-value", "email" => "caller@example.com" } + build_client(mode: :audience, release: "1.2.3").track("Opened", properties: properties) + expect(calls.last[:body]["properties"]).to include(properties.merge("$release" => "1.2.3")) end it "ignores scalar, hash, batch, and invalid identity calls before validation" do @@ -178,13 +155,12 @@ def expect_audience(payload) calls << { path: path, body: JSON.parse(body) } Altertable::Adapters::Response.new(calls.length == 1 ? 503 : 200, '{}', {}) end - items = [{ event: "Retry", distinct_id: "ignored", properties: { "$url" => "https://site.example/?secret=yes" } }] + items = [{ event: "Retry", distinct_id: "ignored" }] expect { instance.track(items) }.to raise_error(Altertable::ApiError) expect(on_error).to have_received(:call).with(an_instance_of(Altertable::ApiError)) instance.track(items) expect(calls.length).to eq(2) calls.each { |call| expect_audience(call[:body].first) } - expect(calls.last[:body].first["properties"]["$url"]).to eq("https://site.example/") end it "reports delivery failures and does not replay failed events into another client" do From d7b2a7e12de2c8f94594ea77c2e133c91d0ac1b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Chalifour?= Date: Mon, 9 Nov 2026 15:05:29 +0100 Subject: [PATCH 8/8] refactor: ignore audience identity calls without logging --- lib/altertable/client.rb | 5 +---- spec/altertable/client_audience_spec.rb | 7 +++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/lib/altertable/client.rb b/lib/altertable/client.rb index 13d976f..8e822e7 100644 --- a/lib/altertable/client.rb +++ b/lib/altertable/client.rb @@ -80,10 +80,7 @@ def alias(distinct_id, new_user_id = nil, **options) private def reject_identity_call? - return false unless @mode == :audience - - warn "[Altertable] identify() and alias() calls are ignored in audience mode." if @debug - true + @mode == :audience end def select_adapter(name, options) diff --git a/spec/altertable/client_audience_spec.rb b/spec/altertable/client_audience_spec.rb index e8d3afb..8bcd2ad 100644 --- a/spec/altertable/client_audience_spec.rb +++ b/spec/altertable/client_audience_spec.rb @@ -69,11 +69,10 @@ def expect_audience(payload) expect_audience(calls.last[:body]) end - it "warns about ignored identity calls when debug logging is enabled" do + it "ignores identity calls silently, even with debug enabled" do debug_client = build_client(mode: :audience, debug: true) - expect { debug_client.identify("user") }.to output(/ignored in audience mode/).to_stderr - expect { debug_client.alias("old", "new") }.to output(/ignored in audience mode/).to_stderr - expect { client.identify("user") }.not_to output.to_stderr + expect { debug_client.identify("user") }.not_to output.to_stderr + expect { debug_client.alias("old", "new") }.not_to output.to_stderr end it "validates events and whole batches without sending partial batches" do