← Blog

Claude skill audit trail and transaction logging security — SA-SKL-TXLOG

MCP skills that handle privileged operations — admin account deletions, plan tier changes, API key rotations, permission grants — need an append-only audit trail that survives transaction rollbacks, cannot be deleted by the subject of the audit, and can be verified for integrity after the fact. SkillAudit finds four consistent gaps: privileged actions not logged at all, audit log entries written inside the same transaction as the action so rollbacks erase them, audit entries writable via the same DELETE endpoint as other data, and no tamper-detection mechanism on stored entries. SA-SKL-TXLOG-001 through TXLOG-004 cover each failure mode with code examples and fixes.

By SkillAudit  |  5 Nov 2026

Why audit trail gaps are high-severity in MCP skills

An MCP skill operating as a trust intermediary — scanning code repositories, managing API credentials, enforcing security policy — takes actions whose consequences outlast the HTTP request that triggered them. When those actions are attacked, the audit trail is the forensic record: when did the attacker first access the system, what did they modify, which credentials did they rotate to ones they control, which users were affected. A missing or incomplete audit trail does not prevent the attack — it prevents detection, containment, and attribution. For skills that hold Team plan subscribers to SOC 2 or compliance commitments, an audit trail is not optional; its absence is a contract breach.

The four SA-SKL-TXLOG patterns describe progressively more sophisticated gaps: TXLOG-001 is an audit log that simply does not exist for some actions; TXLOG-002 is an audit log that exists but is silently dropped on transaction failure; TXLOG-003 is an audit log that users can delete via standard API endpoints; TXLOG-004 is an audit log that cannot be trusted even if it exists because there is no mechanism to detect post-write modifications.

SA-SKL-TXLOG in scope: TXLOG-001 (missing audit trail for privileged actions), TXLOG-002 (audit log in same DB transaction), TXLOG-003 (audit log user-deletable), TXLOG-004 (audit log without tamper detection). Each includes the attack scenario, vulnerable code pattern, and fix.

TXLOG-001 — Missing audit trail for privileged actions

MCP skills typically log routine operations — audit submissions, scan results, badge generations — but omit audit entries for the most consequential actions: admin-initiated account deletions, plan tier upgrades and downgrades, API key rotations, permission scope changes, and SSO configuration changes. These actions are exactly what an attacker performs after gaining unauthorized access. Without a log entry, an incident response team discovering a breach two weeks later cannot determine what the attacker changed, which accounts were affected, or when access was first gained. The fix is a before/after snapshot pattern that records the state before and after every privileged mutation, stored in a separate audit_log table with the acting user's ID, timestamp, action type, and affected resource.

// VULNERABLE: plan upgrade updates the subscription record without any audit entry
app.post('/api/subscription/upgrade', requireAuth, async (req, res) => {
  const { planId } = req.body;

  // No audit entry before or after — attacker who gains billing access
  // can upgrade/downgrade plans with no forensic record
  await db.subscriptions.update({
    userId: req.session.userId,
    planId,
    updatedAt: new Date(),
  });

  res.json({ ok: true });
});
// FIXED: before/after snapshot written to audit_log before committing the change
app.post('/api/subscription/upgrade', requireAuth, async (req, res) => {
  const { planId } = req.body;

  const current = await db.subscriptions.findOne({ userId: req.session.userId });

  // Write audit entry BEFORE the change — captures before state
  // If the update fails, the audit entry still records the attempt
  await db.audit_log.create({
    actorUserId: req.session.userId,
    action: 'subscription.upgrade',
    resourceType: 'subscription',
    resourceId: current.id,
    before: { planId: current.planId },
    after: { planId },
    ip: req.ip,
    userAgent: req.headers['user-agent'],
    at: new Date(),
  });

  await db.subscriptions.update({
    userId: req.session.userId,
    planId,
    updatedAt: new Date(),
  });

  res.json({ ok: true });
});
HIGH
SA-SKL-TXLOG-001 — MCP skill does not write audit log entries for privileged mutations (admin deletes, plan changes, API key rotations, permission grants); an attacker who gains unauthorized access can perform consequential actions with no forensic record, preventing incident detection and attribution. Fix: audit_log table with actorUserId, action, before/after snapshots, ip, and at timestamp; write entry before every privileged mutation. Detection: SkillAudit flags route handlers for /admin/, /api/key, /api/subscription, and /api/permission that contain database writes without a preceding audit_log insert.

TXLOG-002 — Audit log entry in same DB transaction

When audit log entries are written inside the same database transaction as the action they record, a rolled-back transaction silently discards both the action and its audit record. This creates a gap: operations that fail atomically (due to validation errors, constraint violations, or explicit rollback) produce no log entry. An attacker probing the system with invalid inputs generates zero audit trail — every failed probe attempt disappears with its transaction. More critically, in SQLite (the SkillAudit tech stack) a failed audit write can silently suppress an audit entry even when the main operation succeeds, depending on transaction ordering. The fix is to write audit entries outside the main transaction, in a separate database connection or after the transaction commits.

