camada 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +46 -13
- data/lib/camada/beacon_js.rb +3 -3
- data/lib/camada/config.rb +17 -0
- data/lib/camada/constants.rb +1 -1
- data/lib/camada/engine.rb +11 -3
- data/lib/camada/events/build.rb +16 -16
- data/lib/camada/guarded.rb +16 -2
- data/lib/camada/rack.rb +2 -2
- data/lib/camada/redact.rb +36 -1
- data/lib/camada/version.rb +1 -1
- metadata +7 -4
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 81e8475950a7190044a094fa9329467bff9e064e083fe83327663b4eaf82e9be
|
|
4
|
+
data.tar.gz: 9e5b3394a0b60d9c4c26959c57b491d4194f1839348df7272648bc0d36192ee2
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 93e2b04ad0211340418261867467fab531d140bbf1b78785912ce924ea0c410052c22a8ed67cabf095320f07931a1b6fd6a85daeed3fc98f23e713963529169f
|
|
7
|
+
data.tar.gz: e154873db06c8b6fcce9ba670aef1f462e65bc44b0506955cccdc3c51303ecf5b15c0098a0159640aadbd3ee690ab7c494971885e268b5dfe68d3555fe7f070f
|
data/README.md
CHANGED
|
@@ -4,13 +4,21 @@ camada for Ruby: enforces the tenant snapshot inline (your ordered custom rules,
|
|
|
4
4
|
block, challenge), serves a first-party proof-of-work challenge page and beacon, records the
|
|
5
5
|
outcomes your handlers know (`Camada.track`), and ships wire events in batches off the request
|
|
6
6
|
path. One gem with a Rack middleware that any Rack app mounts (Sinatra, Hanami, plain Rack) and
|
|
7
|
-
a Railtie that mounts it for Rails
|
|
7
|
+
a Railtie that mounts it for Rails (the `sentry-ruby` model). Fails open by design: a camada
|
|
8
8
|
outage or bug never 5xxes your app.
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
Install from RubyGems with `bundle add camada`. Ruby 3.1 or newer, with no runtime dependencies
|
|
11
|
+
(stdlib only: `net/http`, `openssl`, `digest`, `json`, `securerandom`, `zlib`, `stringio`). For
|
|
12
|
+
local SDK work, use `gem "camada", path: "../camada-ruby"` in your Gemfile, as
|
|
13
|
+
[`camada-ruby-example`](https://github.com/camada-app/camada-ruby-example) does.
|
|
14
|
+
|
|
15
|
+
## Documentation
|
|
16
|
+
|
|
17
|
+
- [Ruby SDK guide](https://www.camada.app/docs/ruby): options, Rack middleware, Rails Railtie, and proxy rules.
|
|
18
|
+
- [Rails and Rack quickstart](https://www.camada.app/docs/quickstart/rails): install the gem and mount `Camada::Rack`.
|
|
19
|
+
- [In-app bot detection](https://www.camada.app/bot-detection): how camada stops credential stuffing, fake signups, and scrapers.
|
|
20
|
+
- [Test your bot signals](https://www.camada.app/tools/bot-test): live browser, HTTP, and TLS signal inspector.
|
|
21
|
+
- [Docs](https://www.camada.app/docs) and [Pricing](https://www.camada.app/pricing): full reference and plan limits.
|
|
14
22
|
|
|
15
23
|
## Quickstart
|
|
16
24
|
|
|
@@ -66,7 +74,7 @@ use Camada::Rack, engine
|
|
|
66
74
|
thread at the cadence your tenant config sets (`poll_seconds`), with ETag/304 and gzip on the
|
|
67
75
|
wire. `CAMADA_SERVERLESS=1` switches to a per-request staleness check with no poll thread. Every
|
|
68
76
|
poll and event batch carries `x-camada-sdk: @camada/ruby/<version>`, and polls ask for
|
|
69
|
-
snapshot v5 (`x-camada-snapshot: 5`)
|
|
77
|
+
snapshot v5 (`x-camada-snapshot: 5`), the container that carries your ordered custom rules.
|
|
70
78
|
2. Resolves the client from the socket peer (`REMOTE_ADDR`), combined with `X-Forwarded-For`
|
|
71
79
|
only under your tenant's trusted-proxy config (or `CAMADA_TRUSTED_PROXY` locally). A forwarded
|
|
72
80
|
header on its own is never the ip: any caller can set it. **Never `request.ip`**:
|
|
@@ -124,12 +132,27 @@ use Camada::Rack, engine
|
|
|
124
132
|
| `challenge_path` | `/__camada/challenge` | where the page posts its solution |
|
|
125
133
|
| `snapshot_version` | `5` | 4 drops your custom rules; 3 the allow/challenge sides too |
|
|
126
134
|
| `script_path` / `fp_path` | `/_cam/b.js` / `/_cam/fp` | the beacon endpoints; keep them in one directory |
|
|
135
|
+
| `token_hash` | `nil` | set to `true` to enable credential hashing or `false` to disable it |
|
|
136
|
+
| `token_header` | `nil` | optional extra credential header to try before `Authorization` |
|
|
127
137
|
|
|
128
138
|
Env: `CAMADA_KEY` (or `CAMADA_TOKEN` + `CAMADA_SNAPSHOT_TOKEN`), `CAMADA_INGEST_URL`,
|
|
129
139
|
`CAMADA_SNAPSHOT_URL`, `CAMADA_TRUSTED_PROXY` (`none | vercel | hops:N | cidrs:a,b`),
|
|
130
140
|
`CAMADA_SERVERLESS=1`, `CAMADA_CHALLENGE=0`, and the kill switch `CAMADA_DISABLED=1` (checked per
|
|
131
141
|
request; set at boot, no threads start at all).
|
|
132
142
|
|
|
143
|
+
### Credential hashing
|
|
144
|
+
|
|
145
|
+
Set `token_hash: true` or `CAMADA_TOKEN_HASH=1` to enable credential hashing. The environment
|
|
146
|
+
flag must be exactly `1` and applies only when `token_hash` is unset. Use `token_header` or
|
|
147
|
+
`CAMADA_TOKEN_HEADER` to name an extra header, such as `X-Api-Key`. A non-empty option takes
|
|
148
|
+
precedence over the environment. Camada reads these settings when it creates the engine and
|
|
149
|
+
tries the extra header before `Authorization` on each request.
|
|
150
|
+
|
|
151
|
+
Request events carry `tk` as the first 32 lowercase hex characters of an HMAC-SHA256 keyed by
|
|
152
|
+
your ingest token. The credential value stays in the app. Camada omits `tk` when hashing is off,
|
|
153
|
+
no header yields a usable credential, or hashing fails. Enable this only for random tokens or API keys.
|
|
154
|
+
Keep it off for human passwords sent over Basic authentication.
|
|
155
|
+
|
|
133
156
|
## The first-party beacon
|
|
134
157
|
|
|
135
158
|
```ruby
|
|
@@ -141,6 +164,12 @@ The tag is `<script src="/_cam/b.js?r=<rid>" async>`, so the beacon joins the pa
|
|
|
141
164
|
served it. Move both paths with `script_path` / `fp_path` when `/_cam/` is not yours; the script
|
|
142
165
|
derives the post path from its own URL, so the two must share a directory.
|
|
143
166
|
|
|
167
|
+
The SDK vendors a tagged `@camada/browser` release, never a build of camada-browser main. CI reads
|
|
168
|
+
the version from `BEACON_VERSION` in `lib/camada/beacon_js.rb`, checks out `camada-browser` at
|
|
169
|
+
`v<version>`, builds it and compares it byte for byte with the vendored copy, so beacon changes on
|
|
170
|
+
main cannot turn this CI red. To take a new beacon, re-sync from its release tag (see the testing
|
|
171
|
+
notes below) and commit; the version bump moves CI to the new tag.
|
|
172
|
+
|
|
144
173
|
## App-context events
|
|
145
174
|
|
|
146
175
|
```ruby
|
|
@@ -171,7 +200,7 @@ valid `_cch`, then `nil`. A non-page (non-HTML) request also gets `nil` and is s
|
|
|
171
200
|
outcomes. Puma hands the env to Rack as binary strings; the middleware reads them as UTF-8 with
|
|
172
201
|
invalid bytes replaced (U+FFFD) before matching and shipping, so a stray high byte in a header
|
|
173
202
|
neither escapes a rule nor costs the batch it rides in. The Rack env carries no wire header order (`hord` is the env's order), so this tap ships no header-order signal; camada resolves ASN and country itself. Enforcement
|
|
174
|
-
at this position covers ip, path, user-agent and header conditions
|
|
203
|
+
at this position covers ip, path, user-agent and header conditions: ASN, country and TLS entries
|
|
175
204
|
fail open in-app. `matches` patterns are JS regexes read by Ruby's Onigmo: named groups are
|
|
176
205
|
native, `[^]` and `\cX` are translated, `^`/`$` become `\A`/`\z` (Ruby's are line anchors,
|
|
177
206
|
JS's are not), `\d`/`\w`/`\b` are ASCII as in JS; a spelling Ruby still rejects never matches
|
|
@@ -183,14 +212,14 @@ match differently here than at the edge: that is an Onigmo engine difference.
|
|
|
183
212
|
|
|
184
213
|
## Deploying it
|
|
185
214
|
|
|
186
|
-
- Every worker process polls its own snapshot (about 5 MB resident, read a word at a time
|
|
215
|
+
- Every worker process polls its own snapshot (about 5 MB resident, read a word at a time, never
|
|
187
216
|
expanded into Ruby Integers) and flushes its own batches; the tenant's `poll_seconds` keeps the
|
|
188
217
|
cadence honest across a fleet.
|
|
189
218
|
- Threads do not survive a fork. Ruby has no fork hook, so the SDK compares `Process.pid` on every
|
|
190
219
|
call and starts over in a forked worker: new locks, an empty queue, its poll and flush threads
|
|
191
220
|
restarted. Puma cluster mode with `preload_app!`, Unicorn and Passenger need nothing added.
|
|
192
221
|
- Pending events drain at interpreter exit within half a second (`at_exit`). No signal handlers
|
|
193
|
-
are installed
|
|
222
|
+
are installed (an app owns its own shutdown), so a worker killed by SIGKILL, or by SIGTERM
|
|
194
223
|
without a handler, may drop its last batch.
|
|
195
224
|
- Serverless: `CAMADA_SERVERLESS=1`. A cold invocation fails open and catches up on the next one.
|
|
196
225
|
- The middleware writes lower-case header names; it appends `set-cookie` as an Array under Rack 3
|
|
@@ -213,12 +242,16 @@ bundle install && bundle exec rubocop && bundle exec rspec
|
|
|
213
242
|
No type checker: the gem has no runtime dependencies and a Sorbet or Steep setup would add a
|
|
214
243
|
toolchain (and RBS signatures for every stdlib seam) for a 2.5k-line port whose behaviour is
|
|
215
244
|
pinned by the golden fixtures instead; it is deferred, not refused. A Rails example app is
|
|
216
|
-
deferred the same way
|
|
245
|
+
deferred the same way: the Railtie ships in the gem, and the example repo is Sinatra.
|
|
217
246
|
|
|
218
247
|
The suite reads the golden snapshot fixtures from the `camada-core` sibling checkout and pins the
|
|
219
|
-
vendored beacon to `camada-browser/dist/auto.global.js` (
|
|
220
|
-
`ruby scripts/sync_beacon.rb`
|
|
221
|
-
|
|
248
|
+
vendored beacon to `camada-browser/dist/auto.global.js` (check out the release tag, run `npm run
|
|
249
|
+
build` there, then `ruby scripts/sync_beacon.rb`). Both fail by name when the checkout is missing
|
|
250
|
+
rather than skipping (`CAMADA_FIXTURES_DIR`, `CAMADA_BROWSER_DIST` override the paths). CI checks
|
|
251
|
+
out `camada-core` at the commit pinned by `ref:` in `.github/workflows/ci.yml`, so a fixture
|
|
252
|
+
change on camada-core main cannot turn this CI red; local runs use the sibling checkout as it is.
|
|
253
|
+
To take new fixtures, push them to camada-core main first, then set `ref:` to that commit's full
|
|
254
|
+
SHA in the same commit as the SDK change.
|
|
222
255
|
|
|
223
256
|
[`camada-ruby-example`](https://github.com/camada-app/camada-ruby-example) is the hand-test bench (Sinatra under Puma on
|
|
224
257
|
:3004), and `node scripts/e2e-sdk-ruby.mjs` in `camada/edge-analyst` drives it against a seeded
|
data/lib/camada/beacon_js.rb
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
# dist/auto.global.js) vendored as a String literal: served at /_cam/b.js with no runtime file
|
|
5
5
|
# read. spec/beacon_js_spec.rb pins it to the sibling build byte for byte.
|
|
6
6
|
module Camada
|
|
7
|
-
BEACON_VERSION = "0.
|
|
8
|
-
BEACON_SHA256 = "
|
|
9
|
-
BEACON_JS = "\"use strict\";(()=>{var
|
|
7
|
+
BEACON_VERSION = "0.5.0"
|
|
8
|
+
BEACON_SHA256 = "587367f83327fd63699174ad9080460ccb08d75f90b4f45f4edaad6cb07387f9"
|
|
9
|
+
BEACON_JS = "\"use strict\";(()=>{var b=\"0.5.0\";var k=\"@camada/browser\";var _=`${k}/${b}`;function x(n){return n.top!==n?1:0}function e(n){try{return n()}catch{return null}}function T(n){let t=2166136261;for(let i=0;i<n.length;i++)t^=n.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(16)}function R(){let n=document.createElement(\"canvas\");n.width=240,n.height=60;let t=n.getContext(\"2d\");return t?(t.textBaseline=\"alphabetic\",t.fillStyle=\"#f60\",t.fillRect(120,5,60,20),t.fillStyle=\"#069\",t.font=\"15px Arial\",t.fillText(\"Sfp\\u2603 1.0\",2,15),t.fillStyle=\"rgba(102,204,0,0.7)\",t.font=\"17px Times\",t.fillText(\"Sfp\\u2603 1.0\",4,45),T(n.toDataURL())):null}function S(){let n=document.createElement(\"canvas\"),t=n.getContext(\"webgl\")||n.getContext(\"experimental-webgl\");if(!t)return null;let i=t.getExtension(\"WEBGL_debug_renderer_info\");return{v:i?t.getParameter(i.UNMASKED_VENDOR_WEBGL):t.getParameter(t.VENDOR),r:i?t.getParameter(i.UNMASKED_RENDERER_WEBGL):t.getParameter(t.RENDERER)}}function N(){return T([Math.tan(-1e300),Math.sinh(1),Math.expm1(1),Math.cbrt(100),Math.log1p(10),Math.atanh(.5)].join(\"|\"))}var L=/^\\$?cdc_|^__webdriver|^__selenium|^__nightmare|^__playwright|^callPhantom/,j=/^\\$?cdc_|^__webdriver|^__selenium|^__nightmare|^__playwright|^callPhantom|^_phantom/;function O(){let n=document,t=navigator,i=window,o=0;for(let s in n)L.test(s)&&o++;for(let s in i)j.test(s)&&o++;return{wd:t.webdriver===!0?1:0,cdc:o,chrome:typeof i.chrome<\"u\"?1:0,plugins:t.plugins?t.plugins.length:-1,langs:t.languages?t.languages.length:-1,outer:window.outerWidth===0&&window.outerHeight===0?1:0,perm:e(()=>Notification.permission),pdf:typeof t.pdfViewerEnabled==\"boolean\"?t.pdfViewerEnabled?1:0:-1,err:e(()=>{try{null.x}catch(s){let c=s.stack;return c?c.split(`\n`).length:0}})}}function D({endpoint:n,rid:t}){let i=t||null,o=performance.now(),s=0,c=0,m=0,f=0,h=0,u=null;function d(){u===null&&(u=Math.round(performance.now()-o))}addEventListener(\"mousemove\",()=>{s++,d()},{passive:!0}),addEventListener(\"scroll\",()=>{c++,d()},{passive:!0}),addEventListener(\"keydown\",()=>{m++,d()},{passive:!0}),addEventListener(\"touchstart\",()=>{f++,d()},{passive:!0}),addEventListener(\"click\",()=>{h++,d()},{passive:!0});function w(){let r=navigator,a=e(()=>performance.getEntriesByType(\"navigation\")[0]),M=e(()=>{let g=performance.getEntriesByType(\"paint\");return g.length?Math.round(g[g.length-1].startTime):null}),l=e(()=>r.connection)||{};return{sdk:_,rid:i,ts:Date.now(),scr:e(()=>[screen.width,screen.height,screen.availWidth,screen.availHeight,screen.colorDepth]),win:e(()=>[window.innerWidth,window.innerHeight,window.outerWidth,window.outerHeight]),dpr:e(()=>window.devicePixelRatio),tz:e(()=>Intl.DateTimeFormat().resolvedOptions().timeZone),tzo:e(()=>new Date().getTimezoneOffset()),lang:e(()=>r.language),langs:e(()=>r.languages?Array.prototype.slice.call(r.languages,0,5):null),plat:e(()=>r.platform),cores:e(()=>r.hardwareConcurrency),mem:e(()=>r.deviceMemory),touch:e(()=>r.maxTouchPoints),ua:e(()=>r.userAgent),dnt:e(()=>r.doNotTrack),cookies:e(()=>r.cookieEnabled?1:0),conn:e(()=>[l.effectiveType,l.rtt,l.downlink,l.saveData?1:0]),gl:e(S),cv:e(R),mf:e(N),auto:e(O),vis:e(()=>document.visibilityState),focus:e(()=>document.hasFocus()?1:0),timing:a?[Math.round(a.domContentLoadedEventEnd),Math.round(a.loadEventEnd),Math.round(a.responseEnd-a.requestStart)]:null,paint:M,fr:e(()=>x(window)),input:{moves:s,scrolls:c,keys:m,touches:f,clicks:h,first:u,at:Math.round(performance.now()-o)}}}function v(r){let a=JSON.stringify(r?Object.assign(w(),{hi:r}):w());navigator.sendBeacon&&navigator.sendBeacon(n,new Blob([a],{type:\"application/json\"}))||fetch(n,{method:\"POST\",body:a,keepalive:!0,headers:{\"content-type\":\"application/json\"}}).catch(()=>{})}let p=navigator.userAgentData,y=p&&p.getHighEntropyValues?p.getHighEntropyValues([\"architecture\",\"bitness\",\"model\",\"platformVersion\",\"fullVersionList\"]).catch(()=>null):Promise.resolve(null);setTimeout(()=>{y.then(v)},2e3),addEventListener(\"pagehide\",()=>{y.then(r=>{v(r)})},{once:!0})}function P(n){let t=new URL(n,\"http://_\"),i=t.pathname.split(\"/\");return i[i.length-1]=\"fp\",{endpoint:i.join(\"/\"),rid:t.searchParams.get(\"r\")}}(function(){try{let n=document.currentScript,t=n&&n.src;if(!t)return;let{endpoint:i,rid:o}=P(t);D({endpoint:i,rid:o})}catch{}})();})();\n"
|
|
10
10
|
end
|
data/lib/camada/config.rb
CHANGED
|
@@ -7,6 +7,23 @@ module Camada
|
|
|
7
7
|
# as JSON delivers them. A trusted-proxy config mirrors the server-validated tenant config
|
|
8
8
|
# (edge-analyst src/tenant-config.js): {mode: none} | {mode: hops, hops: N} | {mode: cidrs, cidrs: [...]} | {mode: vercel}.
|
|
9
9
|
module Config
|
|
10
|
+
def self.token_hash_enabled?(option, env_value)
|
|
11
|
+
option.nil? ? env_value == "1" : option == true
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Returns [header name, invalid setting?] so the caller can warn without logging the input.
|
|
15
|
+
def self.resolve_token_header(option, env_value)
|
|
16
|
+
selected = option.nil? || option == "" ? env_value : option
|
|
17
|
+
return [nil, false] if selected.nil? || selected == ""
|
|
18
|
+
return [nil, true] unless selected.is_a?(String)
|
|
19
|
+
|
|
20
|
+
name = selected.b.downcase(:ascii)
|
|
21
|
+
return [nil, true] unless /\A[a-z0-9-]{1,64}\z/.match?(name)
|
|
22
|
+
return [nil, true] if %w[authorization cookie set-cookie].include?(name)
|
|
23
|
+
|
|
24
|
+
[name, false]
|
|
25
|
+
end
|
|
26
|
+
|
|
10
27
|
# CAMADA_KEY is `<ingest_token>.<snap_token>` (printed by reconcile instructions and seed).
|
|
11
28
|
def self.parse_key(key)
|
|
12
29
|
return nil if key.nil? || key.empty?
|
data/lib/camada/constants.rb
CHANGED
|
@@ -21,7 +21,7 @@ module Camada
|
|
|
21
21
|
BODY_MAX = 4 * 1024 # the verify form is ~120 bytes; anything larger is not ours
|
|
22
22
|
# Row keys only the SDK can attest (TLS/network facts, outcome, session, track()). A beacon body is the
|
|
23
23
|
# visitor's, so these never ride a sig:1 row; the analyst joins them from the beacon's request row.
|
|
24
|
-
REQUEST_ROW_KEYS = %w[tlsx ja4 asn cc sid ns st dur rt blk rl wrn chs ch et uid].freeze
|
|
24
|
+
REQUEST_ROW_KEYS = %w[tlsx ja4 asn cc sid ns st dur rt blk rl wrn chs ch et uid tk bf upf].freeze
|
|
25
25
|
|
|
26
26
|
SESSION_COOKIE = "_sfp" # same cookie as the edge collector: sid/ns comparable across taps
|
|
27
27
|
SESSION_MAX_AGE = 2_592_000 # 30 days
|
data/lib/camada/engine.rb
CHANGED
|
@@ -90,7 +90,8 @@ module Camada
|
|
|
90
90
|
attr_reader :env, :snap, :queue, :kit, :script_path, :fp_path, :challenge_path, :challenge_on
|
|
91
91
|
|
|
92
92
|
def initialize(env: ENV, transport: nil, refresh_s: nil, script_path: SCRIPT_PATH, fp_path: FP_PATH,
|
|
93
|
-
challenge: true, challenge_path: CHALLENGE_PATH, snapshot_version: DEFAULT_SNAPSHOT_VERSION
|
|
93
|
+
challenge: true, challenge_path: CHALLENGE_PATH, snapshot_version: DEFAULT_SNAPSHOT_VERSION,
|
|
94
|
+
token_hash: nil, token_header: nil)
|
|
94
95
|
# env: where CAMADA_* are read from (ENV, or a Hash); transport: threaded into the snapshot
|
|
95
96
|
# client and event queue (tests); refresh_s: pinned poll cadence; challenge: enforce
|
|
96
97
|
# `challenge` verdicts with the first-party page (CAMADA_CHALLENGE=0 also off).
|
|
@@ -105,6 +106,13 @@ module Camada
|
|
|
105
106
|
@kit = nil
|
|
106
107
|
return if @env.nil? || env[KILL_SWITCH_ENV] == "1" # unconfigured or killed at boot: no threads, no exit hooks, truly silent
|
|
107
108
|
|
|
109
|
+
header, invalid_header = Config.resolve_token_header(token_header, env["CAMADA_TOKEN_HEADER"])
|
|
110
|
+
Guarded.warn_rate_limited("invalid or forbidden token header name") if invalid_header
|
|
111
|
+
if Config.token_hash_enabled?(token_hash, env["CAMADA_TOKEN_HASH"])
|
|
112
|
+
ingest_token = @env.ingest_token
|
|
113
|
+
@token_config = Events::TokenConfig.new(header: header, hasher: ->(credential) { Redact.hash_token(credential, ingest_token) })
|
|
114
|
+
end
|
|
115
|
+
|
|
108
116
|
@snap = Snapshot::Client.new(
|
|
109
117
|
@env.snapshot_url, @env.snap_token, refresh_s: refresh_s, mode: @env.serverless ? :lazy : :timer,
|
|
110
118
|
transport: transport, sdk: SDK_ID, snapshot_version: snapshot_version
|
|
@@ -304,7 +312,7 @@ module Camada
|
|
|
304
312
|
def event(req, rid, sid, new_session, ip)
|
|
305
313
|
info = Events::RequestInfo.new(method: req.method, host: req.host, path: req.path, query: req.query, headers: req.headers,
|
|
306
314
|
ip: ip, http_version: req.http_version)
|
|
307
|
-
Events.build_wire_event(info, tap: TAP, rid: rid, sid: sid, new_session: new_session)
|
|
315
|
+
Events.build_wire_event(info, tap: TAP, rid: rid, sid: sid, new_session: new_session, token_config: @token_config)
|
|
308
316
|
end
|
|
309
317
|
|
|
310
318
|
# ---- beacon ----
|
|
@@ -380,7 +388,7 @@ module Camada
|
|
|
380
388
|
|
|
381
389
|
def self.create_engine(**opts)
|
|
382
390
|
e = Engine.new(**opts)
|
|
383
|
-
Guarded.
|
|
391
|
+
Guarded.warn_rate_limited("CAMADA_KEY (or CAMADA_TOKEN + CAMADA_SNAPSHOT_TOKEN) not set — camada is inactive") if e.env.nil?
|
|
384
392
|
e
|
|
385
393
|
end
|
|
386
394
|
end
|
data/lib/camada/events/build.rb
CHANGED
|
@@ -15,10 +15,6 @@ module Camada
|
|
|
15
15
|
].freeze
|
|
16
16
|
HDR_BIT = HDRS.each_with_index.to_h { |name, i| [name, 1 << i] }.freeze
|
|
17
17
|
|
|
18
|
-
# A schemeless header (`Authorization: <raw token>`) has no safe prefix: the first "word" IS
|
|
19
|
-
# the credential. Only a real auth-scheme token followed by a space ever ships.
|
|
20
|
-
SCHEME_RE = /\A[A-Za-z0-9!#$%&'*+.^_`|~-]{1,16}\z/
|
|
21
|
-
|
|
22
18
|
RequestInfo = Struct.new(
|
|
23
19
|
:method, :host, :path,
|
|
24
20
|
:query, # includes the leading '?', or empty
|
|
@@ -27,28 +23,21 @@ module Camada
|
|
|
27
23
|
:http_version, # e.g. '1.1'
|
|
28
24
|
keyword_init: true
|
|
29
25
|
)
|
|
26
|
+
TokenConfig = Struct.new(:header, :hasher, keyword_init: true)
|
|
30
27
|
|
|
31
|
-
def self.auth_scheme(value)
|
|
32
|
-
return nil if value.nil? || value.empty?
|
|
33
|
-
|
|
34
|
-
sp = value.index(" ")
|
|
35
|
-
return nil if sp.nil? || sp <= 0
|
|
36
|
-
|
|
37
|
-
scheme = value[0, sp]
|
|
38
|
-
SCHEME_RE.match?(scheme) ? scheme : nil
|
|
39
|
-
end
|
|
28
|
+
def self.auth_scheme(value) = Redact.auth_scheme(value)
|
|
40
29
|
|
|
41
30
|
def self.now_ms = Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
|
|
42
31
|
|
|
43
32
|
# The mutable wire event (string keys, ready for JSON); the caller fills st/dur on
|
|
44
33
|
# response-finish before enqueueing.
|
|
45
|
-
def self.build_wire_event(r, tap:, rid:, sid: nil, new_session: false, ja4: nil)
|
|
34
|
+
def self.build_wire_event(r, tap:, rid:, sid: nil, new_session: false, ja4: nil, token_config: nil)
|
|
46
35
|
mask = hn = hb = 0
|
|
47
36
|
cookie = +""
|
|
48
37
|
names = []
|
|
49
38
|
first = {}
|
|
50
39
|
(r.headers || []).each do |name, value|
|
|
51
|
-
k = name.downcase
|
|
40
|
+
k = name.downcase(:ascii)
|
|
52
41
|
hn += 1
|
|
53
42
|
hb += name.bytesize + value.bytesize # bytes on the wire, as the collector and the WSGI (latin-1) port count them
|
|
54
43
|
names << k
|
|
@@ -58,11 +47,13 @@ module Camada
|
|
|
58
47
|
end
|
|
59
48
|
query = r.query || ""
|
|
60
49
|
qn = query.length > 1 ? query[1..].split("&").count { |p| !p.empty? } : 0
|
|
50
|
+
tk = token_hash(first, token_config) if token_config
|
|
61
51
|
ev = {
|
|
62
52
|
"tap" => tap, "rid" => rid, "sid" => sid, "ns" => new_session ? 1 : 0, "ts" => now_ms,
|
|
63
53
|
"ip" => r.ip,
|
|
64
54
|
"proto" => r.http_version ? "HTTP/#{r.http_version}" : nil,
|
|
65
|
-
"m" => r.method, "h" => r.host,
|
|
55
|
+
"m" => r.method, "h" => r.host,
|
|
56
|
+
"p" => r.path, "q" => Redact.scrub_query(query)[0, 512], "qn" => qn,
|
|
66
57
|
"ct" => first["content-type"], "cl" => first["content-length"],
|
|
67
58
|
"ua" => first["user-agent"], "chua" => first["sec-ch-ua"],
|
|
68
59
|
"chmob" => first["sec-ch-ua-mobile"], "chplat" => first["sec-ch-ua-platform"],
|
|
@@ -75,9 +66,18 @@ module Camada
|
|
|
75
66
|
"hord" => names.join(",")[0, 2048] # header order as this host reports it (the env's order under Rack)
|
|
76
67
|
}
|
|
77
68
|
ev["ja4"] = ja4 if ja4
|
|
69
|
+
ev["tk"] = tk if tk
|
|
78
70
|
ev["st"] = nil
|
|
79
71
|
ev["dur"] = nil # 'dur': the collector wire already claims 'lat' for latitude
|
|
80
72
|
ev
|
|
81
73
|
end
|
|
74
|
+
|
|
75
|
+
def self.token_hash(first, token_config)
|
|
76
|
+
credential = Redact.select_credential(first, token_config.header)
|
|
77
|
+
token_config.hasher.call(credential) if credential
|
|
78
|
+
rescue StandardError, NotImplementedError
|
|
79
|
+
nil # Keep the row and enforcement decision even if hashing fails.
|
|
80
|
+
end
|
|
81
|
+
private_class_method :token_hash
|
|
82
82
|
end
|
|
83
83
|
end
|
data/lib/camada/guarded.rb
CHANGED
|
@@ -5,6 +5,7 @@ module Camada
|
|
|
5
5
|
# the SDK catches, falls back, and reports through log_rate_limited: at most one line a minute.
|
|
6
6
|
module Guarded
|
|
7
7
|
@last_log = nil # monotonic seconds of the last line; nil until the first one
|
|
8
|
+
@last_warn = nil
|
|
8
9
|
@logger = nil
|
|
9
10
|
|
|
10
11
|
class << self
|
|
@@ -18,14 +19,27 @@ module Camada
|
|
|
18
19
|
return if @last_log && now - @last_log < 60
|
|
19
20
|
|
|
20
21
|
@last_log = now
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
write_line("[camada] suppressed error (SDK fails open): #{describe(err)}")
|
|
23
|
+
rescue StandardError
|
|
24
|
+
nil # even logging must not raise
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def warn_rate_limited(msg)
|
|
28
|
+
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
29
|
+
return if @last_warn && now - @last_warn < 60
|
|
30
|
+
|
|
31
|
+
@last_warn = now
|
|
32
|
+
write_line("[camada] config warning: #{msg}")
|
|
23
33
|
rescue StandardError
|
|
24
34
|
nil # even logging must not raise
|
|
25
35
|
end
|
|
26
36
|
|
|
27
37
|
private
|
|
28
38
|
|
|
39
|
+
def write_line(line)
|
|
40
|
+
(@logger || ->(s) { warn(s) }).call(line)
|
|
41
|
+
end
|
|
42
|
+
|
|
29
43
|
# Exceptions print as "Class: message" on one line — never a backtrace, and never the
|
|
30
44
|
# "(ClassName)" spelling an uncaught Ruby exception uses, so a crash grep stays quiet.
|
|
31
45
|
def describe(err)
|
data/lib/camada/rack.rb
CHANGED
|
@@ -21,9 +21,9 @@ module Camada
|
|
|
21
21
|
headers = []
|
|
22
22
|
env.each do |k, v|
|
|
23
23
|
if k.start_with?("HTTP_")
|
|
24
|
-
headers << [k[5..].downcase.tr("_", "-"), utf8(v)]
|
|
24
|
+
headers << [k[5..].downcase(:ascii).tr("_", "-"), utf8(v)]
|
|
25
25
|
elsif (k == "CONTENT_TYPE" || k == "CONTENT_LENGTH") && v && !v.to_s.empty?
|
|
26
|
-
headers << [k.downcase.tr("_", "-"), utf8(v)]
|
|
26
|
+
headers << [k.downcase(:ascii).tr("_", "-"), utf8(v)]
|
|
27
27
|
end
|
|
28
28
|
end
|
|
29
29
|
query = utf8(env["QUERY_STRING"])
|
data/lib/camada/redact.rb
CHANGED
|
@@ -18,6 +18,7 @@ module Camada
|
|
|
18
18
|
HEX_RE = /\A[a-fA-F0-9]{32,}\z/n
|
|
19
19
|
B64_RE = %r{\A[A-Za-z0-9+/_-]{40,}={0,2}\z}n
|
|
20
20
|
ESC_RE = /%([0-9a-fA-F]{2})/n
|
|
21
|
+
SCHEME_RE = /\A[A-Za-z0-9!#$%&'*+.^_`|~-]{1,16}\z/
|
|
21
22
|
|
|
22
23
|
REDACT_ALLOWLIST = %w[plan role locale ab_variant].freeze # additions only, never narrowing
|
|
23
24
|
|
|
@@ -119,7 +120,41 @@ module Camada
|
|
|
119
120
|
# Stable per-tenant pseudonym: HMAC-SHA256 keyed by the ingest token, labelled so the hash
|
|
120
121
|
# can never double as anything else, truncated to 32 hex chars. The raw identifier never leaves.
|
|
121
122
|
def self.hash_user_id(user_id, ingest_token)
|
|
122
|
-
|
|
123
|
+
hash_labeled("uid", user_id, ingest_token)
|
|
123
124
|
end
|
|
125
|
+
|
|
126
|
+
# Only a valid auth-scheme token followed by a space is safe to ship.
|
|
127
|
+
def self.auth_scheme(value)
|
|
128
|
+
return nil if value.nil? || value.empty?
|
|
129
|
+
|
|
130
|
+
sp = value.index(" ")
|
|
131
|
+
return nil if sp.nil? || sp <= 0
|
|
132
|
+
|
|
133
|
+
scheme = value[0, sp]
|
|
134
|
+
SCHEME_RE.match?(scheme) ? scheme : nil
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def self.credential(value, scheme_split)
|
|
138
|
+
return nil if value.nil?
|
|
139
|
+
|
|
140
|
+
value = value.b.gsub(/\A[ \t]+|[ \t]+\z/, "")
|
|
141
|
+
scheme = auth_scheme(value) if scheme_split
|
|
142
|
+
value = value[(scheme.length + 1)..].sub(/\A[ \t]+/, "") if scheme
|
|
143
|
+
value if /\A[\x20-\x7e]{8,}\z/n.match?(value)
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
def self.select_credential(first, token_header)
|
|
147
|
+
extra = credential(first[token_header], false) if token_header
|
|
148
|
+
extra || credential(first["authorization"], true)
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def self.hash_token(credential, ingest_token)
|
|
152
|
+
hash_labeled("tok", credential, ingest_token.encode(Encoding::UTF_8))
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def self.hash_labeled(label, value, key)
|
|
156
|
+
OpenSSL::HMAC.hexdigest("SHA256", key, "#{label}:#{value}")[0, 32]
|
|
157
|
+
end
|
|
158
|
+
private_class_method :hash_labeled
|
|
124
159
|
end
|
|
125
160
|
end
|
data/lib/camada/version.rb
CHANGED
|
@@ -6,6 +6,6 @@ module Camada
|
|
|
6
6
|
# camada-web, camada-mkt) parse this file with /^\s*VERSION = "([^"]+)"/m the way they parse
|
|
7
7
|
# a package.json. Plain X.Y.Z only, and @camada/ruby must stay in the analyst's SDK_NAMES:
|
|
8
8
|
# its sdkId drops anything else.
|
|
9
|
-
VERSION = "0.
|
|
9
|
+
VERSION = "0.3.0"
|
|
10
10
|
SDK_ID = "@camada/ruby/#{VERSION}".freeze
|
|
11
11
|
end
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: camada
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.3.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- camada
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-
|
|
11
|
+
date: 2026-11-24 00:00:00.000000000 Z
|
|
12
12
|
dependencies: []
|
|
13
13
|
description: 'camada SDK for Ruby: inline enforcement of your snapshot (ordered custom
|
|
14
14
|
rules, then allow, block, challenge), first-party beacon and proof-of-work challenge,
|
|
@@ -44,13 +44,16 @@ files:
|
|
|
44
44
|
- lib/camada/snapshot/parse.rb
|
|
45
45
|
- lib/camada/transport.rb
|
|
46
46
|
- lib/camada/version.rb
|
|
47
|
-
homepage: https://
|
|
47
|
+
homepage: https://www.camada.app/docs/ruby
|
|
48
48
|
licenses:
|
|
49
49
|
- MIT
|
|
50
50
|
metadata:
|
|
51
51
|
rubygems_mfa_required: 'true'
|
|
52
|
-
homepage_uri: https://
|
|
52
|
+
homepage_uri: https://www.camada.app/docs/ruby
|
|
53
|
+
documentation_uri: https://www.camada.app/docs
|
|
53
54
|
source_code_uri: https://github.com/camada-app/camada-ruby
|
|
55
|
+
bug_tracker_uri: https://github.com/camada-app/camada-ruby/issues
|
|
56
|
+
changelog_uri: https://github.com/camada-app/camada-ruby/blob/main/CHANGELOG.md
|
|
54
57
|
post_install_message:
|
|
55
58
|
rdoc_options: []
|
|
56
59
|
require_paths:
|