From 69de0c655143c92c59913e164c100b4aff7ea16d Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Thu, 10 Sep 2026 04:49:34 +0000 Subject: [PATCH 01/12] feat(integrations): add OAuth refresh leases --- lib/kodo/integrations/integration.ex | 10 ++++++ ...refresh_claim_to_provider_integrations.exs | 36 +++++++++++++++++++ priv/repo/structure.sql | 18 ++++++++-- 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 priv/repo/migrations/20260910044734_add_refresh_claim_to_provider_integrations.exs diff --git a/lib/kodo/integrations/integration.ex b/lib/kodo/integrations/integration.ex index 2b0f0bc..2e80063 100644 --- a/lib/kodo/integrations/integration.ex +++ b/lib/kodo/integrations/integration.ex @@ -34,6 +34,10 @@ defmodule Kodo.Integrations.Integration do field :validated_at, :utc_datetime_usec field :refreshed_at, :utc_datetime_usec field :validation_error_code, :string + field :refresh_claim_owner_id, Ecto.UUID + field :refresh_claim_epoch, :integer, default: 0 + field :refresh_claim_generation, :integer + field :refresh_lease_expires_at, :utc_datetime_usec belongs_to :user, Kodo.Accounts.User, type: :id @@ -72,6 +76,12 @@ defmodule Kodo.Integrations.Integration do |> check_constraint(:credential_generation, name: :provider_integrations_credential_generation_valid ) + |> check_constraint(:refresh_claim_epoch, + name: :provider_integrations_refresh_claim_epoch_valid + ) + |> check_constraint(:refresh_claim_owner_id, + name: :provider_integrations_refresh_claim_valid + ) |> check_constraint(:connection_status, name: :provider_integrations_state_valid) |> check_constraint(:active, name: :provider_integrations_active_connected) |> unique_constraint(:active, name: :provider_integrations_one_active_index) diff --git a/priv/repo/migrations/20260910044734_add_refresh_claim_to_provider_integrations.exs b/priv/repo/migrations/20260910044734_add_refresh_claim_to_provider_integrations.exs new file mode 100644 index 0000000..09656a0 --- /dev/null +++ b/priv/repo/migrations/20260910044734_add_refresh_claim_to_provider_integrations.exs @@ -0,0 +1,36 @@ +defmodule Kodo.Repo.Migrations.AddRefreshClaimToProviderIntegrations do + use Ecto.Migration + + def change do + alter table(:provider_integrations) do + add :refresh_claim_owner_id, :binary_id + add :refresh_claim_epoch, :bigint, null: false, default: 0 + add :refresh_claim_generation, :bigint + add :refresh_lease_expires_at, :utc_datetime_usec + end + + create index(:provider_integrations, [:refresh_lease_expires_at], + where: "refresh_claim_owner_id IS NOT NULL", + name: :provider_integrations_refresh_lease_index + ) + + create constraint(:provider_integrations, :provider_integrations_refresh_claim_epoch_valid, + check: "refresh_claim_epoch >= 0" + ) + + create constraint(:provider_integrations, :provider_integrations_refresh_claim_valid, + check: """ + ( + refresh_claim_owner_id IS NULL AND + refresh_claim_generation IS NULL AND + refresh_lease_expires_at IS NULL + ) OR ( + refresh_claim_owner_id IS NOT NULL AND + refresh_claim_generation IS NOT NULL AND + refresh_claim_generation >= 0 AND + refresh_lease_expires_at IS NOT NULL + ) + """ + ) + end +end diff --git a/priv/repo/structure.sql b/priv/repo/structure.sql index ba404cc..bef1f4c 100644 --- a/priv/repo/structure.sql +++ b/priv/repo/structure.sql @@ -2,7 +2,7 @@ -- PostgreSQL database dump -- -\restrict XOpxqSYwtvGfTiqRIBStCvyZpzZaCE6LIgMjOIQHCBPW9ZYUkI1mr4M5q3RWTPU +\restrict VoWETYGZi4vEwyliUNWQG3BVneag5OunvKzcS2NOBFzVtuTzyBWpDfhYIneu2ek -- Dumped from database version 15.19 (Debian 15.19-0+deb12u1) -- Dumped by pg_dump version 15.19 (Debian 15.19-0+deb12u1) @@ -183,11 +183,17 @@ CREATE TABLE public.provider_integrations ( updated_at timestamp without time zone NOT NULL, display_name character varying(80) NOT NULL, active boolean DEFAULT false NOT NULL, + refresh_claim_owner_id uuid, + refresh_claim_epoch bigint DEFAULT 0 NOT NULL, + refresh_claim_generation bigint, + refresh_lease_expires_at timestamp without time zone, CONSTRAINT provider_integrations_active_connected CHECK (((NOT active) OR ((connection_status)::text = 'connected'::text))), CONSTRAINT provider_integrations_authentication_type_valid CHECK (((authentication_type)::text = ANY ((ARRAY['api_key'::character varying, 'oauth'::character varying])::text[]))), CONSTRAINT provider_integrations_credential_generation_valid CHECK ((credential_generation >= 0)), CONSTRAINT provider_integrations_provider_authentication_valid CHECK (((((provider)::text = 'openai_codex'::text) AND ((authentication_type)::text = 'oauth'::text)) OR (((provider)::text = ANY ((ARRAY['openai'::character varying, 'anthropic'::character varying, 'openrouter'::character varying])::text[])) AND ((authentication_type)::text = 'api_key'::text)))), CONSTRAINT provider_integrations_provider_valid CHECK (((provider)::text = ANY ((ARRAY['openai'::character varying, 'openai_codex'::character varying, 'anthropic'::character varying, 'openrouter'::character varying])::text[]))), + CONSTRAINT provider_integrations_refresh_claim_epoch_valid CHECK ((refresh_claim_epoch >= 0)), + CONSTRAINT provider_integrations_refresh_claim_valid CHECK ((((refresh_claim_owner_id IS NULL) AND (refresh_claim_generation IS NULL) AND (refresh_lease_expires_at IS NULL)) OR ((refresh_claim_owner_id IS NOT NULL) AND (refresh_claim_generation IS NOT NULL) AND (refresh_claim_generation >= 0) AND (refresh_lease_expires_at IS NOT NULL)))), CONSTRAINT provider_integrations_state_valid CHECK (((((connection_status)::text = 'disconnected'::text) AND ((validation_status)::text = 'unverified'::text) AND (encrypted_credentials IS NULL) AND (encryption_key_version IS NULL) AND (credential_format_version IS NULL) AND (expires_at IS NULL) AND (validated_at IS NULL) AND (refreshed_at IS NULL) AND (validation_error_code IS NULL)) OR (((connection_status)::text = 'connected'::text) AND ((validation_status)::text = ANY ((ARRAY['unverified'::character varying, 'valid'::character varying, 'invalid'::character varying, 'unavailable'::character varying])::text[])) AND (encrypted_credentials IS NOT NULL) AND (encryption_key_version IS NOT NULL) AND (credential_format_version IS NOT NULL)) OR (((connection_status)::text = 'reauthorization_required'::text) AND ((validation_status)::text = 'unverified'::text) AND (encrypted_credentials IS NOT NULL) AND (encryption_key_version IS NOT NULL) AND (credential_format_version IS NOT NULL)))) ); @@ -553,6 +559,13 @@ CREATE UNIQUE INDEX provider_integrations_attempt_owner_identity_index ON public CREATE UNIQUE INDEX provider_integrations_one_active_index ON public.provider_integrations USING btree (user_id, provider) WHERE active; +-- +-- Name: provider_integrations_refresh_lease_index; Type: INDEX; Schema: public; Owner: - +-- + +CREATE INDEX provider_integrations_refresh_lease_index ON public.provider_integrations USING btree (refresh_lease_expires_at) WHERE (refresh_claim_owner_id IS NOT NULL); + + -- -- Name: provider_integrations_user_id_provider_index; Type: INDEX; Schema: public; Owner: - -- @@ -767,7 +780,7 @@ ALTER TABLE ONLY public.users_tokens -- PostgreSQL database dump complete -- -\unrestrict XOpxqSYwtvGfTiqRIBStCvyZpzZaCE6LIgMjOIQHCBPW9ZYUkI1mr4M5q3RWTPU +\unrestrict VoWETYGZi4vEwyliUNWQG3BVneag5OunvKzcS2NOBFzVtuTzyBWpDfhYIneu2ek INSERT INTO public."schema_migrations" (version) VALUES (20260807073017); INSERT INTO public."schema_migrations" (version) VALUES (20260808062115); @@ -786,3 +799,4 @@ INSERT INTO public."schema_migrations" (version) VALUES (20260903201206); INSERT INTO public."schema_migrations" (version) VALUES (20260904051620); INSERT INTO public."schema_migrations" (version) VALUES (20260907083117); INSERT INTO public."schema_migrations" (version) VALUES (20260907161929); +INSERT INTO public."schema_migrations" (version) VALUES (20260910044734); From 9b30beb723ae8206fefe1fd9cb0c83e59902a084 Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Thu, 10 Sep 2026 04:52:02 +0000 Subject: [PATCH 02/12] feat(integrations): coordinate OAuth refresh claims --- lib/kodo/integrations.ex | 98 ++++++++++++++++++++++++++++- test/kodo/integrations_test.exs | 108 ++++++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+), 3 deletions(-) diff --git a/lib/kodo/integrations.ex b/lib/kodo/integrations.ex index f52226c..f746477 100644 --- a/lib/kodo/integrations.ex +++ b/lib/kodo/integrations.ex @@ -27,6 +27,7 @@ defmodule Kodo.Integrations do @device_authorization_token_max_bytes 8_192 @device_authorization_cleanup_age_seconds 24 * 60 * 60 @device_authorization_claim_lease_ms 30_000 + @refresh_claim_lease_ms 30_000 @device_authorization_terminal_errors ~w( provider_unavailable provider_rejected @@ -393,6 +394,62 @@ defmodule Kodo.Integrations do ) end + @doc "Claims one generation of an OAuth integration for a bounded refresh operation." + def claim_refresh(%Scope{user: user}, id, generation, claim_owner_id) + when is_integer(generation) and generation >= 0 do + with {:ok, id} <- cast_uuid(id), + {:ok, claim_owner_id} <- cast_uuid(claim_owner_id) do + lease_expires_at = + DateTime.add(database_now(), @refresh_claim_lease_ms, :millisecond) + + query = + from integration in Integration, + where: + integration.id == ^id and integration.user_id == ^user.id and + integration.provider == "openai_codex" and + integration.authentication_type == "oauth" and + integration.connection_status in ["connected", "reauthorization_required"] and + integration.credential_generation == ^generation and + (is_nil(integration.refresh_claim_owner_id) or + integration.refresh_lease_expires_at <= fragment("clock_timestamp()")) + + updates = [ + set: [ + refresh_claim_owner_id: claim_owner_id, + refresh_claim_generation: generation, + refresh_lease_expires_at: lease_expires_at, + updated_at: now() + ], + inc: [refresh_claim_epoch: 1] + ] + + case Repo.update_all(query, updates) do + {1, nil} -> {:ok, Repo.get_by!(Integration, id: id, user_id: user.id)} + {0, nil} -> refresh_claim_conflict(user.id, id, generation) + end + end + end + + def claim_refresh(%Scope{}, _id, _generation, _claim_owner_id), + do: {:error, :stale_credential_generation} + + @doc "Releases only the exact refresh claim represented by the supplied snapshot." + def release_refresh_claim(%Scope{user: user}, %Integration{} = claim) do + query = exact_refresh_claim_query(user.id, claim) + + case Repo.update_all(query, + set: [ + refresh_claim_owner_id: nil, + refresh_claim_generation: nil, + refresh_lease_expires_at: nil, + updated_at: now() + ] + ) do + {1, nil} -> :ok + {0, nil} -> {:error, :stale_refresh_claim} + end + end + def validation_succeeded(%Scope{} = scope, id, generation) do update_fenced(scope, id, generation, ["connected"], "validation_succeeded", %{ validation_status: "valid", @@ -455,7 +512,10 @@ defmodule Kodo.Integrations do expires_at: nil, validated_at: nil, refreshed_at: nil, - validation_error_code: nil + validation_error_code: nil, + refresh_claim_owner_id: nil, + refresh_claim_generation: nil, + refresh_lease_expires_at: nil } ) |> notify_integration_change() @@ -914,7 +974,13 @@ defmodule Kodo.Integrations do end defp device_authorization_integration_changes(%Integration{}, generation, timestamp) do - [credential_generation: generation, updated_at: timestamp] + [ + credential_generation: generation, + refresh_claim_owner_id: nil, + refresh_claim_generation: nil, + refresh_lease_expires_at: nil, + updated_at: timestamp + ] end defp supersede_active_device_authorization(integration_id, timestamp) do @@ -1086,7 +1152,10 @@ defmodule Kodo.Integrations do expires_at: opts[:expires_at], validated_at: nil, refreshed_at: opts[:refreshed_at], - validation_error_code: nil + validation_error_code: nil, + refresh_claim_owner_id: nil, + refresh_claim_generation: nil, + refresh_lease_expires_at: nil }) update_fenced(scope, id, generation, allowed_connections, audit_event_type, changes) @@ -1106,6 +1175,29 @@ defmodule Kodo.Integrations do defp require_connected(%Integration{connection_status: "connected"}), do: :ok defp require_connected(%Integration{}), do: {:error, :integration_not_connected} + defp refresh_claim_conflict(user_id, id, generation) do + case Repo.get_by(Integration, id: id, user_id: user_id) do + %Integration{credential_generation: ^generation, refresh_claim_owner_id: owner} + when not is_nil(owner) -> + {:error, :refresh_in_progress} + + %Integration{} -> + {:error, :stale_credential_generation} + + nil -> + {:error, :integration_not_found} + end + end + + defp exact_refresh_claim_query(user_id, %Integration{} = claim) do + from integration in Integration, + where: + integration.id == ^claim.id and integration.user_id == ^user_id and + integration.credential_generation == ^claim.refresh_claim_generation and + integration.refresh_claim_owner_id == ^claim.refresh_claim_owner_id and + integration.refresh_claim_epoch == ^claim.refresh_claim_epoch + end + defp lock_provider_integrations(user_id, integration_id) do provider = Integration diff --git a/test/kodo/integrations_test.exs b/test/kodo/integrations_test.exs index 9780eed..bb9022b 100644 --- a/test/kodo/integrations_test.exs +++ b/test/kodo/integrations_test.exs @@ -258,6 +258,114 @@ defmodule Kodo.IntegrationsTest do |> then(fn {:ok, payload} -> {:ok, Map.take(payload, ["access_token"])} end) end + test "claims one OAuth refresh generation and fences release across takeover", %{scope: scope} do + integration = oauth_integration(scope) + + assert {:ok, connected} = + Integrations.oauth_succeeded(scope, integration.id, 0, %{ + "access_token" => "old-access", + "refresh_token" => "old-refresh", + "account_id" => "account" + }) + + first_owner = Ecto.UUID.generate() + second_owner = Ecto.UUID.generate() + + assert {:ok, first_claim} = + Integrations.claim_refresh( + scope, + connected.id, + connected.credential_generation, + first_owner + ) + + assert first_claim.refresh_claim_owner_id == first_owner + assert first_claim.refresh_claim_generation == connected.credential_generation + assert first_claim.refresh_claim_epoch == 1 + + assert {:error, :refresh_in_progress} = + Integrations.claim_refresh( + scope, + connected.id, + connected.credential_generation, + second_owner + ) + + Repo.update!( + change(first_claim, + refresh_lease_expires_at: DateTime.add(DateTime.utc_now(), -1, :second) + ) + ) + + assert {:ok, second_claim} = + Integrations.claim_refresh( + scope, + connected.id, + connected.credential_generation, + second_owner + ) + + assert second_claim.refresh_claim_epoch == 2 + + assert {:error, :stale_refresh_claim} = + Integrations.release_refresh_claim(scope, first_claim) + + assert :ok = Integrations.release_refresh_claim(scope, second_claim) + + released = Repo.reload!(connected) + assert is_nil(released.refresh_claim_owner_id) + assert is_nil(released.refresh_claim_generation) + assert is_nil(released.refresh_lease_expires_at) + assert released.refresh_claim_epoch == 2 + end + + test "a credential-generation transition clears and permanently fences a refresh claim", %{ + scope: scope + } do + integration = oauth_integration(scope) + + assert {:ok, connected} = + Integrations.oauth_succeeded(scope, integration.id, 0, %{ + "access_token" => "old-access", + "refresh_token" => "old-refresh", + "account_id" => "account" + }) + + assert {:ok, claim} = + Integrations.claim_refresh( + scope, + connected.id, + connected.credential_generation, + Ecto.UUID.generate() + ) + + assert {:ok, _attempt} = + Integrations.begin_device_authorization( + scope, + connected.id, + connected.credential_generation, + %{"device_auth_id" => "device", "user_code" => "CODE"}, + 0 + ) + + fenced = Repo.reload!(connected) + assert fenced.credential_generation == connected.credential_generation + 1 + assert is_nil(fenced.refresh_claim_owner_id) + assert {:error, :stale_refresh_claim} = Integrations.release_refresh_claim(scope, claim) + + assert {:error, :stale_credential_generation} = + Integrations.refresh_succeeded( + scope, + connected.id, + claim.refresh_claim_generation, + %{ + "access_token" => "late-access", + "refresh_token" => "late-refresh", + "account_id" => "account" + } + ) + end + test "activates only the first OAuth account after authorization", %{scope: scope} do first = oauth_integration(scope) From d142e742f7abc9e1411fec5b040838ad27cfbb15 Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Thu, 10 Sep 2026 04:53:14 +0000 Subject: [PATCH 03/12] refactor(integrations): share OAuth credential transport --- ...ion_req_adapter.ex => credential_req_adapter.ex} | 8 ++++---- .../integrations/req_device_authorization_client.ex | 12 ++++++------ ...ter_test.exs => credential_req_adapter_test.exs} | 13 ++++++------- .../req_device_authorization_client_test.exs | 8 ++++---- 4 files changed, 20 insertions(+), 21 deletions(-) rename lib/kodo/integrations/{device_authorization_req_adapter.ex => credential_req_adapter.ex} (93%) rename test/kodo/integrations/{device_authorization_req_adapter_test.exs => credential_req_adapter_test.exs} (51%) diff --git a/lib/kodo/integrations/device_authorization_req_adapter.ex b/lib/kodo/integrations/credential_req_adapter.ex similarity index 93% rename from lib/kodo/integrations/device_authorization_req_adapter.ex rename to lib/kodo/integrations/credential_req_adapter.ex index 5756a83..406416a 100644 --- a/lib/kodo/integrations/device_authorization_req_adapter.ex +++ b/lib/kodo/integrations/credential_req_adapter.ex @@ -1,6 +1,6 @@ -defmodule Kodo.Integrations.DeviceAuthorizationReqAdapter do +defmodule Kodo.Integrations.CredentialReqAdapter do @moduledoc """ - Req adapter for credential-bearing device authorization requests. + Req adapter for credential-bearing OAuth requests. It deliberately uses Mint directly: Finch telemetry includes request and response values, which are secrets throughout this protocol. @@ -10,7 +10,7 @@ defmodule Kodo.Integrations.DeviceAuthorizationReqAdapter do @max_response_bytes 64 * 1024 def run(%Req.Request{} = request) do - timeout = request.options[:device_authorization_timeout] || @default_timeout + timeout = request.options[:credential_request_timeout] || @default_timeout started_at = System.monotonic_time(:millisecond) task = Task.async(fn -> safe_perform(request, started_at, timeout) end) @@ -30,7 +30,7 @@ defmodule Kodo.Integrations.DeviceAuthorizationReqAdapter do end defp perform( - %Req.Request{options: %{device_authorization_transport: transport}} = request, + %Req.Request{options: %{credential_request_transport: transport}} = request, started_at, timeout ) diff --git a/lib/kodo/integrations/req_device_authorization_client.ex b/lib/kodo/integrations/req_device_authorization_client.ex index 5b3ecd2..bdf8b61 100644 --- a/lib/kodo/integrations/req_device_authorization_client.ex +++ b/lib/kodo/integrations/req_device_authorization_client.ex @@ -134,25 +134,25 @@ defmodule Kodo.Integrations.ReqDeviceAuthorizationClient do req_options = Keyword.take(req_options, [ :plug, - :device_authorization_transport, - :device_authorization_timeout + :credential_request_transport, + :credential_request_timeout ]) options = [ url: url, - adapter: Kodo.Integrations.DeviceAuthorizationReqAdapter, + adapter: Kodo.Integrations.CredentialReqAdapter, redirect: false, retry: false, decode_body: false, - device_authorization_timeout: @timeout + credential_request_timeout: @timeout ] ++ request_options ++ req_options request = Req.new() |> Req.Request.register_options([ - :device_authorization_timeout, - :device_authorization_transport + :credential_request_timeout, + :credential_request_transport ]) case Req.post(request, options) do diff --git a/test/kodo/integrations/device_authorization_req_adapter_test.exs b/test/kodo/integrations/credential_req_adapter_test.exs similarity index 51% rename from test/kodo/integrations/device_authorization_req_adapter_test.exs rename to test/kodo/integrations/credential_req_adapter_test.exs index d623971..d495dce 100644 --- a/test/kodo/integrations/device_authorization_req_adapter_test.exs +++ b/test/kodo/integrations/credential_req_adapter_test.exs @@ -1,19 +1,18 @@ -defmodule Kodo.Integrations.DeviceAuthorizationReqAdapterTest do +defmodule Kodo.Integrations.CredentialReqAdapterTest do use ExUnit.Case, async: true - alias Kodo.Integrations.DeviceAuthorizationReqAdapter + alias Kodo.Integrations.CredentialReqAdapter test "builds origin-form request targets for every device authorization endpoint" do - assert DeviceAuthorizationReqAdapter.request_target( + assert CredentialReqAdapter.request_target( URI.parse("https://auth.openai.com/api/accounts/deviceauth/usercode") ) == "/api/accounts/deviceauth/usercode" - assert DeviceAuthorizationReqAdapter.request_target( + assert CredentialReqAdapter.request_target( URI.parse("https://auth.openai.com/api/accounts/deviceauth/token?attempt=1") ) == "/api/accounts/deviceauth/token?attempt=1" - assert DeviceAuthorizationReqAdapter.request_target( - URI.parse("https://auth.openai.com/oauth/token") - ) == "/oauth/token" + assert CredentialReqAdapter.request_target(URI.parse("https://auth.openai.com/oauth/token")) == + "/oauth/token" end end diff --git a/test/kodo/integrations/req_device_authorization_client_test.exs b/test/kodo/integrations/req_device_authorization_client_test.exs index e281d43..c8fca92 100644 --- a/test/kodo/integrations/req_device_authorization_client_test.exs +++ b/test/kodo/integrations/req_device_authorization_client_test.exs @@ -199,7 +199,7 @@ defmodule Kodo.Integrations.ReqDeviceAuthorizationClientTest do end assert {:error, :provider_unavailable} = - ReqDeviceAuthorizationClient.create(device_authorization_transport: transport) + ReqDeviceAuthorizationClient.create(credential_request_transport: transport) end test "accepts device fields at 1024 bytes and rejects 1025 bytes" do @@ -274,7 +274,7 @@ defmodule Kodo.Integrations.ReqDeviceAuthorizationClientTest do assert {:ok, %{"authorization_code" => ^sentinel}} = ReqDeviceAuthorizationClient.poll( %{"device_auth_id" => sentinel, "user_code" => sentinel}, - device_authorization_transport: transport + credential_request_transport: transport ) refute_receive {:finch_telemetry, _event, _measurements, _metadata} @@ -299,8 +299,8 @@ defmodule Kodo.Integrations.ReqDeviceAuthorizationClientTest do assert {:error, :provider_unavailable} = ReqDeviceAuthorizationClient.create( - device_authorization_transport: transport, - device_authorization_timeout: 10 + credential_request_transport: transport, + credential_request_timeout: 10 ) assert_received :transport_started From 64539d09a93f2bab7059e45c2fb7aa9cc2510100 Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Thu, 10 Sep 2026 04:55:01 +0000 Subject: [PATCH 04/12] feat(integrations): add Codex refresh client --- lib/kodo/integrations/refresh_client.ex | 5 + lib/kodo/integrations/req_refresh_client.ex | 85 +++++++++++++++++ .../integrations/req_refresh_client_test.exs | 94 +++++++++++++++++++ 3 files changed, 184 insertions(+) create mode 100644 lib/kodo/integrations/refresh_client.ex create mode 100644 lib/kodo/integrations/req_refresh_client.ex create mode 100644 test/kodo/integrations/req_refresh_client_test.exs diff --git a/lib/kodo/integrations/refresh_client.ex b/lib/kodo/integrations/refresh_client.ex new file mode 100644 index 0000000..2507453 --- /dev/null +++ b/lib/kodo/integrations/refresh_client.ex @@ -0,0 +1,5 @@ +defmodule Kodo.Integrations.RefreshClient do + @moduledoc false + + @callback refresh(String.t(), keyword()) :: {:ok, map()} | {:error, atom()} +end diff --git a/lib/kodo/integrations/req_refresh_client.ex b/lib/kodo/integrations/req_refresh_client.ex new file mode 100644 index 0000000..5e01825 --- /dev/null +++ b/lib/kodo/integrations/req_refresh_client.ex @@ -0,0 +1,85 @@ +defmodule Kodo.Integrations.ReqRefreshClient do + @moduledoc "Performs the pinned OpenAI Codex refresh-token contract." + + @behaviour Kodo.Integrations.RefreshClient + + @client_id "app_EMoamEEZ73f0CkXaXp7hrann" + @token_url "https://auth.openai.com/oauth/token" + @timeout 10_000 + @max_response_bytes 8_192 + + @impl true + def refresh(refresh_token, req_options \\ []) + + def refresh(refresh_token, req_options) + when is_binary(refresh_token) and byte_size(refresh_token) > 0 and + byte_size(refresh_token) <= @max_response_bytes and is_list(req_options) do + options = + [ + url: @token_url, + json: %{ + client_id: @client_id, + grant_type: "refresh_token", + refresh_token: refresh_token + }, + adapter: Kodo.Integrations.CredentialReqAdapter, + redirect: false, + retry: false, + decode_body: false, + credential_request_timeout: @timeout + ] ++ + Keyword.take(req_options, [ + :plug, + :credential_request_transport, + :credential_request_timeout + ]) + + request = + Req.new() + |> Req.Request.register_options([ + :credential_request_timeout, + :credential_request_transport + ]) + + case Req.post(request, options) do + {:ok, %Req.Response{status: status, body: body}} when status in 200..299 -> + decode_success(body) + + {:ok, %Req.Response{status: 400, body: body}} -> + if invalid_grant?(body), + do: {:error, :invalid_grant}, + else: {:error, :provider_unavailable} + + {:ok, %Req.Response{status: status}} when status in 300..399 -> + {:error, :redirect} + + {:ok, %Req.Response{}} -> + {:error, :provider_unavailable} + + {:error, _reason} -> + {:error, :provider_unavailable} + end + end + + def refresh(_refresh_token, _req_options), do: {:error, :oauth_refresh_response_invalid} + + defp decode_success(body) do + with {:ok, decoded} when is_map(decoded) <- decode_json(body), + access_token when is_binary(access_token) and byte_size(access_token) > 0 <- + decoded["access_token"] do + {:ok, decoded} + else + _invalid -> {:error, :oauth_refresh_response_invalid} + end + end + + defp invalid_grant?(body) do + case decode_json(body) do + {:ok, %{"error" => "invalid_grant"}} -> true + _other -> false + end + end + + defp decode_json(body) when is_binary(body), do: Jason.decode(body) + defp decode_json(_body), do: {:error, :invalid_body} +end diff --git a/test/kodo/integrations/req_refresh_client_test.exs b/test/kodo/integrations/req_refresh_client_test.exs new file mode 100644 index 0000000..53a7b58 --- /dev/null +++ b/test/kodo/integrations/req_refresh_client_test.exs @@ -0,0 +1,94 @@ +defmodule Kodo.Integrations.ReqRefreshClientTest do + use ExUnit.Case, async: true + + alias Kodo.Integrations.ReqRefreshClient + + @client_id "app_EMoamEEZ73f0CkXaXp7hrann" + + test "refreshes at the pinned endpoint with the published contract" do + plug = fn conn -> + assert conn.method == "POST" + assert conn.scheme == :https + assert conn.host == "auth.openai.com" + assert conn.request_path == "/oauth/token" + + assert json_body(conn) == %{ + "client_id" => @client_id, + "grant_type" => "refresh_token", + "refresh_token" => "refresh-secret" + } + + Req.Test.json(conn, %{ + "access_token" => "access-secret", + "refresh_token" => "rotated-secret", + "id_token" => "identity-secret" + }) + end + + assert {:ok, %{"access_token" => "access-secret"}} = + ReqRefreshClient.refresh("refresh-secret", plug: plug) + end + + test "classifies only an exact invalid_grant response as invalid credentials" do + invalid_grant = fn conn -> + conn |> Plug.Conn.put_status(400) |> Req.Test.json(%{"error" => "invalid_grant"}) + end + + assert {:error, :invalid_grant} = + ReqRefreshClient.refresh("refresh-secret", plug: invalid_grant) + + for body <- [%{"error" => "temporarily_unavailable"}, %{"message" => "invalid_grant"}] do + plug = fn conn -> conn |> Plug.Conn.put_status(400) |> Req.Test.json(body) end + + assert {:error, :provider_unavailable} = + ReqRefreshClient.refresh("refresh-secret", plug: plug) + end + end + + test "rejects redirects, malformed success, and unsafe caller input with bounded errors" do + redirect = fn conn -> Plug.Conn.send_resp(conn, 302, "private") end + malformed = fn conn -> Req.Test.json(conn, %{"refresh_token" => "private"}) end + + assert {:error, :redirect} = ReqRefreshClient.refresh("refresh-secret", plug: redirect) + + assert {:error, :oauth_refresh_response_invalid} = + ReqRefreshClient.refresh("refresh-secret", plug: malformed) + + assert {:error, :oauth_refresh_response_invalid} = ReqRefreshClient.refresh("") + assert {:error, :oauth_refresh_response_invalid} = ReqRefreshClient.refresh(:secret) + end + + test "uses the credential transport without emitting Finch telemetry" do + test_pid = self() + handler_id = "refresh-finch-canary-#{System.unique_integer()}" + + :ok = + :telemetry.attach_many( + handler_id, + [[:finch, :request, :start], [:finch, :request, :stop], [:finch, :request, :exception]], + fn event, measurements, metadata, pid -> + send(pid, {:finch_telemetry, event, measurements, metadata}) + end, + test_pid + ) + + on_exit(fn -> :telemetry.detach(handler_id) end) + + transport = fn request, _started_at, _timeout -> + assert IO.iodata_to_binary(request.body) =~ "refresh-secret" + + {request, + Req.Response.new(status: 200, body: Jason.encode!(%{"access_token" => "access-secret"}))} + end + + assert {:ok, _tokens} = + ReqRefreshClient.refresh("refresh-secret", credential_request_transport: transport) + + refute_receive {:finch_telemetry, _event, _measurements, _metadata} + end + + defp json_body(conn) do + {:ok, body, _conn} = Plug.Conn.read_body(conn) + Jason.decode!(body) + end +end From a0c32e2d9506b8be99e81e971b1f3e167cade593 Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Thu, 10 Sep 2026 04:56:59 +0000 Subject: [PATCH 05/12] feat(integrations): normalize rotated OAuth tokens --- lib/kodo/integrations/refresh_tokens.ex | 91 +++++++++++++++++++ .../kodo/integrations/refresh_tokens_test.exs | 82 +++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 lib/kodo/integrations/refresh_tokens.ex create mode 100644 test/kodo/integrations/refresh_tokens_test.exs diff --git a/lib/kodo/integrations/refresh_tokens.ex b/lib/kodo/integrations/refresh_tokens.ex new file mode 100644 index 0000000..74df26e --- /dev/null +++ b/lib/kodo/integrations/refresh_tokens.ex @@ -0,0 +1,91 @@ +defmodule Kodo.Integrations.RefreshTokens do + @moduledoc false + + @account_claim "https://api.openai.com/auth" + @max_token_bytes 8_192 + + def normalize(response, current, now \\ DateTime.utc_now()) + + def normalize(response, current, %DateTime{} = now) + when is_map(response) and is_map(current) do + with {:ok, access_token} <- token(response, "access_token"), + {:ok, expires_at} <- access_expiry(access_token, now), + {:ok, refresh_token} <- optional_token(response, current, "refresh_token"), + {:ok, id_token} <- optional_token(response, current, "id_token"), + {:ok, current_account_id} <- token(current, "account_id"), + {:ok, account_id} <- account_id(response, id_token, current_account_id), + true <- account_id == current_account_id do + {:ok, + %{ + credentials: %{ + "access_token" => access_token, + "refresh_token" => refresh_token, + "id_token" => id_token, + "account_id" => account_id + }, + expires_at: expires_at + }} + else + false -> {:error, :refresh_account_identity_mismatch} + {:error, _reason} = error -> error + end + end + + def normalize(_response, _current, _now), do: {:error, :oauth_refresh_response_invalid} + + defp account_id(response, id_token, current_account_id) do + if Map.has_key?(response, "id_token") do + with {:ok, claims} <- jwt_claims(id_token), + %{"chatgpt_account_id" => account_id} <- claims[@account_claim], + :ok <- valid_token(account_id) do + {:ok, account_id} + else + _invalid -> {:error, :oauth_refresh_response_invalid} + end + else + {:ok, current_account_id} + end + end + + defp access_expiry(access_token, now) do + with {:ok, %{"exp" => unix}} when is_integer(unix) <- jwt_claims(access_token), + {:ok, expires_at} <- DateTime.from_unix(unix), + true <- DateTime.after?(expires_at, now) do + {:ok, %{expires_at | microsecond: {0, 6}}} + else + _invalid -> {:error, :oauth_refresh_response_invalid} + end + end + + defp optional_token(response, current, field) do + case Map.fetch(response, field) do + {:ok, value} -> checked_token(value) + :error -> token(current, field) + end + end + + defp token(payload, field), do: payload |> Map.get(field) |> checked_token() + + defp checked_token(value) do + case valid_token(value) do + :ok -> {:ok, value} + :error -> {:error, :oauth_refresh_response_invalid} + end + end + + defp valid_token(value) + when is_binary(value) and byte_size(value) > 0 and byte_size(value) <= @max_token_bytes, + do: :ok + + defp valid_token(_value), do: :error + + defp jwt_claims(token) do + with [_header, payload, _signature] <- String.split(token, "."), + {:ok, json} <- Base.url_decode64(payload, padding: false), + {:ok, claims} when is_map(claims) <- Jason.decode(json) do + {:ok, claims} + else + _invalid -> {:error, :oauth_refresh_response_invalid} + end + end +end diff --git a/test/kodo/integrations/refresh_tokens_test.exs b/test/kodo/integrations/refresh_tokens_test.exs new file mode 100644 index 0000000..ef8df2a --- /dev/null +++ b/test/kodo/integrations/refresh_tokens_test.exs @@ -0,0 +1,82 @@ +defmodule Kodo.Integrations.RefreshTokensTest do + use ExUnit.Case, async: true + + alias Kodo.Integrations.RefreshTokens + + test "requires a future access expiry and retains omitted rotated fields" do + now = ~U[2026-09-10 05:00:00.000000Z] + current = current_tokens() + + assert {:ok, normalized} = + RefreshTokens.normalize( + %{"access_token" => jwt(%{"exp" => DateTime.to_unix(now) + 60})}, + current, + now + ) + + assert normalized.credentials["refresh_token"] == current["refresh_token"] + assert normalized.credentials["id_token"] == current["id_token"] + assert normalized.credentials["account_id"] == "account" + assert normalized.expires_at == ~U[2026-09-10 05:01:00.000000Z] + + assert {:error, :oauth_refresh_response_invalid} = + RefreshTokens.normalize( + %{"access_token" => jwt(%{"exp" => DateTime.to_unix(now)})}, + current, + now + ) + end + + test "persists rotated refresh and identity tokens without changing billing identity" do + now = ~U[2026-09-10 05:00:00.000000Z] + rotated_id = id_token("account") + + assert {:ok, normalized} = + RefreshTokens.normalize( + %{ + "access_token" => jwt(%{"exp" => DateTime.to_unix(now) + 60}), + "refresh_token" => "rotated-refresh", + "id_token" => rotated_id + }, + current_tokens(), + now + ) + + assert normalized.credentials["refresh_token"] == "rotated-refresh" + assert normalized.credentials["id_token"] == rotated_id + end + + test "rejects an account identity change and malformed returned identity token" do + response = %{ + "access_token" => jwt(%{"exp" => DateTime.utc_now() |> DateTime.to_unix() |> Kernel.+(60)}), + "id_token" => id_token("other-account") + } + + assert {:error, :refresh_account_identity_mismatch} = + RefreshTokens.normalize(response, current_tokens()) + + assert {:error, :oauth_refresh_response_invalid} = + RefreshTokens.normalize( + %{response | "id_token" => "malformed"}, + current_tokens() + ) + end + + defp current_tokens do + %{ + "access_token" => "old-access", + "refresh_token" => "old-refresh", + "id_token" => id_token("account"), + "account_id" => "account" + } + end + + defp id_token(account_id) do + jwt(%{"https://api.openai.com/auth" => %{"chatgpt_account_id" => account_id}}) + end + + defp jwt(claims) do + encoded = claims |> Jason.encode!() |> Base.url_encode64(padding: false) + "header.#{encoded}.signature" + end +end From 82d7d2a75836586b9ee4c9053b9b1fcf68903d80 Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Thu, 10 Sep 2026 05:04:18 +0000 Subject: [PATCH 06/12] feat(integrations): refresh OAuth credentials just in time --- lib/kodo/integrations.ex | 33 ++- lib/kodo/integrations/audit_event.ex | 1 + lib/kodo/integrations/oauth_refresh.ex | 183 ++++++++++++++ lib/kodo/llm.ex | 3 +- lib/kodo/llm/credential_resolver.ex | 2 + lib/kodo/llm/provider_error.ex | 4 +- test/kodo/integrations/oauth_refresh_test.exs | 232 ++++++++++++++++++ test/kodo/llm/credential_resolver_test.exs | 16 +- test/support/fake_refresh_client.ex | 15 ++ 9 files changed, 481 insertions(+), 8 deletions(-) create mode 100644 lib/kodo/integrations/oauth_refresh.ex create mode 100644 test/kodo/integrations/oauth_refresh_test.exs create mode 100644 test/support/fake_refresh_client.ex diff --git a/lib/kodo/integrations.ex b/lib/kodo/integrations.ex index f746477..765fca9 100644 --- a/lib/kodo/integrations.ex +++ b/lib/kodo/integrations.ex @@ -408,7 +408,7 @@ defmodule Kodo.Integrations do integration.id == ^id and integration.user_id == ^user.id and integration.provider == "openai_codex" and integration.authentication_type == "oauth" and - integration.connection_status in ["connected", "reauthorization_required"] and + integration.connection_status == "connected" and integration.credential_generation == ^generation and (is_nil(integration.refresh_claim_owner_id) or integration.refresh_lease_expires_at <= fragment("clock_timestamp()")) @@ -450,6 +450,37 @@ defmodule Kodo.Integrations do end end + def require_refresh_reauthorization(%Scope{user: user}, %Integration{} = claim, error_code) + when error_code in ~w(refresh_invalid_grant refresh_account_identity_mismatch) do + Repo.transaction(fn -> + changes = [ + connection_status: "reauthorization_required", + active: false, + validation_status: "unverified", + validated_at: nil, + validation_error_code: error_code, + refresh_claim_owner_id: nil, + refresh_claim_generation: nil, + refresh_lease_expires_at: nil, + updated_at: now() + ] + + case Repo.update_all(exact_refresh_claim_query(user.id, claim), set: changes) do + {1, nil} -> + integration = Repo.get_by!(Integration, id: claim.id, user_id: user.id) + audit!(user.id, integration, "refresh_reauthorization_required") + integration + + {0, nil} -> + Repo.rollback(:stale_refresh_claim) + end + end) + |> notify_integration_change() + end + + def require_refresh_reauthorization(%Scope{}, %Integration{}, _error_code), + do: {:error, :unsafe_refresh_error} + def validation_succeeded(%Scope{} = scope, id, generation) do update_fenced(scope, id, generation, ["connected"], "validation_succeeded", %{ validation_status: "valid", diff --git a/lib/kodo/integrations/audit_event.ex b/lib/kodo/integrations/audit_event.ex index e78ba87..9ecfa2c 100644 --- a/lib/kodo/integrations/audit_event.ex +++ b/lib/kodo/integrations/audit_event.ex @@ -19,6 +19,7 @@ defmodule Kodo.Integrations.AuditEvent do oauth_succeeded refresh_succeeded refresh_invalid_grant + refresh_reauthorization_required ) @primary_key {:id, :binary_id, autogenerate: true} diff --git a/lib/kodo/integrations/oauth_refresh.ex b/lib/kodo/integrations/oauth_refresh.ex new file mode 100644 index 0000000..0c35ec6 --- /dev/null +++ b/lib/kodo/integrations/oauth_refresh.ex @@ -0,0 +1,183 @@ +defmodule Kodo.Integrations.OAuthRefresh do + @moduledoc "Runs generation-fenced, just-in-time OAuth refreshes as finite tasks." + + alias Kodo.Accounts.Scope + alias Kodo.Cluster.InstanceManager + alias Kodo.Integrations + alias Kodo.Integrations.CredentialEncryption + alias Kodo.Integrations.Integration + alias Kodo.Integrations.RefreshTokens + + @refresh_buffer_seconds 5 * 60 + @wait_timeout_ms 12_000 + @wait_interval_ms 250 + + def ensure_fresh(%Scope{} = scope, %Integration{} = integration, opts \\ []) do + now = Keyword.get(opts, :now, DateTime.utc_now()) + buffer = Keyword.get(opts, :refresh_buffer_seconds, @refresh_buffer_seconds) + + if refresh_due?(integration, now, buffer) do + refresh(scope, integration, opts) + else + {:ok, integration} + end + end + + defp refresh(scope, integration, opts) do + owner_id = Keyword.get_lazy(opts, :claim_owner_id, &InstanceManager.current_boot_id/0) + + deadline = + System.monotonic_time(:millisecond) + Keyword.get(opts, :wait_timeout, @wait_timeout_ms) + + if is_binary(owner_id) do + claim_or_wait(scope, integration, owner_id, deadline, opts) + else + {:error, :provider_unavailable} + end + end + + defp claim_or_wait(scope, integration, owner_id, deadline, opts) do + case Integrations.claim_refresh( + scope, + integration.id, + integration.credential_generation, + owner_id + ) do + {:ok, claim} -> + run_claim(scope, claim, opts) + + {:error, :refresh_in_progress} -> + wait_for_claim(scope, integration, owner_id, deadline, opts) + + {:error, :stale_credential_generation} -> + current_result(scope, integration) + + {:error, _reason} -> + {:error, :provider_unavailable} + end + end + + defp wait_for_claim(scope, integration, owner_id, deadline, opts) do + if System.monotonic_time(:millisecond) < deadline do + receive do + after + @wait_interval_ms -> claim_or_wait(scope, integration, owner_id, deadline, opts) + end + else + current_result(scope, integration) + end + end + + defp run_claim(scope, claim, opts) do + supervisor = Keyword.get(opts, :supervisor, Kodo.ControlPlaneTaskSupervisor) + + task = + Task.Supervisor.async_nolink(supervisor, fn -> + perform(scope, claim, opts) + end) + + case Task.yield(task, Keyword.get(opts, :wait_timeout, @wait_timeout_ms)) do + {:ok, result} -> + result + + {:exit, _reason} -> + {:error, :provider_unavailable} + + nil -> + _result = Task.shutdown(task, :brutal_kill) + {:error, :provider_unavailable} + end + end + + defp perform(scope, claim, opts) do + client = Keyword.get(opts, :client, configured_client()) + client_options = Keyword.get(opts, :client_options, []) + + with {:ok, current} <- CredentialEncryption.decrypt(claim), + {:ok, refresh_token} <- fetch_refresh_token(current), + {:ok, response} <- safe_refresh(client, refresh_token, client_options), + {:ok, normalized} <- RefreshTokens.normalize(response, current), + {:ok, integration} <- + Integrations.refresh_succeeded( + scope, + claim.id, + claim.refresh_claim_generation, + normalized.credentials, + expires_at: normalized.expires_at, + refreshed_at: DateTime.utc_now() + ) do + {:ok, integration} + else + {:error, :invalid_grant} -> + require_reauthorization(scope, claim, "refresh_invalid_grant") + + {:error, :refresh_account_identity_mismatch} -> + require_reauthorization(scope, claim, "refresh_account_identity_mismatch") + + {:error, :stale_credential_generation} -> + current_result(scope, claim) + + {:error, _reason} -> + _result = Integrations.release_refresh_claim(scope, claim) + {:error, :provider_unavailable} + end + end + + defp require_reauthorization(scope, claim, error_code) do + case Integrations.require_refresh_reauthorization(scope, claim, error_code) do + {:ok, _integration} -> {:error, :integration_reauthorization_required} + {:error, :stale_refresh_claim} -> current_result(scope, claim) + {:error, _reason} -> {:error, :provider_unavailable} + end + end + + defp current_result(scope, integration) do + case Integrations.get_integration(scope, integration.id) do + {:ok, %{connection_status: "connected"} = current} + when current.credential_generation > integration.credential_generation -> + {:ok, current} + + {:ok, %{connection_status: "reauthorization_required"}} -> + {:error, :integration_reauthorization_required} + + _other -> + {:error, :provider_unavailable} + end + end + + defp refresh_due?( + %Integration{ + provider: "openai_codex", + authentication_type: "oauth", + expires_at: expires_at + }, + %DateTime{} = now, + buffer + ) + when is_integer(buffer) and buffer >= 0 do + not match?(%DateTime{}, expires_at) or + DateTime.compare(expires_at, DateTime.add(now, buffer, :second)) != :gt + end + + defp refresh_due?(_integration, _now, _buffer), do: false + + defp fetch_refresh_token(%{"refresh_token" => token}) + when is_binary(token) and byte_size(token) > 0, + do: {:ok, token} + + defp fetch_refresh_token(_current), do: {:error, :oauth_refresh_response_invalid} + + defp safe_refresh(client, refresh_token, options) do + try do + client.refresh(refresh_token, options) + rescue + _exception -> {:error, :provider_unavailable} + catch + _kind, _reason -> {:error, :provider_unavailable} + end + end + + defp configured_client do + Application.get_env(:kodo, :oauth_refresh_client, Kodo.Integrations.ReqRefreshClient) + end +end diff --git a/lib/kodo/llm.ex b/lib/kodo/llm.ex index c54f1de..2029a02 100644 --- a/lib/kodo/llm.ex +++ b/lib/kodo/llm.ex @@ -124,7 +124,8 @@ defmodule Kodo.LLM do :integration_disconnected, :integration_reauthorization_required, :integration_invalid, - :stale_credential_generation + :stale_credential_generation, + :provider_unavailable ] -> {:error, ProviderError.from_integration(reason, model)} diff --git a/lib/kodo/llm/credential_resolver.ex b/lib/kodo/llm/credential_resolver.ex index 0659332..c5e400b 100644 --- a/lib/kodo/llm/credential_resolver.ex +++ b/lib/kodo/llm/credential_resolver.ex @@ -12,6 +12,7 @@ defmodule Kodo.LLM.CredentialResolver do alias Kodo.Integrations alias Kodo.Integrations.CredentialEncryption alias Kodo.Integrations.Integration + alias Kodo.Integrations.OAuthRefresh alias Kodo.LLM.Credential alias Kodo.LLM.IntegrationRef @@ -47,6 +48,7 @@ defmodule Kodo.LLM.CredentialResolver do :ok <- require_authentication_type(integration, reference), :ok <- require_billing_path(integration, reference), :ok <- require_usable(integration), + {:ok, integration} <- OAuthRefresh.ensure_fresh(scope, integration), {:ok, payload} <- CredentialEncryption.decrypt(integration) do build_credential(integration, reference, payload) end diff --git a/lib/kodo/llm/provider_error.ex b/lib/kodo/llm/provider_error.ex index 249f1bc..02ac85f 100644 --- a/lib/kodo/llm/provider_error.ex +++ b/lib/kodo/llm/provider_error.ex @@ -28,7 +28,8 @@ defmodule Kodo.LLM.ProviderError do :integration_disconnected, :integration_reauthorization_required, :integration_invalid, - :stale_credential_generation + :stale_credential_generation, + :provider_unavailable ] do provider = Atom.to_string(model.provider) @@ -96,6 +97,7 @@ defmodule Kodo.LLM.ProviderError do defp integration_kind(:integration_invalid), do: :authentication_rejected defp integration_kind(:integration_reauthorization_required), do: :authentication_rejected defp integration_kind(:stale_credential_generation), do: :integration_changed + defp integration_kind(:provider_unavailable), do: :provider_unavailable defp integration_kind(_reason), do: :integration_required defp billing_path("openai_codex"), do: :subscription diff --git a/test/kodo/integrations/oauth_refresh_test.exs b/test/kodo/integrations/oauth_refresh_test.exs new file mode 100644 index 0000000..dfc0fcd --- /dev/null +++ b/test/kodo/integrations/oauth_refresh_test.exs @@ -0,0 +1,232 @@ +defmodule Kodo.Integrations.OAuthRefreshTest do + use Kodo.DataCase, async: false + + alias Kodo.AccountsFixtures + alias Kodo.Integrations + alias Kodo.Integrations.CredentialEncryption + alias Kodo.Integrations.DeviceAuthorizationAttempt + alias Kodo.Integrations.Integration + alias Kodo.Integrations.OAuthRefresh + alias Kodo.Test.FakeRefreshClient + + setup do + supervisor = start_supervised!({Task.Supervisor, name: nil}) + scope = AccountsFixtures.user_scope_fixture() + + integration = + %Integration{user_id: scope.user.id} + |> Integration.create_changeset(%{ + provider: "openai_codex", + authentication_type: "oauth", + display_name: "Subscription" + }) + |> Repo.insert!() + + current = current_tokens() + + assert {:ok, connected} = + Integrations.oauth_succeeded(scope, integration.id, 0, current, + expires_at: DateTime.add(DateTime.utc_now(), 30, :second) + ) + + %{scope: scope, integration: connected, supervisor: supervisor} + end + + test "refreshes shortly before expiry and persists rotated token state", context do + client = fake_client([{:ok, rotated_tokens("account")}]) + + assert {:ok, refreshed} = refresh(context, client) + assert refreshed.credential_generation == context.integration.credential_generation + 1 + assert refreshed.connection_status == "connected" + assert %DateTime{} = refreshed.refreshed_at + assert %DateTime{} = refreshed.expires_at + assert is_nil(refreshed.refresh_claim_owner_id) + + assert {:ok, credentials} = CredentialEncryption.decrypt(refreshed) + assert credentials["access_token"] == rotated_tokens("account")["access_token"] + assert credentials["refresh_token"] == "rotated-refresh" + assert credentials["account_id"] == "account" + assert Agent.get(client, &Enum.reverse(&1.refresh_tokens)) == ["old-refresh"] + end + + test "does not refresh a token outside the refresh buffer", context do + integration = + context.integration + |> change(expires_at: DateTime.add(DateTime.utc_now(), 3_600, :second)) + |> Repo.update!() + + client = fake_client([]) + + assert {:ok, unchanged} = + OAuthRefresh.ensure_fresh(context.scope, integration, + client: FakeRefreshClient, + client_options: [agent: client], + supervisor: context.supervisor, + claim_owner_id: Ecto.UUID.generate() + ) + + assert unchanged.credential_generation == integration.credential_generation + assert Agent.get(client, & &1.refresh_tokens) == [] + end + + test "invalid grant and account changes require reauthorization without erasing credentials", + context do + for {response, error_code} <- [ + {{:error, :invalid_grant}, "refresh_invalid_grant"}, + {{:ok, rotated_tokens("other-account")}, "refresh_account_identity_mismatch"} + ] do + integration = Repo.reload!(context.integration) + client = fake_client([response]) + + assert {:error, :integration_reauthorization_required} = + refresh(%{context | integration: integration}, client) + + required = Repo.reload!(integration) + assert required.connection_status == "reauthorization_required" + assert required.validation_error_code == error_code + assert required.credential_generation == integration.credential_generation + assert required.encrypted_credentials == integration.encrypted_credentials + + Repo.update!( + change(required, + connection_status: "connected", + active: true, + validation_error_code: nil + ) + ) + end + end + + test "transient provider failures preserve credentials and release the exact claim", context do + client = fake_client([{:error, :provider_unavailable}]) + + assert {:error, :provider_unavailable} = refresh(context, client) + + unchanged = Repo.reload!(context.integration) + assert unchanged.connection_status == "connected" + assert unchanged.encrypted_credentials == context.integration.encrypted_credentials + assert is_nil(unchanged.refresh_claim_owner_id) + assert unchanged.refresh_claim_epoch == 1 + end + + test "the first generation-matching success wins after lease takeover", context do + owner = self() + first_tokens = rotated_tokens("account", "first") + second_tokens = rotated_tokens("account", "second") + + first_response = fn _refresh_token -> + send(owner, {:first_refresh_started, self()}) + + receive do + :finish_first_refresh -> {:ok, first_tokens} + end + end + + client = fake_client([first_response, {:ok, second_tokens}]) + + first = Task.async(fn -> refresh(context, client) end) + assert_receive {:first_refresh_started, first_worker} + + context.integration + |> Repo.reload!() + |> change(refresh_lease_expires_at: DateTime.add(DateTime.utc_now(), -1, :second)) + |> Repo.update!() + + assert {:ok, winner} = refresh(context, client) + assert winner.credential_generation == context.integration.credential_generation + 1 + + send(first_worker, :finish_first_refresh) + assert {:ok, same_winner} = Task.await(first) + assert same_winner.credential_generation == winner.credential_generation + + assert {:ok, persisted} = CredentialEncryption.decrypt(Repo.reload!(winner)) + assert persisted["refresh_token"] == "second-refresh" + assert persisted["access_token"] == second_tokens["access_token"] + end + + test "user deletion cascades OAuth state and fences an in-flight refresh", context do + assert {:ok, _attempt} = + Integrations.begin_device_authorization( + context.scope, + context.integration.id, + context.integration.credential_generation, + %{"device_auth_id" => "device", "user_code" => "CODE"}, + 0 + ) + + integration = Repo.reload!(context.integration) + owner = self() + + blocked = fn _refresh_token -> + send(owner, {:deletion_refresh_started, self()}) + + receive do + :finish_deleted_refresh -> {:ok, rotated_tokens("account")} + end + end + + client = fake_client([blocked]) + refresh = Task.async(fn -> refresh(%{context | integration: integration}, client) end) + assert_receive {:deletion_refresh_started, worker} + + assert Repo.reload!(integration).refresh_claim_owner_id + Repo.delete!(context.scope.user) + refute Repo.exists?(Integration) + refute Repo.exists?(DeviceAuthorizationAttempt) + + send(worker, :finish_deleted_refresh) + assert {:error, :provider_unavailable} = Task.await(refresh) + refute Repo.exists?(Integration) + refute Repo.exists?(DeviceAuthorizationAttempt) + end + + defp refresh(context, client) do + OAuthRefresh.ensure_fresh(context.scope, context.integration, + client: FakeRefreshClient, + client_options: [agent: client], + supervisor: context.supervisor, + claim_owner_id: Ecto.UUID.generate() + ) + end + + defp fake_client(responses) do + start_supervised!( + {Agent, fn -> %{responses: responses, refresh_tokens: []} end}, + id: {:fake_refresh_client, System.unique_integer([:positive])} + ) + end + + defp current_tokens do + %{ + "access_token" => "old-access", + "refresh_token" => "old-refresh", + "id_token" => id_token("account"), + "account_id" => "account" + } + end + + defp rotated_tokens(account_id) do + rotated_tokens(account_id, "rotated") + end + + defp rotated_tokens(account_id, label) do + %{ + "access_token" => + jwt(%{ + "exp" => DateTime.utc_now() |> DateTime.to_unix() |> Kernel.+(3_600), + "label" => label + }), + "refresh_token" => "#{label}-refresh", + "id_token" => id_token(account_id) + } + end + + defp id_token(account_id) do + jwt(%{"https://api.openai.com/auth" => %{"chatgpt_account_id" => account_id}}) + end + + defp jwt(claims) do + encoded = claims |> Jason.encode!() |> Base.url_encode64(padding: false) + "header.#{encoded}.signature" + end +end diff --git a/test/kodo/llm/credential_resolver_test.exs b/test/kodo/llm/credential_resolver_test.exs index ef34360..0a96f79 100644 --- a/test/kodo/llm/credential_resolver_test.exs +++ b/test/kodo/llm/credential_resolver_test.exs @@ -288,11 +288,17 @@ defmodule Kodo.LLM.CredentialResolverTest do integration = Kodo.Repo.insert!(integration) assert {:ok, connected} = - Integrations.oauth_succeeded(scope, integration.id, 0, %{ - "access_token" => "access-secret", - "refresh_token" => "refresh-secret", - "account_id" => "account-secret" - }) + Integrations.oauth_succeeded( + scope, + integration.id, + 0, + %{ + "access_token" => "access-secret", + "refresh_token" => "refresh-secret", + "account_id" => "account-secret" + }, + expires_at: DateTime.add(DateTime.utc_now(), 3_600, :second) + ) codex_model = LLMDB.Model.new!(%{id: "codex", provider: :openai_codex}) diff --git a/test/support/fake_refresh_client.ex b/test/support/fake_refresh_client.ex new file mode 100644 index 0000000..7c04bdf --- /dev/null +++ b/test/support/fake_refresh_client.ex @@ -0,0 +1,15 @@ +defmodule Kodo.Test.FakeRefreshClient do + @moduledoc false + + def refresh(refresh_token, opts) do + agent = Keyword.fetch!(opts, :agent) + + response = + Agent.get_and_update(agent, fn %{responses: [response | remaining]} = state -> + {response, + %{state | responses: remaining, refresh_tokens: [refresh_token | state.refresh_tokens]}} + end) + + if is_function(response, 1), do: response.(refresh_token), else: response + end +end From b5dabde26ddd0ee5602d10f768bf224a5657a823 Mon Sep 17 00:00:00 2001 From: Darwin Wu Date: Thu, 10 Sep 2026 05:07:53 +0000 Subject: [PATCH 07/12] feat(integrations): verify ChatGPT subscription access --- lib/kodo/integrations.ex | 21 ++++++ lib/kodo/integrations/audit_event.ex | 1 + .../integrations/oauth_access_validation.ex | 67 +++++++++++++++++++ lib/kodo/integrations/oauth_refresh.ex | 4 +- lib/kodo_web/live/integrations_live.ex | 12 ++-- test/kodo/integrations/oauth_refresh_test.exs | 20 ++++++ test/kodo_web/live/integrations_live_test.exs | 27 ++++++++ test/support/fake_refresh_client.ex | 3 +- 8 files changed, 147 insertions(+), 8 deletions(-) create mode 100644 lib/kodo/integrations/oauth_access_validation.ex diff --git a/lib/kodo/integrations.ex b/lib/kodo/integrations.ex index 765fca9..8c6ece6 100644 --- a/lib/kodo/integrations.ex +++ b/lib/kodo/integrations.ex @@ -481,6 +481,27 @@ defmodule Kodo.Integrations do def require_refresh_reauthorization(%Scope{}, %Integration{}, _error_code), do: {:error, :unsafe_refresh_error} + def fail_refresh(%Scope{user: user}, %Integration{} = claim) do + Repo.transaction(fn -> + case Repo.update_all(exact_refresh_claim_query(user.id, claim), + set: [ + refresh_claim_owner_id: nil, + refresh_claim_generation: nil, + refresh_lease_expires_at: nil, + updated_at: now() + ] + ) do + {1, nil} -> + integration = Repo.get_by!(Integration, id: claim.id, user_id: user.id) + audit!(user.id, integration, "refresh_failed") + integration + + {0, nil} -> + Repo.rollback(:stale_refresh_claim) + end + end) + end + def validation_succeeded(%Scope{} = scope, id, generation) do update_fenced(scope, id, generation, ["connected"], "validation_succeeded", %{ validation_status: "valid", diff --git a/lib/kodo/integrations/audit_event.ex b/lib/kodo/integrations/audit_event.ex index 9ecfa2c..b1e3fdd 100644 --- a/lib/kodo/integrations/audit_event.ex +++ b/lib/kodo/integrations/audit_event.ex @@ -20,6 +20,7 @@ defmodule Kodo.Integrations.AuditEvent do refresh_succeeded refresh_invalid_grant refresh_reauthorization_required + refresh_failed ) @primary_key {:id, :binary_id, autogenerate: true} diff --git a/lib/kodo/integrations/oauth_access_validation.ex b/lib/kodo/integrations/oauth_access_validation.ex new file mode 100644 index 0000000..3091d52 --- /dev/null +++ b/lib/kodo/integrations/oauth_access_validation.ex @@ -0,0 +1,67 @@ +defmodule Kodo.Integrations.OAuthAccessValidation do + @moduledoc "Validates ChatGPT subscription access through the bounded refresh contract." + + alias Kodo.Accounts.Scope + alias Kodo.Integrations + alias Kodo.Integrations.Integration + alias Kodo.Integrations.OAuthRefresh + + def start(%Scope{} = scope, %{id: id, credential_generation: generation}) do + Task.Supervisor.async_nolink(Kodo.ControlPlaneTaskSupervisor, fn -> + validate(scope, id, generation) + end) + end + + @doc false + def validate(%Scope{} = scope, id, generation, opts \\ []) do + with {:ok, integration} <- Integrations.get_integration(scope, id), + :ok <- admit(integration, generation) do + case OAuthRefresh.ensure_fresh(scope, integration, Keyword.put(opts, :force, true)) do + {:ok, refreshed} -> + scope + |> Integrations.validation_succeeded(refreshed.id, refreshed.credential_generation) + |> broadcast_result(refreshed) + + {:error, :provider_unavailable} = error -> + result = + Integrations.validation_unavailable( + scope, + integration.id, + integration.credential_generation, + "provider_unavailable" + ) + + _result = broadcast_result(result, integration) + error + + {:error, _reason} = error -> + error + end + end + end + + defp admit( + %Integration{ + provider: "openai_codex", + authentication_type: "oauth", + connection_status: "connected", + credential_generation: generation + }, + generation + ), + do: :ok + + defp admit(%Integration{}, _generation), do: {:error, :stale_credential_generation} + + defp broadcast_result({:ok, validated} = result, integration) do + Phoenix.PubSub.broadcast( + Kodo.PubSub, + "integration:#{integration.user_id}", + {:integration_validation_finished, validated.id, validated.credential_generation} + ) + + result + end + + defp broadcast_result(error, _integration), do: error +end diff --git a/lib/kodo/integrations/oauth_refresh.ex b/lib/kodo/integrations/oauth_refresh.ex index 0c35ec6..76705d4 100644 --- a/lib/kodo/integrations/oauth_refresh.ex +++ b/lib/kodo/integrations/oauth_refresh.ex @@ -16,7 +16,7 @@ defmodule Kodo.Integrations.OAuthRefresh do now = Keyword.get(opts, :now, DateTime.utc_now()) buffer = Keyword.get(opts, :refresh_buffer_seconds, @refresh_buffer_seconds) - if refresh_due?(integration, now, buffer) do + if Keyword.get(opts, :force, false) or refresh_due?(integration, now, buffer) do refresh(scope, integration, opts) else {:ok, integration} @@ -118,7 +118,7 @@ defmodule Kodo.Integrations.OAuthRefresh do current_result(scope, claim) {:error, _reason} -> - _result = Integrations.release_refresh_claim(scope, claim) + _result = Integrations.fail_refresh(scope, claim) {:error, :provider_unavailable} end end diff --git a/lib/kodo_web/live/integrations_live.ex b/lib/kodo_web/live/integrations_live.ex index 1487bb0..add2f5c 100644 --- a/lib/kodo_web/live/integrations_live.ex +++ b/lib/kodo_web/live/integrations_live.ex @@ -4,6 +4,7 @@ defmodule KodoWeb.IntegrationsLive do alias Kodo.Integrations alias Kodo.Integrations.APIKeyValidation alias Kodo.Integrations.DeviceAuthorization + alias Kodo.Integrations.OAuthAccessValidation @provider_configs [ %{ @@ -454,7 +455,11 @@ defmodule KodoWeb.IntegrationsLive do end defp start_validation(socket, integration) do - task = APIKeyValidation.start(socket.assigns.current_scope, integration) + task = + case integration.authentication_type do + "oauth" -> OAuthAccessValidation.start(socket.assigns.current_scope, integration) + "api_key" -> APIKeyValidation.start(socket.assigns.current_scope, integration) + end update(socket, :validation_tasks, fn tasks -> Map.put(tasks, task.ref, {integration.id, integration.credential_generation}) @@ -897,10 +902,7 @@ defmodule KodoWeb.IntegrationsLive do Activate