# Nushell Plugins for Provisioning Platform

Complete guide to authentication, KMS, and orchestrator plugins.

## Overview

Three native Nushell plugins provide high-performance integration with the provisioning platform:

1. **nu_plugin_auth** - JWT authentication and MFA operations
2. **nu_plugin_kms** - Key management (RustyVault, Age, Cosmian, AWS, Vault)
3. **nu_plugin_orchestrator** - Orchestrator operations (status, validate, tasks)

## Why Native Plugins

**Performance Advantages**:

- **10x faster** than HTTP API calls (KMS operations)
- **Direct access** to Rust libraries (no HTTP overhead)
- **Native integration** with Nushell pipelines
- **Type safety** with Nushell's type system

**Developer Experience**:

- **Pipeline friendly** - Use Nushell pipes naturally
- **Tab completion** - All commands and flags
- **Consistent interface** - Follows Nushell conventions
- **Error handling** - Nushell-native error messages

---

## Installation

### Prerequisites

- Nushell 0.107.1+
- Rust toolchain (for building from source)
- Access to provisioning platform services

### Build from Source

```bash
cd /Users/Akasha/project-provisioning/provisioning/core/plugins/nushell-plugins

# Build all plugins
cargo build --release -p nu_plugin_auth
cargo build --release -p nu_plugin_kms
cargo build --release -p nu_plugin_orchestrator

# Or build individually
cargo build --release -p nu_plugin_auth
cargo build --release -p nu_plugin_kms
cargo build --release -p nu_plugin_orchestrator
```plaintext

### Register with Nushell

```bash
# Register all plugins
plugin add target/release/nu_plugin_auth
plugin add target/release/nu_plugin_kms
plugin add target/release/nu_plugin_orchestrator

# Verify registration
plugin list | where name =~ "provisioning"
```plaintext

### Verify Installation

```bash
# Test auth commands
auth --help

# Test KMS commands
kms --help

# Test orchestrator commands
orch --help
```plaintext

---

## Plugin: nu_plugin_auth

Authentication plugin for JWT login, MFA enrollment, and session management.

### Commands

#### `auth login <username> [password]`

Login to provisioning platform and store JWT tokens securely.

**Arguments**:

- `username` (required): Username for authentication
- `password` (optional): Password (prompts interactively if not provided)

**Flags**:

- `--url <url>`: Control center URL (default: `http://localhost:9080`)
- `--password <password>`: Password (alternative to positional argument)

**Examples**:

```nushell
# Interactive password prompt (recommended)
auth login admin

# Password in command (not recommended for production)
auth login admin mypassword

# Custom URL
auth login admin --url http://control-center:9080

# Pipeline usage
"admin" | auth login
```plaintext

**Token Storage**:
Tokens are stored securely in OS-native keyring:

- **macOS**: Keychain Access
- **Linux**: Secret Service (gnome-keyring, kwallet)
- **Windows**: Credential Manager

**Success Output**:

```plaintext
✓ Login successful
User: admin
Role: Admin
Expires: 2025-10-09T14:30:00Z
```plaintext

---

#### `auth logout`

Logout from current session and remove stored tokens.

**Examples**:

```nushell
# Simple logout
auth logout

# Pipeline usage (conditional logout)
if (auth verify | get active) { auth logout }
```plaintext

**Success Output**:

```plaintext
✓ Logged out successfully
```plaintext

---

#### `auth verify`

Verify current session and check token validity.

**Examples**:

```nushell
# Check session status
auth verify

# Pipeline usage
auth verify | if $in.active { echo "Session valid" } else { echo "Session expired" }
```plaintext

**Success Output**:

```json
{
  "active": true,
  "user": "admin",
  "role": "Admin",
  "expires_at": "2025-10-09T14:30:00Z",
  "mfa_verified": true
}
```plaintext

---

#### `auth sessions`

List all active sessions for current user.

**Examples**:

```nushell
# List sessions
auth sessions

# Filter by date
auth sessions | where created_at > (date now | date to-timezone UTC | into string)
```plaintext

**Output Format**:

```json
[
  {
    "session_id": "sess_abc123",
    "created_at": "2025-10-09T12:00:00Z",
    "expires_at": "2025-10-09T14:30:00Z",
    "ip_address": "192.168.1.100",
    "user_agent": "nushell/0.107.1"
  }
]
```plaintext

---

#### `auth mfa enroll <type>`

Enroll in MFA (TOTP or WebAuthn).

