-module(gitproxy_ffi). -export([ halt/1, unix_seconds/0, format_rfc3339/1, get_cwd/0, read_line/0, write_stdout/1, write_stderr/1, run_git/3, memory_new/0, memory_put/3, memory_get/2, memory_keys/1, uuid_v4/0, open_browser/1, oauth_can_bind/1, oauth_wait_callback/2, dpop_generate_keypair/0, dpop_sign_jwt/3, base64url_encode/1, base64url_decode/1, random_bytes/1, sha256/1 ]). halt(Code) when is_integer(Code) -> erlang:halt(Code). unix_seconds() -> erlang:system_time(second). format_rfc3339(Secs) when is_integer(Secs) -> {{Y, Mo, D}, {H, Mi, S}} = calendar:system_time_to_universal_time(Secs, second), list_to_binary( io_lib:format("~4..0B-~2..0B-~2..0BT~2..0B:~2..0B:~2..0BZ", [Y, Mo, D, H, Mi, S]) ). get_cwd() -> case file:get_cwd() of {ok, Cwd} -> {ok, unicode:characters_to_binary(Cwd)}; {error, Reason} -> {error, reason_bin(Reason)} end. %% Gleam: OkLine(String) | Eof | ReadError(String) read_line() -> case io:get_line("") of eof -> eof; {error, Reason} -> {read_error, reason_bin(Reason)}; Line when is_list(Line) -> {ok_line, strip_newline(unicode:characters_to_binary(Line))}; Line when is_binary(Line) -> {ok_line, strip_newline(Line)} end. strip_newline(Bin) when byte_size(Bin) =:= 0 -> Bin; strip_newline(Bin) -> case binary:last(Bin) of $\n -> Sz = byte_size(Bin) - 1, case Sz > 0 andalso binary:at(Bin, Sz - 1) =:= $\r of true -> binary:part(Bin, 0, Sz - 1); false -> binary:part(Bin, 0, Sz) end; _ -> Bin end. write_stdout(Bin) when is_binary(Bin) -> ok = io:put_chars(standard_io, Bin), nil. write_stderr(Bin) when is_binary(Bin) -> ok = io:put_chars(standard_error, Bin), nil. %% Run git; optional stdin via a temp file so the pipe is closed cleanly. %% Args: [binary()], Dir: binary(), Input: none | {some, binary()} run_git(Args, Dir, Input) when is_list(Args), is_binary(Dir) -> case os:find_executable("git") of false -> {error, <<"git not found in PATH">>}; Git -> ArgList = [to_list(A) || A <- Args], case Input of none -> run_port(Git, ArgList, to_list(Dir), undefined); {some, Bin} when is_binary(Bin) -> run_with_stdin_file(Git, ArgList, to_list(Dir), Bin); Bin when is_binary(Bin) -> run_with_stdin_file(Git, ArgList, to_list(Dir), Bin) end end. run_with_stdin_file(Git, ArgList, Dir, Bin) -> Tmp = tmp_path(), case file:write_file(Tmp, Bin) of ok -> try ShArgs = [ "-c", "exec \"$0\" \"$@\" < \"$GITPROXY_STDIN\"", Git | ArgList ], Env = [{"GITPROXY_STDIN", Tmp}], run_port_sh(ShArgs, Dir, Env) after _ = file:delete(Tmp) end; {error, Reason} -> {error, reason_bin(Reason)} end. run_port(Git, ArgList, Dir, undefined) -> PortSettings = [ {args, ArgList}, {cd, Dir}, binary, stream, eof, exit_status, hide, use_stdio, stderr_to_stdout ], Port = open_port({spawn_executable, Git}, PortSettings), collect_port(Port, []). run_port_sh(ShArgs, Dir, Env) -> case os:find_executable("sh") of false -> {error, <<"sh not found in PATH">>}; Sh -> PortSettings = [ {args, ShArgs}, {cd, Dir}, {env, Env}, binary, stream, eof, exit_status, hide, use_stdio, stderr_to_stdout ], Port = open_port({spawn_executable, Sh}, PortSettings), collect_port(Port, []) end. collect_port(Port, Acc) -> receive {Port, {data, Data}} -> collect_port(Port, [Data | Acc]); {Port, eof} -> port_close(Port), Exit = receive {Port, {exit_status, Code}} -> Code after 5000 -> 1 end, Out = iolist_to_binary(lists:reverse(Acc)), case Exit of 0 -> {ok, Out}; _ -> {error, Out} end after 120000 -> catch port_close(Port), {error, <<"git command timed out">>} end. tmp_path() -> Base = case os:getenv("TMPDIR") of false -> "/tmp"; Dir -> Dir end, filename:join( Base, "gitproxy-stdin-" ++ integer_to_list(erlang:unique_integer([positive])) ). to_list(Bin) when is_binary(Bin) -> unicode:characters_to_list(Bin); to_list(List) when is_list(List) -> List. memory_new() -> ets:new(gitproxy_memory, [public, set]). memory_put(Tid, Key, Value) when is_reference(Tid), is_binary(Key), is_binary(Value) -> true = ets:insert(Tid, {Key, Value}), nil. memory_get(Tid, Key) when is_reference(Tid), is_binary(Key) -> case ets:lookup(Tid, Key) of [{_, Value}] -> {ok, Value}; [] -> {error, nil} end. memory_keys(Tid) when is_reference(Tid) -> ets:select(Tid, [{{'$1', '_'}, [], ['$1']}]). uuid_v4() -> <> = crypto:strong_rand_bytes(16), C2 = (C band 16#0fff) bor 16#4000, D2 = (D band 16#3fff) bor 16#8000, list_to_binary( io_lib:format( "~8.16.0b-~4.16.0b-~4.16.0b-~4.16.0b-~12.16.0b", [A, B, C2, D2, E] ) ). reason_bin(Reason) -> unicode:characters_to_binary(io_lib:format("~p", [Reason])). %% --------------------------------------------------------------------------- %% OAuth / DPoP helpers %% --------------------------------------------------------------------------- open_browser(Url) when is_binary(Url) -> Target = binary_to_list(Url), Cmds = case os:type() of {unix, darwin} -> [{"open", [Target]}]; {win32, _} -> [{"cmd", ["/c", "start", "", Target]}]; _ -> [{"xdg-open", [Target]}] end, open_browser_try(Cmds). open_browser_try([]) -> {error, <<"no browser opener available">>}; open_browser_try([{Cmd, Args} | Rest]) -> case os:find_executable(Cmd) of false -> open_browser_try(Rest); Path -> try Port = open_port( {spawn_executable, Path}, [{args, Args}, hide, binary, exit_status] ), spawn(fun() -> drain_port(Port) end), {ok, nil} catch _:_ -> open_browser_try(Rest) end end. drain_port(Port) -> receive {Port, {exit_status, _}} -> ok; {Port, _} -> drain_port(Port) after 5000 -> catch port_close(Port), ok end. %% Probe whether we can bind 127.0.0.1:Port (closes immediately). oauth_can_bind(Port) when is_integer(Port) -> case gen_tcp:listen(Port, [ binary, {packet, raw}, {active, false}, {reuseaddr, true}, {ip, {127, 0, 0, 1}}, {backlog, 1} ]) of {ok, Listen} -> gen_tcp:close(Listen), true; {error, _} -> false end. %% Listen on 127.0.0.1:Port, wait for one HTTP request, return query string. %% TimeoutMs is the overall wait budget. oauth_wait_callback(Port, TimeoutMs) when is_integer(Port), is_integer(TimeoutMs) -> case gen_tcp:listen(Port, [ binary, {packet, raw}, {active, false}, {reuseaddr, true}, {ip, {127, 0, 0, 1}}, {backlog, 1} ]) of {error, Reason} -> {error, reason_bin(Reason)}; {ok, Listen} -> try case gen_tcp:accept(Listen, TimeoutMs) of {error, Reason} -> {error, reason_bin(Reason)}; {ok, Sock} -> case recv_http_request(Sock, <<>>, TimeoutMs) of {error, Reason} -> gen_tcp:close(Sock), {error, Reason}; {ok, PathQuery} -> Body = <<"HTTP/1.1 200 OK\r\n", "content-type: text/plain; charset=utf-8\r\n", "connection: close\r\n", "content-length: 48\r\n", "\r\n", "Authentication complete. You can close this window.">>, _ = gen_tcp:send(Sock, Body), gen_tcp:close(Sock), {ok, PathQuery} end end after gen_tcp:close(Listen) end end. recv_http_request(Sock, Acc, TimeoutMs) -> case gen_tcp:recv(Sock, 0, min(TimeoutMs, 30_000)) of {error, Reason} -> {error, reason_bin(Reason)}; {ok, Data} -> Buf = <>, case binary:match(Buf, <<"\r\n\r\n">>) of nomatch when byte_size(Buf) > 65536 -> {error, <<"HTTP request too large">>}; nomatch -> recv_http_request(Sock, Buf, TimeoutMs); {Pos, _} -> Header = binary:part(Buf, 0, Pos), case parse_request_line(Header) of {error, _} = E -> E; {ok, PathQuery} -> {ok, PathQuery} end end end. parse_request_line(Header) -> case binary:split(Header, <<"\r\n">>) of [Line | _] -> case binary:split(Line, <<" ">>, [global]) of [_Method, PathQuery | _] -> {ok, PathQuery}; _ -> {error, <<"malformed request line">>} end; _ -> {error, <<"empty request">>} end. %% Generate P-256 keypair for DPoP. Returns {ok, {D, X, Y}} as base64url binaries. dpop_generate_keypair() -> {Pub, Priv} = crypto:generate_key(ecdh, secp256r1), <<4, X:32/binary, Y:32/binary>> = Pub, D = case Priv of <> -> D0; _ when is_binary(Priv), byte_size(Priv) =< 32 -> pad32(Priv); _ -> error({bad_priv, Priv}) end, {ok, {base64url_encode(D), base64url_encode(X), base64url_encode(Y)}}. %% Sign JWT signing-input (header.payload) with ES256 using private key D (base64url). %% Public X,Y also base64url — used only for header jwk construction by Gleam. %% Returns base64url signature (R||S, 64 bytes). dpop_sign_jwt(SigningInput, DB64, _XYIgnored) when is_binary(SigningInput), is_binary(DB64) -> try D = base64url_decode_strict(DB64), D32 = pad32(D), Der = crypto:sign(ecdsa, sha256, SigningInput, [D32, secp256r1]), Raw = der_ecdsa_to_raw(Der), {ok, base64url_encode(Raw)} catch C:E:S -> {error, reason_bin({C, E, S})} end. base64url_encode(Bin) when is_binary(Bin) -> Enc = base64:encode(Bin, #{mode => urlsafe, padding => false}), case is_binary(Enc) of true -> Enc; false -> unicode:characters_to_binary(Enc) end. base64url_decode(Bin) when is_binary(Bin) -> try {ok, base64url_decode_strict(Bin)} catch _:_ -> {error, nil} end. base64url_decode_strict(Bin) -> %% OTP base64 urlsafe may need padding restored Padded = pad_b64(Bin), Decoded = base64:decode(Padded, #{mode => urlsafe}), case Decoded of B when is_binary(B) -> B; {ok, B} when is_binary(B) -> B; Other -> error({bad_base64, Other}) end. pad_b64(Bin) -> case byte_size(Bin) rem 4 of 0 -> Bin; 2 -> <>; 3 -> <> end. random_bytes(N) when is_integer(N), N > 0 -> crypto:strong_rand_bytes(N). sha256(Bin) when is_binary(Bin) -> crypto:hash(sha256, Bin). pad32(Bin) when byte_size(Bin) =:= 32 -> Bin; pad32(Bin) when byte_size(Bin) < 32 -> Pad = 32 - byte_size(Bin), <<0:(Pad * 8), Bin/binary>>; pad32(Bin) when byte_size(Bin) > 32 -> binary:part(Bin, byte_size(Bin) - 32, 32). %% Convert DER ECDSA signature to IEEE P1363 R||S (32+32 bytes). der_ecdsa_to_raw(<<16#30, _Len, Rest0/binary>>) -> {R, Rest1} = der_parse_int(Rest0), {S, _} = der_parse_int(Rest1), <<(pad32(R))/binary, (pad32(S))/binary>>; der_ecdsa_to_raw(Other) -> error({bad_der_sig, Other}). der_parse_int(<<16#02, Len, Rest/binary>>) when Len > 0, byte_size(Rest) >= Len -> <> = Rest, %% INTEGER may have a leading 0x00 for positive values with high bit set Clean = strip_der_int_padding(Int), {Clean, Tail}; der_parse_int(Other) -> error({bad_der_int, Other}). strip_der_int_padding(<<0, RestInt/binary>>) when byte_size(RestInt) > 0 -> case binary:first(RestInt) band 16#80 of 0 -> <<0, RestInt/binary>>; _ -> RestInt end; strip_der_int_padding(Int) -> Int.