Initial import — snapshot from admin host /srv/gosec/gsc-ops-api

This repo had no version control prior to this commit. The import is a
straight snapshot of the working tree at 2026-05-03; the deployed
binary on fihelvop01 was being rebuilt from this source via `make
build` + scp into place, with no upstream review path.

The snapshot already includes one in-flight fix made on 2026-05-03 to
internal/service/persona.go:GetSelfModel — the handler queried
`source` and `strength` columns plus an `is_active = true` filter on
persona.persona_commitments, none of which exist on that table (its
shape is session-bound commitments with `status`, `commitment_meta`,
etc.). The query returned a 500 every time SynapseHub bootstrapped a
persona's self-model, dropping the IdentityConstraints / Commitments /
ConscienceStandards layer from the assembled prompt. The patched
query reads existing columns only (commitment_text, commitment_type),
filters on `status='active'`, and synthesises Source="learned" /
Strength=1.0 to keep the SelfModel response shape stable for callers.

Verified live: `GET /api/v1/personas/70f7cfd9-.../self-model` now
returns 200 with `{identityConstraints:[],commitments:[],
conscienceStandards:[]}` instead of 500.

Future changes go through PRs against this repo — no more bin-only
deploys.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Claude (gsc-ops-api init)
2026-05-03 20:06:02 +02:00
commit 3847eb2036
68 changed files with 12982 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
package middleware
import (
"crypto/subtle"
"github.com/gofiber/fiber/v2"
"github.com/gosec/gsc-ops-api/pkg/types"
)
const APIKeyHeader = "X-API-Key"
// APIKey validates the X-API-Key header against configured keys
func APIKey(validKeys []string) fiber.Handler {
return func(c *fiber.Ctx) error {
key := c.Get(APIKeyHeader)
if key == "" {
apiErr := types.NewUnauthorized("Missing API key")
return c.Status(apiErr.Status).JSON(types.NewErrorResponse(apiErr, GetRequestID(c)))
}
valid := false
for _, vk := range validKeys {
if subtle.ConstantTimeCompare([]byte(key), []byte(vk)) == 1 {
valid = true
break
}
}
if !valid {
apiErr := types.NewUnauthorized("Invalid API key")
return c.Status(apiErr.Status).JSON(types.NewErrorResponse(apiErr, GetRequestID(c)))
}
return c.Next()
}
}

View File

@@ -0,0 +1,68 @@
package middleware
import (
"strings"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
)
// JWTClaims contains extracted claims from the JWT
type JWTClaims struct {
Subject string `json:"sub"`
Email string `json:"email"`
Name string `json:"name"`
TenantID string `json:"tenantId"`
}
// JWTExtract extracts JWT claims from the Authorization header for audit context.
// This middleware does NOT validate the JWT — it only extracts claims.
// Authentication is handled by mTLS + API key. JWT is optional passthrough.
func JWTExtract() fiber.Handler {
return func(c *fiber.Ctx) error {
auth := c.Get("Authorization")
if auth == "" || !strings.HasPrefix(auth, "Bearer ") {
return c.Next()
}
tokenStr := strings.TrimPrefix(auth, "Bearer ")
// Parse without validation — we trust the API key for auth
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
token, _, err := parser.ParseUnverified(tokenStr, jwt.MapClaims{})
if err != nil {
// Invalid JWT — ignore, not blocking
return c.Next()
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return c.Next()
}
jwtClaims := &JWTClaims{}
if sub, ok := claims["sub"].(string); ok {
jwtClaims.Subject = sub
}
if email, ok := claims["email"].(string); ok {
jwtClaims.Email = email
}
if name, ok := claims["name"].(string); ok {
jwtClaims.Name = name
}
if tid, ok := claims["tenantId"].(string); ok {
jwtClaims.TenantID = tid
}
c.Locals("jwtClaims", jwtClaims)
return c.Next()
}
}
// GetJWTClaims retrieves JWT claims from context
func GetJWTClaims(c *fiber.Ctx) *JWTClaims {
if claims, ok := c.Locals("jwtClaims").(*JWTClaims); ok {
return claims
}
return nil
}

View File

@@ -0,0 +1,39 @@
package middleware
import (
"time"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog"
)
// Logging provides structured request logging via zerolog
func Logging(logger zerolog.Logger) fiber.Handler {
return func(c *fiber.Ctx) error {
start := time.Now()
err := c.Next()
duration := time.Since(start)
status := c.Response().StatusCode()
event := logger.Info()
if status >= 500 {
event = logger.Error()
} else if status >= 400 {
event = logger.Warn()
}
event.
Str("method", c.Method()).
Str("path", c.Path()).
Int("status", status).
Dur("duration", duration).
Str("requestId", GetRequestID(c)).
Str("ip", c.IP()).
Str("userAgent", c.Get("User-Agent")).
Msg("request")
return err
}
}

View File

@@ -0,0 +1,29 @@
package middleware
import (
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
)
const RequestIDHeader = "X-Request-ID"
// RequestID generates or extracts a request ID for each request
func RequestID() fiber.Handler {
return func(c *fiber.Ctx) error {
reqID := c.Get(RequestIDHeader)
if reqID == "" {
reqID = uuid.New().String()
}
c.Locals("requestId", reqID)
c.Set(RequestIDHeader, reqID)
return c.Next()
}
}
// GetRequestID extracts the request ID from context
func GetRequestID(c *fiber.Ctx) string {
if id, ok := c.Locals("requestId").(string); ok {
return id
}
return ""
}