**Arguments**:

- `type` (required): MFA type (`totp` or `webauthn`)

**Examples**:

```nushell
# Enroll TOTP (Google Authenticator, Authy)
auth mfa enroll totp

# Enroll WebAuthn (YubiKey, Touch ID, Windows Hello)
auth mfa enroll webauthn
```plaintext

**TOTP Enrollment Output**:

```plaintext
✓ TOTP enrollment initiated

Scan this QR code with your authenticator app:

  ████ ▄▄▄▄▄ █▀█ █▄▀▀▀▄ ▄▄▄▄▄ ████
  ████ █   █ █▀▀▀█▄ ▀▀█ █   █ ████
  ████ █▄▄▄█ █ █▀▄ ▀▄▄█ █▄▄▄█ ████
  ...

Or enter manually:
Secret: JBSWY3DPEHPK3PXP
URL: otpauth://totp/Provisioning:admin?secret=JBSWY3DPEHPK3PXP&issuer=Provisioning

Backup codes (save securely):
1. ABCD-EFGH-IJKL
2. MNOP-QRST-UVWX
...
```plaintext

---

#### `auth mfa verify --code <code>`

Verify MFA code (TOTP or backup code).

**Flags**:

- `--code <code>` (required): 6-digit TOTP code or backup code

**Examples**:

```nushell
# Verify TOTP code
auth mfa verify --code 123456

# Verify backup code
auth mfa verify --code ABCD-EFGH-IJKL
```plaintext

**Success Output**:

```plaintext
✓ MFA verification successful
```plaintext

---

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `USER` | Default username | Current OS user |
| `CONTROL_CENTER_URL` | Control center URL | `http://localhost:9080` |

---

### Error Handling

**Common Errors**:

```nushell
# "No active session"
Error: No active session found
→ Run: auth login <username>

# "Invalid credentials"
Error: Authentication failed: Invalid username or password
→ Check username and password

# "Token expired"
Error: Token has expired
→ Run: auth login <username>

# "MFA required"
Error: MFA verification required
→ Run: auth mfa verify --code <code>

# "Keyring error" (macOS)
Error: Failed to access keyring
→ Check Keychain Access permissions

# "Keyring error" (Linux)
Error: Failed to access keyring
→ Install gnome-keyring or kwallet
```plaintext

---

## Plugin: nu_plugin_kms

Key Management Service plugin supporting multiple backends.

### Supported Backends

| Backend | Description | Use Case |
|---------|-------------|----------|
| `rustyvault` | RustyVault Transit engine | Production KMS |
| `age` | Age encryption (local) | Development/testing |
| `cosmian` | Cosmian KMS (HTTP) | Cloud KMS |
| `aws` | AWS KMS | AWS environments |
| `vault` | HashiCorp Vault | Enterprise KMS |

### Commands

#### `kms encrypt <data> [--backend <backend>]`

Encrypt data using KMS.

**Arguments**:

- `data` (required): Data to encrypt (string or binary)

**Flags**:

- `--backend <backend>`: KMS backend (`rustyvault`, `age`, `cosmian`, `aws`, `vault`)
- `--key <key>`: Key ID or recipient (backend-specific)
- `--context <context>`: Additional authenticated data (AAD)

**Examples**:

```nushell
# Auto-detect backend from environment
kms encrypt "secret data"

# RustyVault
kms encrypt "data" --backend rustyvault --key provisioning-main

# Age (local encryption)
kms encrypt "data" --backend age --key age1xxxxxxxxx

# AWS KMS
kms encrypt "data" --backend aws --key alias/provisioning

# With context (AAD)
kms encrypt "data" --backend rustyvault --key provisioning-main --context "user=admin"
```plaintext

**Output Format**:

```plaintext
vault:v1:abc123def456...
```plaintext

---

#### `kms decrypt <encrypted> [--backend <backend>]`

Decrypt KMS-encrypted data.

**Arguments**:

- `encrypted` (required): Encrypted data (base64 or KMS format)

**Flags**:

- `--backend <backend>`: KMS backend (auto-detected if not specified)
- `--context <context>`: Additional authenticated data (AAD, must match encryption)

**Examples**:

```nushell
# Auto-detect backend
kms decrypt "vault:v1:abc123def456..."

# RustyVault explicit
kms decrypt "vault:v1:abc123..." --backend rustyvault

# Age
kms decrypt "-----BEGIN AGE ENCRYPTED FILE-----..." --backend age

# With context
kms decrypt "vault:v1:abc123..." --backend rustyvault --context "user=admin"
```plaintext

