본문으로 건너뛰기
cccskills
무료GitHub에 공개

audit-trail-test-author

Build-an-X for audit-log tests across compliance frameworks - required-events catalog (auth events / privilege change / data access / admin action / config change / export / impersonation); structured-log-format assertions per OWASP A09:2021; tamper-evident chain (hash-chain + signed-batch patterns) for HIPAA §164.312(b) + PCI Req 10 + SOC 2 CC7.3; immutability + retention per framework; query-replay tests for forensic reconstruction. Use when authoring audit log tests for any compliance framework (HIPAA / PCI / SOC 2 / GDPR / etc.).

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa스타 13(GitHub 13 + cccskills 0)

실행 점수 미검증

설치 방법 보기

포함된 파일(2)

  • SKILL.md11.0 KB
  • .tessl-plugin/plugin.json679 B

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

audit-trail-test-author

Overview

Audit logs are the universal compliance-evidence artifact. Every major framework requires them, with overlapping but framework-specific requirements:

FrameworkAudit log requirement
HIPAA Security Rule §164.312(b)"implement hardware, software, and/or procedural mechanisms that record and examine activity in information systems that contain or use ePHI"
PCI DSS v4.0 Req 10Audit trails for all access to system components, plus log review + retention
SOC 2 CC7.3Detection of security events + logging
GDPR Art. 5(1)(f) + Art. 32Integrity + confidentiality of personal data; audit log is the standard evidence
ISO 27001 A.8.15Logging
NIST 800-53 AU familyAudit + accountability controls

This is a build-an-X workflow - the per-system audit-log test recipe. Different from a generic logging skill; specifically focused on compliance-grade audit trails (tamper-evidence, retention, required events).

When to use

  • Compliance framework requires audit logging.
  • Authoring tests for a new feature that handles regulated data.
  • Audit findings flagged audit-log gaps in a previous review.
  • New service/component must be onboarded to org-wide audit pipeline.

Step 1 - Required-events catalog

Universal events (required by most compliance frameworks):

Event classExamples
AuthenticationLogin success / failure / lockout / session expiry / MFA challenge
AuthorizationPermission grant / revoke / failed-access-attempt / role change
Data accessRead PHI / PII / payment data; query that returns regulated data
Data modificationCreate / update / delete of regulated records (with before/after)
Admin actionConfig change / user provision / deprovision / privilege escalation
System eventsService start / stop / crash / restart / config-reload
Export / disclosureBulk download / API export / cross-org sharing
Impersonation / escalation"Sign in as" / sudo / break-glass access
Failed actionsAnything in the above categories that errored / was denied

Per-framework additions:

  • HIPAA: emergency-access invocation
  • PCI: PAN access (must NOT contain the PAN itself)
  • SOC 2: change-management events
  • GDPR: data-subject-rights workflow events (SAR, erasure)

Step 2 - Structured log format

Per OWASP A09:2021 (Security Logging + Monitoring Failures), audit logs MUST be structured (JSON) - NOT free-text. Schema:

{
  "event_id": "audit-2026-05-06T12:00:00Z-abc123",
  "timestamp": "2026-05-06T12:00:00.123Z",
  "event_type": "phi_access",
  "actor": {
    "user_id": "alice@example.com",
    "session_id": "sess-xyz",
    "ip_address": "203.0.113.42",
    "user_agent": "Mozilla/5.0..."
  },
  "subject": {
    "type": "patient_record",
    "id": "patient:123",
    "phi_type": "clinical_notes"
  },
  "action": "read",
  "outcome": "success",
  "context": {
    "request_id": "req-abc",
    "service": "ehr-api",
    "version": "1.2.3"
  },
  "previous_event_hash": "sha256:abc...",
  "this_event_hash": "sha256:def..."
}

Test pattern:

def test_audit_log_structure_valid():
    user.access_phi(patient_id=123)
    audit = AuditLog.objects.latest('timestamp')
    # Required fields
    for field in ['event_id', 'timestamp', 'event_type', 'actor', 'subject', 'action', 'outcome']:
        assert field in audit.to_dict()
    # Actor structure
    for sub_field in ['user_id', 'session_id', 'ip_address', 'user_agent']:
        assert sub_field in audit.actor
    # Schema-validated
    assert validate_against_schema(audit, 'audit-event-v1.json-schema')

Step 3 - Tamper-evident chain (hash-chain)

For HIPAA §164.312(b) / PCI Req 10 / SOC 2 CC7.3 integrity requirements:

def test_audit_log_hash_chain_integrity():
    """Each event references the previous event's hash; tampering breaks the chain."""
    events = AuditLog.objects.all().order_by('timestamp')
    for i in range(1, len(events)):
        previous = events[i - 1]
        current = events[i]
        # current event's previous_event_hash must equal previous event's hash
        assert current.previous_event_hash == previous.this_event_hash, \
            f"Hash chain broken at event {current.event_id}"
        # Each event's hash is reproducible from its content
        recomputed = sha256(current.canonical_serialization())
        assert current.this_event_hash == recomputed, \
            f"Event {current.event_id} hash mismatch (tampered?)"

