-
Notifications
You must be signed in to change notification settings - Fork 6
/
serve.go
128 lines (118 loc) · 3.38 KB
/
serve.go
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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
)
const (
bearerSchema = "Bearer "
)
// leaseRequest defines the payload of a lease HTTP request submitted by an
// agent.
type leaseRequest struct {
PubKey string
}
// leaseResponse define the payload of a lease HTTP response returned by a
// server.
type leaseResponse struct {
Status string
IP string
ServerWireguardIP string
AllowedIPs []string
PubKey string
Endpoint string
}
// HTTPLeaseHandler implements the HTTP server that manages peer address leases.
type HTTPLeaseHandler struct {
leaseManager *fileLeaseManager
serverConfig *serverConfig
tokenValidator *tokenValidator
}
func extractBearerTokenFromHeader(req *http.Request, header string) (string, error) {
authHeader := req.Header.Get(header)
if authHeader == "" {
return "", fmt.Errorf("Header: %s not found", header)
}
if !strings.HasPrefix(authHeader, bearerSchema) {
return "", fmt.Errorf("Header is missing schema prefix: %s", bearerSchema)
}
return authHeader[len(bearerSchema):], nil
}
func (lh *HTTPLeaseHandler) newPeerLease(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
token, err := extractBearerTokenFromHeader(r, "Authorization")
if err != nil {
logger.Errorf(
"Cannot parse authorization token error=%v", err)
http.Error(
w,
fmt.Sprintf("error parsing auth token: %v", err),
http.StatusInternalServerError,
)
return
}
tokenInfo, err := lh.tokenValidator.validate(token, "access_token")
if err != nil {
logger.Errorf("Cannot check token validity error=%v", err)
http.Error(
w,
fmt.Sprintf("error checking token validity: %v", err),
http.StatusInternalServerError,
)
return
}
if !tokenInfo.Active {
http.Error(w, "invalid token", http.StatusForbidden)
return
}
if tokenInfo.Exp <= 0 {
http.Error(w, "token does not expire, cannot accept this", http.StatusBadRequest)
return
}
decoder := json.NewDecoder(r.Body)
var p leaseRequest
if err := decoder.Decode(&p); err != nil {
logger.Errorf("Cannot decode request body error=%v", err)
http.Error(w, "Cannot decode request body", http.StatusInternalServerError)
return
}
wg, err := lh.leaseManager.addNewPeer(tokenInfo.UserName, p.PubKey, time.Unix(tokenInfo.Exp, 0))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pubKey, _, err := getKeys("")
if err != nil {
http.Error(w, "cannot get public key", http.StatusInternalServerError)
return
}
response := &leaseResponse{
Status: "success",
IP: fmt.Sprintf("%s/32", wg.IP.String()),
ServerWireguardIP: lh.serverConfig.WireguardIPPrefix.IP().String(),
AllowedIPs: lh.serverConfig.AllowedIPs,
PubKey: pubKey,
Endpoint: lh.serverConfig.Endpoint,
}
r, err := json.Marshal(response)
if err != nil {
http.Error(w, "cannot encode response", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, string(r))
default:
fmt.Fprintf(w, "only POST method is supported.")
}
}
func (lh *HTTPLeaseHandler) start() {
http.HandleFunc("/newPeerLease", lh.newPeerLease)
logger.Verbosef("Starting server for lease requests")
if err := http.ListenAndServe(lh.serverConfig.ServerListenAddress, nil); err != nil {
logger.Errorf("%v", err)
os.Exit(1)
}
}