// VULNERABLE: audit entry inside the same transaction as the action
app.delete('/api/admin/user/:id', requireAdmin, async (req, res) => {
  const tx = await db.transaction(); // Single transaction for both writes
  try {
    await db.users.destroy({ where: { id: req.params.id }, transaction: tx });

    // If audit_log.create throws (e.g., constraint violation), the whole tx rolls back
    // If the user delete fails for any reason, the audit entry also disappears
    await db.audit_log.create({
      action: 'admin.user.delete',
      resourceId: req.params.id,
      actorUserId: req.session.userId,
      at: new Date(),
    }, { transaction: tx }); // ← Same transaction: sink or swim together

    await tx.commit();
    res.json({ ok: true });
  } catch (err) {
    await tx.rollback(); // Both the delete AND the audit entry are erased
    res.status(500).json({ error: 'Failed' });
  }
});
// FIXED: audit entry written outside the main transaction
app.delete('/api/admin/user/:id', requireAdmin, async (req, res) => {
  const user = await db.users.findOne({ id: req.params.id });
  if (!user) return res.status(404).json({ error: 'Not found' });

  // Write audit entry FIRST, outside any transaction
  // Even if the delete fails, the attempt is recorded
  await db.audit_log.create({
    action: 'admin.user.delete',
    resourceType: 'user',
    resourceId: req.params.id,
    before: { email: user.email, planId: user.planId },
    actorUserId: req.session.userId,
    ip: req.ip,
    at: new Date(),
    // status will be updated after the action completes
    status: 'attempted',
  });

  try {
    await db.users.destroy({ id: req.params.id });

    // Update audit entry status to reflect success (outside main operation)
    await db.audit_log.updateLatest({ resourceId: req.params.id, status: 'completed' });
    res.json({ ok: true });
  } catch (err) {
    await db.audit_log.updateLatest({ resourceId: req.params.id, status: 'failed', error: err.code });
    res.status(500).json({ error: 'Delete failed' });
  }
});
HIGH
SA-SKL-TXLOG-002 — MCP skill audit log entries are written inside the same database transaction as the mutating operation; a transaction rollback silently discards both the action and its audit record, creating invisible gaps for failed or probed operations; an attacker iterating invalid inputs to find exploitable states generates no audit trail. Fix: write audit entries in a separate db.audit_log.create() call outside any transaction and before the main operation; use a status field (attempted / completed / failed) to track outcomes. Detection: SkillAudit flags audit_log.create() calls that receive a transaction option shared with a data-mutating call in the same handler.

TXLOG-003 — Audit log entries user-deletable

MCP skills with per-user data deletion endpoints (GDPR compliance, "delete my account") sometimes include the audit_log table in the deletion scope. This allows users to delete their own audit trail. An attacker who compromises an account and performs unauthorized actions can then trigger account deletion to erase the evidence. Even in non-adversarial scenarios, a user disputing a billing action may delete their audit log before support can review it. The fix is to separate audit log ownership from user data ownership: audit entries are owned by the system, not the user, and are not included in user-initiated deletion flows. Retention should be governed by a system-level retention policy (e.g., 90 days), not by user action.

// VULNERABLE: audit_log included in user-initiated delete scope
app.delete('/api/account', requireAuth, async (req, res) => {
  const userId = req.session.userId;

  // GDPR deletion — but audit_log is included, letting users erase their trail
  await Promise.all([
    db.users.destroy({ id: userId }),
    db.subscriptions.destroy({ userId }),
    db.audits.destroy({ userId }),       // audit history of scans — appropriate
    db.audit_log.destroy({ actorUserId: userId }), // ← VULNERABLE: system audit trail deleted
  ]);

  res.json({ ok: true });
});
// FIXED: audit_log excluded from user-initiated deletion; governed by retention policy
app.delete('/api/account', requireAuth, async (req, res) => {
  const userId = req.session.userId;

  // User data deleted on request (GDPR right to erasure)
  await Promise.all([
    db.users.destroy({ id: userId }),
    db.subscriptions.destroy({ userId }),
    db.audits.destroy({ userId }),
    // audit_log is NOT deleted — it is a system record, not user data
    // The actorUserId field is pseudonymized by the retention job, not deleted
  ]);

  // Pseudonymize the user reference in audit_log rather than deleting entries
  // This preserves the action record while removing PII
  await db.audit_log.pseudonymize({ actorUserId: userId });

  res.json({ ok: true });
});

// Separate system retention job (runs daily via cron):
// await db.audit_log.destroyOlderThan(90); // 90-day retention policy
HIGH
SA-SKL-TXLOG-003 — MCP skill account deletion or GDPR erasure endpoint includes audit_log entries in the deletion scope, allowing users to delete their own audit trail; an attacker who performs unauthorized actions can trigger account deletion to erase the evidence of their activity. Fix: exclude audit_log from user-initiated deletion flows; pseudonymize the actorUserId reference on GDPR erasure rather than deleting entries; govern audit log retention with a system-level retention policy separate from user data. Detection: SkillAudit flags route handlers containing audit_log.destroy() or audit_log.deleteMany() with a userId or actorUserId filter in a user-authenticated context.

TXLOG-004 — Audit log without tamper detection

Even when audit log entries exist, are transactionally isolated, and cannot be deleted by users, a compromised database connection or a malicious database administrator can silently modify or delete entries. For MCP skills that offer compliance exports (SOC 2 audit log export, SBOM reports), the audit log's integrity is part of the compliance claim. A tamper-evident log uses a SHA-256 hash chain: each entry includes the hash of the previous entry, so any modification to an earlier entry invalidates all subsequent hashes. This does not prevent modification by a database admin, but it makes modification detectable: the hash chain verification will fail when the log is next read. For stronger guarantees, the log can be mirrored to an append-only external sink (Cloudflare R2 with Object Lock, AWS S3 with S3 Object Lock).

// VULNERABLE: audit log entries stored without integrity check
await db.audit_log.create({
  actorUserId: req.session.userId,
  action: 'admin.apikey.rotate',
  resourceId: keyId,
  before: { keyPrefix: oldKey.substring(0, 8) },
  at: new Date(),
  // No previousHash, no entryHash — entries are plain mutable rows
});
// FIXED: SHA-256 hash chain — each entry hashes the previous entry's hash
const crypto = require('crypto');

async function appendAuditLog(entry) {
  // Retrieve the hash of the most recent entry (null for first entry)
  const latest = await db.audit_log.findLatest();
  const previousHash = latest?.entryHash ?? '0'.repeat(64);

  // Build the canonical entry body (deterministic JSON)
  const entryBody = JSON.stringify({
    actorUserId: entry.actorUserId,
    action: entry.action,
    resourceType: entry.resourceType,
    resourceId: entry.resourceId,
    before: entry.before ?? null,
    after: entry.after ?? null,
    ip: entry.ip,
    at: entry.at.toISOString(),
    previousHash,
  });

  // Hash the entry body — chains to previous entry
  const entryHash = crypto.createHash('sha256').update(entryBody).digest('hex');

  await db.audit_log.create({
    ...entry,
    previousHash,
    entryHash,
  });

  return entryHash;
}

// Verification function — run periodically or on compliance export
async function verifyAuditLogIntegrity() {
  const entries = await db.audit_log.findAll({ order: [['id', 'ASC']] });
  let previousHash = '0'.repeat(64);

  for (const entry of entries) {
    const expectedBody = JSON.stringify({
      actorUserId: entry.actorUserId,
      action: entry.action,
      resourceType: entry.resourceType,
      resourceId: entry.resourceId,
      before: entry.before ?? null,
      after: entry.after ?? null,
      ip: entry.ip,
      at: new Date(entry.at).toISOString(),
      previousHash,
    });
    const expectedHash = crypto.createHash('sha256').update(expectedBody).digest('hex');

    if (expectedHash !== entry.entryHash) {
      throw new Error(`Audit log tamper detected at entry ${entry.id}`);
    }
    previousHash = entry.entryHash;
  }
  return true; // Chain valid
}
MEDIUM
SA-SKL-TXLOG-004 — MCP skill audit log entries are stored as plain mutable database rows without any integrity verification mechanism; a compromised database connection or database admin can silently modify or delete entries without detection; compliance exports based on this log cannot be trusted. Fix: implement a SHA-256 hash chain where each entry includes previousHash (hash of the prior entry) and entryHash (SHA-256 of the canonical entry body including previousHash); run chain verification on compliance export; for stronger guarantees, mirror entries to an append-only external sink (S3 Object Lock, Cloudflare R2 with Object Lock). Detection: SkillAudit flags audit_log table schemas that do not include a previousHash or entryHash column in the ORM model definition.

SkillAudit detection summary — SA-SKL-TXLOG

Pattern IDSeverityWhat SkillAudit flagsFix
TXLOG-001HIGHRoute handlers for /admin/, /api/key, /api/subscription, /api/permission that contain DB writes without a preceding audit_log insertaudit_log table with before/after snapshot, actorUserId, ip, at
TXLOG-002HIGHaudit_log.create() calls that receive a transaction option shared with a data-mutating call in the same handlerWrite audit entry outside any transaction, before the main operation
TXLOG-003HIGHaudit_log.destroy() with a userId/actorUserId filter in a user-authenticated route handlerExclude audit log from user deletion; pseudonymize PII fields instead
TXLOG-004MEDIUMaudit_log ORM model that does not define previousHash or entryHash columnsSHA-256 hash chain; verifyAuditLogIntegrity() on compliance export

Related patterns: For credential and secret exposure that creates the need for key rotation (which should be logged), see SA-SKL-SECRETEXPOSE. For log injection attacks that can forge entries in application logs (distinct from audit trail integrity), see SA-SKL-LOGINJECT.