Skip to content

KTS-o7/permission-mongo

Repository files navigation

Permission Mongo

RBAC-powered CRUD service for MongoDB — Schema to API in minutes

Go Version License Tests

What is Permission Mongo?

A high-performance Backend-as-a-Service that gives you:

  • REST API — Full CRUD operations with batch support
  • Fine-grained RBAC — Role-based access with hierarchical permissions
  • Schema validation — Types, constraints, computed fields
  • Document versioning — Track changes, diff, and restore
  • Hooks — Pre/post triggers with HTTP webhook support
  • Prometheus metrics — Full observability with Grafana dashboards
  • 50K+ QPS — Optimized for high throughput

Quick Start

Prerequisites

  • Go 1.21+
  • MongoDB 6.0+
  • Redis 7.0+ (optional, for caching)

Installation

# Clone the repository
git clone https://github.com/yourusername/permission-mongo.git
cd permission-mongo

# Install dependencies
go mod download

# Build
go build -o bin/permission-mongo ./cmd/server

# Run tests
go test -race ./...

Configuration

Create config.yaml:

version: "1.0"

server:
  host: "0.0.0.0"
  port: 8080
  read_timeout: 30s
  write_timeout: 30s

mongodb:
  uri: "mongodb://localhost:27017"
  database: "permission_mongo"
  max_pool_size: 100

redis:
  url: "localhost:6379"
  pool_size: 500

Running

./bin/permission-mongo --config config.yaml

API Endpoints

Health & Monitoring

Method Endpoint Description
GET /health Health check
GET /ready Readiness check
GET /metrics Prometheus metrics

Document Operations

Method Endpoint Description
POST /{collection} Create document
GET /{collection} List documents
GET /{collection}/{id} Get document
PUT /{collection}/{id} Update document
DELETE /{collection}/{id} Delete document

Batch Operations

Method Endpoint Description
POST /{collection}/batch Batch create
PUT /{collection}/batch Batch update
DELETE /{collection}/batch Batch delete

Query Operations

Method Endpoint Description
POST /{collection}/count Count documents
POST /{collection}/aggregate Aggregation pipeline

Version History

Method Endpoint Description
GET /{collection}/{id}/versions List versions
GET /{collection}/{id}/versions/{v} Get specific version
GET /{collection}/{id}/diff/{v1}/{v2} Diff between versions
POST /{collection}/{id}/restore/{v} Restore to version

RBAC Permissions

Define role-based policies:

policies:
  orders:
    admin:
      actions: [create, read, update, delete]
      when: doc.company_id == user.tenant_id
    
    manager:
      actions: [create, read, update]
      when: |
        doc.company_id == user.tenant_id &&
        (doc.created_by == user.id || doc.created_by in user.$subordinates)
    
    employee:
      actions: [create, read]
      when: doc.company_id == user.tenant_id && doc.created_by == user.id
      fields:
        deny: [internal_notes]
        mask:
          email: email

Expression Syntax

  • Comparisons: ==, !=, >, >=, <, <=
  • Logical: &&, ||, !
  • Membership: in, not in
  • References: doc.field, user.id, user.roles, user.$subordinates

Monitoring

Start the full monitoring stack:

docker-compose -f docker-compose.monitoring.yaml up -d

Access:

Available Metrics

Metric Type Description
permission_mongo_http_requests_total Counter HTTP requests by method, path, status
permission_mongo_http_request_duration_seconds Histogram Request latency
permission_mongo_mongo_operations_total Counter MongoDB operations by collection
permission_mongo_mongo_operation_duration_seconds Histogram MongoDB latency
permission_mongo_cache_hits_total Counter Cache hits by type
permission_mongo_cache_misses_total Counter Cache misses by type
permission_mongo_rbac_evaluations_total Counter RBAC evaluations (allowed/denied)
permission_mongo_audit_logs_total Counter Audit log entries

Pre-built Grafana dashboard included with panels for HTTP, MongoDB, Cache, RBAC, and Audit metrics.

See monitoring/README.md for full documentation.

Project Structure

permission-mongo/
├── cmd/
│   ├── server/          # Main server binary
│   └── pmctl/           # CLI management tool
├── pkg/
│   ├── api/             # HTTP handlers, router, middleware
│   ├── audit/           # Async audit logging with batching
│   ├── auth/            # JWT authentication
│   ├── cache/           # Redis caching layer
│   ├── config/          # Configuration loading
│   ├── hierarchy/       # User hierarchy resolution
│   ├── hooks/           # Pre/post operation hooks
│   ├── logging/         # Structured logging (slog)
│   ├── metrics/         # Prometheus metrics
│   ├── rbac/            # RBAC engine and expression compiler
│   ├── schema/          # Schema validation
│   ├── store/           # MongoDB data layer
│   └── version/         # Document versioning
├── monitoring/          # Prometheus, Grafana configs, dashboards
├── docker-compose.monitoring.yaml
└── README.md

Performance Optimizations

  • Lock-free router using atomic operations
  • Connection pooling for MongoDB (100 conns) and Redis (500 conns)
  • Async audit logging with batched MongoDB inserts
  • AST caching for RBAC expression parsing
  • Fasthttp tuned for 256K concurrent connections

Development

# Run all tests with race detector
go test -race ./...

# Run with coverage
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

# Build for production
CGO_ENABLED=0 go build -ldflags="-s -w" -o bin/permission-mongo ./cmd/server

Architecture

┌─────────────────┐     ┌─────────────────────────────────┐
│  Your App /     │────▶│    Permission Mongo Service     │
│  Mobile / Web   │     │                                 │
└─────────────────┘     │  ┌───────────┐ ┌─────────────┐  │
                        │  │ Schema    │ │ Policy      │  │
                        │  └───────────┘ └─────────────┘  │
                        │                                 │
                        │  CRUD + RBAC + Hooks + Metrics  │
                        └────────────────┬────────────────┘
                                         │
                         ┌───────────────┴───────────────┐
                         ▼                               ▼
                    ┌─────────┐                   ┌─────────┐
                    │  Redis  │                   │ MongoDB │
                    │ (cache) │                   │ (data)  │
                    └─────────┘                   └─────────┘
                         │
                         ▼
                    ┌──────────┐     ┌─────────┐
                    │Prometheus│────▶│ Grafana │
                    └──────────┘     └─────────┘

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Run tests (go test -race ./...)
  4. Commit changes (git commit -m 'Add amazing feature')
  5. Push to branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

License

MIT License - see LICENSE for details.

About

RBAC-powered CRUD service for MongoDB - High-performance BaaS with fine-grained permissions, document versioning, and full observability

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages