Skip to content
Closed
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
24 changes: 24 additions & 0 deletions deployments/chain/zone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,30 @@ export async function zoneCallbackGatewayRegistered(
})
}

/** The Portal calls that remove every role `account` holds; none when it holds neither. */
export async function portalRoleRevokeCalls(
client: Pick<PublicClient, 'readContract'>,
portal: Address,
account: Address,
) {
const holds = (role: keyof typeof zonePortalRole) =>
client.readContract({
address: portal,
abi: zonePortalAbi,
functionName: 'hasRole',
args: [account, zonePortalRole[role]],
})
const [allowedAccount, gateway] = await Promise.all([holds('account'), holds('callbackGateway')])
const call = (functionName: 'setAllowedAccount' | 'setGateway') => ({
to: portal,
data: encodeFunctionData({ abi: zonePortalAbi, functionName, args: [account, false] }),
})
return [
...(allowedAccount ? [call('setAllowedAccount')] : []),
...(gateway ? [call('setGateway')] : []),
]
}

/**
* The Portal calls that give the router `role`. The Portal holds one role per account and grants
* one only from none, so a router admitted under the other gateway mode is moved in one batch:
Expand Down
48 changes: 38 additions & 10 deletions deployments/core/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ import { engineDefinitions, inspectEngineBindings } from '../modules/earn/engine
import {
capabilityModules,
deploymentStep,
deploymentSteps,
executeAvailableAuthority,
} from '../../deployments/modules/index.js'
import type {
DiscoveryOptions,
InspectionReport,
PrivilegedPrincipal,
import {
retiredOutputKey,
type DiscoveryOptions,
type InspectionReport,
type PrivilegedPrincipal,
} from '../../deployments/modules/module.js'
import {
assertFoundryVersion,
Expand Down Expand Up @@ -183,13 +185,9 @@ async function deployEarnProfileLocked(options: LifecycleOptions): Promise<EarnD
: new Set<IntentComponent>()
for (const component of replaced) reconciling.add(component)
// A paused replacement may itself predate this checkout's build, so cached contracts are checked too.
const cached = cachedPendingOutputs(options.profilePath, profile)
const staleCached = committed
? await replacedComponents(
client,
profile,
{ addresses: cachedPendingOutputs(options.profilePath, profile) },
compile,
)
? await replacedComponents(client, profile, { addresses: cached }, compile)
: new Set<IntentComponent>()
syncFoundryOutputs(options.root, options.profilePath)
let pending: PendingDeployment
Expand All @@ -213,6 +211,12 @@ async function deployEarnProfileLocked(options: LifecycleOptions): Promise<EarnD
replaced,
staleCached,
)
// Replaced contracts keep what activation granted them until the revoke steps remove it.
const retired = retiredContracts(committed.addresses, reconciling, cached, staleCached)
if (Object.keys(retired).length > 0) {
pending = { ...pending, outputs: { ...pending.outputs, ...retired } }
savePendingDeployment(options.profilePath, profile, pending)
}
Comment on lines +214 to +219

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟣 pre-existing, not blocking: A replaced router can keep its pool admission and Portal roles while deploy reports complete, once the gitignored pending file is lost or reset. The retired addresses live only in deployment.pending.json, but the record pointing at the successor is published before activation runs. Fix: keep the retired addresses in durable state, such as the published record or something derived from record history, so later runs and verify still see them; or hold back publishing the successor record until both revoke steps are satisfied.
A small fix can ride a push you are already making; otherwise a short reply is enough.

Why this was flagged

The retired entries are written only into pending outputs (deploy.ts:215-218). buildDeploymentRecord leaves them out of the record, and publishProfileDeploymentRecord (deploy.ts:302) commits the successor router before the activation loop (deploy.ts:343). Suppose a revoke step hands off and the operator resumes from another checkout or CI (pending is gitignored as **/deployment.pending.json). Or suppose the profile is edited and loadPendingDeployment throws on the intent-hash check, which restorePendingDeployment swallows at pending.ts:184-186 and then overwrites. Either way the committed record already has the new router, so replaced is empty and retiredContracts returns nothing. revokeRetired*Pool/Gateway then see retiredOutputs(...) as [] and report satisfied, and deploy returns complete while the old router stays a pool taker/recipient and Portal gateway. The verify path (reconcile.ts:476) checks record addresses only, so it also misses the leftover authority.

