diff --git a/src/albedo/harness/extensions/codex/accounts.gleam b/src/albedo/harness/extensions/codex/accounts.gleam index e2ffdce60..f35326674 100644 --- a/src/albedo/harness/extensions/codex/accounts.gleam +++ b/src/albedo/harness/extensions/codex/accounts.gleam @@ -521,28 +521,203 @@ pub fn usage_limit(body: String, now: Int) -> Result(#(Int, Bool), String) { } } -/// Revoke and profile-pruning remain one journaled native transaction. +/// Drops the account whose access token the server rejected, so the next +/// turn picks a sibling or asks for /login instead of replaying a revoked +/// token. Profiles that rotate through it stop naming it, in the same +/// journaled settings commit. Returns the removed account's email, or `""` +/// when none is recorded. pub fn revoke( home: String, stored: credentials.Stored(Account), ) -> Result(String, String) { let value = credentials.value(stored) - revoke_snapshot( - home, - credentials.public_id(stored), - value.access, - value.refresh, - ) + let public_id = credentials.public_id(stored) + with_credentials_lock(home, fn() { + remove_revoked(home, public_id, value.access, value.refresh) + }) } -@external(erlang, "albedo_openai_auth", "codex_revoke") -fn revoke_snapshot( +/// Where creds.json keeps Codex accounts. +const store_key = "openai-codex" + +fn remove_revoked( home: String, public_id: String, access: String, refresh: String, +) -> Result(String, String) { + case stored_accounts(home) { + Error(True) -> Ok("") + Error(False) -> Error("stored Codex credentials are unreadable") + Ok(data) -> { + let #(rejected, kept) = + oauth_values(data, store_key) + |> list.partition(fn(value) { + field_is(value, "access", access) + && field_is(value, "refresh", refresh) + && { + public_id == "" || field_is(value, "_albedo_account_id", public_id) + } + }) + case rejected { + [] -> Ok("") + [removed, ..] -> { + let ids = + list.filter_map(rejected, fn(value) { + decode.run( + value, + decode.at(["_albedo_account_id"], decode.dynamic), + ) + }) + case remove_accounts(home, put_values(data, store_key, kept), ids) { + Ok(Nil) -> Ok(public_email(removed)) + Error(Nil) -> Error("could not remove revoked Codex credential") + } + } + } + } + } +} + +/// Whether a stored credential's field equals `expected`, a missing field +/// counting as `""`. +fn field_is(value: Dynamic, key: String, expected: String) -> Bool { + decode.run(value, field_or(key, dynamic.string(""), decode.dynamic)) + == Ok(dynamic.string(expected)) +} + +fn field_or( + key: String, + default: a, + decoder: decode.Decoder(a), +) -> decode.Decoder(a) { + use value <- decode.optional_field(key, default, decoder) + decode.success(value) +} + +/// The accounts section with `values` stored under `key`: none removes it, +/// one is stored bare, more as a list. +fn put_values( + data: dict.Dict(String, Dynamic), + key: String, + values: List(Dynamic), +) -> dict.Dict(String, Dynamic) { + case values { + [] -> dict.delete(data, key) + [one] -> dict.insert(data, key, one) + many -> dict.insert(data, key, dynamic.list(many)) + } +} + +fn remove_accounts( + home: String, + accounts: dict.Dict(String, Dynamic), + removed_ids: List(Dynamic), +) -> Result(Nil, Nil) { + let object = decode.dict(decode.string, decode.dynamic) + use config <- result.try(read_settings(home, "config.json")) + use creds <- result.try(read_settings(home, "creds.json")) + use profiles <- result.try( + decode.run(config, field_or("providers", dict.new(), object)) + |> result.replace_error(Nil), + ) + use updated <- result.try( + dict.to_list(profiles) + |> list.try_map(fn(entry) { + use profile <- result.map( + decode.run(entry.1, object) |> result.replace_error(Nil), + ) + #(entry.0, prune_rotation(profile, entry.1, removed_ids)) + }) + |> result.map(dict.from_list), + ) + use creds <- result.try( + decode.run(creds, object) |> result.replace_error(Nil), + ) + let documents = + dict.from_list([ + #( + "creds.json", + to_dynamic(dict.insert(creds, "accounts", to_dynamic(accounts))), + ), + ]) + use documents <- result.try(case updated == profiles { + True -> Ok(documents) + False -> { + use config <- result.map( + decode.run(config, object) |> result.replace_error(Nil), + ) + dict.insert( + documents, + "config.json", + to_dynamic(dict.insert(config, "providers", to_dynamic(updated))), + ) + } + }) + commit_settings(home, documents) +} + +/// A profile that rotates through removed accounts keeps the rest. When none +/// remain it pins the first account it named instead. +fn prune_rotation( + profile: dict.Dict(String, Dynamic), + raw: Dynamic, + removed_ids: List(Dynamic), +) -> Dynamic { + case dict.get(profile, "accountIds") { + Ok(ids) -> + case decode.run(ids, decode.list(decode.dynamic)) { + Ok([first, ..] as ids) -> + case list.filter(ids, fn(id) { !list.contains(removed_ids, id) }) { + [] -> + profile + |> dict.insert("accountId", first) + |> dict.delete("accountIds") + |> to_dynamic + kept -> + profile + |> dict.insert("accountIds", dynamic.list(kept)) + |> to_dynamic + } + _ -> raw + } + Error(Nil) -> raw + } +} + +fn to_dynamic(object: dict.Dict(String, Dynamic)) -> Dynamic { + object + |> dict.to_list + |> list.map(fn(entry) { #(dynamic.string(entry.0), entry.1) }) + |> dynamic.properties +} + +/// Runs `run` under the settings lock of the credential store's directory. +/// A busy lock, or a result that is not a text, answers an error. +@external(erlang, "albedo_openai_auth", "with_credentials_lock") +fn with_credentials_lock( + home: String, + run: fn() -> Result(String, String), ) -> Result(String, String) +/// The accounts section of creds.json, or whether it is missing. +@external(erlang, "albedo_openai_auth", "stored_accounts") +fn stored_accounts(home: String) -> Result(dict.Dict(String, Dynamic), Bool) + +/// The OAuth credentials stored under `key`. +@external(erlang, "albedo_openai_auth", "oauth_values") +fn oauth_values(data: dict.Dict(String, Dynamic), key: String) -> List(Dynamic) + +@external(erlang, "albedo_openai_auth", "read_settings") +fn read_settings(home: String, name: String) -> Result(Dynamic, Nil) + +/// Commits the documents together through the settings recovery journal. +@external(erlang, "albedo_openai_auth", "commit_settings") +fn commit_settings( + home: String, + documents: dict.Dict(String, Dynamic), +) -> Result(Nil, Nil) + pub fn explicit(home: String, profile: String) -> Bool { case profile { "" -> True diff --git a/src/albedo/harness/extensions/codex/albedo_openai_auth.erl b/src/albedo/harness/extensions/codex/albedo_openai_auth.erl index 4860d7d28..e54c8e9f5 100644 --- a/src/albedo/harness/extensions/codex/albedo_openai_auth.erl +++ b/src/albedo/harness/extensions/codex/albedo_openai_auth.erl @@ -1,19 +1,20 @@ -module(albedo_openai_auth). -%% Atomic revoked-account/profile pruning. --export([codex_revoke/4]). --define(STORE, <<"openai-codex">>). +%% The credential-store primitives Codex's revoked-account pruning needs: the +%% settings lock, raw creds.json sections, and the journaled settings commit. +%% No SDK helper exposes them. The pruning policy is Gleam (codex/accounts). +-export([ + with_credentials_lock/2, + stored_accounts/1, + oauth_values/2, + read_settings/2, + commit_settings/2 +]). -credentials(Data) -> albedo_credentials:oauth(Data, ?STORE). - -%% Drops the account whose access token the server rejected, so the next turn -%% picks a sibling or asks for /login instead of replaying a revoked token. -%% Returns the removed account's email, or <<>> when none is recorded. -codex_revoke(Home0, PublicId, Access, Refresh) -> - Path = albedo_credentials:creds_path(Home0), +with_credentials_lock(Home, Run) -> case albedo_settings_lock:with_lock( - filename:dirname(Path), - fun() -> remove_snapshot(Path, PublicId, Access, Refresh) end, + directory(Home), + Run, fun() -> {error, <<"credential store is busy">>} end ) of @@ -22,63 +23,31 @@ codex_revoke(Home0, PublicId, Access, Refresh) -> _ -> {error, <<"could not remove revoked Codex credential">>} end. -remove_snapshot(Path, PublicId, Access, Refresh) -> - case albedo_credentials:accounts(Path) of - {ok, Data} -> - Values = credentials(Data), - Revoked = fun(Value) -> - maps:get(<<"access">>, Value, <<>>) =:= Access andalso - maps:get(<<"refresh">>, Value, <<>>) =:= Refresh andalso - (PublicId =:= <<>> orelse - maps:get(<<"_albedo_account_id">>, Value, <<>>) =:= PublicId) - end, - case lists:partition(Revoked, Values) of - {[], _} -> - {ok, <<>>}; - {[Removed | _] = Rejected, Kept} -> - Ids = [Id || #{<<"_albedo_account_id">> := Id} <- Rejected], - case - remove_accounts( - Path, albedo_credentials:put_values(Data, ?STORE, Kept), Ids - ) - of - ok -> - {ok, 'albedo@harness@extensions@codex@accounts':public_email(Removed)}; - {error, _} -> - {error, <<"could not remove revoked Codex credential">>} - end - end; - {error, enoent} -> - {ok, <<>>}; - {error, _} -> - {error, <<"stored Codex credentials are unreadable">>} +%% {ok, Accounts}, {error, true} when creds.json is missing, or {error, false}. +stored_accounts(Home) -> + case albedo_credentials:accounts(albedo_credentials:creds_path(Home)) of + {ok, Data} -> {ok, Data}; + {error, enoent} -> {error, true}; + {error, _} -> {error, false} end. -remove_accounts(Path, Accounts, RemovedIds) -> - Home = unicode:characters_to_binary(filename:dirname(Path)), +oauth_values(Data, Key) -> albedo_credentials:oauth(Data, Key). + +read_settings(Home, Name) -> try - Config = albedo_settings_store:read(Home, <<"config.json">>), - Creds = albedo_settings_store:read(Home, <<"creds.json">>), - Profiles = maps:get(<<"providers">>, Config, #{}), - Updated = maps:map(fun(_, Profile) -> prune_rotation(Profile, RemovedIds) end, Profiles), - Documents = #{<<"creds.json">> => Creds#{<<"accounts">> => Accounts}}, - Next = - case Updated =:= Profiles of - true -> Documents; - false -> Documents#{<<"config.json">> => Config#{<<"providers">> => Updated}} - end, - albedo_settings_store:commit_group(Home, Next) + {ok, albedo_settings_store:read(settings_home(Home), Name)} catch - _:_ -> {error, <<"could not remove revoked Codex credential">>} + _:_ -> {error, nil} end. -prune_rotation(Profile, RemovedIds) -> - case maps:get(<<"accountIds">>, Profile, null) of - Ids when is_list(Ids), Ids =/= [] -> - case [Id || Id <- Ids, not lists:member(Id, RemovedIds)] of - [] -> maps:remove(<<"accountIds">>, Profile#{<<"accountId">> => hd(Ids)}); - Kept -> Profile#{<<"accountIds">> => Kept} - end; - _ -> - Profile +commit_settings(Home, Documents) -> + try albedo_settings_store:commit_group(settings_home(Home), Documents) of + ok -> {ok, nil}; + _ -> {error, nil} + catch + _:_ -> {error, nil} end. + +directory(Home) -> filename:dirname(albedo_credentials:creds_path(Home)). + +settings_home(Home) -> unicode:characters_to_binary(directory(Home)).