Files
nexarch/dms/cmd/app/api.go
T
patrickandClaude Sonnet 5 b44c2df15f
CI / Core-Modul (Build/Vet/Test) (push) Canceled after 0s
CI / DMS Security-Test-Gate (AC5, Merge-Gate) (push) Canceled after 0s
CI / DMS-Modul (Lint/Build/Test/Coverage/Artefakt) (push) Canceled after 0s
CI / DMS-Modul Supply-Chain-Scan (govulncheck) (push) Canceled after 0s
CI / Web (dms-browser) (push) Canceled after 0s
CI / Web (pdf-viewer) (push) Canceled after 0s
CI / Web (shl) (push) Canceled after 0s
INT-01: rest-api v1 mit core-jwt-identitaet, openapi und einheitlichem fehlerformat
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 23:25:59 +02:00

177 lines
6.6 KiB
Go

package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/apiwiring"
dmscrypto "gitea.perlbach24.de/scripte/nexarch/dms/internal/crypto"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/jobqueue"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/moduleauth"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/policyclient"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/searchsync"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/storage"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/upload"
"gitea.perlbach24.de/scripte/nexarch/dms/internal/workerruntime"
)
type uploadStack struct {
svc *upload.Service
storage *storage.Service
crypto *dmscrypto.Service
}
func newUploadStack(pool *pgxpool.Pool, stagingDir string) uploadStack {
storageDir := os.Getenv("NEXARCH_DMS_APP_STORAGE_DIR")
signingSecret := os.Getenv("NEXARCH_DMS_APP_STORAGE_SIGNING_SECRET")
publicBaseURL := os.Getenv("NEXARCH_DMS_APP_STORAGE_PUBLIC_BASE_URL")
driver := storage.NewLocalDriver(storageDir, []byte(signingSecret), publicBaseURL, 0)
usageReporter := storage.NewHTTPUsageReporter(
os.Getenv("NEXARCH_DMS_APP_USAGE_ENDPOINT_URL"),
os.Getenv("NEXARCH_DMS_APP_USAGE_CLIENT_ID"),
os.Getenv("NEXARCH_DMS_APP_USAGE_CLIENT_SECRET"),
nil,
)
tenantSlug := os.Getenv("NEXARCH_DMS_APP_TENANT_SLUG")
storageSvc := storage.NewService(driver, usageReporter, tenantSlug)
kekProvider := dmscrypto.NewHTTPKEKProvider(
os.Getenv("NEXARCH_DMS_APP_KEK_ENDPOINT_URL"),
os.Getenv("NEXARCH_DMS_APP_KEK_CLIENT_ID"),
os.Getenv("NEXARCH_DMS_APP_KEK_CLIENT_SECRET"),
nil,
)
cryptoSvc := dmscrypto.NewService(kekProvider)
maxSize := int64(0)
if raw := os.Getenv("NEXARCH_DMS_APP_UPLOAD_MAX_SIZE_BYTES"); raw != "" {
if v, err := strconv.ParseInt(raw, 10, 64); err == nil {
maxSize = v
}
}
var allowedMimeTypes []string
if raw := os.Getenv("NEXARCH_DMS_APP_UPLOAD_ALLOWED_MIME_TYPES"); raw != "" {
allowedMimeTypes = strings.Split(raw, ",")
}
validator := upload.NewValidator(maxSize, allowedMimeTypes)
sessions := upload.NewSessionStore(pool)
staging := upload.NewStaging(stagingDir)
svc := upload.NewService(pool, sessions, staging, storageSvc, cryptoSvc, validator, tenantSlug)
enqueueTypes := []string{"thumbnail.generate", "ocr.plan", "einvoice.read"}
if os.Getenv("NEXARCH_DMS_APP_MANTICORE_ADDR") != "" {
enqueueTypes = append(enqueueTypes, searchsync.JobType)
}
if raw := os.Getenv("NEXARCH_DMS_APP_ENQUEUE_JOB_TYPES"); raw != "" {
enqueueTypes = strings.Split(raw, ",")
}
workerruntime.AttachEnqueuers(svc, pool, jobqueue.NewQueue(pool, 5*time.Minute), enqueueTypes)
hasScan := false
for _, jt := range enqueueTypes {
hasScan = hasScan || jt == "malwarescan.scan"
}
if !hasScan {
log.Print("dms-app: Virenscan wird beim Import nicht eingereiht (NEXARCH_DMS_APP_ENQUEUE_JOB_TYPES ohne malwarescan.scan): importierte Dokumente werden ungescannt angezeigt")
}
return uploadStack{svc: svc, storage: storageSvc, crypto: cryptoSvc}
}
func envSeconds(name string, def time.Duration) time.Duration {
if v, err := strconv.Atoi(os.Getenv(name)); err == nil && v > 0 {
return time.Duration(v) * time.Second
}
return def
}
func splitIDs(raw string) []string {
var out []string
for _, id := range strings.Split(raw, ",") {
if id = strings.TrimSpace(id); id != "" {
out = append(out, id)
}
}
return out
}
// setupAPI haengt alle dokument-eigenen Endpunkte ein (INT-01).
func setupAPI(api *http.ServeMux, dsn string) error {
pool, err := pgxpool.New(context.Background(), dsn)
if err != nil {
return fmt.Errorf("datenbankverbindung: %w", err)
}
stagingDir := os.Getenv("NEXARCH_DMS_APP_STAGING_DIR")
if stagingDir == "" {
stagingDir = os.Getenv("NEXARCH_DMS_APP_WATCHFOLDER_STAGING_DIR")
}
if stagingDir == "" {
return fmt.Errorf("NEXARCH_DMS_APP_STAGING_DIR nicht gesetzt")
}
stack := newUploadStack(pool, stagingDir)
return apiwiring.Mount(api, apiwiring.Deps{
Pool: pool,
Storage: stack.storage,
Crypto: stack.crypto,
TenantSlug: os.Getenv("NEXARCH_DMS_APP_TENANT_SLUG"),
Upload: stack.svc,
DownloadSecret: []byte(os.Getenv("NEXARCH_DMS_APP_DOWNLOAD_SIGNING_SECRET")),
DownloadTTL: envSeconds("NEXARCH_DMS_APP_DOWNLOAD_URL_TTL_SECONDS", 5*time.Minute),
TrashRetention: envSeconds("NEXARCH_DMS_APP_TRASH_RETENTION_SECONDS", 30*24*time.Hour),
Auditors: splitIDs(os.Getenv("NEXARCH_DMS_APP_AUDITOR_USER_IDS")),
SearchEnqueuer: searchEnqueuerFor(pool),
})
}
func searchEnqueuerFor(pool *pgxpool.Pool) *searchsync.Enqueuer {
if os.Getenv("NEXARCH_DMS_APP_MANTICORE_ADDR") == "" {
return nil
}
return &searchsync.Enqueuer{Queue: jobqueue.NewQueue(pool, 5*time.Minute)}
}
// identityChain baut aus der Umgebung die Authentifizierung und optional die
// Rechteentscheidung; ohne Identitaetsquelle startet der Dienst nicht.
func identityChain(next http.Handler, prefix string) (http.Handler, error) {
jwksURL := os.Getenv("NEXARCH_DMS_APP_CORE_JWKS_URL")
allowCaller := os.Getenv("NEXARCH_DMS_APP_ALLOW_CALLER_IDENTITY") == "true"
if jwksURL == "" && !allowCaller {
return nil, fmt.Errorf("keine identitaetsquelle: NEXARCH_DMS_APP_CORE_JWKS_URL setzen (oder uebergangsweise NEXARCH_DMS_APP_ALLOW_CALLER_IDENTITY=true)")
}
cfg := apiwiring.ChainConfig{Prefix: prefix, AllowCaller: allowCaller}
if policyURL := os.Getenv("NEXARCH_DMS_APP_POLICY_URL"); policyURL != "" {
token := os.Getenv("NEXARCH_DMS_APP_POLICY_SERVICE_TOKEN")
if token == "" {
return nil, fmt.Errorf("NEXARCH_DMS_APP_POLICY_URL ohne NEXARCH_DMS_APP_POLICY_SERVICE_TOKEN")
}
role := os.Getenv("NEXARCH_DMS_APP_POLICY_DEFAULT_ROLE")
if role == "" {
role = "user"
}
admins := map[string]bool{}
for _, id := range splitIDs(os.Getenv("NEXARCH_DMS_APP_ADMIN_USER_IDS")) {
admins[id] = true
}
cfg.Policy = &policyclient.EnforceConfig{
Client: policyclient.New(policyURL, token, envSeconds("NEXARCH_DMS_APP_POLICY_TTL_SECONDS", 30*time.Second)),
Prefix: prefix, DefaultRole: role, AdminRole: "tenant_admin", Admins: admins,
}
} else {
log.Print("dms-app: NEXARCH_DMS_APP_POLICY_URL nicht gesetzt, keine zentrale Rechteentscheidung (nur Eigentuemer-/Admin-Regeln des Guards)")
}
if jwksURL != "" {
cfg.Verifier = moduleauth.NewVerifier(envSeconds("NEXARCH_DMS_APP_JWKS_TTL_SECONDS", 5*time.Minute),
os.Getenv("NEXARCH_DMS_APP_TENANT_SLUG"), moduleauth.HTTPKeyFetcher(jwksURL, nil))
}
if allowCaller {
log.Print("dms-app: WARNUNG: caller-Parameter als Identitaet zugelassen (NEXARCH_DMS_APP_ALLOW_CALLER_IDENTITY=true), nicht authentifiziert")
}
return apiwiring.Chain(next, cfg), nil
}