// SPDX-License-Identifier: BUSL-1.1 // Copyright (c) 2026 Liquidbox Corp. // Licensed under the Business Source License 1.1. See LICENSE.md. // Terms of use: https://www.inco.org/terms-of-services // Security contact team@inco.network pragma solidity ^0.8; import {IncoTest} from "./IncoTest.sol"; import {e, inco} from "../Lib.sol"; import {euint256, ALLOWANCE_GRANTED_MAGIC_VALUE} from "../Types.sol"; import {CTokenSessionVerifier, CTokenSession, CTokenSessionRequest} from "../periphery/CTokenSessionVerifier.sol"; import {SessionVerifier, Session} from "../periphery/SessionVerifier.sol"; import {AllowanceVoucher, AllowanceProof} from "../lightning-parts/AccessControl/AdvancedAccessControl.sol"; import {REQUIRED_ALLOWANCE_VOUCHER_WARNING} from "../lightning-parts/AccessControl/AdvancedAccessControl.types.sol"; import {IIncoVerifier} from "../interfaces/IIncoVerifier.sol"; import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol"; /// @notice Stand-in for `WrapperFactory`, exposing only the `getWrapper` lookup the verifier uses. /// @dev Mirrors `IWrapperFactory.getWrapper`'s signature so a drift there fails these tests. contract MockWrapperFactory { mapping(IERC20 erc20 => address cToken) private _wrappers; function setWrapper(address erc20, address cToken) external { _wrappers[IERC20(erc20)] = cToken; } function getWrapper(IERC20 erc20) external view returns (address) { return _wrappers[erc20]; } } /// @notice Stand-in for a cERC20: takes `allowThis` on the handles it produces, exactly as /// `CTokenWrapper._update` does, which is what puts those handles in a session's scope. contract MockCToken { using e for bytes; using e for euint256; euint256 public balanceOfHolder; function setBalance(bytes memory ciphertext, address holder) external { balanceOfHolder = ciphertext.newEuint256(holder); balanceOfHolder.allowThis(); balanceOfHolder.allow(holder); } function handle() external view returns (bytes32) { return euint256.unwrap(balanceOfHolder); } } /// @notice Stand-in ACL whose verdict is fixed, used to prove the verifier asks the IncoLightning it /// was constructed with rather than the `inco` singleton from Lib.sol. contract MockAcl { bool private immutable _verdict; constructor(bool verdict) { _verdict = verdict; } function isAllowed(bytes32, address) external view returns (bool) { return _verdict; } } /// @notice Data alice holds that has nothing to do with confidential tokens — the blast radius a /// plain {SessionVerifier} session covers and a {CTokenSessionVerifier} session must not. contract UnrelatedSecretHolder { using e for bytes; using e for euint256; euint256 public secret; function save(bytes memory ciphertext, address holder) external { secret = ciphertext.newEuint256(holder); secret.allowThis(); secret.allow(holder); } function handle() external view returns (bytes32) { return euint256.unwrap(secret); } } contract TestCTokenSessionVerifier is IncoTest { CTokenSessionVerifier private verifier; MockWrapperFactory private factory; // usdc/dai stand in for the underlying ERC-20s; cUsdc/cDai for the wrappers the factory resolves to. address private usdc; address private dai; MockCToken private cUsdc; MockCToken private cDai; // Alice's cUSDC balance handle: allowed on cUsdc (and alice), so an in-scope session unlocks it. bytes32 private cUsdcHandle; // Alice's cDAI balance handle: allowed on cDai only. bytes32 private cDaiHandle; // Alice's non-token secret: allowed on no cERC20 at all. bytes32 private unrelatedHandle; function setUp() public override { super.setUp(); usdc = getLabeledAddress("usdc"); dai = getLabeledAddress("dai"); cUsdc = new MockCToken(); cDai = new MockCToken(); UnrelatedSecretHolder unrelated = new UnrelatedSecretHolder(); vm.deal(address(cUsdc), 100 ether); vm.deal(address(cDai), 100 ether); vm.deal(address(unrelated), 100 ether); cUsdc.setBalance(fakePrepareEuint256Ciphertext(1_000, alice, address(cUsdc)), alice); cDai.setBalance(fakePrepareEuint256Ciphertext(2_000, alice, address(cDai)), alice); unrelated.save(fakePrepareEuint256Ciphertext(42, alice, address(unrelated)), alice); cUsdcHandle = cUsdc.handle(); cDaiHandle = cDai.handle(); unrelatedHandle = unrelated.handle(); factory = new MockWrapperFactory(); factory.setWrapper(usdc, address(cUsdc)); factory.setWrapper(dai, address(cDai)); verifier = _deployVerifierProxy(alice, address(factory)); } // ============ Scope: sharer-signed token list ============ function test_SignedToken_InScopeHandle_ReturnsAllowanceGranted() public view { bytes32 result = verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens(usdc)), ""); assertEq(result, ALLOWANCE_GRANTED_MAGIC_VALUE, "cUSDC handle should be in scope of a USDC session"); } function test_SignedToken_OtherCTokensHandle_ReturnsZero() public view { // The whole point of this verifier: a USDC session does not reach alice's cDAI balance. bytes32 result = verifier.canUseSession(cDaiHandle, bob, _session(bob, _tokens(usdc)), ""); assertEq(result, bytes32(0), "a USDC-scoped session must not cover a cDAI handle"); } function test_SignedToken_NonTokenHandle_ReturnsZero() public view { bytes32 result = verifier.canUseSession(unrelatedHandle, bob, _session(bob, _tokens(usdc)), ""); assertEq(result, bytes32(0), "a cToken session must not cover non-token data"); } function test_SignedToken_UnregisteredToken_ReturnsZero() public { // weth resolves to address(0) through the factory, so it can never match a handle. address weth = getLabeledAddress("weth"); bytes32 result = verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens(weth)), ""); assertEq(result, bytes32(0), "a token with no registered wrapper should never grant"); } function test_SignedTokens_MatchesAnyEntryInTheList() public view { address[] memory tokens = new address[](2); tokens[0] = usdc; tokens[1] = dai; assertEq( verifier.canUseSession(cDaiHandle, bob, _session(bob, tokens), ""), ALLOWANCE_GRANTED_MAGIC_VALUE, "a multi-token session should match on any listed token" ); } // ============ Scope: blanket session + requester-named tokens ============ function test_BlanketSession_RequesterNamesToken_ReturnsAllowanceGranted() public view { bytes32 result = verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens()), _request(_tokens(usdc))); assertEq(result, ALLOWANCE_GRANTED_MAGIC_VALUE, "blanket session should honour the requester's token"); } function test_BlanketSession_RequesterNamesUnregisteredToken_ReturnsZero() public view { // Blanket consent still means "any *WrapperFactory* cERC20" — the requester cannot name an // arbitrary address that happens to be allowed on the handle. bytes32 result = verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens()), _request(_tokens(address(cUsdc)))); assertEq(result, bytes32(0), "requester-named address must still resolve through the factory"); } function test_BlanketSession_NoRequesterData_ReturnsZero() public view { bytes32 result = verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens()), ""); assertEq(result, bytes32(0), "no token named on either side means nothing is in scope"); } function test_BlanketSession_EmptyRequesterList_ReturnsZero() public view { bytes32 result = verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens()), _request(_tokens())); assertEq(result, bytes32(0), "an empty requester list leaves nothing to resolve"); } // ============ Scope: the requester can never widen a signed scope ============ function test_SignedToken_RequesterCannotWidenScope() public view { // Alice signed for USDC only. Bob asks for DAI as well and points at her cDAI handle. bytes memory request = _request(_tokens(usdc, dai)); assertEq( verifier.canUseSession(cDaiHandle, bob, _session(bob, _tokens(usdc)), request), bytes32(0), "requesterArgData must be ignored when the sharer pinned a scope" ); assertEq( verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens(usdc)), request), ALLOWANCE_GRANTED_MAGIC_VALUE, "the signed token itself still grants" ); } function test_SignedToken_MalformedRequesterDataIsIgnored() public view { bytes32 result = verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens(usdc)), hex"deadbeef"); assertEq(result, ALLOWANCE_GRANTED_MAGIC_VALUE, "requesterArgData is never decoded for a pinned scope"); } // ============ Session validity ============ function test_ExpiredSession_ReturnsZero() public { bytes memory sharerArgData = _session(bob, _tokens(usdc)); vm.warp(block.timestamp + 1 days + 1); assertEq(verifier.canUseSession(cUsdcHandle, bob, sharerArgData, ""), bytes32(0), "expired session must deny"); } function test_SessionExpiringThisBlock_StillGrants() public view { bytes memory sharerArgData = abi.encode(CTokenSession({decrypter: bob, expiresAt: block.timestamp, erc20Tokens: _tokens(usdc)})); assertEq( verifier.canUseSession(cUsdcHandle, bob, sharerArgData, ""), ALLOWANCE_GRANTED_MAGIC_VALUE, "expiresAt == now is still live, matching SessionVerifier" ); } function test_WrongDecrypter_ReturnsZero() public view { bytes32 result = verifier.canUseSession(cUsdcHandle, carol, _session(bob, _tokens(usdc)), ""); assertEq(result, bytes32(0), "only the named decrypter may use the session"); } // ============ Wrapper factory administration ============ function test_Initialize_SetsOwnerAndFactory() public view { assertEq(verifier.owner(), alice, "owner should be the initializer's owner argument"); assertEq(verifier.wrapperFactory(), address(factory), "factory should be pinned at initialize"); } function test_Initialize_EmitsWrapperFactoryUpdated() public { CTokenSessionVerifier impl = new CTokenSessionVerifier(bytes32(0), address(inco)); vm.expectEmit(true, true, false, false); emit CTokenSessionVerifier.WrapperFactoryUpdated(address(0), address(factory)); new ERC1967Proxy(address(impl), abi.encodeCall(CTokenSessionVerifier.initialize, (alice, address(factory)))); } function test_Initialize_ZeroFactory_Reverts() public { CTokenSessionVerifier impl = new CTokenSessionVerifier(bytes32(0), address(inco)); vm.expectRevert(CTokenSessionVerifier.InvalidWrapperFactory.selector); new ERC1967Proxy(address(impl), abi.encodeCall(CTokenSessionVerifier.initialize, (alice, address(0)))); } function test_Initialize_CannotBeCalledTwice() public { vm.expectRevert(); verifier.initialize(bob, address(factory)); } function test_SetWrapperFactory_ByOwner_UpdatesAndEmits() public { MockWrapperFactory newFactory = new MockWrapperFactory(); vm.expectEmit(true, true, false, false); emit CTokenSessionVerifier.WrapperFactoryUpdated(address(factory), address(newFactory)); vm.prank(alice); verifier.setWrapperFactory(address(newFactory)); assertEq(verifier.wrapperFactory(), address(newFactory), "factory should be repointed"); } function test_SetWrapperFactory_ByNonOwner_Reverts() public { MockWrapperFactory newFactory = new MockWrapperFactory(); vm.prank(bob); vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, bob)); verifier.setWrapperFactory(address(newFactory)); } function test_SetWrapperFactory_Zero_Reverts() public { vm.prank(alice); vm.expectRevert(CTokenSessionVerifier.InvalidWrapperFactory.selector); verifier.setWrapperFactory(address(0)); } function test_SetWrapperFactory_RepointsTheTokenUniverse() public { // A factory that resolves USDC somewhere else drops the previously in-scope handle. MockWrapperFactory newFactory = new MockWrapperFactory(); newFactory.setWrapper(usdc, address(cDai)); vm.prank(alice); verifier.setWrapperFactory(address(newFactory)); bytes memory sharerArgData = _session(bob, _tokens(usdc)); assertEq( verifier.canUseSession(cUsdcHandle, bob, sharerArgData, ""), bytes32(0), "the old cUSDC handle should fall out of scope under the new factory" ); assertEq( verifier.canUseSession(cDaiHandle, bob, sharerArgData, ""), ALLOWANCE_GRANTED_MAGIC_VALUE, "the new factory's USDC wrapper defines the scope now" ); } // ============ Upgradeability ============ function test_Upgrade_ByOwner_PreservesFactory() public { CTokenSessionVerifier newImpl = new CTokenSessionVerifier(bytes32(0), address(inco)); vm.prank(alice); verifier.upgradeToAndCall(address(newImpl), ""); assertEq(verifier.wrapperFactory(), address(factory), "namespaced storage should survive the upgrade"); assertEq( verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens(usdc)), ""), ALLOWANCE_GRANTED_MAGIC_VALUE, "sessions should keep working after an upgrade" ); } function test_Upgrade_ByNonOwner_Reverts() public { CTokenSessionVerifier newImpl = new CTokenSessionVerifier(bytes32(0), address(inco)); vm.prank(bob); vm.expectRevert(); verifier.upgradeToAndCall(address(newImpl), ""); } // ============ IncoLightning address is constructor-injected, not the Lib.sol singleton ============ function test_ConstructorLightningAddress_IsTheAclConsulted() public { // Same handle, same scope, two verifiers differing only in the ACL they were built against. CTokenSessionVerifier denying = _deployVerifierProxyFor(address(new MockAcl(false))); CTokenSessionVerifier granting = _deployVerifierProxyFor(address(new MockAcl(true))); bytes memory sharerArgData = _session(bob, _tokens(usdc)); assertEq( denying.canUseSession(cUsdcHandle, bob, sharerArgData, ""), bytes32(0), "a verifier built against a denying ACL must not fall back to the inco singleton" ); assertEq( granting.canUseSession(bytes32(uint256(0xdead)), bob, sharerArgData, ""), ALLOWANCE_GRANTED_MAGIC_VALUE, "the injected ACL is the one asked, even for a handle inco has never seen" ); } function test_LightningAddress_IsImmutableAcrossUpgrade() public { // The address lives in the impl's bytecode, so upgrading to an impl built against another ACL // moves it — worth stating, since it is the one piece of config a proxy upgrade can change. CTokenSessionVerifier newImpl = new CTokenSessionVerifier(bytes32(0), address(new MockAcl(false))); vm.prank(alice); verifier.upgradeToAndCall(address(newImpl), ""); assertEq( verifier.canUseSession(cUsdcHandle, bob, _session(bob, _tokens(usdc)), ""), bytes32(0), "the new implementation's IncoLightning address takes effect" ); } // ============ Selector compatibility with SessionVerifier ============ function test_SelectorMatchesSessionVerifier() public pure { assertEq( CTokenSessionVerifier.canUseSession.selector, SessionVerifier.canUseSession.selector, "selector must be unchanged so existing SDK voucher paths drive it" ); } // ============ End to end through the ACL ============ function test_EndToEnd_ScopedVoucherClaimsOnlyTheTokenHandle() public { IIncoVerifier incoVerifier = inco.incoVerifier(); AllowanceVoucher memory voucher = AllowanceVoucher({ sessionNonce: bytes32(0), verifyingContract: address(verifier), callFunction: CTokenSessionVerifier.canUseSession.selector, sharerArgData: _session(bob, _tokens(usdc)), warning: REQUIRED_ALLOWANCE_VOUCHER_WARNING }); AllowanceProof memory proof = AllowanceProof({ sharer: alice, voucher: voucher, voucherSignature: getSignatureForDigest(incoVerifier.allowanceVoucherDigest(voucher), alicePrivKey), requesterArgData: "" }); assertTrue(incoVerifier.isAllowedWithProof(cUsdcHandle, bob, proof), "bob should reach alice's cUSDC balance"); assertFalse(incoVerifier.isAllowedWithProof(cDaiHandle, bob, proof), "bob should not reach her cDAI balance"); assertFalse(incoVerifier.isAllowedWithProof(unrelatedHandle, bob, proof), "nor her unrelated secret"); vm.prank(bob); inco.claimHandle(cUsdcHandle, proof); assertTrue(inco.persistAllowed(cUsdcHandle, bob), "bob should hold a persistent allowance on the cUSDC handle"); } function test_EndToEnd_BlanketVoucherIsStillBoundedToCTokens() public { IIncoVerifier incoVerifier = inco.incoVerifier(); AllowanceVoucher memory voucher = AllowanceVoucher({ sessionNonce: bytes32(0), verifyingContract: address(verifier), callFunction: CTokenSessionVerifier.canUseSession.selector, sharerArgData: _session(bob, _tokens()), warning: REQUIRED_ALLOWANCE_VOUCHER_WARNING }); bytes memory signature = getSignatureForDigest(incoVerifier.allowanceVoucherDigest(voucher), alicePrivKey); // Bob names both tokens and reaches both balances — a blanket session is wide across cERC20s. AllowanceProof memory proof = AllowanceProof({ sharer: alice, voucher: voucher, voucherSignature: signature, requesterArgData: _request(_tokens(usdc, dai)) }); assertTrue(incoVerifier.isAllowedWithProof(cUsdcHandle, bob, proof), "blanket session covers cUSDC"); assertTrue(incoVerifier.isAllowedWithProof(cDaiHandle, bob, proof), "blanket session covers cDAI"); // ...but never past them, whatever he names. assertFalse( incoVerifier.isAllowedWithProof(unrelatedHandle, bob, proof), "a blanket cToken session still must not reach non-token data" ); // A plain SessionVerifier session over the same voucher shape would have reached it — that // difference is the reason this verifier exists. SessionVerifier plain = new SessionVerifier(""); AllowanceVoucher memory plainVoucher = AllowanceVoucher({ sessionNonce: bytes32(0), verifyingContract: address(plain), callFunction: SessionVerifier.canUseSession.selector, sharerArgData: abi.encode(Session({decrypter: bob, expiresAt: block.timestamp + 1 days})), warning: REQUIRED_ALLOWANCE_VOUCHER_WARNING }); AllowanceProof memory plainProof = AllowanceProof({ sharer: alice, voucher: plainVoucher, voucherSignature: getSignatureForDigest(incoVerifier.allowanceVoucherDigest(plainVoucher), alicePrivKey), requesterArgData: "" }); assertTrue( incoVerifier.isAllowedWithProof(unrelatedHandle, bob, plainProof), "SessionVerifier grants the sharer's whole surface - the scope this contract narrows" ); } // ============ Helpers ============ function _deployVerifierProxy(address proxyOwner, address wrapperFactory) private returns (CTokenSessionVerifier) { return _deployVerifierProxy(proxyOwner, wrapperFactory, address(inco)); } /// @dev Same wiring as {_deployVerifierProxy}, against `factory` and the real inco ACL. function _deployVerifierProxyFor(address incoLightningAddress) private returns (CTokenSessionVerifier) { return _deployVerifierProxy(alice, address(factory), incoLightningAddress); } function _deployVerifierProxy(address proxyOwner, address wrapperFactory, address incoLightningAddress) private returns (CTokenSessionVerifier) { CTokenSessionVerifier impl = new CTokenSessionVerifier(bytes32(0), incoLightningAddress); ERC1967Proxy proxy = new ERC1967Proxy( address(impl), abi.encodeCall(CTokenSessionVerifier.initialize, (proxyOwner, wrapperFactory)) ); return CTokenSessionVerifier(payable(address(proxy))); } function _session(address decrypter, address[] memory erc20Tokens) private view returns (bytes memory) { return abi.encode( CTokenSession({decrypter: decrypter, expiresAt: block.timestamp + 1 days, erc20Tokens: erc20Tokens}) ); } function _request(address[] memory erc20Tokens) private pure returns (bytes memory) { return abi.encode(CTokenSessionRequest({erc20Tokens: erc20Tokens})); } function _tokens() private pure returns (address[] memory tokens) { tokens = new address[](0); } function _tokens(address a) private pure returns (address[] memory tokens) { tokens = new address[](1); tokens[0] = a; } function _tokens(address a, address b) private pure returns (address[] memory tokens) { tokens = new address[](2); tokens[0] = a; tokens[1] = b; } }