Files
simple-aircraft-manager-rails/app/services/air_trail_client.rb
T
rickyandClaude Opus 5.5 bffdea937c REST API v1: tokens, read endpoints, squawks, webhooks
- Personal tokens (Profile → API tokens) act as their owner; integration
  tokens (Admin → Integrations) reach chosen aircraft and scopes, and their
  writes name the person they're for (SAM-On-Behalf-Of). Tokens are stored
  hashed, shown once, revocable, with last use recorded.
- GET aircraft, components, due list, inspections, ADs, logbook entries and
  squawks; POST/PATCH squawks with external_ref links to the other system.
- Idempotency-Key for safe retries, paging, JSON errors, rate limits.
- Record history keeps the token with each change (in the hashed payload).
- Webhooks (squawk created/updated/resolved, entry signed), HMAC-signed,
  retried, never sent to the server itself; deliveries listed for admins.
- The outbound address check is shared by AirTrail and webhooks; reporting a
  squawk is announced the same way from the form and the API.
- docs/guide/api.md: the API reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:05:10 -05:00

117 lines
4.2 KiB
Ruby

require "net/http"
# Minimal client for AirTrail's REST API (/api/v1, Bearer API key).
class AirTrailClient
class Error < StandardError
attr_reader :status, :code
def initialize(message, status: nil, code: nil)
super(message)
@status = status
@code = code
end
end
class NetworkError < Error; end # retryable: timeouts, connection refused, 5xx
class AuthError < Error; end # 401/403: bad key or missing scope
class NotFound < Error; end
class ValidationError < Error; end # 400/422
# An address the server won't send to (see #address). Like a bad key, the
# user has to fix the connection, so it's recorded there and not retried.
class BlockedAddress < AuthError; end
# allow_private: may reach addresses on the private network (admins; and
# hosts listed in AIRTRAIL_ALLOWED_HOSTS for everyone). The server itself
# and link-local addresses (cloud metadata) are never reached.
def initialize(base_url:, api_key:, timeout: 20, allow_private: false)
@base = URI.parse(base_url.to_s.chomp("/"))
@api_key = api_key
@timeout = timeout
@allow_private = allow_private || self.class.allowed_hosts.include?(@base.host.to_s.downcase)
end
def self.allowed_hosts = ENV.fetch("AIRTRAIL_ALLOWED_HOSTS", "").split(",").map { _1.strip.downcase }.compact_blank
def me = request(:get, "/api/v1/me").fetch("data")
def search_airports(query) = request(:get, "/api/v1/airports", query: { query: query }).fetch("data")
def search_aircraft(query) = request(:get, "/api/v1/aircraft", query: { query: query }).fetch("data")
# Yields every flight the key's user owns (follows cursor pagination).
def each_flight
cursor = nil
loop do
q = { scope: "mine", limit: 100 }
q[:cursor] = cursor if cursor
page = request(:get, "/api/v1/flights", query: q)
page.fetch("data").each { yield _1 }
cursor = page.dig("page", "nextCursor")
break unless cursor
end
end
def create_flight(body) = request(:post, "/api/v1/flights", body: body).dig("data", "id")
def update_flight(id, body) = request(:put, "/api/v1/flights/#{Integer(id)}", body: body)
def delete_flight(id)
request(:delete, "/api/v1/flights/#{Integer(id)}")
rescue NotFound
nil # already gone
end
private
def request(method, path, query: nil, body: nil)
uri = @base.dup
uri.path = "#{@base.path}#{path}"
uri.query = URI.encode_www_form(query) if query
req = Net::HTTP.const_get(method.to_s.capitalize).new(uri)
req["Authorization"] = "Bearer #{@api_key}"
req["Accept"] = "application/json"
if body
req["Content-Type"] = "application/json"
req.body = JSON.generate(body)
end
http = Net::HTTP.new(uri.host, uri.port)
http.ipaddr = address(uri.host) # connect to the address that was checked (the name can't be re-pointed in between)
http.use_ssl = uri.scheme == "https"
http.open_timeout = http.read_timeout = @timeout
handle(http.start { _1.request(req) })
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message)
end
# The address to connect to (see OutboundAddress).
def address(host)
OutboundAddress.resolve!(host, allow_private: @allow_private)
rescue OutboundAddress::Blocked => e
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{e.reason}", host: host)
end
def handle(response)
status = response.code.to_i
json = begin
response.body.to_s.empty? ? {} : JSON.parse(response.body)
rescue JSON::ParserError
{}
end
return json if status.between?(200, 299)
error = json["error"].is_a?(Hash) ? json["error"] : {}
message = [ error["message"] || "HTTP #{status}", details(error["details"]) ].compact.join(": ")
klass = case status
when 401, 403 then AuthError
when 404 then NotFound
when 400, 409, 422 then ValidationError
else NetworkError
end
raise klass.new("AirTrail: #{message}", status: status, code: error["code"])
end
def details(list)
return nil unless list.is_a?(Array) && list.any?
list.first(3).map { |d| [ Array(d["path"]).join("."), d["message"] ].compact_blank.join(" ") }.join("; ")
end
end