---
name: scramble-credentials
description: |
  Trigger this skill when securing credentials before storage:

  **Triggers:**
  - "scramble credentials"
  - "secure credentials"
  - "prepare for commit"
  - Before saving config files
  - Before committing to git
  - After successful testing (automatic)

  **What it does:**
  1. Detects all credential patterns in config and credential files
  2. Replaces real credentials with cryptographically random values
  3. Validates that no credentials were missed
  4. Returns scrambled versions safe for storage
  5. Provides warnings about potential missed credentials

  **CRITICAL:** This is a MANDATORY step before ANY storage operation.
sdkVersion: 3.18.1
features:
  stepFunctions: []
  expressionFunctions: []
  inputTypes: []
  authTypes: [ custom, oauth2 ]
  paginationModes: []
  validationRules: []
---

# Credential Scrambling Skill

## Overview

This skill secures connector configurations by automatically detecting and scrambling sensitive credentials before storage. It's a critical security step that MUST be performed before committing files, sharing configs, or storing them anywhere.

## When to Use

**Automatic triggers (MANDATORY):**
- ✅ After successful testing (before saving configs)
- ✅ Before committing to git
- ✅ Before sharing configs with team
- ✅ Before uploading to S3/storage

**Manual triggers:**
- User explicitly asks to scramble/secure credentials
- After adding new auth types to connector
- Before creating documentation examples

## Security Philosophy

**"Never commit plaintext credentials"**

Even test credentials, temporary tokens, or "fake" API keys should NEVER be committed. The scrambler ensures this by:

1. **Automatic detection** - Finds credentials in multiple formats
2. **Cryptographic replacement** - Uses secure random generation
3. **Validation warnings** - Alerts about potentially missed patterns
4. **Zero trust** - Assumes everything is sensitive unless proven otherwise

## Prerequisites

- Validated connector YAML configuration
- Test credentials used for successful testing
- Both config and credentials files accessible

## Execution Flow

### Step 1: Prepare Input Files

```bash
# Read validated config
CONFIG_JSON=$(cat connectors/<provider>/<provider>.connector.s1.yaml | yq -o=json)

# Read test credentials
CREDENTIALS_JSON=$(cat test-credentials/<provider>_oauth2.json)
```

### Step 2: Call Scrambler Tool

```typescript
scramble_credentials({
  config: CONFIG_JSON,           // Connector YAML as JSON string
  credentials: CREDENTIALS_JSON,  // Credentials JSON as string
  securityLevel: "PRODUCTION",    // PRODUCTION | BALANCED | DEVELOPMENT | DEBUG
  customPatterns: []              // Optional: Additional regex patterns
});
```

**Security Levels:**

| Level | Use Case | Detection | Preservation |
|-------|----------|-----------|--------------|
| **PRODUCTION** | Live configs, commits | Maximum | Minimal (only structure) |
| **BALANCED** | Default, recommended | High | Some (for debugging) |
| **DEVELOPMENT** | Local testing | Medium | More (for development) |
| **DEBUG** | Troubleshooting only | Low | Maximum (not for storage) |

**IMPORTANT:** Always use `PRODUCTION` level for:
- ✅ Git commits
- ✅ Shared configs
- ✅ Documentation examples
- ✅ Production deployments

### Step 3: Parse Results

