
| Audited | otter-sec/anchor at commit 50c68b9b9b57ce7a6f6014e707febef9abb33401 |
|---|---|
| Date | 11 October 2026 (audited again; first audit 11 October 2026) |
| How it ran | local run on our workstation, full audit, Standard review |
| Verdict after review | Pass with notes (Fail if a High finding remains after review, otherwise Pass with notes) |
Compared with the first audit
Same commit as the first audit: the project's default branch has no later commits (checked 11 October 2026), so nothing could have been fixed upstream in between. Each finding of the first audit (11 October 2026) was checked again against the code audited now. 39 findings in the first audit; 39 still open (27 found again, 12 not reported again but still present). This audit has 143 findings after review, 116 of them new.
| First audit | Finding | Reviewed rating then | Now | In this audit |
|---|---|---|---|---|
| #1 | associatedAddress ignores Token-2022 | Low | Still open | #7 |
| #2 | signAllTransactions result not validated | Low | Still open | #10 |
| #3 | removeEventListener race with add | Low | Still open | #99 |
| #4 | module-global account subscription registry | Low | Still open | #18 |
| #5 | Rust client event sub ends silently | Medium | Still open | #41 |
| #6 | debugger re-resolves paths per frame | Low | Still open | not reported again |
| #7 | GDB accept loop 20 ms poll | Low | Still open | not reported again |
| #8 | nightly cache one version for two binaries | Low | Still open | not reported again |
| #9 | current-version file non-atomic | Low | Still open | not reported again |
| #10 | set_current_dir not restored on error | Low | Still open | not reported again |
| #11 | IDL stream decompressor no total budget | Low | Still open | not reported again |
| #12 | legacy IDL fetch unbounded inflate | Low | Still open | #36 |
| #13 | legacy IDL fetch unchecked slice (panic) | Low | Still open | #36 |
| #14 | base58 metadata decode no limit | Low | Still open | not reported again |
| #15 | TS metadata gunzip/inflate/bs58 no limit | Low | Still open | #35 |
| #16 | anchor account trusts u32 vec count | Low | Still open | #37 |
| #17 | IDL resolution env value exact-case | Low | Still open | not reported again |
| #18 | cli/src/lib.rs very large | Low | Still open | #52 |
| #19 | program.rs / config.rs large | Low | Still open | #52 |
| #20 | resolver does not coalesce fetches | Low | Still open | #29, #30 |
| #21 | anchor new deletes existing lib.rs | Medium | Still open | not reported again |
| #22 | anchor init --force overwrites silently | Low | Still open | #83 |
| #23 | solana-verify downloaded, no checksum | Low | Still open | #72 |
| #24 | legacy Solana installer in shared /tmp | Low | Still open | #112 |
| #25 | installer hashes from same bucket | Low | Still open | #80 |
| #26 | default keypair path built 7 times | Low | Still open | #61 |
| #27 | prerelease logic duplicated in scripts | Low | Still open | #92 |
| #28 | host target detection duplicated | Low | Still open | #62 |
| #29 | template.rs <-> lib.rs import cycle | Low | Still open | not reported again |
| #30 | npm publish no version assertion | Low | Still open | #68 |
| #31 | npm wrapper repeats warning | Info | Still open | not reported again |
| #32 | program keypair default perms | Low | Still open | #116 |
| #33 | remove_dir_all weak path checks | Low | Still open | #120, #121 |
| #34 | surfpool wait no timeout / leak | Low | Still open | #119 |
| #35 | IDL history accepts foreign chunks | Medium | Still open | not reported again |
| #36 | websocket callback decodes unguarded | Low | Still open | #40 |
| #37 | fetchMultiple throws, docs say null | Low | Still open | #100 |
| #38 | fixed 1000-byte encode buffer | Low | Still open | #101 |
| #39 | make publish omits two crates | Low | Still open | #75 |
Each finding keeps the number it has in the audit report. The rating shown first is the one after review; the first automated rating is listed with it. 86 findings were first rated Medium or High; 16 of them are Medium or High after review. Text marked "From the report" is quoted from the audit report; fixes are suggestions and were not tested. Code locations link to the file and line at the audited commit.
Medium after review (16)
spl/src/metadata.rs:512From the report
collection: *ctx.accounts.metadata.key,
collection_authority: *ctx.accounts.collection_authority.key,
metadata: *ctx.accounts.metadata.key,
the context has a collection account that is never read. The CPI references the wrong account, so it fails or targets the wrong metadata.
use *ctx.accounts.collection.key.
spl/src/metadata.rs:533From the report
collection: *ctx.accounts.metadata.key,
this is the same defect as finding 11, here for sized collections.
use *ctx.accounts.collection.key.
cli/src/config.rs:1305From the report
if let Some(startup_wait) = other_test.startup_wait {
my_test.startup_wait = Some(startup_wait);
}
an overriding test file's shutdown_wait and upgradeable values are silently ignored.
carry every field in the merge, and destructure the overriding struct exhaustively.
cli/src/config.rs:907From the report
workspace: (!self.workspace.members.is_empty() || !self.workspace.exclude.is_empty())
.then(|| self.workspace.clone()),
keys sync and new rewrite the file. A project that only sets idls/types loses them.
write the workspace table whenever it differs from the default.
cli/src/lib.rs:6954From the report
deployment.address = Pubkey::try_from(actual_program_id.as_str()).unwrap();
fs::write(cfg.path(), cfg.to_string())?;
- The config being saved already includes
--provider.*overrides (config.rs:675-680) and an absolute wallet path, so values meant for one run become permanent. - Re-serializing also drops the user's comments and formatting.
config set(lib.rs:6762) does the same.
keep the persisted config separate from the effective config, and edit only the intended keys with a format-preserving TOML editor.
cli/src/debugger/gdb.rs:82From the report
if let Ok(captures) = self.captures.lock() {
if let Err(e) = write_pending_captures(&self.profile_dir, &captures) {
the captures are written only when the guard is dropped. std::process::exit on a failing test (lib.rs:5039) skips that, so traces are lost in exactly the case the debugger is meant for.
flush captures explicitly before exiting, or return the exit code to the entry point.
client/src/lib.rs:414From the report
let events = parse_logs(&logs.value.logs, &program_id_str)?;
let _ = self.handle.await; // line 277
one unparsable log (or a bad signature at line 404) ends the listener task. The error is discarded on unsubscribe, so later events are silently missed.
log or forward per-notification errors and keep the loop running. Return the task's result on unsubscribe.
cli/src/lib.rs:1125From the report
if let Ok(Some(cfg)) = Config::discover(cfg_override) {
if Anchor.toml exists but has an error, the command quietly uses the Solana CLI config, or mainnet with the default wallet.
propagate the config error, fall back only when no Anchor.toml exists, and print which cluster and wallet were chosen.
lang/attribute/account/src/lazy.rs:66From the report
#ty_as_lazy::size_of(&self.__info.data.borrow()[self.#offset_of_ident()..])
each offset calls the previous offset and size, and that size calls the offset again. Accounts with many variable-size fields exhaust the compute budget.
compute offsets once (a running sum or cache).
Review: opt-in Lazy accounts only
lang/syn/src/codegen/program/idl.rs:187From the report
idl_account.authority = *accounts.from.key;
the first signer becomes the IDL authority of any program that enables the legacy IDL instructions. That person can then publish misleading layouts.
require the program's upgrade authority, or drop the legacy path.
idl/src/convert.rs:619From the report
IdlType::String => seed.value.to_string().as_bytes().into(),
the seed bytes include " characters, so clients derive the wrong PDA.
use seed.value.as_str(), and add a round-trip test.
Review: ` keeps the quotes)
cli/src/lib.rs:1237From the report
let result = process_command(opts);
restore_toolchain(restore_cbs)?;
failed tests, builds and migrations call process::exit (lines 5039, 3048, 6524). The machine-wide Solana version then stays switched.
return exit codes to entry, or restore the toolchain in a drop guard.
cli/src/lib.rs:6407From the report
None => program.keypair_file()?.path().clone(),
on a fresh clone, a new keypair is generated and deployed to. The id mismatch is only a warning (line 2340, marked FIXME).
make a missing or mismatched keypair a hard error in deploy.
cli/src/program.rs:1910From the report
loader_v3_instruction::set_upgrade_authority(
&program_id, ¤t_authority_keypair.pubkey(), new_upgrade_authority.as_ref(),
with both flags given, the tool prints "Making program immutable" but sets the new authority. The user believes the program is frozen.
declare the flags as conflicting, and pass None whenever --final is set.
Review: `, so the authority is set, not removed. The "Making program immutable" text the report quotes is in the deploy path, program.rs:1303, not this one)
cli/src/legacy_idl.rs:629From the report
for retries in 0..20 {
...
match client.send_and_confirm_transaction_with_spinner(&tx) {
after a confirmation timeout, a re-signed retry can append the same chunk twice and corrupt the on-chain IDL.
check the signature status or the account length before retrying.
cli/src/config.rs:823From the report
(Ok(h), Ok(w)) if h.domain() == w.domain() => s.serialize_str(http),
IP hosts, and same-domain URLs with different ports, lose their custom websocket endpoint.
collapse to one string only when ws equals the value that would be derived from http.
Review: is None for IP hosts and ignores ports, so the ws` entry is silently dropped on rewrite; same class as #15)
Low after review (123)
From the report
::anchor_spl::associated_token::create(CpiContext::new(associated_token_program.key(), ...
let #cpi_context = anchor_lang::context::CpiContext::new(system_program.key(), #cpi_accounts);
the parser (lang/syn/src/parser/accounts/mod.rs:156) only checks that fields named system_program, token_program or associated_token_program exist. It never checks their type. If a developer declares one of them as an unchecked account, the generated init code sends the payer's signed CPI (or a PDA payer's seeds) to any program the caller supplies.
require the field type to be the matching Program<...> / Interface<TokenInterface> at parse time. Alternatively, have the generated code compare the key with the canonical program ids before each CPI.
spl/src/token_2022.rs:21From the report
let ix = spl_token_2022::instruction::transfer(&ctx.program_id, ctx.accounts.from.key, ...
if key != ctx.program_id {
the target program comes from the caller-built context. The return-data check compares against that same unchecked value, so it proves nothing.
require ctx.program_id to be the legacy token id or the Token-2022 id, and compare return data against the canonical id.
From the report
ctx.accounts.token_program_id.key,
ctx.accounts.mint.key,
transfer_fee_config_authority,
these wrappers sign authority changes with invoke_signed toward a program id that nothing validates.
check token_program_id against the Token-2022 id in each wrapper, or type the field as the token interface.
spl/src/token_interface.rs:98From the report
let mint_data = account.data.borrow();
let mint_with_extension =
StateWithExtensions::<spl_token_2022::state::Mint>::unpack(&mint_data)?;
extension-authority constraints rely on data read from any account, and borrow() panics when a mutable borrow is active.
check the owner against the token program ids first, and use try_borrow_data().
spl/src/metadata.rs:194From the report
token_program: spl_token_interface::ID,
these wrappers cannot be used with Token-2022 mints, while sibling wrappers use the caller's token program. The convention is inconsistent.
take the token program from a validated account restricted to the two known ids, or document that only the legacy program is supported and remove the unused field.
ts/packages/anchor/src/utils/token.ts:17From the report
[owner.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],
ASSOCIATED_PROGRAM_ID
the helper returns the wrong address for Token-2022 mints.
add a token-program parameter that defaults to the legacy id.
From the report
if (name === "tokenAccount") {
const account = decodeTokenAccount(accountInfo.data);
any account whose bytes fit the layout is accepted, and its fields are then used as PDA seeds.
reject the account unless its owner is one of the two token programs.
From the report
let #lamport_amt = #field_info.lamports().checked_sub(#new_rent_minimum).unwrap();
anchor_lang::Lamports::add_lamports(#payer_ref, #lamport_amt)?;
on a shrink, the released rent goes to whichever mutable account is named as payer. That account does not have to be a signer or the original funder.
require the realloc payer to be a signer, and return an error instead of unwrapping.
ts/packages/anchor/src/provider.ts:260From the report
const signedTxs = await this.wallet.signAllTransactions(txs);
const tx = signedTxs[k];
const rawTx = tx.serialize();
a wallet that drops or rejects entries causes a failure mid-batch, after earlier transactions have already been sent.
before sending anything, check the returned count and that the required signatures are present.
idl/src/convert.rs:452From the report
generics: Default::default(),
ty: value.ty.into(),
converting a legacy IDL loses its generic parameters, although the reverse conversion carries them.
map the legacy generics list into type generics, and add a round-trip test.
From the report
this._accounts = accounts;
return resolved;
the builder (methods.ts:182-184) keeps its own reference. If a custom resolver returns a new object, the builder never sees the accounts it resolved.
merge the result into the shared object (Object.assign), or let the builder read accounts back from the resolver.
From the report
const sub = subscriptions.get(address.toString());
if (sub) {
return sub.ee;
the subscription map is module-wide (line 397). A second client for the same address, with another account type or provider, receives the first client's emitter and decoder. An unsubscribe from one client also removes the subscription for all of them.
key subscriptions per client instance, or by program, account type, address and commitment.
cli/src/config.rs:706From the report
if !deploy_dir.exists() && !cfg.programs.contains_key(&Cluster::Localnet) {
println!("Updating program ids...");
keys_sync(&ConfigOverride::default(), None)?;
nearly every command loads the config. On a fresh checkout, a read-only command can create keypairs and rewrite declare_id! and Anchor.toml.
keep config loading free of side effects, and run the sync explicitly in build/init.
avm/src/lib.rs:915From the report
if !nightly_enabled() {
backup_stable_avm()?;
}
the nightly binary is activated before the state flag is written (line 922). If enabling is interrupted, the next enable backs up the nightly binary over the stable backup.
write the state first, or make enable/disable one transactional routine. Refuse to overwrite the backup with a non-stable binary.
cli/src/lib.rs:4981From the report
let Some(cmd) = scripts.get(script_name) else {
bail!("Not able to find script for `{}`", script_name);
};
the validator has already been started (lines 4912-4946) and is killed only further down. It keeps the port, so the next run fails.
resolve the script before starting the validator, or hold the child process in a guard that kills it on drop.
cli/src/lib.rs:7121From the report
std::io::stdin().lock().lines().next().unwrap().unwrap();
when stdin is at end-of-file (CI, containers, nohup), this panics right after the validator starts and leaves it orphaned. The same code is at line 5018.
handle end-of-file by shutting down, or wait on a signal instead.
cli/src/lib.rs:2998From the report
docker_exec(container_name, &["rm", "-rf", target_dir.to_str().unwrap()])?;
if this step fails, docker rm -f never runs. Because the container name is fixed, every later verifiable build then fails.
always remove the container, clear stale containers before starting, and use a unique name per build.
cli/src/debugger/gdb.rs:507From the report
while start.elapsed() < window && !cancel.load(Ordering::Acquire) {
if let Ok(s) = TcpStream::connect(("127.0.0.1", port)) { return Some(s); }
thread::yield_now();
one thread is spawned per instruction (line 438) and spins on connect. Long traces become extremely slow.
use one long-lived watcher or a notification channel, or at least add backoff.
client/src/lib.rs:263From the report
pub struct EventUnsubscriber<'a> {
handle: JoinHandle<Result<(), ClientError>>,
if the handle is dropped without calling unsubscribe(), the subscription task keeps running.
implement Drop to abort the task or unsubscribe.
avm/src/lib.rs:1021 (line corrected on review; the report cites :1019)From the report
if now - ts < UPDATE_CHECK_INTERVAL_SECS && nightly_binaries_exist() {
activate_nightly_avm()?;
the whole binary is copied on every call, even when nothing changed.
copy only when the size or hash differs.
From the report
while ((await this.resolvePdasAndRelations(this._idlIx.accounts)) + (await this.resolveCustom()) > 0) {
accounts that cannot be resolved are fetched again on every pass, up to 16 passes.
stop when a pass resolves nothing new, and cache failed lookups for the duration of the resolve.
From the report
if (!this._cache.has(address)) {
the account type that was requested is not part of the cache key.
include the requested name in the key, and check that the decoded type matches it.
ts/packages/anchor/src/workspace.ts:67From the report
if (cargoTargetDirectoryCache !== undefined) { return cargoTargetDirectoryCache; }
a cached value can be stale after cwd or CARGO_TARGET_DIR changes.
key the cache by those inputs, or do not cache.
From the report
this._resolveAccounts = true; // accountsPartial
this._resolveAccounts = false; // accountsStrict (line 237)
the resulting behaviour depends on the order in which the methods are called.
reject mixed use, or set the mode once.
ts/packages/anchor/src/utils/rpc.ts:110From the report
const results = await Promise.all(batches.map((batch) => getMultipleAccountsAndContextCore(connection, batch, commitment)));
large requests can hit RPC rate limits.
limit how many requests are in flight, and back off on 429 responses.
cli/src/lib.rs:5545From the report
idl.address = address;
the generated TypeScript types and the workspace copies keep the old address.
route address updates through one function that refreshes every copy.
ts/packages/anchor/src/idl.ts:475From the report
case MetadataCompression.Gzip:
return Buffer.from(ungzip(data));
case MetadataCompression.Zlib:
IDL data is controlled by whoever publishes it, and the resolver fetches it automatically. A compression bomb exhausts the client's memory.
inflate with a hard cap on output size (a few MiB), and reject anything larger.
cli/src/legacy_idl.rs:248From the report
let compressed_bytes = &account.data[44..44 + compressed_len];
let mut z = ZlibDecoder::new(compressed_bytes);
z.read_to_end(&mut s)?;
an inconsistent length panics on the slice, and a crafted stream expands without limit. The sibling fetch path already caps decompression at 16 MiB.
check the bounds, and read through .take(MAX) with the shared cap.
cli/src/lib.rs:4260From the report
let mut vec_data: Vec<JsonValue> = Vec::with_capacity(size);
a length of up to 4 billion read from account data aborts anchor account by exhausting memory.
cap the pre-allocation by the remaining bytes, and add depth and element budgets.
ts/packages/borsh/src/index.ts:266From the report
if (elementLayout.span < 0 && count > remainingBytes) {
elements with span 0 are never checked. A 4-byte length can drive about 4 billion iterations from a tiny buffer.
cap the count for zero-size elements, or reject them.
ts/packages/anchor/src/utils/case.ts:14From the report
.replace(/([A-Z][A-Z\d]*)([A-Z][a-z])/g, "$1 $2")
every name in an untrusted on-chain IDL is converted. A very long upper-case identifier stalls the event loop.
use a linear tokenizer, or cap identifier length before conversion.
From the report
data: layout.layout.decode(logArr.subarray(givenDisc.length)),
a decode error inside the websocket callback stops the remaining events of that transaction from being delivered.
catch decode errors per event, and guard each user callback.
cli/src/config.rs:80From the report
pub commitment: Option<CaseInsensitiveCommitmentLevel>,
only log subscriptions use the option (lib.rs:7566). Every other client is hard-coded to confirmed.
pass the option through to every client, or remove it.
lang/src/lazy.rs:115From the report
(0..get_len(buf)).fold(LEN, |acc, _| acc + T::size_of(&buf[acc..]))
the element count read from account bytes is not compared with the buffer length.
reject counts the remaining bytes cannot hold.
idl/spec/src/lib.rs:344From the report
if let Some(inner) = s.strip_prefix("Option<") {
let inner_ty = Self::from_str(
deeply nested input can exhaust the stack.
pass a depth counter and fail past a small limit.
avm/src/lib.rs:1175From the report
let bytes = response.bytes()
an oversized response is held entirely in memory.
check the length and stream with a maximum size.
cli/src/fetch/pmp.rs:472From the report
let mut eligible = fetch_signatures_for_address(client, account_address, None, None, Some(before_or_at_slot), tuning.max_signatures,
nested replays multiply RPC work with no total limit.
add a global transaction cap and a deadline.
cli/src/fetch/rpc.rs:113From the report
loop { let config = GetConfirmedSignaturesForAddress2Config { ... limit: Some(IDL_SIGNATURE_PAGE_SIZE),
only the entries kept are capped, not the pages scanned.
cap the number of pages scanned.
cli/src/codama.rs:602From the report
type_node_from_anchor(inner_ty, &scoped)
expansion is recursive with no depth or node budget.
track depth and the instantiations already visited.
avm/src/lib.rs:1037From the report
if let Err(err) = install_nightly_manifest(&manifest, skip_attestation) {
write_nightly_cache_error();
the underlying error is dropped and a cached build is activated. That error can be a failed provenance check.
print the error, and say clearly that a cached build is in use.
cli/src/lib.rs:1From the report
mod abs_path; mod account; ... pub mod fetch; ... mod program;
lib.rsis about 8.6k lines and mixes parsing, build, validators, IDL, deploy and keys.program.rs(3.2k),config.rs(2.4k),template.rs(2.2k) andcodama.rs(1.9k) are similarly mixed.
This makes changes risky.
split by responsibility, and keep only dispatch in lib.rs.
From the report
fn generate_constraint_init_group(
- The function is about 730 lines, in a 2,078-line file with one block repeated 12 times.
parser/accounts/constraints.rs(about 1.9k lines) andlang/syn/src/lib.rs(about 1.3k lines) are similar.
split by constraint kind, and share the repeated mint-extension checks.
avm/src/lib.rs:1From the report
mod attestation;
pub mod idl_nightly;
pub mod platform_tools;
avm/src/lib.rs, client/src/lib.rs and idl/src/convert.rs each exceed 1,000 lines and mix several concerns.
extract the nightly, update-check and install modules, plus the event parsing and the separate conversion directions.
cli/src/config.rs:1808From the report
pub fn keypair_file(&self) -> Result<WithPath<File>> {
a read-style accessor creates a new program identity when the key is missing.
split it into a read that fails when the key is missing and an explicit create.
cli/src/lib.rs:4368From the report
std::env::set_var(crate::debugger::gdb::SOCKET_ENV, driver.sock_path());
the process environment is changed after the accept thread has started, and helpers call process::exit.
set the environment before spawning threads, or pass it per child, and return errors instead of exiting.
cli/src/fetch/rpc.rs:31From the report
pub(super) fn create_rpc_client(cfg_override: &ConfigOverride) -> Result<RpcClient> {
the copies (also account.rs:113, legacy_idl.rs:223, lib.rs:1123) use different defaults.
use one shared resolver.
cli/src/debugger/arena.rs:581From the report
fn short_pid(pid: &str) -> String { ... &pid[..8] ...
parse_transaction_data, short_pid, cargo_home and the no-op contexts each exist twice, and these byte slices panic on non-ASCII input.
keep one crate-level copy of each.
cli/src/lib.rs:3438From the report
let is_localnet = cluster_url.contains("localhost") || cluster_url.contains("127.0.0.1");
substring matching also accepts real hostnames that contain these strings, and an IDL write is then skipped with exit code 0.
use one helper that parses the host.
cli/src/legacy_idl.rs:339From the report
for retries in 0..20 {
the retry logic and its count can drift apart between copies.
extract one send-with-retries helper.
cli/src/keygen.rs:128From the report
path.push(".config"); path.push("solana"); path.push("id.json");
the copies can drift, and expect panics when there is no home directory.
use one helper that does not panic.
avm/src/lib.rs:534From the report
let output = Command::new("rustc").arg("-vV").output()?;
these helpers duplicate rustc_host_target, and idl_nightly.rs:231 duplicates find_ancestor_file.
reuse the shared helpers.
cli/src/lib.rs:6245From the report
_ => "http://127.0.0.1:8899".to_string(),
changing DEFAULT_RPC_PORT would leave stale copies behind.
build these URLs from the constants.
cli/src/lib.rs:5074From the report
fn rent_exempt_minimum(data_len: u64) -> u64 { (128 + data_len) * 3480 * 2 }
this diverges from the cluster's rent parameters, which are used elsewhere in the same crate.
read the rent parameters from the cluster.
cli/src/account.rs:51From the report
"rentEpoch": account.rent_epoch,
JavaScript consumers lose precision; for example, u64::MAX is common here.
emit 64- and 128-bit integers as strings.
cli/src/program.rs:2969From the report
.filter(|e| format!("{:?}", e) != "AlreadyProcessed")
- After the write phase, the buffer is not read back and compared with the binary before the irreversible deploy or upgrade.
- Resume uses a snapshot that may still be changing on timeout (line 265).
- Errors are filtered by their Debug text.
A corrupted program can go on-chain, and possibly be made immutable.
compare the buffer byte for byte (or by hash) before deploying, and match on the error variant.
.github/workflows/release.yaml:153From the report
if grep -q "no packages selected" "$out_file" \
&& grep -q "disabled due to previous publish" "$out_file"; then
a tag whose sources carry another version is treated as "already published", and a release and an image are still produced under that tag.
compare the tag with VERSION, the Cargo workspace version and package.json in verify-tag.
.github/workflows/release-pr.yaml:9From the report
- .github/workflows/publish-crates.yaml
- .github/workflows/publish-npmjs.yaml
edits to the real release.yaml never trigger the rehearsal, and the dry-run uses a different toolchain from the release.
watch release.yaml, and use the same toolchain and flags.
cli/npm-package/package.json:18From the report
"prepack": "[ ... ] && (echo Can be packed only on x86_64 GNU/Linux && exit 1) || ([ ... ] && (echo Check anchor binary version && exit 2) || exit 0)"
the trailing || exit 0 swallows both failures, so a wrong-platform or wrong-version binary can be published.
rewrite the guard as explicit if/else in a checked script, and run it in the publish job.
Review: maintainer-only, borderline
From the report
const { channel, date, version, git_sha, git_short_sha, github_run_id } = manifests[0].data;
each matrix job checks out master separately (line 50). A commit that lands between jobs produces a mixed set, labelled with the first job's commit.
resolve the commit once, check out that commit in every job, and assert all manifests agree.
avm/src/lib.rs:662From the report
let bin_path = get_bin_dir_path().join("solana-verify");
fs::write(&bin_path, res.bytes()?)?;
solana-verify, and the platform-tools archive later run as a compiler (platform_tools.rs:586), are installed with no checksum or attestation check. The Anchor binaries are attested.
verify a pinned SHA-256 or an attestation before installing. Where that is impossible, print an explicit "unverified" warning.
cli/src/template.rs:739From the report
read_keypair_file(&keypair_path)
.unwrap_or_else(|_| {
let keypair = Keypair::new();
a transient read error or a malformed file destroys the key that controls the program address.
create a key only when the file is not found, and report every other error.
Review: )` overwrites; called only by init/new paths, lib.rs:1859, 2107)
avm/install:333From the report
if ! ln -sfn "$BIN_DIR/anchor" "$cargo_bin/anchor" 2>/dev/null; then
a cargo-installed stable anchor is overwritten without a backup.
check whether the target exists, then back it up or ask first, and print what was replaced.
Makefile:15From the report
publish:
cd lang/syn/ && cargo publish && cd ../../
sleep 25
the target omits crates that others pin exactly (for example lang/error, cli/cli-macros), so it fails midway. It also bypasses the signed-tag release flow.
delete the target, or call the same release command as CI.
.github/workflows/release.yaml:344From the report
RELEASE_CHANGELOG="$(echo $GITHUB_REF_NAME | sed 's/\.//g' | sed 's/^v//')---$(date '+%Y-%m-%d')"
bump-version.sh:146 dates the heading on bump day. A release on another day links to an anchor that does not exist.
derive the anchor from the changelog heading itself.
.github/workflows/release.yaml:191From the report
publish-npmjs:
needs: verify-tag
five independent publish jobs run with no closing verification, so one failure leaves a half-published release.
add a final job that installs the published artifacts and checks their versions.
cli/src/program.rs:1675From the report
println!("Signature: {}", signature); Ok(())
success is reported on transaction confirmation alone.
compare the program data's length and hash with the uploaded binary.
avm/src/platform_tools.rs:618From the report
if target.exists() { fs::remove_dir_all(target)...?; }
fs::rename(staging, target)...?;
if the rename fails, the user is left without a toolchain.
rename the old install aside, swap in the new one, and restore the old one on failure.
avm/install:303From the report
[ "$actual_sha" = "$expected_sha" ] || fail "checksum mismatch ..."
the checksum comes from the same bucket as the artifact. The size field is ignored, and the existing attestations are not checked.
verify the build attestation, and check the size.
avm/install:357From the report
nightly_version="$(field "$avm_line" 1)"
anchor_version="$(field "$anchor_line" 1)"
both values come from the same manifest field, so a mixed set is never detected.
compare per-artifact identifiers such as the commit.
cli/src/program.rs:2296From the report
let mut file = File::create(&output_file)
program dump, the coverage output (coverage.rs:146) and fetch output overwrite existing files.
use create_new, or require --force.
cli/src/lib.rs:1842From the report
if force { ... fs::remove_dir_all(default_program_dir)?; }
customised Anchor.toml and security.json files are replaced without a prompt.
list what will be replaced and ask first, or skip files that already exist.
cli/src/lib.rs:7378From the report
let client = RpcClient::new(cluster_url);
these commands read finalized state while the rest of the CLI reads confirmed.
route them through create_client().
avm/src/lib.rs:1445From the report
eprintln!("avm update check failed. Next attempt in {next_attempt_secs}s.");
the repeated line drowns out real warnings.
print it once per window, or only in verbose mode.
ts/packages/anchor/src/utils/rpc.ts:202From the report
console.error(res.error.message, logTrace);
throw new SendTransactionError(...)
the output duplicates the thrown error, and callers cannot silence it.
drop the console output, or put it behind a debug flag.
avm/src/platform_tools.rs:84From the report
static MAP: LazyLock<ParsedMap> = LazyLock::new(|| { ...
the copies in solana.rs and idl_nightly.rs can drift apart.
use one generic loader.
cli/src/program.rs:1500From the report
RpcSendTransactionConfig { skip_preflight, preflight_commitment: Some(CommitmentConfig::confirmed().commitment), ...
the copies can drift apart.
use one helper.
.github/workflows/benchmark-sync.yaml:24From the report
SOLANA_VERSION: 3.1.10
other workflows use 4.1.2 or 4.1.0-rc.1, and the checkout action is pinned at three major versions.
keep one source of truth, and document deliberate differences.
.github/actions/setup-ts/action.yaml:16 (line corrected on review; the report cites :13)From the report
- uses: nick-fields/retry@... # v2
the block is repeated more than ten times.
loop over the packages in one step, and reuse the action.
ts/packages/anchor/src/provider.ts:177 (line corrected on review; the report cites :175)From the report
if (err instanceof ConfirmError) {
this logic appears in two methods, and the blockhash check in three.
extract shared helpers.
.github/workflows/release.yaml:401 (line corrected on review; the report cites :399)From the report
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-.+ ]]; then
the same logic also lives in publish-npmjs.sh.
move it into one shared script.
lang/src/vec.rs:36From the report
T::try_accounts(program_id, accounts, ix_data, bumps, reallocs)
.map(|item| vec.push(item))?;
Ok(vec)
a Vec<Account<..>> field looks as if it validates every supplied account. In fact it validates one, and the rest stay unchecked in the remaining slice.
loop until the slice is exhausted (or up to a declared count), or reject Vec<T> at compile time.
lang/syn/src/codegen/program/idl.rs:235From the report
new_rent_minimum
.checked_sub(idl_ref.lamports())
.unwrap(),
anyone can send lamports to this deterministic address. Once it holds more than the minimum, resize panics permanently.
use saturating arithmetic, and skip the transfer when the account is already funded.
lang/src/accounts/account_loader.rs:190From the report
bytemuck::from_bytes(&data[disc.len()..mem::size_of::<T>() + disc.len()])
with a custom discriminator whose length is not a multiple of the type's alignment, load, load_mut and load_init abort on every call.
use try_from_bytes, and assert the alignment at compile time.
From the report
await this._provider!.connection.removeOnLogsListener(this._onLogsSubscriptionId);
this._onLogsSubscriptionId = undefined;
a listener added during the await sees the old id and skips subscribing, so it never receives events.
clear the id before the await, or serialise add and remove.
From the report
data: this._coder.accounts.decode(this._idlAccount.name, account.data),
the method is documented to return null for a wrong discriminator, but decode throws, so one foreign account fails the whole batch.
catch the error per entry and return null.
From the report
const buffer = Buffer.alloc(1000); // TODO: use a tighter buffer.
larger accounts cannot be encoded. Type encoding (types.ts:33) has the same limit.
size the buffer from the layout, or grow it on demand.
ts/packages/anchor/src/provider.ts:270From the report
sigs.push(await sendAndConfirmRawTransaction(this.connection, rawTx, opts));
the first failure throws without the signatures of transactions that already committed, so callers retry them blindly.
attach the partial results and the failing index to the error.
From the report
if (log.startsWith(PROGRAM_LOG) || log.startsWith(PROGRAM_DATA)) {
a program that logs caller-controlled text lets that caller forge events.
decode events only from Program data: lines, and make the free-text path opt-in.
client/src/lib.rs:453From the report
if let Some(log) = l
.strip_prefix(PROGRAM_LOG)
.or_else(|| l.strip_prefix(PROGRAM_DATA))
this is the same weakness as finding 103, in the Rust client.
accept only Program data: lines for events.
From the report
case "i64":
return new BN(value).toArrayLike(Buffer, "le", 8);
the magnitude is encoded instead of two's complement, so negative seeds derive a different PDA from the on-chain program.
use .toTwos(bits) for signed types, and range-check u8/i8.
Review: toArrayLike` encodes the magnitude; the wrong PDA fails the seeds check loudly)
From the report
value && value.data.length !== 0
? this._coder.accounts.decode<T>(this._idlAccount.name, value.data)
an account from another program with the same discriminator is accepted as genuine state.
compare value.owner with the program id before decoding.
From the report
const genericLen = genericArgs.find((g) => g.kind === "const");
the first const argument is taken regardless of its name, so data silently mis-parses.
match the const generic by name.
ts/packages/anchor/src/error.ts:96From the report
const leftPubkey = pubkeyRegex.exec(logs[anchorErrorLogIndex + 2])![1];
const rightPubkey = pubkeyRegex.exec(logs[anchorErrorLogIndex + 4])![1];
missing lines or non-key text throw, and that exception replaces the original transaction error.
null-check every match, and fall back to the untranslated error.
ts/packages/anchor/src/workspace.ts:97From the report
get(workspaceCache: { [key: string]: Program }, programName: string) {
...
programName = toCamelCase(programName);
logging, awaiting or inspecting anchor.workspace throws.
return undefined for non-string keys and for probe names such as then, toJSON and inspect.
ts/packages/anchor/src/provider.ts:365From the report
class SimulateError extends Error {
constructor(readonly simulationResponse: SimulatedTransactionResponse, message?: string) {
super(message);
the error is thrown at line 358 with an empty message and is not exported, so callers can neither read nor match it.
build a message from the error and logs, set the name, and export the class.
avm/src/solana.rs:429From the report
let status = Command::new("sh")
.arg("-c")
.arg(script)
the script is triggered automatically by versions pinned in a cloned project, with no checksum and no confirmation.
verify a pinned checksum, and ask for consent before project-triggered installs.
avm/src/solana.rs:485From the report
let installer = std::env::temp_dir().join(format!("solana-install-init-{target}-{version}"));
fs::write(&installer, bytes)
another local user can pre-create or swap the file, which then runs as the invoking user.
use a private temporary directory with exclusive creation, and verify a checksum before running.
avm/src/lib.rs:617From the report
use_version(Some(version))
project-triggered installs (cli/src/lib.rs:1422, 3253) change the default Anchor version for every other project.
make activation an explicit step.
avm/src/main.rs:468From the report
if !exit.status.success() {
std::process::exit(exit.status.code().unwrap_or(1));
the temporary cargo-proxy directory (a binary copy on Windows) is never cleaned up.
return the code to main, and exit only after the guards are dropped.
client/src/cluster.rs:86From the report
Cluster::Debug => "http://34.90.18.145:8899",
signed traffic goes unencrypted to an address nothing shows the project controls.
remove the variant, or use TLS on a domain the project controls.
cli/src/config.rs:1823From the report
let mut file = File::create(&path)
file.write_all(format!("{:?}", program_kp.to_bytes()).as_bytes())?;
other local users can read the program key. The crate already has a 0600 writer (lib.rs:5081).
use write_keypair_secure.
cli/src/lib.rs:1307From the report
let install_script = std::process::Command::new("curl")
.args(["-sSfL", &format!("https://release.{domain}/v{version}/install")])
.output()?;
the curl exit status is never checked. A failed download produces an empty script, and sh -c "" succeeds.
check the status and that the script is non-empty, and ask before running a downloaded script.
cli/src/lib.rs:6080From the report
loop {
let resp = client.send::<RpcResponse<SurfnetInfoResponse>>(
a stuck runbook hangs anchor test forever, and an RPC error leaves Surfpool running.
add a deadline and error checks, and kill the child on failure.
cli/src/lib.rs:6268From the report
if !ledger_path.is_relative() {
...
fs::remove_dir_all(&ledger_path)
ledger = "." or ".." (possibly inherited through extends) deletes the project or its parent on every test run.
canonicalise the path, require a strict descendant of a tool-owned directory, and reject ...
cli/src/lib.rs:4749From the report
let trace_path = ws.root.join(trace_dir);
anchor coverage --trace-dir . deletes the whole project (line 4767).
enforce containment in the target directory.
cli/src/program.rs:1030From the report
let is_upgrade = rpc_client.get_account(&program_id).is_ok();
a transient error sends an existing program down the fresh-deploy path. The full buffer is written, at a cost in fees, before the deploy fails.
distinguish "not found" from transport errors.
Review: ` at 1030; cost is buffer fees, and the deploy then fails)
cli/src/fetch/legacy.rs:31From the report
all_chunks.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
signatures carry no ordering, so several writes in one slot reassemble scrambled.
use the on-chain order as the tie-break.
cli/src/fetch/pmp.rs:982From the report
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16)
slicing the string by byte offsets panics on multi-byte characters, and in the parallel path that aborts the process.
decode over as_bytes().
cli/src/lib.rs:4221From the report
IdlType::U256 => todo!("Upon completion of u256 IDL standard"),
u256, i256 and generic array lengths crash the command.
return descriptive errors instead.
cli/src/codama.rs:198From the report
let multi_program = idl_paths.len() > 1;
a single-program build in a multi-program workspace switches the layout, and the clean step removes sibling clients.
derive the layout from the workspace's program count.
cli/src/codama.rs:318From the report
"npx".to_string(),
vec!["--yes".to_string(), "codama".to_string()],
the latest published package runs unattended on every build.
pin exact versions.
cli/src/lib.rs:2357From the report
Some(idl) => Some(PathBuf::from(idl)),
these options are plain strings, so the absolute-path conversion skips them. Files are then written relative to each program's directory.
declare the options as PathBuf.
cli/src/legacy_idl.rs:282From the report
with_workspace(cfg_override, |cfg| {
let idl = fs::read(&idl_filepath)?;
run from a subdirectory, the command reads a different file or fails.
use PathBuf so the path is made absolute.
cli/src/checks.rs:19From the report
.and_then(|profile| profile.overflow_checks)
.ok_or(anyhow!("`overflow-checks` is not enabled. ...
overflow-checks = false returns Ok(false), and the caller (lib.rs:2331) only uses ?, so the build proceeds.
fail when the value is false.
Review: an explicit false is the developer's own setting
cli/src/config.rs:1226 (line corrected on review; the report cites :1227)From the report
current_toml.merge(_TestToml::from_path(&canonical_base)?);
a file that extends itself, directly or through others, recurses without end.
track the paths already visited and report the cycle.
cli/src/config.rs:866From the report
if http_key != "http" || ws_key != "ws" {
{ ws = ..., http = ... } is rejected as an invalid key.
deserialize into a struct with named fields.
cli/src/lib.rs:6853From the report
let script_with_args = format!("{script_cmd} {}", script_args.join(" "));
arguments with spaces or shell characters break.
pass them as positional parameters.
cli/src/lib.rs:6495From the report
std::process::Command::new(&command)
.args(&args)
...
.output()
the output of TypeScript migrations is captured and never shown, and a signal exit panics on unwrap (line 6524).
inherit stdio or print the output on failure, and use unwrap_or(1).
Review: at 6498 captures; unwrap()` on the exit code at 6524)
cli/src/template.rs:1442From the report
const __connection = new web3.Connection("{cluster_url}", "processed");
Windows backslashes and quotes in paths or URLs break the generated script or change its code.
embed values as JSON-encoded literals.
cli/src/lib.rs:1217From the report
let priority_fee = priority_fee
.unwrap_or_else(|| get_recommended_micro_lamport_fee(client, write_locked_accounts));
a fee spike or a hostile RPC can make deploy, upgrade and close transactions burn a large part of the payer's balance. The averaging at line 1204 can also overflow.
clamp the fee to a configurable maximum, and use checked arithmetic.
cli/src/metadata.rs:27From the report
let mut command = Command::new("npx");
command.arg("--yes");
command.arg(format!("--package=@solana-program/program-metadata@{PMP_CLIENT_VERSION}"));
- The upgrade-authority keypair path goes to code installed on the fly. Its transitive dependencies are not locked.
- The RPC URL, which may contain an API key, is passed on the command line, where other processes can see it.
vendor or lock the client with integrity hashes, and pass the URL through the environment.
docs-v2/api/mcp.ts:11From the report
const url = process.env.MCP_INDEX_URL ?? `${origin}/docs/search-index.json`
cache.set(origin, await fetch(url).then((r) => r.json()))
- Where the Host header is not pinned, callers choose what the server fetches.
- The cache grows without limit.
- A failed fetch throws on every tool call.
use a configured base URL, check the response, and bound the cache.
Review: origin`, mcp.ts:102; whether the host can be chosen by the caller depends on the hosting setup, CANNOT-VERIFY; an unbounded cache and unchecked fetch are confirmed)
From the report
upload-to-cloud-bucket:
if: github.event.repository.fork == false
permissions:
id-token: write
a manual dispatch on any branch runs that branch's upload code with production bucket credentials, including latest.
restrict the job to master, and add a protected environment.
Info after review (4)
spl/src/token.rs:519From the report
// Field parsers to save compute. All account validation is assumed to be done
// outside of these methods.
amount_bytes.copy_from_slice(&bytes[64..72]);
a short or foreign account causes a slice panic or a wrong value.
return an error when the length is under 165 bytes or the owner is wrong, or document the precondition prominently.
client/src/lib.rs:894 (line corrected on review; the report cites :874)From the report
tokio::time::sleep(Duration::from_millis(500))
this polls even though a pubsub connection that could deliver signature notifications is available.
use a signature subscription, and keep polling with backoff only as a fallback.
cli/src/debugger/cargo_deps.rs:109From the report
let rev_prefix = &hash[..7];
a multi-byte character panics the debugger.
use hash.get(..7).
avm/src/solana.rs:33From the report
const ANCHOR_SOLANA_MAP_TOML: &str = include_str!("../anchor-solana-map.toml");
updating the mapping data requires a new release.
serve the maps as versioned remote data, and keep the embedded copy as a fallback.