gitops-pusher.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 apiKey != "" && (oauthId != "" || oauthSecret != "") {
  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 && (oauthId != "" || oauthSecret != "") {
  139. // Both should ideally be set, but if either are non-empty it means the user had an intent
  140. // to set _something_, so they should receive the oauth error flow.
  141. oauthConfig := &clientcredentials.Config{
  142. ClientID: oauthId,
  143. ClientSecret: oauthSecret,
  144. TokenURL: fmt.Sprintf("https://%s/api/v2/oauth/token", *apiServer),
  145. }
  146. client = oauthConfig.Client(context.Background())
  147. } else {
  148. client = http.DefaultClient
  149. }
  150. cache, err := LoadCache(*cacheFname)
  151. if err != nil {
  152. if os.IsNotExist(err) {
  153. cache = &Cache{}
  154. } else {
  155. log.Fatalf("error loading cache: %v", err)
  156. }
  157. }
  158. defer cache.Save(*cacheFname)
  159. applyCmd := &ffcli.Command{
  160. Name: "apply",
  161. ShortUsage: "gitops-pusher [options] apply",
  162. ShortHelp: "Pushes changes to CONTROL",
  163. LongHelp: `Pushes changes to CONTROL`,
  164. Exec: apply(cache, client, tailnet, apiKey),
  165. }
  166. testCmd := &ffcli.Command{
  167. Name: "test",
  168. ShortUsage: "gitops-pusher [options] test",
  169. ShortHelp: "Tests ACL changes",
  170. LongHelp: "Tests ACL changes",
  171. Exec: test(cache, client, tailnet, apiKey),
  172. }
  173. cksumCmd := &ffcli.Command{
  174. Name: "checksum",
  175. ShortUsage: "Shows checksums of ACL files",
  176. ShortHelp: "Fetch checksum of CONTROL's ACL and the local ACL for comparison",
  177. LongHelp: "Fetch checksum of CONTROL's ACL and the local ACL for comparison",
  178. Exec: getChecksums(cache, client, tailnet, apiKey),
  179. }
  180. root := &ffcli.Command{
  181. ShortUsage: "gitops-pusher [options] <command>",
  182. ShortHelp: "Push Tailscale ACLs to CONTROL using a GitOps workflow",
  183. Subcommands: []*ffcli.Command{applyCmd, cksumCmd, testCmd},
  184. FlagSet: rootFlagSet,
  185. }
  186. if err := root.Parse(os.Args[1:]); err != nil {
  187. log.Fatal(err)
  188. }
  189. ctx, cancel := context.WithTimeout(context.Background(), *timeout)
  190. defer cancel()
  191. if err := root.Run(ctx); err != nil {
  192. fmt.Println(err)
  193. os.Exit(1)
  194. }
  195. }
  196. func sumFile(fname string) (string, error) {
  197. data, err := os.ReadFile(fname)
  198. if err != nil {
  199. return "", err
  200. }
  201. formatted, err := hujson.Format(data)
  202. if err != nil {
  203. return "", err
  204. }
  205. h := sha256.New()
  206. _, err = h.Write(formatted)
  207. if err != nil {
  208. return "", err
  209. }
  210. return fmt.Sprintf("%x", h.Sum(nil)), nil
  211. }
  212. func applyNewACL(ctx context.Context, client *http.Client, tailnet, apiKey, policyFname, oldEtag string) error {
  213. fin, err := os.Open(policyFname)
  214. if err != nil {
  215. return err
  216. }
  217. defer fin.Close()
  218. req, err := http.NewRequestWithContext(ctx, httpm.POST, fmt.Sprintf("https://%s/api/v2/tailnet/%s/acl", *apiServer, tailnet), fin)
  219. if err != nil {
  220. return err
  221. }
  222. req.SetBasicAuth(apiKey, "")
  223. req.Header.Set("Content-Type", "application/hujson")
  224. req.Header.Set("If-Match", `"`+oldEtag+`"`)
  225. resp, err := client.Do(req)
  226. if err != nil {
  227. return err
  228. }
  229. defer resp.Body.Close()
  230. got := resp.StatusCode
  231. want := http.StatusOK
  232. if got != want {
  233. var ate ACLGitopsTestError
  234. err := json.NewDecoder(resp.Body).Decode(&ate)
  235. if err != nil {
  236. return err
  237. }
  238. return ate
  239. }
  240. return nil
  241. }
  242. func testNewACLs(ctx context.Context, client *http.Client, tailnet, apiKey, policyFname string) error {
  243. data, err := os.ReadFile(policyFname)
  244. if err != nil {
  245. return err
  246. }
  247. data, err = hujson.Standardize(data)
  248. if err != nil {
  249. return err
  250. }
  251. req, err := http.NewRequestWithContext(ctx, httpm.POST, fmt.Sprintf("https://%s/api/v2/tailnet/%s/acl/validate", *apiServer, tailnet), bytes.NewBuffer(data))
  252. if err != nil {
  253. return err
  254. }
  255. req.SetBasicAuth(apiKey, "")
  256. req.Header.Set("Content-Type", "application/hujson")
  257. resp, err := client.Do(req)
  258. if err != nil {
  259. return err
  260. }
  261. defer resp.Body.Close()
  262. var ate ACLGitopsTestError
  263. err = json.NewDecoder(resp.Body).Decode(&ate)
  264. if err != nil {
  265. return err
  266. }
  267. if len(ate.Message) != 0 || len(ate.Data) != 0 {
  268. return ate
  269. }
  270. got := resp.StatusCode
  271. want := http.StatusOK
  272. if got != want {
  273. return fmt.Errorf("wanted HTTP status code %d but got %d", want, got)
  274. }
  275. return nil
  276. }
  277. var lineColMessageSplit = regexp.MustCompile(`line ([0-9]+), column ([0-9]+): (.*)$`)
  278. // ACLGitopsTestError is redefined here so we can add a custom .Error() response
  279. type ACLGitopsTestError struct {
  280. tailscale.ACLTestError
  281. }
  282. func (ate ACLGitopsTestError) Error() string {
  283. var sb strings.Builder
  284. if *githubSyntax && lineColMessageSplit.MatchString(ate.Message) {
  285. sp := lineColMessageSplit.FindStringSubmatch(ate.Message)
  286. line := sp[1]
  287. col := sp[2]
  288. msg := sp[3]
  289. fmt.Fprintf(&sb, "::error file=%s,line=%s,col=%s::%s", *policyFname, line, col, msg)
  290. } else {
  291. fmt.Fprintln(&sb, ate.Message)
  292. }
  293. fmt.Fprintln(&sb)
  294. for _, data := range ate.Data {
  295. if data.User != "" {
  296. fmt.Fprintf(&sb, "For user %s:\n", data.User)
  297. }
  298. if len(data.Errors) > 0 {
  299. fmt.Fprint(&sb, "Errors found:\n")
  300. for _, err := range data.Errors {
  301. fmt.Fprintf(&sb, "- %s\n", err)
  302. }
  303. }
  304. if len(data.Warnings) > 0 {
  305. fmt.Fprint(&sb, "Warnings found:\n")
  306. for _, err := range data.Warnings {
  307. fmt.Fprintf(&sb, "- %s\n", err)
  308. }
  309. }
  310. }
  311. return sb.String()
  312. }
  313. func getACLETag(ctx context.Context, client *http.Client, tailnet, apiKey string) (string, error) {
  314. req, err := http.NewRequestWithContext(ctx, httpm.GET, fmt.Sprintf("https://%s/api/v2/tailnet/%s/acl", *apiServer, tailnet), nil)
  315. if err != nil {
  316. return "", err
  317. }
  318. req.SetBasicAuth(apiKey, "")
  319. req.Header.Set("Accept", "application/hujson")
  320. resp, err := client.Do(req)
  321. if err != nil {
  322. return "", err
  323. }
  324. defer resp.Body.Close()
  325. got := resp.StatusCode
  326. want := http.StatusOK
  327. if got != want {
  328. return "", fmt.Errorf("wanted HTTP status code %d but got %d", want, got)
  329. }
  330. return Shuck(resp.Header.Get("ETag")), nil
  331. }