npm package: @iota-big3/sdk-security
Description: Advanced security features including zero trust, quantum-safe crypto, and ML threat detection
Author: iota-big3 SDK Team
Latest version: 2.0.0

# @iota-big3/sdk-security

Enterprise-grade security and compliance features for IOTA SDK, including Zero Trust Architecture, Advanced IAM, Compliance Automation, Security Scanning, and Blockchain-based Audit Trail.

## Features

### 🔐 Zero Trust Architecture

- Service mesh integration (Istio/Linkerd)
- Mutual TLS (mTLS) between services
- Service-to-service authentication
- Policy-based access control
- Automatic certificate rotation

### 👤 Advanced IAM

- **RBAC** (Role-Based Access Control)
- **ABAC** (Attribute-Based Access Control)
- **Policy Engine** with OPA integration
- **Multi-Factor Authentication** (MFA)
- **Single Sign-On** (SSO) with SAML/OAuth/OIDC

### 📋 Compliance Automation

- **SOC2 Type II** automated assessments
- **HIPAA** compliance validation
- **GDPR** data protection checks
- **PCI-DSS** payment security
- **ISO 27001** and **NIST** frameworks
- Automated evidence collection
- PDF/JSON compliance reports

### 🔍 Security Scanning

- **SAST** (Static Application Security Testing) with Semgrep
- **DAST** (Dynamic Application Security Testing)
- **SCA** (Software Composition Analysis) with Snyk
- **Container scanning** with Trivy
- **IaC scanning** with Checkov
- **Secret detection** with Gitleaks

### 📝 Blockchain Audit Trail

- Immutable audit logs with Hyperledger Fabric
- Real-time audit streaming
- Encrypted sensitive data
- Compliance evidence collection
- Forensic analysis tools
- Multi-format export (JSON/CSV/PDF)

## Installation

```bash
npm install @iota-big3/sdk-security
```

## Quick Start

```typescript
import { SecurityManager, SecurityConfig } from '@iota-big3/sdk-security';

// Configure security
const config: SecurityConfig = {
  zeroTrust: {
    enabled: true,
    serviceMesh: 'istio',
    mtlsMode: 'strict',
    certificateRotationDays: 30
  },
  iam: {
    providers: [
      { type: 'oidc', name: 'auth0', config: {...}, enabled: true }
    ],
    sessionTimeout: 3600,
    mfaRequired: true,
    passwordPolicy: {
      minLength: 12,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: true,
      maxAge: 90,
      historyCount: 5
    },
    apiKeyRotationDays: 90
  },
  compliance: {
    frameworks: ['SOC2', 'HIPAA', 'GDPR'],
    autoAssessment: true,
    reportingSchedule: 'weekly',
    evidenceRetentionDays: 2555 // 7 years
  },
  scanning: {
    enabledScanners: ['SAST', 'SCA', 'Secret'],
    scheduledScans: true,
    scanOnCommit: true,
    severityThreshold: 'high'
  },
  audit: {
    enabled: true,
    blockchain: {
      type: 'hyperledger',
      networkUrl: 'grpc://localhost:7051',
      channelName: 'audit-channel'
    },
    retentionDays: 2555,
    realTimeStreaming: true,
    encryptionEnabled: true
  }
};

// Initialize security manager
const security = new SecurityManager(config);

// Check access
const decision = await security.checkAccess({
  subject: { id: 'user123', username: 'john.doe' },
  resource: '/api/grades',
  action: 'read',
  context: { ip: '192.168.1.1' }
});

if (decision.allowed) {
  // Access granted
} else {
  // Access denied: decision.reason
}
```

## Usage Examples

### Zero Trust Service Registration

```typescript
import { ServiceMeshIntegration } from "@iota-big3/sdk-security";

const serviceMesh = new ServiceMeshIntegration(config, logger);

// Register service
const identity = await serviceMesh.registerService("grades-api", "education");

// Apply Zero Trust policy
await serviceMesh.applyPolicy({
  id: "grades-read-policy",
  name: "Grades Read Policy",
  effect: "allow",
  rules: [
    {
      resource: "/api/grades/*",
      actions: ["GET"],
      subjects: ["teachers", "students"],
      conditions: [
        {
          type: "time",
          operator: "greater_than",
          value: "08:00",
        },
      ],
    },
  ],
  priority: 100,
  enabled: true,
});
```

### RBAC/ABAC Setup