Verification: The base never revoked anything. Trigger: a run publishes the successor record and then stops at an activation handoff, and on the next run the pending file is missing or cannot be loaded. The retired addresses exist only in pending outputs (deploy.ts:215-218). poolRoutersRevoked and portalRoutersRevoked call .every on an empty list, which is true. The deploy ends complete.

Comment on lines +214 to +219

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (trigger unconfirmed) · unverified: Retired-router revocation obligation lives only in ephemeral pending state; losing it marks…

Mechanism: when a router is replaced, deployEarnProfile records the old address under retired.<output>.<address> only in deployment.pending.json (deploy.ts:214-219). That file is gitignored (.gitignore) and is never written to deployment.json. The same run publishes the deployment record naming the successor before the activation and revoke steps run (deploy.ts:281-302 vs 339-344).

Full finding

Retired-router revocation obligation lives only in ephemeral pending state; losing it marks the profile complete while the replaced router keeps pool and Portal roles

Mechanism: when a router is replaced, deployEarnProfile records the old address under retired.<output>.<address> only in deployment.pending.json (deploy.ts:214-219). That file is gitignored (.gitignore) and is never written to deployment.json. The same run publishes the deployment record naming the successor before the activation and revoke steps run (deploy.ts:281-302 vs 339-344). From the next run on, committed.addresses holds the successor, so reconciling is empty and retiredContracts (deploy.ts:787-805) cannot rebuild the retired entry. The pending file is the only copy of the obligation.

How the obligation is lost:
(a) In hosted CI (deploy.yml:104-114), the pending file survives only through actions/cache. That cache is best-effort: entries are evicted after about 7 days without access or under the repository size cap. Revoke steps are external-authority handoffs (Zone administrator, pool owner) that can easily outlast that.
(b) Any profile edit that changes deploymentIntentHash makes loadPendingDeployment throw (pending.ts:88-94). restorePendingDeployment then silently starts from empty outputs (pending.ts:181-186).
(c) A fresh checkout or another operator machine has no pending file at all.

In each case, retiredOutputs(outputs, 'earnRouter' | 'zoneRouter') returns []. poolRoutersRevoked and portalRoutersRevoked return true for the empty list (earn/zone-router/steps.ts:269-276, 341-350), so all four revoke steps are satisfied. The deploy reaches 'complete', calls removePendingDeployment, and reports success.

Impact: the replaced router still holds PropAMM taker/recipient admission and Portal callback-gateway and allowed-account roles. Two privileged routers stay live, which is the condition this PR exists to remove. The lifecycle also gives a false 'complete' signal, so nobody is prompted to revoke.

Preconditions: a router replacement whose revoke handoff does not land in the same run, followed by loss or discard of deployment.pending.json before the authority acts.

Missing evidence: GitHub cache retention for this repository and the real authority turnaround times. Whether the old router's leftover roles are exploitable depends on that contract's code; at minimum, it remains a privileged admitted taker/recipient and gateway.

Remediation: persist the retired set durably. Options: write retired addresses into the published deployment record, or a committed sidecar, until revocation is verified. Or derive retired routers from on-chain or record history, such as previous records' router addresses or role-grant events. Do not let an empty pending-derived list satisfy the revoke steps. At least, have restorePendingDeployment carry retired.* keys forward when it discards a mismatched pending file.

Valid? React with 👍 / 👎.

Comment on lines +214 to +219

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (trigger unconfirmed) · unverified: Publishing a replacement can strand revocations in disposable resume state

Once a replacement is published, unfinished revocations must remain discoverable on subsequent deploys. The command saves the predecessor only in pending outputs, publishes the successor before activation, and excludes the predecessor and cleanup obligations from the published record.

Full finding

Once a replacement is published, unfinished revocations must remain discoverable on subsequent deploys. The command saves the predecessor only in pending outputs, publishes the successor before activation, and excludes the predecessor and cleanup obligations from the published record. If revocation then requires a handoff and the pending file is absent on the next run, or a later periphery edit invalidates its intent hash, restore starts without the predecessor. The new record contains only the successor, so retirement detection cannot reconstruct the missing obligation. An empty retirement list satisfies cleanup, allowing complete while old grants remain. This can occur without an attacker; the workflow handles the pending cache and published record separately. No actual cache miss or affected live deployment was established. Persist unresolved retirements in durable, verified state before publishing the successor, carry them across allowed intent changes, and remove them only after checking the historical grants onchain.

Valid? React with 👍 / 👎.

} else {
pending = loadPendingDeployment(options.profilePath, profile)
}
Expand Down Expand Up @@ -776,6 +780,30 @@ export function publicFixtureAddresses() {
)
}

/**
* The pending-output entries for granted contracts this deployment redeploys, whether its intent or its
* code changed: the recorded ones, and stale cached replacements.
*/
function retiredContracts(
recorded: DeploymentAddresses,
reconciling: ReadonlySet<IntentComponent>,
cached: DeploymentAddresses,
staleCached: ReadonlySet<IntentComponent>,
) {
const retired: Record<string, Address> = {}
for (const step of deploymentSteps) {
if (step.execution !== 'foundry' || !step.source?.retireOnReplace) continue
const { output } = step.source
const previous = [
step.intent.some((component) => reconciling.has(component)) ? recorded[output] : undefined,
step.intent.some((component) => staleCached.has(component)) ? cached[output] : undefined,
]
for (const address of previous)
if (address) retired[retiredOutputKey(output, address)] = address
Comment on lines +797 to +802

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low (exposure and trigger unconfirmed) · unverified: Retirement checks the successor's grant targets instead of the predecessor's

Retirement must remove grants where they were issued. The new journal stores only the router address, while both router implementations use the successor's configured pool and discovered Portal for verification, writes, and handoffs. Same-chain target changes are expressly allowed during reconciliation.

Full finding

Retirement must remove grants where they were issued. The new journal stores only the router address, while both router implementations use the successor's configured pool and discovered Portal for verification, writes, and handoffs. Same-chain target changes are expressly allowed during reconciliation. For example, if router A was admitted on pool P and its successor uses pool Q, the check can find no permission for A on Q and report success while both flags remain on P. If the successor has no conversion pool, the step is disabled instead. A Zone move has the same problem for roles on the old Portal. Deployment can therefore report complete with the predecessor still authorized on its former infrastructure. This needs a supported profile migration and a previously granted router, not an attacker prerequisite; no affected live migration was established. Persist the original chain, pool, Portal, and Zone identity for each retirement before replacing the record, and verify and route revocations against those historical targets.

Valid? React with 👍 / 👎.

}
return retired
}

/** The contracts a resumable pending file holds, or none when there is no usable one. */
function cachedPendingOutputs(profilePath: string, profile: EarnDeploymentProfile) {
try {
Expand Down
11 changes: 9 additions & 2 deletions deployments/core/pending.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { address, object } from './parse.js'

import { deploymentActions, planEarnDeployment, type EarnDeploymentActionId } from './plan.js'
import { capabilityModules, deploymentStep } from '../../deployments/modules/index.js'
import { isRetiredOutputKey } from '../../deployments/modules/module.js'
import { pendingDeploymentPath } from './bundle.js'
import {
componentDeploymentIntentHashes,
Expand Down Expand Up @@ -112,7 +113,9 @@ export function loadPendingDeployment(
'outputs',
'output',
(key) =>
recordedAddress(key) || capabilityModules.some((module) => module.metadataOutput?.(key)),
recordedAddress(key) ||
isRetiredOutputKey(key) ||
capabilityModules.some((module) => module.metadataOutput?.(key)),
)
// Written by the Foundry step the deployment is executing; see `readActionOutputs`.
const latestOutputs = addresses('latestOutputs', 'latest output', recordedAddress)
Expand Down Expand Up @@ -352,10 +355,14 @@ export function parsePendingOutputs(value: unknown, path: string, metadata = fal
Object.entries(object(value, path)).map(([key, value]) => {
if (
!deploymentAddressKeys.includes(key as DeploymentAddressKey) &&
!(metadata && isRetiredOutputKey(key)) &&
!(metadata && capabilityModules.some((module) => module.metadataOutput?.(key)))
)
throw new Error(`${path} has unsupported output ${key}`)
return [key, address(value, `${path}.${key}`)]
const parsed = address(value, `${path}.${key}`)
if (isRetiredOutputKey(key) && !isRetiredOutputKey(key, parsed))
throw new Error(`${path}.${key} names a different address`)
return [key, parsed]
}),
)
}
18 changes: 18 additions & 0 deletions deployments/core/reconcile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
recordFoundryAction,
} from './reconcile.js'
import { deploymentStep } from '../modules/index.js'
import { retiredOutputKey } from '../modules/module.js'
import * as Inspection from './inspection.js'
import { pendingDeploymentPath } from './bundle.js'

Expand Down Expand Up @@ -287,6 +288,23 @@ describe('Earn deployment lifecycle', () => {
}
})

