Files
orca/internal/daemon/server.go
T
ciagent 31ccb52114 feat(P08): mTLS daemon + transport + cert CLI + doctor
Wave B/C/D of P01 mTLS implementation.

- internal/audit/audit.go — thin wrapper around engine.Audit for
  cert/handshake events (Action* and Result* constants; REQ-038).
- internal/certpaths/ — extracted path constants out of cli to break
  the cli<->doctor import cycle; cli re-exports the helpers for
  backward compat.
- internal/security/ca.go — public WriteCert/WriteKey helpers (0600
  for keys, 0644 for certs; REQ-033); used by the cert CLI and
  integration test.
- internal/daemon/tls.go — mTLS server with GetCertificate hot-swap
  callback. Plaintext HTTP remains the default for v0.1 compat;
  StartMTLS() flips the server into mTLS mode.
- internal/daemon/server.go — adds mtls *MTLSState field; MTLSActive()
  getter for health endpoints.
- internal/transport/mtls.go — mTLS client with VerifyPeerCertificate
  for pinned peer identity; DialContext for raw TLS.
- internal/transport/handshake_log.go — structured slog helpers for
  handshake ok/fail (REQ-038 fields: event, result, peer, cert_fp).
- internal/cli/cert.go — orca cert {ca-init,gen,show,renew,fingerprint}
  subcommands; file mode enforcement at every entry; redacted cert
  show (REQ-035).
- internal/cli/doctor.go — orca doctor {cert,network,db} subcommands
  (REQ-032); --json output supported.
- internal/cli/node.go — adds --ca-fingerprint to orca node join
  (REQ-026); fails fast on mismatch.
- internal/doctor/doctor.go — 6 checks: cert.ca, cert.server,
  cert.expiry, cert.fingerprint, network stub, db stub.
- internal/doctor/doctor_test.go — happy + sad path coverage.
- internal/security/integration_test.go — end-to-end: CA-init, CSR
  generation, mTLS handshake, mismatch failure, rotation alarm,
  redaction, file mode enforcement.

All tests pass with -race; gofmt -l . clean; go vet ./... clean.

---ci---
project: orca
phase: 8
milestone: v0.2
status: execute
---/ci---
2026-06-03 21:33:41 +00:00

127 lines
3.7 KiB
Go

// Package daemon implements the orca HTTP daemon.
//
// The daemon exposes health endpoints (/healthz, /readyz), a status endpoint
// (/v1/status), and a v1 resource API for jobs, nodes, and tasks. All handlers
// follow the project conventions:
//
// - context.Context propagated to all I/O
// - errors wrapped with %w
// - structured JSON via writeJSON
// - no secrets in logs
// - input validation on path/query/body
package daemon
import (
"context"
"database/sql"
"errors"
"log/slog"
"net/http"
"sync/atomic"
"time"
)
// Server is the orca HTTP daemon. It holds shared dependencies and lifecycle
// state. Construct it with NewServer, then call Start/Shutdown.
type Server struct {
db *sql.DB
log *slog.Logger
addr string
ready atomic.Bool
httpServer *http.Server
// mtls is non-nil after StartMTLS has been called; nil otherwise.
// Plaintext HTTP and mTLS are mutually exclusive — a Server is
// either in plaintext mode (default, v0.1 compat) or mTLS mode
// (v0.2 P01 forward).
mtls *MTLSState
}
// Options configures a new Server.
type Options struct {
DB *sql.DB
Log *slog.Logger
Addr string
Actor string // used for audit logging from API requests
}
// NewServer constructs a Server with the default mux and route table.
func NewServer(opts Options) *Server {
if opts.Log == nil {
opts.Log = slog.Default()
}
if opts.Addr == "" {
opts.Addr = ":8080"
}
if opts.Actor == "" {
opts.Actor = "api"
}
s := &Server{
db: opts.DB,
log: opts.Log,
addr: opts.Addr,
}
s.httpServer = &http.Server{
Addr: opts.Addr,
Handler: s.mux(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
return s
}
// Addr returns the configured listen address.
func (s *Server) Addr() string { return s.addr }
// MarkReady flips the readiness flag to true. The /readyz endpoint returns
// 200 only when this flag is set AND the database is reachable.
func (s *Server) MarkReady() { s.ready.Store(true) }
// MarkNotReady flips the readiness flag to false. Called at shutdown start
// so load balancers stop routing traffic.
func (s *Server) MarkNotReady() { s.ready.Store(false) }
// Ready reports the current readiness flag.
func (s *Server) Ready() bool { return s.ready.Load() }
// mux builds the route table. Handlers are split across files:
// - health.go /healthz, /readyz, /v1/status
// - jobs_handler.go /v1/jobs/*
// - nodes_handler.go /v1/nodes/*
// - tasks_handler.go /v1/tasks/*
func (s *Server) mux() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/healthz", s.handleHealthz)
mux.HandleFunc("/readyz", s.handleReadyz)
mux.HandleFunc("/v1/status", s.handleStatus)
mux.HandleFunc("/v1/jobs", s.handleJobsCollection)
mux.HandleFunc("/v1/jobs/", s.handleJobsItem)
mux.HandleFunc("/v1/nodes", s.handleNodesCollection)
mux.HandleFunc("/v1/tasks", s.handleTasksCollection)
return loggingMiddleware(s.log, mux)
}
// Start runs the HTTP server. Returns http.ErrServerClosed on clean shutdown.
func (s *Server) Start() error {
s.log.Info("daemon starting",
slog.String("addr", s.addr),
slog.String("component", "daemon"))
return s.httpServer.ListenAndServe()
}
// Shutdown gracefully stops the server, bounded by ctx. It also flips the
// readiness flag to false so /readyz returns 503 immediately.
func (s *Server) Shutdown(ctx context.Context) error {
s.MarkNotReady()
s.log.Info("daemon shutting down", slog.String("component", "daemon"))
return s.httpServer.Shutdown(ctx)
}
// IsShutdownErr reports whether err is the expected error from a stopped server.
func IsShutdownErr(err error) bool {
return errors.Is(err, http.ErrServerClosed)
}