```typescript
import { AccessControl } from "@iota-big3/sdk-security";

const accessControl = new AccessControl(rbacConfig, abacConfig, logger);

// Create role
await accessControl.rbac.createRole({
  id: "teacher",
  name: "Teacher",
  permissions: [
    {
      id: "read-grades",
      resource: "/api/grades/*",
      action: "read",
      effect: "allow",
    },
    {
      id: "write-grades",
      resource: "/api/grades/*",
      action: "write",
      effect: "allow",
    },
  ],
});

// Assign role
await accessControl.rbac.assignRole("user123", "teacher");

// Register ABAC attribute provider
accessControl.abac.registerAttributeProvider("time", async (request) => ({
  currentHour: new Date().getHours(),
  dayOfWeek: new Date().getDay(),
}));

// Load ABAC policy
await accessControl.abac.loadPolicy(
  "working-hours",
  `
  package schoolos.authz

  default allow = false

  allow {
    input.attributes.currentHour >= 8
    input.attributes.currentHour <= 17
    input.attributes.dayOfWeek >= 1
    input.attributes.dayOfWeek <= 5
  }
`
);
```

### Compliance Assessment

```typescript
import { ComplianceAutomation } from "@iota-big3/sdk-security";

const compliance = new ComplianceAutomation(config, logger);

// Add evidence
await compliance.addEvidence({
  id: "ev-001",
  type: "security_policy",
  title: "Information Security Policy v2.0",
  description: "Approved security policy document",
  url: "https://docs.example.com/security-policy.pdf",
  collectedAt: new Date(),
  collectedBy: "security-team",
});

// Run assessment
const reports = await compliance.runAssessment({
  security: {
    mfaEnabled: true,
    rbacEnabled: true,
    sessionTimeout: 1800,
  },
  observability: {
    loggingEnabled: true,
    metricsEnabled: true,
    alertingEnabled: true,
  },
  infrastructure: {
    disasterRecovery: true,
    backupsEnabled: true,
  },
  metrics: {
    uptime: 99.95,
  },
});

// Get SOC2 report
const soc2Report = reports.get("SOC2");
console.log(`Compliance Score: ${soc2Report.summary.complianceScore}%`);
```

### Security Scanning

```typescript
import { SecurityScanner } from "@iota-big3/sdk-security";

const scanner = new SecurityScanner(config, logger);

// Start SAST scan
const scanId = await scanner.startScan("SAST", "./src", "application");

// Wait for completion
scanner.on("scan:completed", (scan) => {
  console.log(`Found ${scan.summary.totalFindings} issues`);
  console.log(`Critical: ${scan.summary.criticalCount}`);
  console.log(`High: ${scan.summary.highCount}`);

  // Export results
  const sarif = scanner.exportResults(scan, "sarif");
});

// Run full scan
const results = await scanner.runFullScan("./");
```

### Blockchain Audit Trail

```typescript
import { BlockchainAuditTrail } from "@iota-big3/sdk-security";

const auditTrail = new BlockchainAuditTrail(config, logger);

// Log audit event
await auditTrail.logEvent({
  eventType: "data_access",
  actor: {
    type: "user",
    id: "user123",
    name: "John Doe",
    roles: ["teacher"],
  },
  resource: {
    type: "student_record",
    id: "student456",
    name: "Student Grade Record",
  },
  action: "read",
  outcome: "success",
  ipAddress: "192.168.1.100",
  details: {
    reason: "Viewing semester grades",
    browser: "Chrome/120.0",
  },
});

// Query audit logs
const events = await auditTrail.queryEvents({
  startDate: new Date("2024-01-01"),
  eventTypes: ["data_access", "data_modification"],
  actors: ["user123"],
  limit: 100,
});

// Verify event integrity
const isValid = await auditTrail.verifyEventIntegrity("event-id-123");

// Export audit trail
const csv = await auditTrail.exportAuditTrail(
  {
    startDate: new Date("2024-01-01"),
    endDate: new Date(),
  },
  "csv"
);
```

## Express Integration

```typescript
import express from "express";
import { SecurityManager, securityMiddleware } from "@iota-big3/sdk-security";

const app = express();
const security = new SecurityManager(config);

// Apply security middleware
app.use(securityMiddleware(security));

// Protected route
app.get("/api/sensitive-data", async (req, res) => {
  // Access already validated by middleware
  res.json({ data: "sensitive information" });
});

// Health endpoint
app.get("/health/security", async (req, res) => {
  const health = await security.healthCheck();
  res.json(health);
});
```

## SDK Integration

The Security SDK integrates seamlessly with other IOTA Big3 SDKs to provide comprehensive security across your application.

### With sdk-database

```typescript
import { SecurityManager } from "@iota-big3/sdk-security";
import { SDKDatabaseManager } from "@iota-big3/sdk-database";

const database = new SDKDatabaseManager({
  type: "postgresql",
  config: {
    host: "localhost",
    database: "schoolos",
    user: "admin",
    password: "secure",
  },
});

const security = new SecurityManager({
  config: securityConfig,
  database, // Enables persistent storage of roles, policies, and audit logs
});

// Security data is now persisted to database
await security.initialize();
```

### With sdk-events

```typescript
import { SecurityManager, AccessControl } from "@iota-big3/sdk-security";
import { EventBus } from "@iota-big3/sdk-events";

const eventBus = new EventBus();
const security = new SecurityManager({
  config: securityConfig,
  eventBus,
});

// Listen to security events
eventBus.on("security:auth.success", (event) => {
  console.log(`User ${event.userId} logged in at ${new Date(event.timestamp)}`);
});

eventBus.on("security:threat.detected", (event) => {
  // Send alert to security team
  alertSecurityTeam(event);
});

// Security SDK also listens to other SDK events
eventBus.emit("auth:user.created", { userId: "new-user-123" });
// Security SDK automatically creates default security settings for new user
```

### With sdk-observability

```typescript
import { SecurityManager } from "@iota-big3/sdk-security";
import { CentralizedLogger } from "@iota-big3/sdk-observability";

const logger = new CentralizedLogger({
  serviceName: "schoolos-security",
  environment: "production",
});

const security = new SecurityManager({
  config: securityConfig,
  logger, // All security operations are now logged
});

// Structured logging for security events
// Automatic correlation IDs for request tracing
// Performance metrics for security operations
```

### With sdk-performance

```typescript
import { SecurityManager, AccessControl } from "@iota-big3/sdk-security";
import { PerformanceManager } from "@iota-big3/sdk-performance";

const performance = new PerformanceManager({
  cache: {
    ttl: 300,
    maxSize: 10000,
  },
});

const accessControl = new AccessControl(rbacConfig, abacConfig, logger, {
  cache: performance.cache,
});

// Access control decisions are now cached for performance
// - Permission checks are cached for 5 minutes
// - Role assignments are cached
// - Security scan results are cached
```

### With sdk-core

```typescript
import { SecurityManager } from "@iota-big3/sdk-security";
import { SDK as CoreSDK } from "@iota-big3/sdk-core";

const core = new CoreSDK({
  appName: "SchoolOS",
  environment: "production",
});

// Set security configuration in core
core.config.set("security", {
  mfaRequired: true,
  sessionTimeout: 7200, // 2 hours
  passwordMinLength: 12,
});

const security = new SecurityManager({
  config: securityConfig,
  core, // Security uses centralized configuration
});

// Configuration changes are automatically propagated
core.config.set("security.mfaRequired", false);
// Security SDK automatically updates its configuration
```

### With sdk-gateway

```typescript
import { SecurityManager } from "@iota-big3/sdk-security";
import { UniversalAPIGateway } from "@iota-big3/sdk-gateway";

const gateway = new UniversalAPIGateway({
  port: 8080,
  routes: [],
});

const security = new SecurityManager({
  config: securityConfig,
  gateway,
});

await security.initialize();

// Security automatically registers:
// - Authentication middleware
// - Authorization middleware
// - Security endpoints (/security/health, /security/audit/query)
// - Rate limiting integration

// Start the gateway with security enabled
await gateway.start();
```

### Complete Integration Example

```typescript
import { SecurityManager, AccessControl } from "@iota-big3/sdk-security";
import { SDKDatabaseManager } from "@iota-big3/sdk-database";
import { EventBus } from "@iota-big3/sdk-events";
import { CentralizedLogger } from "@iota-big3/sdk-observability";
import { PerformanceManager } from "@iota-big3/sdk-performance";
import { SDK as CoreSDK } from "@iota-big3/sdk-core";
import { UniversalAPIGateway } from "@iota-big3/sdk-gateway";

// Initialize all SDKs
const database = new SDKDatabaseManager({
  /* ... */
});
const eventBus = new EventBus();
const logger = new CentralizedLogger({
  /* ... */
});
const performance = new PerformanceManager({
  /* ... */
});
const core = new CoreSDK({
  /* ... */
});
const gateway = new UniversalAPIGateway({
  /* ... */
});

// Create fully integrated security manager
const security = new SecurityManager({
  config: {
    // Your security configuration
  },
  database, // Persistent storage
  eventBus, // Event-driven architecture
  logger, // Structured logging
  cache: performance.cache, // Performance optimization
  core, // Centralized configuration
  gateway, // API integration
});

// Initialize and start
await security.initialize();

// All security features now benefit from:
// - Persistent storage of security data
// - Real-time event notifications
// - Comprehensive logging and monitoring
// - High-performance caching
// - Centralized configuration management
// - Automatic API endpoint registration
```

### Event Integration Patterns

The Security SDK emits and listens to various events:

#### Emitted Events

```typescript
// Authentication events
"security:auth.success";
"security:auth.failed";
"security:session.created";
"security:session.expired";

// Authorization events
"security:permission.granted";
"security:permission.denied";
"security:role.assigned";
"security:role.revoked";

// Security scanning events
"security:scan.started";
"security:scan.completed";
"security:vulnerability.found";

// Threat detection events
"security:threat.detected";
"security:threat.mitigated";
"security:anomaly.detected";

// Compliance events
"security:compliance.violation";
"security:compliance.assessed";
"security:audit.logged";
```

#### Listened Events

```typescript
// User lifecycle events from auth SDK
eventBus.on("auth:user.created", async (event) => {
  // Create default security roles and settings
});

eventBus.on("auth:user.deleted", async (event) => {
  // Clean up user's security data
});

// Configuration changes from core SDK
eventBus.on("config:changed", async (event) => {
  // Update security configuration if relevant
});
```

## CLI Commands

```bash
# Run security scan
npx @iota-big3/sdk-security scan --type=SAST --target=./src

# Run compliance assessment
npx @iota-big3/sdk-security compliance --framework=SOC2

# Query audit logs
npx @iota-big3/sdk-security audit query --start=2024-01-01 --type=data_access

# Export compliance report
npx @iota-big3/sdk-security compliance export --format=pdf --output=./soc2-report.pdf
```

## Configuration

### Environment Variables

```bash
# Service Mesh
SERVICE_MESH_URL=localhost:8080
NAMESPACE=production
TRUST_DOMAIN=cluster.local

# Compliance
COMPLIANCE_WEBHOOK=https://slack.webhook.url

# Blockchain
FABRIC_NETWORK_CONFIG=/path/to/connection-profile.json
FABRIC_WALLET_PATH=/path/to/wallet
```

### Advanced Configuration

```typescript
const advancedConfig: SecurityConfig = {
  zeroTrust: {
    enabled: true,
    serviceMesh: "linkerd",
    mtlsMode: "strict",
    certificateRotationDays: 7,
    // Custom service mesh config
    customConfig: {
      proxyImage: "linkerd/proxy:stable-2.14.1",
      controllerImage: "linkerd/controller:stable-2.14.1",
    },
  },
  iam: {
    providers: [
      {
        type: "saml",
        name: "okta",
        config: {
          entryPoint: "https://company.okta.com/app/sso/saml",
          issuer: "schoolos",
          cert: "MIIDpDCCAoygAwIBAgIGAV2...",
        },
        enabled: true,
      },
      {
        type: "oauth2",
        name: "google",
        config: {
          clientId: "xxx.apps.googleusercontent.com",
          clientSecret: process.env.GOOGLE_SECRET,
          callbackUrl: "https://api.example.com/auth/google/callback",
        },
        enabled: true,
      },
    ],
    // ... other IAM config
  },
  // ... other config
};
```

## Performance

- **Authentication**: <50ms latency
- **Policy Evaluation**: <10ms per decision
- **Audit Logging**: <5ms overhead
- **Security Scanning**: <2 minutes for full scan
- **Compliance Check**: <30 seconds

## Best Practices

1. **Defense in Depth**: Use multiple security layers
2. **Least Privilege**: Grant minimum required permissions
3. **Audit Everything**: Log all security-relevant events
4. **Automate Compliance**: Run regular assessments
5. **Scan Early**: Integrate security scanning in CI/CD
6. **Rotate Secrets**: Use automatic rotation for keys/certs
7. **Monitor Continuously**: Set up real-time alerts

## Troubleshooting

### Service Mesh Connection Issues

```typescript
// Check service mesh status
const metrics = serviceMesh.getMetrics();
console.log("Service Identity:", metrics.serviceIdentity);
console.log("mTLS Mode:", metrics.mtlsMode);
```

### Compliance Assessment Failures

```typescript
// Check evidence
const evidence = await compliance.exportComplianceData();
console.log("Evidence collected:", evidence.evidence);

// Manually add missing evidence
await compliance.addEvidence({
  type: "security_policy",
  // ... evidence details
});
```

### Blockchain Audit Issues

```typescript
// Check blockchain connection
const auditMetrics = auditTrail.getMetrics();
console.log("Blockchain connected:", auditMetrics.blockchainConnected);
console.log("Buffer size:", auditMetrics.bufferSize);

// Force flush
await auditTrail.flushBuffer();
```

## Contributing

See [CONTRIBUTING.md](../../CONTRIBUTING.md) for development setup and guidelines.

## License

MIT