gitops-pusher.go 11 KB

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