**Output**:

```plaintext
secret data
```plaintext

---

#### `kms generate-key [--spec <spec>]`

Generate data encryption key (DEK) using KMS.

**Flags**:

- `--spec <spec>`: Key specification (`AES128` or `AES256`, default: `AES256`)
- `--backend <backend>`: KMS backend

**Examples**:

```nushell
# Generate AES-256 key
kms generate-key

# Generate AES-128 key
kms generate-key --spec AES128

# Specific backend
kms generate-key --backend rustyvault
```plaintext

**Output Format**:

```json
{
  "plaintext": "base64-encoded-key",
  "ciphertext": "vault:v1:encrypted-key",
  "spec": "AES256"
}
```plaintext

---

#### `kms status`

Show KMS backend status and configuration.

**Examples**:

```nushell
# Show status
kms status

# Filter to specific backend
kms status | where backend == "rustyvault"
```plaintext

**Output Format**:

```json
{
  "backend": "rustyvault",
  "status": "healthy",
  "url": "http://localhost:8200",
  "mount_point": "transit",
  "version": "0.1.0"
}
```plaintext

---

### Environment Variables

**RustyVault Backend**:

```bash
export RUSTYVAULT_ADDR="http://localhost:8200"
export RUSTYVAULT_TOKEN="your-token-here"
export RUSTYVAULT_MOUNT="transit"
```plaintext

**Age Backend**:

```bash
export AGE_RECIPIENT="age1xxxxxxxxx"
export AGE_IDENTITY="/path/to/key.txt"
```plaintext

**HTTP Backend (Cosmian)**:

```bash
export KMS_HTTP_URL="http://localhost:9998"
export KMS_HTTP_BACKEND="cosmian"
```plaintext

**AWS KMS**:

```bash
export AWS_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="..."
export AWS_SECRET_ACCESS_KEY="..."
```plaintext

---

### Performance Comparison

| Operation | HTTP API | Plugin | Improvement |
|-----------|----------|--------|-------------|
| Encrypt (RustyVault) | ~50 ms | ~5 ms | **10x faster** |
| Decrypt (RustyVault) | ~50 ms | ~5 ms | **10x faster** |
| Encrypt (Age) | ~30 ms | ~3 ms | **10x faster** |
| Decrypt (Age) | ~30 ms | ~3 ms | **10x faster** |
| Generate Key | ~60 ms | ~8 ms | **7.5x faster** |

---

## Plugin: nu_plugin_orchestrator

Orchestrator operations plugin for status, validation, and task management.

### Commands

#### `orch status [--data-dir <dir>]`

Get orchestrator status from local files (no HTTP).

**Flags**:

- `--data-dir <dir>`: Data directory (default: `provisioning/platform/orchestrator/data`)

**Examples**:

```nushell
# Default data dir
orch status

# Custom dir
orch status --data-dir ./custom/data

# Pipeline usage
orch status | if $in.active_tasks > 0 { echo "Tasks running" }
```plaintext

**Output Format**:

```json
{
  "active_tasks": 5,
  "completed_tasks": 120,
  "failed_tasks": 2,
  "pending_tasks": 3,
  "uptime": "2d 4h 15m",
  "health": "healthy"
}
```plaintext

---

#### `orch validate <workflow.ncl> [--strict]`

Validate workflow Nickel file.

**Arguments**:

- `workflow.ncl` (required): Path to Nickel workflow file

**Flags**:

- `--strict`: Enable strict validation (all checks, warnings as errors)

**Examples**:

```nushell
# Basic validation
orch validate workflows/deploy.ncl

# Strict mode
orch validate workflows/deploy.ncl --strict

# Pipeline usage
ls workflows/*.ncl | each { |file| orch validate $file.name }
```plaintext

**Output Format**:

```json
{
  "valid": true,
  "workflow": {
    "name": "deploy_k8s_cluster",
    "version": "1.0.0",
    "operations": 5
  },
  "warnings": [],
  "errors": []
}
```plaintext

**Validation Checks**:

- KCL syntax errors
- Required fields present
- Dependency graph valid (no cycles)
- Resource limits within bounds
- Provider configurations valid

---

#### `orch tasks [--status <status>] [--limit <n>]`

List orchestrator tasks.

**Flags**:

- `--status <status>`: Filter by status (`pending`, `running`, `completed`, `failed`)
- `--limit <n>`: Limit number of results (default: 100)
- `--data-dir <dir>`: Data directory (default from `ORCHESTRATOR_DATA_DIR`)

**Examples**:

```nushell
# All tasks
orch tasks

# Pending tasks only
orch tasks --status pending

# Running tasks (limit to 10)
orch tasks --status running --limit 10

# Pipeline usage
orch tasks --status failed | each { |task| echo $"Failed: ($task.name)" }
```plaintext

**Output Format**:

```json
[
  {
    "task_id": "task_abc123",
    "name": "deploy_kubernetes",
    "status": "running",
    "priority": 5,
    "created_at": "2025-10-09T12:00:00Z",
    "updated_at": "2025-10-09T12:05:00Z",
    "progress": 45
  }
]
```plaintext

---

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `ORCHESTRATOR_DATA_DIR` | Data directory | `provisioning/platform/orchestrator/data` |

---

### Performance Comparison

| Operation | HTTP API | Plugin | Improvement |
|-----------|----------|--------|-------------|
| Status | ~30 ms | ~3 ms | **10x faster** |
| Validate | ~100 ms | ~10 ms | **10x faster** |
| Tasks List | ~50 ms | ~5 ms | **10x faster** |

---

## Pipeline Examples

### Authentication Flow

```nushell
# Login and verify in one pipeline
auth login admin
    | if $in.success { auth verify }
    | if $in.mfa_required { auth mfa verify --code (input "MFA code: ") }
```plaintext

### KMS Operations

```nushell
# Encrypt multiple secrets
["secret1", "secret2", "secret3"]
    | each { |data| kms encrypt $data --backend rustyvault }
    | save encrypted_secrets.json

# Decrypt and process
open encrypted_secrets.json
    | each { |enc| kms decrypt $enc }
    | each { |plain| echo $"Decrypted: ($plain)" }
```plaintext

### Orchestrator Monitoring

```nushell
# Monitor running tasks
while true {
    orch tasks --status running
        | each { |task| echo $"($task.name): ($task.progress)%" }
    sleep 5sec
}
```plaintext

### Combined Workflow

```nushell
# Complete deployment workflow
auth login admin
    | auth mfa verify --code (input "MFA: ")
    | orch validate workflows/deploy.ncl
    | if $in.valid {
        orch tasks --status pending
            | where priority > 5
            | each { |task| echo $"High priority: ($task.name)" }
      }
```plaintext

---

## Troubleshooting

### Auth Plugin

**"No active session"**:

```nushell
auth login <username>
```plaintext

**"Keyring error" (macOS)**:

- Check Keychain Access permissions
- Security & Privacy → Privacy → Full Disk Access → Add Nushell

**"Keyring error" (Linux)**:

```bash
# Install keyring service
sudo apt install gnome-keyring  # Ubuntu/Debian
sudo dnf install gnome-keyring  # Fedora

# Or use KWallet
sudo apt install kwalletmanager
```plaintext

**"MFA verification failed"**:

- Check time synchronization (TOTP requires accurate clocks)
- Use backup codes if TOTP not working
- Re-enroll MFA if device lost

---

### KMS Plugin

**"RustyVault connection failed"**:

```bash
# Check RustyVault running
curl http://localhost:8200/v1/sys/health

# Set environment
export RUSTYVAULT_ADDR="http://localhost:8200"
export RUSTYVAULT_TOKEN="your-token"
```plaintext

**"Age encryption failed"**:

```bash
# Check Age keys
ls -la ~/.age/

# Generate new key if needed
age-keygen -o ~/.age/key.txt

# Set environment
export AGE_RECIPIENT="age1xxxxxxxxx"
export AGE_IDENTITY="$HOME/.age/key.txt"
```plaintext

**"AWS KMS access denied"**:

```bash
# Check AWS credentials
aws sts get-caller-identity

# Check KMS key policy
aws kms describe-key --key-id alias/provisioning
```plaintext

---

### Orchestrator Plugin

**"Failed to read status"**:

```bash
# Check data directory exists
ls provisioning/platform/orchestrator/data/

# Create if missing
mkdir -p provisioning/platform/orchestrator/data
```plaintext

**"Workflow validation failed"**:

```nushell
# Use strict mode for detailed errors
orch validate workflows/deploy.ncl --strict
```plaintext

**"No tasks found"**:

