go-rbac-api

module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2026 License: MIT

README

Go RBAC API

Go PostgreSQL gRPC OpenAPI License

A reusable RBAC / Authorization Service written in Go.

It provides centralized roles, permissions, authorization checks, service-to-service authentication, local session support, external identity sync, audit logging, REST API, gRPC API, Swagger/OpenAPI documentation, and a Go client SDK.

This service is not a full identity provider. It can work standalone for local users, and it can integrate with Keycloak, Auth0, or any external identity provider. External services call RBAC through REST or gRPC instead of implementing authorization logic themselves.


Status

This project is a production-oriented RBAC foundation and portfolio project.

It is suitable for:

  • learning and experimentation
  • local demos
  • internal tools
  • service authorization prototypes
  • a foundation for real microservice authorization systems

Before real production use, add or harden:

  • TLS everywhere
  • API key rotation
  • secret manager integration
  • rate limiting
  • deployment hardening
  • production monitoring/exporters
  • backup and migration strategy
  • CI/CD hardening
  • stronger service-to-service security such as mTLS or trusted service JWTs

Features

  • REST API
  • gRPC API
  • Swagger UI for REST docs
  • OpenAPI 3.0 spec
  • Service-to-service authentication
  • Admin/local session authentication
  • Refresh/logout/session management
  • User, role, and permission management
  • User-role assignment
  • Role-permission assignment
  • Authorization decision API
  • External identity sync
  • Local session introspection
  • Audit logging
  • Go client SDK
  • Billing service example
  • Postman collection
  • Smoke test script

Why This Project Exists

Authorization logic becomes complex across microservices. Each service can start with a few role checks, then grow its own permission naming, audit behavior, exceptions, and duplicated database queries.

Identity platforms like Keycloak are powerful, but complex RBAC rules can be difficult to configure, customize, and keep consistent across services.

This project separates authentication from authorization:

  • Authentication answers: who is the user?
  • Authorization answers: can this user do this action?

Services can use Keycloak, Auth0, local login, or a custom identity system for authentication, then delegate authorization decisions to this RBAC service.


What This Is Not

This project is not:

  • an OAuth2/OIDC provider
  • an SSO server
  • a complete Keycloak replacement
  • a frontend authentication library
  • a policy engine like OPA

It focuses on centralized RBAC authorization decisions for backend services.

A common production setup would be:

Keycloak/Auth0/custom auth -> authenticate users
Go RBAC API -> authorize user actions

Architecture Overview

flowchart LR
    Client[Client / Frontend]
    Billing[Billing Service Example]
    RBAC[RBAC Service]
    DB[(PostgreSQL)]
    Admin[Admin / Backoffice]
    Keycloak[Keycloak or External IdP]

    Client -->|Authorization: session or JWT| Billing
    Billing -->|X-Service-Name + X-Service-Key| RBAC
    Billing -->|Authorize / SyncIdentity / IntrospectSession| RBAC
    RBAC --> DB
    Admin -->|Admin Session| RBAC
    Keycloak -->|sub/email/profile| Billing
    Billing -->|SyncIdentity| RBAC

External services should not access the RBAC database directly. They should use REST/gRPC APIs or pkg/rbacclient.

More detail:


Core Concepts

User

A local user or a synced external identity.

Examples:

admin@example.com
finance@example.com
viewer@example.com
keycloak-user@example.com
Role

A named group of permissions, optionally scoped to a service.

Examples:

global.super_admin
billing.finance_manager
billing.viewer
inventory.admin
Permission

An action on a resource inside a service.

Permission format:

service.resource.action

Examples:

billing.invoices.read
billing.invoices.approve
billing.invoices.delete
inventory.products.create
UserRole

An assignment that gives a user a role.

RolePermission

An assignment that gives a role a permission.

Service Client

An external backend service that is allowed to call runtime RBAC APIs.

Example:

billing-service
Audit Log

