gitops-pusher.go 11 KB

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