-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
301 lines (265 loc) · 11.5 KB
/
Copy pathserver.go
File metadata and controls
301 lines (265 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package api
import (
"context"
"encoding/json"
"expvar"
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/forgekeep/nebula-mesh/internal/auth"
"github.com/forgekeep/nebula-mesh/internal/configgen"
"github.com/forgekeep/nebula-mesh/internal/enrollment"
"github.com/forgekeep/nebula-mesh/internal/keystore"
"github.com/forgekeep/nebula-mesh/internal/pki"
"github.com/forgekeep/nebula-mesh/internal/ratelimit"
"github.com/forgekeep/nebula-mesh/internal/store"
)
// Server is the HTTP API server.
type Server struct {
router chi.Router
store store.Store
caResolver *pki.CAResolver // resolves CAs by id from the store (multi-CA)
master *keystore.Master
defaultCAID string // id of the seeded default CA (when imported)
logger *slog.Logger
metrics *metrics
metricsEnabled bool
metricsRequireAuth bool
hostSeen HostSeenEmitter
limiter *ratelimit.Limiter
passwordPolicy auth.Policy
enrollmentTokenTTL time.Duration
events EventEmitter
clock func() time.Time // nil => time.Now; injectable for tests
}
// EventEmitter receives lifecycle events the handlers publish (host enrolled,
// blocked, deleted, cert rotated). The webhook.Dispatcher satisfies it; the
// interface keeps the api package free of a webhook import. A nil emitter (the
// default) makes emit a no-op.
type EventEmitter interface {
Emit(eventType string, data map[string]any)
}
// WithEventEmitter wires the outbound-event sink. Must be set before ServeHTTP.
func (s *Server) WithEventEmitter(e EventEmitter) { s.events = e }
// emit publishes a lifecycle event, nil-safe so handlers need no guard.
func (s *Server) emit(eventType string, data map[string]any) {
if s.events != nil {
s.events.Emit(eventType, data)
}
}
// WithClock overrides the server's wall clock. The default (nil) uses
// time.Now. Tests inject a controllable clock to exercise time-dependent paths
// (cert renewal, the rotation overlap window, poll timestamp skew) without
// real waits. Behavior is unchanged when unset.
func (s *Server) WithClock(fn func() time.Time) { s.clock = fn }
// now returns the current time from the injected clock, or time.Now.
func (s *Server) now() time.Time {
if s.clock != nil {
return s.clock()
}
return time.Now()
}
// NewServer creates a new API server.
func NewServer(s store.Store, logger *slog.Logger) *Server {
srv := &Server{
store: s,
logger: logger,
metrics: newMetrics(s),
metricsEnabled: true,
passwordPolicy: auth.Default(),
enrollmentTokenTTL: 24 * time.Hour,
}
srv.setupRoutes()
return srv
}
// WithEnrollmentTokenTTL sets the default enrollment-token TTL applied when
// the per-network override is unset. Default is 24h (ADR 0004 §7.1).
func (s *Server) WithEnrollmentTokenTTL(ttl time.Duration) {
if ttl > 0 {
s.enrollmentTokenTTL = ttl
}
}
// tokenTTLFor resolves the enrollment-token TTL for the network via the shared
// enrollment policy resolver. Order of precedence: per-network
// `enrollment_token_ttl` value in `network_config`, then the server-level
// default, then enrollment.DefaultTokenTTL.
func (s *Server) tokenTTLFor(ctx context.Context, networkID string) time.Duration {
return enrollment.TokenTTL(ctx, s.store, s.enrollmentTokenTTL, networkID)
}
// WithCAResolver attaches a CAResolver. Must be called before ServeHTTP.
// When set, host signing operations look up the CA by host.CAID; the
// legacy single-CA fallback is used only when host.CAID is empty.
func (s *Server) WithCAResolver(r *pki.CAResolver) {
s.caResolver = r
}
// WithMaster sets the master keystore used to create new CAs.
func (s *Server) WithMaster(m *keystore.Master) { s.master = m }
// RecordLogin records an operator login attempt against the server's
// Prometheus metrics. Exposed so the Web UI handlers (a separate package)
// can plumb their login outcomes through without an import cycle.
//
// Result is one of "ok" / "denied" / "error"; factor is one of
// "password" / "totp" / "recovery" / "oidc".
func (s *Server) RecordLogin(result, factor string) {
s.metrics.recordLogin(result, factor)
}
// WithRateLimiter installs a rate-limit middleware. nil disables limiting.
func (s *Server) WithRateLimiter(l *ratelimit.Limiter) {
s.limiter = l
s.setupRoutes()
}
// WithPasswordPolicy installs the policy applied to every server-side
// password-setting path (operator create, future operator reset).
func (s *Server) WithPasswordPolicy(p auth.Policy) { s.passwordPolicy = p }
// WithMetricsEnabled toggles the Prometheus /metrics endpoint. Disable in
// air-gapped deployments where the exporter is not scraped. Must be called
// before the router is exercised by ServeHTTP — re-wires the routes.
func (s *Server) WithMetricsEnabled(enabled bool) {
s.metricsEnabled = enabled
s.setupRoutes()
}
// WithMetricsRequireAuth gates /metrics behind bearer auth when true (#187).
// Must be called before the router is exercised — re-wires the routes.
func (s *Server) WithMetricsRequireAuth(require bool) {
s.metricsRequireAuth = require
s.setupRoutes()
}
// HostSeenEmitter is invoked after every successful agent poll so the Web
// UI can stream a live "host X just polled" event over its SSE endpoint.
// hostID is the DB id, lastSeen is the wall-clock timestamp the agent's
// poll was observed at, and networkID is included so per-network views can
// filter without an extra lookup.
type HostSeenEmitter func(hostID string, lastSeen time.Time, networkID string)
// WithHostSeenEmitter wires the callback the API server fires when an
// agent polls. Passing nil disables emission.
func (s *Server) WithHostSeenEmitter(emit HostSeenEmitter) {
s.hostSeen = emit
}
// WithDefaultCAID records the id of the CA seeded from the legacy
// on-disk material. Used when host.CAID matches this id to short-circuit
// to the legacy in-memory CAManager.
func (s *Server) WithDefaultCAID(id string) {
s.defaultCAID = id
}
func (s *Server) setupRoutes() {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Recoverer)
r.Use(requestLogger(s.logger))
r.Use(s.metricsMiddleware())
r.Use(maxBodySize(1 << 20)) // 1MB
// Public endpoints — operations and enrollment
r.Get("/health", s.handleHealth) // legacy alias
r.Get("/healthz", s.handleHealth)
r.Get("/readyz", s.handleReady)
// /metrics is bearer-gated by default (#262); set metrics.require_auth:
// false to expose it publicly on a trusted network. When gated it moves
// into the bearer-protected group below (#187) — the labels expose
// host/network/CA IDs and operational counters.
if s.metricsEnabled && !s.metricsRequireAuth {
r.Method("GET", "/metrics", promhttp.HandlerFor(s.metrics.reg, promhttp.HandlerOpts{}))
}
r.Group(func(r chi.Router) {
r.Use(s.rateLimitMiddleware("enroll"))
r.Post("/api/v1/enroll", s.handleEnroll)
})
r.Group(func(r chi.Router) {
r.Use(s.rateLimitMiddleware("agent_poll"))
r.Get("/api/v1/agent/updates", s.handleAgentUpdates)
})
// Protected endpoints (require API key)
r.Group(func(r chi.Router) {
r.Use(s.rateLimitMiddleware("api"))
r.Use(bearerAuth(s.store))
// Debug/diagnostics are bearer-gated (#187): expvar leaks memstats and
// the process command line, and /metrics labels expose host/network/CA
// IDs when require_auth is on.
r.Method("GET", "/debug/vars", expvar.Handler())
if s.metricsEnabled && s.metricsRequireAuth {
r.Method("GET", "/metrics", promhttp.HandlerFor(s.metrics.reg, promhttp.HandlerOpts{}))
}
r.Post("/api/v1/networks", s.handleCreateNetwork)
r.Get("/api/v1/networks", s.handleListNetworks)
r.Get("/api/v1/networks/{id}", s.handleGetNetwork)
r.Post("/api/v1/hosts", s.handleCreateHost)
r.Get("/api/v1/hosts", s.handleListHosts)
r.Get("/api/v1/hosts/{id}", s.handleGetHost)
r.Patch("/api/v1/hosts/{id}", s.handleUpdateHost)
r.Delete("/api/v1/hosts/{id}", s.handleDeleteHost)
r.Post("/api/v1/hosts/{id}/block", s.handleBlockHost)
r.Post("/api/v1/hosts/{id}/unblock", s.handleUnblockHost)
r.Post("/api/v1/hosts/{id}/enrollment-token", s.handleRegenerateEnrollmentToken)
r.Post("/api/v1/hosts/{id}/rotate-cert", s.handleRotateCert)
r.Post("/api/v1/hosts/{id}/reenroll", s.handleReenroll)
r.Post("/api/v1/hosts/{id}/mobile-bundle", s.handleMobileBundle)
r.Get("/api/v1/blocklist", s.handleGetBlocklist)
r.Get("/api/v1/networks/{id}/firewall", s.handleGetFirewall)
r.Put("/api/v1/networks/{id}/firewall", s.handleUpdateFirewall)
r.Get("/api/v1/audit-log", s.handleGetAuditLog)
r.Get("/api/v1/operators", s.handleListOperators)
r.Post("/api/v1/operators", s.handleCreateOperator)
r.Post("/api/v1/operators/{id}/disable", s.handleDisableOperator)
r.Post("/api/v1/operators/{id}/enable", s.handleEnableOperator)
r.Get("/api/v1/operators/{id}/api-keys", s.handleListOperatorAPIKeys)
r.Post("/api/v1/operators/{id}/api-keys", s.handleCreateOperatorAPIKey)
r.Delete("/api/v1/operators/{id}/api-keys/{kid}", s.handleRevokeOperatorAPIKey)
r.Get("/api/v1/cas", s.handleListCAs)
r.Post("/api/v1/cas", s.handleCreateCA)
r.Get("/api/v1/cas/{id}", s.handleGetCAByID)
r.Delete("/api/v1/cas/{id}", s.handleDeleteCA)
r.Post("/api/v1/cas/{id}/rotate", s.handleRotateCA)
r.Get("/api/v1/settings", s.handleGetSettings)
r.Patch("/api/v1/settings", s.handlePatchSettings)
r.Get("/api/v1/webhook-subscriptions", s.handleListWebhookSubscriptions)
r.Post("/api/v1/webhook-subscriptions", s.handleCreateWebhookSubscription)
r.Get("/api/v1/webhook-subscriptions/{id}", s.handleGetWebhookSubscription)
r.Patch("/api/v1/webhook-subscriptions/{id}", s.handleUpdateWebhookSubscription)
r.Delete("/api/v1/webhook-subscriptions/{id}", s.handleDeleteWebhookSubscription)
})
s.router = r
}
// ServeHTTP implements http.Handler.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
// handleReady reports readiness — verifies the database is reachable.
func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
ctx, cancel := contextWithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.store.Ping(ctx); err != nil {
// Log the cause server-side but do not echo internal error detail
// (DB path/driver) to unauthenticated readiness probes (#187).
s.logger.Error("readiness check failed", "error", err)
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "unavailable"})
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ready"})
}
// writeJSON sends a JSON response.
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
slog.Error("encode JSON response", "error", err)
}
}
// writeError sends a JSON error response.
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
// ConfigGenerator is used by handlers to generate Nebula configs.
// Kept separate to avoid circular deps.
var _ = configgen.GeneratorInput{} // compile-time check that configgen is importable
// contextWithTimeout wraps context.WithTimeout for tests that may pass a nil request context.
func contextWithTimeout(parent context.Context, d time.Duration) (context.Context, context.CancelFunc) {
if parent == nil {
parent = context.Background()
}
return context.WithTimeout(parent, d)
}