blob: da0ff6c0a40ea1d105cce4d9b9e8ae41140912ea [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": [
gioc23530e2024-05-01 11:06:09 +040042 {{- range .cidrs }}
Giorgi Lekveishvili2dbce6c2023-12-05 15:16:27 +040043 { // Everyone has passthough access to private-network-proxy node
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040044 "action": "accept",
45 "src": ["*"],
gioc23530e2024-05-01 11:06:09 +040046 "dst": ["{{ . }}:*", "private-network-proxy:0"],
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040047 },
gioc23530e2024-05-01 11:06:09 +040048 {{- end }}
giob36178f2024-08-23 18:59:15 +040049 {{- range .users }}
50 { // Everyone has passthough access to private-network-proxy node
51 "action": "accept",
52 "src": ["{{ . }}"],
53 "dst": ["{{ . }}:*"],
54 },
55 {{- end }}
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +040056 ],
57}
58`
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040059
60type server struct {
giob36178f2024-08-23 18:59:15 +040061 port int
62 client *client
63 fetchUsersAddr string
64 self string
65 aclsPath string
66 aclsReloadPath string
67 cidrs []string
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040068}
69
giob36178f2024-08-23 18:59:15 +040070func newServer(port int, client *client, fetchUsersAddr, self, aclsPath string, cidrs []string) *server {
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040071 return &server{
72 port,
73 client,
giob36178f2024-08-23 18:59:15 +040074 fetchUsersAddr,
75 self,
76 aclsPath,
77 fmt.Sprintf("%s-reload", aclsPath), // TODO(gio): take from the flag
78 cidrs,
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +040079 }
80}
81
gio6ec78542024-06-12 11:21:18 +040082func (s *server) start() error {
giob36178f2024-08-23 18:59:15 +040083 f, err := os.Create(s.aclsReloadPath)
84 if err != nil {
85 return err
86 }
87 f.Close()
gio6ec78542024-06-12 11:21:18 +040088 r := mux.NewRouter()
giob36178f2024-08-23 18:59:15 +040089 r.HandleFunc("/sync-users", s.handleSyncUsers).Methods(http.MethodGet)
gio6ec78542024-06-12 11:21:18 +040090 r.HandleFunc("/user/{user}/preauthkey", s.createReusablePreAuthKey).Methods(http.MethodPost)
91 r.HandleFunc("/user", s.createUser).Methods(http.MethodPost)
92 r.HandleFunc("/routes/{id}/enable", s.enableRoute).Methods(http.MethodPost)
giob36178f2024-08-23 18:59:15 +040093 go func() {
94 rand.Seed(uint64(time.Now().UnixNano()))
95 s.syncUsers()
96 for {
97 delay := time.Duration(rand.Intn(60)+60) * time.Second
98 time.Sleep(delay)
99 s.syncUsers()
100 }
101 }()
gio6ec78542024-06-12 11:21:18 +0400102 return http.ListenAndServe(fmt.Sprintf(":%d", s.port), r)
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400103}
104
105type createUserReq struct {
106 Name string `json:"name"`
107}
108
gio6ec78542024-06-12 11:21:18 +0400109func (s *server) createUser(w http.ResponseWriter, r *http.Request) {
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400110 var req createUserReq
gio6ec78542024-06-12 11:21:18 +0400111 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
112 http.Error(w, err.Error(), http.StatusBadRequest)
113 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400114 }
115 if err := s.client.createUser(req.Name); err != nil {
gio6ec78542024-06-12 11:21:18 +0400116 http.Error(w, err.Error(), http.StatusInternalServerError)
117 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400118 }
119}
120
gio6ec78542024-06-12 11:21:18 +0400121func (s *server) createReusablePreAuthKey(w http.ResponseWriter, r *http.Request) {
122 user, ok := mux.Vars(r)["user"]
123 if !ok {
124 http.Error(w, "no user", http.StatusBadRequest)
125 return
126 }
127 if key, err := s.client.createPreAuthKey(user); err != nil {
128 http.Error(w, err.Error(), http.StatusInternalServerError)
129 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400130 } else {
gio6ec78542024-06-12 11:21:18 +0400131 fmt.Fprint(w, key)
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400132 }
133}
134
giob36178f2024-08-23 18:59:15 +0400135func (s *server) handleSyncUsers(_ http.ResponseWriter, _ *http.Request) {
136 go s.syncUsers()
137}
138
139type user struct {
140 Username string `json:"username"`
141}
142
143func (s *server) syncUsers() {
144 resp, err := http.Get(fmt.Sprintf("%s?selfAddress=%s/sync-users", s.fetchUsersAddr, s.self))
145 if err != nil {
146 fmt.Println(err)
147 return
148 }
149 users := []user{}
150 if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
151 fmt.Println(err)
152 return
153 }
154 var usernames []string
155 for _, u := range users {
156 usernames = append(usernames, u.Username)
157 if err := s.client.createUser(u.Username); err != nil && !errors.Is(err, ErrorAlreadyExists) {
158 fmt.Println(err)
159 continue
160 }
161 }
162 currentACLs, err := ioutil.ReadFile(s.aclsPath)
163 if err != nil {
164 fmt.Println(err)
165 }
166 newACLs, err := updateACLs(s.aclsPath, s.cidrs, usernames)
167 if err != nil {
168 fmt.Println(err)
169 panic(err)
170 }
171 if !bytes.Equal(currentACLs, newACLs) {
172 if err := os.Remove(s.aclsReloadPath); err != nil {
173 fmt.Println(err)
174 }
175 }
176}
177
gio6ec78542024-06-12 11:21:18 +0400178func (s *server) enableRoute(w http.ResponseWriter, r *http.Request) {
179 id, ok := mux.Vars(r)["id"]
180 if !ok {
181 http.Error(w, "no id", http.StatusBadRequest)
182 return
183 }
184 if err := s.client.enableRoute(id); err != nil {
185 http.Error(w, err.Error(), http.StatusInternalServerError)
186 return
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400187 }
188}
189
giob36178f2024-08-23 18:59:15 +0400190func updateACLs(aclsPath string, cidrs []string, users []string) ([]byte, error) {
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400191 tmpl, err := template.New("acls").Parse(defaultACLs)
192 if err != nil {
giob36178f2024-08-23 18:59:15 +0400193 return nil, err
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400194 }
Giorgi Lekveishvili9d5e3f52024-03-13 15:02:50 +0400195 out, err := os.Create(aclsPath)
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400196 if err != nil {
giob36178f2024-08-23 18:59:15 +0400197 return nil, err
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400198 }
199 defer out.Close()
giob36178f2024-08-23 18:59:15 +0400200 var ret bytes.Buffer
201 if err := tmpl.Execute(io.MultiWriter(out, &ret), map[string]any{
gioc23530e2024-05-01 11:06:09 +0400202 "cidrs": cidrs,
giob36178f2024-08-23 18:59:15 +0400203 "users": users,
204 }); err != nil {
205 return nil, err
206 }
207 return ret.Bytes(), nil
Giorgi Lekveishvili6ae65d12023-12-04 15:37:53 +0400208}
209
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400210func main() {
211 flag.Parse()
gioc23530e2024-05-01 11:06:09 +0400212 var cidrs []string
213 for _, ips := range strings.Split(*ipSubnet, ",") {
214 _, cidr, err := net.ParseCIDR(ips)
215 if err != nil {
216 panic(err)
217 }
218 cidrs = append(cidrs, cidr.String())
Giorgi Lekveishvili9d5e3f52024-03-13 15:02:50 +0400219 }
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400220 c := newClient(*config)
giob36178f2024-08-23 18:59:15 +0400221 s := newServer(*port, c, *fetchUsersAddr, *self, *acls, cidrs)
gio6ec78542024-06-12 11:21:18 +0400222 log.Fatal(s.start())
Giorgi Lekveishvili52814d92023-06-15 19:30:32 +0400223}