Ruby SDK#
The public API of sdks/ruby, with its doc comments. Guide: docs/sdk/ruby.md.
325 public declarations, 239 with a doc comment.
lib/allowedby/capabilities.rb#
sdks/ruby/lib/allowedby/capabilities.rb
module CapabilitiesABY-3: capabilities, constraints, route matching, the display a person signs. Ported from the Python reference (sdks/python/src/allowedby/verifier.py, core.py) with the same results.
AllowedBy::Capabilities::CLASS_MAXABY-1 §2: the longest a grant of each class may last.
def match_route(routes, method, path) # AllowedBy::CapabilitiesThe route of the map for a method and a normalised path, with its path parameters, or [nil, nil].
def top_class(route) # AllowedBy::CapabilitiesThe most serious class a route can have (a route classed by amount: its last threshold).
def resolve_class(route, body) # AllowedBy::CapabilitiesABY-3 §4, §4.1: a route classed by amount takes its class from the request before anything that depends on the class. No readable amount: the last, most serious class.
def resource_of(route, params) # AllowedBy::Capabilitiesdef seg_match(pat, ids) # AllowedBy::Capabilitiesdef scope_ok(pattern, resource) # AllowedBy::Capabilitiesdef scope_within(outer, inner) # AllowedBy::CapabilitiesEvery resource the pattern inner names is named by outer: ** only within **, * within * or **.
def zone_ok(tz) # AllowedBy::CapabilitiesTime zones: this SDK keeps to the standard library, which has no IANA database, so only UTC is known. A constraint naming another zone never matches (fail closed, as the Python SDK does for a zone it lacks).
def constraints_ok(cons) # AllowedBy::CapabilitiesABY-3 §2 grammar for constraint values that end up in the text the person signs.
def in_window(window, time) # AllowedBy::CapabilitiesABY-3 §2 window: time t is in [from, to) (a window may wrap midnight, e.g. 22:00-06:00).
def period(per, time) # AllowedBy::CapabilitiesThe calendar period holding time t (UTC): day, ISO week, month; and when it ends.
def satisfies(cap, route, body, resource, gid, now) # AllowedBy::CapabilitiesABY-3 §3: does this capability cover this request? -> the counter charges [key, increment, max, keep_until] when it does (count and cumulative amounts, kept under the root gid), else nil.
def field_ok(fields, ptr) # AllowedBy::CapabilitiesA body member a fields constraint allows: one of the fields, or inside one.
def attenuates(child, parent) # AllowedBy::CapabilitiesABY-3 §3: a child capability is equal to or narrower than its parent (ABY-1 §4).
def narrower(name, child, parent) # AllowedBy::Capabilitiesdef window_within(child, parent) # AllowedBy::Capabilitiesdef render_display(caps, lang, templates) # AllowedBy::CapabilitiesAMH-1 §4 / ABY-3 §5: the only source of the text the person signs. Raises ArgumentError.
def render_one(template, cons) # AllowedBy::Capabilitieslib/allowedby/crypto.rb#
sdks/ruby/lib/allowedby/crypto.rb
module CryptoKeys and signatures with the OpenSSL standard library: Ed25519 (EdDSA) and P-256 (ES256) for JWS, plus the WebAuthn encodings of passkey signatures (DER ES256, Ed25519, RSA PKCS#1 v1.5).
AllowedBy::Crypto::JWS_ALGSOAID-1 §3.1: the only JWS algorithms. alg "none", RS256, HS256 and anything else are refused.
def alg_for(jwk) # AllowedBy::Cryptodef thumbprint(jwk) # AllowedBy::CryptoRFC 7638 thumbprint, the kid of every key in AllowedBy. Raises ArgumentError.
def public_key(jwk) # AllowedBy::CryptoAn OpenSSL public key from a JWK: Ed25519, P-256, or RSA (passkeys only). Raises ArgumentError.
def fixed(b64, size) # AllowedBy::Cryptodef rsa_spki(jwk) # AllowedBy::Cryptodef verify_raw(alg, jwk, data, sig) # AllowedBy::CryptoA JWS signature check, algorithm pinned to the key: EdDSA for Ed25519, ES256 (raw r||s, 64 bytes) for P-256. Never raises; false for anything else.
def webauthn_ok(jwk, auth_data, cdj, sig) # AllowedBy::CryptoWebAuthn signature over authenticatorData || SHA-256(clientDataJSON), in the passkey's own encoding (DER for ES256, ABY-1 §3.3). Never raises.
def raw_to_der(sig) # AllowedBy::Cryptodef der_to_raw(der) # AllowedBy::Cryptodef p256_from_scalar(d_bytes) # AllowedBy::CryptoA P-256 private key from its 32-byte scalar (test vectors and JWK d).
def public_jwk(pkey) # AllowedBy::CryptoThe public JWK of an OpenSSL key (Ed25519 or P-256), without kid.
class KeyA signing key: Ed25519 (EdDSA, the default) or P-256 (ES256). Its private part never appears in #inspect.
attr_reader :alg, :kid, :jwk # AllowedBy::Keydef self.generate(kind = "Ed25519") # AllowedBy::Keydef self.from_pem(pem) # AllowedBy::Keydef self.from_ed25519_seed(seed) # AllowedBy::Keydef initialize(pkey) # AllowedBy::Keydef sign(data) # AllowedBy::Keydef derive(info) # AllowedBy::KeyA key derived from this one for one use, named by info: HKDF-SHA256 (RFC 5869) of the raw private key
(Ed25519: its 32-byte seed; P-256: its scalar, 32 bytes big-endian, so no key encoding changes it), no salt
(32 zero bytes), 32 bytes. The nonce key (sdks/CONTRACT.md, Extended: AllowedBy-Nonce). The Ed25519 seed is read
from the key's PKCS#8 form (RFC 8410: the fixed prefix, then the seed): Ruby 3.2's openssl has no raw_private_key.
def to_pem # AllowedBy::KeyPKCS#8 PEM, the key file format shared with the Python SDK (load_keys).
def inspect # AllowedBy::Keymodule JWSCompact JWS (RFC 7515) with JCS header and payload, as every AllowedBy document.
def sign(key, typ, payload, extra = {}) # AllowedBy::JWSdef parse(token) # AllowedBy::JWS[header, payload, signing input bytes, signature bytes]. Raises ArgumentError.
def payload(token) # AllowedBy::JWSmodule JWEJWE compact serialization, ECDH-ES+A256KW with A256GCM (OAID-7 §7): what a node encrypts personal data to the service's disclosure key with.
def encrypt(jwk, plaintext) # AllowedBy::JWEdef decrypt(pkey, token) # AllowedBy::JWEThe plaintext bytes. Raises ArgumentError for any malformed or forged token.
def concat_kdf(shared) # AllowedBy::JWENIST SP 800-56A Concat KDF, one SHA-256 round (RFC 7518 §4.6.2; no apu/apv).
def key_wrap(kek, key) # AllowedBy::JWERFC 3394 AES key wrap with a 256-bit KEK.
def key_unwrap(kek, data) # AllowedBy::JWEdef aes_block(kek, block, direction) # AllowedBy::JWEdef xor_t(block, t) # AllowedBy::JWElib/allowedby/grants.rb#
sdks/ruby/lib/allowedby/grants.rb
module GrantsGrant cores, request digests and proofs (ABY-1 §3, ABY-2 §3, §4).
AllowedBy::Grants::CORE_EXCLUDEDABY-1 §3.1: what the human signs is the grant without these members (and actor reduced to who runs it).
def core(grant) # AllowedBy::Grantsdef core_hash(grant) # AllowedBy::Grantsbase64url SHA-256(JCS(core)): the WebAuthn challenge of one grant (ABY-1 §3.2).
def batch_challenge(hashes) # AllowedBy::GrantsABY-1 §3.2 / AMH-1 §11: SHA-256(JCS({"batch": [h1, ..., hn]})).
def request_digest(htm, htu, query, body) # AllowedBy::GrantsABY-1 §7: what a single-use grant is bound to. query: without "?", nil or "" when there is none.
def content_digest(body) # AllowedBy::GrantsRFC 9530 Content-Digest: sha-256 of the content as transmitted.
def make_proof(key, htm, htu, allowed_by: nil, body: nil, iat: Time.now.to_i, extra: {}) # AllowedBy::GrantsABY-2 §3 proof JWT. body: the bytes as transmitted, or nil.
module WebAuthnWebAuthn assertion checks of ABY-1 §3.3 (CHANGES-0.2 §15).
def check(sig, challenge:, origin:, rp_id:, jwk:, type: "webauthn.get") # AllowedBy::WebAuthnsig: {authenticator_data, client_data_json, signature} in base64url. -> nil when valid, else the reason.
lib/allowedby/handlers.rb#
sdks/ruby/lib/allowedby/handlers.rb
class HandlerMapCONTRACT §2.10 rule 5, for an adapter that sees the handler its router chose (the Rails and Sinatra guards): which route of the map each handler serves, and whether a request may run one. A handler is what the router runs (a controller action, a Sinatra block), whatever the method and path that reached it.
AllowedBy::HandlerMap::PROBEA word no route of an app is written with: a sample path with one of its words replaced by it shows a catch-all.
AllowedBy::HandlerMap::AUTHN_RANKHow strong an authenticator a route asks for: none (or software), synced, hardware.
AllowedBy::HandlerMap::SITE_WIDEA rule that takes any path from the root (/*path, a Sinatra /*): a site-wide fallback.
def initialize(service, resolve, declared: [], guarded: [], log: ->(_) {}) # AllowedBy::HandlerMapresolve: -> (method, path) -> [[handler, the rule it matched through], ...] the router may run there. declared: [[route, handler], ...] the router lists as written like a route of the map; guarded: other handlers an unchecked request never runs (a glob written over a route of the map). log: -> (message), told once of each catch-all.
def protected?(handler) # AllowedBy::HandlerMapA handler an unchecked request never runs (on a longer path too: this is what refuses one that reaches a catch-all of a route): a route's own, a glob written over a route, a catch-all under a route's prefix (it can only be another handler of that route), or a site-wide fallback for a route whose own handler is not known (it may be that route's handler). Once a route's own handler is known (a rule of its own shape, a sample, a checked request), a site-wide fallback is not protected for it: it keeps serving other pages.
def handlers # AllowedBy::HandlerMapdef foreign?(handlers, route) # AllowedBy::HandlerMapWhether one of these handlers is protected and not the route's own (nil: no route), or the route's own and also
a handler of another route it does not cover: what a pass may not reach.
def blind_near?(at) # AllowedBy::HandlerMapA route of the map, of any method, that no handler serves (its samples reach none and none was learnt), whose template the path extends: the SDK cannot tell what runs there for it (CONTRACT §2.10 rule 5), refused. at: [method, path or paths] (a mounted app: the path it sees, and with its prefix).
def allow?(chosen, route, own_shape: ->(_) { false }, at: nil) # AllowedBy::HandlerMapWhether a request checked for this route (nil: not checked) may run these handlers (the ones the router may try,
in order). A handler known as the route's own runs (one it shares with other routes, only when this route covers
them all); another route's handler never does. A catch-all for the route runs for it through a rule of the
route's own shape (own_shape: -> (handler) -> bool), and is then that route's own handler; otherwise it is never
learnt, and runs, unrecorded, only while it is the only handler found for the route. Any other handler is learnt
as this
route's when no route owns it and the route covers every other route, of any method, whose handler is not known
(CONTRACT §2.10 rule 5, "covers"). Reading is lock-free; deciding again and recording a learnt handler are one
step under the lock.
An unchecked request (route nil) never runs a protected handler, nor a catch-all for a route whose path it
extends (/admin/anything near a mapped /admin served by a fallback): the router cannot tell which route it
stands for. at: [method, path] of that request.
def self.shape?(template, rule) # AllowedBy::HandlerMapThe route's template has this rule's shape: the same words, a parameter (":name") for each of its parameters.
lib/allowedby/http.rb#
sdks/ruby/lib/allowedby/http.rb
class HTTPThe HTTP client the SDK uses to reach its node (statements, status lists, approvals): Net::HTTP, http(s) only, bounded time and size. Replace it with any object answering #call(method, url, body, headers) -> [status, body] (tests use AllowedBy::Testing::Node).
class Error < StandardErrorAny network failure: refused connection, timeout, TLS, an answer too large.
def initialize(open_timeout: 5, read_timeout: 10) # AllowedBy::HTTPdef call(method, url, body = nil, headers = {}) # AllowedBy::HTTPlib/allowedby/jcs.rb#
sdks/ruby/lib/allowedby/jcs.rb
module JCSRFC 8785 JSON Canonicalization Scheme: the bytes every signature and hash in AllowedBy is computed over.
def dump(value) # AllowedBy::JCSThe canonical JSON text of a value. Raises TypeError for a value JSON cannot hold, ArgumentError for a non-finite number or a string that is not UTF-8.
def bytes(value) # AllowedBy::JCSThe canonical UTF-8 bytes of a value.
def object(hash) # AllowedBy::JCSdef string(str) # AllowedBy::JCSdef utf8(str) # AllowedBy::JCSdef number(value) # AllowedBy::JCSECMAScript Number.prototype.toString for a double (RFC 8785 §3.2.2.3).
lib/allowedby/keys.rb#
sdks/ruby/lib/allowedby/keys.rb
module KeyFileThe service's two keys: the signing key (Ed25519: approval requests, the organisation profile) and the disclosure key (P-256, ECDH-ES+A256KW / A256GCM: personal data is encrypted to it, ORG-1 §4).
def load(path) # AllowedBy::KeyFile[signing Key, disclosure OpenSSL::PKey::EC] from path, created with fresh keys on first use: written once,
atomically, mode 0600, first writer wins, so instances started together all use the keys on disk. The
format is the Python SDK's (sdk.load_keys): {"signing": {"pem"}, "disclosure": {"pem"}}, PKCS#8 PEM.
def create(path) # AllowedBy::KeyFileAllowedBy::KeyFile::NO_LINKSWhat link raises on a file system without hard links (EPERM: Linux FAT mounts; EINVAL: Windows FAT).
def publish(tmp, path, link: File.method(:link)) # AllowedBy::KeyFileGives the complete file its name, or leaves the file another instance created first: one atomic step, never a check then a rename. The caller reads the file on disk in both cases; any other error is raised as it is.
def disclosure_jwk(pkey, kid = "d1") # AllowedBy::KeyFileThe public JWK of the disclosure key, as published in /.well-known/allowedby.
lib/allowedby/link_endpoint.rb#
sdks/ruby/lib/allowedby/link_endpoint.rb
class ServiceAccount linking's part of the service (ABY-3 §6; CONTRACT 1.8, Extended): link_start for the app, POST /allowedby/link for the agent. The codes and the links are kept by AllowedBy::Linking.
def link_start(account, ttl = 600) # AllowedBy::ServiceAccount linking (ABY-3 §6). Your signed-in account page calls this and shows the code: the person gives it to
their agent, which sends it to POST /allowedby/link; their approval (aby:link) then links their identity to
account, and routes with require_link: true accept them. ttl: seconds the code is valid (600 by default).
def unlink(account) # AllowedBy::ServiceABY-3 §6, Removing a link: when you delete the account, or the person asks to be forgotten. The stored pair and the account's pending linking codes go; a require_link route then refuses the person (403 human_not_linked) until they link again with a new code. -> false when the account was not linked (a no-op but for its pending codes). Raises ArgumentError for an account that is not a non-empty String, as link_start does.
def link_path?(method, path) # AllowedBy::ServiceWhether the request is for POST /allowedby/link, the SDK's own route (any spelling of the path).
def link(headers, body, query = nil, mount: "") # AllowedBy::ServicePOST /allowedby/link (ABY-3 §6), which the middleware serves, and check too: the code is checked first,
before any approval is asked for (400 invalid_request); then the request is checked as any route (aby:link,
write, level 1, a single-use grant, the approval created by the service); accepted, the code is spent and the
person linked to its account.
headers: name => value, any case. body: the bytes as received. -> [status, headers, body]
lib/allowedby/linking.rb#
sdks/ruby/lib/allowedby/linking.rb
class LinkingAccount linking (ABY-3 §6; CONTRACT 1.8, Extended): the linking codes of the app's accounts, and the pair (home node, pairwise id) linked to each account. Kept in this process's memory, bounded, thread-safe: several instances behind one origin each keep their own (link on the instance that serves the account page, or keep one).
def initialize(clock, max_codes: MAX_CODES, max_links: MAX_LINKS) # AllowedBy::Linkingclock: -> Integer seconds, the service's own (an injected clock governs expiry too). max_codes, max_links: the bounds (tests set smaller ones).
def start(account, ttl) # AllowedBy::LinkingABY-3 §6 step 1: a new code for the account, unguessable (96 random bits), valid ttl seconds, single use. An older code of the account stays valid until one of them is used. Raises ArgumentError when MAX_CODES codes are pending, none expired (nothing is revoked to make room: ABY-3 §6 step 1).
def pending(code) # AllowedBy::LinkingABY-3 §6 step 3: the account of a pending code, or nil for one that is unknown, spent, revoked, or at or past its issue time plus its lifetime.
def spend(code, iss, hid) # AllowedBy::LinkingABY-3 §6 step 5, in one step: the code is spent, the account's other pending codes are revoked, and the pair is linked to the account in place of any other pair of that account. -> the account, or nil when the code is no longer pending (spent by a request accepted at the same moment).
def linked?(iss, hid, account) # AllowedBy::LinkingWhether the pair is linked, and to account when one is named (nil: the route names none). Both members of the
pair count: the same pairwise id from another home node is another person.
def account_of(iss, hid, account) # AllowedBy::LinkingThe account the pair is linked to, when it is account or the route names none (nil), else nil.
def remove(account) # AllowedBy::LinkingABY-3 §6, Removing a link: the account's pair and its pending codes go, in one step. -> true when it was linked; an account that was not is a no-op (false; its pending codes still go). Raises ArgumentError for an account that is not a non-empty String, as start does.
def pair_of(account) # AllowedBy::LinkingThe pair linked to the account, or nil: the approvals the service creates name it (human_hint, AMH-1 §7).
lib/allowedby/middleware.rb#
sdks/ruby/lib/allowedby/middleware.rb
class MiddlewareRack middleware (Rack 2 and 3): the SDK's endpoints first, then the check on every route of the map, then your app. Paths outside the map reach the app unchanged, body unread. The body of a mapped route is read once and given back to the app intact. The accepted Context is env["allowedby.context"].
use AllowedBy::Middleware, service # config.ru, Sinatra
use AllowedBy::Middleware, -> { service } # resolved on the first request (Rails, forking servers)AllowedBy::Middleware::TARGET_KEYThe method and whole path (SCRIPT_NAME + PATH_INFO, normalised) an accepted request was checked for.
AllowedBy::Middleware::SERVICE_KEYThe service that checked the request: its verifier holds the request's refund state (CONTRACT 1.10).
AllowedBy::Middleware::MOVEDWhat a guard answers for an accepted request moved after the check (the path is never repeated).
AllowedBy::Middleware::REFUNDEDWhat a guard answers for an accepted request that cannot run again: refused already (its approval given back), or answered and forgotten, or past the bound of the refund state (still spent). The detail claims neither.
AllowedBy::Middleware::QUERY_OVERRIDEA _method key of a query (_method=, _method[]=), not a key that ends in it (payment_method=).
AllowedBy::Middleware::OVERRIDE_VERBSThe verbs a request can be overridden to, and the headers that do it.
AllowedBy::Middleware::FORM_TYPEWhat Rack parses as a form: no Content-Type at all, urlencoded, any multipart.
def initialize(app, service, max_body: MAX_BODY, router: nil) # AllowedBy::Middlewarerouter: -> (env, service) -> true when the app's router gives the request to handlers that serve no route of the map (the Railtie passes one; an app that registers AllowedBy::SinatraGuard is found by itself). It then decides for a path longer than a mapped one, which is otherwise refused (CONTRACT §2.10 rule 2).
def call(env) # AllowedBy::Middlewaredef self.target(env) # AllowedBy::MiddlewareThe method and the whole path, normalised (RFC 3986 §6.2.2, as the check), a request has now: a mount that moves a prefix from PATH_INFO to SCRIPT_NAME leaves it as it is (at the mount's root, Rack::URLMap leaves PATH_INFO empty and Rails' router makes it "/"), and so does another spelling of the same path.
def self.checker(env, fallback) # AllowedBy::MiddlewareThe service that checked this request (the one whose refund state it has), or fallback when none did.
def self.moved?(env) # AllowedBy::MiddlewarePlan 14: an accepted request whose method or path is no longer the one checked, changed by a step after the middleware (a rewrite, Rack::MethodOverride): its handler would act on values the person never approved. The Rails and Sinatra guards refuse it, whatever handler the router chose; a plain Rack app is not seen.
lib/allowedby/nonce.rb#
sdks/ruby/lib/allowedby/nonce.rb
class NonceABY-2 §3.2, AllowedBy-Nonce (sdks/CONTRACT.md, Extended): the service's nonces, stateless. A nonce is base64url(t || HMAC-SHA256(key, t)[0:16]), t its issue time in seconds as 8 bytes big-endian. It is current for LIFETIME seconds from its issue on every instance that shares the key file (the key is derived from the signing key), and across a restart.
def self.key_for(key) # AllowedBy::NonceThe nonce key of a signing key (Key#derive): used for nothing else.
def initialize(key) # AllowedBy::Noncekey: 32 bytes (Nonce.key_for).
def issue(now) # AllowedBy::NonceA nonce issued at now.
def current?(value, now) # AllowedBy::NonceWhether value is a nonce of this service issued at most LIFETIME seconds before now, and not after it.
def inspect # AllowedBy::Noncelib/allowedby/rails.rb#
sdks/ruby/lib/allowedby/rails.rb
module ControllerHelpersController helpers. allowedby_context is the accepted Context of this request (nil outside the route map).
before_action :require_allowedby! on the actions of protected routes refuses any request that reached them
without the middleware's check (a path the route map does not name, e.g. another Rails route to the same
action): a second line of defence, fail closed.
def allowedby_context # AllowedBy::ControllerHelpersdef require_allowedby! # AllowedBy::ControllerHelpersmodule ControllerGuardWhich controller actions serve the routes of the map, asked of the Rails router. Such an action never runs without
the middleware's check, whichever path reached it: a glob (/notes/*id), an optional segment, another route or a
mount. A catch-all that serves only unmapped paths is not such an action. An action that serves a mapped and,
on purpose, an unchecked path opts out with skip_before_action :refuse_unchecked_allowedby_action.
AllowedBy::ControllerGuard::BUILDWhich route of the map each action serves (CONTRACT §2.10 rule 5), kept until the routes are drawn again (a reload in development). Read without a lock; built and published under one, checked again inside it: two first requests never learn in two maps.
def self.map(service) # AllowedBy::ControllerGuarddef self.actions(service) # AllowedBy::ControllerGuardThe actions an unchecked request never runs.
def self.clears?(env, service) # AllowedBy::ControllerGuardThe middleware's router: true when Rails gives this longer path to controller actions that serve no route of
the map and that this guard covers. Anything else the routes may run (a Rack endpoint, an engine, a redirect, a
controller without the guard) is not: the request is refused (CONTRACT §2.10 rule 2).
def self.picks(set, env, method, path) # AllowedBy::ControllerGuardWhat Rails may run for a path: [controller, action] of each route up to the first that is sure to match (a route with a lambda constraint may pass to the next one), nil for what is not a controller action.
def self.covers?(pick) # AllowedBy::ControllerGuarddef dispatch(name, request, response) # AllowedBy::ControllerGuardAn action cannot hand a longer path over to the next route (X-Cascade): that one was not looked at.
def self.resolve(method, path) # AllowedBy::ControllerGuardWhat the router answers for a call: [[[controller, action], the rule it matched]], or [] for none.
def self.rule_of(method, path, action) # AllowedBy::ControllerGuardThe rule (its path spec) of the first route of this action that matches the path, "" when none is found.
def self.declared(service) # AllowedBy::ControllerGuardThe routes written like a mapped one (/notes/:id for /notes/{id}), whatever their constraints: no sample
value satisfies every constraint. -> [[route of the map, [controller, action], glob?], ...]
def self.written_like?(tpl, spec) # AllowedBy::ControllerGuardclass Railtie < ::Rails::RailtieRails integration. In config/initializers/allowedby.rb (bin/rails generate allowedby:install writes it):
Rails.application.config.allowedby.service = AllowedBy.new(origin: ..., node: ..., org: ..., routes: [...],
templates: {...})The middleware is added to the stack when the service is set; controllers get allowedby_context and
require_allowedby!.
lib/allowedby/rate.rb#
sdks/ruby/lib/allowedby/rate.rb
class RateLimitRate limits (sdks/CONTRACT.md, Extended): at most n calls per sliding window of s seconds per agent (the passport's
sub) and per operator (operator.id), on the verifier's clock: a call at t sees those at x with t - x < s. Both
limits are checked, then both counted, as one step; a call refused by a limit counts for neither. In this process,
as the Python reference's (core.RateLimit): each server of several counts its own calls. At most MAX_KEYS agents
and as many operators are held, the one seen least recently dropped first.
def self.limits(rate) # AllowedBy::RateLimitThe service option rate, {actor: [n, seconds], operator: [n, seconds]}, each optional, over DEFAULTS. Any other
key, or a value that is not two positive integers, raises ConfigError: a misspelt limit would leave the default.
attr_reader :limits # AllowedBy::RateLimitdef initialize(rate = nil) # AllowedBy::RateLimitdef take(actor, operator, now) # AllowedBy::RateLimitCounts this call for its agent and its operator, or for neither: false when either limit is reached.
lib/allowedby/service.rb#
sdks/ruby/lib/allowedby/service.rb
AllowedBy::EXTENDED_ROUTE_OPTIONSRoute options the Python SDK accepts and this SDK does not enforce yet: accepting one and not enforcing it would fail open, so the configuration is refused (CONTRACT §2).
AllowedBy::ROUTE_KEYSThe members of a route as AllowedBy.route builds it.
AllowedBy::ROUTE_LEVELThe Python SDK's service options that are route options here (CONTRACT §2, Extended: account linking).
AllowedBy::ISO_3166ISO 3166-1 alpha-2 (ORG-1 §2 country)
AllowedBy::TITLESTitles of the problem documents (RFC 9457); the reason, when there is one, is in detail.
def route(method, path, capability = nil, **opts) # AllowedByOne line of the route map (ABY-3 §4.1). level 0: the agent's passport is enough (no person).
AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*")
AllowedBy.route("DELETE", "/notes/{id}", "notes:delete", class: "write-hard", level: 2, resource: "note:{id}")class (or cls): read, write, write-hard, irreversible; or, for payments, amount thresholds [{"up_to" => "1000.00", "class" => "write-hard"}, {"class" => "irreversible"}] read at amount_field. level 0-3; resource: the ABY-3 resource, with {params} from the path (default "<namespace>:*"); amount_field / currency_field: JSON Pointers into the body; authn: synced or hardware passkeys only; tier: the agent's custody tier; max_lifetime: seconds (60 s to 30 days); level_profile: eu or na on level 3; summary and body describe the route to agents (OpenAPI). require_link: the person must have linked their identity to one of your accounts (ABY-3 §6), and to the one the path parameter account_param names when the path has it (default "account"). nonce: the proof must carry a current AllowedBy-Nonce of the service (ABY-2 §3.2), which needs the service's nonces on (every irreversible route asks for one then). Raises ConfigError naming what to fix.
def link_options(where, path, capability, level, opts) # AllowedByABY-3 §6: require_link (true or false) on a route of level 1 or more (at level 0 there is no person, and the verifier never looks further); account_param, a parameter of the path, with it only. -> the members of the route.
def pointer?(value) # AllowedBydef new(**) # AllowedByBuild the service SDK object: AllowedBy.new(origin:, node:, org:, routes:, templates:, ...). See Service.
class ServiceWhat a service embeds: publishes the discovery documents, verifies every request of its route map offline, answers challenges and creates the approval for serious actions (ABY-2 §5, §6). Thread-safe.
AllowedBy::Service::SCOPE_BAD_ESCAPEWhere what routers read apart from a last segment starts: ".json", ";a", "%00"... No pattern that is matched against a path may backtrack: their cost is linear in the length of the path. ABY-2 §6 (0.2.10): an escape in a path value of a challenge's scope that is malformed or decodes to a control character or "/"; and what each value, decoded, must be: an ABY-3 §2 scope segment, so that an approval of the scope can satisfy the route. The whole scope is at most SCOPE_MAX bytes.
AllowedBy::Service::PLAIN_TARGETCONTRACT §2.10 (10): the bytes a request target's path may hold as sent (RFC 3986 pchar, "/" and "%").
attr_reader :origin, :node, :host, :routes, :templates, :key, :verifier, :title, :version # AllowedBy::Servicedef initialize(origin:, node:, org:, routes:, templates:, key_file: nil, store: nil, trust_list: nil, refresh_seconds: 5, node_max_level: 3, clock: nil, title: nil, version: "1.0.0", description: nil, rfc9421: false, logger: nil, http: nil, start: true, unprotected: [], link_authorize: nil, nonce: false, rate: nil, tenants: {}, **extended) # AllowedBy::Serviceorigin: this service's public origin, as agents call it (https://api.example.com).
node: the AllowedBy node it trusts (https://node.example.org), pinned on first fetch.
org: {legal_name:, country:} and optionally website, support, privacy_policy, logo (ORG-1 §2).
routes: AllowedBy.route(...) lines. templates: {capability => "sentence"} or {summary: {lang:}, lines: {lang:}}.
key_file: keeps the signing and disclosure keys across restarts and instances (created on first use, 0600).
store: MemoryStore (one process) or RedisStore (several). trust_list: a TrustList instead of node alone.
refresh_seconds: background refresh period (1-60). node_max_level: the highest level accepted from the node.
clock: -> Integer seconds. title, version, description: the OpenAPI info. rfc9421: accept the Web Bot Auth
profile. logger: #call(message) (default: standard error). http: the HTTP client (tests).
unprotected: your own pages that look like a variant of a protected route or extend one, served without a check:
exact paths or templates, for every method or one: ["/notes.csv", ["GET", "/notes/{id}/photo"]]. Logged at start.
nonce: AllowedBy-Nonce (ABY-2 §3.2) on every irreversible route and on the routes with nonce (default off).
rate: the rate limits, {actor: [n, seconds], operator: [n, seconds]}, each optional (default 600 and 6000 calls
per 60 s). tenants: {id => {name:, routes: {capability => overrides}, budgets: {capability => {max:, currency:,
per:, tz:}}, org:, members_only:}}, the accounts named by the path parameter {tenant} (ORG-1 §3.3, §5.3).
def well_known(mount = "") # AllowedBy::ServiceGET /.well-known/allowedby (ABY-3 §4): vocabulary, templates, keys, the signed organisation profile. mount: the prefix the app is mounted under (SCRIPT_NAME), part of every published URL.
def published # AllowedBy::ServiceThe route map as published: the app's routes, then the SDK's own (POST /allowedby/link, ABY-3 §6).
def openapi(mount = "") # AllowedBy::ServiceOpenAPI 3.1 for the route map (ABY-3 §5.1): each operation's security names the capability it needs,
x-allowedby adds class, level and amount.
def api_catalog(mount = "") # AllowedBy::ServiceRFC 9727 API catalog: where this origin's APIs and their descriptions are.
def handle(method, path, mount = "") # AllowedBy::ServiceThe SDK's own endpoints. -> [status, headers, body] or nil when the path is not one of them.
def target_refusal(path) # AllowedBy::ServiceCONTRACT §2.10 (10): a request target whose path holds a byte that is not plain (a raw non-ASCII byte, a space, a control character, a quote, a backslash...) is refused before routing and verification. -> refusal or nil.
def report(message) # AllowedBy::ServiceA line for the service's log (an adapter's warning at start). Never a value of a request.
def route_for(method, path, routes = @routes) # AllowedBy::ServiceThe route of the map a request falls under, or nil (the app's own paths, unchanged).
def variant_of(method, path, routes = @routes) # AllowedBy::ServiceThe route of the map another router could reach with this request although the map does not name it: the path
read with its dot segments kept, with reserved characters decoded (%2F, %3A, several times over), without
control characters, with a repeated or trailing "/" dropped, or without a suffix (/notes.json, /notes;a:
Rails routes /notes, /notes/, //notes and /notes.json to the same action); or the method in another
case. Such a request is refused (400), never handed to the app unchecked. -> route or nil.
def extension_of(method, path, routes = @routes) # AllowedBy::ServiceThe route of the map that a longer path reaches when a router gives a parameter several segments (/notes/{id}
and /notes/7/x: a wildcard, a splat, a path converter). The SDK cannot see the router: the request is refused
unless unprotected: names the path (CONTRACT §2.10 rule 2). /notes/7 below a literal /notes is the app's.
def longer_only?(method, path) # AllowedBy::ServiceTrue when rule 2 alone refuses the request and an adapter that sees the route its router chooses may decide instead (CONTRACT §2.10 rule 2). An odd or very long path stays refused.
def taken_as(method, path) # AllowedBy::ServiceThe mapped paths this longer path may stand for, its parameters taken from its own segments: the handler the router gives them to is the protected one, whatever a parameter's pattern accepts.
def unprotected?(method, path, variants: false) # AllowedBy::ServiceA page the application declares as its own (unprotected:, CONTRACT §2.10 rule 3). An exact entry is for that
very path; a template only for a plain path: no empty segment, control character, encoded separator or dot
segment. variants: whether the question is about a variant of a route (an exact entry only).
def protects?(method, path, routes = @routes) # AllowedBy::ServiceTrue when the request is the SDK's to check or refuse: a route of the map, a variant of one (variant_of) or an extension of one (extension_of).
def samples # AllowedBy::ServiceCalls of each route of the map, its parameters filled in with values of the usual kinds: [method, path]. The Rails and Sinatra guards ask their router which handler serves them: it never runs unchecked, whichever path reached it.
def check(method, path, headers, body = nil, query = nil, mount: "", longer: false) # AllowedBy::Service-> [Context, nil] when the request is allowed, or [nil, [status, headers, body]] to send back. A path outside the route map is allowed with a nil context (your own authentication applies). headers: name => value, any case. body: the bytes as received ("" or nil when there is none). query: without "?". mount: the prefix the app is mounted under (SCRIPT_NAME); the route map names paths without it. longer: the adapter has seen the route its router chose for this longer path (longer_only?): not refused here. An accepted context: call forget(ctx) once the request is answered (CONTRACT 1.10; the middleware does), or its refund state stays, with the context, until the bound of 10 000 drops it.
def verified(route, method, path, headers, body, query, mount) # AllowedBy::ServiceThe check of a request for this route of the verifier's map, once the path is known to be plain. -> as check.
AllowedBy::Service::BUDGET_FIRSTThe refusals a challenge would answer, after which a used-up tenant budget is answered instead (a single-use approval spent, or a dead agent key, is not the budget's to answer).
def stale(req, route, err) # AllowedBy::Servicedef budget_of(route, path, body) # AllowedBy::ServiceORG-1 §5.3: the tenant budget of this request's route, if any. -> {budget, tenant, key, amount, until}: the amount at the route's amount_field, nil when it is absent or in another currency than the budget's (ORG-1 §5.1: never converted), which no budget can count.
def over_budget(req, route, bud, charge: nil) # AllowedBy::Servicenil when the amount fits what is left of the budget (with charge, the accepted context: once it is counted, in the verifier's store, which every instance that shares it shares), else the 403 budget_exceeded. Only a charge counts: what is used is read for the message of a refusal, or to refuse before a challenge. Raises StoreError.
def money(value) # AllowedBy::ServiceTwo decimals, exactly (a Float would round a large amount).
def release(ctx) # AllowedBy::Servicesdks/CONTRACT.md, Refund on the SDK's own refusal (ABY-2 §5 step 9), for an adapter: release(ctx) when the SDK
itself refuses an accepted request before its handler starts (it gives back exactly what the check charged, once;
-> true when given back), started(ctx) just before the handler runs (-> false for a request given back
already: it must not reach a handler). Nothing is given back once a request started, or for the app's own
refusals.
def refund(ctx) # AllowedBy::ServiceThe handler refused an accepted request (a wrong total, an unknown invoice): the tenant budget it counted is given back (ORG-1 §5.3), once. -> true when given back. The rest of what the check charged stays spent.
def started(ctx) # AllowedBy::ServiceThe handler is about to run: nothing is given back from now on. -> false when this request was given back or forgotten already: it must not reach a handler.
def forget(ctx) # AllowedBy::ServiceThe request is answered: its refund state goes (the middleware does this itself). An adapter of your own calls it once it has the app's answer, or the state stays until the bound of 10 000 drops it.
def problem(code, status, detail = nil, headers = {}, **extra) # AllowedBy::ServiceA problem document (RFC 9457) as [status, headers, body].
def challenge(req, rej) # AllowedBy::ServiceABY-2 §6, §7: the answer to a refused request, with the challenge when a person's approval can fix it. For a write-hard or irreversible route the service creates the approval itself, bound to this exact request.
lib/allowedby/sinatra.rb#
sdks/ruby/lib/allowedby/sinatra.rb
module SinatraGuardSinatra extension: register AllowedBy::SinatraGuard (require "allowedby/sinatra"), with the service in
set :allowedby, -> { service }. The handler of a mapped route never runs without the middleware's check,
whichever path reached it: a splat (/notes/*), an optional segment, strict_paths false or a mount. A
catch-all that serves only unmapped paths is untouched.
def self.registered(app) # AllowedBy::SinatraGuarddef self.router_of(app) # AllowedBy::SinatraGuardThe middleware's router when the next app is a Sinatra app with this guard and nothing else runs before or
after its routes (its own middleware, a downstream app); nil otherwise: longer paths are then refused.
def self.clears?(klass, env, service) # AllowedBy::SinatraGuardTrue when the app's routes give this longer path to no handler of a mapped route.
AllowedBy::SinatraGuard::BUILDWhich route of the map each handler serves (CONTRACT §2.10 rule 5), for this app's prefix: asked of the router once per class, service and prefix, again when the class has more routes. Read without a lock; built and published under one, checked again inside it: two first requests never learn in two maps.
def self.handler_map(klass, service, prefix) # AllowedBy::SinatraGuarddef self.declared(klass, service, prefix) # AllowedBy::SinatraGuardThe routes of the app written like a route of the map (/notes/:id for /notes/{id}): that route's own
handlers, whatever their conditions. -> [[route of the map, handler], ...]
def self.sinatra_routes(klass, method) # AllowedBy::SinatraGuarddef self.handlers_for(klass, method, calls) # AllowedBy::SinatraGuardThe handlers these calls run, for this method (HEAD runs what GET is).
def self.handlers(klass, method, path, every: false) # AllowedBy::SinatraGuardThe handlers Sinatra may run for a path: up to the first route without conditions, in this class and the ones
above. A handler is the block of the route: two routes with one block are one handler (CONTRACT §2.10 rule 2).
every: all the routes of the path, as pass can reach any of them.
def self.matched(klass, method, path, every: false) # AllowedBy::SinatraGuard[[handler, its route's pattern], ...] for a path, as handlers.
def self.handler_of(pattern, wrapper) # AllowedBy::SinatraGuardThe block Sinatra compiled the route from, or the route itself when it cannot be found.
def self.serves?(chosen, mapped) # AllowedBy::SinatraGuardWhether one of the chosen handlers is one of these.
module HelpersThe helpers of the extension.
def allowedby_context # AllowedBy::SinatraGuard::Helpersdef pass(&) # AllowedBy::SinatraGuard::Helperspass hands the request to the next routes of its path, which the guard did not look at: refused when one of
them is the handler of another route of the map, and an unchecked one always on a longer path the router
decided.
A checked request passes only to handlers its route owns, or that no route of the map does.
lib/allowedby/store.rb#
sdks/ruby/lib/allowedby/store.rb
module StoreThe state a verifier keeps (ABY-2 §3.3, ABY-1 §7, ABY-3 §3): the replay set of proofs, single-use grants and
counters. Every method takes now from the SDK's clock, never the store's own, so an injected clock governs
expiry too. A store:
add(key, expires, now) -> true when added, false when the key is live (a replay, a second use)
get(key, now) -> the live value, or 0
charge(charges, now) -> all or nothing: [[key, increment, max or nil, expires]], true when every total
stays within its maxA refund (sdks/CONTRACT.md, Refund on the SDK's own refusal) is a charge too: the receipt of the check, each increment negated, with no max, applied exactly (the single-use mark back to 0, the totals back by the amount). A store that does not take it returns false or raises StoreError: the approval then stays spent.
Keys are arrays of strings and numbers. A store that cannot answer raises StoreError: the request is refused.
def self.key(parts) # AllowedBy::Storeclass MemoryStoreFor one process only (thread-safe: Puma's threads share it). Several processes or machines need a shared store such as RedisStore, or a replayed proof is accepted by the instance that has not seen it.
def initialize(max_keys: 200_000) # AllowedBy::MemoryStoredef add(key, expires, now) # AllowedBy::MemoryStoredef get(key, now) # AllowedBy::MemoryStoredef charge(charges, now) # AllowedBy::MemoryStoreclass RedisStoreThe same store in Redis, shared by every instance and process. Pass a connected client of the redis gem
(redis-rb 5 or later): AllowedBy::RedisStore.new(Redis.new(url: ENV["REDIS_URL"])). The gem is not a
dependency of this one: bring your own.
add is one Lua script (atomic); charge is a WATCH/MULTI transaction retried on conflict, with amounts kept as exact fractions ("4200/1") because Lua numbers are doubles. Each key expires in Redis a minute after its own deadline, measured from the SDK's clock.
def initialize(redis, prefix: "allowedby:", retries: 20) # AllowedBy::RedisStoredef add(key, expires, now) # AllowedBy::RedisStoredef get(key, now) # AllowedBy::RedisStoredef charge(charges, now) # AllowedBy::RedisStorelib/allowedby/tenants.rb#
sdks/ruby/lib/allowedby/tenants.rb
module TenantsTenants and tenant budgets (ORG-1 §3.3, §5.3; sdks/CONTRACT.md, Extended), ported from the Python reference
(sdk.py _check_tenants, verifier.py effective_route): the service option tenants, checked when the service is
built, the route a tenant's overrides make of the provider's (never looser), and the budgets' periods.
AllowedBy::Tenants::LATERThe tenant keys of authority policies (ABY-1 §5): an extended feature this SDK does not implement yet.
def check(tenants, routes) # AllowedBy::TenantsThe tenants option, checked against the route map: a frozen copy with string keys, the caller's never written.
Every key is one the verifier enforces and every value has its shape; anything else raises ConfigError, as a
misspelt override would leave the route as loose as the provider's (CONTRACT: every option is enforced or
refused).
def check_tenant(where, tenant, caps, routes) # AllowedBy::Tenantsdef check_override(where, override) # AllowedBy::Tenantsdef override_ok?(override) # AllowedBy::Tenantsdef budget_refusal(budget, cap, routes) # AllowedBy::TenantsORG-1 §5.3: a budget {max, currency, per: day | week | month, tz?} on cap, every route of which reads an amount
(a route without one could never be called: the budget refuses a request it cannot count). -> why it is
refused, or nil.
def effective(route, tenant, tenants) # AllowedBy::TenantsThe route a tenant's overrides make of the provider's: tighter only (ORG-1 §3.1 overridable, §3.3): the higher
level, the stronger authn, mandate and require_link (true wins), a shorter lifetime, an amount ceiling, an
operator allowlist. A members_only tenant with an org needs a mandate from it on every route, level 0 included
(it is tenant-wide, not keyed by capability). The route itself when the tenant changes nothing.
def zone(tz) # AllowedBy::TenantsA budget's IANA time zone (tzinfo: the system's zoneinfo, or the tzinfo-data gem), UTC when it names none; nil for a name this machine does not know.
def period_id(per, time, tz) # AllowedBy::TenantsThe calendar period holding time t in tz: the day, the ISO week (from Monday) or the month (ABY-3 §2), as the Python reference names it (core.period_id).
def period_end(per, time, tz) # AllowedBy::TenantsWhen that period ends, in epoch seconds: the local midnight after it, so a day that changes the clocks lasts 23 or 25 hours.
def midnight(zone, date) # AllowedBy::TenantsThe first instant of a local date: its midnight, the earlier one when the clocks go back over it, and the first time the day has when they skip it (a change at 00:00).
def budget_key(tenant, cap, budget, time) # AllowedBy::TenantsThe store key of a tenant budget's count this period. Its currency and tz are in it: a budget moved to another currency or zone starts a new count, never one that mixes them (the Python reference's key).
def origin?(value) # AllowedBy::TenantsAn https origin with no path, query, fragment or user (http on this machine only): a URL keys are fetched from.
def plain(value) # AllowedBy::TenantsA deep copy with string keys (a Ruby caller may write symbols), never the caller's objects.
lib/allowedby/testing.rb#
sdks/ruby/lib/allowedby/testing.rb
module TestingTest helpers: an in-memory AllowedBy node, a person with a software passkey and an agent, so you can test your
own app end to end without a browser or a network. TEST ONLY: the keys are generated per run and the "node"
answers only through the http: option of AllowedBy.new.
require "allowedby/testing"
node = AllowedBy::Testing::Node.new
aby = AllowedBy.new(origin: "https://notes.test", node: node.origin, http: node, start: false, ...)
aby.verifier.refresh
agent = node.agent
grant = node.grant(agent, audience: "https://notes.test", capabilities: [{ "cap" => "notes:read",
"constraints" => { "scope" => "note:*" } }])
headers = agent.headers("GET", "https://notes.test/notes", allowed_by: grant)class AgentAn agent: its key and its passport. #headers signs one request (ABY-2 §3).
attr_reader :key, :passport, :sub # AllowedBy::Testing::Agentdef initialize(key, passport, sub, clock) # AllowedBy::Testing::Agentdef headers(method, url, allowed_by: @passport, body: nil) # AllowedBy::Testing::AgentThe Allowed-By and AllowedBy-Proof headers for one request. url: the full URL (the query is not signed).
class NodeA node that issues passports, human registrations and countersigned grants, and serves its statement, its
status list and service-initiated approvals to the SDK through #call (the http: option).
attr_reader :name, :origin, :approvals, :passkey, :credential_id # AllowedBy::Testing::Nodedef initialize(name: "node.test", clock: -> { Time.now.to_i }, level: 2, authn: "hardware") # AllowedBy::Testing::Nodedef status_uri # AllowedBy::Testing::Nodedef statement # AllowedBy::Testing::Nodedef status_list # AllowedBy::Testing::Nodedef revoke(token) # AllowedBy::Testing::NodeRevoke a grant or a passport (the next refresh of the SDK sees it).
def agent(operator: "agent.test", tier: 0, ttl: 3600) # AllowedBy::Testing::NodeA new agent with a tier-0 passport (OAID-3) from this node.
def registration # AllowedBy::Testing::NodeThe person's registration (OAID-7 §4): their passkey, their level.
def human_id(audience) # AllowedBy::Testing::NodeThe person's pairwise id at an audience (what the service sees as human_id).
def grant(agent, audience:, capabilities:, level: @level, initiator: nil, single_use: nil, ttl: 3600, templates: nil, batch: nil, **overrides) # AllowedBy::Testing::NodeA grant the person approved with a passkey tap and this node countersigned (ABY-1 §3). initiator: the service key's kid for a service-initiated grant (write-hard, irreversible), else nil. single_use: the request_digest it is bound to (ABY-1 §7). Other members override the grant's.
def sub_grant(parent, agent, capabilities:, ttl: 1800, **overrides) # AllowedBy::Testing::NodeA sub-agent's grant under parent (ABY-1 §4), countersigned by this node: one level deeper, the parent's
person, audience and approval, no signature of the person's own. Other members override the grant's (a test
of a malformed chain).
def assertion(challenge, rp_id: @name, flags: 0x05) # AllowedBy::Testing::NodeA WebAuthn assertion by the person's passkey over challenge (ABY-1 §3.3).
def call(method, url, body = nil, headers = {}) # AllowedBy::Testing::NodeThe SDK's HTTP client (the http: option): statement, status list, approval creation.
lib/allowedby/trust.rb#
sdks/ruby/lib/allowedby/trust.rb
class TrustListOAID-5 §2: a signed trust list (oaid-trust+jwt) instead of trust on first use. key is the service's own
public JWK that signed it (configuration integrity). Raises ConfigError.
attr_reader :payload, :exp, :anchors, :denied, :vouching, :programs, :witnesses_min # AllowedBy::TrustListdef self.load(path, key) # AllowedBy::TrustListdef self.sign(key, payload) # AllowedBy::TrustListdef initialize(jws, key) # AllowedBy::TrustListclass TrustResolverOAID-5 §3: which nodes a trust list trusts, at which level: anchors, then program lists, then vouching depth
by depth, then witnesses_min. Pure: every document comes from the callables, so the same code runs in the
background refresh (HTTP) and against the test vectors.
def initialize(trust_list, statement:, program:, vouches:, checkpoint:) # AllowedBy::TrustResolverstatement: name -> parsed statement {"name", "kid", "payload", "origin"} or nil program: url -> program list JWS or nil vouches: statement -> [vouch JWS] the node published checkpoint: statement -> the node's latest checkpoint (C2SP signed note) or nil
def resolve(now) # AllowedBy::TrustResolver-> {name => {"statement", "max_level", "via", "depth", "witness_ok"}}
module CheckpointC2SP signed notes: the checkpoints a node's transparency log publishes (OAID-4) and their witness cosignatures.
def parse(note) # AllowedBy::Checkpoint-> [body with its final newline, [[signer, signature bytes]]] or [nil, []]
def keyhash(name, sigtype, jwk) # AllowedBy::Checkpointdef role_keys(statement, role) # AllowedBy::Checkpointdef signed_by_node?(body, lines, statement) # AllowedBy::CheckpointThe checkpoint's origin line is the node's log origin, signed by one of its checkpoint keys.
def cosigned?(body, signer, sig, timestamp, statement) # AllowedBy::Checkpointlib/allowedby/util.rb#
sdks/ruby/lib/allowedby/util.rb
class ConfigError < ArgumentErrorRaised for a configuration the SDK refuses at construction: the message says what to fix.
class StoreError < StandardErrorRaised by a store that cannot answer (a lost Redis connection): the request is refused, never accepted.
module UtilEncodings and small helpers shared by every part of the SDK.
def b64u(bytes) # AllowedBy::Utilbase64url without padding (RFC 7515 §2).
def b64u_dec(str) # AllowedBy::UtilStrict base64url: the URL-safe alphabet only, no padding, no whitespace. Raises ArgumentError.
def b64_dec(str) # AllowedBy::UtilStandard base64 with padding, strict (RFC 4648 §4). Raises ArgumentError.
def b64(bytes) # AllowedBy::Utildef sha256(data) # AllowedBy::Utildef parse_json(bytes) # AllowedBy::UtilJSON from bytes: valid UTF-8, any JSON value. Raises ArgumentError. Like the Python reference (json.loads), a repeated member keeps its last value.
def secure_eq(left, right) # AllowedBy::UtilConstant-time equality of two strings (digests, challenges, tokens).
def clip(value, max = 80) # AllowedBy::UtilAn attacker-supplied value, safe to put in a message: printable and bounded.
def dec(value) # AllowedBy::UtilAn amount as text (ABY-3 §2): at most 15 digits before the point and 6 after, as an exact Rational.
def pointer(doc, ptr) # AllowedBy::UtilRFC 6901 JSON Pointer; nil when the member is missing.
def json_leaves(doc, prefix = "") # AllowedBy::UtilThe JSON Pointers of every leaf member of an object (what fields constrains, ABY-3 §2).
def norm_path(path) # AllowedBy::UtilRFC 3986 §6.2.2 for a path: percent-encoding normalised (unreserved decoded, hex upper), dot segments removed. Bytes outside printable ASCII are percent-encoded first, so the result is always ASCII.
def pct_path(path) # AllowedBy::UtilThe percent-encoding part of norm_path alone: dot segments are still there, as a router that does not remove them sees the path.
AllowedBy::Util::HEXThe value of each hex digit, by its byte.
AllowedBy::Util::CONTROLSC0, DEL, C1, U+2028 and U+2029 in a path, as sent or encoded any number of times.
def decode_once(value) # AllowedBy::UtilOne percent-decoding of a path value (CONTRACT §2 item 7, as Python's unquote): each %XX becomes its byte once
(%2520 gives %20, %2F a "/" inside the value), any other "%" stays, and bytes that are not UTF-8 become
U+FFFD.
def decoded_path(path) # AllowedBy::UtilA path with every percent-encoding decoded, again and again until none is left (bytes). One pass: a byte that completes an encoding is replaced by what it stands for, which may complete another one (%252525...).
def normalize_origin(origin) # AllowedBy::Utilscheme://host[:port] with the scheme and host lowercased and the default port removed (ABY-2 §3 htu).
Raises ArgumentError for anything else (a path, a query, credentials).
def local_host?(host) # AllowedBy::UtilTrue for this machine's names, where plain http is allowed in development: localhost and *.localhost are the loopback (RFC 6761), as in the Python reference (core.is_local), and the loopback addresses.
def origin_host(origin) # AllowedBy::UtilThe host part of an origin, for local_host?.
def netloc(origin) # AllowedBy::Utilhost[:port] of an origin (the realm, the node name).
def deep_freeze(value) # AllowedBy::UtilA deep copy that cannot be changed: what the handler receives is read-only.
lib/allowedby/verifier.rb#
sdks/ruby/lib/allowedby/verifier.rb
AllowedBy::STATUSStatus of every refusal code (ABY-2 §6), the same as the Python reference (verifier.STATUS).
AllowedBy::CHALLENGE_CODESThe codes that answer with an AllowedBy challenge (WWW-Authenticate with what to ask the person for).
class Reject < StandardErrorA refused request: code is the ABY-2 error code, status its HTTP status, why a short reason without
secrets or personal data.
attr_reader :code, :why, :route, :actor_sub, :status, :nonce # AllowedBy::Rejectnonce: a fresh AllowedBy-Nonce for the answer's header (ABY-2 §3.2), when the refusal asks for one.
def initialize(code, why = nil, route: nil, actor_sub: nil, nonce: nil) # AllowedBy::Rejectdef self.build(**fields) # AllowedBydef initialize(mount: "", **rest) # AllowedBydef full_path # AllowedBydef header(name) # AllowedByclass VerifierABY-2 §5: verifies every request offline against the route map. Node statements and status lists are fetched
by a background thread, never while handling a request (OAID-5 §3): with an empty cache a request is
refused (untrusted_node, status_stale). Ported from sdks/python/src/allowedby/verifier.py (Verifier.verify).
AllowedBy::Verifier::MAX_TICKETSAccepted requests in flight whose refund state is kept (CONTRACT 1.10), oldest dropped first: the middleware and the link endpoint forget each one when it is answered (an adapter of your own calls Service#forget), so only an integration that never forgets reaches the bound. A request without a ticket (forgotten, dropped) never starts: fail closed.
attr_reader :origin, :routes, :store, :nodes, :status, :service_kids, :nonce, :rate # AllowedBy::Verifierdef initialize(origin:, routes:, service_kids:, trusted_nodes: {}, dev_webauthn_origins: {}, refresh_seconds: 5, clock: nil, store: nil, trust_list: nil, templates: {}, rfc9421: false, http: nil, logger: nil, start: true, linked: nil, nonce: nil, rate: nil, tenants: {}) # AllowedBy::Verifiertrusted_nodes: {node origin => max_level}, each node's node key pinned on first fetch (trust on first use);
trust_list: a TrustList (OAID-5), which then replaces trusted_nodes. http: #call(method, url, body, headers)
-> [status, body] (default Net::HTTP). start: run the background refresh. With it, the first refresh is over
(done or failed) before the constructor returns, at most STARTUP_WAIT seconds, so a service that starts cold
(a new instance, one that scales to zero) holds node keys and status lists before its first request: nothing
is fetched at request time (ARCH-1 §4, CONTRACT §2 item 4). linked: ->(iss, human_id, route, params) -> the
account the pair is linked to (a String, which the context's linked_account carries), or nil: a require_link
route refuses a request it answers nil or false for (ABY-3 §6). nonce: a Nonce, when the service's nonces are on
(ABY-2 §3.2): a route with nonce, and every irreversible route, then needs a current one. rate: a RateLimit
(default: RateLimit::DEFAULTS). tenants: the service's tenants (Tenants.check), whose overrides tighten the routes
that name one ({tenant}, ORG-1 §3.3).
def now # AllowedBy::Verifierdef start_refresh # AllowedBy::VerifierStarts the refresh thread (once; again after a fork or if it died). Only the constructor waits for its first refresh: a thread started again (in a forked worker, from the middleware) serves the cache the worker inherited, and no request waits on the network.
def ensure_refresh # AllowedBy::VerifierThe middleware calls this on every request: a refresh thread that was started is started again in a forked worker (Puma cluster mode, Unicorn), where threads do not survive the fork. Cheap when it runs.
def stop_refresh # AllowedBy::Verifierdef refresh # AllowedBy::VerifierFetch node statements (trust on first use or the trust list) and status lists. Background only; also callable directly (tests, a deploy hook). A failure keeps the cache: staleness rules apply.
def parse_statement(jws, origin) # AllowedBy::VerifierA node statement (OAID-2 §3), self-signed by its single node key, unexpired.
-> {"name", "kid", "payload", "origin"}. Raises ArgumentError with the reason.
def node_entry(statement, max_level, via: "tofu", witness_ok: true) # AllowedBy::VerifierThe cache entry of a trusted node. Keys whose kid is not their thumbprint are dropped.
def install_node(jws, max_level, origin:) # AllowedBy::VerifierTrust a node from its statement, as a refresh does (tests, or a statement obtained out of band).
def install_status(uri, jws, into = nil, node: nil) # AllowedBy::VerifierTake a status list (statuslist+jwt) signed by an issue key of the node whose statement names uri.
-> true when accepted. A list older than the one held is ignored (no rollback).
node: the node the list was fetched for (the refresh passes it). Without it, the single node whose statement
names uri; refused when several do, so one node never decides with which keys another node's list is read.
def verify(req, link: false) # AllowedBy::Verifier-> Context, or raises Reject. link: the caller is the link endpoint (Service#link): only it is answered on the SDK's own aby:link route (ABY-3 §6), whose code is checked first.
def node_doc(token, typ, role) # AllowedBy::Verifierdef bit(ref, cls, at) # AllowedBy::Verifierdef registration(token, at, cls) # AllowedBy::VerifierA human registration (OAID-7 §4) from a trusted home node, unrevoked. -> [payload, effective level]
def human(grant, at, cls) # AllowedBy::VerifierABY-1 §3.3 steps 1-2 on the root, a batch signature included (§3.2). -> [registration, level]
def assertion(reg, sig, challenge) # AllowedBy::VerifierABY-1 §3.3 step 2 for one assertion under one registration. -> nil when valid, else the reason.
def release(ctx) # AllowedBy::Verifiersdks/CONTRACT.md, Refund on the SDK's own refusal (ABY-2 §5 step 9): the SDK refused this accepted request itself before its handler started (rule 5, a method or path changed after the check). Gives back exactly what the check charged for it, once: the single-use mark, the grant's count and amount totals, as negative increments with no max. -> true when given back. Nothing is given back for a request whose handler started (start), twice, or when the store does not take it: the approval then stays spent, logged without request data.
def attach(ctx, charge) # AllowedBy::VerifierORG-1 §5.3: the tenant budget's charge of this accepted request (Service#check counts it after the check), given back with the rest by release, or alone by refund_budget.
def refund_budget(ctx) # AllowedBy::VerifierThe handler refused this accepted request: its tenant budget's charge is given back, once (ORG-1 §5.3). -> true when given back; false when there is none, it was given back already, or the store does not take it (the amount then stays counted, logged without request data).
def start(ctx) # AllowedBy::VerifierThe adapter is about to hand this accepted request to its handler: from now on nothing is given back for it. False for a request given back already: its approval is usable again, so it never reaches a handler (a layer that dispatches it once more). False too for one whose state is gone (answered and forgotten, or dropped at the bound): nothing can tell it was not given back. True again for one already started (the same handler, again).
def forget(ctx) # AllowedBy::VerifierThis accepted request is answered: its refund state goes (nothing is given back after this, and it never starts again: a later dispatch of it is refused).
lib/allowedby/version.rb#
sdks/ruby/lib/allowedby/version.rb
AllowedBy::VERSIONThe version of this gem (semver).
AllowedBy::SPEC_VERSIONThe AllowedBy specification set this gem implements (specs/README.md).