systemforge

module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT

README

SystemForge

Go CI Go Lint Go SAST Docs DevGuide Visualization License

SystemForge is a batteries-included Go platform module providing reusable identity, session, authorization, and feature flags for multi-tenant SaaS applications. Think of it as Django/Laravel-style conveniences for Go.

Within the plexusone org, SystemForge is the shared identity/session/authorization foundation the Forge platform family (ActionForge, AgentForge, DashForge) builds on — one contract instead of each app inventing its own. See INIT-SYSTEMFORGE-001 for the unified authorization vocabulary, IAM console, and shell composition work this drives.

Moved from github.com/grokify/systemforge to github.com/plexusone/systemforge in v0.10.0 — the old path still resolves via GitHub's repository-transfer redirect for existing pins, but won't receive new tags. See the v0.10.0 release notes for the full migration.

v0.11.0 renamed coreauth → systemauth, cf_ tables/API-keys → sf_, and unified the principal-link field to sf_principal_id — a hard cutover with no dual-name compatibility. See the v0.11.0 release notes for the full migration.

Features

Identity Module
  • 👤 Users - Email, password hash (Argon2id), platform admin flag
  • 🏢 Organizations - Multi-tenant with name, slug, plan, settings
  • 🔗 Memberships - User-org relationships with flexible roles
  • 👑 Ownership Transfer - Transaction-safe organization ownership transfers
  • 🔐 OAuth Accounts - External OAuth provider links (GitHub, Google)
  • 🌐 Social Login - GitHub/Google login served centrally by SystemAuth (__Host-sf_login session, provider-subject account linking, logout, consent)
  • 🤝 Relying Parties - identity/relyingparty: apps federate to SystemAuth via OIDC (ID-token/JWKS verification, sub → sf_principal_id linking), mount the /bff/* cookie-session surface, and accept SystemAuth JWTs or API keys from programmatic clients
  • 🔑 API Keys - Machine-to-machine authentication with scopes
OAuth 2.0 Server (Fosite)
  • 📜 Authorization Code + PKCE - Secure browser-based auth
  • 🤖 Client Credentials - Service-to-service auth
  • 🔄 Refresh Token - Rotation with reuse detection (family revocation) and absolute lifetime
  • 🪪 OpenID Connect - RS256 ID tokens, UserInfo, JWKS with key ID, optional JWT access tokens
  • 📝 JWT Bearer (RFC 7523) - Service account authentication
  • ⚙️ Service Accounts - Non-human identities with RSA/EC key pairs
  • 🔍 Token Introspection & Revocation - RFC 7662/7009
Session Module
  • 🎫 JWT Service - Access/refresh token generation with HS256/RS256/ES256
  • 🔒 DPoP (RFC 9449) - Proof-of-possession token binding
  • 🖥️ BFF Pattern - Backend for Frontend with server-side sessions
  • 💾 OmniStorage Backend - Production session storage with Redis, size limits, and observability
  • 🛡️ Middleware - JWT Bearer and API key authentication
Authorization Module
  • 👥 RBAC/ReBAC - Role and relationship-based access control
  • 🔐 SpiceDB Provider - Zanzibar-style fine-grained authorization
  • ✨ Simple Provider - Lightweight permission checking
  • 🧩 Query Policy Bridge - Use authz.Authorizer to feed safe query languages such as GrokifyQL
  • 🚧 HTTP Middleware - Route protection for Chi and stdlib
Observability
  • 📊 Vendor-Agnostic - Integrates with omniobserve
  • 🔌 Multiple Backends - OTLP, Datadog, New Relic, Dynatrace
  • 📈 Pre-Built Metrics - SystemAuth, rate limiting, JWT/API key validation
  • 🔍 Distributed Tracing - Automatic span creation for OAuth flows
  • 📝 slog Integration - Trace-correlated structured logging
Marketplace
  • 🛒 Listings - Product catalog with tiers and pricing
  • 💳 Stripe Integration - Subscription billing and webhooks
  • 📜 Licensing - Per-seat, unlimited, and time-limited licenses
  • 👥 Seat Management - Assign and revoke user access
Feature Flags
  • 🚩 Flag Engine - Boolean, percentage, and user list flags
  • 🏢 Organization Scoping - Per-org flag evaluation
  • 💾 In-Memory Store - Development and testing
Row-Level Security (RLS)
  • 🗃️ PostgreSQL RLS - Policy generation and session variables
  • 🏠 Tenant Isolation - Multi-tenant data separation
  • 🔗 Ent Integration - Transaction helpers with tenant context
Multi-App Platform
  • 🏗️ Multi-App Server - Run multiple SaaS apps on shared infrastructure
  • 📦 Schema Isolation - Each app gets its own PostgreSQL schema
  • 🔀 X-App-ID Routing - Header-based request routing to app backends
  • 🔌 AppBackend Interface - Composable app registration with lifecycle hooks
  • 💾 Shared Caching - Redis or in-memory with app-scoped prefixes

Installation

go get github.com/plexusone/systemforge

Quick Start

Using Identity Schemas

SystemForge provides Ent schemas with cf_ table prefix for side-by-side migration.

Direct Schema Usage
package main

import (
    "context"

    "github.com/plexusone/systemforge/identity/ent"
    _ "github.com/lib/pq"
)

func main() {
    client, err := ent.Open("postgres", "postgres://...")
    if err != nil {
        panic(err)
    }
    defer client.Close()

    // Run migrations
    if err := client.Schema.Create(context.Background()); err != nil {
        panic(err)
    }

    // Create a user
    user, err := client.User.Create().
        SetEmail("user@example.com").
        SetName("Example User").
        Save(context.Background())
}

Compose SystemForge mixins into your own schemas:

// your-app/ent/schema/user.go
package schema

import (
    "entgo.io/ent"
    "entgo.io/ent/schema/field"
    cfmixin "github.com/plexusone/systemforge/identity/ent/mixin"
)

type User struct {
    ent.Schema
}

func (User) Mixin() []ent.Mixin {
    return []ent.Mixin{
        cfmixin.UUIDMixin{},      // UUID primary key
        cfmixin.TimestampMixin{}, // created_at, updated_at
    }
}

func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("username").Unique(),
        // App-specific fields...
    }
}
JWT Authentication
import (
    "github.com/plexusone/systemforge/session/jwt"
    "github.com/plexusone/systemforge/session/middleware"
)

// Create JWT service
svc, err := jwt.NewService(&jwt.Config{
    Secret:             []byte("your-secret-key"),
    AccessTokenExpiry:  15 * time.Minute,
    RefreshTokenExpiry: 7 * 24 * time.Hour,
    Issuer:             "your-app",
})

// Generate tokens
pair, err := svc.GenerateTokenPair(userID, email, name)

// Middleware for protected routes
r.Use(middleware.JWT(svc))
DPoP Token Binding

DPoP (RFC 9449) lives in the standalone github.com/grokify/goauth/dpop package (moved out of SystemForge in v0.9.0). See the goauth DPoP guide.

import "github.com/grokify/goauth/dpop"

// Generate DPoP key pair (BFF side)
keyPair, err := dpop.GenerateKeyPair()

// Create proof for API request
proof, err := dpop.CreateProofWithOptions(keyPair, "POST", "https://api.example.com/data", dpop.ProofOptions{
    AccessToken: accessToken,
})

// Verify proof (API side)
verifier := dpop.NewVerifier(dpop.VerificationConfig{
    MaxAge: 5 * time.Minute,
})
result, err := verifier.Verify(proofJWT, dpop.VerificationRequest{
    Method:      "POST",
    URI:         "https://api.example.com/data",
    AccessToken: accessToken,
})
BFF Pattern
import "github.com/plexusone/systemforge/session/bff"

// Create BFF proxy
proxy := bff.NewProxy(bff.ProxyConfig{
    Backend:        "https://api.internal.example.com",
    AllowedOrigins: []string{"https://app.example.com"},
    SessionStore:   bff.NewMemoryStore(),
})

// Mount proxy handler
r.Handle("/api/*", proxy.Handler())
Authorization
import (
    "github.com/plexusone/systemforge/authz"
    "github.com/plexusone/systemforge/authz/simple"
)

// Create authorization provider
provider := simple.NewProvider(simple.Config{
    AllowOwnerFullAccess:  true,
    AllowPlatformAdminAll: true,
})

// Add role permissions
provider.AddRolePermissions("admin", []string{
    "users:read", "users:write",
    "settings:read", "settings:write",
})
provider.AddRolePermissions("member", []string{
    "users:read",
})

// Use middleware
mw := authz.NewMiddleware(provider)
r.With(mw.RequireAction(authz.ResourceType("users"), authz.ActionRead)).Get("/users", listUsers)

Module Structure

github.com/plexusone/systemforge/
├── identity/              # User, Organization, Membership, OAuth
│   ├── ent/schema/        # Ent schemas with cf_ prefix
│   ├── apikey/            # API key service
│   ├── oauth/             # OAuth 2.0 server (Fosite)
│   ├── oauthclient/       # GitHub/Google/SystemAuth OAuth client primitives
│   ├── relyingparty/      # OIDC relying party for apps federating to SystemAuth (/bff, bearer)
│   ├── systemauth/        # SystemAuth OAuth 2.0 / OIDC server (social login, userinfo; cmd/systemauth binary)
│   ├── password.go        # Argon2id hashing
│   └── service.go         # Identity service interfaces
│
├── session/               # Session management
│   ├── jwt/               # JWT service with DPoP claims
│   ├── bff/               # Backend for Frontend pattern (DPoP via goauth/dpop)
│   ├── middleware/        # Auth middleware
│   └── ratelimit/         # Rate limiting with observability
│
├── observability/         # Vendor-agnostic observability
│   ├── observability.go   # Core wrapper for omniobserve
│   ├── middleware.go      # HTTP request tracing
│   └── metrics.go         # Pre-defined metric names
│
├── authz/                 # Authorization
│   ├── simple/            # Simple RBAC provider
│   ├── spicedb/           # SpiceDB ReBAC provider
│   ├── noop/              # No-op syncer for testing
│   ├── providertest/      # Provider test suite
│   └── middleware.go      # HTTP middleware
│
├── marketplace/           # SaaS marketplace
│   ├── listing.go         # Product listings and tiers
│   ├── license.go         # License management
│   ├── subscription.go    # Subscription handling
│   └── stripe/            # Stripe billing integration
│
├── featureflags/          # Feature flag engine
│   └── stores/            # Flag stores
│
├── multiapp/              # Multi-app platform
│   ├── server.go          # Multi-app server with routing
│   ├── app.go             # AppBackend interface
│   ├── database.go        # Schema-per-app isolation
│   ├── cache.go           # Redis and memory cache
│   └── context.go         # App context helpers
│
└── rls/                   # PostgreSQL Row-Level Security
    ├── rls.go             # Policy generation
    └── middleware.go      # HTTP middleware

Design Decisions

Decision Choice Rationale
Table prefix sf_ Avoids conflicts, enables side-by-side migration
Role storage String field Apps define own vocabularies (owner/admin/member)
OAuth pattern Fosite library Production-ready, RFC-compliant OAuth 2.0
Refresh tokens Database-backed Enables revocation, theft detection
Primary keys UUID Modern, distributed-friendly
Password hashing Argon2id OWASP recommended, memory-hard

Database Tables

SystemForge creates the following tables (all prefixed with sf_):

Table Description
sf_users User accounts
sf_organizations Multi-tenant organizations
sf_memberships User-organization relationships
sf_oauth_accounts External OAuth provider links
sf_external_identities Upstream login identities (GitHub/Google) linked to principals
sf_refresh_tokens JWT refresh token tracking
sf_api_keys Developer API keys
sf_oauth_apps OAuth client applications
sf_oauth_app_secrets Client secrets (hashed)
sf_oauth_tokens Issued OAuth tokens
sf_oauth_auth_codes Authorization codes
sf_oauth_consents User consent records
sf_login_sessions SystemAuth login sessions (token hashes only)
sf_login_states In-flight upstream social logins (single-use)
sf_consent_grants Consent-page grants per principal, client and scope
sf_service_accounts Non-human identities
sf_service_account_key_pairs RSA/EC key pairs

Applications federating to SystemAuth create two more tables in their own database with identity/relyingparty/pgstore.EnsureSchema:

Table Description
sf_rp_sessions Relying-party browser sessions (token hashes; SystemAuth tokens encrypted at rest)
sf_rp_login_states In-flight logins to SystemAuth (single-use; nonce and PKCE verifier encrypted)

Migration Strategy

For existing apps, SystemForge supports side-by-side migration:

  1. Side-by-Side: Create sf_* tables alongside existing tables
  2. Dual-Write: Write to both old and new tables
  3. Cutover: Switch reads to SystemForge tables
  4. Cleanup: Remove old tables

Documentation

Full documentation is available via MkDocs:

# Install MkDocs
pip install mkdocs mkdocs-material

# Serve locally
mkdocs serve

# Build static site
mkdocs build

Relevant authorization guides:

  • docs/authorization/spicedb-setup.md
  • docs/authorization/spicedb-schema.md
  • docs/authorization/integration.md
  • docs/authorization/query-policy-engines.md

Contributing

Contributions are welcome! Please read the contributing guidelines before submitting PRs.

License

MIT License - see LICENSE file for details.

Directories

Path Synopsis
Package authz provides a pluggable authorization interface for SystemForge applications.
Package authz provides a pluggable authorization interface for SystemForge applications.
noop
Package noop provides a no-operation authorization syncer for deployments that don't require authorization backend synchronization.
Package noop provides a no-operation authorization syncer for deployments that don't require authorization backend synchronization.
providertest
Package providertest provides conformance tests for authz.Provider implementations.
Package providertest provides conformance tests for authz.Provider implementations.
simple
Package simple provides a simple role-based authorization provider.
Package simple provides a simple role-based authorization provider.
spicedb
Package spicedb provides SpiceDB-based authorization for SystemForge.
Package spicedb provides SpiceDB-based authorization for SystemForge.
cmd
systemauth command
Package main provides a standalone SystemAuth OAuth 2.0 / OpenID Connect server.
Package main provides a standalone SystemAuth OAuth 2.0 / OpenID Connect server.
Package compose defines SystemForge's composition runtime: the Feature and Registrar contracts that let capabilities — a single feature slice or a whole application — be composed into one binary or split across services without changing the capabilities themselves.
Package compose defines SystemForge's composition runtime: the Feature and Registrar contracts that let capabilities — a single feature slice or a whole application — be composed into one binary or split across services without changing the capabilities themselves.
Package contract implements the SystemForge Product Contract specification, providing standardized endpoints for integration with SystemAuth federation.
Package contract implements the SystemForge Product Contract specification, providing standardized endpoints for integration with SystemAuth federation.
audit
Package audit provides audit event storage and streaming functionality.
Package audit provides audit event storage and streaming functionality.
Package coreapi provides API management capabilities including rate limiting, API key management, and usage tracking.
Package coreapi provides API management capabilities including rate limiting, API key management, and usage tracking.
Package featureflags provides a feature flag engine for SystemForge applications.
Package featureflags provides a feature flag engine for SystemForge applications.
stores
Package stores provides feature flag storage implementations.
Package stores provides feature flag storage implementations.
Package identity provides identity management for SystemForge applications.
Package identity provides identity management for SystemForge applications.
apikey
Package apikey provides API key generation, validation, and management.
Package apikey provides API key generation, validation, and management.
credential
Package credential provides credential management for principals.
Package credential provides credential management for principals.
delegation
Package delegation provides delegation chain management for agent principals.
Package delegation provides delegation chain management for agent principals.
ent
ent/mixin
Package mixin provides reusable Ent schema mixins for SystemForge entities.
Package mixin provides reusable Ent schema mixins for SystemForge entities.
ent/schema
Package schema provides Ent schema definitions for SystemForge identity management.
Package schema provides Ent schema definitions for SystemForge identity management.
invite
Package invite provides organization invitation management.
Package invite provides organization invitation management.
oauthclient
Package oauthclient is SystemForge's single sanctioned package for talking to upstream social-login providers (GitHub, Google) and to SystemAuth as an OAuth client.
Package oauthclient is SystemForge's single sanctioned package for talking to upstream social-login providers (GitHub, Google) and to SystemAuth as an OAuth client.
organization
Package organization provides organization management services.
Package organization provides organization management services.
principal
Package principal provides the core principal abstraction for identity management.
Package principal provides the core principal abstraction for identity management.
relyingparty
Package relyingparty lets an application federate its login to SystemAuth as an OpenID Connect relying party, so the application never implements GitHub/Google login itself.
Package relyingparty lets an application federate its login to SystemAuth as an OpenID Connect relying party, so the application never implements GitHub/Google login itself.
relyingparty/pgstore
Package pgstore provides PostgreSQL-backed relying-party stores: a relyingparty.SessionStore and a relyingparty.LoginStateStore that survive restarts and are shared by every instance of the application.
Package pgstore provides PostgreSQL-backed relying-party stores: a relyingparty.SessionStore and a relyingparty.LoginStateStore that survive restarts and are shared by every instance of the application.
relyingparty/storetest
Package storetest is a conformance suite for relying-party stores.
Package storetest is a conformance suite for relying-party stores.
scim
Package scim provides SCIM 2.0 (RFC 7643/7644) support for identity provisioning.
Package scim provides SCIM 2.0 (RFC 7643/7644) support for identity provisioning.
scim/filter
Package filter provides SCIM filter expression parsing and evaluation.
Package filter provides SCIM filter expression parsing and evaluation.
scim/mapper
Package mapper provides mapping between SCIM resources and SystemForge entities.
Package mapper provides mapping between SCIM resources and SystemForge entities.
scim/patch
Package patch provides SCIM PATCH operation handling.
Package patch provides SCIM PATCH operation handling.
scim/schema
Package schema provides SCIM schema definitions for discovery endpoints.
Package schema provides SCIM schema definitions for discovery endpoints.
scim/store
Package store provides SCIM Store implementations.
Package store provides SCIM Store implementations.
security
Package security provides security features for identity management including account lockout protection against brute-force attacks.
Package security provides security features for identity management including account lockout protection against brute-force attacks.
signup
Package signup provides user signup and personal organization creation.
Package signup provides user signup and personal organization creation.
systemauth/schema
Package schema provides the embedded JSON Schema for SystemAuth configuration.
Package schema provides the embedded JSON Schema for SystemAuth configuration.
systemauth/storetest
Package storetest is a conformance suite for SystemAuth social login stores.
Package storetest is a conformance suite for SystemAuth social login stores.
token
Package token provides token management for principals.
Package token provides token management for principals.
internal
pgtest
Package pgtest provides throwaway PostgreSQL databases for integration tests.
Package pgtest provides throwaway PostgreSQL databases for integration tests.
Package marketplace provides a unified framework for two-sided marketplace applications including listings, licenses, and subscriptions.
Package marketplace provides a unified framework for two-sided marketplace applications including listings, licenses, and subscriptions.
stripe
Package stripe provides Stripe integration for the marketplace.
Package stripe provides Stripe integration for the marketplace.
Package multiapp provides infrastructure for running multiple apps on shared or dedicated backend infrastructure.
Package multiapp provides infrastructure for running multiple apps on shared or dedicated backend infrastructure.
example
Package example provides a minimal example of implementing the AppBackend interface.
Package example provides a minimal example of implementing the AppBackend interface.
example/cmd command
Package main demonstrates running apps in single-app and multi-app modes.
Package main demonstrates running apps in single-app and multi-app modes.
Package observability provides vendor-agnostic observability for SystemForge applications.
Package observability provides vendor-agnostic observability for SystemForge applications.
Package productgraph provides a client for sending events to ProductGraph and middleware for frontend-backend correlation.
Package productgraph provides a client for sending events to ProductGraph and middleware for frontend-backend correlation.
Package rls provides PostgreSQL Row-Level Security helpers for SystemForge.
Package rls provides PostgreSQL Row-Level Security helpers for SystemForge.
session
bff
Package bff implements the Backend for Frontend (BFF) pattern for secure session management.
Package bff implements the Backend for Frontend (BFF) pattern for secure session management.
invalidation
Package invalidation provides session tracking and invalidation for user sessions.
Package invalidation provides session tracking and invalidation for user sessions.
jwt
Package jwt provides JWT token generation and validation for SystemForge applications.
Package jwt provides JWT token generation and validation for SystemForge applications.
middleware
Package middleware provides HTTP middleware for authentication and authorization.
Package middleware provides HTTP middleware for authentication and authorization.
ratelimit
Package ratelimit provides HTTP rate limiting middleware with support for per-principal and per-application rate limits.
Package ratelimit provides HTTP rate limiting middleware with support for per-principal and per-application rate limits.

Jump to

Keyboard shortcuts

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