Skip to content

Implement Certificate Validation Rules and Comprehensive Test Suite #32

@Hemavathi15sg

Description

@Hemavathi15sg

Certificate Validation Rules Implementation & Testing

Overview

Implement comprehensive validation and testing for certificate generation, verification, and lifecycle management according to the certificate creation rules defined in .github/instructions/certificate.instructions.md.


Required Data Field Validations

1. CertificateId (GUID)

Rule: Immutable primary identifier, must be valid GUID

  • Test: Valid GUID generation
  • Test: GUID immutability after creation
  • Test: Reject invalid GUID formats
  • Test: Uniqueness constraint at database level

2. SerialNumber

Rule: Unique, sequential, human-readable (no PII)

  • Test: Sequential number generation
  • Test: Uniqueness enforcement at persistence layer
  • Test: Transactional allocation prevents gaps
  • Test: Human-readable format (e.g., CERT-2025-00001)
  • Test: No personally identifiable information in serial number

3. HolderName

Rule: Full official name (validated, sanitized), 1-120 characters with Unicode normalization

  • Test: Accept valid names (1-120 chars)
  • Test: Reject empty or null names
  • Test: Reject names < 1 character
  • Test: Reject names > 120 characters
  • Test: Unicode normalization (NFC) applied
  • Test: HTML/script tag sanitization
  • Test: Special character handling (accents, non-Latin scripts)
  • Test: Whitespace trimming and normalization

4. CourseTitle

Rule: Exact course name from catalog

  • Test: Valid course title from catalog
  • Test: Reject non-existent course titles
  • Test: Case-sensitive matching
  • Test: No HTML injection in course titles

5. IssueDateUtc

Rule: UTC timestamp, required field

  • Test: Valid UTC timestamp storage
  • Test: Reject null/empty dates
  • Test: Reject future dates (optional business rule)
  • Test: Proper UTC timezone handling (no local time conversion)
  • Test: ISO 8601 format compliance

6. ExpiryDateUtc

Rule: Nullable UTC timestamp, must be > IssueDateUtc when present

  • Test: Null expiry date for non-expiring certificates
  • Test: Valid future expiry date
  • Test: Reject expiry date ≤ issue date
  • Test: Proper UTC timezone handling
  • Test: Status automatically set to Expired when date passed

7. IssuedBy

Rule: Authority identifier (organization unit code)

  • Test: Valid organization unit code
  • Test: Reject unauthorized issuers
  • Test: Audit trail for issuer information

8. VerificationUrl

Rule: HTTPS endpoint to validate authenticity

  • Test: Valid HTTPS URL format
  • Test: Reject HTTP (non-secure) URLs
  • Test: URL includes CertificateId or SerialNumber
  • Test: URL accessibility and response validation

9. SignatureHash

Rule: SHA-256 hash of canonical certificate payload

  • Test: SHA-256 hash generation from canonical payload
  • Test: Hash recomputation on mutable field changes
  • Test: Tampered payload detection (hash mismatch)
  • Test: Canonical JSON ordering for consistent hashing
  • Test: Hash verification on certificate retrieval

10. Version

Rule: Semantic version of certificate schema

  • Test: Valid semantic version format (e.g., 1.0.0)
  • Test: Version incremented on schema changes
  • Test: Backward compatibility verification
  • Test: Version included in signature scope

11. Status

Rule: Active | Revoked | Expired enum

  • Test: Default status is Active on creation
  • Test: Status transition: Active → Revoked
  • Test: Status transition: Active → Expired
  • Test: Reject invalid status values
  • Test: Status immutability (cannot change Revoked/Expired back to Active)

Generation Workflow Tests

  • Test: Load finalized course completion record
  • Test: Construct canonical payload (stable ordered JSON)
  • Test: Generate unique GUID for CertificateId
  • Test: Allocate SerialNumber in transactional scope
  • Test: Compute SignatureHash with organization private key
  • Test: Atomic persistence (all-or-nothing)
  • Test: Event emission: CertificateIssued
  • Test: VerificationUrl generation with proper encoding
  • Test: Rollback on generation failure (no partial persistence)

Security Tests

  • Test: Private signing material not exposed in responses
  • Test: Rate limiting on verification endpoints
  • Test: Abuse detection for multiple failed verifications
  • Test: Enumeration prevention (require full SerialNumber or GUID)
  • Test: HTTPS-only enforcement
  • Test: HSTS header present on verification endpoints
  • Test: SQL injection prevention in verification queries
  • Test: XSS prevention in certificate display

Revocation Tests

  • Test: Revoke certificate with valid reason
  • Test: Store RevocationReason and RevokedDateUtc
  • Test: Maintain audit trail (who, when, why)
  • Test: Revoked certificates not deleted (soft delete)
  • Test: Verification endpoint returns explicit revoked state
  • Test: Revoked certificates excluded from active listings
  • Test: Cannot un-revoke a certificate

