Kivera Integration

7.1 Integration Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                         KIVERA INTEGRATION ARCHITECTURE                      │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                    Cloudflare Workers (Control Plane)                │    │
│  │                                                                      │    │
│  │   Provisioning       Price Collection       Health Monitoring        │    │
│  │   Workflow           Workers                Workers                  │    │
│  └────────┬─────────────────┬─────────────────────┬────────────────────┘    │
│           │                 │                     │                         │
│           │    All cloud API requests routed through Kivera                 │
│           │                 │                     │                         │
│           ▼                 ▼                     ▼                         │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                         KIVERA PROXY CLUSTER                          │   │
│  │                                                                       │   │
│  │  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐       │   │
│  │  │ Identity:       │  │ Policy:         │  │ Logging:        │       │   │
│  │  │ compute-arb-    │  │ Spot-Instance-  │  │ All API calls   │       │   │
│  │  │ platform        │  │ Controls        │  │ to SIEM         │       │   │
│  │  └─────────────────┘  └─────────────────┘  └─────────────────┘       │   │
│  │                                                                       │   │
│  │  Profiles Applied:                                                    │   │
│  │  - SpotInstanceControls (enforce instance types, regions)            │   │
│  │  - DataBoundary (enforce approved cloud accounts)                    │   │
│  │  - CostControls (enforce max spot prices)                            │   │
│  │  - TaggingRequirements (enforce required tags)                       │   │
│  │                                                                       │   │
│  └────────────────────────────────────────────────────────────────────── │   │
│                                    │                                         │
│           ┌────────────────────────┼────────────────────────┐               │
│           ▼                        ▼                        ▼               │
│  ┌─────────────────┐      ┌─────────────────┐      ┌─────────────────┐     │
│  │      AWS        │      │     Azure       │      │      GCP        │     │
│  │   EC2 API       │      │   Compute API   │      │   Compute API   │     │
│  └─────────────────┘      └─────────────────┘      └─────────────────┘     │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

7.2 Kivera Policies for Spot Instance Controls

# policies/spot-instance-controls.rego

package kivera.policies.spot_instance

import future.keywords.if
import future.keywords.in

# Approved instance types for spot workloads
approved_instance_types := {
  # Compute optimized
  "c5.large", "c5.xlarge", "c5.2xlarge", "c5.4xlarge",
  "c6i.large", "c6i.xlarge", "c6i.2xlarge", "c6i.4xlarge",
  # Memory optimized
  "r5.large", "r5.xlarge", "r5.2xlarge", "r5.4xlarge",
  # GPU instances
  "g4dn.xlarge", "g4dn.2xlarge", "g4dn.4xlarge",
  "p3.2xlarge", "p3.8xlarge",
}

# Approved regions
approved_regions := {
  "us-east-1", "us-east-2", "us-west-2",
  "eu-west-1", "eu-central-1",
  "ap-southeast-1", "ap-southeast-2",
}

# Maximum spot price (USD per hour)
max_spot_prices := {
  "c5.large": 0.10,
  "c5.xlarge": 0.20,
  "c5.2xlarge": 0.40,
  "g4dn.xlarge": 0.60,
  "p3.2xlarge": 3.50,
}

# Rule: Only allow approved instance types
valid if {
  input.Action == "RunInstances"
  input.Body.InstanceType in approved_instance_types
}

# Rule: Only allow approved regions
valid if {
  input.Action == "RunInstances"
  input.ProviderMetadata.Region in approved_regions
}

# Rule: Enforce spot instance configuration
valid if {
  input.Action == "RunInstances"
  input.Body.InstanceMarketOptions.MarketType == "spot"
}

# Rule: Enforce maximum spot price
valid if {
  input.Action == "RunInstances"
  instance_type := input.Body.InstanceType
  max_price := max_spot_prices[instance_type]
  requested_price := to_number(input.Body.InstanceMarketOptions.SpotOptions.MaxPrice)
  requested_price <= max_price
}

# Rule: Require mandatory tags
valid if {
  input.Action == "RunInstances"
  tags := input.Body.TagSpecifications[_].Tags
  has_tag(tags, "workload-id")
  has_tag(tags, "customer-id")
  has_tag(tags, "managed-by")
}

has_tag(tags, key) if {
  some tag in tags
  tag.Key == key
  tag.Value != ""
}

# Custom error response
block_response := {
  "ruleId": data.ctx.rule.id,
  "error": "SPOT_INSTANCE_POLICY_VIOLATION",
  "description": reason,
} if {
  not valid
  reason := build_reason
}

build_reason := "Instance type not approved" if {
  not input.Body.InstanceType in approved_instance_types
}

build_reason := "Region not approved" if {
  not input.ProviderMetadata.Region in approved_regions
}

build_reason := "Spot price exceeds maximum allowed" if {
  instance_type := input.Body.InstanceType
  max_price := max_spot_prices[instance_type]
  requested_price := to_number(input.Body.InstanceMarketOptions.SpotOptions.MaxPrice)
  requested_price > max_price
}

7.3 Kivera Data Boundary Policy

# policies/data-boundary.rego

package kivera.policies.data_boundary

import future.keywords.if
import future.keywords.in

# Approved cloud accounts per customer
# In production, this would be fetched from KV store
approved_accounts := {
  "customer-acme-corp": {
    "aws": ["111111111111", "222222222222"],
    "azure": ["sub-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
    "gcp": ["acme-prod-project", "acme-dev-project"],
  },
}

# Get customer from request context (passed via identity)
customer_id := data.ctx.identity.metadata.customer_id

# AWS data boundary
valid if {
  input.Provider == "AWS"
  customer_accounts := approved_accounts[customer_id].aws
  input.ProviderMetadata.Account in customer_accounts
}

# Azure data boundary
valid if {
  input.Provider == "Azure"
  customer_subs := approved_accounts[customer_id].azure
  input.ProviderMetadata.SubscriptionId in customer_subs
}

# GCP data boundary
valid if {
  input.Provider == "GCP"
  customer_projects := approved_accounts[customer_id].gcp
  input.ProviderMetadata.ProjectId in customer_projects
}

block_response := {
  "error": "DATA_BOUNDARY_VIOLATION",
  "description": sprintf("Operation attempted outside approved cloud accounts for customer %s", [customer_id]),
} if not valid

7.4 Kivera Configuration via Konfig

# kivera-config/rules/spot-controls.yaml
apiVersion: kivera.io/v1
kind: Rule
metadata:
  name: spot-instance-controls
  labels:
    category: compute
    environment: production
spec:
  provider: AWS
  service: EC2
  actions:
    - RunInstances
    - RequestSpotInstances
  mode: enforce
  policy: |
    # Inline Rego policy or reference to external file
    ${file:policies/spot-instance-controls.rego}

---
# kivera-config/profiles/compute-arbitrage.yaml
apiVersion: kivera.io/v1
kind: Profile
metadata:
  name: compute-arbitrage-platform
spec:
  rules:
    - spot-instance-controls
    - data-boundary
    - cost-controls
    - tagging-requirements

---
# kivera-config/identities/platform.yaml
apiVersion: kivera.io/v1
kind: Identity
metadata:
  name: compute-arbitrage-platform
spec:
  type: basic-auth
  credentials:
    username: compute-arb-platform
    # Password managed via secrets
  profiles:
    - compute-arbitrage-platform
  metadata:
    platform: compute-arbitrage
    environment: production

7.5 Cloud Provisioner with Kivera Integration

// provisioners/src/base.ts
export abstract class CloudProvisioner {
  protected env: Env;
  protected kiveraProxy: string;
  
  constructor(env: Env) {
    this.env = env;
    this.kiveraProxy = env.KIVERA_PROXY_ENDPOINT;
  }
  
  protected async makeCloudRequest(
    request: CloudAPIRequest
  ): Promise<CloudAPIResponse> {
    // Route all cloud API requests through Kivera proxy
    const proxyUrl = new URL(this.kiveraProxy);
    
    const response = await fetch(request.endpoint, {
      method: request.method,
      headers: {
        ...request.headers,
        // Add Kivera identity headers
        'Proxy-Authorization': `Basic ${btoa(
          `${this.env.KIVERA_USERNAME}:${this.env.KIVERA_PASSWORD}`
        )}`,
        // Add workload context for policy evaluation
        'X-Workload-Id': request.context.workloadId,
        'X-Customer-Id': request.context.customerId,
      },
      body: request.body,
      // Route through Kivera proxy
      cf: {
        resolveOverride: proxyUrl.hostname,
      },
    });
    
    if (!response.ok) {
      const error = await response.json();
      
      // Check if this is a Kivera policy block
      if (error.error === 'KIVERA_POLICY_BLOCK') {
        throw new KiveraPolicyError(error.description, error.ruleId);
      }
      
      throw new CloudAPIError(request.service, response.status, error);
    }
    
    return response.json();
  }
}