handlers.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package acn
  2. /*
  3. ArozOS Cluster Node protocol (ACN) - server side plumbing
  4. Server owns the HTTP mux mounted at BasePath on every node. Higher layers
  5. (membership, metadata, storage, jobs) register their endpoints on it with
  6. Handle / HandleFunc, which wrap the handler with signature verification.
  7. Built-in endpoints:
  8. GET /cluster/acn/hello anonymous reachability probe
  9. POST /cluster/acn/ping signed round trip check
  10. GET /cluster/acn/tunnel tunnel upgrade for NAT-only nodes
  11. * /cluster/acn/relay/{node}/... forward to a node tunnelled here
  12. */
  13. import (
  14. "context"
  15. "encoding/json"
  16. "errors"
  17. "net/http"
  18. "strings"
  19. "time"
  20. )
  21. // AuthenticatedHandler is a handler that only runs for verified members.
  22. type AuthenticatedHandler func(w http.ResponseWriter, r *http.Request, sender *SignedIdentity, body []byte)
  23. // HelloResponse is the anonymous reachability reply.
  24. type HelloResponse struct {
  25. ACN bool `json:"acn"`
  26. Version string `json:"version"`
  27. InCluster bool `json:"inCluster"`
  28. Time int64 `json:"time"`
  29. }
  30. // Server mounts the ACN endpoints of this node.
  31. type Server struct {
  32. Verifier *Verifier
  33. Hub *TunnelHub
  34. Version string
  35. mux *http.ServeMux
  36. }
  37. // NewServer builds the ACN mux with the built-in endpoints registered.
  38. func NewServer(verifier *Verifier, hub *TunnelHub, version string) *Server {
  39. s := &Server{
  40. Verifier: verifier,
  41. Hub: hub,
  42. Version: version,
  43. mux: http.NewServeMux(),
  44. }
  45. s.mux.HandleFunc(BasePath+"/hello", s.handleHello)
  46. s.mux.HandleFunc(RelayPrefix+"/", s.handleRelay)
  47. if hub != nil {
  48. s.mux.HandleFunc(TunnelPath, hub.HandleTunnel)
  49. }
  50. s.HandleFunc(BasePath+"/ping", func(w http.ResponseWriter, r *http.Request, sender *SignedIdentity, body []byte) {
  51. WriteJSON(w, map[string]interface{}{"pong": true, "node": sender.NodeID, "time": time.Now().Unix()})
  52. })
  53. return s
  54. }
  55. // ServeHTTP lets the server be mounted in the main router.
  56. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  57. s.mux.ServeHTTP(w, r)
  58. }
  59. // HandleFunc registers a signed endpoint. Requests failing verification get 401.
  60. func (s *Server) HandleFunc(path string, handler AuthenticatedHandler) {
  61. s.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
  62. sender, body, err := s.Verifier.VerifyRequest(r)
  63. if err != nil {
  64. status := http.StatusUnauthorized
  65. if errors.Is(err, ErrBodyTooLarge) {
  66. status = http.StatusRequestEntityTooLarge
  67. }
  68. http.Error(w, err.Error(), status)
  69. return
  70. }
  71. handler(w, r, sender, body)
  72. })
  73. }
  74. // HandleRaw registers an endpoint without verification. Only for endpoints
  75. // that carry their own credentials (join tokens) or are intentionally public.
  76. func (s *Server) HandleRaw(path string, handler http.HandlerFunc) {
  77. s.mux.HandleFunc(path, handler)
  78. }
  79. func (s *Server) handleHello(w http.ResponseWriter, r *http.Request) {
  80. WriteJSON(w, HelloResponse{
  81. ACN: true,
  82. Version: s.Version,
  83. InCluster: s.Verifier.ClusterID() != "",
  84. Time: time.Now().Unix(),
  85. })
  86. }
  87. // handleRelay verifies the sender and forwards the request over the tunnel of
  88. // the target node. The signature (made over the original path) is preserved.
  89. func (s *Server) handleRelay(w http.ResponseWriter, r *http.Request) {
  90. target, original, ok := StripRelayPrefix(r.URL.Path)
  91. if !ok {
  92. http.Error(w, "invalid relay path", http.StatusBadRequest)
  93. return
  94. }
  95. if !strings.HasPrefix(original, BasePath+"/") {
  96. http.Error(w, "relay only forwards ACN paths", http.StatusBadRequest)
  97. return
  98. }
  99. _, body, err := s.Verifier.VerifyRequest(r)
  100. if err != nil {
  101. http.Error(w, err.Error(), http.StatusUnauthorized)
  102. return
  103. }
  104. if s.Hub == nil || !s.Hub.Connected(target) {
  105. http.Error(w, ErrTunnelNotConnected.Error(), http.StatusBadGateway)
  106. return
  107. }
  108. ctx, cancel := context.WithTimeout(r.Context(), DefaultRequestTimeout)
  109. defer cancel()
  110. resp, err := s.Hub.Do(ctx, target, r.Method, SignedTarget(original, r.URL.RawQuery), signedHeaders(r), body)
  111. if err != nil {
  112. http.Error(w, err.Error(), http.StatusBadGateway)
  113. return
  114. }
  115. for k, vals := range resp.Header {
  116. for _, v := range vals {
  117. w.Header().Add(k, v)
  118. }
  119. }
  120. w.WriteHeader(resp.Status)
  121. w.Write(resp.Body)
  122. }
  123. // WriteJSON encodes v as the JSON response body.
  124. func WriteJSON(w http.ResponseWriter, v interface{}) {
  125. js, err := json.Marshal(v)
  126. if err != nil {
  127. http.Error(w, err.Error(), http.StatusInternalServerError)
  128. return
  129. }
  130. w.Header().Set("Content-Type", "application/json")
  131. w.Write(js)
  132. }
  133. // WriteError sends a plain text error with the given status.
  134. func WriteError(w http.ResponseWriter, status int, msg string) {
  135. http.Error(w, msg, status)
  136. }