gitops-pusher.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Command gitops-pusher allows users to use a GitOps flow for managing Tailscale ACLs.
  5. //
  6. // See README.md for more details.
  7. package main
  8. import (
  9. "bytes"
  10. "context"
  11. "crypto/sha256"
  12. "encoding/json"
  13. "flag"
  14. "fmt"
  15. "log"
  16. "net/http"
  17. "os"
  18. "regexp"
  19. "strings"
  20. "time"
  21. "github.com/peterbourgon/ff/v3/ffcli"
  22. "github.com/tailscale/hujson"
  23. )
  24. var (
  25. rootFlagSet = flag.NewFlagSet("gitops-pusher", flag.ExitOnError)
  26. policyFname = rootFlagSet.String("policy-file", "./policy.hujson", "filename for policy file")
  27. cacheFname = rootFlagSet.String("cache-file", "./version-cache.json", "filename for the previous known version hash")
  28. timeout = rootFlagSet.Duration("timeout", 5*time.Minute, "timeout for the entire CI run")
  29. githubSyntax = rootFlagSet.Bool("github-syntax", true, "use GitHub Action error syntax (https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message)")
  30. )
  31. func modifiedExternallyError() {
  32. if *githubSyntax {
  33. fmt.Printf("::warning file=%s,line=1,col=1,title=Policy File Modified Externally::The policy file was modified externally in the admin console.\n", *policyFname)
  34. } else {
  35. fmt.Printf("The policy file was modified externally in the admin console.\n")
  36. }
  37. }
  38. func apply(cache *Cache, tailnet, apiKey string) func(context.Context, []string) error {
  39. return func(ctx context.Context, args []string) error {
  40. controlEtag, err := getACLETag(ctx, tailnet, apiKey)
  41. if err != nil {
  42. return err
  43. }
  44. localEtag, err := sumFile(*policyFname)
  45. if err != nil {
  46. return err
  47. }
  48. if cache.PrevETag == "" {
  49. log.Println("no previous etag found, assuming local file is correct and recording that")
  50. cache.PrevETag = localEtag
  51. }
  52. log.Printf("control: %s", controlEtag)
  53. log.Printf("local: %s", localEtag)
  54. log.Printf("cache: %s", cache.PrevETag)
  55. if cache.PrevETag != controlEtag {
  56. modifiedExternallyError()
  57. }
  58. if controlEtag == localEtag {
  59. cache.PrevETag = localEtag
  60. log.Println("no update needed, doing nothing")
  61. return nil
  62. }
  63. if err := applyNewACL(ctx, tailnet, apiKey, *policyFname, controlEtag); err != nil {
  64. return err
  65. }
  66. cache.PrevETag = localEtag
  67. return nil
  68. }
  69. }
  70. func test(cache *Cache, tailnet, apiKey string) func(context.Context, []string) error {
  71. return func(ctx context.Context, args []string) error {
  72. controlEtag, err := getACLETag(ctx, tailnet, apiKey)
  73. if err != nil {
  74. return err
  75. }
  76. localEtag, err := sumFile(*policyFname)
  77. if err != nil {
  78. return err
  79. }
  80. if cache.PrevETag == "" {
  81. log.Println("no previous etag found, assuming local file is correct and recording that")
  82. cache.PrevETag = localEtag
  83. }
  84. log.Printf("control: %s", controlEtag)
  85. log.Printf("local: %s", localEtag)
  86. log.Printf("cache: %s", cache.PrevETag)
  87. if cache.PrevETag != controlEtag {
  88. modifiedExternallyError()
  89. }
  90. if controlEtag == localEtag {
  91. log.Println("no updates found, doing nothing")
  92. return nil
  93. }
  94. if err := testNewACLs(ctx, tailnet, apiKey, *policyFname); err != nil {
  95. return err
  96. }
  97. return nil
  98. }
  99. }
  100. func getChecksums(cache *Cache, tailnet, apiKey string) func(context.Context, []string) error {
  101. return func(ctx context.Context, args []string) error {
  102. controlEtag, err := getACLETag(ctx, tailnet, apiKey)
  103. if err != nil {
  104. return err
  105. }
  106. localEtag, err := sumFile(*policyFname)
  107. if err != nil {
  108. return err
  109. }
  110. if cache.PrevETag == "" {
  111. log.Println("no previous etag found, assuming local file is correct and recording that")
  112. cache.PrevETag = Shuck(localEtag)
  113. }
  114. log.Printf("control: %s", controlEtag)
  115. log.Printf("local: %s", localEtag)
  116. log.Printf("cache: %s", cache.PrevETag)
  117. return nil
  118. }
  119. }
  120. func main() {
  121. tailnet, ok := os.LookupEnv("TS_TAILNET")
  122. if !ok {
  123. log.Fatal("set envvar TS_TAILNET to your tailnet's name")
  124. }
  125. apiKey, ok := os.LookupEnv("TS_API_KEY")
  126. if !ok {
  127. log.Fatal("set envvar TS_API_KEY to your Tailscale API key")
  128. }
  129. cache, err := LoadCache(*cacheFname)
  130. if err != nil {
  131. if os.IsNotExist(err) {
  132. cache = &Cache{}
  133. } else {
  134. log.Fatalf("error loading cache: %v", err)
  135. }
  136. }
  137. defer cache.Save(*cacheFname)
  138. applyCmd := &ffcli.Command{
  139. Name: "apply",
  140. ShortUsage: "gitops-pusher [options] apply",
  141. ShortHelp: "Pushes changes to CONTROL",
  142. LongHelp: `Pushes changes to CONTROL`,
  143. Exec: apply(cache, tailnet, apiKey),
  144. }
  145. testCmd := &ffcli.Command{
  146. Name: "test",
  147. ShortUsage: "gitops-pusher [options] test",
  148. ShortHelp: "Tests ACL changes",
  149. LongHelp: "Tests ACL changes",
  150. Exec: test(cache, tailnet, apiKey),
  151. }
  152. cksumCmd := &ffcli.Command{
  153. Name: "checksum",
  154. ShortUsage: "Shows checksums of ACL files",
  155. ShortHelp: "Fetch checksum of CONTROL's ACL and the local ACL for comparison",
  156. LongHelp: "Fetch checksum of CONTROL's ACL and the local ACL for comparison",
  157. Exec: getChecksums(cache, tailnet, apiKey),
  158. }
  159. root := &ffcli.Command{
  160. ShortUsage: "gitops-pusher [options] <command>",
  161. ShortHelp: "Push Tailscale ACLs to CONTROL using a GitOps workflow",
  162. Subcommands: []*ffcli.Command{applyCmd, cksumCmd, testCmd},
  163. FlagSet: rootFlagSet,
  164. }
  165. if err := root.Parse(os.Args[1:]); err != nil {
  166. log.Fatal(err)
  167. }
  168. ctx, cancel := context.WithTimeout(context.Background(), *timeout)
  169. defer cancel()
  170. if err := root.Run(ctx); err != nil {
  171. fmt.Println(err)
  172. os.Exit(1)
  173. }
  174. }
  175. func sumFile(fname string) (string, error) {
  176. data, err := os.ReadFile(fname)
  177. if err != nil {
  178. return "", err
  179. }
  180. formatted, err := hujson.Format(data)
  181. if err != nil {
  182. return "", err
  183. }
  184. h := sha256.New()
  185. _, err = h.Write(formatted)
  186. if err != nil {
  187. return "", err
  188. }
  189. return fmt.Sprintf("%x", h.Sum(nil)), nil
  190. }
  191. func applyNewACL(ctx context.Context, tailnet, apiKey, policyFname, oldEtag string) error {
  192. fin, err := os.Open(policyFname)
  193. if err != nil {
  194. return err
  195. }
  196. defer fin.Close()
  197. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("https://api.tailscale.com/api/v2/tailnet/%s/acl", tailnet), fin)
  198. if err != nil {
  199. return err
  200. }
  201. req.SetBasicAuth(apiKey, "")
  202. req.Header.Set("Content-Type", "application/hujson")
  203. req.Header.Set("If-Match", `"`+oldEtag+`"`)
  204. resp, err := http.DefaultClient.Do(req)
  205. if err != nil {
  206. return err
  207. }
  208. defer resp.Body.Close()
  209. got := resp.StatusCode
  210. want := http.StatusOK
  211. if got != want {
  212. var ate ACLTestError
  213. err := json.NewDecoder(resp.Body).Decode(&ate)
  214. if err != nil {
  215. return err
  216. }
  217. return ate
  218. }
  219. return nil
  220. }
  221. func testNewACLs(ctx context.Context, tailnet, apiKey, policyFname string) error {
  222. data, err := os.ReadFile(policyFname)
  223. if err != nil {
  224. return err
  225. }
  226. data, err = hujson.Standardize(data)
  227. if err != nil {
  228. return err
  229. }
  230. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("https://api.tailscale.com/api/v2/tailnet/%s/acl/validate", tailnet), bytes.NewBuffer(data))
  231. if err != nil {
  232. return err
  233. }
  234. req.SetBasicAuth(apiKey, "")
  235. req.Header.Set("Content-Type", "application/hujson")
  236. resp, err := http.DefaultClient.Do(req)
  237. if err != nil {
  238. return err
  239. }
  240. defer resp.Body.Close()
  241. var ate ACLTestError
  242. err = json.NewDecoder(resp.Body).Decode(&ate)
  243. if err != nil {
  244. return err
  245. }
  246. if len(ate.Message) != 0 || len(ate.Data) != 0 {
  247. return ate
  248. }
  249. got := resp.StatusCode
  250. want := http.StatusOK
  251. if got != want {
  252. return fmt.Errorf("wanted HTTP status code %d but got %d", want, got)
  253. }
  254. return nil
  255. }
  256. var lineColMessageSplit = regexp.MustCompile(`line ([0-9]+), column ([0-9]+): (.*)$`)
  257. type ACLTestError struct {
  258. Message string `json:"message"`
  259. Data []ACLTestErrorDetail `json:"data"`
  260. }
  261. func (ate ACLTestError) Error() string {
  262. var sb strings.Builder
  263. if *githubSyntax && lineColMessageSplit.MatchString(ate.Message) {
  264. sp := lineColMessageSplit.FindStringSubmatch(ate.Message)
  265. line := sp[1]
  266. col := sp[2]
  267. msg := sp[3]
  268. fmt.Fprintf(&sb, "::error file=%s,line=%s,col=%s::%s", *policyFname, line, col, msg)
  269. } else {
  270. fmt.Fprintln(&sb, ate.Message)
  271. }
  272. fmt.Fprintln(&sb)
  273. for _, data := range ate.Data {
  274. fmt.Fprintf(&sb, "For user %s:\n", data.User)
  275. for _, err := range data.Errors {
  276. fmt.Fprintf(&sb, "- %s\n", err)
  277. }
  278. }
  279. return sb.String()
  280. }
  281. type ACLTestErrorDetail struct {
  282. User string `json:"user"`
  283. Errors []string `json:"errors"`
  284. }
  285. func getACLETag(ctx context.Context, tailnet, apiKey string) (string, error) {
  286. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://api.tailscale.com/api/v2/tailnet/%s/acl", tailnet), nil)
  287. if err != nil {
  288. return "", err
  289. }
  290. req.SetBasicAuth(apiKey, "")
  291. req.Header.Set("Accept", "application/hujson")
  292. resp, err := http.DefaultClient.Do(req)
  293. if err != nil {
  294. return "", err
  295. }
  296. defer resp.Body.Close()
  297. got := resp.StatusCode
  298. want := http.StatusOK
  299. if got != want {
  300. return "", fmt.Errorf("wanted HTTP status code %d but got %d", want, got)
  301. }
  302. return Shuck(resp.Header.Get("ETag")), nil
  303. }