# Package Installation Architecture & Security

## Overview

Archipelago uses a **container-based app installation system** similar to StartOS, with enhanced security and flexibility.

## Installation Methods

### 1. **Web UI Marketplace** (Current Implementation)
**How it works:**
- User clicks "Install" in the marketplace
- Frontend calls `package.install` RPC method
- Backend pulls Docker image and creates Podman container
- Container starts with predefined configuration

**Security:**
- ✅ Image name validation (prevents injection attacks)
- ✅ Resource limits (CPU, memory)
- ⚠️ Uses hardcoded configs (will use manifests)
- ⚠️ No image signature verification yet

**Pros:**
- User-friendly (click to install)
- Fast installation
- Works for most Docker-based apps

**Cons:**
- Limited configuration options
- No manifest-based permissions yet
- Requires internet for image pull

---

### 2. **Manifest-Based Installation** (Recommended Future)

**How it works:**
```yaml
# apps/home-assistant/manifest.yml
app:
  id: home-assistant
  name: Home Assistant
  container:
    image: homeassistant/home-assistant:2024.1
    image_signature: cosign://...  # Verify with Cosign
  security:
    capabilities: [NET_BIND_SERVICE]
    readonly_root: false
    network_policy: host
  resources:
    cpu_limit: 2
    memory_limit: 2Gi
```

**Installation:**
```bash
# Backend reads manifest, validates, creates container with exact specs
archipelago install --manifest apps/home-assistant/manifest.yml
```

**Security Benefits:**
- ✅ **Image verification** with Cosign signatures
- ✅ **Explicit permissions** (capabilities, network access)
- ✅ **Resource limits** from manifest
- ✅ **Dependency resolution** (Bitcoin Core before LND)
- ✅ **AppArmor/SELinux profiles** per app
- ✅ **Audit trail** of what permissions were granted

---

### 3. **Sideload from .s9pk** (StartOS Compatible)

**How it works:**
- User uploads `.s9pk` file (ZIP with manifest + Docker image)
- Backend extracts, verifies signature
- Creates container from embedded image

**Security:**
- ✅ GPG signature verification
- ✅ Offline installation (no internet needed)
- ✅ User reviews permissions before install

---

## Security Considerations

### Current Implementation (package.install)

