GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — openctem/server at main · openctemio/openctem

Expand file tree

/

server

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
/

server

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
api
api
 
 
changelog.d
changelog.d
 
 
cmd
cmd
 
 
configs
configs
 
 
deploy
deploy
 
 
docs
docs
 
 
examples/custombuild
examples/custombuild
 
 
internal
internal
 
 
migrations
migrations
 
 
pkg
pkg
 
 
proto
proto
 
 
scripts
scripts
 
 
tests
tests
 
 
tools
tools
 
 
.air.toml
.air.toml
 
 
.betterleaks.toml
.betterleaks.toml
 
 
.dockerignore
.dockerignore
 
 
.env.example
.env.example
 
 
.gitignore
.gitignore
 
 
.gitleaksignore
.gitleaksignore
 
 
.golangci.yml
.golangci.yml
 
 
.pre-commit-config.yaml
.pre-commit-config.yaml
 
 
CHANGELOG.md
CHANGELOG.md
 
 
CLAUDE.md
CLAUDE.md
 
 
Dockerfile
Dockerfile
 
 
Dockerfile.migrations
Dockerfile.migrations
 
 
Dockerfile.seed
Dockerfile.seed
 
 
LICENSE
LICENSE
 
 
Makefile
Makefile
 
 
README.md
README.md
 
 
docker-compose.dev.yml
docker-compose.dev.yml
 
 
docker-compose.yml
docker-compose.yml
 
 
go.mod
go.mod
 
 
go.sum
go.sum
 
 
trivy.yaml
trivy.yaml
 
 

README.md

Outline

OpenCTEM API

Go Version PostgreSQL Redis License: GPL-3.0

Backend API for the OpenCTEM Continuous Threat Exposure Management platform. Built with Go, PostgreSQL, and Redis using Clean Architecture (DDD).

Features

Asset Management (35 asset types)

  • External Attack Surface: Domains, Subdomains, Certificates, IPs
  • Applications: Websites, APIs, Mobile Apps, Services
  • Cloud: Cloud Accounts, Compute, Storage, Serverless, Container Registry
  • Infrastructure: Hosts, Containers, Databases, Networks, VPCs, K8s
  • Identity: IAM Users, IAM Roles, Service Accounts
  • Code: Git Repositories
  • Recon: HTTP Services, Open Ports, Discovered URLs

Security & Findings

  • Vulnerability management with severity-based prioritization
  • CVSS scoring and exploit maturity tracking
  • Finding lifecycle: Open > Confirmed > Fix Applied > Resolved
  • AI-powered triage (Claude, OpenAI, Gemini)
  • SLA policy enforcement with escalation

Scanning

  • 30+ scanner integrations via Agent SDK (Nuclei, Trivy, Semgrep, Betterleaks, Nmap, etc.)
  • Pipeline-based scan orchestration with multi-step workflows
  • Platform agents with lease-based lifecycle management
  • Bootstrap token authentication for agent self-registration

Access Control

  • 2-layer RBAC: Permissions (what you can DO) + Groups (what you can SEE)
  • 164 granular permissions across all modules
  • Real-time permission sync via Redis
  • OAuth2 (Google, GitHub, Microsoft) + OIDC (Keycloak)

Integrations

  • ITSM: Jira
  • SCM: GitHub, GitLab (repository sync, credential import)
  • Notifications: Slack, Teams, Telegram, Email, Webhooks
  • Compliance: PCI-DSS, HIPAA, SOC2, GDPR, ISO27001, NIST, FedRAMP, CCPA

Observability

  • Prometheus metrics (HTTP, Redis, Pipeline, Scan, Agent, Finding)
  • Structured logging (slog)
  • Audit logging with tenant isolation

Tech Stack

Component Technology
Language Go 1.27+
Router Chi (net/http compatible)
Database PostgreSQL 16, 17 or 18 (17 recommended)
Cache/Queue Redis 7 (Asynq)
Auth JWT (local) / OAuth2 / OIDC
Metrics Prometheus client_golang
Encryption AES-256-GCM

Project Structure

