Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
206 changes: 206 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
# GitStore Rails 8 Examples

This directory contains complete Rails 8 example applications demonstrating the key use cases for GitStore.

## 📚 Available Examples

### 1. Wiki/CMS (`wiki_cms/`)

A complete wiki application with versioned content management.

**Features:**
- Create and edit wiki pages with Markdown support
- Full version history with diff viewing
- Rollback to any previous version
- Wiki-style `[[Page Links]]`
- Search functionality

**Key files:**
- `app/models/page.rb` - Page model with GitStore integration
- `app/controllers/pages_controller.rb` - Full CRUD with history
- `app/views/pages/` - Views with Tailwind CSS

[Read more →](wiki_cms/README.md)

---

### 2. Configuration Management (`config_management/`)

Version-controlled application configuration storage.

**Features:**
- YAML/JSON configuration storage
- Environment-specific configs
- Instant rollback for bad configurations
- Diff viewing between versions
- API access for programmatic use

**Key files:**
- `app/models/config_entry.rb` - Config model with versioning
- `app/controllers/configs_controller.rb` - Config management
- `app/services/` - (Optional) Config validation services

[Read more →](config_management/README.md)

---

### 3. Audit Trail (`audit_trail/`)

Tamper-evident data storage for compliance requirements.

**Features:**
- Immutable audit trail
- Point-in-time data reconstruction
- Cryptographic integrity verification
- Compliance report generation
- Existence proofs for legal/regulatory needs

**Key files:**
- `app/models/audited_record.rb` - Record with full audit capabilities
- `app/services/audit_service.rb` - Report generation and compliance tools
- `app/controllers/records_controller.rb` - CRUD with audit features

[Read more →](audit_trail/README.md)

---

## 🚀 Quick Start

Each example can be integrated into a new Rails 8 application:

```bash
# Create a new Rails 8 app
rails new my_app --database=sqlite3 --css=tailwind

# Add git_store to your Gemfile
cd my_app
echo "gem 'git_store', github: 'georgi/git_store'" >> Gemfile
bundle install

# Copy example files
cp -r /path/to/examples/wiki_cms/app/* app/
cp -r /path/to/examples/wiki_cms/config/* config/

# Initialize the content repository
mkdir -p content_repo
cd content_repo && git init && cd ..

# Start the server
rails server
```

## 📁 Common Patterns

### GitStore Initialization

All examples use a similar pattern for initializing GitStore in Rails:

```ruby
# config/initializers/git_store.rb
Rails.application.config.to_prepare do
repo_path = Rails.root.join('data_repo')

unless File.exist?(repo_path.join('.git'))
FileUtils.mkdir_p(repo_path)
Dir.chdir(repo_path) do
system('git init')
system('git config user.name "App System"')
system('git config user.email "system@example.com"')
end
end

Rails.application.config.store = GitStore.new(repo_path.to_s)
end
```

### Model Pattern

The examples use a consistent model pattern:

```ruby
class MyModel
include ActiveModel::Model
include ActiveModel::Attributes

class << self
def store
Rails.application.config.store
end

def find(id)
data = store["records/#{id}.yml"]
return nil unless data
new(data.merge(id: id))
end
end

def save(author: nil, message: nil)
store.transaction(message, git_author(author)) do
store["records/#{id}.yml"] = to_hash
end
end
end
```

### Transaction Pattern

For atomic operations:

```ruby
store.transaction("Update multiple configs", author) do
store["config/feature_a.yml"] = { enabled: true }
store["config/feature_b.yml"] = { enabled: false }
# All changes committed together, or all rolled back on error
end
```

## 🔑 Key Benefits

| Feature | Traditional DB | GitStore |
|---------|---------------|----------|
| Version History | Custom implementation | Built-in (Git) |
| Rollback | Complex | One command |
| Diff/Comparison | Custom | Git diff |
| Branching | Not available | Git branches |
| Audit Trail | Extra tables | Every commit |
| External Editing | Not possible | Edit files directly |
| Backup | DB dumps | Git clone |

## 💡 When to Use GitStore

**Good for:**
- Content Management Systems
- Configuration storage
- Audit-critical data
- Documentation systems
- Data that changes infrequently
- Human-readable data storage

**Not ideal for:**
- High-frequency writes
- Complex relational queries
- Large binary files
- Real-time data

## 🔒 Security Notes

When integrating these examples into your Rails application:

1. **CSRF Protection** - Ensure your `ApplicationController` has CSRF protection enabled:
```ruby
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
```

2. **Authentication** - Add proper authentication before allowing data modifications
3. **Authorization** - Implement role-based access control for sensitive operations
4. **Input Validation** - The examples include basic validation; add more as needed
5. **Repository Access** - Restrict file system access to the Git repositories

## 📖 Further Reading