For higher integrity (PCI / fintech), use signed-batch logs:

def test_audit_batch_signed_by_kms():
    """Daily batches signed by KMS; tampering invalidates signature."""
    today_batch = AuditBatch.objects.get(date=today())
    # Verify signature against KMS public key
    assert kms.verify_signature(today_batch.content, today_batch.signature)

Step 4 - Immutability + retention

Audit logs MUST be append-only + retention-enforced:

def test_audit_log_append_only():
    """Old events must not be modifiable / deletable."""
    old = AuditLog.objects.first()
    # Database row-level: UPDATE on audit_log table fails for non-admin
    with pytest.raises(PermissionDenied):
        connection.cursor().execute(f"UPDATE audit_log SET action = 'X' WHERE id = {old.id}")
    with pytest.raises(PermissionDenied):
        connection.cursor().execute(f"DELETE FROM audit_log WHERE id = {old.id}")

def test_audit_log_retention_policy():
    """Logs older than retention period are archived, not deleted (PCI: 1 year online + 1 year archive minimum)."""
    expired = AuditLog.objects.filter(timestamp__lt=timezone.now() - timedelta(days=365)).first()
    if expired:
        # Should be in archive, not main store
        assert AuditArchive.objects.filter(event_id=expired.event_id).exists()

Retention requirements vary:

FrameworkRetention
PCI DSS Req 10.5.11 year minimum, last 3 months online
HIPAA §164.316(b)(2)6 years from creation or last effective date
SOC 2observation period + reasonable retention
GDPRas long as needed for the documented purpose
ISO 27001per ISMS retention policy

Step 5 - PII redaction

For frameworks that require audit logs but forbid PII in logs (PCI: no PAN; HIPAA: minimum-necessary):

def test_pan_not_in_audit_logs():
    """PCI Req 3.4: PAN must not appear in audit logs."""
    user.access_card(card_id=123)
    audit_text = AuditLog.objects.latest('timestamp').full_event_text
    # No 13-19 digit sequences (typical PAN length)
    assert not re.search(r'\d{13,19}', audit_text)

def test_phi_redacted_in_audit():
    """HIPAA minimum-necessary: log access event but not PHI content."""
    user.access_patient_record(patient_id=123)
    audit = AuditLog.objects.latest('timestamp')
    # Should log: who, what (event type), when, on which subject
    assert 'patient:123' in audit.subject_id
    # Should NOT log: the actual clinical notes content
    assert 'diagnosis' not in audit.full_event_text

Step 6 - Forensic reconstruction (query-replay)

Compliance frameworks require ability to reconstruct events for investigation:

def test_can_reconstruct_user_activity_in_window():
    """SOC 2 CC7.3: detect security events; allows post-incident reconstruction."""
    user_id = 'alice@example.com'
    start = timezone.now() - timedelta(days=7)
    end = timezone.now()

    activity = AuditLog.objects.filter(
        actor__user_id=user_id,
        timestamp__range=[start, end],
    )
    # Activity is queryable + complete (no gaps)
    assert activity.count() > 0
    timestamps = sorted([e.timestamp for e in activity])
    # No suspicious gaps (e.g., gaps > 1 hour during active session)
    for i in range(1, len(timestamps)):
        gap = (timestamps[i] - timestamps[i - 1]).total_seconds()
        # Annotate: this would be domain-specific; just ensure queryable

Step 7 - Cross-system aggregation

Modern systems span microservices; per-service local audit logs must aggregate to a central audit store:

def test_audit_events_aggregated_centrally():
    """Distributed audit events MUST land in central store within SLA."""
    # Trigger an event in microservice A
    response = service_a.access_phi(patient_id=123)
    event_id = response.headers['X-Event-ID']

    # Within 30 seconds, central store should have it
    deadline = time.time() + 30
    while time.time() < deadline:
        if CentralAuditStore.objects.filter(event_id=event_id).exists():
            return
        time.sleep(1)
    pytest.fail(f"Event {event_id} not aggregated to central store within 30s")

Step 8 - End-to-end test recipe

For each system handling regulated data:

  1. ✅ Required events emitted (Step 1 catalog)
  2. ✅ Structured format conforms to schema (Step 2)
  3. ✅ Hash chain or signed-batch integrity (Step 3)
  4. ✅ Append-only + retention enforced (Step 4)
  5. ✅ Sensitive content redacted (Step 5)
  6. ✅ Forensic-replay queries succeed (Step 6)
  7. ✅ Distributed events aggregate centrally (Step 7)

Anti-patterns

