Repository navigation
Expand file tree
/
Copy pathmodule.go
More file actions
469 lines (433 loc) · 15.7 KB
/
Copy pathmodule.go
File metadata and controls
469 lines (433 loc) · 15.7 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/*
* Copyright 2026 Swytch Labs BV
*
* This file is part of Swytch.
*
* Swytch is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Swytch is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Swytch. If not, see <https://www.gnu.org/licenses/>.
*/
// Package caddy provides Swytch storage for sharing TLS certificates across
// Caddy instances without an external database. An embedded Swytch node
// replicates TLS state peer-to-peer and coordinates ACME issuance locks.
package caddy
import (
"context"
"errors"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
caddycore "github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/certmagic"
"github.com/swytchdb/engine/beacon"
"github.com/swytchdb/engine/effects"
)
func init() {
caddycore.RegisterModule(SwytchStorage{})
}
// Subspace markers within a configured key_prefix. Splitting the
// caller-supplied prefix into a data subspace and a lock subspace stops
// a Caddy key like "l:foo" from colliding with the lock namespace.
const (
dataSubspace = "d:"
lockSubspace = "l:"
)
// Defaults for Caddyfile parsing.
const (
defaultClusterPort = 7380
defaultKeyPrefix = "__caddy:"
defaultLockTTL = 30 * time.Second
)
// SwytchStorage shares TLS certificates across Caddy instances without an external database.
//
// Each instance runs an embedded Swytch node. Together, they replicate TLS
// certificates, ACME account state, and OCSP staples peer-to-peer and coordinate
// ACME issuance locks through Swytch's serializable transactions.
//
// Point your Caddy instances at the same `join` DNS name and they'll
// form a cluster. `join` should resolve to reachable peer addresses:
// SRV records are preferred, otherwise A/AAAA records are used with
// `cluster_port`. `cluster_passphrase` must match across every node.
//
// Alternatively, set `connection_secret` to use Swytch Cloud for peer discovery
// and durable storage. This replaces `cluster_passphrase` and `join`;
// TLS state still replicates peer-to-peer.
type SwytchStorage struct {
// DataDir enables local durability by mirroring resident effects to disk.
// Empty disables local durability. Each node must use its own directory.
DataDir string `json:"data_dir,omitempty"`
// ClusterPassphrase enables cluster mode. Empty = single-node, no
// replication. Must match across every peer.
ClusterPassphrase string `json:"cluster_passphrase,omitempty"`
// ConnectionSecret enables Swytch Cloud durability. It is a self-contained
// cluster identity: the mTLS passphrase derives from it, so it is mutually
// exclusive with ClusterPassphrase, and peer discovery uses the cloud
// membership roster, so Join must be empty. When set, TLS state replicates
// peer-to-peer as usual and is additionally backed by Swytch Cloud, so a key
// evicted from every live peer is rehydrated from Cloud instead of lost.
ConnectionSecret string `json:"connection_secret,omitempty"`
// Join is the DNS name to discover peers.
// Empty is fine for single-node deployments.
Join string `json:"join,omitempty"`
// ClusterPort is the QUIC port for cluster traffic.
ClusterPort int `json:"cluster_port,omitempty"`
// ClusterAdvertise is the <host>:<port> this node advertises.
// Empty triggers auto-detection.
ClusterAdvertise string `json:"cluster_advertise,omitempty"`
// KeyPrefix scopes all keys this module reads/writes. Must live
// under the reserved `__caddy:` namespace so the effect cache's
// system-key pinning (which is __swytch:-only) does not pin
// potentially large certificate/lock data and defeat the cache's
// memory limit. Default `__caddy:`.
KeyPrefix string `json:"key_prefix,omitempty"`
// LockTTL is the duration after which a held lock is considered
// stale and may be stolen by another acquirer.
LockTTL caddycore.Duration `json:"lock_ttl,omitempty"`
}
// CaddyModule implements caddy.Module.
func (SwytchStorage) CaddyModule() caddycore.ModuleInfo {
return caddycore.ModuleInfo{
ID: "caddy.storage.swytch",
New: func() caddycore.Module { return new(SwytchStorage) },
}
}
// CertMagicStorage implements caddy.StorageConverter — returns a
// certmagic.Storage backed by the singleton runtime that Provision
// claimed a reference to.
func (s *SwytchStorage) CertMagicStorage() (certmagic.Storage, error) {
rt := singletonRuntime()
if rt == nil {
return nil, errors.New("swytch storage: not provisioned")
}
return &swytchStore{
runtime: rt.rt,
waiters: rt.waiters,
dataPrefix: s.KeyPrefix + dataSubspace,
lockPrefix: s.KeyPrefix + lockSubspace,
owner: ownerToken(rt.rt.Engine),
lockTTL: time.Duration(s.LockTTL),
}, nil
}
// Provision is called once per Caddy reload. It claims a reference on
// the process-wide swytch runtime, starting it on the first call.
//
// String fields are expanded through Caddy's Replacer so users can write
// `{env.SWYTCH_DATA_DIR}`, `{env.SWYTCH_PASS}`, or
// `{file./run/secrets/swytch}` in the Caddyfile.
func (s *SwytchStorage) Provision(ctx caddycore.Context) error {
repl := caddycore.NewReplacer()
if s.DataDir != "" {
dataDir, err := repl.ReplaceOrErr(s.DataDir, true, true)
if err != nil {
return fmt.Errorf("swytch storage: data_dir: %w", err)
}
s.DataDir = dataDir
}
s.ClusterPassphrase = repl.ReplaceAll(s.ClusterPassphrase, "")
s.ConnectionSecret = repl.ReplaceAll(s.ConnectionSecret, "")
s.Join = repl.ReplaceAll(s.Join, "")
s.ClusterAdvertise = repl.ReplaceAll(s.ClusterAdvertise, "")
s.KeyPrefix = repl.ReplaceAll(s.KeyPrefix, "")
if s.ConnectionSecret != "" {
// Swytch Cloud identity is self-contained: the mTLS passphrase derives
// from the secret, and peers come from the cloud roster. beacon.NewRuntime
// rejects both collisions, but catch them here so the operator gets a
// Caddyfile-level error instead of a runtime start failure.
if s.ClusterPassphrase != "" {
return fmt.Errorf("swytch storage: connection_secret is mutually exclusive with cluster_passphrase (the mTLS passphrase derives from the secret)")
}
if s.Join != "" {
return fmt.Errorf("swytch storage: connection_secret is mutually exclusive with join (peer discovery uses the cloud membership roster)")
}
}
if s.ClusterPort == 0 {
s.ClusterPort = defaultClusterPort
}
if s.KeyPrefix == "" {
s.KeyPrefix = defaultKeyPrefix
}
if !strings.HasPrefix(s.KeyPrefix, "__caddy:") {
return fmt.Errorf("swytch storage: key_prefix must live under __caddy: namespace, got %q", s.KeyPrefix)
}
if s.LockTTL == 0 {
s.LockTTL = caddycore.Duration(defaultLockTTL)
}
if time.Duration(s.LockTTL) < time.Second {
return fmt.Errorf("swytch storage: lock_ttl must be at least 1s, got %s", time.Duration(s.LockTTL))
}
cfg := beacon.RuntimeConfig{
DataDir: s.DataDir,
ClusterPassphrase: s.ClusterPassphrase,
ConnectionSecret: s.ConnectionSecret,
JoinAddr: s.Join,
ClusterPort: s.ClusterPort,
AdvertiseAddr: s.ClusterAdvertise,
Logger: ctx.Slogger(),
// Serve immediately; join the cluster in the background. Caddy gates
// its readiness (the systemd notify) on every module's Provision
// returning, so a blocking cluster join here stalls the whole
// server's startup — and times out under systemd — whenever a peer
// is unreachable. Solo-first + background convergence is the right
// trade for TLS storage, whose values are LWW cert state.
AsyncJoin: true,
}
if isConfigValidation() {
// `caddy validate` provisions every module (to surface config
// errors) but never starts serving and tears the config down
// immediately after. Standing up the cluster transport here would
// bind the QUIC port — colliding with an already-running node on the
// same host — and dial peers as a side effect of a read-only check.
// Caddy exposes no validate signal to modules, so drop into
// single-node mode: the engine still comes up (so storage-config
// validation succeeds) with no network activity. ConnectionSecret is
// cleared too — it derives the passphrase and starts CloudSync, which
// dials Swytch Cloud.
// Do not open or recover the live node's local mirror during validation.
cfg.DataDir = ""
cfg.ClusterPassphrase = ""
cfg.ConnectionSecret = ""
cfg.JoinAddr = ""
}
if err := claimRuntime(cfg, s.KeyPrefix); err != nil {
return fmt.Errorf("swytch storage: %w", err)
}
return nil
}
// isConfigValidation reports whether this process was invoked as
// `caddy validate`. Caddy runs module Provision during validation just as
// it does for a real run, but with no serving and an immediate teardown,
// and exposes no in-context flag distinguishing the two — so we inspect the
// subcommand. Defaults to false (serve) for any other or embedded
// invocation; an in-process admin-API validate is already safe because it
// reuses the running singleton runtime rather than binding a second one.
func isConfigValidation() bool {
return len(os.Args) > 1 && os.Args[1] == "validate"
}
// Cleanup releases this module's reference on the runtime.
func (s *SwytchStorage) Cleanup() error {
return releaseRuntime()
}
// UnmarshalCaddyfile parses the storage block:
//
// storage swytch {
// data_dir <path>
// cluster_passphrase <pass>
// connection_secret <secret>
// join <dns>
// cluster_port <num>
// cluster_advertise <addr:port>
// key_prefix <str>
// lock_ttl <duration>
// }
func (s *SwytchStorage) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if !d.Next() {
return d.Err("expected tokens")
}
if d.NextArg() {
return d.ArgErr()
}
for d.NextBlock(0) {
switch d.Val() {
case "data_dir":
if !d.NextArg() {
return d.ArgErr()
}
s.DataDir = d.Val()
case "cluster_passphrase":
if !d.NextArg() {
return d.ArgErr()
}
s.ClusterPassphrase = d.Val()
case "connection_secret":
if !d.NextArg() {
return d.ArgErr()
}
s.ConnectionSecret = d.Val()
case "join":
if !d.NextArg() {
return d.ArgErr()
}
s.Join = d.Val()
case "cluster_port":
if !d.NextArg() {
return d.ArgErr()
}
port, err := strconv.Atoi(d.Val())
if err != nil {
return d.Errf("invalid cluster_port %q: %v", d.Val(), err)
}
s.ClusterPort = port
case "cluster_advertise":
if !d.NextArg() {
return d.ArgErr()
}
s.ClusterAdvertise = d.Val()
case "key_prefix":
if !d.NextArg() {
return d.ArgErr()
}
s.KeyPrefix = d.Val()
case "lock_ttl":
if !d.NextArg() {
return d.ArgErr()
}
dur, err := caddycore.ParseDuration(d.Val())
if err != nil {
return d.Errf("invalid lock_ttl %q: %v", d.Val(), err)
}
s.LockTTL = caddycore.Duration(dur)
default:
return d.Errf("unrecognized swytch storage option %q", d.Val())
}
if d.NextArg() {
return d.ArgErr()
}
}
return nil
}
// sharedRuntime owns the long-lived engine that survives Caddy reloads.
// Lock-subspace callbacks are wired once at startup so all SwytchStorage
// instances share a single waiters registry.
type sharedRuntime struct {
rt *beacon.Runtime
waiters *waiters
cfg beacon.RuntimeConfig
keyPrefix string
refs int
}
var (
runtimeMu sync.Mutex
currentRuntime *sharedRuntime
)
// singletonRuntime returns the live shared runtime, if any.
func singletonRuntime() *sharedRuntime {
runtimeMu.Lock()
defer runtimeMu.Unlock()
return currentRuntime
}
// claimRuntime starts the runtime if it isn't running, otherwise checks
// that the requested config is compatible and bumps the refcount.
//
// Everything beacon-level is bound at NewRuntime time and has no live
// update path: the QUIC listener takes the port and advertise address,
// the TLS cert SAN bakes in the advertise address, and the cluster
// passphrase / join name configure peer discovery once. The data directory
// is also opened once at startup. So any change
// to those fields across a Caddy reload is rejected — the operator
// must restart the process. The `lock_ttl` field is per-storage (lives
// on swytchStore, not on the shared runtime) and DOES take effect on
// the next reload.
func claimRuntime(cfg beacon.RuntimeConfig, keyPrefix string) error {
runtimeMu.Lock()
defer runtimeMu.Unlock()
if currentRuntime != nil {
prev := currentRuntime.cfg
if prev.DataDir != cfg.DataDir {
return fmt.Errorf("data_dir cannot change without restarting the process")
}
if prev.ClusterPassphrase != cfg.ClusterPassphrase ||
prev.ConnectionSecret != cfg.ConnectionSecret ||
prev.JoinAddr != cfg.JoinAddr ||
prev.ClusterPort != cfg.ClusterPort ||
prev.AdvertiseAddr != cfg.AdvertiseAddr {
return fmt.Errorf("cluster configuration cannot change without restarting the process " +
"(passphrase/connection_secret/join/port/advertise differ from running instance)")
}
if currentRuntime.keyPrefix != keyPrefix {
return fmt.Errorf("key_prefix cannot change without restarting the process "+
"(was %q, now %q — would orphan existing keys)",
currentRuntime.keyPrefix, keyPrefix)
}
currentRuntime.refs++
return nil
}
// The runtime spans Caddy reloads; releaseRuntime stops it when the
// last reference is released, independently of any module's context.
rt, err := beacon.NewRuntime(context.Background(), cfg)
if err != nil {
return fmt.Errorf("start beacon runtime: %w", err)
}
sr := &sharedRuntime{
rt: rt,
waiters: newWaiters(),
cfg: cfg,
keyPrefix: keyPrefix,
refs: 1,
}
wireLockWakeups(rt.Engine, sr)
currentRuntime = sr
return nil
}
// releaseRuntime drops a reference and stops the runtime when the last
// reference goes away.
func releaseRuntime() error {
runtimeMu.Lock()
defer runtimeMu.Unlock()
if currentRuntime == nil {
return nil
}
currentRuntime.refs--
if currentRuntime.refs > 0 {
return nil
}
rt := currentRuntime.rt
currentRuntime = nil
return rt.Stop()
}
// wireLockWakeups chains lock-subspace wake-ups onto the engine's
// notification callbacks. Both OnKeyDataAdded and OnKeyDeleted fire for
// local writes (flushNonTx / flushTx) and for replicated effects
// (HandleRemote). Subscription on first GetSnapshot makes remote writes
// reach this node, so cross-cluster lock release is automatic.
//
// The engine guards its callback invocations with nil checks, so a
// replicated effect arriving in the window between NewRuntime returning
// and the assignments below is harmless — and waiters.subscribe can't
// run until Provision completes anyway.
func wireLockWakeups(eng *effects.Engine, sr *sharedRuntime) {
lockPrefix := sr.keyPrefix + lockSubspace
wakeIfLock := func(key string) {
if strings.HasPrefix(key, lockPrefix) {
sr.waiters.wake(key)
}
}
prevAdded := eng.OnKeyDataAdded
eng.OnKeyDataAdded = func(key string) {
if prevAdded != nil {
prevAdded(key)
}
wakeIfLock(key)
}
prevDeleted := eng.OnKeyDeleted
eng.OnKeyDeleted = func(key string) {
if prevDeleted != nil {
prevDeleted(key)
}
wakeIfLock(key)
}
}
// Interface guards
var (
_ caddycore.Module = (*SwytchStorage)(nil)
_ caddycore.Provisioner = (*SwytchStorage)(nil)
_ caddycore.CleanerUpper = (*SwytchStorage)(nil)
_ caddycore.StorageConverter = (*SwytchStorage)(nil)
_ caddyfile.Unmarshaler = (*SwytchStorage)(nil)
// Storage-side optional interfaces.
_ certmagic.Storage = (*swytchStore)(nil)
_ certmagic.TryLocker = (*swytchStore)(nil)
_ certmagic.LockLeaseRenewer = (*swytchStore)(nil)
)