diff --git a/.golangci.yaml b/.golangci.yaml index 08528b8..4902810 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -29,7 +29,6 @@ linters: - gocritic # We should strive to enable these: - - stylecheck - wrapcheck - goerr113 - forcetypeassert diff --git a/acls.go b/acls.go index 3f94663..1550c34 100644 --- a/acls.go +++ b/acls.go @@ -25,11 +25,11 @@ const ( ) const ( - PORT_RANGE_BEGIN = 0 - PORT_RANGE_END = 65535 - BASE_10 = 10 - BIT_SIZE_16 = 16 - EXPECTED_TOKEN_ITEMS = 2 + Base10 = 10 + BitSize16 = 16 + portRangeBegin = 0 + portRangeEnd = 65535 + expectedTokenItems = 2 ) // LoadACLPolicy loads the ACL policy from the specify path, and generates the ACL rules. @@ -122,7 +122,7 @@ func (h *Headscale) generateACLPolicyDestPorts( d string, ) ([]tailcfg.NetPortRange, error) { tokens := strings.Split(d, ":") - if len(tokens) < EXPECTED_TOKEN_ITEMS || len(tokens) > 3 { + if len(tokens) < expectedTokenItems || len(tokens) > 3 { return nil, errInvalidPortFormat } @@ -133,7 +133,7 @@ func (h *Headscale) generateACLPolicyDestPorts( // tag:montreal-webserver:80,443 // tag:api-server:443 // example-host-1:* - if len(tokens) == EXPECTED_TOKEN_ITEMS { + if len(tokens) == expectedTokenItems { alias = tokens[0] } else { alias = fmt.Sprintf("%s:%s", tokens[0], tokens[1]) @@ -257,7 +257,7 @@ func (h *Headscale) expandAlias(alias string) ([]string, error) { func (h *Headscale) expandPorts(portsStr string) (*[]tailcfg.PortRange, error) { if portsStr == "*" { return &[]tailcfg.PortRange{ - {First: PORT_RANGE_BEGIN, Last: PORT_RANGE_END}, + {First: portRangeBegin, Last: portRangeEnd}, }, nil } @@ -266,7 +266,7 @@ func (h *Headscale) expandPorts(portsStr string) (*[]tailcfg.PortRange, error) { rang := strings.Split(portStr, "-") switch len(rang) { case 1: - port, err := strconv.ParseUint(rang[0], BASE_10, BIT_SIZE_16) + port, err := strconv.ParseUint(rang[0], Base10, BitSize16) if err != nil { return nil, err } @@ -275,12 +275,12 @@ func (h *Headscale) expandPorts(portsStr string) (*[]tailcfg.PortRange, error) { Last: uint16(port), }) - case EXPECTED_TOKEN_ITEMS: - start, err := strconv.ParseUint(rang[0], BASE_10, BIT_SIZE_16) + case expectedTokenItems: + start, err := strconv.ParseUint(rang[0], Base10, BitSize16) if err != nil { return nil, err } - last, err := strconv.ParseUint(rang[1], BASE_10, BIT_SIZE_16) + last, err := strconv.ParseUint(rang[1], Base10, BitSize16) if err != nil { return nil, err } diff --git a/acls_types.go b/acls_types.go index f6557bf..08e650f 100644 --- a/acls_types.go +++ b/acls_types.go @@ -43,18 +43,18 @@ type ACLTest struct { // UnmarshalJSON allows to parse the Hosts directly into netaddr objects. func (hosts *Hosts) UnmarshalJSON(data []byte) error { newHosts := Hosts{} - hostIpPrefixMap := make(map[string]string) + hostIPPrefixMap := make(map[string]string) ast, err := hujson.Parse(data) if err != nil { return err } ast.Standardize() data = ast.Pack() - err = json.Unmarshal(data, &hostIpPrefixMap) + err = json.Unmarshal(data, &hostIPPrefixMap) if err != nil { return err } - for host, prefixStr := range hostIpPrefixMap { + for host, prefixStr := range hostIPPrefixMap { if !strings.Contains(prefixStr, "/") { prefixStr += "/32" } diff --git a/api.go b/api.go index fb8c49c..85c28e3 100644 --- a/api.go +++ b/api.go @@ -18,7 +18,7 @@ import ( "tailscale.com/types/wgkey" ) -const RESERVED_RESPONSE_HEADER_SIZE = 4 +const reservedResponseHeaderSize = 4 // KeyHandler provides the Headscale pub key // Listens in /key. @@ -367,7 +367,7 @@ func (h *Headscale) getMapResponse( } } // declare the incoming size on the first 4 bytes - data := make([]byte, RESERVED_RESPONSE_HEADER_SIZE) + data := make([]byte, reservedResponseHeaderSize) binary.LittleEndian.PutUint32(data, uint32(len(respBody))) data = append(data, respBody...) @@ -397,7 +397,7 @@ func (h *Headscale) getMapKeepAliveResponse( return nil, err } } - data := make([]byte, RESERVED_RESPONSE_HEADER_SIZE) + data := make([]byte, reservedResponseHeaderSize) binary.LittleEndian.PutUint32(data, uint32(len(respBody))) data = append(data, respBody...) diff --git a/app.go b/app.go index a0aa238..17677d4 100644 --- a/app.go +++ b/app.go @@ -47,11 +47,11 @@ import ( ) const ( - AUTH_PREFIX = "Bearer " - POSTGRESQL = "postgresql" - SQLITE = "sqlite3" - UPDATE_RATE_MILLISECONDS = 5000 - HTTP_READ_TIMEOUT = 30 * time.Second + AuthPrefix = "Bearer " + Postgres = "postgresql" + Sqlite = "sqlite3" + updateInterval = 5000 + HTTPReadTimeout = 30 * time.Second ) // Config contains the initial Headscale configuration. @@ -154,7 +154,7 @@ func NewHeadscale(cfg Config) (*Headscale, error) { var dbString string switch cfg.DBtype { - case POSTGRESQL: + case Postgres: dbString = fmt.Sprintf( "host=%s port=%d dbname=%s user=%s password=%s sslmode=disable", cfg.DBhost, @@ -163,7 +163,7 @@ func NewHeadscale(cfg Config) (*Headscale, error) { cfg.DBuser, cfg.DBpass, ) - case SQLITE: + case Sqlite: dbString = cfg.DBpath default: return nil, errors.New("unsupported DB") @@ -321,7 +321,7 @@ func (h *Headscale) grpcAuthenticationInterceptor(ctx context.Context, token := authHeader[0] - if !strings.HasPrefix(token, AUTH_PREFIX) { + if !strings.HasPrefix(token, AuthPrefix) { log.Error(). Caller(). Str("client_address", client.Addr.String()). @@ -363,7 +363,7 @@ func (h *Headscale) httpAuthenticationMiddleware(ctx *gin.Context) { authHeader := ctx.GetHeader("authorization") - if !strings.HasPrefix(authHeader, AUTH_PREFIX) { + if !strings.HasPrefix(authHeader, AuthPrefix) { log.Error(). Caller(). Str("client_address", ctx.ClientIP()). @@ -511,13 +511,13 @@ func (h *Headscale) Serve() error { } // I HATE THIS - go h.watchForKVUpdates(UPDATE_RATE_MILLISECONDS) - go h.expireEphemeralNodes(UPDATE_RATE_MILLISECONDS) + go h.watchForKVUpdates(updateInterval) + go h.expireEphemeralNodes(updateInterval) httpServer := &http.Server{ Addr: h.cfg.Addr, Handler: router, - ReadTimeout: HTTP_READ_TIMEOUT, + ReadTimeout: HTTPReadTimeout, // Go does not handle timeouts in HTTP very well, and there is // no good way to handle streaming timeouts, therefore we need to // keep this at unlimited and be careful to clean up connections diff --git a/apple_mobileconfig.go b/apple_mobileconfig.go index 8989c27..2e454df 100644 --- a/apple_mobileconfig.go +++ b/apple_mobileconfig.go @@ -55,7 +55,7 @@ func (h *Headscale) AppleMobileConfig(ctx *gin.Context) {