server/
├── cmd/
│   ├── server/                # Main API server
│   └── bootstrap-admin/       # Creates the first platform administrators and organization
├── internal/
│   ├── app/                   # Application services (business logic, 40+ services)
│   ├── config/                # Configuration loading
│   └── infra/                 # Infrastructure adapters
│       ├── http/              # Handlers (200+ endpoints), middleware, routes
│       ├── postgres/          # Repository implementations (30+ repos)
│       ├── redis/             # Cache, sessions, job queue
│       ├── notifier/          # Slack, Teams, Telegram, Email, Webhook
│       ├── llm/               # AI triage (Claude, OpenAI, Gemini)
│       ├── scm/               # GitHub, GitLab integration
│       ├── controller/        # Background jobs
│       └── telemetry/         # Tracing
├── pkg/
│   ├── domain/                # Domain models (35+ entities)
│   │   ├── asset/             # Asset entity, risk scoring, value objects
│   │   ├── vulnerability/     # Finding, approval, suppression
│   │   ├── scan/              # Scan orchestration
│   │   ├── agent/             # Platform agents, bootstrap tokens
│   │   ├── workflow/          # Workflow engine
│   │   ├── pipeline/          # Scan pipelines
│   │   └── ...                # 25+ more domains
│   ├── jwt/                   # Token generation/validation
│   ├── crypto/                # AES-256-GCM encryption
│   ├── validator/             # Input validation + SSRF protection
│   ├── password/              # bcrypt hashing
│   └── pagination/            # Cursor/offset pagination
├── migrations/                # 156 sequential migrations
├── tests/
│   ├── unit/                  # Unit tests (100+ files)
│   ├── integration/           # Integration tests
│   └── repository/            # Repository tests
└── docs/                      # Architecture docs

Quick Start

Prerequisites

  • Go 1.27+
  • Docker & Docker Compose
  • PostgreSQL 16, 17 or 18; 17 recommended (or use Docker, which ships 17)
  • Redis 7 (or use Docker)

Development

# Start dependencies
docker compose up -d postgres redis

# Run with hot reload
make dev

# Or start everything
docker compose up

Production

The production stack exposes ONE port: a gateway on 443 (HTTPS) fronts both the web UI and this API, like any appliance. The API, the web UI, Postgres and Redis are never published.

cd deploy
./setup.sh ctem.example.com   # writes .env: release of this checkout (a vX.Y.Z tag; --version vX.Y.Z from a branch), host name, generated secrets (--acme [email protected] for Let's Encrypt)
docker compose run --rm --no-deps api -check-config   # validate the settings, start nothing
docker compose up -d

The API runs in production mode unless told otherwise: an unset APP_ENV means production, which refuses to start without TLS to Postgres and Redis, strong secrets and the other production checks. Secrets that still hold example-file text (openssl rand -hex 32, <CHANGE_ME...>) are refused in every mode. server -check-config reports the first problem without starting or connecting to anything (exit 0 = valid). Back the stack up with deploy/backup.sh (backup, verify, restore <dir> --yes); set BACKUP_AGE_RECIPIENT to an age public key to encrypt every backup file (verify and restore then need BACKUP_AGE_IDENTITY), otherwise backups are plaintext and the script warns.