Verification Tests

  • Test: Verify valid certificate by CertificateId
  • Test: Verify valid certificate by SerialNumber
  • Test: Return 404 for non-existent certificates
  • Test: Return explicit revoked status for revoked certificates
  • Test: Return explicit expired status for expired certificates
  • Test: Signature hash validation on verification
  • Test: Tampered certificate detection
  • Test: Cache positive verification responses (60s)
  • Test: No caching of revoked status

Performance & Indexing Tests

  • Test: Index on CertificateId for fast lookups
  • Test: Index on SerialNumber for verification queries
  • Test: Index on Status for filtering
  • Test: Query performance < 100ms for verification
  • Test: Concurrent certificate generation (no serial number collisions)

Privacy & Data Exposure Tests

  • Test: Only public fields exposed in API responses
  • Test: No grades or performance metrics in certificate data
  • Test: No internal system identifiers exposed (except GUID)
  • Test: GDPR compliance: minimal data exposure

Rendering & Output Tests

  • Test: Server-side template rendering (no client-side generation)
  • Test: QR code generation pointing to VerificationUrl
  • Test: QR code includes alt text for accessibility
  • Test: PDF/HTML output meets WCAG AA standards
  • Test: Cache-busted branding assets
  • Test: No internal identifiers displayed (except via QR/URL)

Internationalization Tests

  • Test: ISO 8601 date format display
  • Test: Localized course title support
  • Test: Store invariant key + localized display string
  • Test: Multiple language certificate rendering

Error Handling Tests

  • Test: Generation failure triggers rollback
  • Test: No partial certificate persistence on error
  • Test: Descriptive error messages (no sensitive data)
  • Test: 404 for unknown certificate on verification
  • Test: Proper HTTP status codes (400, 404, 500)

Audit & Logging Tests

  • Test: Log certificate issuance with correlation ID
  • Test: Log verification lookups (access audit)
  • Test: Log revocations with justification
  • Test: Structured logging format (JSON)
  • Test: Log retention per compliance policy
  • Test: PII-free logging

Versioning & Migration Tests

  • Test: Increment Version on schema changes
  • Test: Backward compatibility for old certificate versions
  • Test: Verification supports all prior versions
  • Test: Migration preserves existing SignatureHash values
  • Test: No silent regeneration of historical certificates

Implementation Checklist

Domain Layer (CourseRegistration.Domain)

  • Create Certificate entity with all required fields
  • Create CertificateStatus enum (Active, Revoked, Expired)
  • Create ICertificateRepository interface

Application Layer (CourseRegistration.Application)

  • Create CertificateDto with proper data annotations
  • Implement CertificateService with generation workflow
  • Create CertificateValidator using FluentValidation
  • Implement signature hash generation
  • Implement verification logic

Infrastructure Layer (CourseRegistration.Infrastructure)

  • Implement CertificateRepository with EF Core
  • Add database indexes (CertificateId, SerialNumber, Status)
  • Implement serial number generation with transactions
  • Configure entity relationships

API Layer (CourseRegistration.API)

  • Create CertificatesController with endpoints:
    • POST /api/certificates/generate (admin only)
    • GET /api/certificates/{id} (public)
    • GET /api/certificates/verify/{serialNumber} (public)
    • POST /api/certificates/{id}/revoke (admin only)
    • GET /api/certificates/{id}/qr (public, returns QR code image)
  • Implement rate limiting middleware
  • Add HTTPS enforcement
  • Configure CORS for verification endpoints

Test Layer (CourseRegistration.Tests)

  • Create CertificateServiceTests (unit tests)
  • Create CertificateRepositoryTests (integration tests)
  • Create CertificateValidatorTests (validation tests)
  • Create CertificateControllerTests (API tests)
  • Achieve minimum 80% code coverage

Acceptance Criteria

✅ All validation rules implemented with corresponding tests
✅ Minimum 80% code coverage for certificate module
✅ All security tests passing (no vulnerabilities)
✅ Performance benchmarks met (< 100ms verification)
✅ Accessibility compliance (WCAG AA)
✅ Documentation updated with API examples
✅ Integration tests with real database
✅ Load testing completed (1000 concurrent verifications)


References

  • Certificate Creation Rules: .github/instructions/certificate.instructions.md
  • .NET Development Standards: .github/instructions/dotnet-dev.instructions.md
  • Existing CertificateService: api/CourseRegistration.Application/Services/CertificateService.cs
  • Existing Certificate entity: api/CourseRegistration.Domain/Entities/Certificate.cs

Priority: High

Type: Feature Implementation + Testing

Estimated Effort: 5-8 days

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions