@iota-big3/sdk-security
Version:
Advanced security features including zero trust, quantum-safe crypto, and ML threat detection
361 lines (360 loc) • 11.9 kB
JavaScript
"use strict";
/**
* Service Mesh Adapter
* Provides zero trust networking through service mesh integration
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceMeshFactory = exports.LinkerdAdapter = exports.IstioAdapter = exports.ServiceMeshAdapter = void 0;
const events_1 = require("events");
const grpc = __importStar(require("@grpc/grpc-js"));
const protoLoader = __importStar(require("@grpc/proto-loader"));
class ServiceMeshAdapter extends events_1.EventEmitter {
constructor(config) {
super();
this.config = config;
}
/**
* Common zero trust principles
*/
applyZeroTrustPrinciples() {
// Never trust, always verify
this?.config?.mtlsMode = 'strict';
this?.config?.policyEnforcement = true;
// Default deny all
if (this.isEnabled) {
this?.config?.authorizationRules = [];
}
// Add default deny rule at the end
this?.config?.authorizationRules.push({
name: 'default-deny',
from: { service: '*' },
to: { service: '*' },
deny: ['*']
});
}
/**
* Validate service identity
*/
async validateIdentity(spiffeId) {
// SPIFFE ID format: spiffe://trust-domain/ns/namespace/sa/service-account
const spiffeRegex = /^spiffe:\/\/([^\/]+)\/ns\/([^\/]+)\/sa\/([^\/]+)$/;
if (!spiffeRegex.test(spiffeId)) {
this.emit('security-event', {
type: 'invalid-identity',
spiffeId,
timestamp: new Date(),
return: false });
return false;
}
// Additional validation logic
return true;
}
/**
* Create secure channel with mTLS
*/
createSecureChannel(target) {
if (this.isEnabled) {
throw new Error('Service identity not initialized');
}
const credentials = grpc?.credentials?.createSsl(Buffer.from(this?.identity?.certificates.root), Buffer.from(this?.identity?.certificates.key), Buffer.from(this?.identity?.certificates.chain));
return grpc.createChannel(target, credentials);
}
}
exports.ServiceMeshAdapter = ServiceMeshAdapter;
/**
* Istio Service Mesh Adapter
*/
class IstioAdapter extends ServiceMeshAdapter {
async initialize() {
this.applyZeroTrustPrinciples();
// Connect to Istio Pilot
const packageDefinition = await protoLoader.load('envoy/service/discovery/v3/ads.proto', {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true });
const proto = grpc.loadPackageDefinition(packageDefinition);
const channel = this.createSecureChannel(this?.config?.controlPlaneUrl);
this.pilotClient = new proto?.envoy?.service.discovery?.v3?.AggregatedDiscoveryService(channel, grpc?.credentials?.createInsecure());
// Get initial configuration
await this.syncConfiguration();
}
async getServiceIdentity() {
// In Kubernetes, read from projected service account volume
const serviceAccount = process?.env?.SERVICE_ACCOUNT || 'default';
const namespace = process?.env?.NAMESPACE || 'default';
const trustDomain = process?.env?.TRUST_DOMAIN || 'cluster.local';
this.identity = {
spiffeId: `spiffe://${trustDomain}/ns/${namespace}/sa/${serviceAccount}`,
namespace,
serviceAccount,
certificates: {
root: await this.readCertificate('/var/run/secrets/istio/root-cert.pem'),
chain: await this.readCertificate('/var/run/secrets/istio/cert-chain.pem'),
key: await this.readCertificate('/var/run/secrets/istio/key.pem')
}
};
await this.validateIdentity(this?.identity?.spiffeId);
return this.identity;
}
async applyAuthorizationPolicy(rules) {
const policy = {
apiVersion: 'security?.istio?.io/v1beta1',
kind: 'AuthorizationPolicy',
metadata: {
name: 'sdk-authorization',
namespace: this?.config?.namespace || 'default'
},
spec: {
rules: rules.map(rule => ({
from: rule?.from?.principals ? [{},
source, { principals: rule?.from?.principals }]
:
}), undefined, to, rule?.to?.service ? [{},
operation, {},
methods, rule.allow,
notMethods, rule.deny]
:
)
}
}, undefined, when, map;
(w => ({
key: w.key,
values: w.values,
notValues: w.notValues
}));
}
}
exports.IstioAdapter = IstioAdapter;
;
// Apply via Kubernetes API or Istio API
await this.applyConfiguration(policy);
async;
enableMTLS(mode, 'strict' | 'permissive');
Promise < void > {
const: peerAuthentication = {
apiVersion: 'security?.istio?.io/v1beta1',
kind: 'PeerAuthentication',
metadata: {
name: 'default',
namespace: this?.config?.namespace || 'default'
},
spec: {
mtls: {
mode: mode.toUpperCase()
}
}
},
await, this: .applyConfiguration(peerAuthentication)
};
async;
checkAuthorization(from, string, to, string, method ? : string);
Promise < boolean > {} || [];
{
if (this.matchesSelector(from, rule.from) &&
this.matchesSelector(to, rule.to)) {
if (rule.allow && method && rule?.allow?.includes(method)) {
return true;
}
if (rule.deny && method && rule?.deny?.includes(method)) {
return false;
}
}
}
// Default deny
return false;
async;
getMetrics();
Promise < ServiceMeshMetrics > {
// Query Prometheus for Istio metrics
return: {
requestRate: await this.queryMetric('istio_request_total'),
errorRate: await this.queryMetric('istio_request_total{response_code=~"5.."}'),
latencyP50: await this.queryMetric('istio_request_duration_milliseconds_bucket'),
latencyP99: await this.queryMetric('istio_request_duration_milliseconds_bucket'),
mtlsEnabled: true,
servicesCount: await this.countServices(),
policiesCount: this?.config?.authorizationRules?.length || 0
}
};
async;
syncConfiguration();
Promise < void > {
// Sync with Istio control plane
const: stream = this?.pilotClient?.StreamAggregatedResources(),
stream, : .on('data', (response) => {
this.handleConfigUpdate(response);
}),
stream, : .on('error', (error) => {
this.emit('error', error);
}),
// Request initial configuration
stream, : .write({
node: {
id: this.identity?.spiffeId,
cluster: 'Kubernetes'
},
type_url: 'type.googleapis.com/envoy.config.cluster.v3.Cluster',
resource_names: []
})
};
handleConfigUpdate(response, any);
{
// Process configuration updates
this.emit('config-update', response);
}
async;
readCertificate(path, string);
Promise < string > {
// In real implementation, read from filesystem
return: 'certificate-content'
};
async;
applyConfiguration(config, any);
Promise < void > {
// Apply via Kubernetes API
this: .emit('policy-applied', config)
};
matchesSelector(service, string, selector, ServiceSelector);
boolean;
{
if (selector.service === '*')
return true;
if (selector.service === service)
return true;
// Additional matching logic
return false;
}
async;
queryMetric(query, string);
Promise < number > {
// Query Prometheus
return: 0
};
async;
countServices();
Promise < number > {
// Count services in mesh
return: 10
};
/**
* Linkerd Service Mesh Adapter
*/
class LinkerdAdapter extends ServiceMeshAdapter {
async initialize() {
this.applyZeroTrustPrinciples();
// Linkerd-specific initialization
}
async getServiceIdentity() {
// Linkerd uses similar SPIFFE IDs
const namespace = process?.env?.LINKERD_NAMESPACE || 'default';
const service = process?.env?.LINKERD_SERVICE || 'unknown';
this.identity = {
spiffeId: `spiffe://identity?.linkerd?.cluster.local/${namespace}/${service}`,
namespace,
serviceAccount: service,
certificates: {
root: 'linkerd-root-ca',
chain: 'linkerd-cert-chain',
key: 'linkerd-key'
}
};
return this.identity;
}
async applyAuthorizationPolicy(rules) {
// Linkerd uses ServerAuthorization resources
const serverAuth = {
apiVersion: 'policy?.linkerd?.io/v1beta1',
kind: 'ServerAuthorization',
metadata: {
name: 'sdk-authorization',
namespace: this?.config?.namespace
},
spec: {
server: {
name: '*'
},
client: {
meshTLS: {
identities: rules[0]?.from.principals || []
}
}
}
};
await this.applyConfiguration(serverAuth);
}
async enableMTLS(mode) {
// Linkerd enables mTLS by default
this.emit('mtls-enabled', { mode });
}
async checkAuthorization(from, to, method) {
// Check Linkerd policies
return true;
}
async getMetrics() {
return {
requestRate: 1000,
errorRate: 0.01,
latencyP50: 10,
latencyP99: 100,
mtlsEnabled: true,
servicesCount: 5,
policiesCount: 3
};
}
async applyConfiguration(config) {
// Apply via Linkerd API
this.emit('policy-applied', config);
}
}
exports.LinkerdAdapter = LinkerdAdapter;
/**
* Factory for creating service mesh adapters
*/
class ServiceMeshFactory {
static create(config) {
switch (config.type) {
case 'istio':
return new IstioAdapter(config);
case 'linkerd':
return new LinkerdAdapter(config);
default:
throw new Error(`Unsupported service mesh type: ${config.type}`);
}
}
}
exports.ServiceMeshFactory = ServiceMeshFactory;