gitops-pusher.go 10.0 KB

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