TLS modes (OPENCTEM_TLS_MODE): internal (own CA, for LAN/IP installs; the root for sensors is exported to deploy/ca/), acme (Let's Encrypt), files (your certificate), http (only behind your own TLS proxy, explicit opt-in). Routing table and details: deploy/gateway/Caddyfile and the docs page "Exposing OpenCTEM: one HTTPS port". Sensors use API_URL=https://<host>.

Verify

curl --cacert deploy/ca/openctem-root-ca.crt https://<host>/health
# {"status":"healthy"}

# Readiness and metrics are not public; ask from inside the network:
docker compose -f deploy/docker-compose.yml exec api wget -qO- localhost:8080/ready

Environment Variables

Required (Production)

Variable Description
DB_PASSWORD PostgreSQL password
REDIS_PASSWORD Redis password
APP_ENCRYPTION_KEY AES-256 key (64 hex chars: openssl rand -hex 32)
CORS_ALLOWED_ORIGINS Allowed CORS origins
DB_SSLMODE require or verify-full (the default disable is refused in production)
REDIS_TLS_ENABLED true; with a private CA also REDIS_TLS_CA_FILE

AUTH_JWT_SECRET (session signing secret) is optional: unset, it is derived from APP_ENCRYPTION_KEY. Set it (at least 64 characters) to rotate the two independently.

APP_ENV defaults to production when unset; set APP_ENV=development explicitly for local development (.env.example does).

Optional

Variable Default Description
AUTH_PROVIDER local Auth provider: local, oidc, hybrid (the default was oidc up to v0.8.0)
SIGNUP_MODE disabled The sign-up ceiling, which no API can change: disabled (only the platform administrator creates organizations; nobody else can create an account without an invitation or their organization's SSO), domain (sign-up only for addresses on an organization's verified domain) or open (anyone may sign up and create an organization; needs the platform e-mail, and in production the Turnstile keys). The console (System > Sign-up) switches sign-up within it. Replaces TENANT_CREATION_MODE.
AI_PLATFORM_PROVIDER — AI triage: claude, openai, gemini
RATE_LIMIT_RPS 100 Rate limit (requests/second)
LOG_LEVEL info Log level: debug, info, warn, error

Production User Management

Public registration and self-service organizations are off by default:

SIGNUP_MODE=disabled    # No public sign-up; the console cannot open it (the default)

Platform e-mail (set-password links, invitations, verification) is set in the admin console, System > E-mail; headless installs pass BOOTSTRAP_SMTP_* to bootstrap-admin.

Flow: the platform administrator creates the organization and its owner (bootstrap-admin -org-* at install, then the console) → the owner sets a password through a one-time link → the owner (or an organization admin) creates users, invites them, or configures SSO.

# API: Create invitation (requires team:admin permission)
POST /api/v1/tenants/{tenant}/invitations
{"email": "[email protected]", "role_ids": ["00000000-0000-0000-0000-000000000003"]}

# System roles (pre-seeded, shared across all tenants):
#   00000000-...-000000000001  owner       (full access)
#   00000000-...-000000000002  admin       (all except team:delete)
#   00000000-...-000000000003  member      (read/write, no delete)
#   00000000-...-000000000004  viewer      (read-only)

# User accepts invitation (the token travels in the body, never in the URL)
POST /api/v1/invitations/accept   {"token": "..."}

Per-Tenant SMTP

Each tenant can configure its own SMTP server for outgoing emails (invitations, notifications). If not configured, the platform e-mail (admin console, System > E-mail) is used as fallback.

Setup via email integration:

POST /api/v1/integrations
{
  "name": "Company Email",
  "category": "notification",
  "provider": "email",
  "auth_type": "basic",
  "metadata": {
    "smtp_host": "smtp.company.com",
    "smtp_port": 587,
    "smtp_user": "[email protected]",
    "smtp_password": "app-password",
    "smtp_from": "[email protected]",
    "smtp_from_name": "Security Team",
    "smtp_tls": true
  }
}

Resolution order:

  1. Tenant has active email integration → use tenant SMTP
  2. No tenant integration → use the platform e-mail (admin console, System > E-mail)
  3. No system SMTP → emails skipped (logged as warning)

Credentials are encrypted at rest using AES-256-GCM.

Commands

make dev             # Run with hot reload (Air)
make build           # Build production binary
make test            # Run all tests
make lint            # Run golangci-lint (30 linters)
make fmt             # Format code (goimports)
make migrate-up      # Run database migrations
make migrate-down    # Rollback last migration
make security-scan   # Run security scan (semgrep + betterleaks + trivy)

API Endpoints (200+)

Core

Method Endpoint Description
GET /health Liveness check
GET /ready Readiness check (DB + Redis)
GET /metrics Prometheus metrics
GET /docs API documentation (not served in production; platform administrators use /api/v1/admin/docs)
GET /openapi.yaml The OpenAPI spec (shipped in the release images; signed-in users only in production)

Assets

Method Endpoint Description
GET /api/v1/assets List assets (paginated, 10+ filters)
POST /api/v1/assets Create asset
GET /api/v1/assets/{id} Get asset (tenant-scoped)
PUT /api/v1/assets/{id} Update asset
DELETE /api/v1/assets/{id} Delete asset
GET /api/v1/assets/stats Aggregated statistics (SQL)
POST /api/v1/assets/bulk/status Atomic bulk status update
POST /api/v1/assets/{id}/scan Trigger scan

Findings, Scans, Integrations, Compliance, Pentest, Workflows...

See /docs endpoint for complete OpenAPI documentation.

Platform Agents

Method Endpoint Description
POST /api/v1/platform/register Agent self-registration
PUT /api/v1/platform/lease Renew agent lease
POST /api/v1/platform/poll Long-poll for jobs
POST /api/v1/platform/jobs/{id}/result Submit job results

Deployment

Docker Compose

# 1. Go to the production stack (server/deploy/ in the openctem repository)
cd deploy

# 2. Create the environment file: OPENCTEM_VERSION (required, no default),
#    OPENCTEM_HOSTNAME, OPENCTEM_PUBLIC_URL, OPENCTEM_TLS_MODE and every
#    secret marked required
cp .env.example .env

# 3. Start the gateway (443), web, API, Postgres and Redis
docker compose up -d

# 4. Create the first admin, its break-glass backup and the first organization
#    (see Bootstrap Admin below)
docker compose run --rm bootstrap-admin [email protected] [email protected] \
  -org-name="Example Corp" [email protected]

Kubernetes (Helm)

# 1. Create namespace and secrets
kubectl create namespace openctem

kubectl create secret generic openctem-api-secrets \
  --namespace openctem \
  --from-literal=APP_ENCRYPTION_KEY=$(openssl rand -hex 32) \
  --from-literal=DB_USER=openctem \
  --from-literal=DB_PASSWORD=$(openssl rand -hex 24) \
  --from-literal=DB_NAME=openctem

kubectl create secret generic openctem-db-secrets \
  --namespace openctem \
  --from-literal=username=openctem \
  --from-literal=password=<same-db-password>

kubectl create secret generic openctem-redis-secrets \
  --namespace openctem \
  --from-literal=password=$(openssl rand -hex 24)

# 2. Install with the bootstrap Job (first-time only); chart: openctemio/helm-charts
helm install openctem openctem/openctem \
  --namespace openctem \
  --set api.bootstrapAdmin.enabled=true \
  --set [email protected] \
  --set [email protected] \
  --set api.bootstrapAdmin.org.name="Example Corp" \
  --set [email protected]

# 3. Read the temporary passwords and the owner's set-password link (shown
#    once), then delete the Job. The Job is kept after it succeeds for this.
kubectl logs job/openctem-api-bootstrap-admin -n openctem
kubectl delete job/openctem-api-bootstrap-admin -n openctem

Bootstrap Admin (First-time Setup)

The first platform administrators must be created with bootstrap-admin — there is no default account. One run creates two (RFC-022 revision 4):

  • the primary administrator (-email, role -role, default super_admin);
  • a break-glass backup (-backup-email), always a super_admin. It is a local account that can never be bound to the platform identity provider and is exempt from "require IdP", so the console stays reachable when the IdP is down. Every sign-in with it writes a high-severity console.break_glass_sign_in audit row, a WARN log line with alert=break_glass_sign_in (alert on it), and emails the other administrators through the system SMTP sender (SMTP_*). Test it periodically (at least every 90 days): sign in with it, then another super admin confirms the test on the console's Administrators page. Store its credentials offline.

Each gets a new sign-in account (an email that already has one is refused) and a temporary password printed once. On first use the administrator signs in on /login, enrolls an authenticator app when opening the admin console, and must change the temporary password before anything else. Administrators have no API keys. The run is idempotent: existing administrators are reported and left alone, so re-running with -backup-email adds a backup to an existing install. -backup-email is required unless -no-backup is passed explicitly.

A platform administrator belongs to no organization, so the same run can also create the first organization (-org-name, -org-owner-email; the slug is derived from the name unless -org-slug is given). It goes through the same service as the console's Organizations → Create: the owner's membership and role are written with the organization, and tenant.created / user.created are audited in it. A new owner account gets a one-time set-password link (valid 24 hours): emailed when SMTP is configured (SMTP_*), otherwise printed once (as $SMTP_BASE_URL/set-password#token=...). An organization whose slug exists is reported and left alone. The owner's email must not be an administrator's.

First install, end to end:

  1. Run the migrations (compose and the Helm chart do it before the API starts).
  2. bootstrap-admin -email … -backup-email … -org-name … -org-owner-email …
  3. The administrator signs in on /login with the temporary password, changes it, and enrolls an authenticator app when opening the console at /admin. Store the break-glass credentials offline.
  4. The organization owner opens the set-password link, chooses a password and signs in on /login.
  5. The owner creates or invites users and configures the organization; the administrator configures the organization's SSO from the console and creates further organizations there.

Docker Compose:

# A one-off container with the schema owner's credentials from .env (the
# running api container never has them)
docker compose run --rm bootstrap-admin \
  [email protected] [email protected] \
  -org-name="Example Corp" [email protected]

Kubernetes (during helm install):

helm install openctem openctem/openctem \
  --set api.bootstrapAdmin.enabled=true \
  --set [email protected] \
  --set [email protected] \
  --set api.bootstrapAdmin.org.name="Example Corp" \
  --set [email protected]

Kubernetes (after install):

kubectl exec -it deploy/openctem-api -n openctem -- \
  /app/bootstrap-admin [email protected] [email protected]

Standalone binary (the database URL from the environment, never on the command line, where ps and the shell history would show the password):

read -rs DATABASE_URL && export DATABASE_URL   # postgres://user:pass@host:5432/openctem?sslmode=require
./bootstrap-admin [email protected] [email protected]

The temporary passwords (and a set-password link) are printed once, so the command refuses to run when stdout is not a terminal unless -print-secrets is given; the Compose service has no container log. Every administrator it creates, replaces or links is recorded in the administrators' hash-chained audit log in the same transaction (admin.created, admin.replaced, admin.relinked; actor bootstrap-admin, with the OS user and host), and the other active administrators are emailed when the platform e-mail is configured.

Flag Env Var Description
-db DATABASE_URL or DB_HOST/DB_USER/DB_PASSWORD/DB_NAME Database connection: use the env vars; the flag is for tests only (it puts the password in ps)
-email ADMIN_EMAIL Admin email (required)
-name ADMIN_NAME Display name (defaults to email prefix)
-role — super_admin, ops_admin, readonly (primary only). A new admin defaults to super_admin; -force keeps the existing role unless -role is given
-backup-email ADMIN_BACKUP_EMAIL Break-glass backup administrator (required unless -no-backup)
-backup-name ADMIN_BACKUP_NAME Backup display name (defaults to email prefix)
-no-backup — Skip the break-glass backup (not recommended; prints a warning)
-force — Delete and re-create the existing -email admin and its sign-in account (new temporary password, authenticator removed). Never touches the backup. Keeps the role unless -role is given; refuses to bring back an inactive admin without -role, and to leave no active super admin. Prints the role and status before and after
-force-backup — The same for the existing break-glass backup (-backup-email)
-yes — Confirm -force/-force-backup without a terminal; on a terminal the email is typed back instead
-print-secrets — Print the one-time credentials even when stdout is not a terminal (a file, a pipe, a job log)
-link — Link an administrator created before sign-in accounts (v0.8 and older) to a new one and reactivate it (keeps role and authenticator)
-org-name ORG_NAME Create the first organization (needs -org-owner-email)
-org-slug ORG_SLUG Its URL slug (derived from the name when empty)
-org-owner-email ORG_OWNER_EMAIL Its owner; a new account gets a one-time set-password link
-org-owner-name ORG_OWNER_NAME Display name for a new owner account

Security

  • SSRF protection on all URL inputs (webhooks, integrations, template sources)
  • OAuth redirect URI whitelist validation
  • Command injection prevention in scan executors (ExtraArgs validation)
  • Tenant isolation on all 200+ endpoints (WHERE tenant_id = ?)
  • Password reset token single-use enforcement
  • X-Forwarded header injection prevention
  • AES-256-GCM credential encryption
  • bcrypt password hashing (cost=12)
  • Constant-time token comparison
  • Rate limiting on all endpoints

License

GNU General Public License v3.0 (GPL-3.0). See LICENSE.

Legal

  • Terms of Service
  • Privacy Policy
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.