All files index.js

77.7% Statements 122/157
82.1% Branches 78/95
76.92% Functions 20/26
78.06% Lines 121/155

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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 4995x 5x 5x                 132x                       132x               132x 132x     132x             132x     132x 132x 132x 132x     132x   132x                     35x   35x   29x   4x 4x     4x                       4x           29x 29x 29x   6x 6x                 62x 4x 58x 1x 57x   16x 16x     4x       62x                     20x   20x       20x 1x 19x 4x   15x       20x     20x         20x 20x 9x   9x                       11x                       9x   9x                 2x 2x               10x 10x     10x 10x 1x 1x       9x     8x 8x 8x   8x     8x 5x   5x 2x         3x       6x     6x 3x     6x     3x 3x                                                                                                                                                                                                   1015x 3x 3x       1015x               6x 6x   5x 3x 2x     4x   2x 2x                 132x 132x 132x   132x       4x     128x             1x 1x 1x 1x               6x 6x               22x 9x 9x   22x             14x             3x 3x               33x                 19x             3x 3x                     4x 4x 4x   4x 4x   4x 4x               4x 4x                 5x
const Minio = require('minio');
const crypto = require('crypto');
const winston = require('winston');
 
/**
 * Storage Connector for MinIO with automatic fingerprinting
 * Provides immutable content storage with verification
 */
class StorageConnector {
  constructor(config = {}) {
    // Logger setup
    this.logger = winston.createLogger({
      level: config.logLevel || 'info',
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json()
      ),
      transports: [
        new winston.transports.Console()
      ]
    });
 
    // MinIO client configuration
    const minioConfig = {
      endPoint: config.endPoint || process.env.MINIO_ENDPOINT || 'localhost',
      port: parseInt(config.port || process.env.MINIO_PORT || 9000),
      useSSL: config.useSSL || process.env.MINIO_USE_SSL === 'true',
      accessKey: config.accessKey || process.env.MINIO_ACCESS_KEY || 'minioadmin',
      secretKey: config.secretKey || process.env.MINIO_SECRET_KEY || 'minioadmin'
    };
 
    this.client = new Minio.Client(minioConfig);
    this.defaultBucket = config.defaultBucket || process.env.MINIO_DEFAULT_BUCKET || 'api-storage';
 
    // Store config for access in tests
    this.config = {
      ...minioConfig,
      bucketName: this.validateBucketName(config.bucketName || 'oa-drive-storage'),
      cacheMaxSize: config.cacheMaxSize || 100
    };
 
    // MinIO client
    this.minioClient = this.client;
 
    // Cache configuration
    this.cacheEnabled = config.cacheEnabled !== false;
    this.cache = new Map();
    this.contentCache = new Map();
    this.maxCacheSize = config.maxCacheSize || 100; // Max items in cache
 
    // Track initialization
    this.initialized = false;
 