Anti-patternWhy it failsFix
Free-text logs without structureCan't reliably query for forensicsStructured JSON (Step 2)
No tamper-evidenceLogs modifiable post-incident; auditor rejectsHash chain or signed batch (Step 3)
PAN/PII in logsPCI/HIPAA violation in the audit logs themselvesRedaction (Step 5)
Audit logs writable by appApp compromise = audit log tamperingAppend-only DB perms (Step 4)
Per-service local logs onlyNo cross-service incident reconstructionCentral aggregation (Step 7)

Limitations

  • This is a build-an-X workflow. Tests use the team's existing test framework + DB / log-store APIs.
  • Tamper-evidence is implementation-specific; hash-chain is one option; signed-batch + WORM storage another.
  • Some frameworks (GDPR) require subject access to their own audit logs - adds a SAR-flow assertion that varies by interpretation.
  • Distributed-system clock-skew can cause hash-chain disorder; use logical clocks (Lamport / vector) for ordering critical events.

References

  • owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures - OWASP Top 10 2021 audit logging
  • nist.gov/publications/sp-800-92-guide-computer-security-log-management - NIST SP 800-92 log management guide
  • hipaa-test-patterns - §164.312(b)
  • pci-dss-control-test-author - Req 10
  • soc2-evidence-collector - CC7.3
  • gdpr-test-patterns - Art. 5(1)(f)

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Builds a CI gate that fails the build on **new** WCAG / a11y violations introduced by a PR while grandfathering pre-existing violations on a per-rule / per-page baseline. Aggregates verdicts from axe-core / pa11y / Lighthouse a11y / WAVE / IBM Equal Access scans. Use when a project has accumulated a11y debt and a strict "zero violations" gate would block every PR - the ratchet pattern lets the team ship while preventing regressions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Workflow skill that builds an A/B-test validity checklist from an experiment proposal, walking the canonical design-correctness gates - pre-registered OEC/power/guardrails, randomization unit + SRM check, assignment integrity, telemetry, peeking discipline, novelty/primacy, post-experiment SRM re-check - into a per-experiment checklist + sign-off form. Use when launching, auditing, or governing an experiment. For pitfall mechanics (guardrails, peeking) see experiment-results-interpreter's references; to read an already-valid result use experiment-results-interpreter; for per-SDK harness tests use experiment-sdk-testing - this gates DESIGN, not SDK code.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

The single install-flow skill: the reference contract for the PWA install flow (installability gate fields, `beforeinstallprompt` handshake, per-platform paths - Android WebAPK / iOS Share menu / Firefox no-op - and the `display-mode` post-install signal, in references/install-flow-reference.md) plus the build-an-X workflow that emits the Add-to-Home-Screen suite. Walks the four-stage timeline, emitting one test per gate cell per [web.dev/articles/install-criteria][install-criteria], the deferred-prompt → `prompt()` → `userChoice` chain per [web.dev/articles/customize-install][customize-install], the iOS Safari manual-metadata branch (`apple-touch-icon`) per [web.dev/learn/pwa/installation][learn-pwa], and the post-install `(display-mode: standalone)` MQ assertion. Output: a Playwright spec with per-stage cells plus a coverage matrix. Use when a PWA's manifest, icons, or install handler change, when install conversion drops at an unknown stage, or when triaging a flaky install assertion.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Build-an-X workflow that uses an LLM to map existing tests to spec sections - given a spec doc + the test suite, the LLM identifies which tests cover which sections, surfaces uncovered sections (gap), and recommends specific tests to add. Output is a coverage matrix per spec ID. Scope is mapping tests that already exist and naming the gaps, not authoring tests for new acceptance criteria. Use when a spec doc and a test suite both exist but nobody can say which requirements are actually covered - before a release sign-off, an audit, or a decision about where to spend the next round of test effort.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Generates tests from natural-language specs (acceptance criteria, user stories, requirements) using an LLM, with confidence scoring per test case (LLM self-assessment plus heuristics: assertion quality, naming, completeness), batching uncertain cases for human review, and integration with the team's existing test framework. Use when the user asks to generate unit tests from acceptance criteria, convert user stories to test cases, automate test creation from requirements, or augment a spec-driven test suite with AI-generated stubs that are then curated before merge.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

Configures Allure Report (test-runner adapter install, `allure-results` directory wiring, `categories.json` for failure classification, `history-trend.json` retention via the copy-history-between-runs pattern), runs the Allure CLI to convert `allure-results` to a static HTML site, and uploads the report as a CI artifact. Use when the team needs richer test reporting than JUnit XML - step-level attachments, per-test history, retry tracking, and severity / epic / feature labeling across framework-agnostic adapters (pytest, Jest, JUnit, TestNG, NUnit, Mocha). As a rich static HTML report generator, it is the open-source alternative to the sunset ExtentReports (JVM/.NET per-test HTML narrative); for hosted cross-run flakiness analytics rather than a static per-run report use currents-integration.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

testland/qa132026년 10월 20일 업데이트

testland의 스킬 모두 보기

이 스킬의 문제 신고