A record of important authorization, admin, session, service-client, and identity events.


Authentication vs Authorization

Authentication identifies the caller.

Authorization decides what the caller may do.

Keycloak or another external identity provider can authenticate users and issue JWTs. This RBAC service decides permissions.

A service validates the JWT, extracts identity claims such as sub and email, syncs the identity if needed, then calls RBAC to authorize an action.

Example:

User logs in with Keycloak
Frontend sends JWT to Billing Service
Billing Service validates JWT
Billing Service extracts subject/email
Billing Service calls RBAC SyncIdentity
Billing Service calls RBAC Authorize
RBAC returns allowed=true/false

Service-to-Service Authentication

External backend services call RBAC using service credentials:

X-Service-Name: billing-service
X-Service-Key: rbac_sk_...

These credentials authenticate the calling backend service, not the end user.

Never expose service keys to:

  • frontend apps
  • mobile apps
  • browsers
  • public clients
  • logs
  • GitHub

Service keys are backend secrets only.


Local Session Mode

Local login returns an opaque session string:

rbac_sess_...

API clients send it without a Bearer prefix:

Authorization: rbac_sess_...

Refresh uses the same Authorization session header.

Refresh is not admin-only. Any local user session can be refreshed while refresh_expires_at is valid.

Example:

curl -X POST 'http://localhost:8080/api/v1/auth/login' \
  -H 'Content-Type: application/json' \
  -d '{"email":"finance@example.com","password":"Finance@123456!"}'

Response:

{
  "success": true,
  "data": {
    "session": "rbac_sess_..."
  }
}

External Identity Mode

Services validate external JWTs themselves, then extract:

  • identity_provider
  • subject
  • email
  • username

The service calls SyncIdentity, then calls Authorize with identity_provider and subject.

Example authorization request:

{
  "identity_provider": "keycloak",
  "subject": "keycloak-user-sub",
  "service": "billing",
  "resource": "invoices",
  "action": "approve"
}

Billing Service Example

The billing service is a separate example service inside this repository.

It demonstrates how external services integrate with RBAC.

It:

  • does not access the RBAC database
  • does not import RBAC internal packages
  • only uses pkg/rbacclient
  • fails closed on missing auth or RBAC errors
  • checks RBAC for every protected invoice action

Billing routes:

GET    /api/v1/invoices
POST   /api/v1/invoices
POST   /api/v1/invoices/:id/approve
DELETE /api/v1/invoices/:id

Permission mapping:

GET    /api/v1/invoices              -> billing.invoices.read
POST   /api/v1/invoices              -> billing.invoices.create
POST   /api/v1/invoices/:id/approve  -> billing.invoices.approve
DELETE /api/v1/invoices/:id          -> billing.invoices.delete

Billing supports two local demo auth modes:

1. Local RBAC session mode
Authorization: rbac_sess_...

Billing introspects the session through RBAC, gets the user identity, then calls Authorize.

2. Explicit fake identity header mode
X-Identity-Provider: local
X-User-Subject: demo-finance-sub

This mode is for local demo only.

Requests without Authorization or explicit fake identity headers return 401 AUTH_REQUIRED.


Prerequisites

  • Go 1.24+
  • Docker
  • Docker Compose
  • PostgreSQL through docker-compose
  • jq
  • grpcurl
  • make
  • protoc and protobuf Go plugins, only if regenerating gRPC code
  • Postman, optional
  • Swagger UI / Swagger Editor / Redoc, optional

Install grpcurl on macOS:

brew install grpcurl

Install jq on macOS:

brew install jq

Demo Credentials

Seed creates local demo users.

User Email Password
Admin admin@example.com Admin@123456!
Finance finance@example.com Finance@123456!
Viewer viewer@example.com Viewer@123456!

Demo service client:

X-Service-Name: billing-service
X-Service-Key: rbac_sk_demo_billing_service_key

