summaryrefslogtreecommitdiffhomepage
path: root/tsconsensus/http.go
blob: a7e3af35d94f663ea900ecd0bf57fb3d6c47d845 (plain)
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
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package tsconsensus

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"

	"tailscale.com/util/httpm"
)

type joinRequest struct {
	RemoteHost string
	RemoteID   string
}

type commandClient struct {
	port       uint16
	httpClient *http.Client
}

func (rac *commandClient) url(host string, path string) string {
	return fmt.Sprintf("http://%s:%d%s", host, rac.port, path)
}

const maxBodyBytes = 1024 * 1024

func readAllMaxBytes(r io.Reader) ([]byte, error) {
	return io.ReadAll(io.LimitReader(r, maxBodyBytes+1))
}

func (rac *commandClient) join(host string, jr joinRequest) error {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	rBs, err := json.Marshal(jr)
	if err != nil {
		return err
	}
	url := rac.url(host, "/join")
	req, err := http.NewRequestWithContext(ctx, httpm.POST, url, bytes.NewReader(rBs))
	if err != nil {
		return err
	}
	resp, err := rac.httpClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		respBs, err := readAllMaxBytes(resp.Body)
		if err != nil {
			return err
		}
		return fmt.Errorf("remote responded %d: %s", resp.StatusCode, string(respBs))
	}
	return nil
}

func (rac *commandClient) executeCommand(host string, bs []byte) (CommandResult, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	url := rac.url(host, "/executeCommand")
	req, err := http.NewRequestWithContext(ctx, httpm.POST, url, bytes.NewReader(bs))
	if err != nil {
		return CommandResult{}, err
	}
	resp, err := rac.httpClient.Do(req)
	if err != nil {
		return CommandResult{}, err
	}
	defer resp.Body.Close()
	respBs, err := readAllMaxBytes(resp.Body)
	if err != nil {
		return CommandResult{}, err
	}
	if resp.StatusCode != 200 {
		return CommandResult{}, fmt.Errorf("remote responded %d: %s", resp.StatusCode, string(respBs))
	}
	var cr CommandResult
	if err = json.Unmarshal(respBs, &cr); err != nil {
		return CommandResult{}, err
	}
	return cr, nil
}

type authedHandler struct {
	auth    *authorization
	handler http.Handler
}

func (h authedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := h.auth.Refresh(r.Context())
	if err != nil {
		log.Printf("error authedHandler ServeHTTP refresh auth: %v", err)
		http.Error(w, "", http.StatusInternalServerError)
		return
	}
	a, err := addrFromServerAddress(r.RemoteAddr)
	if err != nil {
		log.Printf("error authedHandler ServeHTTP refresh auth: %v", err)
		http.Error(w, "", http.StatusInternalServerError)
		return
	}
	allowed := h.auth.AllowsHost(a)
	if !allowed {
		http.Error(w, "peer not allowed", http.StatusForbidden)
		return
	}
	h.handler.ServeHTTP(w, r)
}

func (c *Consensus) handleJoinHTTP(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes+1))
	var jr joinRequest
	err := decoder.Decode(&jr)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	_, err = decoder.Token()
	if !errors.Is(err, io.EOF) {
		http.Error(w, "Request body must only contain a single JSON object", http.StatusBadRequest)
		return
	}
	if jr.RemoteHost == "" {
		http.Error(w, "Required: remoteAddr", http.StatusBadRequest)
		return
	}
	if jr.RemoteID == "" {
		http.Error(w, "Required: remoteID", http.StatusBadRequest)
		return
	}
	err = c.handleJoin(jr)
	if err != nil {
		log.Printf("join handler error: %v", err)
		http.Error(w, "", http.StatusInternalServerError)
		return
	}
}

func (c *Consensus) handleExecuteCommandHTTP(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	decoder := json.NewDecoder(r.Body)
	var cmd Command
	err := decoder.Decode(&cmd)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	result, err := c.executeCommandLocally(cmd)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if err := json.NewEncoder(w).Encode(result); err != nil {
		log.Printf("error encoding execute command result: %v", err)
		return
	}
}

func (c *Consensus) makeCommandMux() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /join", c.handleJoinHTTP)
	mux.HandleFunc("POST /executeCommand", c.handleExecuteCommandHTTP)
	return mux
}

func (c *Consensus) makeCommandHandler(auth *authorization) http.Handler {
	return authedHandler{
		handler: c.makeCommandMux(),
		auth:    auth,
	}
}