- [GitStore README](../README.md)
- [GitStore Documentation](../docs/)
- [Shinmun Blog Engine](http://www.matthias-georgi.de/shinmun) - Inspiration for GitStore
- [Rails Security Guide](https://guides.rubyonrails.org/security.html)
176 changes: 176 additions & 0 deletions examples/audit_trail/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# GitStore Audit Trail Example

A Rails 8 application demonstrating versioned data storage with complete audit capabilities powered by GitStore.

## Features

- **Immutable audit trail** - Every change is a Git commit that can't be tampered with
- **Point-in-time reconstruction** - Reconstruct data state at any moment in history
- **Complete provenance** - Track who changed what, when, and why
- **Compliance ready** - Perfect for SOX, HIPAA, GDPR audit requirements
- **Cryptographic integrity** - Git SHA ensures data hasn't been altered

## Quick Start

```bash
# Create a new Rails 8 application
rails new audit_app --database=sqlite3 --css=tailwind

# Add git_store to Gemfile
echo "gem 'git_store', path: '../../../'" >> Gemfile

# Install dependencies
bundle install

# Copy the example files
cp -r app/* audit_app/app/
cp -r config/* audit_app/config/

# Initialize the audit repository
mkdir -p audit_app/audit_repo
cd audit_app/audit_repo && git init

# Run the application
cd audit_app && rails server
```

## Use Cases

### 1. Financial Transaction Auditing

```ruby
# Record a financial transaction with full audit trail
AuditedRecord.create(
type: 'financial_transaction',
id: 'txn_12345',
data: {
amount: 1000.00,
currency: 'USD',
from_account: 'ACC001',
to_account: 'ACC002',
description: 'Wire transfer'
},
author: current_user,
message: 'Initiated wire transfer'
)

# Later, if we need to prove the transaction existed at a specific time
record = AuditedRecord.find('financial_transaction', 'txn_12345')
proof = record.existence_proof
# => { commit_id: 'abc123...', timestamp: '2024-01-15T10:30:00Z', ... }
```

### 2. Medical Record Management (HIPAA Compliance)

```ruby
# Store patient data with audit trail
AuditedRecord.create(
type: 'patient_record',
id: 'patient_001',
data: {
name: 'John Doe',
dob: '1990-01-15',
diagnoses: ['Type 2 Diabetes'],
medications: ['Metformin 500mg']
},
author: current_user,
message: 'Initial patient registration'
)

# Track who accessed the record
AuditService.log_access(
record_type: 'patient_record',
record_id: 'patient_001',
user: current_user,
action: 'view'
)

# Generate HIPAA audit report
report = AuditService.generate_report(
record_type: 'patient_record',
record_id: 'patient_001',
from: 30.days.ago,
to: Time.current
)
```

### 3. Document Version Control

```ruby
# Store a legal document
AuditedRecord.create(
type: 'legal_document',
id: 'contract_2024_001',
data: {
title: 'Service Agreement',
version: '1.0',
content: contract_text,
parties: ['Company A', 'Company B']
},
author: current_user,
message: 'Initial draft of service agreement'
)

# Get the complete revision history
record = AuditedRecord.find('legal_document', 'contract_2024_001')
record.revisions.each do |revision|
puts "Version at #{revision.timestamp}: #{revision.message}"
puts "Changed by: #{revision.author}"
end
```

## Compliance Features

### Tamper-Evident Storage

Every record is stored with a cryptographic hash (Git SHA). Any modification to historical data would change the hash, making tampering detectable.

```ruby
# Verify data integrity
record = AuditedRecord.find('financial_transaction', 'txn_12345')
record.verify_integrity!
# => true (data hasn't been tampered with)
```

### Point-in-Time Queries

Reconstruct the exact state of data at any historical moment:

```ruby
# What did this record look like last week?
record = AuditedRecord.find('patient_record', 'patient_001')
historical_state = record.state_at(1.week.ago)
```

### Audit Log Generation

```ruby
# Generate comprehensive audit log
log = AuditService.generate_log(
from: 1.month.ago,
to: Time.current,
record_types: ['financial_transaction', 'patient_record'],
format: :csv
)
```

## API Endpoints

| Method | Path | Description |
|--------|------|-------------|
| GET | /records | List all audited records |
| GET | /records/:type/:id | Get a specific record |
| POST | /records | Create a new record |
| PATCH | /records/:type/:id | Update a record |
| GET | /records/:type/:id/history | Full revision history |
| GET | /records/:type/:id/state_at | State at a point in time |
| GET | /records/:type/:id/proof | Existence proof for compliance |
| GET | /audit_logs | Search audit logs |
| GET | /audit_logs/report | Generate audit report |

## Security Considerations

1. **Repository Protection** - The audit repository should be protected with restricted access
2. **Backup Strategy** - Regular backups of the Git repository ensure durability
3. **Key Management** - Consider signing commits for additional integrity
4. **Access Logging** - All API access should be logged separately
Loading