test('keeps retired contracts in pending state only under their own address', () => {
const root = mkdtempSync(join(tmpdir(), 'earn-retired-'))
try {
const path = join(root, 'profile.json')
const pending = loadPendingDeployment(path, profile)
const retired = address('9')
const key = retiredOutputKey('earnRouter', retired)
savePendingDeployment(path, profile, { ...pending, outputs: { [key]: retired } })
expect(loadPendingDeployment(path, profile).outputs).toEqual({ [key]: retired })
expect(() =>
savePendingDeployment(path, profile, { ...pending, outputs: { [key]: address('8') } }),
).toThrow('names a different address')
} finally {
rmSync(root, { recursive: true, force: true })
}
})

test('rejects unsupported output keys before persistence without poisoning valid state', () => {
const root = mkdtempSync(join(tmpdir(), 'earn-output-schema-'))
try {
Expand Down
120 changes: 119 additions & 1 deletion deployments/modules/authority.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
import { privateKeyToAccount } from 'viem/accounts'
import { describe, expect, test, vi } from 'vitest'

import { executeAvailableAuthority } from '../../deployments/modules/index.js'
import { deploymentStep, executeAvailableAuthority } from '../../deployments/modules/index.js'
import { retiredOutputKey } from './module.js'
import { authorizeRouter, canAuthorizeRouter } from './earn/zone-router/steps.js'
import { requireRouterProvenance } from './earn/zone-router/provenance.js'
import {
Expand Down Expand Up @@ -74,6 +75,123 @@ const authorityKey = `0x${'3'.repeat(64)}` as const
const authorityAccount = privateKeyToAccount(authorityKey).address
const receiptHash = `0x${'a'.repeat(64)}` as const

describe('replaced router revocation', () => {
const old = address('9')
const live = address('d')
const retired = { [retiredOutputKey('earnRouter', old)]: old }
const deployerKey = `0x${'2'.repeat(64)}` as const
const deployer = privateKeyToAccount(deployerKey).address

/** Chain reads where the live router holds every grant unless `liveGranted` is false. */
function chain(options: { liveGranted?: boolean; oldGateway?: boolean; oldPool?: boolean }) {
const runtime = mockDependencies([])
runtime.readContract.mockImplementation(async ({ functionName, args }) => {
const [account, role] = (args ?? []) as [string, number]
const granted = account === live ? options.liveGranted !== false : false
if (functionName === 'admin') return authorityAccount
if (functionName === 'owner') return deployer
if (functionName === 'isGatewayOpen' || functionName === 'isAccessEnforced') return false
if (functionName === 'hasRole')
return account === old ? role === 3 && options.oldGateway !== false : granted && role === 3
if (functionName === 'takerAllowed' || functionName === 'recipientAllowed')
return account === old ? options.oldPool !== false : granted
if (functionName === 'resolveRecipient') return account
throw new Error(`Unexpected read ${functionName}`)
})
return runtime
}
const stepOutputs = { ...outputs, earnRouter: live, ...retired }

test('removes every Portal role a replaced router holds, and nothing when it holds none', async () => {
const runtime = chain({ oldPool: false })
const result = await execute(
profile,
'revoke-retired-router-gateway',
{ ZONE_ADMIN_PRIVATE_KEY: authorityKey },
stepOutputs,
runtime.dependencies,
)
expect(result).toEqual({ transactions: [receiptHash] })
const [call] = runtime.sendTransactionSync.mock.calls[0]![0].calls as Array<{
to: string
data: `0x${string}`
}>
expect(call!.to).toBe(outputs.zonePortal)
expect(decodeFunctionData({ abi: zonePortalAbi, data: call!.data })).toMatchObject({
functionName: 'setGateway',
args: [old, false],
})

const none = chain({ oldGateway: false })
await expect(
execute(
profile,
'revoke-retired-router-gateway',
{ ZONE_ADMIN_PRIVATE_KEY: authorityKey },
stepOutputs,
none.dependencies,
),
).resolves.toEqual({ transactions: [] })
expect(none.sendTransactionSync).not.toHaveBeenCalled()
})

test('removes pool admission from a replaced router as the pool owner', async () => {
const runtime = chain({})
const result = await execute(
profile,
'revoke-retired-router-pool',
{ DEPLOYER_PRIVATE_KEY: deployerKey },
stepOutputs,
runtime.dependencies,
)
expect(result).toEqual({ transactions: [receiptHash] })
const calls = runtime.sendTransactionSync.mock.calls[0]![0].calls as Array<{
to: string
data: `0x${string}`
}>
expect(calls.map((call) => call.to)).toEqual([address('7'), address('7')])
expect(
calls.map((call) => decodeFunctionData({ abi: propAMMPoolAbi, data: call.data })),
).toMatchObject([
{ functionName: 'setTakerAllowed', args: [old, false] },
{ functionName: 'setRecipientAllowed', args: [old, false] },
])
})

test.each(['revoke-retired-router-pool', 'revoke-retired-router-gateway'])(
'%s hands off rather than revoke while the successor lacks a grant',
async (id) => {
const runtime = chain({ liveGranted: false })
await expect(
execute(
profile,
id,
{ DEPLOYER_PRIVATE_KEY: deployerKey, ZONE_ADMIN_PRIVATE_KEY: authorityKey },
stepOutputs,
runtime.dependencies,
),
).resolves.toBeUndefined()
expect(runtime.sendTransactionSync).not.toHaveBeenCalled()
},
)

test('is satisfied with nothing retired and names each router still privileged', async () => {
const step = deploymentStep('revoke-retired-router-gateway')
const client = {
readContract: vi.fn(async ({ args }: { args: unknown[] }) => args[0] === old),
} as never
await expect(step.satisfied(client, profile, { ...outputs, earnRouter: live })).resolves.toBe(
true,
)
await expect(step.satisfied(client, profile, stepOutputs)).resolves.toBe(false)
// The live router is never treated as retired, even if a stale entry names it.
const self = { ...outputs, earnRouter: old, ...retired }
await expect(step.satisfied(client, profile, self)).resolves.toBe(true)
if (step.execution !== 'authority') throw new Error('Expected an authority step')
expect(step.handoff(profile, stepOutputs)).toContain(old)
})
})

function mockDependencies(values: unknown[]) {
const readContract = vi.fn()
for (const value of values) readContract.mockResolvedValueOnce(value)
Expand Down
4 changes: 2 additions & 2 deletions deployments/modules/earn/zone-router/steps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,10 @@ describe('Zone admission guards', () => {
expect(runtime.sendTransactionSync).not.toHaveBeenCalled()
})

test('keeps all five Zone administration steps as handoffs until authority is proven', () => {
test('keeps all seven Zone administration steps as handoffs until authority is proven', () => {
const plan = presentEarnDeploymentPlan(profile, options.environment)
const admin = plan.filter((step) => step.authority === 'zone-administrator')
expect(admin).toHaveLength(5)
expect(admin).toHaveLength(7)
expect(admin.every((step) => step.execution === 'handoff')).toBe(true)
expect(enableZoneTokens.probeSigner).toBeTypeOf('function')
expect(registerZoneGateway.probeSigner).toBeTypeOf('function')
Expand Down
Loading