blob: 8a3a9ec2dbf1278179c4bd7779024eadeedee9d9 [file] [log] [blame]
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +04001package main
2
3import (
giob36178f2024-08-23 18:59:15 +04004 "bytes"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +04005 "encoding/json"
giob36178f2024-08-23 18:59:15 +04006 "errors"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +04007 "flag"
8 "fmt"
giob36178f2024-08-23 18:59:15 +04009 "io"
10 "io/ioutil"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040011 "log"
Giorgi Lekveishvili9d5e3f52024-03-13 15:02:50 +040012 "net"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040013 "net/http"
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040014 "os"
gioc23530e2024-05-01 11:06:09 +040015 "strings"
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040016 "text/template"
giob36178f2024-08-23 18:59:15 +040017 "time"
18
19 "golang.org/x/exp/rand"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040020
gio6ec78542024-06-12 11:21:18 +040021 "github.com/gorilla/mux"
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040022)
23
24var port = flag.Int("port", 3000, "Port to listen on")
25var config = flag.String("config", "", "Path to headscale config")
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040026var acls = flag.String("acls", "", "Path to the headscale acls file")
Giorgi Lekveishvili9d5e3f52024-03-13 15:02:50 +040027var ipSubnet = flag.String("ip-subnet", "10.1.0.0/24", "IP subnet of the private network")
giob36178f2024-08-23 18:59:15 +040028var fetchUsersAddr = flag.String("fetch-users-addr", "", "API endpoint to fetch user data")
29var self = flag.String("self", "", "Self address")
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040030
Giorgi Lekveishvili2dbce6c2023-12-05 15:16:27 +040031// TODO(gio): make internal network cidr and proxy user configurable
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040032const defaultACLs = `
33{
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040034 "autoApprovers": {
35 "routes": {
gioc23530e2024-05-01 11:06:09 +040036 {{- range .cidrs }}
37 "{{ . }}": ["*"],
38 {{- end }}
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040039 },
40 },
41 "acls": [
gioe10ba162025-07-31 19:52:29 +040042 {
43 "action": "accept",
44 "src": ["*"],
45 "dst": ["*:*"]
46 },
giof6ad2982024-08-23 17:42:49 +040047 // {
48 // "action": "accept",
49 // "src": ["10.42.0.0/16", "10.43.0.0/16", "135.181.48.180/32", "65.108.39.172/32"],
50 // "dst": ["10.42.0.0/16:*", "10.43.0.0/16:*", "135.181.48.180/32:*", "65.108.39.172/32:*"],
51 // },
gioc23530e2024-05-01 11:06:09 +040052 {{- range .cidrs }}
Giorgi Lekveishvili2dbce6c2023-12-05 15:16:27 +040053 { // Everyone has passthough access to private-network-proxy node
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040054 "action": "accept",
55 "src": ["*"],
gioc23530e2024-05-01 11:06:09 +040056 "dst": ["{{ . }}:*", "private-network-proxy:0"],
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040057 },
gioc23530e2024-05-01 11:06:09 +040058 {{- end }}
giof6ad2982024-08-23 17:42:49 +040059 { // Everyone has access to every port of nodes owned by private-network-proxy
60 "action": "accept",
61 "src": ["*"],
62 "dst": ["private-network-proxy:*"],
63 },
64 {
65 "action": "accept",
66 "src": ["private-network-proxy"],
67 "dst": ["private-network-proxy:*"],
68 },
giob36178f2024-08-23 18:59:15 +040069 {{- range .users }}
giof6ad2982024-08-23 17:42:49 +040070 {
giob36178f2024-08-23 18:59:15 +040071 "action": "accept",
72 "src": ["{{ . }}"],
73 "dst": ["{{ . }}:*"],
74 },
75 {{- end }}
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040076 ],
77}
78`
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040079
80type server struct {
giob36178f2024-08-23 18:59:15 +040081 port int
82 client *client
83 fetchUsersAddr string
84 self string
85 aclsPath string
86 aclsReloadPath string
87 cidrs []string
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040088}
89
giob36178f2024-08-23 18:59:15 +040090func newServer(port int, client *client, fetchUsersAddr, self, aclsPath string, cidrs []string) *server {
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040091 return &server{
92 port,
93 client,
giob36178f2024-08-23 18:59:15 +040094 fetchUsersAddr,
95 self,
96 aclsPath,
97 fmt.Sprintf("%s-reload", aclsPath), // TODO(gio): take from the flag
98 cidrs,
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040099 }
100}
101
gio6ec78542024-06-12 11:21:18 +0400102func (s *server) start() error {
giob36178f2024-08-23 18:59:15 +0400103 f, err := os.Create(s.aclsReloadPath)
104 if err != nil {
105 return err
106 }
107 f.Close()
gio6ec78542024-06-12 11:21:18 +0400108 r := mux.NewRouter()
giob36178f2024-08-23 18:59:15 +0400109 r.HandleFunc("/sync-users", s.handleSyncUsers).Methods(http.MethodGet)
gio6ec78542024-06-12 11:21:18 +0400110 r.HandleFunc("/user/{user}/preauthkey", s.createReusablePreAuthKey).Methods(http.MethodPost)
gio864b4332024-09-05 13:56:47 +0400111 r.HandleFunc("/user/{user}/preauthkey", s.expireReusablePreAuthKey).Methods(http.MethodDelete)
112 r.HandleFunc("/user/{user}/node/{node}/expire", s.expireUserNode).Methods(http.MethodPost)
giof6ad2982024-08-23 17:42:49 +0400113 r.HandleFunc("/user/{user}/node/{node}/ip", s.getNodeIP).Methods(http.MethodGet)
gio864b4332024-09-05 13:56:47 +0400114 r.HandleFunc("/user/{user}/node/{node}", s.removeUserNode).Methods(http.MethodDelete)
gio6ec78542024-06-12 11:21:18 +0400115 r.HandleFunc("/user", s.createUser).Methods(http.MethodPost)
116 r.HandleFunc("/routes/{id}/enable", s.enableRoute).Methods(http.MethodPost)
giob36178f2024-08-23 18:59:15 +0400117 go func() {
118 rand.Seed(uint64(time.Now().UnixNano()))
119 s.syncUsers()
120 for {
121 delay := time.Duration(rand.Intn(60)+60) * time.Second
122 time.Sleep(delay)
123 s.syncUsers()
124 }
125 }()
gio6ec78542024-06-12 11:21:18 +0400126 return http.ListenAndServe(fmt.Sprintf(":%d", s.port), r)
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400127}
128
129type createUserReq struct {
130 Name string `json:"name"`
131}
132
gio6ec78542024-06-12 11:21:18 +0400133func (s *server) createUser(w http.ResponseWriter, r *http.Request) {
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400134 var req createUserReq
gio6ec78542024-06-12 11:21:18 +0400135 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
136 http.Error(w, err.Error(), http.StatusBadRequest)
137 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400138 }
gio3cabc3e2024-10-06 18:37:27 +0400139 if err := s.client.createUser(req.Name); err != nil && !errors.Is(err, ErrorAlreadyExists) {
gio6ec78542024-06-12 11:21:18 +0400140 http.Error(w, err.Error(), http.StatusInternalServerError)
141 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400142 }
143}
144
gio6ec78542024-06-12 11:21:18 +0400145func (s *server) createReusablePreAuthKey(w http.ResponseWriter, r *http.Request) {
146 user, ok := mux.Vars(r)["user"]
147 if !ok {
148 http.Error(w, "no user", http.StatusBadRequest)
149 return
150 }
151 if key, err := s.client.createPreAuthKey(user); err != nil {
152 http.Error(w, err.Error(), http.StatusInternalServerError)
153 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400154 } else {
gio6ec78542024-06-12 11:21:18 +0400155 fmt.Fprint(w, key)
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400156 }
157}
158
gio864b4332024-09-05 13:56:47 +0400159type expirePreAuthKeyReq struct {
160 AuthKey string `json:"authKey"`
161}
162
163func (s *server) expireReusablePreAuthKey(w http.ResponseWriter, r *http.Request) {
164 user, ok := mux.Vars(r)["user"]
165 if !ok {
166 http.Error(w, "no user", http.StatusBadRequest)
167 return
168 }
169 var req expirePreAuthKeyReq
170 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
171 http.Error(w, err.Error(), http.StatusBadRequest)
172 return
173 }
174 if err := s.client.expirePreAuthKey(user, req.AuthKey); err != nil {
gio92116ca2024-10-06 13:55:46 +0400175 if errors.Is(err, ErrorNotFound) {
176 http.Error(w, err.Error(), http.StatusNotFound)
177 } else {
178 http.Error(w, err.Error(), http.StatusInternalServerError)
179 }
gio864b4332024-09-05 13:56:47 +0400180 return
181 }
182}
183
184func (s *server) expireUserNode(w http.ResponseWriter, r *http.Request) {
185 fmt.Println("expire node")
186 user, ok := mux.Vars(r)["user"]
187 if !ok {
188 http.Error(w, "no user", http.StatusBadRequest)
189 return
190 }
191 node, ok := mux.Vars(r)["node"]
192 if !ok {
193 http.Error(w, "no user", http.StatusBadRequest)
194 return
195 }
196 if err := s.client.expireUserNode(user, node); err != nil {
gio92116ca2024-10-06 13:55:46 +0400197 if errors.Is(err, ErrorNotFound) {
198 http.Error(w, err.Error(), http.StatusNotFound)
199 } else {
200 http.Error(w, err.Error(), http.StatusInternalServerError)
201 }
gio864b4332024-09-05 13:56:47 +0400202 return
203 }
204}
205
206func (s *server) removeUserNode(w http.ResponseWriter, r *http.Request) {
207 user, ok := mux.Vars(r)["user"]
208 if !ok {
209 http.Error(w, "no user", http.StatusBadRequest)
210 return
211 }
212 node, ok := mux.Vars(r)["node"]
213 if !ok {
214 http.Error(w, "no user", http.StatusBadRequest)
215 return
216 }
217 if err := s.client.removeUserNode(user, node); err != nil {
gio92116ca2024-10-06 13:55:46 +0400218 if errors.Is(err, ErrorNotFound) {
219 http.Error(w, err.Error(), http.StatusNotFound)
220 } else {
221 http.Error(w, err.Error(), http.StatusInternalServerError)
222 }
gio864b4332024-09-05 13:56:47 +0400223 return
224 }
225}
226
giob36178f2024-08-23 18:59:15 +0400227func (s *server) handleSyncUsers(_ http.ResponseWriter, _ *http.Request) {
228 go s.syncUsers()
229}
230
231type user struct {
232 Username string `json:"username"`
233}
234
235func (s *server) syncUsers() {
236 resp, err := http.Get(fmt.Sprintf("%s?selfAddress=%s/sync-users", s.fetchUsersAddr, s.self))
237 if err != nil {
238 fmt.Println(err)
239 return
240 }
241 users := []user{}
242 if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
243 fmt.Println(err)
244 return
245 }
246 var usernames []string
247 for _, u := range users {
248 usernames = append(usernames, u.Username)
249 if err := s.client.createUser(u.Username); err != nil && !errors.Is(err, ErrorAlreadyExists) {
250 fmt.Println(err)
251 continue
252 }
253 }
254 currentACLs, err := ioutil.ReadFile(s.aclsPath)
255 if err != nil {
256 fmt.Println(err)
257 }
258 newACLs, err := updateACLs(s.aclsPath, s.cidrs, usernames)
259 if err != nil {
260 fmt.Println(err)
261 panic(err)
262 }
263 if !bytes.Equal(currentACLs, newACLs) {
264 if err := os.Remove(s.aclsReloadPath); err != nil {
265 fmt.Println(err)
266 }
267 }
268}
269
gio6ec78542024-06-12 11:21:18 +0400270func (s *server) enableRoute(w http.ResponseWriter, r *http.Request) {
271 id, ok := mux.Vars(r)["id"]
272 if !ok {
273 http.Error(w, "no id", http.StatusBadRequest)
274 return
275 }
276 if err := s.client.enableRoute(id); err != nil {
277 http.Error(w, err.Error(), http.StatusInternalServerError)
278 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400279 }
280}
281
giof6ad2982024-08-23 17:42:49 +0400282func (s *server) getNodeIP(w http.ResponseWriter, r *http.Request) {
283 user, ok := mux.Vars(r)["user"]
284 if !ok || user == "" {
285 http.Error(w, "no user", http.StatusBadRequest)
286 return
287 }
288 node, ok := mux.Vars(r)["node"]
289 if !ok || node == "" {
290 http.Error(w, "no name", http.StatusBadRequest)
291 return
292 }
293 addr, err := s.client.getNodeAddresses(user, node)
294 if err != nil {
295 if errors.Is(err, ErrorNotFound) {
296 http.Error(w, err.Error(), http.StatusNotFound)
297 } else {
298 http.Error(w, err.Error(), http.StatusInternalServerError)
299 }
300 return
301 }
302 if len(addr) == 0 || addr[0] == nil {
303 http.Error(w, "no address", http.StatusPreconditionFailed)
304 return
305 }
306 fmt.Fprintf(w, "%s", addr[0].String())
307}
308
giob36178f2024-08-23 18:59:15 +0400309func updateACLs(aclsPath string, cidrs []string, users []string) ([]byte, error) {
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400310 tmpl, err := template.New("acls").Parse(defaultACLs)
311 if err != nil {
giob36178f2024-08-23 18:59:15 +0400312 return nil, err
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400313 }
Giorgi Lekveishvili9d5e3f52024-03-13 15:02:50 +0400314 out, err := os.Create(aclsPath)
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400315 if err != nil {
giob36178f2024-08-23 18:59:15 +0400316 return nil, err
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400317 }
318 defer out.Close()
giob36178f2024-08-23 18:59:15 +0400319 var ret bytes.Buffer
320 if err := tmpl.Execute(io.MultiWriter(out, &ret), map[string]any{
gioc23530e2024-05-01 11:06:09 +0400321 "cidrs": cidrs,
giob36178f2024-08-23 18:59:15 +0400322 "users": users,
323 }); err != nil {
324 return nil, err
325 }
326 return ret.Bytes(), nil
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400327}
328
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400329func main() {
330 flag.Parse()
gioc23530e2024-05-01 11:06:09 +0400331 var cidrs []string
332 for _, ips := range strings.Split(*ipSubnet, ",") {
333 _, cidr, err := net.ParseCIDR(ips)
334 if err != nil {
335 panic(err)
336 }
337 cidrs = append(cidrs, cidr.String())
Giorgi Lekveishvili9d5e3f52024-03-13 15:02:50 +0400338 }
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400339 c := newClient(*config)
giob36178f2024-08-23 18:59:15 +0400340 s := newServer(*port, c, *fetchUsersAddr, *self, *acls, cidrs)
gio6ec78542024-06-12 11:21:18 +0400341 log.Fatal(s.start())
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400342}