These credentials are for local development only.


Quick Start

Start dependencies and prepare data:

docker compose up -d
go run ./cmd/migrator
go run ./cmd/seed

If the database is reset or migrations change, run the migrator and seed again.

Terminal 1:

go run ./cmd/httpserver

Terminal 2:

go run ./cmd/grpcserver

Terminal 3:

go run ./examples/billing-service/cmd/server

Make Commands

If your local setup includes the provided Makefile, you can use:

make tidy
make fmt
make test
make migrate
make seed
make http
make grpc
make billing
make smoke

Equivalent manual commands:

go mod tidy
gofmt -w .
go test ./...
go run ./cmd/migrator
go run ./cmd/seed
go run ./cmd/httpserver
go run ./cmd/grpcserver
go run ./examples/billing-service/cmd/server
bash scripts/smoke-test.sh

Smoke Test

Run the HTTP server, gRPC server, and billing service in separate terminals, then:

bash scripts/smoke-test.sh

The smoke test covers:

  • admin login
  • protected admin API
  • REST authorize
  • gRPC authorize
  • finance login
  • finance session introspection
  • billing finance read
  • billing finance approve
  • billing finance delete denied
  • viewer login
  • billing viewer read
  • billing viewer approve denied
  • no-auth billing request denied
  • explicit fake header mode
  • local session refresh

Required tools:

  • jq
  • grpcurl

Expected result:

Smoke test passed.

REST Examples

Admin Login
SESSION=$(curl -s -X POST 'http://localhost:8080/api/v1/auth/login' \
  -H 'Content-Type: application/json' \
  -d '{"email":"admin@example.com","password":"Admin@123456!"}' | jq -r '.data.session')
List Users
curl 'http://localhost:8080/api/v1/users' \
  -H "Authorization: $SESSION"
Service Authorize
curl -X POST 'http://localhost:8080/api/v1/authorize' \
  -H 'Content-Type: application/json' \
  -H 'X-Service-Name: billing-service' \
  -H 'X-Service-Key: rbac_sk_demo_billing_service_key' \
  -d '{
    "identity_provider": "local",
    "subject": "demo-finance-sub",
    "service": "billing",
    "resource": "invoices",
    "action": "approve"
  }'
Introspect Local Session
FINANCE_SESSION=$(curl -s -X POST 'http://localhost:8080/api/v1/auth/login' \
  -H 'Content-Type: application/json' \
  -d '{"email":"finance@example.com","password":"Finance@123456!"}' | jq -r '.data.session')

curl -X POST 'http://localhost:8080/api/v1/auth/introspect' \
  -H 'X-Service-Name: billing-service' \
  -H 'X-Service-Key: rbac_sk_demo_billing_service_key' \
  -H "X-User-Session: $FINANCE_SESSION"
Billing Service Read Invoices
curl 'http://localhost:8081/api/v1/invoices' \
  -H "Authorization: $FINANCE_SESSION"

Postman

Import:

postman/go-rbac-api.postman_collection.json
postman/go-rbac-api.local.postman_environment.json

Recommended run order:

  1. Health / GET Health
  2. Auth - Sessions / Admin Login
  3. Auth - Sessions / Finance Login
  4. Auth - Sessions / Viewer Login
  5. Service Auth - Runtime APIs
  6. Admin folders
  7. Billing Service Demo
  8. Audit Logs
  9. Negative Tests
  10. Destructive / Run Last

Run login requests first so Postman stores session variables.

Run destructive requests last because they invalidate sessions.

gRPC tests are done separately through Postman gRPC request UI. See:

postman/grpc-postman-guide.md

gRPC Testing

The gRPC API is documented by proto files under:

api/proto

It can be tested with grpcurl or Postman gRPC.

List services:

grpcurl -plaintext localhost:9090 list

Describe RBAC service:

grpcurl -plaintext localhost:9090 describe rbac.v1.RBACService

Authorize example:

grpcurl -plaintext \
  -H 'x-service-name: billing-service' \
  -H 'x-service-key: rbac_sk_demo_billing_service_key' \
  -d '{
    "identity_provider": "local",
    "subject": "demo-finance-sub",
    "service": "billing",
    "resource": "invoices",
    "action": "approve"
  }' \
  localhost:9090 rbac.v1.RBACService/Authorize

Introspect session example:

FINANCE_SESSION=$(curl -s -X POST 'http://localhost:8080/api/v1/auth/login' \
  -H 'Content-Type: application/json' \
  -d '{"email":"finance@example.com","password":"Finance@123456!"}' | jq -r '.data.session')

grpcurl -plaintext \
  -H 'x-service-name: billing-service' \
  -H 'x-service-key: rbac_sk_demo_billing_service_key' \
  -d "{
    \"session\": \"$FINANCE_SESSION\"
  }" \
  localhost:9090 rbac.v1.RBACService/IntrospectSession

See:

postman/grpc-postman-guide.md
postman/grpc-message-examples.json

OpenAPI

The REST OpenAPI spec is available at:

docs/openapi.yaml

It can be opened in:

  • Swagger Editor
  • Swagger UI
  • Redoc
  • Postman import

Swagger / OpenAPI UI

After starting the HTTP server:

go run ./cmd/httpserver

Open:

http://localhost:8080/swagger

The OpenAPI spec is available at:

http://localhost:8080/swagger/openapi.yaml

Swagger UI is for REST API only.

gRPC is documented through proto files and tested with grpcurl or Postman gRPC.

Swagger routes are enabled by default for local development.

Disable Swagger routes:

SWAGGER_ENABLED=false go run ./cmd/httpserver

Project Structure

.
├── api
│   ├── gen
│   └── proto
├── cmd
│   ├── grpcserver
│   ├── httpserver
│   ├── migrator
│   └── seed
├── config
├── docs
├── examples
│   └── billing-service
├── internal
│   ├── model
│   ├── repository
│   ├── server
│   └── service
├── migrations
├── pkg
│   ├── apikey
│   ├── password
│   ├── rbacclient
│   ├── session
│   └── validator
├── postman
└── scripts

Testing

Run all Go tests:

go test ./...

Or:

make test

Run smoke test:

bash scripts/smoke-test.sh

Validate Postman JSON files:

jq . postman/go-rbac-api.postman_collection.json > /dev/null
jq . postman/go-rbac-api.local.postman_environment.json > /dev/null
jq . postman/grpc-message-examples.json > /dev/null

Security Notes

  • Service keys are hashed in the database.
  • Plain service keys are returned only once at creation time.
  • Passwords are hashed.
  • Sessions are opaque and hashed.
  • API responses do not expose password_hash.
  • Audit logs track important events.
  • Audit logs should never include secrets.
  • Billing service fails closed.
  • Requests without identity return 401.
  • Permission denied returns 403.
  • RBAC errors return 503.
  • Fake billing header mode is local demo only.
  • Never expose service keys to frontend/mobile/browser clients.
  • Store service keys in a secret manager or environment variables.
  • Use TLS in production.
  • Add API key rotation before production use.
  • Consider mTLS for service-to-service traffic.
  • Add rate limiting before public exposure.
  • External JWTs must be validated by the calling service before calling SyncIdentity or Authorize.

Roadmap

  • Admin UI
  • API key rotation
  • mTLS support
  • More integration tests
  • Docker Compose full stack
  • Kubernetes manifests
  • OpenTelemetry exporter setup
  • Swagger UI hosting controls for production
  • Keycloak integration example
  • CI/CD hardening
  • Deployment examples
  • More SDK examples
  • Optional admin CLI

License

MIT

Directories

Path Synopsis
api
cmd
grpcserver command
httpserver command
seed command
examples
internal
pkg
jwt

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL