# Gitea Actions Setup Guide

Quick setup guide for enabling Gitea Actions on your self-hosted Gitea instance.

## Prerequisites

- Gitea 1.19+ (Actions support)
- Gitea Runner installed and configured
- Repository with `.gitea/workflows/` directory

## 1. Enable Gitea Actions

### Check if Actions are enabled

Visit your Gitea repository and check if you see an "Actions" tab. If not, Actions need to be enabled.

### Enable Actions in Gitea Configuration

Edit `app.ini` (usually in `/etc/gitea/app.ini` or `custom/conf/app.ini`):

```ini
[actions]
ENABLED = true
DEFAULT_ACTIONS_URL = https://github.com
```

Restart Gitea:
```bash
sudo systemctl restart gitea
```

## 2. Install Gitea Runner

### Download and Install

```bash
# Download latest runner
wget https://dl.gitea.com/act_runner/latest/act_runner-latest-linux-amd64

# Make executable
chmod +x act_runner-latest-linux-amd64
sudo mv act_runner-latest-linux-amd64 /usr/local/bin/act_runner
```

### Register Runner

1. Generate registration token in Gitea:
   - Site Admin → Actions → Runners → Create new Runner
   - Copy the registration token

2. Register the runner:
```bash
act_runner register \
  --instance https://your-gitea-instance.com \
  --token YOUR_REGISTRATION_TOKEN \
  --name runner-01
```

3. Start the runner:
```bash
# Test run
act_runner daemon

# Or as systemd service
sudo systemctl enable gitea-runner
sudo systemctl start gitea-runner
```

### Systemd Service (Optional)

Create `/etc/systemd/system/gitea-runner.service`:

```ini
[Unit]
Description=Gitea Actions Runner
After=network.target

[Service]
Type=simple
User=gitea-runner
WorkingDirectory=/var/lib/gitea-runner
ExecStart=/usr/local/bin/act_runner daemon
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
```

Enable and start:
```bash
sudo systemctl daemon-reload
sudo systemctl enable gitea-runner
sudo systemctl start gitea-runner
sudo systemctl status gitea-runner
```

## 3. Configure Repository Secrets

For automated Gitea issue creation, configure a `GITEA_TOKEN` secret:

### Generate Access Token

1. Navigate to: **User Settings → Applications → Manage Access Tokens**
2. Click "Generate New Token"
3. Token name: `CI_SECURITY_SCANNER`
4. Select scopes:
   - `write:issue` (required for creating issues)
   - `read:repository` (recommended)
5. Generate and **copy the token immediately** (it won't be shown again)

### Add Repository Secret

1. Navigate to: **Repository → Settings → Secrets**
2. Click "Add Secret"
3. Name: `GITEA_TOKEN`
4. Value: Paste the access token from above
5. Save

## 4. Verify Workflow Configuration

Your repository should have:

```
.gitea/
└── workflows/
    └── security-scan.yml
```

Check workflow syntax:
```bash
cat .gitea/workflows/security-scan.yml
```

## 5. Test the Workflow

### Manual Trigger

1. Navigate to repository → Actions
2. Select "Security Vulnerability Scan" workflow
3. Click "Run workflow"
4. Select branch (e.g., `main`)
5. Click "Run"

### Monitor Execution

1. Click on the running workflow
2. View real-time logs
3. Check job status (success/failure)
4. Download artifacts if needed

### Expected Output

**Successful scan:**
```
✓ Checkout code
✓ Setup PHP
✓ Validate composer.json
✓ Install dependencies
✓ Run Composer Security Audit
✓ Parse audit results
✓ Upload audit results
✓ Summary

Status: ✅ No security vulnerabilities detected
```

**Failed scan (vulnerabilities found):**
```
✓ Checkout code
✓ Setup PHP
✓ Validate composer.json
✓ Install dependencies
✓ Run Composer Security Audit
✗ Parse audit results

Status: ❌ Security vulnerabilities detected
```

## 6. Troubleshooting

### Actions Tab Not Visible

**Problem:** Actions tab not showing in repository

**Solution:**
1. Verify Actions enabled in `app.ini`
2. Restart Gitea: `sudo systemctl restart gitea`
3. Clear browser cache
4. Check Gitea version >= 1.19

### Runner Not Executing Workflows

**Problem:** Workflows stay in "waiting" status

**Solution:**
1. Check runner status: `systemctl status gitea-runner`
2. Verify runner registration: Check Gitea Admin → Runners
3. Check runner logs: `journalctl -u gitea-runner -f`
4. Restart runner: `systemctl restart gitea-runner`

### GITEA_TOKEN Not Working

**Problem:** "GITEA_TOKEN not configured" warning in logs

**Solution:**
1. Verify secret exists: Repository → Settings → Secrets
2. Check secret name is exactly `GITEA_TOKEN` (case-sensitive)
3. Regenerate token with correct permissions
4. Re-add secret to repository

### Workflow Syntax Errors

**Problem:** Workflow fails with syntax errors

**Solution:**
1. Validate YAML syntax: `yamllint .gitea/workflows/security-scan.yml`
2. Check indentation (use spaces, not tabs)
3. Verify action references use `https://` URLs for Gitea
4. Compare with working example workflows

### PHP Setup Fails

**Problem:** `Setup PHP` step fails

**Solution:**
1. Verify runner has network access
2. Check if setup-php action is accessible
3. Try using specific PHP version: `php-version: '8.4.0'`
4. Check runner logs for detailed error messages

## 7. Gitea Runner Configuration

### Custom Runner Configuration

Edit `.runner` config file:

```yaml
log:
  level: info

runner:
  # Number of concurrent jobs
  capacity: 1

  # Timeout for a single job
  timeout: 3h

  # Environment variables
  envs:
    COMPOSER_ALLOW_SUPERUSER: "1"
    COMPOSER_HOME: "/tmp/composer"

cache:
  enabled: true
  dir: "/var/cache/gitea-runner"

container:
  network: "bridge"
  privileged: false
```

### Resource Limits

For security scanning workloads, recommended runner specs:
- **CPU**: 2 cores minimum
- **RAM**: 2GB minimum
- **Disk**: 10GB available
- **Network**: Stable internet connection

## 8. Monitoring and Maintenance

### View Runner Status

```bash
# Via Gitea UI
Site Admin → Actions → Runners

# Via systemd
systemctl status gitea-runner

# View logs
journalctl -u gitea-runner -f --since "1 hour ago"
```

### Workflow Execution History

Navigate to: **Repository → Actions**
- View all workflow runs
- Filter by status (success/failure)
- Download artifacts
- Re-run failed workflows

### Cleanup Old Artifacts

Artifacts are retained for 30 days by default. To manually clean up:

1. Repository → Actions → Artifacts
2. Select old artifacts
3. Delete

Or configure automatic cleanup in workflow:
```yaml
retention-days: 7  # Keep for 1 week only
```

## 9. Advanced Configuration

### Matrix Builds (Multiple PHP Versions)

```yaml
jobs:
  security-audit:
    strategy:
      matrix:
        php-version: ['8.2', '8.3', '8.4']

    steps:
      - name: Setup PHP ${{ matrix.php-version }}
        uses: https://github.com/shivammathur/setup-php@v2
        with:
          php-version: ${{ matrix.php-version }}
```

### Conditional Execution

```yaml
# Only run on production branch
jobs:
  security-audit:
    if: github.ref == 'refs/heads/main'
```

### Notifications

Add notification step for critical failures:

```yaml
- name: Send notification on failure
  if: failure() && github.event_name == 'schedule'
  run: |
    curl -X POST https://your-webhook-url.com/alert \
      -H "Content-Type: application/json" \
      -d '{"status":"failure","workflow":"security-scan"}'
```

## 10. Security Best Practices

### Runner Security

1. **Isolate runners**: Use dedicated VM/container for runners
2. **Network security**: Restrict runner network access
3. **User permissions**: Run as non-root user
4. **Update regularly**: Keep runner and Gitea updated

### Token Security

1. **Minimal permissions**: Only grant required scopes
2. **Token rotation**: Rotate tokens every 90 days
3. **Secret storage**: Never commit secrets to repository
4. **Access audit**: Regularly review token usage logs

### Workflow Security

1. **Action pinning**: Pin actions to specific versions
2. **Input validation**: Validate all workflow inputs
3. **Artifact encryption**: Encrypt sensitive artifacts
4. **Log sanitization**: Avoid logging secrets

## Resources

- [Gitea Actions Documentation](https://docs.gitea.com/next/usage/actions/overview)
- [Act Runner Repository](https://gitea.com/gitea/act_runner)
- [Workflow Syntax Reference](https://docs.gitea.com/next/usage/actions/workflow-syntax)
- [Security Best Practices](https://docs.gitea.com/next/usage/actions/security)

## Support

For issues with:
- **Gitea Actions**: Check [Gitea Discourse](https://discourse.gitea.io)
- **Runner Issues**: File issue on [act_runner repo](https://gitea.com/gitea/act_runner/issues)
- **Workflow Syntax**: Refer to [GitHub Actions syntax](https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions) (mostly compatible)
