Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/reusable-tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,8 @@ jobs:
path: tests/pyth
- cmd: cd tests/realloc && anchor test --skip-lint && npx tsc --noEmit
path: tests/realloc
- cmd: cd tests/accountloader-realloc && anchor test --skip-lint && npx tsc --noEmit
path: tests/accountloader-realloc
- cmd: cd tests/system-accounts && anchor test --skip-lint
path: tests/system-accounts
- cmd: cd tests/misc && anchor test --skip-lint && npx tsc --noEmit
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ The minor version will be incremented upon a breaking change and the patch versi

### Fixes

- lang: Guard `AccountLoader<T>::exit` against zero-copy buffer truncation and bail with `AccountDidNotDeserialize` instead of rewriting the discriminator over an undersized buffer ([#4633](https://github.com/otter-sec/anchor/pull/4633)).
- lang: Set `anchor-lang` Minimum Supported Rust Version to `1.89` ([#4638](https://github.com/otter-sec/anchor/pull/4638)).
- lang: Shorten invariant lifetimes during `Context` creation ([#4363](https://github.com/solana-foundation/anchor/pull/4363)).
- ts: Guard recursive IDL layouts against stack overflows while preserving supported recursive types ([#4604](https://github.com/solana-foundation/anchor/pull/4604)).
Expand Down
5 changes: 5 additions & 0 deletions lang/src/accounts/account_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,11 @@ impl<'info, T: ZeroCopy + Owner> AccountsExit<'info> for AccountLoader<'info, T>
fn exit(&self, program_id: &Pubkey) -> Result<()> {
// Only persist if the owner is the current program and the account is not closed.
if &T::owner() == program_id && !crate::common::is_closed(self.acc_info) {
// Guard against truncation: refuse to rewrite the discriminator over an undersized buffer.
let required = T::DISCRIMINATOR.len() + mem::size_of::<T>();
if self.acc_info.try_data_len()? < required {
return Err(ErrorCode::AccountDidNotDeserialize.into());
}
let mut data = self.acc_info.try_borrow_mut_data()?;
let dst: &mut [u8] = &mut data;
let mut writer = BpfWriter::new(dst);
Expand Down
6 changes: 4 additions & 2 deletions lang/tests/account_loader_truncation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ macro_rules! setup_truncated_account {
#[test]
fn test_load_truncated() {
setup_truncated_account!(key, owner, lamports, data, account_info);
let loader: AccountLoader<ZcStruct> = AccountLoader::try_from(&account_info).unwrap();
let loader: AccountLoader<ZcStruct> =
AccountLoader::try_from_unchecked(&crate::ID, &account_info).unwrap();
assert_eq!(
loader.load().unwrap_err(),
ErrorCode::AccountDidNotDeserialize.into()
Expand All @@ -43,7 +44,8 @@ fn test_load_truncated() {
#[test]
fn test_load_mut_truncated() {
setup_truncated_account!(key, owner, lamports, data, account_info);
let loader: AccountLoader<ZcStruct> = AccountLoader::try_from(&account_info).unwrap();
let loader: AccountLoader<ZcStruct> =
AccountLoader::try_from_unchecked(&crate::ID, &account_info).unwrap();
assert_eq!(
loader.load_mut().unwrap_err(),
ErrorCode::AccountDidNotDeserialize.into()
Expand Down
9 changes: 9 additions & 0 deletions tests/accountloader-realloc/Anchor.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[programs.localnet]
accountloader_realloc = "8GM8KqKaxYb1jEbn5TiqqPqJYsChhjYvfpT2f6KTmUKb"

[provider]
cluster = "localnet"
wallet = "~/.config/solana/id.json"

[scripts]
test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts"
8 changes: 8 additions & 0 deletions tests/accountloader-realloc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[workspace]
members = [
"programs/*"
]
resolver = "2"

[profile.release]
overflow-checks = true
19 changes: 19 additions & 0 deletions tests/accountloader-realloc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "accountloader-realloc",
"version": "0.1.0",
"license": "(MIT OR Apache-2.0)",
"homepage": "https://github.com/otter-sec/anchor#readme",
"bugs": {
"url": "https://github.com/otter-sec/anchor/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/otter-sec/anchor.git"
},
"engines": {
"node": ">=17"
},
"scripts": {
"test": "anchor test"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "accountloader-realloc"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "lib"]
name = "accountloader_realloc"

[features]
no-entrypoint = []
no-log-ix-name = []
cpi = ["no-entrypoint"]
default = []
idl-build = ["anchor-lang/idl-build"]

[profile.release]
overflow-checks = true

[dependencies]
anchor-lang = { path = "../../../../lang" }
bytemuck = { version = "1.4.0", features = ["derive", "min_const_generics"] }
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
use anchor_lang::prelude::*;

declare_id!("8GM8KqKaxYb1jEbn5TiqqPqJYsChhjYvfpT2f6KTmUKb");

#[program]
pub mod accountloader_realloc {
use super::*;

/// Create the zero-copy account with the full required footprint
/// (`DISCRIMINATOR.len() + size_of::<Data>()`).
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
let mut data = ctx.accounts.data.load_init()?;
data.value = 42;
Ok(())
}

/// Shrink the `AccountLoader` to `new_len` bytes
pub fn shrink(_ctx: Context<Shrink>, _new_len: u16) -> Result<()> {
Ok(())
}

/// Verify the account stays readable after the shrink.
pub fn read(ctx: Context<Read>) -> Result<u64> {
let data = ctx.accounts.data.load()?;
Ok(data.value)
}

/// Creates an account as an older program version left it: v1 footprint
/// with the current discriminator. (In a real upgrade the struct name —
/// and therefore the discriminator — doesn't change; the V1/V2 split
/// exists only so both layouts can coexist in this test.)
pub fn initialize_legacy(ctx: Context<InitializeLegacy>) -> Result<()> {
let mut data = ctx.accounts.counter.try_borrow_mut_data()?;
data[..8].copy_from_slice(CounterV2::DISCRIMINATOR);
let v1 = CounterV1 { value: 42 };
data[8..].copy_from_slice(bytemuck::bytes_of(&v1));
Ok(())
}

/// Grows the legacy account to the v2 footprint via the `realloc`
/// constraint, then fills the new field from existing v1 data.
pub fn migrate(ctx: Context<Migrate>) -> Result<()> {
let mut counter = ctx.accounts.counter.load_mut()?;
counter.extra = counter.value * 2;
Ok(())
}

pub fn read_extra(ctx: Context<ReadCounter>) -> Result<u64> {
Ok(ctx.accounts.counter.load()?.extra)
}
}

#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(mut)]
pub authority: Signer<'info>,

#[account(
init,
payer = authority,
seeds = [b"data"],
bump,
space = 8 + core::mem::size_of::<Data>(),
)]
pub data: AccountLoader<'info, Data>,

pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
#[instruction(new_len: u16)]
pub struct Shrink<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"data"],
bump,
realloc = new_len as usize,
realloc::payer = authority,
realloc::zero = false,
)]
pub data: AccountLoader<'info, Data>,

pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Read<'info> {
#[account(seeds = [b"data"], bump)]
pub data: AccountLoader<'info, Data>,
}

#[derive(Accounts)]
pub struct InitializeLegacy<'info> {
#[account(mut)]
pub authority: Signer<'info>,

/// CHECK: holds the v1 layout; written manually in the handler.
#[account(
init,
payer = authority,
seeds = [b"legacy"],
bump,
space = 8 + core::mem::size_of::<CounterV1>(),
owner = crate::ID,
)]
pub counter: UncheckedAccount<'info>,

pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Migrate<'info> {
#[account(mut)]
pub authority: Signer<'info>,

#[account(
mut,
seeds = [b"legacy"],
bump,
realloc = 8 + core::mem::size_of::<CounterV2>(),
realloc::payer = authority,
realloc::zero = false,
)]
pub counter: AccountLoader<'info, CounterV2>,

pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct ReadCounter<'info> {
#[account(seeds = [b"legacy"], bump)]
pub counter: AccountLoader<'info, CounterV2>,
}

#[account(zero_copy)]
#[repr(C)]
pub struct Data {
pub value: u64,
pub padding: [u8; 64],
}

/// The original account layout (8-bytes body + 8-bytes discriminator = 16 bytes).
#[zero_copy]
pub struct CounterV1 {
pub value: u64,
}

/// The upgraded layout: `extra` was added. (16 bytes body + 8 bytes discriminator = 24 bytes)
#[account(zero_copy)]
#[repr(C)]
pub struct CounterV2 {
pub value: u64,
pub extra: u64,
}
Loading
Loading