diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index 09f0a29de..a45260681 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -191,8 +191,9 @@ The SDK also provides these helpers. depends on it. `mcp_secrets` reads the `mcp` section of `creds.json`. - [`sdk/term_codec`](../src/albedo/harness/sdk/term_codec.gleam): The Erlang external term format for caches and fingerprints that earlier daemons wrote. - `decode_safe` refuses bytes that would create unknown atoms or functions. Use - JSON for new persisted data. + `decode_safe` refuses bytes that would create unknown atoms or functions. + `tuple` and `binary` check decoded shapes exactly. Use JSON for new persisted + data. - [`sdk/log`](../src/albedo/harness/sdk/log.gleam): Warning and debug messages for the daemon's log. Never include secrets or tokens. - [`sdk/process_flag`](../src/albedo/harness/sdk/process_flag.gleam): Flags in diff --git a/src/albedo/harness/extensions/memory/README.md b/src/albedo/harness/extensions/memory/README.md index dbb8ca5d6..cad71991d 100644 --- a/src/albedo/harness/extensions/memory/README.md +++ b/src/albedo/harness/extensions/memory/README.md @@ -85,9 +85,13 @@ interruption between operations, without a power-loss guarantee for directory metadata. The owner is [`files.gleam`](files.gleam). Its native -[`albedo_memory.erl`](albedo_memory.erl) keeps the file, lock, and term-format -primitives that no SDK helper provides. Supporting scenarios live in the -[snapshot tests](../../../../../test/harness/memory_snapshot_test.erl) and +[`albedo_memory.erl`](albedo_memory.erl) keeps the file and lock primitives that +no SDK helper provides. `files.gleam` encodes import receipts and transfer +digests in the external term format through +[`sdk/term_codec`](../../sdk/term_codec.gleam). Supporting scenarios live in the +[snapshot tests](../../../../../test/harness/memory_snapshot_test.erl), +[receipt compatibility tests](../../../../../test/harness/memory_receipt_test.gleam), +and [transfer-owner tests](../../../../../test/harness/transfer_owners_test.gleam). See [workspaces](../../../../../robot-docs/workspaces.md) for transfer ownership and linked-workspace behavior. diff --git a/src/albedo/harness/extensions/memory/albedo_memory.erl b/src/albedo/harness/extensions/memory/albedo_memory.erl index 95966805b..bc5fe56cc 100644 --- a/src/albedo/harness/extensions/memory/albedo_memory.erl +++ b/src/albedo/harness/extensions/memory/albedo_memory.erl @@ -1,10 +1,9 @@ -%% File, lock, and term-format primitives for project memory. The memory -%% policy, snapshots, and import recovery live in files.gleam. +%% File and lock primitives for project memory. The memory policy, +%% snapshots, import recovery, receipts, and digests live in files.gleam. %% %% This stays Erlang for what no SDK helper provides: file errors with their %% posix reason, appends, synced exclusive temporary files, directory -%% listings, a global lock per workspace, and the external term format the -%% import receipts and transfer digests have always used. +%% listings, and a global lock per workspace. -module(albedo_memory). -export([ join/1, @@ -16,10 +15,7 @@ ensure_dir/1, list_dir/1, journals/1, - with_lock/2, - term_digest/1, - encode_receipt/1, - decode_receipt/1 + with_lock/2 ]). -include_lib("kernel/include/file.hrl"). @@ -72,36 +68,6 @@ with_lock(Root, Fun) -> Result -> Result end. -term_digest(Term) -> crypto:hash(sha256, term_to_binary(Term)). - -encode_receipt(State) -> term_to_binary({1, State}). - -%% {ok, {done, Sources}}, {ok, {pending, Sources, Before, After}}, or -%% {error, Reason}. -decode_receipt(Bytes) -> - try binary_to_term(Bytes, [safe]) of - {1, {done, Sources} = State} when is_list(Sources) -> - sources(State, Sources); - {1, {pending, Sources, Before, After} = State} when - is_list(Sources), is_binary(Before), is_binary(After) - -> - sources(State, Sources); - _ -> - {error, <<"invalid memory import receipt">>} - catch - error:badarg -> {error, <<"invalid memory import receipt">>} - end. - -sources(State, Sources) -> - Valid = fun - ({Key, Digest}) -> is_binary(Key) andalso is_binary(Digest); - (_) -> false - end, - case lists:all(Valid, Sources) of - true -> {ok, State}; - false -> {error, <<"invalid memory import sources">>} - end. - atomic_write(Path, Bytes) -> Temp = <>, Result = diff --git a/src/albedo/harness/extensions/memory/files.gleam b/src/albedo/harness/extensions/memory/files.gleam index 6ae0db6ef..f954ec1ca 100644 --- a/src/albedo/harness/extensions/memory/files.gleam +++ b/src/albedo/harness/extensions/memory/files.gleam @@ -7,7 +7,11 @@ import albedo/harness/sdk/digest import albedo/harness/sdk/settings +import albedo/harness/sdk/term_codec import gleam/bit_array +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom import gleam/int import gleam/list import gleam/option.{type Option, None, Some} @@ -46,7 +50,8 @@ type ListError { /// A file's `.imports` receipt: the committed sources, or an import whose /// payload replacement may not have happened yet. Each source pairs a hashed /// origin, transfer, and workspace identity with the imported bytes' digest. -type Receipt { +@internal +pub type Receipt { Done(sources: List(#(BitArray, BitArray))) Pending( sources: List(#(BitArray, BitArray)), @@ -677,12 +682,83 @@ fn journals(root: String) -> List(String) @external(erlang, "albedo_memory", "with_lock") fn with_lock(root: String, run: fn() -> Result(a, String)) -> Result(a, String) -/// The SHA-256 of a value's external term format. -@external(erlang, "albedo_memory", "term_digest") -fn term_digest(term: a) -> BitArray +/// The SHA-256 of a value's external term format, which import keys and +/// transfer digests have always used. +@internal +pub fn term_digest(term: a) -> BitArray { + digest.sha256(term_codec.encode(term)) +} + +/// An import receipt in the external term format earlier daemons wrote: +/// `{1, {done, Sources}}` or `{1, {pending, Sources, Before, After}}`. +@internal +pub fn encode_receipt(state: Receipt) -> BitArray { + term_codec.encode(#(1, state)) +} + +@internal +pub fn decode_receipt(bytes: BitArray) -> Result(Receipt, String) { + let invalid = "invalid memory import receipt" + let shape = { + use term <- result.try(term_codec.decode_safe(bytes)) + use versioned <- result.try(term_codec.tuple(term)) + use state <- result.try(case versioned { + [version, state] -> + case decode.run(version, decode.int) { + Ok(1) -> term_codec.tuple(state) + _ -> Error(Nil) + } + _ -> Error(Nil) + }) + case state { + [tag, sources] -> + case tag_name(tag), list_of(sources) { + Ok("done"), Ok(sources) -> + Ok(#(sources, fn(sources) { Done(sources) })) + _, _ -> Error(Nil) + } + [tag, sources, before, after] -> + case + tag_name(tag), + list_of(sources), + term_codec.binary(before), + term_codec.binary(after) + { + Ok("pending"), Ok(sources), Ok(before), Ok(after) -> + Ok(#(sources, fn(sources) { Pending(sources, before, after) })) + _, _, _, _ -> Error(Nil) + } + _ -> Error(Nil) + } + } + case shape { + Error(Nil) -> Error(invalid) + Ok(#(sources, receipt)) -> + case list.try_map(sources, source) { + Ok(sources) -> Ok(receipt(sources)) + Error(Nil) -> Error("invalid memory import sources") + } + } +} + +fn tag_name(tag: Dynamic) -> Result(String, Nil) { + decode.run(tag, atom.decoder()) + |> result.map(atom.to_string) + |> result.replace_error(Nil) +} -@external(erlang, "albedo_memory", "encode_receipt") -fn encode_receipt(state: Receipt) -> BitArray +fn list_of(value: Dynamic) -> Result(List(Dynamic), Nil) { + decode.run(value, decode.list(decode.dynamic)) |> result.replace_error(Nil) +} -@external(erlang, "albedo_memory", "decode_receipt") -fn decode_receipt(bytes: BitArray) -> Result(Receipt, String) +/// One `{Key, Digest}` pair of binaries. +fn source(value: Dynamic) -> Result(#(BitArray, BitArray), Nil) { + case term_codec.tuple(value) { + Ok([key, digest]) -> + case term_codec.binary(key), term_codec.binary(digest) { + Ok(key), Ok(digest) -> Ok(#(key, digest)) + _, _ -> Error(Nil) + } + _ -> Error(Nil) + } +} diff --git a/src/albedo/harness/sdk/term_codec.gleam b/src/albedo/harness/sdk/term_codec.gleam index 1a6b831e8..3707b31bc 100644 --- a/src/albedo/harness/sdk/term_codec.gleam +++ b/src/albedo/harness/sdk/term_codec.gleam @@ -30,6 +30,35 @@ pub fn decode_safe(bytes: BitArray) -> Result(Dynamic, Nil) { |> result.replace_error(Nil) } +/// The elements of a decoded tuple, in order, for shape checks that must +/// match the tuple's size exactly. Any other value is an error. +pub fn tuple(value: Dynamic) -> Result(List(Dynamic), Nil) { + case is_tuple(value) { + True -> Ok(tuple_to_list(value)) + False -> Error(Nil) + } +} + +/// A decoded binary. A bitstring whose size is not whole bytes is an error. +pub fn binary(value: Dynamic) -> Result(BitArray, Nil) { + case is_binary(value) { + True -> Ok(unsafe_binary(value)) + False -> Error(Nil) + } +} + +@external(erlang, "erlang", "is_binary") +fn is_binary(value: Dynamic) -> Bool + +@external(erlang, "gleam_stdlib", "identity") +fn unsafe_binary(value: Dynamic) -> BitArray + +@external(erlang, "erlang", "is_tuple") +fn is_tuple(value: Dynamic) -> Bool + +@external(erlang, "erlang", "tuple_to_list") +fn tuple_to_list(value: Dynamic) -> List(Dynamic) + @external(erlang, "erlang", "term_to_binary") fn term_to_binary(value: a, options: List(EncodeOption)) -> BitArray diff --git a/test/harness/memory_receipt_test.gleam b/test/harness/memory_receipt_test.gleam new file mode 100644 index 000000000..5198e15c2 --- /dev/null +++ b/test/harness/memory_receipt_test.gleam @@ -0,0 +1,46 @@ +//// Import receipts and transfer digests are bytes earlier daemons wrote, so +//// the Gleam codec must produce and accept exactly the native term format. +//// The golden values came from the former Erlang codec. + +import albedo/harness/extensions/memory/files +import gleam/bit_array + +pub fn receipts_keep_their_stored_bytes_test() -> Nil { + assert bit_array.base16_encode( + files.encode_receipt(files.Done([#(<<"k">>, <<"d">>)])), + ) + == "836802610168027704646F6E656C0000000168026D000000016B6D00000001646A" + assert bit_array.base16_encode( + files.encode_receipt(files.Pending([], <<"b">>, <<"a">>)), + ) + == "83680261016804770770656E64696E676A6D00000001626D0000000161" + assert bit_array.base16_encode(files.term_digest(#("origin", "transfer"))) + == "CF415F5B255D856BBCB7A67B161444A3FE3723D704567C8F918B9CEC2A9A60F7" +} + +pub fn stored_receipts_decode_to_their_state_test() -> Nil { + let assert Ok(done) = + bit_array.base16_decode( + "836802610168027704646F6E656C0000000168026D000000016B6D00000001646A", + ) + assert files.decode_receipt(done) == Ok(files.Done([#(<<"k">>, <<"d">>)])) + let assert Ok(pending) = + bit_array.base16_decode( + "83680261016804770770656E64696E676A6D00000001626D0000000161", + ) + assert files.decode_receipt(pending) + == Ok(files.Pending([], <<"b">>, <<"a">>)) +} + +pub fn malformed_receipts_are_refused_test() -> Nil { + assert files.decode_receipt(<<"garbage">>) + == Error("invalid memory import receipt") + // {2, {done, []}}: an unknown version. + let assert Ok(version) = + bit_array.base16_decode("836802610268027704646F6E656A") + assert files.decode_receipt(version) == Error("invalid memory import receipt") + // {1, {done, [x]}}: a source that is not a pair of binaries. + let assert Ok(source) = + bit_array.base16_decode("836802610168027704646F6E656C000000017701786A") + assert files.decode_receipt(source) == Error("invalid memory import sources") +}