All files / src/security certificateManager.js

36.2% Statements 21/58
46.87% Branches 15/32
38.46% Functions 5/13
36.2% Lines 21/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 2393x       42x 42x 42x 42x               42x                       42x                 1x 1x 1x 1x   1x                                               1x   1x                                                                                                                 1x 1x 1x 1x                                           1x 1x                                                                                                                                                                               3x
const crypto = require('crypto');
 
class CertificateManager {
  constructor(config = {}) {
    this.algorithm = config.algorithm || 'RSA-SHA256';
    this.keyPair = config.keyPair || this.generateKeyPair();
    this.issuer = config.issuer || 'validation-service';
    this.validityDays = config.validityDays || 30;
  }
 
  /**
   * Generate RSA key pair for signing certificates
   * @returns {object} Key pair
   */
  generateKeyPair() {
    const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
      modulusLength: 2048,
      publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
      },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
      }
    });
 
    return { publicKey, privateKey };
  }
 
  /**
   * Generate a validation certificate
   * @param {object} data - Certificate data
   * @returns {Promise<object>} Generated certificate
   */
  async generateCertificate(data) {
    const certificateId = crypto.randomBytes(16).toString('hex');
    const issuedAt = new Date();
    const expiresAt = new Date(issuedAt);
    expiresAt.setDate(expiresAt.getDate() + this.validityDays);
 
    const certificate = {
      id: certificateId,
      version: '1.0',
      issuer: this.issuer,
      subject: {
        serviceName: data.serviceName,
        serviceVersion: data.version
      },
      issuedAt: issuedAt.toISOString(),
      expiresAt: expiresAt.toISOString(),
      validationResults: {
        timestamp: data.validationResults.timestamp,
        success: data.validationResults.success,
        checks: data.validationResults.checks
      },
      fingerprint: this.generateFingerprint(data.validationResults),
      extensions: {
        allowedOperations: data.allowedOperations || ['register', 'heartbeat', 'workflow'],
        restrictions: data.restrictions || [],
        metadata: data.metadata || {}
      }
    };
 
    // Sign the certificate
    certificate.signature = this.signData(certificate);
 
    return certificate;
  }
 
  /**
   * Verify a validation certificate
   * @param {object} certificate - Certificate to verify
   * @returns {Promise<boolean>} Verification result
   */
  async verifyCertificate(certificate) {
    try {
      // Check expiration
      const now = new Date();
      const expiresAt = new Date(certificate.expiresAt);
      if (now > expiresAt) {
        throw new Error('Certificate has expired');
      }
 
      // Check issued date (not in future)
      const issuedAt = new Date(certificate.issuedAt);
      if (now < issuedAt) {
        throw new Error('Certificate issued in the future');
      }
 
      // Verify signature
      const certCopy = { ...certificate };
      const providedSignature = certCopy.signature;
      delete certCopy.signature;
 
      const calculatedSignature = this.signData(certCopy);
      if (providedSignature !== calculatedSignature) {
        throw new Error('Invalid certificate signature');
      }
 
      // Verify fingerprint
      const calculatedFingerprint = this.generateFingerprint(certificate.validationResults);
      if (certificate.fingerprint !== calculatedFingerprint) {
        throw new Error('Certificate data has been tampered with');
      }
 
      // Check issuer
      if (certificate.issuer !== this.issuer) {
        throw new Error(`Unknown certificate issuer: ${certificate.issuer}`);
      }
 
      return true;
    } catch (error) {
      console.error('Certificate verification failed:', error.message);
      return false;
    }
  }
 
  /**
   * Sign data with private key
   * @param {object} data - Data to sign
   * @returns {string} Signature
   */
  signData(data) {
    const sign = crypto.createSign(this.algorithm);
    sign.update(JSON.stringify(data, Object.keys(data).sort()));
    sign.end();
    return sign.sign(this.keyPair.privateKey, 'hex');
  }
 
  /**
   * Verify data signature with public key
   * @param {object} data - Data to verify
   * @param {string} signature - Signature to verify
   * @returns {boolean} Verification result
   */
  verifySignature(data, signature) {
    const verify = crypto.createVerify(this.algorithm);
    verify.update(JSON.stringify(data, Object.keys(data).sort()));
    verify.end();
    return verify.verify(this.keyPair.publicKey, signature, 'hex');
  }
 
  /**
   * Generate fingerprint for data
   * @param {object} data - Data to fingerprint
   * @returns {string} Fingerprint
   */
  generateFingerprint(data) {
    const sortedData = JSON.stringify(data, Object.keys(data).sort());
    return crypto.createHash('sha256').update(sortedData).digest('hex');
  }
 
  /**
   * Revoke a certificate (would need persistent storage in production)
   * @param {string} certificateId - Certificate ID to revoke
   * @returns {Promise<void>}
   */
  async revokeCertificate(certificateId) {
    // In production, this would update a revocation list in database
    // For now, we'll just log it
    console.log(`Certificate ${certificateId} has been revoked`);
  }
 
  /**
   * Check if a certificate is revoked
   * @param {string} certificateId - Certificate ID to check
   * @returns {Promise<boolean>} True if revoked
   */
  async isCertificateRevoked(certificateId) {
    // In production, this would check against a revocation list
    // For now, always return false
    return false;
  }
 
  /**
   * Export public key for distribution
   * @returns {string} Public key in PEM format
   */
  exportPublicKey() {
    return this.keyPair.publicKey;
  }
 
  /**
   * Generate a certificate chain (for future use with intermediate CAs)
   * @param {object} certificate - Leaf certificate
   * @param {Array} chain - Certificate chain
   * @returns {object} Complete chain
   */
  generateCertificateChain(certificate, chain = []) {
    return {
      certificate,
      chain,
      rootCA: this.exportPublicKey()
    };
  }
 
  /**
   * Validate certificate permissions
   * @param {object} certificate - Certificate to check
   * @param {string} operation - Operation to validate
   * @returns {boolean} True if operation is allowed
   */
  validatePermissions(certificate, operation) {
    if (!certificate.extensions || !certificate.extensions.allowedOperations) {
      return false;
    }
 
    return certificate.extensions.allowedOperations.includes(operation);
  }
 
  /**
   * Generate a validation report from certificate
   * @param {object} certificate - Certificate to analyze
   * @returns {object} Validation report
   */
  generateValidationReport(certificate) {
    const now = new Date();
    const expiresAt = new Date(certificate.expiresAt);
    const daysRemaining = Math.floor((expiresAt - now) / (1000 * 60 * 60 * 24));
 
    return {
      certificateId: certificate.id,
      serviceName: certificate.subject.serviceName,
      serviceVersion: certificate.subject.serviceVersion,
      issuer: certificate.issuer,
      issuedAt: certificate.issuedAt,
      expiresAt: certificate.expiresAt,
      daysRemaining,
      isExpired: daysRemaining < 0,
      validationPassed: certificate.validationResults.success,
      checksPerformed: Object.keys(certificate.validationResults.checks || {}),
      allowedOperations: certificate.extensions.allowedOperations,
      restrictions: certificate.extensions.restrictions
    };
  }
}
 
module.exports = CertificateManager;