Or

Use your terminal to configure the default setting for Tailscale by issuing:

- defaults write io.tailscale.ipn.macos ControlURL {{.Url}} + defaults write io.tailscale.ipn.macos ControlURL {{.URL}}

Restart Tailscale.app and log in.

@@ -63,7 +63,7 @@ func (h *Headscale) AppleMobileConfig(ctx *gin.Context) { `)) config := map[string]interface{}{ - "Url": h.cfg.ServerURL, + "URL": h.cfg.ServerURL, } var payload bytes.Buffer @@ -102,7 +102,7 @@ func (h *Headscale) ApplePlatformConfig(ctx *gin.Context) { return } - contentId, err := uuid.NewV4() + contentID, err := uuid.NewV4() if err != nil { log.Error(). Str("handler", "ApplePlatformConfig"). @@ -118,8 +118,8 @@ func (h *Headscale) ApplePlatformConfig(ctx *gin.Context) { } platformConfig := AppleMobilePlatformConfig{ - UUID: contentId, - Url: h.cfg.ServerURL, + UUID: contentID, + URL: h.cfg.ServerURL, } var payload bytes.Buffer @@ -165,7 +165,7 @@ func (h *Headscale) ApplePlatformConfig(ctx *gin.Context) { config := AppleMobileConfig{ UUID: id, - Url: h.cfg.ServerURL, + URL: h.cfg.ServerURL, Payload: payload.String(), } @@ -193,13 +193,13 @@ func (h *Headscale) ApplePlatformConfig(ctx *gin.Context) { type AppleMobileConfig struct { UUID uuid.UUID - Url string + URL string Payload string } type AppleMobilePlatformConfig struct { UUID uuid.UUID - Url string + URL string } var commonTemplate = template.Must( @@ -212,7 +212,7 @@ var commonTemplate = template.Must( PayloadDisplayName Headscale PayloadDescription - Configure Tailscale login server to: {{.Url}} + Configure Tailscale login server to: {{.URL}} PayloadIdentifier com.github.juanfont.headscale PayloadRemovalDisallowed @@ -243,7 +243,7 @@ var iosTemplate = template.Must(template.New("iosTemplate").Parse(` ControlURL - {{.Url}} + {{.URL}} `)) @@ -261,6 +261,6 @@ var macosTemplate = template.Must(template.New("macosTemplate").Parse(` ControlURL - {{.Url}} + {{.URL}} `)) diff --git a/cmd/headscale/cli/namespaces.go b/cmd/headscale/cli/namespaces.go index 8c6f10a..28958ec 100644 --- a/cmd/headscale/cli/namespaces.go +++ b/cmd/headscale/cli/namespaces.go @@ -29,7 +29,7 @@ var createNamespaceCmd = &cobra.Command{ Short: "Creates a new namespace", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { - return fmt.Errorf("Missing parameters") + return fmt.Errorf("missing parameters") } return nil @@ -71,7 +71,7 @@ var destroyNamespaceCmd = &cobra.Command{ Short: "Destroys a namespace", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { - return fmt.Errorf("Missing parameters") + return fmt.Errorf("missing parameters") } return nil @@ -197,7 +197,7 @@ var renameNamespaceCmd = &cobra.Command{ Args: func(cmd *cobra.Command, args []string) error { expectedArguments := 2 if len(args) < expectedArguments { - return fmt.Errorf("Missing parameters") + return fmt.Errorf("missing parameters") } return nil diff --git a/cmd/headscale/cli/nodes.go b/cmd/headscale/cli/nodes.go index c644ad9..218d25b 100644 --- a/cmd/headscale/cli/nodes.go +++ b/cmd/headscale/cli/nodes.go @@ -451,7 +451,7 @@ func nodesToPtables( tableData = append( tableData, []string{ - strconv.FormatUint(machine.Id, headscale.BASE_10), + strconv.FormatUint(machine.Id, headscale.Base10), machine.Name, nodeKey.ShortString(), namespace, diff --git a/cmd/headscale/cli/preauthkeys.go b/cmd/headscale/cli/preauthkeys.go index b28e600..d14193f 100644 --- a/cmd/headscale/cli/preauthkeys.go +++ b/cmd/headscale/cli/preauthkeys.go @@ -13,7 +13,7 @@ import ( ) const ( - DEFAULT_PRE_AUTH_KEY_EXPIRY = 24 * time.Hour + DefaultPreAuthKeyExpiry = 24 * time.Hour ) func init() { @@ -31,7 +31,7 @@ func init() { createPreAuthKeyCmd.PersistentFlags(). Bool("ephemeral", false, "Preauthkey for ephemeral nodes") createPreAuthKeyCmd.Flags(). - DurationP("expiration", "e", DEFAULT_PRE_AUTH_KEY_EXPIRY, "Human-readable expiration of the key (30m, 24h, 365d...)") + DurationP("expiration", "e", DefaultPreAuthKeyExpiry, "Human-readable expiration of the key (30m, 24h, 365d...)") } var preauthkeysCmd = &cobra.Command{ diff --git a/cmd/headscale/cli/routes.go b/cmd/headscale/cli/routes.go index 7d0fcbf..ced1a0b 100644 --- a/cmd/headscale/cli/routes.go +++ b/cmd/headscale/cli/routes.go @@ -45,7 +45,7 @@ var listRoutesCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { output, _ := cmd.Flags().GetString("output") - machineId, err := cmd.Flags().GetUint64("identifier") + machineID, err := cmd.Flags().GetUint64("identifier") if err != nil { ErrorOutput( err, @@ -61,7 +61,7 @@ var listRoutesCmd = &cobra.Command{ defer conn.Close() request := &v1.GetMachineRouteRequest{ - MachineId: machineId, + MachineId: machineID, } response, err := client.GetMachineRoute(ctx, request) @@ -111,7 +111,8 @@ omit the route you do not want to enable. `, Run: func(cmd *cobra.Command, args []string) { output, _ := cmd.Flags().GetString("output") - machineId, err := cmd.Flags().GetUint64("identifier") + + machineID, err := cmd.Flags().GetUint64("identifier") if err != nil { ErrorOutput( err, @@ -138,7 +139,7 @@ omit the route you do not want to enable. defer conn.Close() request := &v1.EnableMachineRoutesRequest{ - MachineId: machineId, + MachineId: machineID, Routes: routes, } diff --git a/cmd/headscale/cli/utils.go b/cmd/headscale/cli/utils.go index f60a72c..a90a3c0 100644 --- a/cmd/headscale/cli/utils.go +++ b/cmd/headscale/cli/utils.go @@ -53,7 +53,7 @@ func LoadConfig(path string) error { viper.SetDefault("cli.timeout", "5s") if err := viper.ReadInConfig(); err != nil { - return fmt.Errorf("Fatal error reading config file: %w", err) + return fmt.Errorf("fatal error reading config file: %w", err) } // Collect any validation errors and return them all at once @@ -306,7 +306,7 @@ func getHeadscaleApp() (*headscale.Headscale, error) { minInactivityTimeout, _ := time.ParseDuration("65s") if viper.GetDuration("ephemeral_node_inactivity_timeout") <= minInactivityTimeout { err := fmt.Errorf( - "ephemeral_node_inactivity_timeout (%s) is set too low, must be more than %s\n", + "ephemeral_node_inactivity_timeout (%s) is set too low, must be more than %s", viper.GetString("ephemeral_node_inactivity_timeout"), minInactivityTimeout, ) diff --git a/db.go b/db.go index fa20060..503eedc 100644 --- a/db.go +++ b/db.go @@ -24,7 +24,7 @@ func (h *Headscale) initDB() error { } h.db = db - if h.dbType == POSTGRESQL { + if h.dbType == Postgres { db.Exec("create extension if not exists \"uuid-ossp\";") } err = db.AutoMigrate(&Machine{}) @@ -66,12 +66,12 @@ func (h *Headscale) openDB() (*gorm.DB, error) { } switch h.dbType { - case SQLITE: + case Sqlite: db, err = gorm.Open(sqlite.Open(h.dbString), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true, Logger: log, }) - case POSTGRESQL: + case Postgres: db, err = gorm.Open(postgres.Open(h.dbString), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true, Logger: log, diff --git a/derp.go b/derp.go index cf128a8..63e448d 100644 --- a/derp.go +++ b/derp.go @@ -32,7 +32,7 @@ func loadDERPMapFromPath(path string) (*tailcfg.DERPMap, error) { } func loadDERPMapFromURL(addr url.URL) (*tailcfg.DERPMap, error) { - ctx, cancel := context.WithTimeout(context.Background(), HTTP_READ_TIMEOUT) + ctx, cancel := context.WithTimeout(context.Background(), HTTPReadTimeout) defer cancel() req, err := http.NewRequestWithContext(ctx, "GET", addr.String(), nil) @@ -41,7 +41,7 @@ func loadDERPMapFromURL(addr url.URL) (*tailcfg.DERPMap, error) { } client := http.Client{ - Timeout: HTTP_READ_TIMEOUT, + Timeout: HTTPReadTimeout, } resp, err := client.Do(req) diff --git a/dns.go b/dns.go index cb986cf..af6f989 100644 --- a/dns.go +++ b/dns.go @@ -11,7 +11,7 @@ import ( ) const ( - BYTE_SIZE = 8 + ByteSize = 8 ) // generateMagicDNSRootDomains generates a list of DNS entries to be included in `Routes` in `MapResponse`. @@ -47,10 +47,10 @@ func generateMagicDNSRootDomains( maskBits, _ := netRange.Mask.Size() // lastOctet is the last IP byte covered by the mask - lastOctet := maskBits / BYTE_SIZE + lastOctet := maskBits / ByteSize // wildcardBits is the number of bits not under the mask in the lastOctet - wildcardBits := BYTE_SIZE - maskBits%BYTE_SIZE + wildcardBits := ByteSize - maskBits%ByteSize // min is the value in the lastOctet byte of the IP // max is basically 2^wildcardBits - i.e., the value when all the wildcardBits are set to 1 diff --git a/grpcv1.go b/grpcv1.go index 4366446..40419c3 100644 --- a/grpcv1.go +++ b/grpcv1.go @@ -338,7 +338,7 @@ func (api headscaleV1APIServer) DebugCreateMachine( return nil, err } - routes, err := stringToIpPrefix(request.GetRoutes()) + routes, err := stringToIPPrefix(request.GetRoutes()) if err != nil { return nil, err } diff --git a/machine.go b/machine.go index 8aee68e..be6d446 100644 --- a/machine.go +++ b/machine.go @@ -529,7 +529,7 @@ func (machine Machine) toNode( node := tailcfg.Node{ ID: tailcfg.NodeID(machine.ID), // this is the actual ID StableID: tailcfg.StableNodeID( - strconv.FormatUint(machine.ID, BASE_10), + strconv.FormatUint(machine.ID, Base10), ), // in headscale, unlike tailcontrol server, IDs are permanent Name: hostname, User: tailcfg.UserID(machine.NamespaceID), @@ -736,7 +736,7 @@ func (h *Headscale) EnableRoutes(machine *Machine, routeStrs ...string) error { } for _, newRoute := range newRoutes { - if !containsIpPrefix(availableRoutes, newRoute) { + if !containsIPPrefix(availableRoutes, newRoute) { return fmt.Errorf( "route (%s) is not available on node %s", machine.Name, diff --git a/namespaces.go b/namespaces.go index 9ee7bf1..bb58c00 100644 --- a/namespaces.go +++ b/namespaces.go @@ -321,7 +321,7 @@ func getMapResponseUserProfiles(machine Machine, peers Machines) []tailcfg.UserP func (n *Namespace) toProto() *v1.Namespace { return &v1.Namespace{ - Id: strconv.FormatUint(uint64(n.ID), BASE_10), + Id: strconv.FormatUint(uint64(n.ID), Base10), Name: n.Name, CreatedAt: timestamppb.New(n.CreatedAt), } diff --git a/oidc.go b/oidc.go index 7e24ed3..07561e8 100644 --- a/oidc.go +++ b/oidc.go @@ -18,9 +18,9 @@ import ( ) const ( - OIDC_STATE_CACHE_EXPIRATION = time.Minute * 5 - OIDC_STATE_CACHE_CLEANUP_INTERVAL = time.Minute * 10 - RANDOM_BYTE_SIZE = 16 + oidcStateCacheExpiration = time.Minute * 5 + oidcStateCacheCleanupInterval = time.Minute * 10 + randomByteSize = 16 ) type IDTokenClaims struct { @@ -57,8 +57,8 @@ func (h *Headscale) initOIDC() error { // init the state cache if it hasn't been already if h.oidcStateCache == nil { h.oidcStateCache = cache.New( - OIDC_STATE_CACHE_EXPIRATION, - OIDC_STATE_CACHE_CLEANUP_INTERVAL, + oidcStateCacheExpiration, + oidcStateCacheCleanupInterval, ) } @@ -76,7 +76,7 @@ func (h *Headscale) RegisterOIDC(ctx *gin.Context) { return } - randomBlob := make([]byte, RANDOM_BYTE_SIZE) + randomBlob := make([]byte, randomByteSize) if _, err := rand.Read(randomBlob); err != nil { log.Error().Msg("could not read 16 bytes from rand") ctx.String(http.StatusInternalServerError, "could not read 16 bytes from rand") @@ -87,12 +87,12 @@ func (h *Headscale) RegisterOIDC(ctx *gin.Context) { stateStr := hex.EncodeToString(randomBlob)[:32] // place the machine key into the state cache, so it can be retrieved later - h.oidcStateCache.Set(stateStr, mKeyStr, OIDC_STATE_CACHE_EXPIRATION) + h.oidcStateCache.Set(stateStr, mKeyStr, oidcStateCacheExpiration) - authUrl := h.oauth2Config.AuthCodeURL(stateStr) - log.Debug().Msgf("Redirecting to %s for authentication", authUrl) + authURL := h.oauth2Config.AuthCodeURL(stateStr) + log.Debug().Msgf("Redirecting to %s for authentication", authURL) - ctx.Redirect(http.StatusFound, authUrl) + ctx.Redirect(http.StatusFound, authURL) } // OIDCCallback handles the callback from the OIDC endpoint diff --git a/poll.go b/poll.go index aaf5bd0..9cf14e7 100644 --- a/poll.go +++ b/poll.go @@ -16,8 +16,8 @@ import ( ) const ( - KEEP_ALIVE_INTERVAL = 60 * time.Second - UPDATE_CHECK_INTERVAL = 10 * time.Second + keepAliveInterval = 60 * time.Second + updateCheckInterval = 10 * time.Second ) // PollNetMapHandler takes care of /machine/:id/map @@ -495,8 +495,8 @@ func (h *Headscale) scheduledPollWorker( mapRequest tailcfg.MapRequest, machine *Machine, ) { - keepAliveTicker := time.NewTicker(KEEP_ALIVE_INTERVAL) - updateCheckerTicker := time.NewTicker(UPDATE_CHECK_INTERVAL) + keepAliveTicker := time.NewTicker(keepAliveInterval) + updateCheckerTicker := time.NewTicker(updateCheckInterval) for { select { diff --git a/preauth_keys.go b/preauth_keys.go index 5159a87..9ba70da 100644 --- a/preauth_keys.go +++ b/preauth_keys.go @@ -156,7 +156,7 @@ func (h *Headscale) generateKey() (string, error) { func (key *PreAuthKey) toProto() *v1.PreAuthKey { protoKey := v1.PreAuthKey{ Namespace: key.Namespace.Name, - Id: strconv.FormatUint(key.ID, BASE_10), + Id: strconv.FormatUint(key.ID, Base10), Key: key.Key, Ephemeral: key.Ephemeral, Reusable: key.Reusable, diff --git a/utils.go b/utils.go index e291703..6d62667 100644 --- a/utils.go +++ b/utils.go @@ -197,7 +197,7 @@ func ipPrefixToString(prefixes []netaddr.IPPrefix) []string { return result } -func stringToIpPrefix(prefixes []string) ([]netaddr.IPPrefix, error) { +func stringToIPPrefix(prefixes []string) ([]netaddr.IPPrefix, error) { result := make([]netaddr.IPPrefix, len(prefixes)) for index, prefixStr := range prefixes { @@ -212,7 +212,7 @@ func stringToIpPrefix(prefixes []string) ([]netaddr.IPPrefix, error) { return result, nil } -func containsIpPrefix(prefixes []netaddr.IPPrefix, prefix netaddr.IPPrefix) bool { +func containsIPPrefix(prefixes []netaddr.IPPrefix, prefix netaddr.IPPrefix) bool { for _, p := range prefixes { if prefix == p { return true