```typescript
// Response structure
{
  "scrambledConfig": {
    // Config with credentials scrambled
    "authentication": [{
      "oauth2": {
        "clientId": "scrambled_aBc123DeF456...",
        "clientSecret": "scrambled_XyZ789GhI012...",
        "tokenUrl": "https://api.provider.com/oauth/token"
      }
    }]
  },
  "scrambledCredentials": {
    // Credentials with values scrambled
    "clientId": "scrambled_aBc123DeF456...",
    "clientSecret": "scrambled_XyZ789GhI012...",
    "apiKey": "scrambled_LmN345OpQ678..."
  },
  "detectedFields": [
    {
      "field": "clientId",
      "location": "config.authentication[0].oauth2",
      "pattern": "credentials_reference",
      "originalValue": "${credentials.clientId}",
      "scrambledValue": "scrambled_aBc123DeF456..."
    },
    {
      "field": "apiKey",
      "location": "credentials",
      "pattern": "api_key",
      "originalValue": "sk_live_1234567890abcdef",
      "scrambledValue": "scrambled_LmN345OpQ678..."
    }
  ],
  "warnings": [
    {
      "field": "customHeader",
      "location": "config.actions[0].steps[0].args",
      "reason": "Contains 'token' keyword but not detected by patterns",
      "suggestion": "Review manually or add custom pattern"
    }
  ],
  "metadata": {
    "securityLevel": "PRODUCTION",
    "totalFieldsScrambled": 12,
    "patternsMatched": 5,
    "warningsCount": 1
  }
}
```

### Step 4: Review Detected Fields

**Check that all sensitive fields were found:**

```typescript
// Review detectedFields array
result.detectedFields.forEach(field => {
  console.log(`✅ ${field.field} (${field.pattern}) - SCRAMBLED`);
});

// Expected patterns:
✅ clientId (credentials_reference) - SCRAMBLED
✅ clientSecret (credentials_reference) - SCRAMBLED
✅ apiKey (api_key) - SCRAMBLED
✅ accessToken (provider_specific) - SCRAMBLED
✅ refreshToken (provider_specific) - SCRAMBLED
✅ password (direct_credential) - SCRAMBLED
```

### Step 5: Address Warnings

**CRITICAL:** DO NOT ignore warnings. Each warning indicates a potentially missed credential.

```typescript
// Check warnings
if (result.warnings.length > 0) {
  result.warnings.forEach(warning => {
    console.log(`⚠️ ${warning.field}: ${warning.reason}`);
    console.log(`   Suggestion: ${warning.suggestion}`);
  });

  // Options:
  // 1. Manually verify field is not sensitive
  // 2. Add custom pattern to detect it
  // 3. Manually scramble the field
}
```

**Example warning resolution:**

```typescript
// Warning: customHeader contains 'token' but not detected

// Option 1: Verify not sensitive (false positive)
// Field contains "token" but is just a label, not a credential
// → Safe to ignore

// Option 2: Add custom pattern
scramble_credentials({
  config: CONFIG_JSON,
  credentials: CREDENTIALS_JSON,
  securityLevel: "PRODUCTION",
  customPatterns: [
    "customHeader",        // Match by field name
    "x-api-.*",           // Match by regex pattern
    ".*-secret.*"         // Match by naming convention
  ]
});

// Option 3: Manually scramble
config.actions[0].steps[0].args.find(a => a.name === "customHeader").value = "scrambled_ManUal123...";
```

### Step 6: Save Scrambled Versions

```typescript
// Save scrambled config
const scrambledYaml = convertJsonToYaml(result.scrambledConfig);
fs.writeFileSync(
  'connectors/<provider>/<provider>.connector.s1.yaml',
  scrambledYaml
);

// Save scrambled credentials (for documentation only)
fs.writeFileSync(
  'docs/examples/<provider>_credentials_example.json',
  JSON.stringify(result.scrambledCredentials, null, 2)
);

// ❌ DELETE original unscrambled files
fs.unlinkSync('test-credentials/<provider>_oauth2.json');
```

**IMPORTANT:** Original unscrambled credentials should NEVER be committed. Delete them after scrambling.

## Detected Credential Patterns

### 1. Config References

**Pattern:** `${credentials.fieldName}`

```yaml
# Detected and scrambled
authorization:
  type: basic
  username: ${credentials.email}       # → ${credentials.email}
  password: ${credentials.apiToken}    # → ${credentials.apiToken}

# Scrambled credentials file updated:
{
  "email": "scrambled_Abc123...",
  "apiToken": "scrambled_DeF456..."
}
```

### 2. Direct Credentials

**Pattern:** Field names like `apiKey`, `accessToken`, `clientSecret`

