-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
877 lines (817 loc) · 31.4 KB
/
Copy pathhandlers.go
File metadata and controls
877 lines (817 loc) · 31.4 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"net/http"
"sort"
"strings"
"time"
"github.com/airplanes-live/image-webconfig/internal/auth"
"github.com/airplanes-live/image-webconfig/internal/feedmeta"
"github.com/airplanes-live/image-webconfig/internal/hardware"
"github.com/airplanes-live/image-webconfig/internal/identity"
"github.com/airplanes-live/image-webconfig/internal/logs"
"github.com/airplanes-live/image-webconfig/internal/status"
)
// MinPasswordLen is the minimum length we accept for setup / change-password.
const MinPasswordLen = 12
// stateResponse is returned by GET /api/state.
type stateResponse struct {
State string `json:"state"`
}
const (
stateUninitialized = "uninitialized"
stateInitialized = "initialized"
stateCorrupt = "corrupt"
)
// detectState stat's the password store. Empty/missing → uninitialized.
// Present and parseable → initialized. Present but malformed → corrupt
// (handled by handlers as a hard 500 with a recovery hint).
func (s *Server) detectState() string {
exists, err := s.store.Exists()
if err != nil || !exists {
return stateUninitialized
}
phc, err := s.store.Read()
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return stateUninitialized
}
return stateCorrupt
}
// Cheap structural check (no argon2 invocation): PHC starts with the
// expected prefix and has the expected number of $ separators.
if !strings.HasPrefix(phc, "$argon2id$v=19$") || strings.Count(phc, "$") != 5 {
return stateCorrupt
}
return stateInitialized
}
func (s *Server) handleState(w http.ResponseWriter, _ *http.Request) {
st := s.detectState()
if st == stateCorrupt {
writeJSONError(w, http.StatusInternalServerError,
"password file is corrupt; recover via /boot/firmware/airplanes-reset-password")
return
}
writeJSON(w, http.StatusOK, stateResponse{State: st})
}
// passwordRequest covers POST /api/setup and the new-password half of
// POST /api/auth/login and POST /api/auth/password.
type passwordRequest struct {
Password string `json:"password"`
}
type changePasswordRequest struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
if st := s.detectState(); st != stateUninitialized {
writeJSONError(w, http.StatusConflict, "webconfig already initialized")
return
}
var req passwordRequest
if err := readJSON(w, r, &req); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
if len(req.Password) < MinPasswordLen {
writeJSONError(w, http.StatusBadRequest,
"password must be at least 12 characters")
return
}
var phc string
var hashErr error
if err := s.guard.RunCtx(r.Context(), func() {
phc, hashErr = auth.Hash(req.Password, s.argon2Params)
}); err != nil {
writeJSONError(w, http.StatusServiceUnavailable, "hash queue exhausted")
return
}
if hashErr != nil {
log.Printf("setup: hash: %v", hashErr)
writeJSONError(w, http.StatusInternalServerError, "hash failed")
return
}
if err := s.store.Setup(phc); err != nil {
if errors.Is(err, auth.ErrExists) {
writeJSONError(w, http.StatusConflict, "webconfig already initialized")
return
}
log.Printf("setup: store: %v", err)
writeJSONError(w, http.StatusInternalServerError, "store write failed")
return
}
// Auto-login — only the linkat winner reaches here.
token, expires, err := s.sessions.Issue()
if err != nil {
log.Printf("setup: session issue: %v", err)
writeJSONError(w, http.StatusInternalServerError, "session issue failed")
return
}
setSessionCookie(w, token, expires)
writeJSON(w, http.StatusOK, map[string]string{"state": stateInitialized})
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
if st := s.detectState(); st != stateInitialized {
writeJSONError(w, http.StatusConflict, "webconfig is "+st)
return
}
if locked, _ := s.lockout.Locked(); locked {
writeJSONError(w, http.StatusLocked, "too many failed attempts; try again later")
return
}
var req passwordRequest
if err := readJSON(w, r, &req); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
// Read the current hash under the store mutex. The mutex is released
// before Argon2 (slow); we then re-read after verify to detect a
// password-change race (codex finding).
s.store.Lock()
phc, err := s.store.Read()
s.store.Unlock()
if err != nil {
log.Printf("login: read hash: %v", err)
writeJSONError(w, http.StatusInternalServerError, "internal error")
return
}
var ok bool
var verifyErr error
if guardErr := s.guard.TryRun(func() {
ok, verifyErr = auth.Verify(req.Password, phc)
}); guardErr != nil {
writeJSONError(w, http.StatusTooManyRequests, "server busy; retry shortly")
return
}
// Re-check lockout after acquiring (race with concurrent failures).
if locked, _ := s.lockout.Locked(); locked {
writeJSONError(w, http.StatusLocked, "too many failed attempts; try again later")
return
}
if verifyErr != nil {
log.Printf("login: verify: %v", verifyErr)
writeJSONError(w, http.StatusInternalServerError, "verify failed")
return
}
if !ok {
s.lockout.RecordFailure()
writeJSONError(w, http.StatusUnauthorized, "wrong password")
return
}
// Race guard: the hash may have been replaced while Verify was running.
// If it changed, the password we just verified against is stale —
// refuse to issue a session.
s.store.Lock()
current, err := s.store.Read()
s.store.Unlock()
if err != nil || current != phc {
s.lockout.RecordFailure()
writeJSONError(w, http.StatusConflict, "password changed mid-flight; retry")
return
}
s.lockout.Reset()
token, expires, err := s.sessions.Issue()
if err != nil {
log.Printf("login: issue session: %v", err)
writeJSONError(w, http.StatusInternalServerError, "session issue failed")
return
}
setSessionCookie(w, token, expires)
writeJSON(w, http.StatusOK, map[string]string{"state": stateInitialized})
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
if tok := readSessionToken(r); tok != "" {
s.sessions.Revoke(tok)
}
clearSessionCookie(w)
writeJSON(w, http.StatusOK, map[string]string{"status": "logged out"})
}
func (s *Server) handleChangePassword(w http.ResponseWriter, r *http.Request) {
var req changePasswordRequest
if err := readJSON(w, r, &req); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
if len(req.NewPassword) < MinPasswordLen {
writeJSONError(w, http.StatusBadRequest,
"new password must be at least 12 characters")
return
}
s.store.Lock()
phc, err := s.store.Read()
s.store.Unlock()
if err != nil {
log.Printf("change-password: read: %v", err)
writeJSONError(w, http.StatusInternalServerError, "internal error")
return
}
var ok bool
var verifyErr error
if guardErr := s.guard.RunCtx(r.Context(), func() {
ok, verifyErr = auth.Verify(req.OldPassword, phc)
}); guardErr != nil {
writeJSONError(w, http.StatusServiceUnavailable, "hash queue exhausted")
return
}
if verifyErr != nil {
log.Printf("change-password: verify: %v", verifyErr)
writeJSONError(w, http.StatusInternalServerError, "verify failed")
return
}
if !ok {
writeJSONError(w, http.StatusUnauthorized, "wrong current password")
return
}
var newPHC string
var hashErr error
if guardErr := s.guard.RunCtx(r.Context(), func() {
newPHC, hashErr = auth.Hash(req.NewPassword, s.argon2Params)
}); guardErr != nil {
writeJSONError(w, http.StatusServiceUnavailable, "hash queue exhausted")
return
}
if hashErr != nil {
log.Printf("change-password: hash: %v", hashErr)
writeJSONError(w, http.StatusInternalServerError, "hash failed")
return
}
if err := s.store.Replace(newPHC); err != nil {
log.Printf("change-password: store: %v", err)
writeJSONError(w, http.StatusInternalServerError, "store write failed")
return
}
// Rotate ALL sessions (codex: don't preserve the current one — captured
// cookies survive a password change otherwise on LAN-HTTP).
s.sessions.RevokeAll()
token, expires, err := s.sessions.Issue()
if err != nil {
log.Printf("change-password: issue: %v", err)
writeJSONError(w, http.StatusInternalServerError, "session issue failed")
return
}
setSessionCookie(w, token, expires)
writeJSON(w, http.StatusOK, map[string]string{"status": "password changed"})
}
func (s *Server) handleWhoami(w http.ResponseWriter, _ *http.Request) {
// requireSession middleware has already validated the session.
writeJSON(w, http.StatusOK, map[string]string{"username": "admin"})
}
// /api/identity (GET): redacted view — feeder ID + claim_secret_present flag.
func (s *Server) handleIdentity(w http.ResponseWriter, _ *http.Request) {
id, err := s.identity.Read()
if err != nil {
if errors.Is(err, identity.ErrNoFeederID) {
writeJSON(w, http.StatusOK, identity.Identity{}) // empty struct: feeder not yet first-run
return
}
log.Printf("identity read: %v", err)
writeJSONError(w, http.StatusInternalServerError, "identity read failed")
return
}
writeJSON(w, http.StatusOK, id)
}
// /api/identity/secret (POST): full claim secret reveal. POST so it can't
// be cached or logged in browser history; Cache-Control: no-store via
// writeJSON.
func (s *Server) handleIdentitySecret(w http.ResponseWriter, _ *http.Request) {
got, err := s.identity.Reveal()
if err != nil {
if errors.Is(err, identity.ErrNoClaimSecret) {
writeJSONError(w, http.StatusNotFound, "no claim secret yet — register first")
return
}
log.Printf("identity reveal: %v", err)
writeJSONError(w, http.StatusInternalServerError, "identity reveal failed")
return
}
writeJSON(w, http.StatusOK, got)
}
// identityBackoutTimeout caps the per-call budget for the export and
// import wrappers. apl-feed backup + restore both touch the secret
// flock and (for restore on UUID change) the feed/mlat restart — 15s
// is generous headroom for either.
const identityBackoutTimeout = 15 * time.Second
// identityBackupEnvelope is the canonical JSON shape apl-feed backup
// emits and apl-feed restore consumes. Both endpoints below read and
// write only this envelope.
type identityBackupEnvelope struct {
SchemaVersion int `json:"schema_version"`
CreatedAt string `json:"created_at,omitempty"`
FeederUUID string `json:"feeder_uuid"`
Claim struct {
Secret string `json:"secret"`
Version *int `json:"version"`
} `json:"claim"`
}
// /api/identity/export (POST): pipes apl-feed backup -'s stdout straight
// back to the client. POST (not GET) so the response stays uncacheable
// and the route never lands in browser history.
func (s *Server) handleIdentityExport(w http.ResponseWriter, r *http.Request) {
cctx, cancel := context.WithTimeout(r.Context(), identityBackoutTimeout)
defer cancel()
res, err := s.runner(cctx, s.priv.ExportIdentity)
if err != nil {
log.Printf("identity export: %v stderr=%q", err, strings.TrimSpace(string(res.Stderr)))
writeJSONError(w, http.StatusInternalServerError, "identity export failed")
return
}
// Validate the wrapper output is parseable canonical JSON before
// returning it — the SPA blob-downloads this verbatim, and a
// corrupted file would only surface much later on an import retry.
var probe identityBackupEnvelope
if perr := json.Unmarshal(res.Stdout, &probe); perr != nil || probe.SchemaVersion != 1 {
log.Printf("identity export: wrapper stdout not canonical JSON (schema=%d err=%v stderr=%q)",
probe.SchemaVersion, perr, strings.TrimSpace(string(res.Stderr)))
writeJSONError(w, http.StatusInternalServerError, "identity export produced invalid payload")
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(res.Stdout)
}
// /api/identity/import (POST): pipes the supplied apl-feed backup
// envelope through apl-feed restore /dev/stdin --force. Validates the
// envelope shape client-side before invocation to surface obvious
// errors (wrong schema, missing fields, malformed UUID/secret) with a
// 400 rather than burning a privileged call.
func (s *Server) handleIdentityImport(w http.ResponseWriter, r *http.Request) {
var req identityBackupEnvelope
if err := readJSON(w, r, &req); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
if req.SchemaVersion != 1 {
writeJSONError(w, http.StatusBadRequest, "unsupported schema_version (expected 1)")
return
}
if !isCanonicalUUID(req.FeederUUID) {
writeJSONError(w, http.StatusBadRequest, "feeder_uuid must be canonical 8-4-4-4-12 hex")
return
}
if !isCanonicalClaimSecret(req.Claim.Secret) {
writeJSONError(w, http.StatusBadRequest, "claim.secret must be 16 chars A-Z 0-9 (hyphens/spaces tolerated)")
return
}
// Re-serialize so the wrapper receives a normalized payload (and so
// we don't pipe the raw request body, which may include trailing
// whitespace the helper's jq calls would otherwise see).
body, err := json.Marshal(req)
if err != nil {
log.Printf("identity import: re-marshal: %v", err)
writeJSONError(w, http.StatusInternalServerError, "identity import failed")
return
}
cctx, cancel := context.WithTimeout(r.Context(), identityBackoutTimeout)
defer cancel()
res, runErr := s.stdinRunner(cctx, s.priv.ImportIdentity, bytes.NewReader(body))
if runErr != nil {
// Log the wrapper's stderr (which carries apl-feed's diagnostic
// reason) so operators have something to grep journalctl for,
// but don't echo it back to the client verbatim — apl-feed
// occasionally includes path or environment details.
log.Printf("identity import: %v stderr=%q", runErr, strings.TrimSpace(string(res.Stderr)))
writeJSONError(w, http.StatusInternalServerError, "identity import failed (see webconfig logs)")
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "imported"})
}
// isCanonicalUUID matches feed's read_backup_file regex
// (^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$) after
// canonicalisation: strip braces / brackets / whitespace, downcase hex.
// Symmetrical with backup.sh's canonicalize_uuid so a webconfig accept
// matches an apl-feed accept.
func isCanonicalUUID(s string) bool {
if len(s) != 36 {
return false
}
for i, c := range s {
if i == 8 || i == 13 || i == 18 || i == 23 {
if c != '-' {
return false
}
continue
}
switch {
case c >= '0' && c <= '9':
case c >= 'a' && c <= 'f':
default:
return false
}
}
return true
}
// isCanonicalClaimSecret tolerates the same input shapes apl-feed's
// canonicalize_secret + validate_secret accept (uppercase letters and
// digits after stripping whitespace and hyphens). 16 chars A-Z 0-9
// canonical, but the input may be the human-friendly XXXX-XXXX-XXXX-XXXX
// form.
func isCanonicalClaimSecret(s string) bool {
count := 0
for _, c := range s {
switch {
case c == '-' || c == ' ' || c == '\t' || c == '\n' || c == '\r':
continue
case c >= 'A' && c <= 'Z':
case c >= 'a' && c <= 'z':
case c >= '0' && c <= '9':
default:
return false
}
count++
}
return count == 16
}
// /api/config (GET): feed.env values filtered against the schema-cached
// readable_keys set. Returns 503 when the schema cache is unavailable
// (boot-time apl-feed schema --json fetch failed and no SIGHUP has
// since refreshed it).
func (s *Server) handleConfigGet(w http.ResponseWriter, _ *http.Request) {
if s.schema == nil || s.schema.Degraded() {
writeJSONError(w, http.StatusServiceUnavailable, "schema unavailable; retry after the next feed update")
return
}
values, err := s.feedEnv.ReadAll()
if err != nil {
log.Printf("feedenv read: %v", err)
writeJSONError(w, http.StatusInternalServerError, "feed.env read failed")
return
}
filtered := make(map[string]string, len(values))
for k, v := range values {
if s.schema.IsReadable(k) {
filtered[k] = v
}
}
writeJSON(w, http.StatusOK, map[string]any{"values": filtered})
}
// statusResponse is the /api/status body: the canonical status snapshot
// plus the request-scoped display unit for CPU temperature. temp_unit is
// presentation metadata derived from Accept-Language, so it lives here on
// the HTTP response rather than on status.Status (which has non-HTTP
// callers that have no locale).
type statusResponse struct {
status.Status
TempUnit string `json:"temp_unit"`
}
// /api/status (GET): service states + manifest + feed snapshot.
func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
st, err := s.status.Read(r.Context())
if err != nil {
log.Printf("status read: %v", err)
writeJSONError(w, http.StatusInternalServerError, "status read failed")
return
}
// Localize the hero-chip summary to the viewer's locale. Presentation
// only: the probed/canonical data stays Celsius. Copy HardwareHealth
// before mutating — it is a pointer and the summary string is the only
// field we rewrite.
unit := tempUnitFromAcceptLanguage(r.Header.Get("Accept-Language"))
if unit == "F" && st.HardwareHealth != nil && st.System.CPUTempCelsius != nil {
hh := *st.HardwareHealth
hh.Summary = hardware.LocalizeTempUnit(hh.Summary, st.System.CPUTempCelsius, unit)
st.HardwareHealth = &hh
}
// The body now varies by request locale.
w.Header().Set("Vary", "Accept-Language")
writeJSON(w, http.StatusOK, statusResponse{Status: st, TempUnit: unit})
}
// /api/log/{unit} (GET): SSE-stream journalctl output for the unit.
func (s *Server) handleLog(w http.ResponseWriter, r *http.Request) {
slug := r.PathValue("unit")
if err := s.logs.ServeSSE(r.Context(), w, slug); err != nil {
if errors.Is(err, logs.ErrUnknownUnit) {
writeJSONError(w, http.StatusNotFound, "unit not in webconfig log allowlist")
return
}
log.Printf("log stream %s: %v", slug, err)
// Headers may already be sent (SSE); no point writing JSON now.
}
}
// configRequest is the POST /api/config payload.
type configRequest struct {
Updates map[string]string `json:"updates"`
}
const (
// applyLockTimeoutSeconds is the lock-acquisition budget passed to
// apl-feed via the sudoers-pinned argv (`--lock-timeout 5`). Keep in
// sync with the trailing token in stage-airplanes/05-install-webconfig/
// files/etc/sudoers.d/010_airplanes-webconfig — both must match
// exactly or sudo rejects the call.
applyLockTimeoutSeconds = 5
// applyConfigTimeout = lock-timeout budget + post-lock budget.
// post-lock covers per-key validation, the atomic mktemp+rename,
// and the service-restart fan-out (each restart bounded inside
// feed-env-apply.sh). 15s gives generous headroom for the typical
// no-restart save plus a slow systemctl on a busy box. webconfig
// owns the end-to-end ceiling so a long-held flock surfaces as a
// structured 503 rather than a generic 500.
applyConfigTimeout = (applyLockTimeoutSeconds + 15) * time.Second
// systemctlTimeout caps each per-unit systemctl call.
systemctlTimeout = 10 * time.Second
)
// /api/config (POST): proxies the body to `apl-feed apply --json` over a
// sudoers-pinned argv. The feed CLI owns validation, the universal-reject
// scan, the atomic write, and the dirty-key service-restart fan-out;
// webconfig translates exit codes + JSON envelopes into HTTP responses.
//
// The schema cache must be loaded (i.e. !s.schema.Degraded()) before this
// endpoint accepts writes — without it we cannot pre-filter the payload
// against the writable_keys set.
func (s *Server) handleConfigPost(w http.ResponseWriter, r *http.Request) {
if s.schema == nil || s.schema.Degraded() {
writeJSONError(w, http.StatusServiceUnavailable, "schema unavailable; retry after the next feed update")
return
}
var req configRequest
if err := readJSON(w, r, &req); err != nil {
writeJSONError(w, http.StatusBadRequest, err.Error())
return
}
// Reject keys not in the schema's writable-key set BEFORE shelling out
// — saves a privileged invocation on obvious client bugs and produces
// a clearer per-key 400.
for k := range req.Updates {
if !s.schema.IsWritable(k) {
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("not a writable key: %s", k))
return
}
}
resp, status, err := s.applyConfigLocked(r.Context(), req.Updates)
if err != nil {
log.Printf("config-post: %v", err)
writeJSONError(w, http.StatusInternalServerError, "config write failed")
return
}
if status != http.StatusOK {
// Forward the structured error envelope from apl-feed apply
// (per-field reasons, lock_timeout message, etc.). Synthesize
// a flat Error field too so the client's `r.payload.error`
// fallback shows the actual reason instead of "save failed".
synthesizeError(&resp)
writeJSON(w, status, resp)
return
}
// A real write landed — nudge the remote-config syncer so the change
// reaches airplanes.live on the next sync (seconds) rather than waiting
// for the ~60s config-sync timer tick. Fire-and-forget and outside
// configMu: the unit self-gates, so this never blocks or alters the save
// response. no_change writes skip it (nothing to propagate).
if resp.Status == "applied" {
s.triggerConfigSyncAsync()
}
writeJSON(w, http.StatusOK, resp)
}
// applyConfigLocked serialises the feed.env metadata-gating read and the apply
// under configMu so both see a consistent view against concurrent webconfig
// writers, then releases the lock. The caller writes the HTTP response and
// fires any follow-up (e.g. the config-sync nudge) outside the lock.
func (s *Server) applyConfigLocked(ctx context.Context, updates map[string]string) (applyFeedResponse, int, error) {
s.configMu.Lock()
defer s.configMu.Unlock()
// A concurrent `apl-feed config sync` write is handled by the apply
// library's flock + LWW gate — the race is benign (worst case: one
// wasted no-op apply round trip).
//
// A read error is not fatal: fall back to a bare-string payload — every
// posted key passes through with no metadata, which matches the
// pre-DEV-383 behavior. We must NOT treat the read failure as bootstrap;
// that would attach metadata to every tracked key the form posts,
// including unchanged ones, and stamp fresh edited_at tuples across the
// sidecar on every save.
current, readErr := s.feedEnv.ReadAll()
var payload map[string]any
if readErr != nil {
log.Printf("config-post: feed.env pre-read for metadata gating failed; falling back to bare-string payload: %v", readErr)
payload = feedmeta.BareStringPayload(updates)
} else {
payload = feedmeta.BuildApplyPayload(current, updates, s.now())
}
return s.invokeApplyFeed(ctx, payload)
}
// triggerConfigSyncAsync starts airplanes-config-sync.service in the background
// so a saved config change is pushed promptly. Best-effort: failures are
// logged, never surfaced on the save response, and the ~60s config-sync timer
// stays the backstop. The unit's own gates (ConditionPathExists on the claim
// secret + the REMOTE_CONFIG_ENABLED opt-in inside apl-feed) decide whether the
// run actually contacts the server, so this carries no remote-config logic.
func (s *Server) triggerConfigSyncAsync() {
go func() {
if err := s.runSudo(context.Background(), s.priv.SyncConfig, systemctlTimeout); err != nil {
log.Printf("config-sync: %v", err)
}
}()
}
// applyFeedResponse mirrors the JSON envelope emitted by
// `apl-feed apply --json`. Any subset of fields can be populated
// depending on status; the client renders them in priority order
// (errors > pending_restart > changed).
//
// Error is synthesized server-side before write (see synthesizeError)
// so the form's existing `r.payload.error` fallback path surfaces a
// useful message instead of the generic "save failed". apl-feed itself
// emits errors / message; we collapse them into a single human string.
type applyFeedResponse struct {
Status string `json:"status"`
Changed []string `json:"changed,omitempty"`
PendingRestart []string `json:"pending_restart,omitempty"`
Errors map[string]string `json:"errors,omitempty"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
}
// synthesizeError populates resp.Error from whichever of resp.Errors /
// resp.Message is the most informative for this status. Called only on
// non-success paths; success envelopes leave Error empty.
//
// rejected envelopes carry per-key reasons in Errors. The form renders
// resp.Error via textContent, which collapses newlines visually — so we
// join "KEY: reason" pairs with "; " for a readable one-line message.
// Sorted to keep the output stable across runs (Go map iteration is
// randomised, and the renderer would otherwise re-order on every save).
// If apl-feed (or a future helper) already populated resp.Error, leave
// it alone — that flat field is authoritative when present.
func synthesizeError(resp *applyFeedResponse) {
if resp.Error != "" {
return
}
if len(resp.Errors) > 0 {
keys := make([]string, 0, len(resp.Errors))
for k := range resp.Errors {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, k+": "+resp.Errors[k])
}
resp.Error = strings.Join(parts, "; ")
return
}
if resp.Message != "" {
resp.Error = resp.Message
return
}
resp.Error = "save failed (status: " + resp.Status + ")"
}
// invokeApplyFeed pipes the request body through `sudo apl-feed apply --json`
// and maps the structured response to an HTTP status. The error return
// is reserved for invocation-layer failures (binary missing, timeout)
// that are NOT part of the apply contract — those become 500.
//
// Status mapping:
//
// applied → 200 (pending_restart may be non-empty)
// no_change → 200
// rejected → 400
// lock_timeout → 503
// filesystem_error → 500
// parse_error → 400 (apl-feed received malformed input from us, but
// forward as 400 so the client sees the message)
// usage_error → 500 (programmer error: argv shape diverged)
func (s *Server) invokeApplyFeed(ctx context.Context, updates map[string]any) (applyFeedResponse, int, error) {
body, err := json.Marshal(map[string]any{"updates": updates})
if err != nil {
return applyFeedResponse{}, 0, err
}
cctx, cancel := context.WithTimeout(ctx, applyConfigTimeout)
defer cancel()
res, runErr := s.stdinRunner(cctx, s.priv.ApplyFeed, bytes.NewReader(body))
var parsed applyFeedResponse
if perr := json.Unmarshal(res.Stdout, &parsed); perr != nil {
// Helper produced no JSON envelope on stdout — treat as an
// internal error and surface stderr in the log only.
log.Printf("apply-feed: cannot parse stdout: %v stdout=%q stderr=%q",
perr, res.Stdout, strings.TrimSpace(string(res.Stderr)))
return applyFeedResponse{}, 0, fmt.Errorf("apply-feed: %w", perr)
}
switch parsed.Status {
case "applied", "no_change":
return parsed, http.StatusOK, nil
case "rejected":
return parsed, http.StatusBadRequest, nil
case "lock_timeout":
return parsed, http.StatusServiceUnavailable, nil
case "filesystem_error":
return parsed, http.StatusInternalServerError, nil
case "parse_error":
return parsed, http.StatusBadRequest, nil
default:
log.Printf("apply-feed: unknown status %q exit=%d stderr=%q err=%v",
parsed.Status, res.ExitCode, strings.TrimSpace(string(res.Stderr)), runErr)
return parsed, http.StatusInternalServerError, nil
}
}
// runSudo runs argv with a per-call timeout and logs on failure.
func (s *Server) runSudo(ctx context.Context, argv []string, timeout time.Duration) error {
cctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
res, err := s.runner(cctx, argv)
if err != nil {
return fmt.Errorf("sudo %v: %w (stderr=%q)", argv, err, strings.TrimSpace(string(res.Stderr)))
}
return nil
}
// maintenanceUnits is the set of transient maintenance units that must not
// be interrupted by a reboot. The orchestrator touches apt/dpkg and release
// artefacts, and would deadlock on the dpkg lock or leave half-configured
// state if it overlapped with a shutdown.
var maintenanceUnits = []string{
"airplanes-update-orchestrator.service",
}
// maintenanceUnitActive returns the name of any maintenance unit currently
// active or activating, or "" if none. A single `systemctl is-active u1 u2`
// invocation prints one state line per unit; we scan for the first busy one.
// systemctl is-active is read-only and does not require sudo.
func (s *Server) maintenanceUnitActive(ctx context.Context) string {
cctx, cancel := context.WithTimeout(ctx, systemctlTimeout)
defer cancel()
argv := append([]string{"/usr/bin/systemctl", "is-active"}, maintenanceUnits...)
res, _ := s.runner(cctx, argv)
lines := strings.Split(strings.TrimRight(string(res.Stdout), "\n"), "\n")
for i, line := range lines {
if i >= len(maintenanceUnits) {
break
}
state := strings.TrimSpace(line)
if state == "active" || state == "activating" {
return maintenanceUnits[i]
}
}
return ""
}
// /api/reboot (POST): refuses with 409 if a maintenance unit is active
// (rebooting mid-dpkg would brick the device). Otherwise writes 202 + flushes,
// then triggers reboot from a goroutine after a brief delay so the response
// actually leaves the wire before init starts tearing things down.
func (s *Server) handleReboot(w http.ResponseWriter, r *http.Request) {
s.maintenanceMu.Lock()
if busy := s.maintenanceUnitActive(r.Context()); busy != "" {
s.maintenanceMu.Unlock()
writeJSONError(w, http.StatusConflict, "reboot refused: "+busy+" is in progress")
return
}
s.maintenanceMu.Unlock()
writeJSON(w, http.StatusAccepted, map[string]string{"status": "rebooting"})
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
go func() {
time.Sleep(250 * time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), systemctlTimeout)
defer cancel()
res, err := s.runner(ctx, s.priv.Reboot)
if err != nil {
log.Printf("reboot: %v stderr=%q", err, strings.TrimSpace(string(res.Stderr)))
}
}()
}
// /api/poweroff (POST): mirrors handleReboot but issues `systemctl poweroff`.
// Same maintenance-active guard so a power-off mid-dpkg can't brick the device.
func (s *Server) handlePoweroff(w http.ResponseWriter, r *http.Request) {
s.maintenanceMu.Lock()
if busy := s.maintenanceUnitActive(r.Context()); busy != "" {
s.maintenanceMu.Unlock()
writeJSONError(w, http.StatusConflict, "power-off refused: "+busy+" is in progress")
return
}
s.maintenanceMu.Unlock()
writeJSON(w, http.StatusAccepted, map[string]string{"status": "powering-off"})
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
go func() {
time.Sleep(250 * time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), systemctlTimeout)
defer cancel()
res, err := s.runner(ctx, s.priv.Poweroff)
if err != nil {
log.Printf("poweroff: %v stderr=%q", err, strings.TrimSpace(string(res.Stderr)))
}
}()
}
// /api/claim/register (POST): kicks airplanes-claim.service via systemctl
// start --no-block. The unit's ConditionPathExists=!feeder-claim-secret
// makes re-trigger a no-op once a secret is on disk, so duplicate clicks
// are safe. The SPA navigates to the claim activity log on 2xx so the
// user sees progress / failures live; this handler only reports whether
// the start request was accepted by systemd.
func (s *Server) handleClaimRegister(w http.ResponseWriter, r *http.Request) {
cctx, cancel := context.WithTimeout(r.Context(), systemctlTimeout)
defer cancel()
res, err := s.runner(cctx, s.priv.RegisterClaim)
if err != nil {
log.Printf("claim-register: %v stderr=%q", err, strings.TrimSpace(string(res.Stderr)))
writeJSONError(w, http.StatusInternalServerError, "claim register start failed")
return
}
writeJSON(w, http.StatusAccepted, map[string]string{
"status": "starting",
"unit": "airplanes-claim.service",
})
}