    this.logger.info('StorageConnector initialized', {
      endpoint: minioConfig.endPoint,
      port: minioConfig.port,
      defaultBucket: this.defaultBucket
    });
  }
 
  /**
   * Initialize connector and ensure bucket exists
   */
  async initialize() {
    try {
      // Check if default bucket exists
      const bucketExists = await this.client.bucketExists(this.defaultBucket);
 
      if (!bucketExists) {
        // Create bucket with versioning
        await this.client.makeBucket(this.defaultBucket, 'us-east-1');
        this.logger.info(`Bucket ${this.defaultBucket} created`);
 
        // Set bucket policy for read access
        const policy = {
          Version: '2012-10-17',
          Statement: [
            {
              Effect: 'Allow',
              Principal: { AWS: ['*'] },
              Action: ['s3:GetObject'],
              Resource: [`arn:aws:s3:::${this.defaultBucket}/*`]
            }
          ]
        };
 
        await this.client.setBucketPolicy(
          this.defaultBucket,
          JSON.stringify(policy)
        );
      }
 
      this.logger.info('StorageConnector ready');
      this.initialized = true;
      return true;
    } catch (error) {
      this.logger.error('Failed to initialize StorageConnector', error);
      throw error;
    }
  }
 
  /**
   * Generate SHA256 fingerprint for content
   */
  generateFingerprint(content) {
    // Handle undefined and null
    if (content === undefined || content === null) {
      content = String(content);
    } else if (typeof content === 'symbol') {
      content = content.toString();
    } else if (typeof content !== 'string' && !Buffer.isBuffer(content)) {
      // Handle circular references
      try {
        content = JSON.stringify(content);
      } catch (err) {
        // If circular reference, use a deterministic string representation
        content = '[Circular Reference]';
      }
    }
 
    return crypto
      .createHash('sha256')
      .update(content)
      .digest('hex');
  }
 
  /**
   * Upload content with automatic fingerprinting
   * Returns the fingerprint and storage path
   */
  async uploadWithFingerprint(bucket, content, pathPrefix = '') {
    try {
      // Ensure bucket is provided
      bucket = bucket || this.defaultBucket;
 
      // Convert content to Buffer if needed
      let buffer;
      if (Buffer.isBuffer(content)) {
        buffer = content;
      } else if (typeof content === 'object') {
        buffer = Buffer.from(JSON.stringify(content));
      } else {
        buffer = Buffer.from(content);
      }
 
      // Generate fingerprint
      const fingerprint = this.generateFingerprint(buffer);
 
      // Build path with fingerprint
      const path = pathPrefix
        ? `${pathPrefix}/${fingerprint}.json`
        : `${fingerprint}.json`;
 
      // Check if object already exists (immutable)
      try {
        await this.client.statObject(bucket, path);
        this.logger.debug(`Object already exists: ${bucket}/${path}`);
 
        return {
          fingerprint,
          bucket,
          path,
          url: this.getPublicUrl(bucket, path),
          existed: true
        };
      } catch (err) {
        // Object doesn't exist, proceed with upload
      }
 
      // Upload to MinIO
      await this.client.putObject(
        bucket,
        path,
        buffer,
        buffer.length,
        {
          'Content-Type': 'application/json',
          'x-amz-meta-fingerprint': fingerprint,
          'x-amz-meta-uploaded-at': new Date().toISOString()
        }
      );
 
      this.logger.info(`Uploaded content to ${bucket}/${path}`, { fingerprint });
 
      return {
        fingerprint,
        bucket,
        path,
        url: this.getPublicUrl(bucket, path),
        existed: false
      };
 
    } catch (error) {
      this.logger.error('Upload failed', error);
      throw error;
    }
  }
 
  /**
   * Download content and verify fingerprint
   */
  async downloadWithVerification(bucket, path, expectedFingerprint) {
    try {
      bucket = bucket || this.defaultBucket;
 
      // Check cache first
      const cacheKey = `${bucket}/${path}/${expectedFingerprint}`;
      if (this.cacheEnabled && this.contentCache.has(cacheKey)) {
        this.logger.debug(`Cache hit for ${cacheKey}`);
        return this.contentCache.get(cacheKey);
      }
 
      // Download from MinIO
      const stream = await this.client.getObject(bucket, path);
 
      // Collect stream data
      const chunks = [];
      for await (const chunk of stream) {
        chunks.push(chunk);
      }
      const buffer = Buffer.concat(chunks);
 
      // Verify fingerprint if provided
      if (expectedFingerprint) {
        const actualFingerprint = this.generateFingerprint(buffer);
 
        if (actualFingerprint !== expectedFingerprint) {
          throw new Error(
            `Fingerprint mismatch! Expected: ${expectedFingerprint}, Got: ${actualFingerprint}`
          );
        }
 
        this.logger.debug(`Fingerprint verified for ${bucket}/${path}`);
      }
 
      // Convert to string
      const content = buffer.toString('utf8');
 
      // Update cache
      if (this.cacheEnabled && expectedFingerprint) {
        this.updateCache(cacheKey, content);
      }
 
      return content;
 
    } catch (error) {
      this.logger.error(`Download failed for ${bucket}/${path}`, error);
      throw error;
    }
  }
 
  /**
   * Get pre-signed URL for direct access
   */
  async getPresignedUrl(bucket, path, expiry = 3600) {
    try {
      bucket = bucket || this.defaultBucket;
 
      const url = await this.client.presignedGetObject(
        bucket,
        path,
        expiry
      );
 
      this.logger.debug(`Generated presigned URL for ${bucket}/${path}`);
      return url;
 
    } catch (error) {
      this.logger.error('Failed to generate presigned URL', error);
      throw error;
    }
  }
 
  /**
   * List objects with fingerprint metadata
   */
  async listWithFingerprints(bucket, prefix = '') {
    try {
      bucket = bucket || this.defaultBucket;
 
      const objects = [];
      const stream = this.client.listObjectsV2(bucket, prefix, true);
 
      for await (const obj of stream) {
        // Get metadata for each object
        const stat = await this.client.statObject(bucket, obj.name);
 
        objects.push({
          name: obj.name,
          size: obj.size,
          lastModified: obj.lastModified,
          fingerprint: stat.metaData['x-amz-meta-fingerprint'],
          uploadedAt: stat.metaData['x-amz-meta-uploaded-at']
        });
      }
 
      return objects;
 
    } catch (error) {
      this.logger.error('Failed to list objects', error);
      throw error;
    }
  }
 
  /**
   * Delete object (use with caution - breaks immutability)
   */
  async deleteObject(bucket, path) {
    try {
      bucket = bucket || this.defaultBucket;
 
      await this.client.removeObject(bucket, path);
      this.logger.warn(`Deleted object: ${bucket}/${path}`);
 
      // Clear from cache
      const cacheKeys = Array.from(this.contentCache.keys())
        .filter(key => key.startsWith(`${bucket}/${path}/`));
 
      cacheKeys.forEach(key => this.contentCache.delete(key));
 
      return true;
 
    } catch (error) {
      this.logger.error(`Failed to delete ${bucket}/${path}`, error);
      throw error;
    }
  }
 
  /**
   * Get public URL for an object
   */
  getPublicUrl(bucket, path) {
    const protocol = this.client.useSSL ? 'https' : 'http';
    const port = this.client.port === 80 || this.client.port === 443
      ? ''
      : `:${this.client.port}`;
 
    return `${protocol}://${this.client.host}${port}/${bucket}/${path}`;
  }
 
  /**
   * Update cache with LRU eviction
   */
  updateCache(key, value) {
    // Remove oldest entry if cache is full
    if (this.contentCache.size >= this.maxCacheSize) {
      const firstKey = this.contentCache.keys().next().value;
      this.contentCache.delete(firstKey);
    }
 
    // Add new entry
    this.contentCache.set(key, value);
  }
 
 
  /**
   * Create bucket if not exists
   */
  async ensureBucket(bucketName) {
    try {
      const exists = await this.client.bucketExists(bucketName);
 
      if (!exists) {
        await this.client.makeBucket(bucketName, 'us-east-1');
        this.logger.info(`Bucket ${bucketName} created`);
      }
 
      return true;
    } catch (error) {
      this.logger.error(`Failed to ensure bucket ${bucketName}`, error);
      throw error;
    }
  }
 
  /**
   * Validate bucket name according to S3 standards
   */
  validateBucketName(name) {
    // S3 bucket naming rules
    const validName = /^[a-z0-9][a-z0-9\-\.]*[a-z0-9]$/;
    const minLength = 3;
    const maxLength = 63;
 
    if (!name ||
        name.length < minLength ||
        name.length > maxLength ||
        !validName.test(name)) {
      return 'oa-drive-storage'; // Return default if invalid
    }
 
    return name;
  }
 
  /**
   * Get object name with fingerprint
   */
  getObjectNameWithFingerprint(originalName, fingerprint) {
    const parts = originalName.split('.');
    const extension = parts.length > 1 ? '.' + parts.pop() : '';
    const baseName = parts.join('.');
    return `${baseName}-${fingerprint}${extension}`;
  }
 
  /**
   * Extract fingerprint from object name
   */
  extractFingerprintFromName(objectName) {
    // Match pattern: name-<64-char-hex>.extension
    const match = objectName.match(/-([a-f0-9]{64})(\.[^.]+)?$/);
    return match ? match[1] : null;
  }
 
  /**
   * Add item to cache with size limit
   */
  addToCache(key, value) {
    // Remove oldest if at max size
    if (this.cache.size >= this.config.cacheMaxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    this.cache.set(key, value);
  }
 
  /**
   * Get item from cache
   */
  getFromCache(key) {
    return this.cache.get(key);
  }
 
  /**
   * Clear all caches
   */
  clearCache() {
    this.cache.clear();
    this.contentCache.clear();
  }
 
  /**
   * Get internal URL for service-to-service communication
   * Returns abstract internal:// URL that will be resolved by adapter
   */
  getInternalUrl(bucket, path) {
    return `internal://storage/${bucket}/${path}`;
  }
 
  /**
   * Get public URL for an object
   * @deprecated Use getInternalUrl() for service-to-service communication
   */
  getPublicUrl(bucket, path) {
    // Pro zpětnou kompatibilitu, vrací internal URL
    return this.getInternalUrl(bucket, path);
  }
 
  /**
   * Get presigned URL for temporary access
   */
  async getPresignedUrl(bucket, objectName, expiry = 86400) {
    try {
      return await this.client.presignedGetUrl('GET', bucket, objectName, expiry);
    } catch (error) {
      this.logger.error('Failed to generate presigned URL', error);
      throw error;
    }
  }
 
  /**
   * List objects with fingerprints
   */
  async listObjectsWithFingerprints(bucket, prefix = '') {
    try {
      bucket = bucket || this.defaultBucket;
      const objects = [];
 
      return new Promise((resolve, reject) => {
        const stream = this.client.listObjectsV2(bucket, prefix, true);
 
        stream.on('data', obj => {
          objects.push({
            name: obj.name,
            size: obj.size,
            lastModified: obj.lastModified,
            fingerprint: this.extractFingerprintFromName(obj.name)
          });
        });
 
        stream.on('error', reject);
        stream.on('end', () => resolve(objects));
      });
    } catch (error) {
      this.logger.error('Failed to list objects', error);
      throw error;
    }
  }
}
 
module.exports = StorageConnector;