Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/key-rotation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@resciencelab/dap": minor
---

Add POST /peer/key-rotation endpoint: both old and new Ed25519 keys sign the rotation record, TOFU cache is updated atomically
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions src/peer-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,28 @@ export function getEndpointAddress(peer: DiscoveredPeerRecord, transport: string
.sort((a, b) => a.priority - b.priority)[0]
return ep?.address ?? null
}

/**
* Replace the public key for an existing peer (key rotation).
* If the peer is not yet in the store, creates a minimal gossip record.
*/
export function tofuReplaceKey(agentId: string, newPublicKey: string): void {
const now = Date.now()
const existing = store.peers[agentId]
if (existing) {
existing.publicKey = newPublicKey
existing.lastSeen = now
} else {
store.peers[agentId] = {
agentId,
publicKey: newPublicKey,
alias: "",
endpoints: [],
capabilities: [],
firstSeen: now,
lastSeen: now,
source: "gossip",
}
}
saveImmediate()
}
44 changes: 43 additions & 1 deletion src/peer-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import Fastify, { FastifyInstance } from "fastify"
import { P2PMessage, Endpoint } from "./types"
import { verifySignature, agentIdFromPublicKey } from "./identity"
import { tofuVerifyAndCache, getPeersForExchange, upsertDiscoveredPeer, removePeer } from "./peer-db"
import { tofuVerifyAndCache, tofuReplaceKey, getPeersForExchange, upsertDiscoveredPeer, removePeer } from "./peer-db"

const MAX_MESSAGE_AGE_MS = 5 * 60 * 1000 // 5 minutes

Expand Down Expand Up @@ -172,6 +172,48 @@ export async function startPeerServer(
return { ok: true }
})

server.post("/peer/key-rotation", async (req, reply) => {
const rot = req.body as any

if (!rot.agentId || !rot.oldPublicKey || !rot.newPublicKey || !rot.signatureByOldKey || !rot.signatureByNewKey) {
return reply.code(400).send({ error: "Missing required key rotation fields" })
}

// Verify agentId matches oldPublicKey
if (agentIdFromPublicKey(rot.oldPublicKey) !== rot.agentId) {
return reply.code(400).send({ error: "agentId does not match oldPublicKey" })
}

// Replay protection: reject if timestamp is too old or in future
if (rot.timestamp && Math.abs(Date.now() - rot.timestamp) > MAX_MESSAGE_AGE_MS) {
return reply.code(400).send({ error: "Key rotation timestamp too old or too far in the future" })
}

// The payload both keys sign
const signable = {
agentId: rot.agentId,
oldPublicKey: rot.oldPublicKey,
newPublicKey: rot.newPublicKey,
timestamp: rot.timestamp,
}

// Verify old key signature
if (!verifySignature(rot.oldPublicKey, signable, rot.signatureByOldKey)) {
return reply.code(403).send({ error: "Invalid signatureByOldKey" })
}

// Verify new key signature
if (!verifySignature(rot.newPublicKey, signable, rot.signatureByNewKey)) {
return reply.code(403).send({ error: "Invalid signatureByNewKey" })
}

// Update TOFU cache to new key
tofuReplaceKey(rot.agentId, rot.newPublicKey)
console.log(`[p2p] key-rotation agentId=${rot.agentId} newKey=${rot.newPublicKey.slice(0, 16)}...`)

return { ok: true }
})

await server.listen({ port, host: "::" })
console.log(`[p2p] Peer server listening on [::]:${port}${testMode ? " (test mode)" : ""}`)
}
Expand Down
121 changes: 121 additions & 0 deletions test/key-rotation.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { test, describe, before, after } from "node:test"
import assert from "node:assert/strict"
import { sha256 } from "@noble/hashes/sha256"
import * as os from "node:os"
import * as fs from "node:fs"
import * as path from "node:path"

const nacl = (await import("tweetnacl")).default

// Import from dist
const { startPeerServer, stopPeerServer } = await import("../dist/peer-server.js")
const { initDb } = await import("../dist/peer-db.js")
const { signMessage, agentIdFromPublicKey } = await import("../dist/identity.js")

function makeKeypair() {
const kp = nacl.sign.keyPair()
const pubB64 = Buffer.from(kp.publicKey).toString("base64")
const privB64 = Buffer.from(kp.secretKey.slice(0, 32)).toString("base64")
const agentId = Buffer.from(sha256(kp.publicKey)).toString("hex").slice(0, 32)
return { publicKey: pubB64, privateKey: privB64, agentId }
}

function signRotation(privB64, payload) {
return signMessage(privB64, payload)
}

describe("key rotation endpoint", () => {
let port
let tmpDir

before(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "dap-kr-test-"))
initDb(tmpDir)
port = 18099
await startPeerServer(port, { testMode: true })
})

after(async () => {
await stopPeerServer()
fs.rmSync(tmpDir, { recursive: true })
})

test("accepts valid key rotation", async () => {
const oldKey = makeKeypair()
const newKey = makeKeypair()

const payload = {
agentId: oldKey.agentId,
oldPublicKey: oldKey.publicKey,
newPublicKey: newKey.publicKey,
timestamp: Date.now(),
}

const body = {
...payload,
signatureByOldKey: signRotation(oldKey.privateKey, payload),
signatureByNewKey: signRotation(newKey.privateKey, payload),
}

const resp = await fetch(`http://[::1]:${port}/peer/key-rotation`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
assert.equal(resp.status, 200)
const json = await resp.json()
assert.equal(json.ok, true)
})

test("rejects invalid old key signature", async () => {
const oldKey = makeKeypair()
const newKey = makeKeypair()
const wrongKey = makeKeypair()

const payload = {
agentId: oldKey.agentId,
oldPublicKey: oldKey.publicKey,
newPublicKey: newKey.publicKey,
timestamp: Date.now(),
}

const body = {
...payload,
signatureByOldKey: signRotation(wrongKey.privateKey, payload), // wrong!
signatureByNewKey: signRotation(newKey.privateKey, payload),
}

const resp = await fetch(`http://[::1]:${port}/peer/key-rotation`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
assert.equal(resp.status, 403)
})

test("rejects mismatched agentId", async () => {
const oldKey = makeKeypair()
const newKey = makeKeypair()
const otherKey = makeKeypair()

const payload = {
agentId: otherKey.agentId, // doesn't match oldPublicKey
oldPublicKey: oldKey.publicKey,
newPublicKey: newKey.publicKey,
timestamp: Date.now(),
}

const body = {
...payload,
signatureByOldKey: signRotation(oldKey.privateKey, payload),
signatureByNewKey: signRotation(newKey.privateKey, payload),
}

const resp = await fetch(`http://[::1]:${port}/peer/key-rotation`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
assert.equal(resp.status, 400)
})
})