{
 "angle": "reentrancy and callback order with Midnight",
 "commit": "bbeda7b27ae80abcf070e0158cb8a31e87bb2286",
 "hasCandidates": false,
 "candidates": [],
 "summary": "No reentrancy or callback-order vulnerability survived. Every adapter entry point reachable from Midnight authenticates msg.sender == midnight, buyer callbacks require buyer == adapter outside forceDeallocate, onSell requires seller == adapter and empty data, and the funding-source callbackData is either supplied by an allocator (take) or committed in the ratified offer leaf (maker buys; HashLib hashes keccak256(offer.callbackData)). Untrusted code (counterparty callbacks) only runs (a) after the adapter's onBuy has fully settled vault accounting, or (b) before the adapter's onSell while Midnight's liquidation lock on (market, adapter) is set, and every adapter path that touches that market checks the lock. The forceDeallocate ratifier bypass (inForceDeallocate) and the gate admission are open only during a window that contains no untrusted call: Midnight's enter-gate check is a view (STATICCALL) and token transfers happen after onBuy clears both flags. Three negative probes against the real Midnight and VaultV2 at the pinned commit confirm this; they are not findings and are listed under covered. Nothing below is a High/Medium candidate.",
 "lowInfo": [
  {
   "title": "forceDeallocate ratifier bypass and the forced onBuy branch are not bound to the specific offer, market or buyer",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:114-117",
    "src/adapters/midnight/MidnightAdapter.sol:457-469",
    "src/adapters/midnight/MidnightAdapter.sol:488-493",
    "src/adapters/midnight/MidnightAdapter.sol:519-526",
    "lib/midnight/src/Midnight.sol:344-393",
    "lib/midnight/src/Midnight.sol:437-449"
   ],
   "detail": "isRatified returns CALLBACK_SUCCESS for ANY offer while the transient flag inForceDeallocate is set (line 493), and onBuy's forced branch (lines 520-526) neither checks the buyer, the market id nor that the take is the adapter's own reduce-only sell offer. Safety relies entirely on the absence of untrusted code between `inForceDeallocate = true` (line 465) and Midnight's call to onBuy: Midnight.take only runs touchMarket, the adapter's own isRatified, and IEnterGate.canIncreaseCredit/canIncreaseDebt in that window, and IEnterGate declares those `view`, so Solidity calls them with STATICCALL (IGate.sol). Token transfers (the hook surface) happen after onBuy (Midnight.sol:448-449). If any of those assumptions changed (a non-view gate interface, a hook in touchMarket, or a future Midnight calling the ratifier later), a reentrant Midnight.take of a forged adapter sell offer with receiverIfMakerIsSeller = attacker and callback = 0 would be ratified and would transfer the adapter's credit without onSell accounting. Probe testProbe_ForceDeallocateBypassDoesNotSurvive shows that the bypass does not persist after forceDeallocate in the same transaction: the flags are false and a forged sell take of the adapter's credit reverts, leaving 1.5e18 credit intact. Defence-in-depth suggestion: store the expected market id (or the offer hash) in transient storage instead of a bool, and in isRatified/onBuy require offer.maker == this, !offer.buy, offer.reduceOnly, offer.tick == 0, offer.callback == 0 and id == stored id."
  },
  {
   "title": "Counterparty buyer callback can nest a forceDeallocate of another market inside an adapter sale (safe, but undocumented)",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:427-477",
    "src/adapters/midnight/MidnightAdapter.sol:617-700",
    "lib/midnight/src/Midnight.sol:437-468"
   ],
   "detail": "When the adapter sells (maker sell offer taken by anyone, or allocator take of an external buy offer), the buyer's callback runs before the adapter's onSell with only the sold market liquidation-locked. From that callback, vault.forceDeallocate on a different market of the same adapter succeeds and runs a nested Midnight.take (adapter as seller) inside the outer take. forceDeallocate on the locked market reverts with SellInProgress; adapter.take reverts NotAuthorized; a forged onSell reverts NotMidnight. Probe testProbe_BuyerCallbackReentersDuringAdapterSale (real Midnight + real VaultV2): market A 2e18 -> sold 1e18 -> 1e18 stored = 1e18 on Midnight; market B 2e18 -> nested force-sale 0.5e18 -> 1.5e18 stored = 1.5e18 on Midnight; vault allocation(adapterId) = 2.5e18 = sum of stored credit. Accounting stays consistent because every path recomputes change as live-minus-stored and overwrites storage. A shortfall in the outer sale still loops over B, which is no longer locked, and reads B's freshly stored credit. Recommendation: document this nesting in the NatSpec next to 'A sale with a shortfall reverts while another market has a sale in progress'."
  },
  {
   "title": "Third parties cannot use the adapter as their buyer callback (payer), even though the adapter keeps a max allowance to Midnight",
   "class": "Informational",
   "verified": true,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:519-528",
    "src/adapters/midnight/MidnightAdapter.sol:613",
    "lib/midnight/src/Midnight.sol:410-449"
   ],
   "detail": "Midnight uses the buyer callback as the payer (Midnight.sol:412), and onBuy leaves a max allowance from the adapter to Midnight (line 613). An attacker who names the adapter as takerCallback (taker buy) or as offer.callback (maker buy) would make Midnight pull from the adapter's balance. onBuy rejects this with NotSelf because buyer != adapter, unless inForceDeallocate is set (see the first item). Probe testProbe_ThirdPartyCannotUseAdapterAsPayer: with 5e18 of stray loan tokens on the adapter and allowance = type(uint256).max, both variants revert NotSelf, and direct onBuy/onSell calls revert NotMidnight. The balance stays 5e18. No action needed. This records the check because the max allowance and the inForceDeallocate exception make NotSelf the only guard on the adapter's balance."
  },
  {
   "title": "TRST-R-13's statement that another MidnightAdapter cannot be the funding adapter no longer holds at this commit",
   "class": "Informational",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:478-482",
    "src/adapters/midnight/MidnightAdapter.sol:578-584",
    "src/adapters/midnight/MidnightAdapter.sol:718-738"
   ],
   "detail": "The TrustSec draft (TRST-R-13) lists among the reentrancy-safety assumptions that 'Another MidnightAdapter cannot be the funding adapter, since its deallocate() reverts with SelfAllocationOnly'. At the pinned commit, deallocate's non-force branch routes `sender != address(this)` to withdrawToVault (line 478-479). When adapter A's onBuy calls vault.deallocate(B, fundingData, buyerAssets), sender = A != B, so B withdraws matured or repaid credit to fund A's buy. By reasoning (not covered by a dedicated test), this remains safe: B.withdrawToVault checks B's own liquidation lock and forceRemoved flag, calls only Midnight.withdraw (no callback), and never calls back into A. The vault's firstTotalAssets is already cached by A's accrueInterest at line 575. Recommendation: update the documented reentrancy assumptions so they match the current routing."
  },
  {
   "title": "Anyone can open a buyer-callback window on a locked adapter market with a zero-unit take of a ratified adapter sell offer",
   "class": "Informational",
   "verified": false,
   "refs": [
    "src/adapters/midnight/MidnightAdapter.sol:617-700",
    "src/adapters/midnight/MidnightAdapter.sol:846-855",
    "lib/midnight/src/Midnight.sol:320-468"
   ],
   "detail": "Midnight permits zero-unit takes and still runs both callbacks (the Cantina draft 3.2.8 notes this for buy offers). Taking 0 units of any ratified adapter sell offer, even an exhausted one, gives the taker a buyer callback while (market, adapter) is liquidation-locked. In that window, realAssets reverts with OtherSellInProgress if the locked market has a non-zero lossFactor, so a first-in-transaction vault accrual, and therefore deposits, withdrawals, and adapter buys in other markets, revert. Sales with a shortfall in other markets also revert. The effect is limited to the caller's own transaction, because the lock is transient. The adapter's onSell for 0 units only re-syncs stored net credit and reports a 0 change. No impact found, and no dedicated PoC was written."
  }
 ],
 "covered": [
  {
   "item": "Build and baseline",
   "how": "Cloned morpho-org/vault-v2 at bbeda7b27ae80abcf070e0158cb8a31e87bb2286 with submodules (lib/midnight at 4e2570e51171d09228645b2d5bdf84ef24b1720b) and built with forge (solc 0.8.37/0.8.28/0.8.26/0.8.19). `FOUNDRY_FUZZ_RUNS=64 forge test --match-path 'test/*Midnight*'`: 6 suites, 398 passed, 0 failed (MidnightAdapterTest 314, MidnightAdapterRatifiersV1 38+36+1, integration 8, gas 1). The integration file test/integration/MidnightAdapterIntegrationTest.sol matched the glob through its directory and ran 8 tests."
  },
  {
   "item": "Caller authentication of callbacks",
   "how": "Code review plus a probe. onBuy and onSell require msg.sender == midnight (lines 519, 627). allocate and deallocate require msg.sender == parentVault (411, 425). allocate also requires sender == adapter (412). deallocate's raw-bytes branch is reachable only with sender == adapter, i.e. only from the adapter's own vault.deallocate calls, whose data it computes itself (onSell 693-698, self-funding 580-581, forceRemove 389). Probe 1 confirms that direct calls revert NotMidnight."
  },
  {
   "item": "Funding-source callbackData control",
   "how": "Taker buys: takerCallbackData comes from adapter.take, which is allocator-only (line 359). Maker buys: isRatified forces offer.callback == adapter (499) and delegates to an allowlisted sub-ratifier. Both MidnightAdapterPriceRatifierV1 and MidnightAdapterRateRatifierV1 verify a Merkle leaf built with HashLib.hashPriceRatifierV1Offer / hashRateRatifierV1Offer, which hash keccak256(offer.callbackData) (HashLib.sol lines 221, 250). Roots can only be ratified by vault allocators. The forced take passes empty takerCallbackData that the forced branch never decodes. onSell rejects non-empty data (629)."
  },
  {
   "item": "Ordering in take/onBuy (adapter buyer)",
   "how": "Traced Midnight.take (Midnight.sol:320-472): ratifier (view) -> gates (view) -> position writes -> liquidation lock on the seller -> buyer callback -> transfers -> seller callback. In the adapter's onBuy, stored state is written first (539-557). The in-progress transient override makes the vault's first accrueInterest exclude the unpaid purchase (561-576). Then come funding, duration caps, and vault.allocate. The counterparty's seller callback runs only after all of this, so untrusted code sees settled accounting. The mid-flight cap and realAssets overstatement during funding are already reported (Cantina 3.2.6, TRST-R-13)."
  },
  {
   "item": "Ordering in take/onSell (adapter seller)",
   "how": "The counterparty's buyer callback runs before onSell with the lock set on (market, adapter). take (361), isRatified (494), withdrawToVault (724), the forceDeallocate branch (433), realAssets for loss markets (852) and other markets' shortfall sales (656) all check the lock. Probe 2 exercises this with nested calls."
  },
  {
   "item": "forceDeallocate path and transient flags",
   "how": "Reviewed the order: transferFrom(sender) -> admit (trusted factory gate) -> set flags -> Midnight.take with the adapter as buyer callback -> onBuy clears inForceDeallocate and admitting and calls unadmit before the token transfers -> net credit re-sync. Checked that no untrusted call is in the window and that both flags are cleared on every non-reverting path (onBuy is always called because takerCallback == adapter, even for 0 units). Probe 3 checks the flags and a forged take in the same transaction. Gate admission is a transient per-gate slot (IKRCompatibleEnterGate.sol:20, 40-53)."
  },
  {
   "item": "Token hooks, vault reentry, skim, multicall",
   "how": "Loan-token reentrancy is an accepted assumption (MidnightAdapter.sol:85). The existing HookedToken test covers enter-gate admission. VaultV2.deallocate does not accrue, and allocate accrues once per transaction through firstTotalAssets (VaultV2.sol:539-586, 610-619), so mid-update realAssets reads only matter for the first accrual of a transaction, which the in-progress override and the lock checks cover. skim is restricted to the timelocked skimRecipient (trusted role). multicall delegatecalls to self with the original msg.sender, so it cannot impersonate Midnight or the vault."
  },
  {
   "item": "Prior audits",
   "how": "Extracted the text of audits/2026-10-12-midnight-adapter-cantina-draft.pdf and audits/2026-10-12-midnight-adapter-trustsec-draft.pdf. Reentrancy-related items already reported: Cantina 3.2.6 (mid-flight cap invariants), Cantina 3.2.8 (zero-unit buy callbacks), TRST-R-13 (buy-side reentrancy assumptions), TRST-L-1 (force-deallocate offer use by others, fixed at this commit by the taker authorization check at line 429). None of the items above duplicates them."
  },
  {
   "item": "Negative probes (not findings)",
   "path": "test/poc/ReentrancyProbes.t.sol",
   "command": "forge test --match-path test/poc/ReentrancyProbes.t.sol --match-test testProbe -vv",
   "output": "No files changed, compilation skipped\n\nRan 3 tests for test/poc/ReentrancyProbes.t.sol:ReentrancyProbes\n[PASS] testProbe_BuyerCallbackReentersDuringAdapterSale() (gas: 20667894)\nLogs:\n  stored A before: 2000000000000000000\n  stored B before: 2000000000000000000\n  stored A after: 1000000000000000000\n  stored B after: 1500000000000000000\n  midnight A after: 1000000000000000000\n  midnight B after: 1500000000000000000\n  vault allocation adapterId: 2500000000000000000\n\n[PASS] testProbe_ForceDeallocateBypassDoesNotSurvive() (gas: 15177589)\nLogs:\n  adapter credit after failed take: 1500000000000000000\n\n[PASS] testProbe_ThirdPartyCannotUseAdapterAsPayer() (gas: 2076690)\nLogs:\n  adapter allowance to Midnight: 115792089237316195423570985008687907853269984665640564039457584007913129639935\n  adapter balance after attempts: 5000000000000000000\n\nSuite result: ok. 3 passed; 0 failed; 0 skipped; finished in 23.15ms (21.56ms CPU time)\n\nRan 1 test suite in 28.95ms (23.15ms CPU time): 3 tests passed, 0 failed, 0 skipped (3 total tests)",
   "source": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../MidnightAdapterTest.sol\";\n\n/// @notice Negative reentrancy probes for MidnightAdapter (angle: reentrancy and callback order with Midnight).\n/// Each test attempts an attack and asserts that it fails and that accounting stays consistent.\ncontract ReentrancyProbes is MidnightAdapterTest {\n    using MathLib for uint256;\n\n    function _credit(Market memory market) internal view returns (uint256) {\n        Market memory dummy;\n        (uint128 c, uint128 p,) = midnight.updatePositionView(dummy, _marketId(market), address(adapter));\n        return c - p;\n    }\n\n    /// Probe 1: a third party sets the adapter as its buyer callback (taker or maker side) so that Midnight\n    /// would pull the loan token from the adapter (payer = buyerCallback). onBuy must reject it.\n    function testProbe_ThirdPartyCannotUseAdapterAsPayer() public {\n        Offer memory bought = buy(7 days, 1e18);\n        // Stray loan tokens sit on the adapter, which already approved Midnight for max.\n        deal(address(loanToken), address(adapter), 5e18);\n        uint256 allowance = loanToken.allowance(address(adapter), address(midnight));\n        emit log_named_uint(\"adapter allowance to Midnight\", allowance);\n\n        address attacker = makeAddr(\"attacker\");\n        // Taker side: attacker buys from an external seller, takerCallback = adapter.\n        Offer memory sellOffer = makeExternalOffer(bought.market, false, 2e18, MAX_TICK);\n        vm.prank(attacker);\n        vm.expectRevert(IMidnightAdapterBase.NotSelf.selector);\n        midnight.take(sellOffer, \"\", 1e18, attacker, address(0), address(adapter), \"\");\n\n        // Maker side: attacker posts a buy offer whose callback is the adapter.\n        Offer memory attackerBuy = storedOffer;\n        attackerBuy.market = bought.market;\n        attackerBuy.buy = true;\n        attackerBuy.maker = attacker;\n        attackerBuy.ratifier = address(this);\n        attackerBuy.callback = address(adapter);\n        attackerBuy.callbackData = abi.encode(address(0), bytes(\"\"));\n        attackerBuy.tick = MAX_TICK;\n        attackerBuy.maxUnits = 1e18;\n        attackerBuy.expiry = block.timestamp;\n        vm.prank(attacker);\n        midnight.setIsAuthorized(address(this), true, attacker);\n        vm.prank(taker);\n        vm.expectRevert(IMidnightAdapterBase.NotSelf.selector);\n        midnight.take(attackerBuy, \"\", 1e18, taker, taker, address(0), \"\");\n\n        // Direct calls to the callbacks.\n        vm.expectRevert(IMidnightAdapterBase.NotMidnight.selector);\n        adapter.onBuy(_marketId(bought.market), bought.market, 1e18, 1e18, 0, address(adapter), abi.encode(address(0), bytes(\"\")));\n        vm.expectRevert(IMidnightAdapterBase.NotMidnight.selector);\n        adapter.onSell(_marketId(bought.market), bought.market, 0, 1e18, 0, address(adapter), address(adapter), \"\");\n\n        emit log_named_uint(\"adapter balance after attempts\", loanToken.balanceOf(address(adapter)));\n        assertEq(loanToken.balanceOf(address(adapter)), 5e18, \"adapter balance untouched\");\n    }\n\n    /// Probe 2: during a sale by the adapter, the counterparty's buyer callback runs before the adapter's onSell.\n    /// It tries forceDeallocate on the market being sold (must fail), forceDeallocate on another market (allowed),\n    /// an allocator-only take and a direct onSell (must fail). Afterwards, stored net credit, Midnight credit and\n    /// vault allocations must agree.\n    function testProbe_BuyerCallbackReentersDuringAdapterSale() public {\n        setUpRealVault();\n        Offer memory offerA = buyOnRealVault(7 days, 2e18);\n        Offer memory offerB = buyOnRealVault(30 days, 2e18);\n        bytes32 idA = _marketId(offerA.market);\n        bytes32 idB = _marketId(offerB.market);\n\n        SaleCallback callback = newCallback();\n        deal(address(loanToken), address(this), 1e18);\n        realVault.deposit(1e18, address(callback));\n\n        callback.push(address(loanToken), abi.encodeCall(IERC20.approve, (address(adapter), type(uint256).max)), bytes4(0));\n        callback.push(\n            address(midnight), abi.encodeCall(IMidnight.setIsAuthorized, (address(adapter), true, address(callback))), bytes4(0)\n        );\n        // Same market as the sale in progress: blocked by the liquidation lock.\n        callback.push(\n            address(realVault),\n            abi.encodeCall(IVaultV2.forceDeallocate, (address(adapter), abi.encode(offerA.market, address(callback)), 0.5e18, address(callback))),\n            IMidnightAdapterBase.SellInProgress.selector\n        );\n        // Other market: allowed, nested Midnight.take inside the outer take.\n        callback.push(\n            address(realVault),\n            abi.encodeCall(IVaultV2.forceDeallocate, (address(adapter), abi.encode(offerB.market, address(callback)), 0.5e18, address(callback))),\n            bytes4(0)\n        );\n        // Allocator-only entry point.\n        callback.push(\n            address(adapter),\n            abi.encodeCall(IMidnightAdapterBase.take, (offerB, hex\"\", 0, hex\"\")),\n            IMidnightAdapterBase.NotAuthorized.selector\n        );\n        // Forged direct onSell.\n        callback.push(\n            address(adapter),\n            abi.encodeWithSignature(\n                \"onSell(bytes32,(uint256,address,address,(address,uint256,uint256,address)[],uint256,uint256,address,address),uint256,uint256,uint256,address,address,bytes)\",\n                idA, offerA.market, 0, 1e18, 0, address(adapter), address(adapter), bytes(\"\")\n            ),\n            IMidnightAdapterBase.NotMidnight.selector\n        );\n\n        uint256 storedA0 = adapter.marketData(idA).netCredit;\n        uint256 storedB0 = adapter.marketData(idB).netCredit;\n        emit log_named_uint(\"stored A before\", storedA0);\n        emit log_named_uint(\"stored B before\", storedB0);\n\n        callbackSale(makeSellOffer(offerA.market, 1e18, MAX_TICK), callback);\n\n        uint256 storedA = adapter.marketData(idA).netCredit;\n        uint256 storedB = adapter.marketData(idB).netCredit;\n        emit log_named_uint(\"stored A after\", storedA);\n        emit log_named_uint(\"stored B after\", storedB);\n        emit log_named_uint(\"midnight A after\", _credit(offerA.market));\n        emit log_named_uint(\"midnight B after\", _credit(offerB.market));\n        emit log_named_uint(\"vault allocation adapterId\", realVault.allocation(adapter.adapterId()));\n        assertEq(storedA, _credit(offerA.market), \"A synced\");\n        assertEq(storedB, _credit(offerB.market), \"B synced\");\n        assertEq(storedA, storedA0 - 1e18, \"A sold 1e18\");\n        assertEq(storedB, storedB0 - 0.5e18, \"B force-sold 0.5e18\");\n        assertEq(realVault.allocation(adapter.adapterId()), storedA + storedB, \"vault allocation matches stored credit\");\n        assertFalse(MidnightAdapter(address(adapter)).inForceDeallocate(), \"flag cleared\");\n        assertFalse(adapter.admitting(), \"admitting cleared\");\n    }\n\n    /// Probe 3: transient flags after forceDeallocate, in the same transaction. The ratifier bypass must not survive.\n    function testProbe_ForceDeallocateBypassDoesNotSurvive() public {\n        setUpRealVault();\n        Offer memory bought = buyOnRealVault(7 days, 2e18);\n        deal(address(loanToken), address(this), 10e18);\n        this.forceThenTake(bought.market);\n    }\n\n    function forceThenTake(Market memory market) external {\n        realVault.forceDeallocate(address(adapter), abi.encode(market, address(this)), 0.5e18, address(this));\n        assertFalse(MidnightAdapter(address(adapter)).inForceDeallocate(), \"inForceDeallocate cleared\");\n        assertFalse(adapter.admitting(), \"admitting cleared\");\n        assertEq(adapter.inProgressBuyMarketId(), bytes32(0), \"no buy in progress\");\n        // A cheap sale of the adapter's credit, with forged (empty) ratifier data, in the same transaction.\n        Offer memory offer = makeSellOffer(market, 1e18, 0);\n        offer.receiverIfMakerIsSeller = address(adapter);\n        address attacker = makeAddr(\"attacker\");\n        deal(address(loanToken), attacker, 1e18);\n        vm.startPrank(attacker);\n        SafeERC20Lib.safeApprove(address(loanToken), address(midnight), type(uint256).max);\n        vm.expectRevert();\n        midnight.take(offer, hex\"\", 1e18, attacker, address(0), address(0), \"\");\n        vm.stopPrank();\n        emit log_named_uint(\"adapter credit after failed take\", _credit(market));\n        assertEq(_credit(market), 1.5e18, \"credit unchanged by attacker\");\n    }\n}\n"
  }
 ],
 "notCovered": [
  "No fuzzing or invariant campaign over arbitrary nested callback sequences. Only the three directed probes plus the existing suite.",
  "Gates other than IKRCompatibleEnterGate, and subgates with custom logic, were not exercised against forceDeallocate admission. A non-view or reentrant subgate is excluded by the NatSpec and by IEnterGate being view.",
  "Nested-vault setups (this VaultV2 held by another vault, or two MidnightAdapters of the same vault trading with each other) were reviewed only by reading the code. The NatSpec states that the latter may revert.",
  "Rounding of the forced sale's settlement fee (adapter mulDivUp vs Midnight's buyerAssets - sellerAssets) was not analysed. It belongs to the accounting angle.",
  "No independent re-run from a clean clone by a second agent (Step 4) was done in this item."
 ]
}