Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Judge customer AI endpoints by the address they resolve to, on every request

Guido Boyke60447a95ff0e
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index dee30d3..6e0b7f8 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -147,6 +147,8 @@ jobs:
spec/helpers/timeline_helper_spec.rb
spec/services/lalabase/safe_markdown_spec.rb
spec/services/lalabase/indexer/git_cloner_spec.rb
+ spec/services/lalabase/public_address_spec.rb
+ spec/services/lalabase/llm/public_endpoint_adapter_spec.rb
spec/components/neo_notification_card_component_spec.rb
spec/components/neo_notification_component_spec.rb
spec/components/neo_time_share_bar_component_spec.rb
diff --git a/app/controllers/concerns/ai_connection_checkable.rb b/app/controllers/concerns/ai_connection_checkable.rb
index dcb5934..160a1f9 100644
--- a/app/controllers/concerns/ai_connection_checkable.rb
+++ b/app/controllers/concerns/ai_connection_checkable.rb
@@ -29,11 +29,11 @@ module AiConnectionCheckable
when :no_models then { alert: t('flash.ai_settings.connection_no_models') }
when :missing_credential then { alert: t('flash.ai_settings.no_client', provider: label) }
else
- # The provider's own words, in a flash — read once by the person who asked for the
- # check. Deliberately NOT the same decision as the stored verdict, which holds only
- # ok/failed: a column the hub renders must not carry unreviewed third-party text
- # (see Lalabase::Llm::ConnectionCheck).
- { alert: t('flash.ai_settings.connection_error', error: result.message) }
+ # A fixed text, never the words of the failure. Those say whether a port is open
+ # (refused, timed out, TLS failed), and with an endpoint the customer typed that
+ # is a port scan of whatever the endpoint reaches. The reason is in the log
+ # (Lalabase::Llm::ConnectionCheck writes it there).
+ { alert: t('flash.ai_settings.connection_error') }
end
end
end
diff --git a/app/models/concerns/ai_credential_connectivity.rb b/app/models/concerns/ai_credential_connectivity.rb
index c592b63..00802ba 100644
--- a/app/models/concerns/ai_credential_connectivity.rb
+++ b/app/models/concerns/ai_credential_connectivity.rb
@@ -70,7 +70,10 @@ module AiCredentialConnectivity
# as a Factory helper it was only reachable from here by naming the service,
# and the rescue below turns any slip into a quiet `false` rather than a raise.
uri_base: effective_api_base,
- additional_config: additional_config
+ additional_config: additional_config,
+ # The operator's own credential, tested from the admin area: its endpoint is
+ # theirs to choose, a model server on the same host included.
+ operator_endpoint: true
)
end
diff --git a/app/services/CLAUDE.md b/app/services/CLAUDE.md
index 07c4ac6..a1ad84a 100644
--- a/app/services/CLAUDE.md
+++ b/app/services/CLAUDE.md
@@ -1,4 +1,4 @@
-# Karte: app/services (Stand: 2026-10-08)
+# Karte: app/services (Stand: 2026-10-19)
**Entry-Point-Konvention für NEUE Services: `Klass.call(**kwargs)`** (Klassenmethode; eine
Instanz-`#call`-Implementierung dahinter ist erlaubt). Pflicht: mindestens 1 Kommentarzeile
@@ -134,11 +134,13 @@ Verzeichnis-Übersicht (Auswahl):
behält auch bei leer (E2-A, der Schlüssel wird nie zurückgespielt); ein Wechsel von
**Anbieter oder Endpunkt** verlangt seine erneute Eingabe, weil ein behaltener Schlüssel plus
ein beschreibbares `ai_api_base` sonst ein Lesezugriff auf ihn ist (Begründung:
- `doc/ki_bereich_navigation_plan.md` §E2a); und der Endpunkt-Riegel `#public_host?` beurteilt
- die **Zieladresse**, nie die Schreibweise — er ging zweimal an genau dieser Verwechslung
- kaputt (IPv4-gemappte IPv6-Literale, dann numerische Notationen wie `127.1` oder
- `0x7f.0.0.1`, die `IPAddr` ablehnt und der Resolver auflöst). Wer dort eine dritte Notation
- in die Beispielliste einträgt, behandelt ein Symptom.
+ `doc/ki_bereich_navigation_plan.md` §E2a); und der Endpunkt-Riegel gehört `Lalabase::PublicAddress`: er löst den Namen
+ auf und beurteilt die **Zieladressen**, nie die Schreibweise. Er ging dreimal an genau dieser
+ Verwechslung kaputt (IPv4-gemappte IPv6-Literale, numerische Notationen wie `127.1`, dann
+ Namen: `localhost.`, `redis.`, öffentliche Namen mit Eintrag nach innen). Beim Speichern ist
+ er nur Komfort; der Schutz ist `Lalabase::Llm::PublicEndpointAdapter`, der bei jeder
+ Verbindung neu prüft und den Socket an die geprüfte Adresse bindet. Vertraut wird nur dem
+ Endpunkt, den eine `AiCredential` nennt (`Factory#operator_endpoint?`).
Registrierung (Website-Schnitt W2, 15.09.2026): `create_signup` ist die EINE
Selbst-Registrierung für das Formular und später den Provisioning-Endpunkt. Tier 2: Sprache
und tenant-freier Rahmen umschließen den ganzen Lauf (die Bestätigungsmail rendert beim
diff --git a/app/services/actors/save_ai_configuration.rb b/app/services/actors/save_ai_configuration.rb
index cebe44c..ba18d80 100644
--- a/app/services/actors/save_ai_configuration.rb
+++ b/app/services/actors/save_ai_configuration.rb
@@ -67,23 +67,6 @@ module Actors
# column outside the audit is a change nobody can reconstruct afterwards.
WRITABLE = AiConfigurationAudit::COLUMNS
- # Names that resolve to the app server itself. The literal-IP families are
- # covered by IPAddr below; this list is for the names that never reach it.
- BLOCKED_API_BASE_HOSTS = %w[localhost ip6-localhost].freeze
-
- # Ranges that reach an internal network but that NO IPAddr predicate reports:
- # #loopback?, #private? and #link_local? together do not cover them, so without
- # this table they read as public.
- #
- # 100.64.0.0/10 Carrier-grade NAT (RFC 6598). Not exotic: it is the address
- # space Tailscale hands out, and several managed-Kubernetes
- # offerings put pod/service networks there. "Shared address
- # space" means shared with the operator's own hosts.
- #
- # A table, not a fourth boolean in the predicate below, so a range added later is
- # a data row somebody can read.
- BLOCKED_API_BASE_RANGES = ['100.64.0.0/10'].map { |cidr| IPAddr.new(cidr) }.freeze
-
def initialize(organisation:, params:, current_user:)
super()
@organisation = organisation
@@ -196,14 +179,12 @@ module Actors
# * a public host — without this the same field reaches the app server's own
# network (127.0.0.1, RFC1918, link-local), i.e. SSRF with a credential attached.
#
- # ⚠️ Residual gap, stated rather than papered over: a NAME that resolves to a private
- # address passes here. Closing that needs resolution at REQUEST time (a check at save
- # time is TOCTOU — DNS can move afterwards), which belongs to the provider layer, not
- # to a write. This check removes the direct route, not the determined one.
- #
- # ⚠️ The embedding lane has the same column (embedding_api_base) and today no such
- # guard, only a presence validation. It has no org-side write path yet; when S5 adds
- # one, this rule moves to a shared owner rather than being copied.
+ # Where a host leads is Lalabase::PublicAddress's question, asked here so a wrong
+ # endpoint is refused while its owner is still on the form. It is not the
+ # protection: DNS answers again for every request and can point inward by then, so
+ # Lalabase::Llm::PublicEndpointAdapter asks again for every connection and sends the
+ # socket to exactly the address it judged. The embedding lane (embedding_api_base)
+ # has no org-side write path yet; when S5 adds one, it calls the same owner.
def reject_unsafe_api_base!
base = @organisation.ai_api_base
return if base.blank?
@@ -219,65 +200,8 @@ module Actors
nil
end
- # ⚠️⚠️ THE ONE RULE OF THIS PREDICATE: judge the DESTINATION a socket would reach,
- # never the NOTATION the customer typed. It has been broken twice, both times by
- # asking IPAddr a question about spelling:
- #
- # 1st IPv4-mapped IPv6 literals. #loopback?/#private?/#link_local? judge the
- # address in the form it was WRITTEN, so ::ffff:127.0.0.1 was none of them.
- # Fixed with .native, which folds the form away before the question.
- # 2nd Numeric notations IPAddr refuses to parse but getaddrinfo resolves happily
- # — 2130706433, 127.1, 0x7f.0.0.1, 0xa.0.0.5. They fell into the rescue
- # branch, which used to conclude "not a literal, therefore a name" and let
- # them through. Measured: all four were stored, all four reach 127.0.0.1 or
- # 10.0.0.5.
- #
- # Before adding a THIRD notation to the example list below, ask the question that
- # would have caught both of the above at design time: does this check decide on the
- # address a connect() ends up at, or on the characters in the field? Only the first
- # is a security property. Another notation is a symptom; another parser that
- # disagrees with the resolver is the defect.
- #
- # The honest remaining gap is a different one and must not be confused with these:
- # a genuine DNS NAME whose record points inward, or moves inward afterwards. That is
- # TOCTOU and belongs to request time (see #reject_unsafe_api_base!). Everything a
- # resolver would answer WITHOUT a DNS lookup belongs here.
- #
- # hostname, not host: it hands over the bare address without the brackets an IPv6
- # literal carries in a URL. IPAddr accepts "[::1]" too, so this is not today the
- # difference between catching a loopback and missing one — it is the form every host
- # check that is not IPAddr would need.
def public_host?(hostname)
- return false if BLOCKED_API_BASE_HOSTS.include?(hostname.downcase)
-
- # .native folds ::ffff:7f00:1 back to 127.0.0.1 before any predicate is asked.
- address = IPAddr.new(hostname).native
-
- # The unspecified addresses (0.0.0.0 and ::) are none of the three predicates and
- # mean "this host" to a connecting socket — the same destination under a name none
- # of the checks above covers.
- return false if address.to_i.zero?
- return false if BLOCKED_API_BASE_RANGES.any? { |range| range.include?(address) }
-
- !(address.loopback? || address.private? || address.link_local?)
- rescue IPAddr::InvalidAddressError
- # IPAddr could not parse it — which says nothing about whether a RESOLVER could.
- # So the branch does not conclude "name", it PROVES name, and refuses everything
- # it cannot prove.
- dns_name?(hostname)
- end
-
- # Is this a DNS name rather than an address in a notation IPAddr does not speak?
- #
- # Decided on the RIGHTMOST label, because that is the one the rules constrain: a
- # fully qualified name ends in a TLD, and no TLD may begin with a digit (RFC 1123
- # relaxed the rule for the other labels; punycode TLDs start "xn--", still a
- # letter). Every numeric notation, in every base, ends in a digit — that is what
- # makes it numeric. So the test is cheap, has no false negative among real names,
- # and needs no list of notations to stay complete, which is exactly what the second
- # defect above cost us.
- def dns_name?(hostname)
- hostname.downcase.delete_suffix('.').split('.').last.to_s.match?(/\A[a-z]/)
+ Lalabase::PublicAddress.public?(hostname)
end
# The other half of the exfiltration guard. Keeping a stored key (E2-A) is safe only
diff --git a/app/services/lalabase/llm/connection_check.rb b/app/services/lalabase/llm/connection_check.rb
index 2ad46f5..062615a 100644
--- a/app/services/lalabase/llm/connection_check.rb
+++ b/app/services/lalabase/llm/connection_check.rb
@@ -25,8 +25,8 @@
# never the message. A provider error can carry the endpoint, a request id, and on a
# misconfigured openai_compatible endpoint whatever a stranger's server chose to
# write; storing it would put unreviewed third-party text into a column the hub card
-# renders. The reason for a failure is a flash, which is read once by the person who
-# asked for it.
+# renders. The flash does not carry it either (AiConnectionCheckable): it would say
+# which ports an endpoint the customer typed can reach. The reason is in the log.
# * A CHECK NEVER FAILS THE REQUEST. Every error becomes a result, because this is a
# diagnostic: an admin pressing "prüfen" on a broken access must get a red answer,
# not a 500.
diff --git a/app/services/lalabase/llm/factory.rb b/app/services/lalabase/llm/factory.rb
index e85c1b4..3654689 100644
--- a/app/services/lalabase/llm/factory.rb
+++ b/app/services/lalabase/llm/factory.rb
@@ -819,10 +819,22 @@ module Lalabase
klass.new(api_key: descriptor.api_key, organisation_id_param: descriptor.organization_id,
organisation: organisation, uri_base: descriptor.api_base,
embedding_model: descriptor.model, additional_config: descriptor.additional_config,
- embedding_dims: descriptor.dims, billing_credential: descriptor.credential)
+ embedding_dims: descriptor.dims, billing_credential: descriptor.credential,
+ operator_endpoint: operator_endpoint?(descriptor.api_base, descriptor.credential))
end
private_class_method :build_provider
+ # Did an operator choose this endpoint? Only when it is exactly the one an
+ # AiCredential names. A BYOK endpoint comes with no credential, and a space row
+ # whose own api_base differs from its credential's is not the operator's choice
+ # either. Everything that is not provably the operator's is judged again for every
+ # request (PublicEndpointAdapter); a self-hosted model server next to the app
+ # belongs on a system credential for exactly that reason.
+ def operator_endpoint?(api_base, credential)
+ credential.present? && api_base.present? && api_base == credential.effective_api_base
+ end
+ private_class_method :operator_endpoint?
+
# `utility:` selects the package rung the credentials come from (P3); it is
# meaningless on the PINNED path, which by definition does not run on the
# org's package at all — see #resolve_credentials, where a rung of a
@@ -888,7 +900,8 @@ module Lalabase
organisation: organisation, uri_base: creds[:api_base],
chat_model: creds[:chat_model], provider_name: creds[:display_name],
additional_config: creds[:additional_config],
- billing_credential: creds[:credential])
+ billing_credential: creds[:credential],
+ operator_endpoint: operator_endpoint?(creds[:api_base], creds[:credential]))
end
private_class_method :instantiate_chat
diff --git a/app/services/lalabase/llm/open_ai_compatible_provider.rb b/app/services/lalabase/llm/open_ai_compatible_provider.rb
index ae3e9e9..5cb9e7d 100644
--- a/app/services/lalabase/llm/open_ai_compatible_provider.rb
+++ b/app/services/lalabase/llm/open_ai_compatible_provider.rb
@@ -74,6 +74,11 @@ module Lalabase
# uri_base is threaded through Provider#initialize; without it this
# provider has no endpoint to talk to.
+ #
+ # An endpoint the operator did not configure goes through PublicEndpointAdapter:
+ # the address is judged for every connection and the socket goes to exactly that
+ # address. ruby-openai builds a fresh Faraday connection per request and hands it
+ # to this block, so the adapter covers every call, streaming included.
def client
@client ||= begin
base = api_base.presence ||
@@ -82,7 +87,9 @@ module Lalabase
access_token: api_key,
uri_base: base,
organization_id: organisation_id_param.presence
- )
+ ) do |connection|
+ connection.adapter(PublicEndpointAdapter) unless operator_endpoint?
+ end
end
end
end
diff --git a/app/services/lalabase/llm/provider.rb b/app/services/lalabase/llm/provider.rb
index 1d73dc4..5ce3276 100644
--- a/app/services/lalabase/llm/provider.rb
+++ b/app/services/lalabase/llm/provider.rb
@@ -73,9 +73,14 @@ module Lalabase
# (KI-Pakete P0, doc/ki_pakete_plan.md §4.1 — with packages, several
# credentials of the same provider are in service at once and a name-based
# second resolution would be ambiguous).
+ # @param operator_endpoint [Boolean] true only when uri_base is the endpoint an
+ # operator put on an AiCredential (Factory#operator_endpoint?). Anything else,
+ # above all an endpoint a customer typed, is judged again for every connection
+ # (PublicEndpointAdapter). Defaults to false, so a construction path that
+ # forgets to say is guarded rather than trusted.
def initialize(api_key:, organisation_id_param: nil, organisation: nil, uri_base: nil,
embedding_model: nil, chat_model: nil, provider_name: nil, additional_config: nil,
- embedding_dims: nil, billing_credential: nil)
+ embedding_dims: nil, billing_credential: nil, operator_endpoint: false)
@api_key = api_key
@organisation_id_param = organisation_id_param
@organisation = organisation
@@ -86,6 +91,11 @@ module Lalabase
@additional_config = additional_config
@configured_embedding_dims = embedding_dims
@billing_credential = billing_credential
+ @operator_endpoint = operator_endpoint
+ end
+
+ def operator_endpoint?
+ @operator_endpoint == true
end
# Non-streaming chat completion.
diff --git a/app/services/lalabase/llm/public_endpoint_adapter.rb b/app/services/lalabase/llm/public_endpoint_adapter.rb
new file mode 100644
index 0000000..bbe90f5
--- /dev/null
+++ b/app/services/lalabase/llm/public_endpoint_adapter.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+require 'faraday/net_http'
+
+# The Faraday adapter for an AI endpoint a customer typed (OpenAiCompatibleProvider
+# with operator_endpoint false). It closes what a check at save time cannot: DNS
+# answers again for every request, and a name that pointed outward when it was saved
+# can point at the app server when the decrypted key is sent (DNS rebinding).
+#
+# So for every connection it resolves the host through Lalabase::PublicAddress, refuses
+# unless every address is public, and pins the socket to the first of them
+# (Net::HTTP#ipaddr=). Net::HTTP keeps the NAME for SNI and the certificate check, so
+# TLS still verifies the host the customer named.
+#
+# Through a proxy the proxy resolves the name and the pinned address means nothing, so
+# a proxied request is refused. An operator who needs one configures the endpoint on a
+# system credential, which does not use this adapter.
+#
+# Entry point: Faraday calls it (connection.adapter(PublicEndpointAdapter))
+module Lalabase
+ module Llm
+ class PublicEndpointAdapter < Faraday::Adapter::NetHttp
+ # A connection failure to every rescue that already handles one (the providers,
+ # retry_on in the jobs, ConnectionCheck), with no port or reason in its text.
+ class EndpointNotPublicError < Faraday::ConnectionFailed; end
+
+ def net_http_connection(env)
+ raise EndpointNotPublicError, 'the endpoint is not a public address' if env[:request][:proxy]
+
+ address = PublicAddress.resolve!(env[:url].hostname).first
+ super.tap { |http| http.ipaddr = address }
+ rescue PublicAddress::NotPublicError
+ raise EndpointNotPublicError, 'the endpoint is not a public address'
+ end
+ end
+ end
+end
diff --git a/app/services/lalabase/public_address.rb b/app/services/lalabase/public_address.rb
new file mode 100644
index 0000000..ff701df
--- /dev/null
+++ b/app/services/lalabase/public_address.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+require 'ipaddr'
+require 'socket'
+
+# Does a host reach the public internet, or the network the app server sits in? The
+# one owner of that question for every address a customer types and the app then
+# connects to with a credential attached: the own AI endpoint (Actors::SaveAiConfiguration
+# at save time, Lalabase::Llm::PublicEndpointAdapter for every request).
+#
+# ⚠️ THE ONE RULE: judge the ADDRESSES a resolver returns, never the characters the
+# customer typed. Every earlier version broke on that confusion: IPv4-mapped IPv6
+# literals, numeric notations IPAddr refuses but getaddrinfo resolves (127.1,
+# 2130706433, 0x7f.0.0.1), then names: `localhost.` with its trailing dot, short names
+# of the server network (`redis.`), and public names whose record points inward (a
+# CNAME to 127.0.0.1 or to the cloud metadata address). Asking the resolver answers all
+# of them at once, and the next notation as well.
+#
+# A name that does not resolve is refused with the same answer as one that points
+# inward. A different answer would tell the caller which internal names exist.
+#
+# Entry point: resolve!
+module Lalabase
+ module PublicAddress
+ class NotPublicError < StandardError; end
+
+ # Ranges that reach an internal network but that NO IPAddr predicate reports:
+ # #loopback?, #private? and #link_local? together do not cover them.
+ #
+ # 100.64.0.0/10 Carrier-grade NAT (RFC 6598). The address space Tailscale hands
+ # out, and where several managed-Kubernetes offerings put pod and
+ # service networks.
+ BLOCKED_RANGES = ['100.64.0.0/10'].map { |cidr| IPAddr.new(cidr) }.freeze
+
+ DEFAULT_RESOLVER = lambda do |hostname|
+ Addrinfo.getaddrinfo(hostname, nil, nil, :STREAM).map(&:ip_address).uniq
+ end
+
+ class << self
+ # Specs replace the resolver (spec/support/public_address_resolver.rb); nil
+ # restores the system one.
+ attr_writer :resolver
+
+ def resolver
+ @resolver || DEFAULT_RESOLVER
+ end
+
+ # @return [Array<String>] every address the host resolves to, all of them public
+ # @raise [NotPublicError] when the host is blank, does not resolve, or any one of
+ # its addresses is not public
+ def resolve!(hostname)
+ host = hostname.to_s.delete_prefix('[').delete_suffix(']')
+ raise NotPublicError, 'blank host' if host.empty?
+
+ addresses = addresses_of(host)
+ raise NotPublicError, "#{host} does not resolve" if addresses.empty?
+ raise NotPublicError, "#{host} is not a public address" unless addresses.all? { |a| public_ip?(a) }
+
+ addresses
+ end
+
+ def public?(hostname)
+ resolve!(hostname)
+ true
+ rescue NotPublicError
+ false
+ end
+
+ private
+
+ # A literal is its own answer; everything else, including the numeric notations
+ # IPAddr does not speak, goes to the resolver.
+ def addresses_of(host)
+ [IPAddr.new(host).to_s]
+ rescue IPAddr::InvalidAddressError
+ resolved_addresses(host)
+ end
+
+ def resolved_addresses(host)
+ Array(resolver.call(host))
+ rescue SocketError, SystemCallError
+ []
+ end
+
+ def public_ip?(text)
+ # .native folds ::ffff:7f00:1 back to 127.0.0.1 before any predicate is asked.
+ address = IPAddr.new(text.to_s).native
+
+ # The unspecified addresses (0.0.0.0 and ::) are none of the predicates below
+ # and mean "this host" to a connecting socket.
+ return false if address.to_i.zero?
+ return false if BLOCKED_RANGES.any? { |range| range.include?(address) }
+
+ !(address.loopback? || address.private? || address.link_local?)
+ rescue IPAddr::InvalidAddressError
+ false
+ end
+ end
+ end
+end
diff --git a/config/locales/controllers.de.yml b/config/locales/controllers.de.yml
index b4e8869..66b91ad 100644
--- a/config/locales/controllers.de.yml
+++ b/config/locales/controllers.de.yml
@@ -396,7 +396,7 @@ de:
connection_success: "Verbindung zu %{provider} erfolgreich getestet."
connection_no_models: "Verbindungstest fehlgeschlagen: Keine Modelle gefunden."
client_configured: "Client für %{provider} konfiguriert."
- connection_error: "Verbindungstest fehlgeschlagen: %{error}"
+ connection_error: "Verbindungstest fehlgeschlagen. Der Anbieter war nicht erreichbar oder hat die Anfrage abgelehnt. Prüfe Endpunkt-URL, Schlüssel und Modell."
activated: "KI-Features wurden für diese Organisation aktiviert."
# Die Einwilligung ist erteilt, der Zugang fehlt trotzdem. Ohne diesen Satz meldete
# die Seite schlicht Erfolg, und die erste Rueckmeldung war Tage spaeter eine Suche,
diff --git a/config/locales/controllers.en.yml b/config/locales/controllers.en.yml
index 8942a46..c66c9af 100644
--- a/config/locales/controllers.en.yml
+++ b/config/locales/controllers.en.yml
@@ -392,7 +392,7 @@ en:
connection_success: "Connection to %{provider} successfully tested."
connection_no_models: "Connection test failed: No models found."
client_configured: "Client for %{provider} configured."
- connection_error: "Connection test failed: %{error}"
+ connection_error: "Connection test failed. The provider could not be reached or refused the request. Check the endpoint URL, the key and the model."
activated: "AI features have been activated for this organisation."
activated_without_embedding_access: >-
AI features are active. Embedding access is still missing. New content stays
diff --git a/config/locales/services.de.yml b/config/locales/services.de.yml
index 0d8f73f..bc05c20 100644
--- a/config/locales/services.de.yml
+++ b/config/locales/services.de.yml
@@ -8,7 +8,7 @@ de:
unusable_token: "Der hinterlegte Schlüssel passt nicht zum Format, das %{provider} erwartet. Gespeichert würde er die KI für die Organisation abschalten, statt sie einzurichten."
token_reentry_required: "Anbieter oder Endpunkt sollen sich ändern. Bitte trage den Schlüssel dafür erneut ein: er wird nie im Klartext angezeigt, und ohne diesen Schritt könnte ein bestehender Schlüssel an eine neue Adresse geschickt werden, ohne dass jemand ihn kennt."
api_base_not_https: "Die Endpunkt-URL muss mit https:// beginnen. Über eine unverschlüsselte Verbindung ginge der Schlüssel im Klartext an den Anbieter."
- api_base_not_public: "Diese Endpunkt-URL zeigt auf das Servernetz von Lalabase statt auf einen Anbieter. Bitte trage die öffentliche Adresse deines Endpunkts ein."
+ api_base_not_public: "Diese Endpunkt-URL führt nicht zu einer öffentlichen Adresse: Sie zeigt auf das Servernetz von Lalabase oder lässt sich nicht auflösen. Bitte trage die öffentliche Adresse deines Endpunkts ein."
fields:
ai_access_token: "Schlüssel"
ai_api_base: "Endpunkt-URL"
diff --git a/config/locales/services.en.yml b/config/locales/services.en.yml
index 25801be..3ed5757 100644
--- a/config/locales/services.en.yml
+++ b/config/locales/services.en.yml
@@ -8,7 +8,7 @@ en:
unusable_token: "The stored key does not match the format %{provider} expects. Saving it would switch AI off for the organisation rather than set it up."
token_reentry_required: "The provider or the endpoint is about to change. Please enter the key again for that: it is never shown in clear, and without this step an existing key could be sent to a new address by someone who does not know it."
api_base_not_https: "The endpoint URL must start with https://. Over an unencrypted connection the key would reach the provider in clear."
- api_base_not_public: "This endpoint URL points at the Lalabase server network rather than at a provider. Please enter the public address of your endpoint."
+ api_base_not_public: "This endpoint URL does not lead to a public address: it points at the Lalabase server network or does not resolve. Please enter the public address of your endpoint."
fields:
ai_access_token: "key"
ai_api_base: "endpoint URL"
diff --git a/spec/controllers/organisations/ai_settings_controller_spec.rb b/spec/controllers/organisations/ai_settings_controller_spec.rb
index 43d88fe..22a1f59 100644
--- a/spec/controllers/organisations/ai_settings_controller_spec.rb
+++ b/spec/controllers/organisations/ai_settings_controller_spec.rb
@@ -246,16 +246,30 @@ RSpec.describe Organisations::AiSettingsController, type: :controller do
)
end
- it 'reports a connection error with the reason when the probe itself raises' do
- # Provider maps the vendor 401 to AuthError; it must surface as the specific
- # connection_error (with the message), not the generic no_client copy.
+ it 'reports a connection error, not the generic no_client copy, when the probe raises' do
provider = instance_double(Lalabase::Llm::OpenAiProvider)
allow(provider).to receive(:connectivity_check).and_raise(Lalabase::Llm::Provider::AuthError, '401 bad key')
allow(Lalabase::Llm::Factory).to receive(:chat_probe).with(organisation).and_return(provider)
post :test_connection, params: test_params
- expect(flash[:alert]).to eq(I18n.t('flash.ai_settings.connection_error', error: '401 bad key'))
+ expect(flash[:alert]).to eq(I18n.t('flash.ai_settings.connection_error'))
+ end
+
+ # The error text of a failed connection says whether a port is open (refused,
+ # timed out, TLS failed). With a customer's endpoint that is a port scan of
+ # whatever the endpoint reaches, so the flash carries none of it.
+ it 'does not show the words of the failure' do
+ provider = instance_double(Lalabase::Llm::OpenAiCompatibleProvider)
+ allow(provider).to receive(:connectivity_check)
+ .and_raise(Faraday::ConnectionFailed, 'Failed to open TCP connection to 127.0.0.1:6379 (Connection refused)')
+ allow(Lalabase::Llm::Factory).to receive(:chat_probe).with(organisation).and_return(provider)
+
+ post :test_connection, params: test_params
+
+ expect(flash[:alert]).not_to include('6379')
+ expect(flash[:alert]).not_to include('refused')
+ expect(flash[:alert]).to eq(I18n.t('flash.ai_settings.connection_error'))
end
end
diff --git a/spec/services/actors/save_ai_configuration_spec.rb b/spec/services/actors/save_ai_configuration_spec.rb
index 7cb00ab..f3668c1 100644
--- a/spec/services/actors/save_ai_configuration_spec.rb
+++ b/spec/services/actors/save_ai_configuration_spec.rb
@@ -225,6 +225,31 @@ RSpec.describe Actors::SaveAiConfiguration do
expect(save_endpoint('https://localhost/v1').code).to eq(:api_base_not_public)
end
+ # Reported against the first version, which judged the spelling of a name: each of
+ # these passed it, and the connection test then said which ports were open.
+ {
+ 'https://localhost./v1' => 'the trailing dot names the same host',
+ 'https://redis.:6379/v1' => 'a short name of the server network',
+ 'https://localhost.attacker.example/v1' => 'a public name pointing at loopback',
+ 'https://awsmeta.attacker.example/v1' => 'a public name pointing at the metadata service'
+ }.each do |endpoint, why|
+ it "refuses #{endpoint} (#{why})" do
+ resolve_names('redis' => ['192.168.0.1'], 'localhost.attacker.example' => ['127.0.0.1', '::1'],
+ 'awsmeta.attacker.example' => ['169.254.169.254'])
+
+ expect(save_endpoint(endpoint).code).to eq(:api_base_not_public)
+ expect(organisation.reload.ai_api_base).to be_blank
+ end
+ end
+
+ # Same answer as for an inward name: a different one would tell the caller which
+ # internal names exist.
+ it 'refuses a name that does not resolve, with the same answer' do
+ Lalabase::PublicAddress.resolver = ->(_hostname) { raise SocketError, 'no such name' }
+
+ expect(save_endpoint('https://nowhere.example/v1').code).to eq(:api_base_not_public)
+ end
+
it 'refuses something that is not a URL at all' do
expect(save_endpoint('not a url').code).to eq(:api_base_not_https)
end
diff --git a/spec/services/lalabase/llm/factory_spec.rb b/spec/services/lalabase/llm/factory_spec.rb
index e766f42..a18c88d 100644
--- a/spec/services/lalabase/llm/factory_spec.rb
+++ b/spec/services/lalabase/llm/factory_spec.rb
@@ -476,6 +476,44 @@ RSpec.describe Lalabase::Llm::Factory do
end
end
+ # An endpoint a customer typed is judged again for every request
+ # (Lalabase::Llm::PublicEndpointAdapter). One the operator put on a system credential
+ # is not: a model server next to a self-hosted app is a legitimate place for it.
+ describe 'who chose the endpoint' do
+ let(:system_credential) do
+ build_stubbed(:ai_credential, provider: 'openai_compatible', enabled: true,
+ access_token: 'sk-sys', default_model: 'm', api_base: 'https://sys.internal/v1')
+ end
+
+ it "treats the organisation's own chat endpoint as the customer's" do
+ organisation.update!(ai_provider: 'openai_compatible', ai_access_token: 'key-123',
+ ai_api_base: 'https://own.example/v1', preferred_chat_model: 'm')
+
+ expect(described_class.for_chat(organisation).operator_endpoint?).to be(false)
+ end
+
+ it "treats the system credential's chat endpoint as the operator's" do
+ organisation.update!(ai_provider: 'openai_compatible', ai_access_token: nil)
+ allow(AiCredential).to receive(:active_for_provider).with('openai_compatible').and_return(system_credential)
+
+ expect(described_class.for_chat(organisation).operator_endpoint?).to be(true)
+ end
+
+ it "treats the organisation's own embedding endpoint as the customer's" do
+ organisation.update!(embedding_provider: 'openai_compatible', embedding_access_token: 'sk-local',
+ embedding_api_base: 'https://own.example/v1', embedding_model: 'bge-1536')
+
+ expect(described_class.for_embeddings(organisation, space: :configured).operator_endpoint?).to be(false)
+ end
+
+ it "treats the system credential's embedding endpoint as the operator's" do
+ organisation.update!(embedding_provider: 'openai_compatible')
+ allow(AiCredential).to receive(:active_for_provider).with('openai_compatible').and_return(system_credential)
+
+ expect(described_class.for_embeddings(organisation, space: :configured).operator_endpoint?).to be(true)
+ end
+ end
+
# ⚠️ REWRITTEN in the review of S7, and the old title was the defect: there was no
# single "precedence", there were two branches, and the org column had a meaning in
# exactly one of them. The examples below used to PIN the wrong behaviour — three of
diff --git a/spec/services/lalabase/llm/public_endpoint_adapter_spec.rb b/spec/services/lalabase/llm/public_endpoint_adapter_spec.rb
new file mode 100644
index 0000000..c6cfecf
--- /dev/null
+++ b/spec/services/lalabase/llm/public_endpoint_adapter_spec.rb
@@ -0,0 +1,115 @@
+# frozen_string_literal: true
+
+# What: Lalabase::Llm::PublicEndpointAdapter, and the OpenAI-compatible provider that
+# uses it for an endpoint a customer typed.
+# Why: a check at save time cannot hold. DNS answers again for every request, and a
+# name that pointed outward when it was saved can point at the app server when the
+# key is sent (DNS rebinding). So the address is judged again for every connection,
+# and the socket goes to exactly the address that was judged, never to a second
+# lookup of the name.
+
+require 'rails_helper'
+require 'socket'
+
+RSpec.describe Lalabase::Llm::PublicEndpointAdapter, :ci_guard do
+ def env_for(url)
+ Faraday::Env.from(method: :get, url: URI(url), request: Faraday::RequestOptions.new,
+ ssl: Faraday::SSLOptions.new, request_headers: {})
+ end
+
+ def connection_for(url)
+ described_class.new(->(env) { env }).send(:net_http_connection, env_for(url))
+ end
+
+ describe 'the connection it builds' do
+ it 'connects to the address it checked and keeps the name for TLS' do
+ resolve_names('api.provider.example' => ['52.1.2.3'])
+
+ http = connection_for('https://api.provider.example/v1/models')
+
+ expect(http.ipaddr).to eq('52.1.2.3')
+ expect(http.address).to eq('api.provider.example')
+ end
+
+ it 'refuses a name that points inward' do
+ resolve_names('localhost.attacker.example' => ['127.0.0.1'])
+
+ expect { connection_for('https://localhost.attacker.example/v1/models') }
+ .to raise_error(described_class::EndpointNotPublicError)
+ end
+
+ # Rebinding: the first answer was public (that is what the save saw), the next
+ # one is not. The adapter asks again and refuses.
+ it 'judges the address again for every connection' do
+ answers = [['52.1.2.3'], ['127.0.0.1']]
+ Lalabase::PublicAddress.resolver = ->(_hostname) { answers.shift }
+
+ expect(connection_for('https://rebind.attacker.example/v1').ipaddr).to eq('52.1.2.3')
+ expect { connection_for('https://rebind.attacker.example/v1') }
+ .to raise_error(described_class::EndpointNotPublicError)
+ end
+
+ # Through a proxy the proxy resolves the name, and the address checked here would
+ # mean nothing.
+ it 'refuses to go through a proxy' do
+ resolve_names('api.provider.example' => ['52.1.2.3'])
+ env = env_for('https://api.provider.example/v1')
+ env.request.proxy = { uri: URI('http://proxy.example:3128') }
+
+ expect { described_class.new(->(e) { e }).send(:net_http_connection, env) }
+ .to raise_error(described_class::EndpointNotPublicError)
+ end
+
+ it 'is a connection failure to every rescue that already handles one' do
+ expect(described_class::EndpointNotPublicError.ancestors).to include(Faraday::ConnectionFailed)
+ end
+ end
+
+ # End to end, with the real OpenAI client: a listener on loopback stands for a
+ # service on the app server, and a public-looking name resolves to it.
+ describe 'Lalabase::Llm::OpenAiCompatibleProvider at request time' do
+ let(:server) { TCPServer.new('127.0.0.1', 0) }
+ let(:accepted) { Queue.new }
+ let(:port) { server.addr[1] }
+
+ before do
+ resolve_names('inward.attacker.example' => ['127.0.0.1'])
+ @listener = Thread.new do
+ loop do
+ socket = server.accept
+ accepted << true
+ socket.close
+ end
+ end
+ end
+
+ after do
+ @listener.kill
+ server.close
+ end
+
+ def provider(endpoint, operator_endpoint:)
+ Lalabase::Llm::OpenAiCompatibleProvider.new(api_key: 'sk-customer', uri_base: endpoint,
+ chat_model: 'm', operator_endpoint: operator_endpoint)
+ end
+
+ it 'never opens a socket to an endpoint a customer typed that points inward' do
+ expect { provider("https://inward.attacker.example:#{port}/v1", operator_endpoint: false).connectivity_check }
+ .to raise_error(described_class::EndpointNotPublicError)
+
+ sleep 0.2
+ expect(accepted).to be_empty
+ end
+
+ # The other side: an endpoint the operator configured (a model server next to the
+ # app on a self-hosted instance) is not the customer's to choose and stays reachable.
+ # A literal, because this path does not ask Lalabase::PublicAddress and so does not
+ # see the names the spec resolver knows.
+ it 'still connects to an endpoint the operator configured' do
+ expect { provider("https://127.0.0.1:#{port}/v1", operator_endpoint: true).connectivity_check }
+ .to raise_error(StandardError)
+
+ expect(accepted.pop(timeout: 5)).to be(true)
+ end
+ end
+end
diff --git a/spec/services/lalabase/public_address_spec.rb b/spec/services/lalabase/public_address_spec.rb
new file mode 100644
index 0000000..5384254
--- /dev/null
+++ b/spec/services/lalabase/public_address_spec.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+# What: Unit spec for Lalabase::PublicAddress, the one owner of "does this host reach
+# the public internet?" for an address a customer types.
+# Why: the first version of the rule judged the characters in the field. Names with a
+# trailing dot (localhost.), short names of the server network (redis.) and public
+# names whose record points inward (a CNAME to 127.0.0.1 or to the cloud metadata
+# address) all passed it, and the connection test then reported which ports were
+# open. Every case below is decided on the addresses a resolver returns.
+
+require 'rails_helper'
+
+RSpec.describe Lalabase::PublicAddress, :ci_guard do
+ describe '.resolve!' do
+ it 'returns the addresses of a public name' do
+ resolve_names('api.provider.example' => ['52.1.2.3', '2606:4700:4700::1111'])
+
+ expect(described_class.resolve!('api.provider.example')).to eq(['52.1.2.3', '2606:4700:4700::1111'])
+ end
+
+ it 'returns a public literal unchanged' do
+ expect(described_class.resolve!('52.1.2.3')).to eq(['52.1.2.3'])
+ end
+
+ {
+ 'localhost.' => 'the trailing dot names the same host',
+ 'LOCALHOST' => 'case does not change a name',
+ 'redis.' => 'a short name of the server network',
+ 'localhost.attacker.example' => 'a public name whose record points at loopback',
+ 'awsmeta.attacker.example' => 'a public name whose record points at the metadata service',
+ 'cgnat.attacker.example' => 'carrier-grade NAT, which no IPAddr predicate reports',
+ 'mixed.attacker.example' => 'one inward address among public ones is enough'
+ }.each do |hostname, why|
+ it "refuses #{hostname} (#{why})" do
+ resolve_names(
+ 'redis' => ['192.168.0.1'],
+ 'localhost.attacker.example' => ['127.0.0.1', '::1'],
+ 'awsmeta.attacker.example' => ['169.254.169.254'],
+ 'cgnat.attacker.example' => ['100.64.0.1'],
+ 'mixed.attacker.example' => ['52.1.2.3', '192.168.0.1']
+ )
+
+ expect { described_class.resolve!(hostname) }.to raise_error(described_class::NotPublicError)
+ end
+ end
+
+ ['127.0.0.1', '::1', '10.0.0.5', '172.16.0.1', '192.168.0.1', '169.254.169.254',
+ '100.64.0.1', '0.0.0.0', '::', '::ffff:127.0.0.1', 'fd00::1', 'fe80::1',
+ '127.1', '2130706433', '0x7f.0.0.1', '0xa.0.0.5'].each do |literal|
+ it "refuses the literal #{literal}" do
+ expect { described_class.resolve!(literal) }.to raise_error(described_class::NotPublicError)
+ end
+ end
+
+ # Unresolvable and inward must read the same: a different answer for a name that
+ # does not exist would tell the caller which internal names do.
+ it 'refuses a name that does not resolve' do
+ described_class.resolver = ->(_hostname) { raise SocketError, 'getaddrinfo: nodename nor servname provided' }
+
+ expect { described_class.resolve!('nowhere.example') }.to raise_error(described_class::NotPublicError)
+ end
+
+ it 'refuses a name that resolves to nothing' do
+ described_class.resolver = ->(_hostname) { [] }
+
+ expect { described_class.resolve!('empty.example') }.to raise_error(described_class::NotPublicError)
+ end
+
+ it 'refuses a blank host' do
+ expect { described_class.resolve!('') }.to raise_error(described_class::NotPublicError)
+ end
+ end
+
+ describe '.public?' do
+ it 'is true for a public name and false for one that points inward' do
+ resolve_names('public.example' => ['52.1.2.3'], 'inward.example' => ['127.0.0.1'])
+
+ expect(described_class.public?('public.example')).to be(true)
+ expect(described_class.public?('inward.example')).to be(false)
+ end
+ end
+end
diff --git a/spec/support/public_address_resolver.rb b/spec/support/public_address_resolver.rb
new file mode 100644
index 0000000..6802e73
--- /dev/null
+++ b/spec/support/public_address_resolver.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+# Lalabase::PublicAddress resolves every host name it judges. A spec must not depend
+# on the DNS of the machine it runs on, so names resolve from a table here:
+#
+# * a numeric notation (127.1, 2130706433, 0x7f.0.0.1) goes to the real resolver
+# with AI_NUMERICHOST, which answers without the network, exactly as production
+# would;
+# * a name in the table gets the addresses listed there;
+# * any other name resolves to one public address from TEST-NET-3 (RFC 5737), so
+# the endpoints in the factories and specs (api.mistral.ai, sovereign.eu) keep
+# passing without a lookup.
+#
+# A spec that needs a name to point somewhere else says so:
+# resolve_names('localhost.attacker.example' => ['127.0.0.1', '::1'])
+module PublicAddressResolverHelpers
+ DEFAULT_PUBLIC_ADDRESS = '203.0.113.10'
+
+ DEFAULT_TABLE = {
+ 'localhost' => ['127.0.0.1', '::1'],
+ 'ip6-localhost' => ['::1']
+ }.freeze
+
+ def self.resolver_for(table)
+ lambda do |hostname|
+ numeric = numeric_addresses(hostname)
+ next numeric if numeric
+
+ name = hostname.downcase.delete_suffix('.')
+ table.fetch(name, [DEFAULT_PUBLIC_ADDRESS])
+ end
+ end
+
+ def self.numeric_addresses(hostname)
+ Addrinfo.getaddrinfo(hostname, nil, nil, :STREAM, nil, Socket::AI_NUMERICHOST).map(&:ip_address).uniq
+ rescue SocketError
+ nil
+ end
+
+ def resolve_names(table)
+ Lalabase::PublicAddress.resolver =
+ PublicAddressResolverHelpers.resolver_for(DEFAULT_TABLE.merge(table.transform_keys(&:downcase)))
+ end
+end
+
+RSpec.configure do |config|
+ config.include PublicAddressResolverHelpers
+
+ config.before do
+ Lalabase::PublicAddress.resolver = PublicAddressResolverHelpers.resolver_for(PublicAddressResolverHelpers::DEFAULT_TABLE)
+ end
+
+ config.after { Lalabase::PublicAddress.resolver = nil }
+end