#### ✅ **What's Secure:**
1. **Input Validation**
   ```rust
   fn is_valid_docker_image(image: &str) -> bool {
       // Rejects shell metacharacters: & | ; ` $ ( ) < >
       // Prevents command injection
   }
   ```

2. **Resource Limits**
   ```rust
   run_args.push("--memory=2g");
   run_args.push("--cpus=2");
   ```

3. **Rootless Podman** (future)
   - Containers run as non-root user
   - Reduced attack surface

#### ⚠️ **What Needs Improvement:**

1. **No Image Verification**
   - **Current**: Trusts Docker Hub/registries blindly
   - **Should**: Verify signatures with Cosign
   ```bash
   cosign verify --key cosign.pub ghcr.io/owner/image:tag
   ```

2. **Hardcoded Configs**
   - **Current**: `get_app_config()` has hardcoded ports/volumes
   - **Should**: Load from `apps/*/manifest.yml`

3. **No Permission Review**
   - **Current**: User doesn't see what access app gets
   - **Should**: Show permission prompt before install:
     ```
     Home Assistant requests:
     - Network: Host (for device discovery)
     - Devices: /dev/ttyUSB0 (serial devices)
     - Capabilities: NET_BIND_SERVICE
     - Storage: 10GB
     
     [Cancel] [Install]
     ```

4. **No Dependency Resolution**
   - **Current**: Install apps independently
   - **Should**: Check dependencies (e.g., LND requires Bitcoin Core)

5. **No Network Isolation**
   - **Current**: Apps can access each other
   - **Should**: Isolated networks by default, explicit connections

---

##Security Best Practices

### Multi-Layer Security Model

```
┌─────────────────────────────────────────────┐
│  1. Supply Chain Security                   │
│  - Cosign image signing                     │
│  - SBOM (Software Bill of Materials)        │
│  - Vulnerability scanning                   │
└─────────────────────────────────────────────┘
           ↓
┌─────────────────────────────────────────────┐
│  2. Installation Validation                 │
│  - Signature verification                   │
│  - Manifest schema validation               │
│  - Permission review                        │
└─────────────────────────────────────────────┘
           ↓
┌─────────────────────────────────────────────┐
│  3. Runtime Isolation                       │
│  - Rootless containers                      │
│  - AppArmor/SELinux profiles                │
│  - Network isolation                        │
│  - Resource limits                          │
└─────────────────────────────────────────────┘
           ↓
┌─────────────────────────────────────────────┐
│  4. Monitoring & Audit                      │
│  - Health checks                            │
│  - Log collection                           │
│  - Anomaly detection                        │
└─────────────────────────────────────────────┘
```

---

## Comparison with StartOS

| Feature | StartOS | Archipelago (Current) | Archipelago (Goal) |
|---------|---------|----------------------|-------------------|
| **Image Format** | .s9pk (custom) | Docker images | Both |
| **Image Verification** | GPG signatures | ❌ None | ✅ Cosign |
| **Permission System** | ✅ Manifest-based | ❌ Hardcoded | ✅ Manifest-based |
| **Network Isolation** | ✅ Per-app networks | ❌ Shared network | ✅ Per-app networks |
| **Dependency Resolution** | ✅ Automatic | ❌ Manual | ✅ Automatic |
| **Resource Limits** | ✅ From manifest | ⚠️ Hardcoded | ✅ From manifest |
| **Audit Trail** | ✅ Yes | ⚠️ Basic logs | ✅ Full audit |

---

## Recommended Next Steps

### Phase 1: Manifest-Based Installation (Priority: HIGH)
1. Implement manifest parser in Rust
2. Load configs from `apps/*/manifest.yml`
3. Apply security policies from manifest
4. Show permission prompt in UI

### Phase 2: Image Verification (Priority: HIGH)
1. Integrate Cosign for signature verification
2. Maintain whitelist of trusted signing keys
3. Reject unsigned images in production

### Phase 3: Network Isolation (Priority: MEDIUM)
1. Create isolated network per app
2. Explicit inter-app connections (e.g., LND → Bitcoin Core RPC)
3. Firewall rules per app

### Phase 4: Dependency Resolution (Priority: MEDIUM)
1. Parse `dependencies` from manifests
2. Auto-install dependencies
3. Prevent removal of depended-upon apps

### Phase 5: Advanced Security (Priority: LOW)
1. AppArmor profile generation per app
2. Hardware attestation (TPM 2.0)
3. Encrypted secrets storage (not plaintext volumes)

---

## How Users Will Install Apps (Production)

### Method 1: Trusted Marketplace (Recommended)
```
User → Marketplace → Verified Registry → Podman
```
- Pre-vetted apps with verified signatures
- Manifests reviewed by Archipelago team
- One-click install

### Method 2: Sideload (.s9pk)
```
User → Upload .s9pk → Verify Signature → Extract → Podman
```
- For community apps
- User takes responsibility for trust

### Method 3: Advanced (Manual)
```
User → SSH → podman run with manifest → Manual config
```
- For developers/power users
- Full control, no guardrails

---

## Security Philosophy

**Defense in Depth:**
- Never trust a single layer
- Verify at supply chain (Cosign)
- Isolate at runtime (containers)
- Monitor continuously (health checks)

**Principle of Least Privilege:**
- Apps get only what they need
- Explicit permissions in manifest
- User approves before granting

**Transparency:**
- Open manifests (readable YAML)
- Clear permission requests
- Audit logs of all actions

---

## Questions Answered

### Is package.install secure?
**Current state:** Moderately secure
- ✅ Input validation prevents injection
- ✅ Resource limits prevent resource exhaustion
- ❌ No image verification (trust Docker Hub)
- ❌ No permission system yet

**With manifests:** Very secure
- ✅ All of the above
- ✅ Signature verification
- ✅ Explicit permissions
- ✅ Network isolation

### How do users install on actual OS?
1. **Pre-installed in ISO**: Included in image build
2. **Web UI Marketplace**: Click to install (current)
3. **Sideload**: Upload .s9pk file
4. **CLI**: SSH + podman commands (advanced)

The **Web UI is the primary method** for end users - simple, secure, auditable.

---

## Implementation Roadmap

**v0.1.0 (Current):**
- ✅ Basic `package.install` RPC
- ✅ Hardcoded app configs
- ✅ Input validation

**v0.2.0 (Next):**
- Manifest parser
- Load from `apps/*/manifest.yml`
- Permission UI prompt

**v0.3.0:**
- Cosign verification
- Network isolation per app
- Dependency resolution

**v1.0.0:**
- Full security model
- AppArmor profiles
- Audit logging
- Production-ready
