2023-01-27 21:37:20 +00:00
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
2022-06-21 20:04:48 +00:00
// Command gitops-pusher allows users to use a GitOps flow for managing Tailscale ACLs.
//
// See README.md for more details.
package main
import (
2022-09-01 17:38:32 +00:00
"bytes"
2022-06-21 20:04:48 +00:00
"context"
"crypto/sha256"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
2022-07-15 14:20:54 +00:00
"regexp"
2022-06-21 20:04:48 +00:00
"strings"
"time"
2022-07-15 15:09:44 +00:00
2022-07-22 13:39:24 +00:00
"github.com/peterbourgon/ff/v3/ffcli"
2022-07-15 15:09:44 +00:00
"github.com/tailscale/hujson"
2023-02-28 02:05:24 +00:00
"golang.org/x/oauth2/clientcredentials"
2023-07-19 14:47:16 +00:00
"tailscale.com/client/tailscale"
2023-01-27 03:35:26 +00:00
"tailscale.com/util/httpm"
2022-06-21 20:04:48 +00:00
)
var (
2024-08-08 18:21:28 +00:00
rootFlagSet = flag . NewFlagSet ( "gitops-pusher" , flag . ExitOnError )
policyFname = rootFlagSet . String ( "policy-file" , "./policy.hujson" , "filename for policy file" )
cacheFname = rootFlagSet . String ( "cache-file" , "./version-cache.json" , "filename for the previous known version hash" )
timeout = rootFlagSet . Duration ( "timeout" , 5 * time . Minute , "timeout for the entire CI run" )
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)" )
apiServer = rootFlagSet . String ( "api-server" , "api.tailscale.com" , "API server to contact" )
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" )
2022-06-21 20:04:48 +00:00
)
2024-08-08 18:21:28 +00:00
func modifiedExternallyError ( ) error {
2022-07-22 19:07:38 +00:00
if * githubSyntax {
2024-08-08 18:21:28 +00:00
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 )
2022-07-22 19:07:38 +00:00
} else {
2024-08-08 18:21:28 +00:00
return fmt . Errorf ( "The policy file was modified externally in the admin console." )
2022-07-22 19:07:38 +00:00
}
}
2023-02-28 02:05:24 +00:00
func apply ( cache * Cache , client * http . Client , tailnet , apiKey string ) func ( context . Context , [ ] string ) error {
2022-07-22 13:39:24 +00:00
return func ( ctx context . Context , args [ ] string ) error {
2023-02-28 02:05:24 +00:00
controlEtag , err := getACLETag ( ctx , client , tailnet , apiKey )
2022-06-21 20:04:48 +00:00
if err != nil {
2022-07-22 13:39:24 +00:00
return err
2022-06-21 20:04:48 +00:00
}
localEtag , err := sumFile ( * policyFname )
if err != nil {
2022-07-22 13:39:24 +00:00
return err
2022-06-21 20:04:48 +00:00
}
2022-07-22 19:07:38 +00:00
if cache . PrevETag == "" {
log . Println ( "no previous etag found, assuming local file is correct and recording that" )
2022-07-25 13:09:32 +00:00
cache . PrevETag = localEtag
2022-07-22 19:07:38 +00:00
}
2022-06-21 20:04:48 +00:00
log . Printf ( "control: %s" , controlEtag )
log . Printf ( "local: %s" , localEtag )
2022-07-22 19:07:38 +00:00
log . Printf ( "cache: %s" , cache . PrevETag )
if cache . PrevETag != controlEtag {
2024-08-08 18:21:28 +00:00
if err := modifiedExternallyError ( ) ; err != nil {
if * failOnManualEdits {
return err
} else {
fmt . Println ( err )
}
}
2022-07-22 19:07:38 +00:00
}
2022-06-21 20:04:48 +00:00
if controlEtag == localEtag {
2022-07-25 13:09:32 +00:00
cache . PrevETag = localEtag
2022-06-21 20:04:48 +00:00
log . Println ( "no update needed, doing nothing" )
2022-07-22 13:39:24 +00:00
return nil
2022-06-21 20:04:48 +00:00
}
2023-02-28 02:05:24 +00:00
if err := applyNewACL ( ctx , client , tailnet , apiKey , * policyFname , controlEtag ) ; err != nil {
2022-07-22 13:39:24 +00:00
return err
2022-06-21 20:04:48 +00:00
}
2022-07-25 13:09:32 +00:00
cache . PrevETag = localEtag
2022-07-22 19:07:38 +00:00
2022-07-22 13:39:24 +00:00
return nil
}
}
2023-02-28 02:05:24 +00:00
func test ( cache * Cache , client * http . Client , tailnet , apiKey string ) func ( context . Context , [ ] string ) error {
2022-07-22 13:39:24 +00:00
return func ( ctx context . Context , args [ ] string ) error {
2023-02-28 02:05:24 +00:00
controlEtag , err := getACLETag ( ctx , client , tailnet , apiKey )
2022-06-21 20:04:48 +00:00
if err != nil {
2022-07-22 13:39:24 +00:00
return err
2022-06-21 20:04:48 +00:00
}
localEtag , err := sumFile ( * policyFname )
if err != nil {
2022-07-22 13:39:24 +00:00
return err
2022-06-21 20:04:48 +00:00
}
2022-07-22 19:07:38 +00:00
if cache . PrevETag == "" {
log . Println ( "no previous etag found, assuming local file is correct and recording that" )
2022-07-25 13:09:32 +00:00
cache . PrevETag = localEtag
2022-07-22 19:07:38 +00:00
}
2022-06-21 20:04:48 +00:00
log . Printf ( "control: %s" , controlEtag )
log . Printf ( "local: %s" , localEtag )
2022-07-22 19:07:38 +00:00
log . Printf ( "cache: %s" , cache . PrevETag )
if cache . PrevETag != controlEtag {
2024-08-08 18:21:28 +00:00
if err := modifiedExternallyError ( ) ; err != nil {
if * failOnManualEdits {
return err
} else {
fmt . Println ( err )
}
}
2022-07-22 19:07:38 +00:00
}
2022-06-21 20:04:48 +00:00
if controlEtag == localEtag {
log . Println ( "no updates found, doing nothing" )
2022-07-22 13:39:24 +00:00
return nil
2022-06-21 20:04:48 +00:00
}
2023-02-28 02:05:24 +00:00
if err := testNewACLs ( ctx , client , tailnet , apiKey , * policyFname ) ; err != nil {
2022-07-22 13:39:24 +00:00
return err
}
return nil
}
}
2023-02-28 02:05:24 +00:00
func getChecksums ( cache * Cache , client * http . Client , tailnet , apiKey string ) func ( context . Context , [ ] string ) error {
2022-07-22 13:39:24 +00:00
return func ( ctx context . Context , args [ ] string ) error {
2023-02-28 02:05:24 +00:00
controlEtag , err := getACLETag ( ctx , client , tailnet , apiKey )
2022-07-22 13:39:24 +00:00
if err != nil {
return err
2022-06-21 20:04:48 +00:00
}
2022-07-22 13:39:24 +00:00
localEtag , err := sumFile ( * policyFname )
if err != nil {
return err
}
2022-07-22 19:07:38 +00:00
if cache . PrevETag == "" {
log . Println ( "no previous etag found, assuming local file is correct and recording that" )
cache . PrevETag = Shuck ( localEtag )
}
2022-07-22 13:39:24 +00:00
log . Printf ( "control: %s" , controlEtag )
log . Printf ( "local: %s" , localEtag )
2022-07-22 19:07:38 +00:00
log . Printf ( "cache: %s" , cache . PrevETag )
2022-07-22 13:39:24 +00:00
return nil
}
}
func main ( ) {
tailnet , ok := os . LookupEnv ( "TS_TAILNET" )
if ! ok {
log . Fatal ( "set envvar TS_TAILNET to your tailnet's name" )
}
apiKey , ok := os . LookupEnv ( "TS_API_KEY" )
2023-02-28 02:05:24 +00:00
oauthId , oiok := os . LookupEnv ( "TS_OAUTH_ID" )
oauthSecret , osok := os . LookupEnv ( "TS_OAUTH_SECRET" )
if ! ok && ( ! oiok || ! osok ) {
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" )
}
2024-01-29 20:52:19 +00:00
if apiKey != "" && ( oauthId != "" || oauthSecret != "" ) {
2023-02-28 02:05:24 +00:00
log . Fatal ( "set either the envvar TS_API_KEY or TS_OAUTH_ID and TS_OAUTH_SECRET" )
}
var client * http . Client
2024-02-03 01:33:50 +00:00
if oiok && ( oauthId != "" || oauthSecret != "" ) {
// Both should ideally be set, but if either are non-empty it means the user had an intent
// to set _something_, so they should receive the oauth error flow.
2023-02-28 02:05:24 +00:00
oauthConfig := & clientcredentials . Config {
ClientID : oauthId ,
ClientSecret : oauthSecret ,
TokenURL : fmt . Sprintf ( "https://%s/api/v2/oauth/token" , * apiServer ) ,
}
client = oauthConfig . Client ( context . Background ( ) )
} else {
client = http . DefaultClient
2022-07-22 13:39:24 +00:00
}
2022-07-22 19:07:38 +00:00
cache , err := LoadCache ( * cacheFname )
if err != nil {
if os . IsNotExist ( err ) {
cache = & Cache { }
} else {
log . Fatalf ( "error loading cache: %v" , err )
}
}
defer cache . Save ( * cacheFname )
2022-07-22 13:39:24 +00:00
applyCmd := & ffcli . Command {
Name : "apply" ,
ShortUsage : "gitops-pusher [options] apply" ,
ShortHelp : "Pushes changes to CONTROL" ,
LongHelp : ` Pushes changes to CONTROL ` ,
2023-02-28 02:05:24 +00:00
Exec : apply ( cache , client , tailnet , apiKey ) ,
2022-07-22 13:39:24 +00:00
}
testCmd := & ffcli . Command {
Name : "test" ,
ShortUsage : "gitops-pusher [options] test" ,
ShortHelp : "Tests ACL changes" ,
LongHelp : "Tests ACL changes" ,
2023-02-28 02:05:24 +00:00
Exec : test ( cache , client , tailnet , apiKey ) ,
2022-07-22 13:39:24 +00:00
}
cksumCmd := & ffcli . Command {
Name : "checksum" ,
ShortUsage : "Shows checksums of ACL files" ,
ShortHelp : "Fetch checksum of CONTROL's ACL and the local ACL for comparison" ,
LongHelp : "Fetch checksum of CONTROL's ACL and the local ACL for comparison" ,
2023-02-28 02:05:24 +00:00
Exec : getChecksums ( cache , client , tailnet , apiKey ) ,
2022-07-22 13:39:24 +00:00
}
root := & ffcli . Command {
ShortUsage : "gitops-pusher [options] <command>" ,
ShortHelp : "Push Tailscale ACLs to CONTROL using a GitOps workflow" ,
Subcommands : [ ] * ffcli . Command { applyCmd , cksumCmd , testCmd } ,
FlagSet : rootFlagSet ,
}
if err := root . Parse ( os . Args [ 1 : ] ) ; err != nil {
log . Fatal ( err )
}
ctx , cancel := context . WithTimeout ( context . Background ( ) , * timeout )
defer cancel ( )
if err := root . Run ( ctx ) ; err != nil {
fmt . Println ( err )
os . Exit ( 1 )
2022-06-21 20:04:48 +00:00
}
}
func sumFile ( fname string ) ( string , error ) {
2022-07-15 15:09:44 +00:00
data , err := os . ReadFile ( fname )
if err != nil {
return "" , err
}
formatted , err := hujson . Format ( data )
2022-06-21 20:04:48 +00:00
if err != nil {
return "" , err
}
h := sha256 . New ( )
2022-07-15 15:09:44 +00:00
_ , err = h . Write ( formatted )
2022-06-21 20:04:48 +00:00
if err != nil {
return "" , err
}
2022-07-22 19:07:38 +00:00
return fmt . Sprintf ( "%x" , h . Sum ( nil ) ) , nil
2022-06-21 20:04:48 +00:00
}
2023-02-28 02:05:24 +00:00
func applyNewACL ( ctx context . Context , client * http . Client , tailnet , apiKey , policyFname , oldEtag string ) error {
2022-06-21 20:04:48 +00:00
fin , err := os . Open ( policyFname )
if err != nil {
return err
}
defer fin . Close ( )
2023-01-27 03:35:26 +00:00
req , err := http . NewRequestWithContext ( ctx , httpm . POST , fmt . Sprintf ( "https://%s/api/v2/tailnet/%s/acl" , * apiServer , tailnet ) , fin )
2022-06-21 20:04:48 +00:00
if err != nil {
return err
}
req . SetBasicAuth ( apiKey , "" )
req . Header . Set ( "Content-Type" , "application/hujson" )
2022-07-25 13:09:32 +00:00
req . Header . Set ( "If-Match" , ` " ` + oldEtag + ` " ` )
2022-06-21 20:04:48 +00:00
2023-02-28 02:05:24 +00:00
resp , err := client . Do ( req )
2022-06-21 20:04:48 +00:00
if err != nil {
return err
}
defer resp . Body . Close ( )
got := resp . StatusCode
want := http . StatusOK
if got != want {
2023-07-19 14:47:16 +00:00
var ate ACLGitopsTestError
2022-07-08 14:53:50 +00:00
err := json . NewDecoder ( resp . Body ) . Decode ( & ate )
if err != nil {
return err
}
return ate
2022-06-21 20:04:48 +00:00
}
return nil
}
2023-02-28 02:05:24 +00:00
func testNewACLs ( ctx context . Context , client * http . Client , tailnet , apiKey , policyFname string ) error {
2022-09-01 17:38:32 +00:00
data , err := os . ReadFile ( policyFname )
if err != nil {
return err
}
data , err = hujson . Standardize ( data )
2022-06-21 20:04:48 +00:00
if err != nil {
return err
}
2023-01-27 03:35:26 +00:00
req , err := http . NewRequestWithContext ( ctx , httpm . POST , fmt . Sprintf ( "https://%s/api/v2/tailnet/%s/acl/validate" , * apiServer , tailnet ) , bytes . NewBuffer ( data ) )
2022-06-21 20:04:48 +00:00
if err != nil {
return err
}
req . SetBasicAuth ( apiKey , "" )
req . Header . Set ( "Content-Type" , "application/hujson" )
2023-02-28 02:05:24 +00:00
resp , err := client . Do ( req )
2022-06-21 20:04:48 +00:00
if err != nil {
return err
}
defer resp . Body . Close ( )
2023-07-19 14:47:16 +00:00
var ate ACLGitopsTestError
2022-07-08 14:53:50 +00:00
err = json . NewDecoder ( resp . Body ) . Decode ( & ate )
if err != nil {
return err
}
2022-06-21 20:04:48 +00:00
2022-07-15 14:20:54 +00:00
if len ( ate . Message ) != 0 || len ( ate . Data ) != 0 {
2022-06-21 20:04:48 +00:00
return ate
}
2022-07-22 17:53:42 +00:00
got := resp . StatusCode
want := http . StatusOK
if got != want {
return fmt . Errorf ( "wanted HTTP status code %d but got %d" , want , got )
}
2022-06-21 20:04:48 +00:00
return nil
}
2022-07-21 17:02:14 +00:00
var lineColMessageSplit = regexp . MustCompile ( ` line ([0-9]+), column ([0-9]+): (.*)$ ` )
2022-07-15 14:20:54 +00:00
2023-07-19 14:47:16 +00:00
// ACLGitopsTestError is redefined here so we can add a custom .Error() response
type ACLGitopsTestError struct {
tailscale . ACLTestError
2022-06-21 20:04:48 +00:00
}
2023-07-19 14:47:16 +00:00
func ( ate ACLGitopsTestError ) Error ( ) string {
2022-06-21 20:04:48 +00:00
var sb strings . Builder
2022-07-15 14:20:54 +00:00
if * githubSyntax && lineColMessageSplit . MatchString ( ate . Message ) {
sp := lineColMessageSplit . FindStringSubmatch ( ate . Message )
line := sp [ 1 ]
col := sp [ 2 ]
msg := sp [ 3 ]
fmt . Fprintf ( & sb , "::error file=%s,line=%s,col=%s::%s" , * policyFname , line , col , msg )
} else {
fmt . Fprintln ( & sb , ate . Message )
}
2022-06-21 20:04:48 +00:00
fmt . Fprintln ( & sb )
for _ , data := range ate . Data {
2023-07-19 14:47:16 +00:00
if data . User != "" {
fmt . Fprintf ( & sb , "For user %s:\n" , data . User )
}
if len ( data . Errors ) > 0 {
fmt . Fprint ( & sb , "Errors found:\n" )
for _ , err := range data . Errors {
fmt . Fprintf ( & sb , "- %s\n" , err )
}
}
if len ( data . Warnings ) > 0 {
fmt . Fprint ( & sb , "Warnings found:\n" )
for _ , err := range data . Warnings {
fmt . Fprintf ( & sb , "- %s\n" , err )
}
2022-06-21 20:04:48 +00:00
}
}
return sb . String ( )
}
2023-02-28 02:05:24 +00:00
func getACLETag ( ctx context . Context , client * http . Client , tailnet , apiKey string ) ( string , error ) {
2023-01-27 03:35:26 +00:00
req , err := http . NewRequestWithContext ( ctx , httpm . GET , fmt . Sprintf ( "https://%s/api/v2/tailnet/%s/acl" , * apiServer , tailnet ) , nil )
2022-06-21 20:04:48 +00:00
if err != nil {
return "" , err
}
req . SetBasicAuth ( apiKey , "" )
req . Header . Set ( "Accept" , "application/hujson" )
2023-02-28 02:05:24 +00:00
resp , err := client . Do ( req )
2022-06-21 20:04:48 +00:00
if err != nil {
return "" , err
}
defer resp . Body . Close ( )
got := resp . StatusCode
want := http . StatusOK
if got != want {
return "" , fmt . Errorf ( "wanted HTTP status code %d but got %d" , want , got )
}
2022-07-22 19:07:38 +00:00
return Shuck ( resp . Header . Get ( "ETag" ) ) , nil
2022-06-21 20:04:48 +00:00
}