```bash
# Check orchestrator running
ps aux | grep orchestrator

# Start orchestrator
cd provisioning/platform/orchestrator
./scripts/start-orchestrator.nu --background
```plaintext

---

## Development

### Building from Source

```bash
cd provisioning/core/plugins/nushell-plugins

# Clean build
cargo clean

# Build with debug info
cargo build -p nu_plugin_auth
cargo build -p nu_plugin_kms
cargo build -p nu_plugin_orchestrator

# Run tests
cargo test -p nu_plugin_auth
cargo test -p nu_plugin_kms
cargo test -p nu_plugin_orchestrator

# Run all tests
cargo test --all
```plaintext

### Adding to CI/CD

```yaml
name: Build Nushell Plugins

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable

      - name: Build Plugins
        run: |
          cd provisioning/core/plugins/nushell-plugins
          cargo build --release --all

      - name: Test Plugins
        run: |
          cd provisioning/core/plugins/nushell-plugins
          cargo test --all

      - name: Upload Artifacts
        uses: actions/upload-artifact@v3
        with:
          name: plugins
          path: provisioning/core/plugins/nushell-plugins/target/release/nu_plugin_*
```plaintext

---

## Advanced Usage

### Custom Plugin Configuration

Create `~/.config/nushell/plugin_config.nu`:

```nushell
# Auth plugin defaults
$env.CONTROL_CENTER_URL = "https://control-center.example.com"

# KMS plugin defaults
$env.RUSTYVAULT_ADDR = "https://vault.example.com:8200"
$env.RUSTYVAULT_MOUNT = "transit"

# Orchestrator plugin defaults
$env.ORCHESTRATOR_DATA_DIR = "/opt/orchestrator/data"
```plaintext

### Plugin Aliases

Add to `~/.config/nushell/config.nu`:

```nushell
# Auth shortcuts
alias login = auth login
alias logout = auth logout

# KMS shortcuts
alias encrypt = kms encrypt
alias decrypt = kms decrypt

# Orchestrator shortcuts
alias status = orch status
alias validate = orch validate
alias tasks = orch tasks
```plaintext

---

## Security Best Practices

### Authentication

✅ **DO**: Use interactive password prompts
✅ **DO**: Enable MFA for production environments
✅ **DO**: Verify session before sensitive operations
❌ **DON'T**: Pass passwords in command line (visible in history)
❌ **DON'T**: Store tokens in plain text files

### KMS Operations

✅ **DO**: Use context (AAD) for encryption when available
✅ **DO**: Rotate KMS keys regularly
✅ **DO**: Use hardware-backed keys (WebAuthn, YubiKey) when possible
❌ **DON'T**: Share Age private keys
❌ **DON'T**: Log decrypted data

### Orchestrator

✅ **DO**: Validate workflows in strict mode before production
✅ **DO**: Monitor task status regularly
✅ **DO**: Use appropriate data directory permissions (700)
❌ **DON'T**: Run orchestrator as root
❌ **DON'T**: Expose data directory over network shares

---

## FAQ

**Q: Why use plugins instead of HTTP API?**
A: Plugins are 10x faster, have better Nushell integration, and eliminate HTTP overhead.

**Q: Can I use plugins without orchestrator running?**
A: `auth` and `kms` work independently. `orch` requires access to orchestrator data directory.

**Q: How do I update plugins?**
A: Rebuild and re-register: `cargo build --release --all && plugin add target/release/nu_plugin_*`

**Q: Are plugins cross-platform?**
A: Yes, plugins work on macOS, Linux, and Windows (with appropriate keyring services).

**Q: Can I use multiple KMS backends simultaneously?**
A: Yes, specify `--backend` flag for each operation.

**Q: How do I backup MFA enrollment?**
A: Save backup codes securely (password manager, encrypted file). QR code can be re-scanned.

---

## Related Documentation

- **Security System**: `docs/architecture/ADR-009-security-system-complete.md`
- **JWT Auth**: `docs/architecture/JWT_AUTH_IMPLEMENTATION.md`
- **Config Encryption**: `docs/user/CONFIG_ENCRYPTION_GUIDE.md`
- **RustyVault Integration**: `RUSTYVAULT_INTEGRATION_SUMMARY.md`
- **MFA Implementation**: `docs/architecture/MFA_IMPLEMENTATION_SUMMARY.md`

---

**Version**: 1.0.0
**Last Updated**: 2025-10-09
**Maintained By**: Platform Team