```json
// Detected and scrambled
{
  "apiKey": "sk_live_1234567890",           // → scrambled_Xyz789...
  "accessToken": "ya29.a0AfH6...",          // → scrambled_Abc123...
  "refreshToken": "1//0gHdP9ZhX...",        // → scrambled_DeF456...
  "clientSecret": "GOCSPX-abc123"           // → scrambled_GhI789...
}
```

### 3. Provider-Specific Patterns

**Pattern:** Provider-specific naming (e.g., `slackToken`, `googleSecret`)

```json
// Detected and scrambled
{
  "slackToken": "xoxb-1234567890-...",      // → scrambled_Jkl012...
  "googleApiKey": "AIzaSyD...",             // → scrambled_Mno345...
  "microsoftTenantId": "12345678-1234-..."  // → scrambled_Pqr678...
}
```

### 4. URL-Embedded Credentials

**Pattern:** Credentials in URLs (Basic auth, API key params)

```yaml
# Detected and scrambled
baseUrl: https://user:pass@api.com         # → https://scrambled_Stu901...:scrambled_Vwx234...@api.com
tokenUrl: https://api.com/token?key=abc123 # → https://api.com/token?key=scrambled_Yza567...
```

### 5. JWT Tokens & Base64 Values

**Pattern:** Long Base64-encoded strings that look like tokens

```json
// Detected and scrambled
{
  "bearerToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",  // → scrambled_Bcd890...
  "encodedSecret": "SGVsbG8gV29ybGQh"                        // → scrambled_Efg123...
}
```

### 6. Fields Marked Secret

**Pattern:** Fields with `secret: true` in config

```yaml
# Detected and scrambled
configFields:
  - key: apiToken
    type: password
    secret: true         # → Automatic detection
    required: true
```

## Custom Pattern Examples

### Adding Custom Patterns

```typescript
scramble_credentials({
  config: CONFIG_JSON,
  credentials: CREDENTIALS_JSON,
  securityLevel: "PRODUCTION",
  customPatterns: [
    // Match specific field names
    "internalToken",
    "companySecret",

    // Match by regex pattern
    "x-.*-key",              // Match all X-*-Key headers
    ".*_token$",             // Match fields ending in _token
    "^secret.*",             // Match fields starting with secret

    // Match by structure
    ".*[Pp]assword.*",       // Match any password variant
    ".*[Cc]redential.*"      // Match any credential variant
  ]
});
```

### Provider-Specific Examples

**Slack:**
```typescript
customPatterns: [
  "xoxb-.*",                // Bot tokens
  "xoxa-.*",                // App tokens
  "xoxp-.*"                 // User tokens
]
```

**Salesforce:**
```typescript
customPatterns: [
  "securityToken",          // Security token field
  "instanceUrl"             // May contain sensitive subdomain
]
```

**AWS:**
```typescript
customPatterns: [
  "accessKeyId",
  "secretAccessKey",
  "sessionToken"
]
```

## Security Checklist

### Before Storage

- [ ] Scrambler run successfully
- [ ] All `detectedFields` reviewed
- [ ] Zero warnings OR all warnings addressed
- [ ] Scrambled config saved
- [ ] Original credentials deleted
- [ ] PRODUCTION security level used
- [ ] No plaintext credentials in files
- [ ] Config still validates after scrambling

### After Scrambling

```bash
# Verify no plaintext credentials remain
grep -r "sk_live" connectors/<provider>/
grep -r "xoxb-" connectors/<provider>/
grep -r "AIzaSy" connectors/<provider>/

# Should return: no results
```

### Git Safety

```bash
# Check what's being committed
git diff connectors/<provider>/

# Should NOT see:
# - Real API keys
# - Actual tokens
# - Working credentials
# - Sensitive URLs

# Should see:
# - scrambled_* values
# - Structure preserved
# - Documentation examples
```

## Common Mistakes & Fixes

### Mistake 1: Using DEBUG Level for Commits

**Wrong:**
```typescript
scramble_credentials({
  securityLevel: "DEBUG"  // ❌ Preserves too much
});
```

**Correct:**
```typescript
scramble_credentials({
  securityLevel: "PRODUCTION"  // ✅ Maximum security
});
```

### Mistake 2: Ignoring Warnings

**Wrong:**
```typescript
if (result.warnings.length > 0) {
  console.log("Warnings present, but proceeding anyway");  // ❌
}
```

**Correct:**
```typescript
if (result.warnings.length > 0) {
  // Address each warning before proceeding
  result.warnings.forEach(w => {
    // Review, add custom pattern, or manually verify
  });
}
```

### Mistake 3: Not Deleting Original Credentials

**Wrong:**
```bash
# Leaves real credentials on disk
cp test-creds.json scrambled-creds.json  # ❌
```

**Correct:**
```bash
# Replace original with scrambled version
mv scrambled-creds.json test-creds.json  # ✅
# Or delete original
rm test-creds.json  # ✅
```

### Mistake 4: Scrambling After Commit

**Wrong:**
```bash
git add .
git commit -m "Add connector"
scramble_credentials(...)  # ❌ Too late!
```

**Correct:**
```bash
scramble_credentials(...)  # ✅ First
git add .
git commit -m "Add connector"
```

## Integration with Workflow

### Part of Security Phase (Step 10)

```typescript
// After successful testing (Step 9)
console.log("All tests passed!");

// MANDATORY: Scramble before storage
const scrambleResult = scramble_credentials({
  config: validatedConfigJson,
  credentials: testCredentialsJson,
  securityLevel: "PRODUCTION"
});

// Verify no warnings
if (scrambleResult.warnings.length > 0) {
  throw new Error("Scrambling warnings present - review before proceeding");
}

// Save scrambled versions
saveScrambledConfig(scrambleResult.scrambledConfig);
deleteOriginalCredentials();

// Now safe to commit
git add .
git commit -m "Add <provider> connector with scrambled credentials"
```

## Output Report

```markdown
## Credential Scrambling Report: <provider>

### Summary
- Status: ✅ Completed
- Security Level: PRODUCTION
- Fields Scrambled: 12
- Patterns Matched: 5
- Warnings: 0

### Detected Credentials
| Field | Location | Pattern | Status |
|-------|----------|---------|--------|
| clientId | config.authentication[0].oauth2 | credentials_reference | ✅ Scrambled |
| clientSecret | config.authentication[0].oauth2 | credentials_reference | ✅ Scrambled |
| apiKey | credentials | api_key | ✅ Scrambled |
| accessToken | credentials | provider_specific | ✅ Scrambled |
| refreshToken | credentials | provider_specific | ✅ Scrambled |

### Security Validation
- [x] No plaintext credentials in config
- [x] No plaintext credentials in credential files
- [x] All warnings addressed
- [x] PRODUCTION security level used
- [x] Config validates after scrambling
- [x] Original credentials deleted

### Files Modified
- connectors/<provider>/<provider>.connector.s1.yaml (scrambled)
- test-credentials/<provider>_oauth2.json (deleted)

### Safe for:
- ✅ Git commit
- ✅ Sharing with team
- ✅ Documentation examples
- ✅ Production deployment
```

## Key Principles

1. **MANDATORY before storage** - Never skip this step
2. **PRODUCTION level for commits** - Maximum security
3. **Address all warnings** - Don't ignore potential issues
4. **Delete originals** - Remove unscrambled credentials
5. **Verify after scrambling** - Check files for plaintext
6. **Custom patterns for providers** - Add provider-specific detection

## Anti-Patterns (NEVER DO THESE)

- ❌ Skipping scrambling before commit
- ❌ Using DEBUG level for production
- ❌ Ignoring warnings
- ❌ Keeping original credentials on disk
- ❌ Scrambling after commit
- ❌ Manual credential replacement (use tool)
- ❌ Assuming test credentials are safe to commit
- ❌ Sharing configs without scrambling first
