mirror of
https://github.com/fleetdm/fleet
synced 2026-04-21 13:37:30 +00:00
Use new error handling approach in other packages (#2954)
This commit is contained in:
parent
2b2e9f9f44
commit
69a4985cac
134 changed files with 1047 additions and 1032 deletions
|
|
@ -20,6 +20,7 @@ linters-settings:
|
|||
include-go-root: false
|
||||
packages-with-error-message:
|
||||
- github.com/rotisserie/eris: "use ctxerr.New or ctxerr.Wrap[f] instead"
|
||||
- github.com/pkg/errors: "use ctxerr if a context.Context is available or stdlib errors.New / fmt.Errorf with the %w verb"
|
||||
|
||||
gofmt:
|
||||
# simplify code: gofmt with `-s` option, true by default
|
||||
|
|
@ -49,10 +50,6 @@ linters-settings:
|
|||
|
||||
issues:
|
||||
exclude-rules:
|
||||
- path: server/contexts/ctxerr/[^/]+\.go$
|
||||
- path: server/datastore/mysql/migrations/[^/]+/[^/]+\.go
|
||||
linters:
|
||||
- depguard
|
||||
- path: server/errorstore/[^/]+\.go$
|
||||
linters:
|
||||
- depguard
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package main
|
|||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/url"
|
||||
|
|
@ -45,7 +46,6 @@ import (
|
|||
"github.com/go-kit/kit/log/level"
|
||||
kitprometheus "github.com/go-kit/kit/metrics/prometheus"
|
||||
"github.com/kolide/kit/version"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"github.com/spf13/cobra"
|
||||
|
|
@ -131,7 +131,7 @@ the way that the Fleet server works.
|
|||
"hostname": true,
|
||||
}
|
||||
if !allowedHostIdentifiers[config.Osquery.HostIdentifier] {
|
||||
initFatal(errors.Errorf("%s is not a valid value for osquery_host_identifier", config.Osquery.HostIdentifier), "set host identifier")
|
||||
initFatal(fmt.Errorf("%s is not a valid value for osquery_host_identifier", config.Osquery.HostIdentifier), "set host identifier")
|
||||
}
|
||||
|
||||
if len(config.Server.URLPrefix) > 0 {
|
||||
|
|
@ -143,7 +143,7 @@ the way that the Fleet server works.
|
|||
|
||||
if !allowedURLPrefixRegexp.MatchString(config.Server.URLPrefix) {
|
||||
initFatal(
|
||||
errors.Errorf("prefix must match regexp \"%s\"", allowedURLPrefixRegexp.String()),
|
||||
fmt.Errorf("prefix must match regexp \"%s\"", allowedURLPrefixRegexp.String()),
|
||||
"setting server URL prefix",
|
||||
)
|
||||
}
|
||||
|
|
@ -750,7 +750,7 @@ func getTLSConfig(profile string) *tls.Config {
|
|||
)
|
||||
default:
|
||||
initFatal(
|
||||
errors.Errorf("%s is invalid", profile),
|
||||
fmt.Errorf("%s is invalid", profile),
|
||||
"set TLS profile",
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package main
|
|||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
|
|
@ -13,7 +14,6 @@ import (
|
|||
"runtime"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/service"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
@ -45,7 +45,7 @@ func clientFromCLI(c *cli.Context) (*service.Client, error) {
|
|||
// Add authentication token
|
||||
t, err := getConfigValue(configPath, context, "token")
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error getting token from the config")
|
||||
return nil, fmt.Errorf("error getting token from the config: %w", err)
|
||||
}
|
||||
|
||||
if token, ok := t.(string); ok {
|
||||
|
|
@ -54,13 +54,13 @@ func clientFromCLI(c *cli.Context) (*service.Client, error) {
|
|||
}
|
||||
fleet.SetToken(token)
|
||||
} else {
|
||||
return nil, errors.Errorf("token config value was not a string: %+v", t)
|
||||
return nil, fmt.Errorf("token config value was not a string: %+v", t)
|
||||
}
|
||||
|
||||
// Perform a "/me" request to verify the session is valid.
|
||||
response, err := fleet.AuthenticatedDo("GET", "/api/v1/fleet/me", "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "Failed to execute session check")
|
||||
return nil, fmt.Errorf("Failed to execute session check: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -70,7 +70,7 @@ func clientFromCLI(c *cli.Context) (*service.Client, error) {
|
|||
case http.StatusUnauthorized:
|
||||
return nil, invalidSessionErr
|
||||
default:
|
||||
return nil, errors.Errorf("session check received status: %d", response.StatusCode)
|
||||
return nil, fmt.Errorf("session check received status: %d", response.StatusCode)
|
||||
}
|
||||
|
||||
return fleet, nil
|
||||
|
|
@ -104,7 +104,7 @@ func unauthenticatedClientFromConfig(cc Context, debug bool, w io.Writer) (*serv
|
|||
options...,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error creating Fleet API client handler")
|
||||
return nil, fmt.Errorf("error creating Fleet API client handler: %w", err)
|
||||
}
|
||||
|
||||
return fleet, nil
|
||||
|
|
@ -121,7 +121,7 @@ func rawHTTPClientFromConfig(cc Context) (*http.Client, *url.URL, error) {
|
|||
}
|
||||
baseURL, err := url.Parse(cc.Address)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, "parse address")
|
||||
return nil, nil, fmt.Errorf("parse address: %w", err)
|
||||
}
|
||||
|
||||
var rootCA *x509.CertPool
|
||||
|
|
@ -130,7 +130,7 @@ func rawHTTPClientFromConfig(cc Context) (*http.Client, *url.URL, error) {
|
|||
// read in the root cert file specified in the context
|
||||
certs, err := ioutil.ReadFile(cc.RootCA)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, "reading root CA")
|
||||
return nil, nil, fmt.Errorf("reading root CA: %w", err)
|
||||
}
|
||||
|
||||
// add certs to pool
|
||||
|
|
@ -161,7 +161,7 @@ func clientConfigFromCLI(c *cli.Context) (Context, error) {
|
|||
var zeroCtx Context
|
||||
|
||||
if err := makeConfigIfNotExists(c.String("config")); err != nil {
|
||||
return zeroCtx, errors.Wrapf(err, "error verifying that config exists at %s", c.String("config"))
|
||||
return zeroCtx, fmt.Errorf("error verifying that config exists at %s: %w", c.String("config"), err)
|
||||
}
|
||||
|
||||
config, err := readConfig(c.String("config"))
|
||||
|
|
|
|||
|
|
@ -2,13 +2,14 @@ package main
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/ghodss/yaml"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
@ -52,7 +53,7 @@ func specGroupFromBytes(b []byte) (*specGroup, error) {
|
|||
}
|
||||
|
||||
if s.Spec == nil {
|
||||
return nil, errors.Errorf("no spec field on %q document", s.Kind)
|
||||
return nil, fmt.Errorf("no spec field on %q document", s.Kind)
|
||||
}
|
||||
|
||||
kind := strings.ToLower(s.Kind)
|
||||
|
|
@ -61,21 +62,21 @@ func specGroupFromBytes(b []byte) (*specGroup, error) {
|
|||
case fleet.QueryKind:
|
||||
var querySpec *fleet.QuerySpec
|
||||
if err := yaml.Unmarshal(s.Spec, &querySpec); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
|
||||
return nil, fmt.Errorf("unmarshaling "+kind+" spec: %w", err)
|
||||
}
|
||||
specs.Queries = append(specs.Queries, querySpec)
|
||||
|
||||
case fleet.PackKind:
|
||||
var packSpec *fleet.PackSpec
|
||||
if err := yaml.Unmarshal(s.Spec, &packSpec); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
|
||||
return nil, fmt.Errorf("unmarshaling "+kind+" spec: %w", err)
|
||||
}
|
||||
specs.Packs = append(specs.Packs, packSpec)
|
||||
|
||||
case fleet.LabelKind:
|
||||
var labelSpec *fleet.LabelSpec
|
||||
if err := yaml.Unmarshal(s.Spec, &labelSpec); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
|
||||
return nil, fmt.Errorf("unmarshaling "+kind+" spec: %w", err)
|
||||
}
|
||||
specs.Labels = append(specs.Labels, labelSpec)
|
||||
|
||||
|
|
@ -86,7 +87,7 @@ func specGroupFromBytes(b []byte) (*specGroup, error) {
|
|||
|
||||
var appConfigSpec interface{}
|
||||
if err := yaml.Unmarshal(s.Spec, &appConfigSpec); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
|
||||
return nil, fmt.Errorf("unmarshaling "+kind+" spec: %w", err)
|
||||
}
|
||||
specs.AppConfig = appConfigSpec
|
||||
|
||||
|
|
@ -97,26 +98,26 @@ func specGroupFromBytes(b []byte) (*specGroup, error) {
|
|||
|
||||
var enrollSecretSpec *fleet.EnrollSecretSpec
|
||||
if err := yaml.Unmarshal(s.Spec, &enrollSecretSpec); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
|
||||
return nil, fmt.Errorf("unmarshaling "+kind+" spec: %w", err)
|
||||
}
|
||||
specs.EnrollSecret = enrollSecretSpec
|
||||
|
||||
case fleet.UserRolesKind:
|
||||
var userRoleSpec *fleet.UsersRoleSpec
|
||||
if err := yaml.Unmarshal(s.Spec, &userRoleSpec); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
|
||||
return nil, fmt.Errorf("unmarshaling "+kind+" spec: %w", err)
|
||||
}
|
||||
specs.UsersRoles = userRoleSpec
|
||||
|
||||
case fleet.TeamKind:
|
||||
var teamSpec TeamSpec
|
||||
if err := yaml.Unmarshal(s.Spec, &teamSpec); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshaling "+kind+" spec")
|
||||
return nil, fmt.Errorf("unmarshaling "+kind+" spec: %w", err)
|
||||
}
|
||||
specs.Teams = append(specs.Teams, teamSpec.Team)
|
||||
|
||||
default:
|
||||
return nil, errors.Errorf("unknown kind %q", s.Kind)
|
||||
return nil, fmt.Errorf("unknown kind %q", s.Kind)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -165,28 +166,28 @@ func applyCommand() *cli.Command {
|
|||
|
||||
if len(specs.Queries) > 0 {
|
||||
if err := fleetClient.ApplyQueries(specs.Queries); err != nil {
|
||||
return errors.Wrap(err, "applying queries")
|
||||
return fmt.Errorf("applying queries: %w", err)
|
||||
}
|
||||
logf(c, "[+] applied %d queries\n", len(specs.Queries))
|
||||
}
|
||||
|
||||
if len(specs.Labels) > 0 {
|
||||
if err := fleetClient.ApplyLabels(specs.Labels); err != nil {
|
||||
return errors.Wrap(err, "applying labels")
|
||||
return fmt.Errorf("applying labels: %w", err)
|
||||
}
|
||||
logf(c, "[+] applied %d labels\n", len(specs.Labels))
|
||||
}
|
||||
|
||||
if len(specs.Packs) > 0 {
|
||||
if err := fleetClient.ApplyPacks(specs.Packs); err != nil {
|
||||
return errors.Wrap(err, "applying packs")
|
||||
return fmt.Errorf("applying packs: %w", err)
|
||||
}
|
||||
logf(c, "[+] applied %d packs\n", len(specs.Packs))
|
||||
}
|
||||
|
||||
if specs.AppConfig != nil {
|
||||
if err := fleetClient.ApplyAppConfig(specs.AppConfig); err != nil {
|
||||
return errors.Wrap(err, "applying fleet config")
|
||||
return fmt.Errorf("applying fleet config: %w", err)
|
||||
}
|
||||
log(c, "[+] applied fleet config\n")
|
||||
|
||||
|
|
@ -194,21 +195,21 @@ func applyCommand() *cli.Command {
|
|||
|
||||
if specs.EnrollSecret != nil {
|
||||
if err := fleetClient.ApplyEnrollSecretSpec(specs.EnrollSecret); err != nil {
|
||||
return errors.Wrap(err, "applying enroll secrets")
|
||||
return fmt.Errorf("applying enroll secrets: %w", err)
|
||||
}
|
||||
log(c, "[+] applied enroll secrets\n")
|
||||
}
|
||||
|
||||
if len(specs.Teams) > 0 {
|
||||
if err := fleetClient.ApplyTeams(specs.Teams); err != nil {
|
||||
return errors.Wrap(err, "applying teams")
|
||||
return fmt.Errorf("applying teams: %w", err)
|
||||
}
|
||||
logf(c, "[+] applied %d teams\n", len(specs.Teams))
|
||||
}
|
||||
|
||||
if specs.UsersRoles != nil {
|
||||
if err := fleetClient.ApplyUsersRoleSecretSpec(specs.UsersRoles); err != nil {
|
||||
return errors.Wrap(err, "applying user roles")
|
||||
return fmt.Errorf("applying user roles: %w", err)
|
||||
}
|
||||
log(c, "[+] applied user roles\n")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
|
@ -9,7 +10,6 @@ import (
|
|||
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/ghodss/yaml"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
@ -75,12 +75,12 @@ func readConfig(fp string) (configFile, error) {
|
|||
}
|
||||
|
||||
if err := yaml.Unmarshal(b, &c); err != nil {
|
||||
return c, errors.Wrap(err, "unmarshal config")
|
||||
return c, fmt.Errorf("unmarshal config: %w", err)
|
||||
}
|
||||
|
||||
if c.Contexts == nil {
|
||||
c.Contexts = map[string]Context{
|
||||
"default": Context{},
|
||||
"default": {},
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
|
|
@ -97,12 +97,12 @@ func writeConfig(fp string, c configFile) error {
|
|||
|
||||
func getConfigValue(configPath, context, key string) (interface{}, error) {
|
||||
if err := makeConfigIfNotExists(configPath); err != nil {
|
||||
return nil, errors.Wrapf(err, "error verifying that config exists at %s", configPath)
|
||||
return nil, fmt.Errorf("error verifying that config exists at %s: %w", configPath, err)
|
||||
}
|
||||
|
||||
config, err := readConfig(configPath)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "error reading config at %s", configPath)
|
||||
return nil, fmt.Errorf("error reading config at %s: %w", configPath, err)
|
||||
}
|
||||
|
||||
currentContext, ok := config.Contexts[context]
|
||||
|
|
@ -134,12 +134,12 @@ func getConfigValue(configPath, context, key string) (interface{}, error) {
|
|||
|
||||
func setConfigValue(configPath, context, key, value string) error {
|
||||
if err := makeConfigIfNotExists(configPath); err != nil {
|
||||
return errors.Wrapf(err, "error verifying that config exists at %s", configPath)
|
||||
return fmt.Errorf("error verifying that config exists at %s: %w", configPath, err)
|
||||
}
|
||||
|
||||
config, err := readConfig(configPath)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "error reading config at %s", configPath)
|
||||
return fmt.Errorf("error reading config at %s: %w", configPath, err)
|
||||
}
|
||||
|
||||
currentContext, ok := config.Contexts[context]
|
||||
|
|
@ -160,7 +160,7 @@ func setConfigValue(configPath, context, key, value string) error {
|
|||
case "tls-skip-verify":
|
||||
boolValue, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "error parsing %q as bool", value)
|
||||
return fmt.Errorf("error parsing %q as bool: %w", value, err)
|
||||
}
|
||||
currentContext.TLSSkipVerify = boolValue
|
||||
case "url-prefix":
|
||||
|
|
@ -172,7 +172,7 @@ func setConfigValue(configPath, context, key, value string) error {
|
|||
config.Contexts[context] = currentContext
|
||||
|
||||
if err := writeConfig(configPath, config); err != nil {
|
||||
return errors.Wrap(err, "error saving config file")
|
||||
return fmt.Errorf("error saving config file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -244,7 +244,7 @@ func configSetCommand() *cli.Command {
|
|||
if flAddress != "" {
|
||||
set = true
|
||||
if err := setConfigValue(configPath, context, "address", flAddress); err != nil {
|
||||
return errors.Wrap(err, "error setting address")
|
||||
return fmt.Errorf("error setting address: %w", err)
|
||||
}
|
||||
fmt.Printf("[+] Set the address config key to %q in the %q context\n", flAddress, c.String("context"))
|
||||
}
|
||||
|
|
@ -252,7 +252,7 @@ func configSetCommand() *cli.Command {
|
|||
if flEmail != "" {
|
||||
set = true
|
||||
if err := setConfigValue(configPath, context, "email", flEmail); err != nil {
|
||||
return errors.Wrap(err, "error setting email")
|
||||
return fmt.Errorf("error setting email: %w", err)
|
||||
}
|
||||
fmt.Printf("[+] Set the email config key to %q in the %q context\n", flEmail, c.String("context"))
|
||||
}
|
||||
|
|
@ -260,7 +260,7 @@ func configSetCommand() *cli.Command {
|
|||
if flToken != "" {
|
||||
set = true
|
||||
if err := setConfigValue(configPath, context, "token", flToken); err != nil {
|
||||
return errors.Wrap(err, "error setting token")
|
||||
return fmt.Errorf("error setting token: %w", err)
|
||||
}
|
||||
fmt.Printf("[+] Set the token config key to %q in the %q context\n", flToken, c.String("context"))
|
||||
}
|
||||
|
|
@ -268,7 +268,7 @@ func configSetCommand() *cli.Command {
|
|||
if flTLSSkipVerify {
|
||||
set = true
|
||||
if err := setConfigValue(configPath, context, "tls-skip-verify", "true"); err != nil {
|
||||
return errors.Wrap(err, "error setting tls-skip-verify")
|
||||
return fmt.Errorf("error setting tls-skip-verify: %w", err)
|
||||
}
|
||||
fmt.Printf("[+] Set the tls-skip-verify config key to \"true\" in the %q context\n", c.String("context"))
|
||||
}
|
||||
|
|
@ -276,7 +276,7 @@ func configSetCommand() *cli.Command {
|
|||
if flRootCA != "" {
|
||||
set = true
|
||||
if err := setConfigValue(configPath, context, "rootca", flRootCA); err != nil {
|
||||
return errors.Wrap(err, "error setting rootca")
|
||||
return fmt.Errorf("error setting rootca: %w", err)
|
||||
}
|
||||
fmt.Printf("[+] Set the rootca config key to %q in the %q context\n", flRootCA, c.String("context"))
|
||||
}
|
||||
|
|
@ -284,7 +284,7 @@ func configSetCommand() *cli.Command {
|
|||
if flURLPrefix != "" {
|
||||
set = true
|
||||
if err := setConfigValue(configPath, context, "url-prefix", flURLPrefix); err != nil {
|
||||
return errors.Wrap(err, "error setting URL Prefix")
|
||||
return fmt.Errorf("error setting URL Prefix: %w", err)
|
||||
}
|
||||
fmt.Printf("[+] Set the url-prefix config key to %q in the %q context\n", flURLPrefix, c.String("context"))
|
||||
}
|
||||
|
|
@ -325,7 +325,7 @@ func configGetCommand() *cli.Command {
|
|||
|
||||
value, err := getConfigValue(configPath, context, key)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error getting config value")
|
||||
return fmt.Errorf("error getting config value: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf(" %s.%s => %s\n", c.String("context"), key, value)
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
|
|
@ -14,7 +15,6 @@ import (
|
|||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/ghodss/yaml"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
@ -51,7 +51,7 @@ func specGroupFromPack(name string, inputPack fleet.PermissivePackContent) (*spe
|
|||
case string:
|
||||
u64, err := strconv.ParseUint(i, 10, 32)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "converting interval from string to uint")
|
||||
return nil, fmt.Errorf("converting interval from string to uint: %w", err)
|
||||
}
|
||||
interval = uint(u64)
|
||||
case uint:
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
|
|
@ -15,11 +16,9 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/pkg/certificate"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func debugCommand() *cli.Command {
|
||||
|
|
@ -84,7 +83,7 @@ func debugProfileCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := writeFile(outfile, profile, defaultFileMode); err != nil {
|
||||
return errors.Wrap(err, "write profile to file")
|
||||
return fmt.Errorf("write profile to file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -125,7 +124,7 @@ func debugCmdlineCommand() *cli.Command {
|
|||
|
||||
if outfile := getOutfile(c); outfile != "" {
|
||||
if err := writeFile(outfile, []byte(out), defaultFileMode); err != nil {
|
||||
return errors.Wrap(err, "write cmdline to file")
|
||||
return fmt.Errorf("write cmdline to file: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -166,7 +165,7 @@ func debugHeapCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := writeFile(outfile, profile, defaultFileMode); err != nil {
|
||||
return errors.Wrapf(err, "write %s to file", name)
|
||||
return fmt.Errorf("write %s to file: %w", name, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -203,7 +202,7 @@ func debugGoroutineCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := writeFile(outfile, profile, defaultFileMode); err != nil {
|
||||
return errors.Wrapf(err, "write %s to file", name)
|
||||
return fmt.Errorf("write %s to file: %w", name, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -240,7 +239,7 @@ func debugTraceCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := writeFile(outfile, profile, defaultFileMode); err != nil {
|
||||
return errors.Wrapf(err, "write %s to file", name)
|
||||
return fmt.Errorf("write %s to file: %w", name, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -284,7 +283,7 @@ func debugArchiveCommand() *cli.Command {
|
|||
|
||||
f, err := secure.OpenFile(outfile, os.O_CREATE|os.O_WRONLY, defaultFileMode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open archive for output")
|
||||
return fmt.Errorf("open archive for output: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
gzwriter := gzip.NewWriter(f)
|
||||
|
|
@ -310,11 +309,11 @@ func debugArchiveCommand() *cli.Command {
|
|||
Mode: defaultFileMode,
|
||||
},
|
||||
); err != nil {
|
||||
return errors.Wrapf(err, "write %s header", profile)
|
||||
return fmt.Errorf("write %s header: %w", profile, err)
|
||||
}
|
||||
|
||||
if _, err := tarwriter.Write(res); err != nil {
|
||||
return errors.Wrapf(err, "write %s contents", profile)
|
||||
return fmt.Errorf("write %s contents: %w", profile, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -416,20 +415,20 @@ or provide an <address> argument to debug: fleetctl debug connection localhost:8
|
|||
// Check that the url's host resolves to an IP address or is otherwise
|
||||
// a valid IP address directly.
|
||||
if err := resolveHostname(c.Context, timeoutPerCheck, baseURL.Hostname()); err != nil {
|
||||
return errors.Wrap(err, "Fail: resolve host")
|
||||
return fmt.Errorf("Fail: resolve host: %w", err)
|
||||
}
|
||||
fmt.Fprintf(c.App.Writer, "Success: can resolve host %s.\n", baseURL.Hostname())
|
||||
|
||||
// Attempt a raw TCP connection to host:port.
|
||||
if err := dialHostPort(c.Context, timeoutPerCheck, baseURL.Host); err != nil {
|
||||
return errors.Wrap(err, "Fail: dial server")
|
||||
return fmt.Errorf("Fail: dial server: %w", err)
|
||||
}
|
||||
fmt.Fprintf(c.App.Writer, "Success: can dial server at %s.\n", baseURL.Host)
|
||||
|
||||
if cert := getFleetCertificate(c); cert != "" {
|
||||
// Run some validations on the TLS certificate.
|
||||
if err := checkFleetCert(c.Context, timeoutPerCheck, cert, baseURL.Host); err != nil {
|
||||
return errors.Wrap(err, "Fail: certificate")
|
||||
return fmt.Errorf("Fail: certificate: %w", err)
|
||||
}
|
||||
fmt.Fprintln(c.App.Writer, "Success: TLS certificate seems valid.")
|
||||
}
|
||||
|
|
@ -438,7 +437,7 @@ or provide an <address> argument to debug: fleetctl debug connection localhost:8
|
|||
// making a POST to /api/v1/osquery/enroll with an invalid
|
||||
// secret).
|
||||
if err := checkAPIEndpoint(c.Context, timeoutPerCheck, baseURL, cli); err != nil {
|
||||
return errors.Wrap(err, "Fail: agent API endpoint")
|
||||
return fmt.Errorf("Fail: agent API endpoint: %w", err)
|
||||
}
|
||||
fmt.Fprintln(c.App.Writer, "Success: agent API endpoints are available.")
|
||||
|
||||
|
|
@ -497,7 +496,7 @@ func checkAPIEndpoint(ctx context.Context, timeout time.Duration, baseURL *url.U
|
|||
bytes.NewBufferString(`{"enroll_secret": "--invalid--"}`),
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "creating request object")
|
||||
return fmt.Errorf("creating request object: %w", err)
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
|
|
@ -505,12 +504,12 @@ func checkAPIEndpoint(ctx context.Context, timeout time.Duration, baseURL *url.U
|
|||
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "request failed")
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if err := json.NewDecoder(res.Body).Decode(&enrollRes); err != nil {
|
||||
return errors.Wrap(err, "invalid JSON")
|
||||
return fmt.Errorf("invalid JSON: %w", err)
|
||||
}
|
||||
if res.StatusCode != http.StatusUnauthorized || enrollRes.Error == "" || !enrollRes.NodeInvalid {
|
||||
return fmt.Errorf("unexpected %d response", res.StatusCode)
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
|
@ -18,7 +19,6 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/service"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
|
@ -14,7 +15,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/service"
|
||||
"github.com/ghodss/yaml"
|
||||
"github.com/olekukonko/tablewriter"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
@ -267,7 +267,7 @@ func getQueriesCommand() *cli.Command {
|
|||
if name == "" {
|
||||
queries, err := client.GetQueries()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list queries")
|
||||
return fmt.Errorf("could not list queries: %w", err)
|
||||
}
|
||||
|
||||
if len(queries) == 0 {
|
||||
|
|
@ -278,7 +278,7 @@ func getQueriesCommand() *cli.Command {
|
|||
if c.Bool(yamlFlagName) || c.Bool(jsonFlagName) {
|
||||
for _, query := range queries {
|
||||
if err := printQuery(c, query); err != nil {
|
||||
return errors.Wrap(err, "unable to print query")
|
||||
return fmt.Errorf("unable to print query: %w", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
@ -305,7 +305,7 @@ func getQueriesCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := printQuery(c, query); err != nil {
|
||||
return errors.Wrap(err, "unable to print query")
|
||||
return fmt.Errorf("unable to print query: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -355,7 +355,7 @@ func getPacksCommand() *cli.Command {
|
|||
|
||||
queries, err := client.GetQueries()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list queries")
|
||||
return fmt.Errorf("could not list queries: %w", err)
|
||||
}
|
||||
|
||||
// Getting all queries then filtering is usually faster than getting
|
||||
|
|
@ -366,7 +366,7 @@ func getPacksCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := printQuery(c, query); err != nil {
|
||||
return errors.Wrap(err, "unable to print query")
|
||||
return fmt.Errorf("unable to print query: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -377,13 +377,13 @@ func getPacksCommand() *cli.Command {
|
|||
if name == "" {
|
||||
packs, err := client.GetPacks()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list packs")
|
||||
return fmt.Errorf("could not list packs: %w", err)
|
||||
}
|
||||
|
||||
if c.Bool(yamlFlagName) || c.Bool(jsonFlagName) {
|
||||
for _, pack := range packs {
|
||||
if err := printPack(c, pack); err != nil {
|
||||
return errors.Wrap(err, "unable to print pack")
|
||||
return fmt.Errorf("unable to print pack: %w", err)
|
||||
}
|
||||
|
||||
addQueries(pack)
|
||||
|
|
@ -423,7 +423,7 @@ func getPacksCommand() *cli.Command {
|
|||
addQueries(pack)
|
||||
|
||||
if err := printPack(c, pack); err != nil {
|
||||
return errors.Wrap(err, "unable to print pack")
|
||||
return fmt.Errorf("unable to print pack: %w", err)
|
||||
}
|
||||
|
||||
return printQueries()
|
||||
|
|
@ -456,7 +456,7 @@ func getLabelsCommand() *cli.Command {
|
|||
if name == "" {
|
||||
labels, err := client.GetLabels()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list labels")
|
||||
return fmt.Errorf("could not list labels: %w", err)
|
||||
}
|
||||
|
||||
if c.Bool(yamlFlagName) || c.Bool(jsonFlagName) {
|
||||
|
|
@ -607,7 +607,7 @@ func getHostsCommand() *cli.Command {
|
|||
}
|
||||
hosts, err := client.GetHosts(query)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list hosts")
|
||||
return fmt.Errorf("could not list hosts: %w", err)
|
||||
}
|
||||
|
||||
if len(hosts) == 0 {
|
||||
|
|
@ -643,7 +643,7 @@ func getHostsCommand() *cli.Command {
|
|||
} else {
|
||||
host, err := client.HostByIdentifier(identifier)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not get host")
|
||||
return fmt.Errorf("could not get host: %w", err)
|
||||
}
|
||||
err = printHostDetail(c, host)
|
||||
if err != nil {
|
||||
|
|
@ -736,19 +736,19 @@ func getCarveCommand() *cli.Command {
|
|||
idString := c.Args().First()
|
||||
|
||||
if idString == "" {
|
||||
return errors.Errorf("must provide carve ID as first argument")
|
||||
return errors.New("must provide carve ID as first argument")
|
||||
}
|
||||
|
||||
id, err := strconv.ParseInt(idString, 10, 64)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unable to parse carve ID as int")
|
||||
return fmt.Errorf("unable to parse carve ID as int: %w", err)
|
||||
}
|
||||
|
||||
outFile := getOutfile(c)
|
||||
stdout := c.Bool(stdoutFlagName)
|
||||
|
||||
if stdout && outFile != "" {
|
||||
return errors.Errorf("-stdout and -outfile must not be specified together")
|
||||
return errors.New("-stdout and -outfile must not be specified together")
|
||||
}
|
||||
|
||||
if stdout || outFile != "" {
|
||||
|
|
@ -756,7 +756,7 @@ func getCarveCommand() *cli.Command {
|
|||
if outFile != "" {
|
||||
f, err := secure.OpenFile(outFile, os.O_CREATE|os.O_WRONLY, defaultFileMode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open out file")
|
||||
return fmt.Errorf("open out file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
out = f
|
||||
|
|
@ -768,7 +768,7 @@ func getCarveCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if _, err := io.Copy(out, reader); err != nil {
|
||||
return errors.Wrap(err, "download carve contents")
|
||||
return fmt.Errorf("download carve contents: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -780,7 +780,7 @@ func getCarveCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := printYaml(carve, c.App.Writer); err != nil {
|
||||
return errors.Wrap(err, "print carve yaml")
|
||||
return fmt.Errorf("print carve yaml: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -816,7 +816,7 @@ func getUserRolesCommand() *cli.Command {
|
|||
|
||||
users, err := client.ListUsers()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list users")
|
||||
return fmt.Errorf("could not list users: %w", err)
|
||||
}
|
||||
|
||||
if len(users) == 0 {
|
||||
|
|
@ -876,7 +876,7 @@ func getTeamsCommand() *cli.Command {
|
|||
|
||||
teams, err := client.ListTeams()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list teams")
|
||||
return fmt.Errorf("could not list teams: %w", err)
|
||||
}
|
||||
|
||||
if len(teams) == 0 {
|
||||
|
|
@ -945,7 +945,7 @@ func getSoftwareCommand() *cli.Command {
|
|||
|
||||
software, err := client.ListSoftware(teamID)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not list software")
|
||||
return fmt.Errorf("could not list software: %w", err)
|
||||
}
|
||||
|
||||
if len(software) == 0 {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
|
|
@ -10,7 +11,6 @@ import (
|
|||
gqmodels "github.com/AbGuthrie/goquery/v2/models"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/service"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"errors"
|
||||
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import (
|
|||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/service"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
)
|
||||
|
|
@ -56,14 +55,14 @@ Interactively prompts for email and password if not specified in the flags or en
|
|||
fmt.Print("Email: ")
|
||||
_, err := fmt.Scanln(&flEmail)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error reading email")
|
||||
return fmt.Errorf("error reading email: %w", err)
|
||||
}
|
||||
}
|
||||
if flPassword == "" {
|
||||
fmt.Print("Password: ")
|
||||
passBytes, err := terminal.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error reading password")
|
||||
return fmt.Errorf("error reading password: %w", err)
|
||||
}
|
||||
fmt.Println()
|
||||
flPassword = string(passBytes)
|
||||
|
|
@ -76,17 +75,17 @@ Interactively prompts for email and password if not specified in the flags or en
|
|||
case service.NotSetupErr:
|
||||
return err
|
||||
}
|
||||
return errors.Wrap(err, "Login failed")
|
||||
return fmt.Errorf("Login failed: %w", err)
|
||||
}
|
||||
|
||||
configPath, context := c.String("config"), c.String("context")
|
||||
|
||||
if err := setConfigValue(configPath, context, "email", flEmail); err != nil {
|
||||
return errors.Wrap(err, "error setting email for the current context")
|
||||
return fmt.Errorf("error setting email for the current context: %w", err)
|
||||
}
|
||||
|
||||
if err := setConfigValue(configPath, context, "token", token); err != nil {
|
||||
return errors.Wrap(err, "error setting token for the current context")
|
||||
return fmt.Errorf("error setting token for the current context: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("[+] Fleet login successful and context configured!\n")
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ package main
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
@ -24,13 +23,13 @@ func logoutCommand() *cli.Command {
|
|||
}
|
||||
|
||||
if err := fleet.Logout(); err != nil {
|
||||
return errors.Wrap(err, "error logging out")
|
||||
return fmt.Errorf("error logging out: %w", err)
|
||||
}
|
||||
|
||||
configPath, context := c.String("config"), c.String("context")
|
||||
|
||||
if err := setConfigValue(configPath, context, "token", ""); err != nil {
|
||||
return errors.Wrap(err, "error setting token for the current context")
|
||||
return fmt.Errorf("error setting token for the current context: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("[+] Fleet logout successful and local token cleared!\n")
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/orbit/pkg/packaging"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
zlog "github.com/rs/zerolog/log"
|
||||
"github.com/skratchdot/open-golang/open"
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
|
|
@ -23,7 +24,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/service"
|
||||
"github.com/mitchellh/go-ps"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
@ -75,35 +75,35 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
osqueryBranch := c.String(previewConfigFlagName)
|
||||
fmt.Printf("Downloading dependencies from %s into %s...\n", osqueryBranch, previewDir)
|
||||
if err := downloadFiles(osqueryBranch); err != nil {
|
||||
return errors.Wrap(err, "Error downloading dependencies")
|
||||
return fmt.Errorf("Error downloading dependencies: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Chdir(previewDir); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := os.Stat("docker-compose.yml"); err != nil {
|
||||
return errors.Wrap(err, "docker-compose file not found in preview directory")
|
||||
return fmt.Errorf("docker-compose file not found in preview directory: %w", err)
|
||||
}
|
||||
|
||||
// Make sure the logs directory is writable, otherwise the Fleet
|
||||
// server errors on startup. This can be a problem when running on
|
||||
// Linux with a non-root user inside the container.
|
||||
if err := os.Chmod(filepath.Join(previewDir, "logs"), 0777); err != nil {
|
||||
return errors.Wrap(err, "make logs writable")
|
||||
return fmt.Errorf("make logs writable: %w", err)
|
||||
}
|
||||
if err := os.Chmod(filepath.Join(previewDir, "vulndb"), 0777); err != nil {
|
||||
return errors.Wrap(err, "make vulndb writable")
|
||||
return fmt.Errorf("make vulndb writable: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Setenv("FLEET_VERSION", c.String(tagFlagName)); err != nil {
|
||||
return errors.Wrap(err, "failed to set Fleet version")
|
||||
return fmt.Errorf("failed to set Fleet version: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Pulling Docker dependencies...")
|
||||
out, err := exec.Command("docker-compose", "pull").CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose")
|
||||
return errors.New("Failed to run docker-compose")
|
||||
}
|
||||
|
||||
fmt.Println("Starting Docker containers...")
|
||||
|
|
@ -112,12 +112,12 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
out, err = cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose")
|
||||
return errors.New("Failed to run docker-compose")
|
||||
}
|
||||
|
||||
fmt.Println("Waiting for server to start up...")
|
||||
if err := waitStartup(); err != nil {
|
||||
return errors.Wrap(err, "wait for server startup")
|
||||
return fmt.Errorf("wait for server startup: %w", err)
|
||||
}
|
||||
|
||||
// Start fleet02 (UI server) after fleet01 (agent/fleetctl server)
|
||||
|
|
@ -128,7 +128,7 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
out, err = cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose")
|
||||
return errors.New("Failed to run docker-compose")
|
||||
}
|
||||
|
||||
fmt.Println("Initializing server...")
|
||||
|
|
@ -140,7 +140,7 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
|
||||
fleetClient, err := service.NewClient(address, true, "", "")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Error creating Fleet API client handler")
|
||||
return fmt.Errorf("Error creating Fleet API client handler: %w", err)
|
||||
}
|
||||
|
||||
token, err := fleetClient.Setup(email, "Admin", password, "Fleet for osquery")
|
||||
|
|
@ -149,7 +149,7 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
case service.SetupAlreadyErr:
|
||||
// Ignore this error
|
||||
default:
|
||||
return errors.Wrap(err, "Error setting up Fleet")
|
||||
return fmt.Errorf("Error setting up Fleet: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -176,39 +176,39 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
c.Set("context", context)
|
||||
|
||||
if err := writeConfig(configPath, config); err != nil {
|
||||
return errors.Wrap(err, "Error writing fleetctl configuration")
|
||||
return fmt.Errorf("Error writing fleetctl configuration: %w", err)
|
||||
}
|
||||
|
||||
// Create client and get enroll secret
|
||||
client, err := unauthenticatedClientFromCLI(c)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Error making fleetctl client")
|
||||
return fmt.Errorf("Error making fleetctl client: %w", err)
|
||||
}
|
||||
|
||||
token, err = client.Login(email, password)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "fleetctl login failed")
|
||||
return fmt.Errorf("fleetctl login failed: %w", err)
|
||||
}
|
||||
|
||||
if err := setConfigValue(configPath, context, "token", token); err != nil {
|
||||
return errors.Wrap(err, "Error setting token for the current context")
|
||||
return fmt.Errorf("Error setting token for the current context: %w", err)
|
||||
}
|
||||
client.SetToken(token)
|
||||
|
||||
fmt.Println("Loading standard query library...")
|
||||
buf, err := downloadStandardQueryLibrary()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to download standard query library")
|
||||
return fmt.Errorf("failed to download standard query library: %w", err)
|
||||
}
|
||||
|
||||
specGroup, err := specGroupFromBytes(buf)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to parse standard query library")
|
||||
return fmt.Errorf("failed to parse standard query library: %w", err)
|
||||
}
|
||||
|
||||
err = client.ApplyQueries(specGroup.Queries)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to apply standard query library")
|
||||
return fmt.Errorf("failed to apply standard query library: %w", err)
|
||||
}
|
||||
|
||||
// disable anonymous analytics collection and enable software inventory for preview
|
||||
|
|
@ -216,7 +216,7 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
"host_settings": {"enable_software_inventory": true},
|
||||
"server_settings": {"enable_analytics": false},
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "failed to apply updated app config")
|
||||
return fmt.Errorf("failed to apply updated app config: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Applying Policies...")
|
||||
|
|
@ -226,7 +226,7 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
|
||||
secrets, err := client.GetEnrollSecretSpec()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Error retrieving enroll secret")
|
||||
return fmt.Errorf("Error retrieving enroll secret: %w", err)
|
||||
}
|
||||
|
||||
if len(secrets.Secrets) != 1 {
|
||||
|
|
@ -238,7 +238,7 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
"server_settings": {"enable_analytics": false},
|
||||
},
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "Error disabling anonymous analytics collection in app config")
|
||||
return fmt.Errorf("Error disabling anonymous analytics collection in app config: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Fleet will now enroll your device and log you into the UI automatically.")
|
||||
|
|
@ -249,13 +249,13 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
fmt.Println("Downloading Orbit and osqueryd...")
|
||||
|
||||
if err := downloadOrbitAndStart(previewDir, secrets.Secrets[0].Secret, address); err != nil {
|
||||
return errors.Wrap(err, "downloading orbit and osqueryd")
|
||||
return fmt.Errorf("downloading orbit and osqueryd: %w", err)
|
||||
}
|
||||
|
||||
// Give it a bit of time so the current device is the one with id 1
|
||||
fmt.Println("Waiting for current host to enroll...")
|
||||
if err := waitFirstHost(client); err != nil {
|
||||
return errors.Wrap(err, "wait for current host")
|
||||
return fmt.Errorf("wait for current host: %w", err)
|
||||
}
|
||||
|
||||
if err := openBrowser("http://localhost:1337/previewlogin"); err != nil {
|
||||
|
|
@ -272,7 +272,7 @@ Use the stop and reset subcommands to manage the server and dependencies once st
|
|||
out, err = cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose")
|
||||
return errors.New("Failed to run docker-compose")
|
||||
}
|
||||
|
||||
fmt.Println("Preview environment complete. Enjoy using Fleet!")
|
||||
|
|
@ -304,22 +304,22 @@ func downloadFiles(branch string) error {
|
|||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return errors.Errorf("download got status %d", resp.StatusCode)
|
||||
return fmt.Errorf("download got status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
zipContents, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "read download contents")
|
||||
return fmt.Errorf("read download contents: %w", err)
|
||||
}
|
||||
|
||||
zipReader, err := zip.NewReader(bytes.NewReader(zipContents), int64(len(zipContents)))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open download contents for unzip")
|
||||
return fmt.Errorf("open download contents for unzip: %w", err)
|
||||
}
|
||||
// zip.NewReader does not need to be closed (and cannot be)
|
||||
|
||||
if err := unzip(zipReader, branch); err != nil {
|
||||
return errors.Wrap(err, "unzip download contents")
|
||||
return fmt.Errorf("unzip download contents: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -331,11 +331,11 @@ func downloadStandardQueryLibrary() ([]byte, error) {
|
|||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf("status: %d", resp.StatusCode)
|
||||
return nil, fmt.Errorf("status: %d", resp.StatusCode)
|
||||
}
|
||||
buf, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "read response body")
|
||||
return nil, fmt.Errorf("read response body: %w", err)
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
|
@ -409,13 +409,13 @@ func waitStartup() error {
|
|||
return err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return errors.Errorf("got status code %d", resp.StatusCode)
|
||||
return fmt.Errorf("got status code %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
retryStrategy,
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "checking server health")
|
||||
return fmt.Errorf("checking server health: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -439,7 +439,7 @@ func waitFirstHost(client *service.Client) error {
|
|||
},
|
||||
retryStrategy,
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "checking host count")
|
||||
return fmt.Errorf("checking host count: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -481,13 +481,13 @@ func previewStopCommand() *cli.Command {
|
|||
return err
|
||||
}
|
||||
if _, err := os.Stat("docker-compose.yml"); err != nil {
|
||||
return errors.Wrap(err, "docker-compose file not found in preview directory")
|
||||
return fmt.Errorf("docker-compose file not found in preview directory: %w", err)
|
||||
}
|
||||
|
||||
out, err := exec.Command("docker-compose", "stop").CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose stop for Fleet server and dependencies")
|
||||
return errors.New("Failed to run docker-compose stop for Fleet server and dependencies")
|
||||
}
|
||||
|
||||
cmd := exec.Command("docker-compose", "stop")
|
||||
|
|
@ -501,11 +501,11 @@ func previewStopCommand() *cli.Command {
|
|||
out, err = cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose stop for simulated hosts")
|
||||
return errors.New("Failed to run docker-compose stop for simulated hosts")
|
||||
}
|
||||
|
||||
if err := stopOrbit(previewDir); err != nil {
|
||||
return errors.Wrap(err, "Failed to stop orbit")
|
||||
return fmt.Errorf("Failed to stop orbit: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Fleet preview server and dependencies stopped. Start again with fleetctl preview.")
|
||||
|
|
@ -534,13 +534,13 @@ func previewResetCommand() *cli.Command {
|
|||
return err
|
||||
}
|
||||
if _, err := os.Stat("docker-compose.yml"); err != nil {
|
||||
return errors.Wrap(err, "docker-compose file not found in preview directory")
|
||||
return fmt.Errorf("docker-compose file not found in preview directory: %w", err)
|
||||
}
|
||||
|
||||
out, err := exec.Command("docker-compose", "rm", "-sf").CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose rm -sf for Fleet server and dependencies.")
|
||||
return errors.New("Failed to run docker-compose rm -sf for Fleet server and dependencies.")
|
||||
}
|
||||
|
||||
cmd := exec.Command("docker-compose", "rm", "-sf")
|
||||
|
|
@ -554,11 +554,11 @@ func previewResetCommand() *cli.Command {
|
|||
out, err = cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return errors.Errorf("Failed to run docker-compose rm -sf for simulated hosts.")
|
||||
return errors.New("Failed to run docker-compose rm -sf for simulated hosts.")
|
||||
}
|
||||
|
||||
if err := stopOrbit(previewDir); err != nil {
|
||||
return errors.Wrap(err, "Failed to stop orbit")
|
||||
return fmt.Errorf("Failed to stop orbit: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Fleet preview server and dependencies reset. Start again with fleetctl preview.")
|
||||
|
|
@ -593,7 +593,7 @@ func readPidFromFile(destDir string, what string) (int, error) {
|
|||
func processNameMatches(pid int, expectedPrefix string) (bool, error) {
|
||||
process, err := ps.FindProcess(pid)
|
||||
if err != nil {
|
||||
return false, errors.Wrapf(err, "find process: %d", pid)
|
||||
return false, fmt.Errorf("find process: %d: %w", pid, err)
|
||||
}
|
||||
if process == nil {
|
||||
return false, nil
|
||||
|
|
@ -626,13 +626,13 @@ func downloadOrbitAndStart(destDir string, enrollSecret string, address string)
|
|||
case "windows":
|
||||
updateOpt.Platform = "windows"
|
||||
default:
|
||||
return errors.Errorf("unsupported arch: %s", runtime.GOOS)
|
||||
return fmt.Errorf("unsupported arch: %s", runtime.GOOS)
|
||||
}
|
||||
updateOpt.ServerURL = "https://tuf.fleetctl.com"
|
||||
updateOpt.RootDirectory = destDir
|
||||
|
||||
if err := packaging.InitializeUpdates(updateOpt); err != nil {
|
||||
return errors.Wrap(err, "initialize updates")
|
||||
return fmt.Errorf("initialize updates: %w", err)
|
||||
}
|
||||
|
||||
cmd := exec.Command(
|
||||
|
|
@ -645,10 +645,10 @@ func downloadOrbitAndStart(destDir string, enrollSecret string, address string)
|
|||
"--log-file", path.Join(destDir, "orbit.log"),
|
||||
)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return errors.Wrap(err, "starting orbit")
|
||||
return fmt.Errorf("starting orbit: %w", err)
|
||||
}
|
||||
if err := storePidFile(destDir, cmd.Process.Pid); err != nil {
|
||||
return errors.Wrap(err, "saving pid file")
|
||||
return fmt.Errorf("saving pid file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -674,11 +674,11 @@ func killFromPIDFile(destDir string, pidFileName string, expectedExecName string
|
|||
case errors.Is(err, os.ErrNotExist):
|
||||
return nil // we assume it's not running
|
||||
default:
|
||||
return errors.Wrapf(err, "reading pid from: %s", destDir)
|
||||
return fmt.Errorf("reading pid from: %s: %w", destDir, err)
|
||||
}
|
||||
matches, err := processNameMatches(pid, expectedExecName)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "inspecting process %d", pid)
|
||||
return fmt.Errorf("inspecting process %d: %w", pid, err)
|
||||
}
|
||||
if !matches {
|
||||
// Nothing to do, another process may be running with this pid
|
||||
|
|
@ -686,7 +686,7 @@ func killFromPIDFile(destDir string, pidFileName string, expectedExecName string
|
|||
return nil
|
||||
}
|
||||
if err := killPID(pid); err != nil {
|
||||
return errors.Wrapf(err, "killing %d", pid)
|
||||
return fmt.Errorf("killing %d: %w", pid, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -718,11 +718,11 @@ func loadPolicies(client *service.Client) error {
|
|||
for _, policy := range policies {
|
||||
q, err := client.CreateQuery(policy.name, policy.query, policy.description)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "creating query")
|
||||
return fmt.Errorf("creating query: %w", err)
|
||||
}
|
||||
err = client.CreatePolicy(q.ID, policy.resolution)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "creating policy")
|
||||
return fmt.Errorf("creating policy: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -741,7 +741,7 @@ func openBrowser(url string) error {
|
|||
}
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errors.Wrap(err, "failed to open in browser")
|
||||
return fmt.Errorf("failed to open in browser: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,12 +2,12 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/service"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
)
|
||||
|
|
@ -68,7 +68,7 @@ func setupCommand() *cli.Command {
|
|||
fmt.Print("Password: ")
|
||||
passBytes, err := terminal.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error reading password")
|
||||
return fmt.Errorf("error reading password: %w", err)
|
||||
}
|
||||
fmt.Println()
|
||||
flPassword = string(passBytes)
|
||||
|
|
@ -76,7 +76,7 @@ func setupCommand() *cli.Command {
|
|||
fmt.Print("Confirm Password: ")
|
||||
passBytes, err = terminal.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error reading password confirmation")
|
||||
return fmt.Errorf("error reading password confirmation: %w", err)
|
||||
}
|
||||
fmt.Println()
|
||||
if flPassword != string(passBytes) {
|
||||
|
|
@ -92,17 +92,17 @@ func setupCommand() *cli.Command {
|
|||
case service.SetupAlreadyErr:
|
||||
return err
|
||||
}
|
||||
return errors.Wrap(err, "error setting up Fleet")
|
||||
return fmt.Errorf("error setting up Fleet: %w", err)
|
||||
}
|
||||
|
||||
configPath, context := c.String("config"), c.String("context")
|
||||
|
||||
if err := setConfigValue(configPath, context, "email", flEmail); err != nil {
|
||||
return errors.Wrap(err, "error setting email for the current context")
|
||||
return fmt.Errorf("error setting email for the current context: %w", err)
|
||||
}
|
||||
|
||||
if err := setConfigValue(configPath, context, "token", token); err != nil {
|
||||
return errors.Wrap(err, "error setting token for the current context")
|
||||
return fmt.Errorf("error setting token for the current context: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Fleet Device Management Inc. periodically collects anonymous information about your instance.\nSending usage statistics from your Fleet instance is optional and can be disabled in settings.")
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
|
@ -9,7 +10,6 @@ import (
|
|||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/ptr"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
)
|
||||
|
|
@ -101,21 +101,21 @@ func createUserCommand() *cli.Command {
|
|||
globalRole = ptr.String(fleet.RoleObserver)
|
||||
} else if globalRoleString != "" {
|
||||
if !fleet.ValidGlobalRole(globalRoleString) {
|
||||
return errors.Errorf("'%s' is not a valid team role", globalRoleString)
|
||||
return fmt.Errorf("'%s' is not a valid team role", globalRoleString)
|
||||
}
|
||||
globalRole = ptr.String(globalRoleString)
|
||||
} else {
|
||||
for _, t := range teamStrings {
|
||||
parts := strings.Split(t, ":")
|
||||
if len(parts) != 2 {
|
||||
return errors.Errorf("Unable to parse '%s' as team_id:role", t)
|
||||
return fmt.Errorf("Unable to parse '%s' as team_id:role", t)
|
||||
}
|
||||
teamID, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Unable to parse team_id")
|
||||
return fmt.Errorf("Unable to parse team_id: %w", err)
|
||||
}
|
||||
if !fleet.ValidTeamRole(parts[1]) {
|
||||
return errors.Errorf("'%s' is not a valid team role", parts[1])
|
||||
return fmt.Errorf("'%s' is not a valid team role", parts[1])
|
||||
}
|
||||
|
||||
teams = append(teams, fleet.UserTeam{Team: fleet.Team{ID: uint(teamID)}, Role: parts[1]})
|
||||
|
|
@ -130,7 +130,7 @@ func createUserCommand() *cli.Command {
|
|||
passBytes, err := terminal.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to read password")
|
||||
return fmt.Errorf("Failed to read password: %w", err)
|
||||
}
|
||||
if len(passBytes) == 0 {
|
||||
return fmt.Errorf("Password may not be empty.")
|
||||
|
|
@ -140,7 +140,7 @@ func createUserCommand() *cli.Command {
|
|||
confBytes, err := terminal.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to read confirmation")
|
||||
return fmt.Errorf("Failed to read confirmation: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(passBytes, confBytes) {
|
||||
|
|
@ -164,7 +164,7 @@ func createUserCommand() *cli.Command {
|
|||
Teams: &teams,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to create user")
|
||||
return fmt.Errorf("Failed to create user: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/config"
|
||||
"github.com/fleetdm/fleet/v4/server/vulnerabilities"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ package eefleetctl
|
|||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
|
|
@ -18,7 +19,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/pkg/file"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/theupdateframework/go-tuf"
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/crypto/ssh/terminal"
|
||||
|
|
@ -91,29 +91,29 @@ func updatesInitFunc(c *cli.Context) error {
|
|||
store := tuf.FileSystemStore(path, passHandler.getPassphrase)
|
||||
meta, err := store.GetMeta()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "get repo meta")
|
||||
return fmt.Errorf("get repo meta: %w", err)
|
||||
}
|
||||
if len(meta) != 0 {
|
||||
return errors.Errorf("repo already initialized: %s", path)
|
||||
return fmt.Errorf("repo already initialized: %s", path)
|
||||
}
|
||||
// Ensure no existing keys before initializing
|
||||
if _, err := os.Stat(filepath.Join(path, "keys")); !errors.Is(err, os.ErrNotExist) {
|
||||
if err == nil {
|
||||
return errors.Errorf("keys directory already exists: %s", filepath.Join(path, "keys"))
|
||||
return fmt.Errorf("keys directory already exists: %s", filepath.Join(path, "keys"))
|
||||
}
|
||||
return errors.Wrap(err, "failed to check existence of keys directory")
|
||||
return fmt.Errorf("failed to check existence of keys directory: %w", err)
|
||||
}
|
||||
|
||||
repo, err := tuf.NewRepo(store)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open repo")
|
||||
return fmt.Errorf("open repo: %w", err)
|
||||
}
|
||||
|
||||
// TODO messaging about using a secure environment
|
||||
|
||||
// Explicitly initialize with consistent snapshots turned off.
|
||||
if err := repo.Init(consistentSnapshots); err != nil {
|
||||
return errors.Wrap(err, "initialize repo")
|
||||
return fmt.Errorf("initialize repo: %w", err)
|
||||
}
|
||||
|
||||
// Generate keys
|
||||
|
|
@ -126,7 +126,7 @@ func updatesInitFunc(c *cli.Context) error {
|
|||
|
||||
// Sign roots metadata
|
||||
if err := repo.Sign("root.json"); err != nil {
|
||||
return errors.Wrap(err, "sign root metadata")
|
||||
return fmt.Errorf("sign root metadata: %w", err)
|
||||
}
|
||||
|
||||
// Create empty manifests for commit
|
||||
|
|
@ -135,18 +135,18 @@ func updatesInitFunc(c *cli.Context) error {
|
|||
nil,
|
||||
time.Now().Add(targetsExpirationDuration),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "initialize targets")
|
||||
return fmt.Errorf("initialize targets: %w", err)
|
||||
}
|
||||
if err := repo.SnapshotWithExpires(time.Now().Add(snapshotExpirationDuration)); err != nil {
|
||||
return errors.Wrap(err, "make snapshot")
|
||||
return fmt.Errorf("make snapshot: %w", err)
|
||||
}
|
||||
if err := repo.TimestampWithExpires(time.Now().Add(timestampExpirationDuration)); err != nil {
|
||||
return errors.Wrap(err, "make timestamp")
|
||||
return fmt.Errorf("make timestamp: %w", err)
|
||||
}
|
||||
|
||||
// Commit empty manifests
|
||||
if err := repo.Commit(); err != nil {
|
||||
return errors.Wrap(err, "commit repo")
|
||||
return fmt.Errorf("commit repo: %w", err)
|
||||
}
|
||||
|
||||
// TODO messaging about separating keys -- maybe we can help by splitting
|
||||
|
|
@ -172,11 +172,11 @@ func updatesRootsFunc(c *cli.Context) error {
|
|||
|
||||
keys, err := repo.RootKeys()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "get root metadata")
|
||||
return fmt.Errorf("get root metadata: %w", err)
|
||||
}
|
||||
|
||||
if err := json.NewEncoder(os.Stdout).Encode(keys); err != nil {
|
||||
return errors.Wrap(err, "encode root metadata")
|
||||
return fmt.Errorf("encode root metadata: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -257,7 +257,7 @@ func updatesAddFunc(c *cli.Context) error {
|
|||
}
|
||||
meta, err := json.Marshal(customMetadata{Version: version})
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "marshal custom metadata")
|
||||
return fmt.Errorf("marshal custom metadata: %w", err)
|
||||
}
|
||||
|
||||
if err := repo.AddTargetsWithExpires(
|
||||
|
|
@ -265,19 +265,19 @@ func updatesAddFunc(c *cli.Context) error {
|
|||
meta,
|
||||
time.Now().Add(targetsExpirationDuration),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "add targets")
|
||||
return fmt.Errorf("add targets: %w", err)
|
||||
}
|
||||
|
||||
if err := repo.SnapshotWithExpires(time.Now().Add(snapshotExpirationDuration)); err != nil {
|
||||
return errors.Wrap(err, "make snapshot")
|
||||
return fmt.Errorf("make snapshot: %w", err)
|
||||
}
|
||||
|
||||
if err := repo.TimestampWithExpires(time.Now().Add(timestampExpirationDuration)); err != nil {
|
||||
return errors.Wrap(err, "make timestamp")
|
||||
return fmt.Errorf("make timestamp: %w", err)
|
||||
}
|
||||
|
||||
if err := repo.Commit(); err != nil {
|
||||
return errors.Wrap(err, "commit repo")
|
||||
return fmt.Errorf("commit repo: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -307,11 +307,11 @@ func updatesTimestampFunc(c *cli.Context) error {
|
|||
if err := repo.TimestampWithExpires(
|
||||
time.Now().Add(timestampExpirationDuration),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "make timestamp")
|
||||
return fmt.Errorf("make timestamp: %w", err)
|
||||
}
|
||||
|
||||
if err := repo.Commit(); err != nil {
|
||||
return errors.Wrap(err, "commit repo")
|
||||
return fmt.Errorf("commit repo: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -359,7 +359,7 @@ func updatesRotateFunc(c *cli.Context) error {
|
|||
// Get old keys for role
|
||||
keys, err := store.GetSigningKeys(role)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "get keys for role")
|
||||
return fmt.Errorf("get keys for role: %w", err)
|
||||
}
|
||||
|
||||
// Prepare to roll back in case of error.
|
||||
|
|
@ -390,7 +390,7 @@ func updatesRotateFunc(c *cli.Context) error {
|
|||
// tuf.ErrKeyNotFound as these represent keys that are not present in the manifest and
|
||||
// so do not need to be revoked.
|
||||
if !errors.As(err, &tuf.ErrKeyNotFound{}) {
|
||||
return errors.Wrap(err, "revoke key")
|
||||
return fmt.Errorf("revoke key: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -405,26 +405,26 @@ func updatesRotateFunc(c *cli.Context) error {
|
|||
|
||||
// Re-sign the root metadata
|
||||
if err := repo.Sign("root.json"); err != nil {
|
||||
return errors.Wrap(err, "sign root.json")
|
||||
return fmt.Errorf("sign root.json: %w", err)
|
||||
}
|
||||
|
||||
// Generate new metadata for each role (technically some of these may not need regeneration
|
||||
// depending on which key was rotated, but there should be no harm in generating new ones for each).
|
||||
if err := repo.AddTargetsWithExpires(nil, nil, time.Now().Add(targetsExpirationDuration)); err != nil {
|
||||
return errors.Wrap(err, "generate targets")
|
||||
return fmt.Errorf("generate targets: %w", err)
|
||||
}
|
||||
|
||||
if err := repo.SnapshotWithExpires(time.Now().Add(snapshotExpirationDuration)); err != nil {
|
||||
return errors.Wrap(err, "generate snapshot")
|
||||
return fmt.Errorf("generate snapshot: %w", err)
|
||||
}
|
||||
|
||||
if err := repo.TimestampWithExpires(time.Now().Add(timestampExpirationDuration)); err != nil {
|
||||
return errors.Wrap(err, "generate timestamp")
|
||||
return fmt.Errorf("generate timestamp: %w", err)
|
||||
}
|
||||
|
||||
// Commit the changes.
|
||||
if err := repo.Commit(); err != nil {
|
||||
return errors.Wrap(err, "commit repo")
|
||||
return fmt.Errorf("commit repo: %w", err)
|
||||
}
|
||||
|
||||
success = true
|
||||
|
|
@ -436,20 +436,20 @@ func updatesRotateFunc(c *cli.Context) error {
|
|||
func startRotatePseudoTx(repoPath string) (commit, rollback func() error, err error) {
|
||||
repositoryDir := filepath.Join(repoPath, "repository")
|
||||
if err := createBackups(repositoryDir); err != nil {
|
||||
return nil, nil, errors.Wrap(err, "backup repository")
|
||||
return nil, nil, fmt.Errorf("backup repository: %w", err)
|
||||
}
|
||||
keysDir := filepath.Join(repoPath, "keys")
|
||||
if err := createBackups(keysDir); err != nil {
|
||||
return nil, nil, errors.Wrap(err, "backup keys")
|
||||
return nil, nil, fmt.Errorf("backup keys: %w", err)
|
||||
}
|
||||
|
||||
commit = func() error {
|
||||
// Remove the backups on successful rotation.
|
||||
if err := os.RemoveAll(filepath.Join(repositoryDir, backupDirectory)); err != nil {
|
||||
return errors.Wrap(err, "remove repository backup directory")
|
||||
return fmt.Errorf("remove repository backup directory: %w", err)
|
||||
}
|
||||
if err := os.RemoveAll(filepath.Join(keysDir, backupDirectory)); err != nil {
|
||||
return errors.Wrap(err, "remove keys backup directory")
|
||||
return fmt.Errorf("remove keys backup directory: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -457,10 +457,10 @@ func startRotatePseudoTx(repoPath string) (commit, rollback func() error, err er
|
|||
rollback = func() error {
|
||||
// Restore the backups on failure.
|
||||
if err := restoreBackups(repositoryDir); err != nil {
|
||||
return errors.Wrap(err, "restore repository backup")
|
||||
return fmt.Errorf("restore repository backup: %w", err)
|
||||
}
|
||||
if err := restoreBackups(keysDir); err != nil {
|
||||
return errors.Wrap(err, "restore keys backup ")
|
||||
return fmt.Errorf("restore keys backup: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -475,22 +475,22 @@ func createBackups(dirPath string) error {
|
|||
backupPath := filepath.Join(dirPath, backupDirectory)
|
||||
if err := os.Mkdir(backupPath, os.ModeDir|0744); err != nil {
|
||||
if errors.Is(err, fs.ErrExist) {
|
||||
return errors.Wrap(err, "backup directory already exists")
|
||||
return fmt.Errorf("backup directory already exists: %w", err)
|
||||
}
|
||||
return errors.Wrap(err, "create backup directory")
|
||||
return fmt.Errorf("create backup directory: %w", err)
|
||||
}
|
||||
|
||||
// Copy each of the *.json files into a backup file.
|
||||
files, err := filepath.Glob(filepath.Join(dirPath, "*.json"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "glob for backup")
|
||||
return fmt.Errorf("glob for backup: %w", err)
|
||||
}
|
||||
for _, path := range files {
|
||||
if err := file.CopyWithPerms(
|
||||
path,
|
||||
filepath.Join(backupPath, filepath.Base(path)),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "copy for backup")
|
||||
return fmt.Errorf("copy for backup: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -502,29 +502,29 @@ func restoreBackups(dirPath string) error {
|
|||
backupDir := filepath.Join(dirPath, backupDirectory)
|
||||
info, err := os.Stat(backupDir)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "stat backup path")
|
||||
return fmt.Errorf("stat backup path: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return errors.Errorf("backup is not directory: %s", backupDir)
|
||||
return fmt.Errorf("backup is not directory: %s", backupDir)
|
||||
}
|
||||
|
||||
// Remove files that did not exist at backup time (determined by no corresponding backup).
|
||||
files, err := filepath.Glob(filepath.Join(dirPath, "*.json"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "glob for restore")
|
||||
return fmt.Errorf("glob for restore: %w", err)
|
||||
}
|
||||
for _, path := range files {
|
||||
backupPath := filepath.Join(backupDir, filepath.Base(path))
|
||||
exists, err := file.Exists(backupPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "check exists for restore")
|
||||
return fmt.Errorf("check exists for restore: %w", err)
|
||||
}
|
||||
|
||||
// File does not exist in the backup, remove it because this implies that the file was added
|
||||
// since the backup was taken.
|
||||
if !exists {
|
||||
if err := os.Remove(path); err != nil {
|
||||
return errors.Wrap(err, "remove for restore")
|
||||
return fmt.Errorf("remove for restore: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -532,20 +532,20 @@ func restoreBackups(dirPath string) error {
|
|||
// Restore files from backups.
|
||||
backupFiles, err := filepath.Glob(filepath.Join(backupDir, "*.json"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "glob for restore")
|
||||
return fmt.Errorf("glob for restore: %w", err)
|
||||
}
|
||||
for _, path := range backupFiles {
|
||||
originalPath := filepath.Join(dirPath, filepath.Base(path))
|
||||
|
||||
// Replace with the backed up file, copying the previous permissions.
|
||||
if err := file.CopyWithPerms(path, originalPath); err != nil {
|
||||
return errors.Wrap(err, "copy for restore")
|
||||
return fmt.Errorf("copy for restore: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the backups now that we are finished with the restore.
|
||||
if err := os.RemoveAll(backupDir); err != nil {
|
||||
return errors.Wrap(err, "remove backup directory")
|
||||
return fmt.Errorf("remove backup directory: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -566,22 +566,22 @@ func checkKeys(repoPath string, keys ...string) error {
|
|||
func copyTarget(srcPath, dstPath string) error {
|
||||
src, err := os.Open(srcPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open src for copy")
|
||||
return fmt.Errorf("open src for copy: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
if err := secure.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
|
||||
return errors.Wrap(err, "create dst dir for copy")
|
||||
return fmt.Errorf("create dst dir for copy: %w", err)
|
||||
}
|
||||
|
||||
dst, err := secure.OpenFile(dstPath, os.O_RDWR|os.O_CREATE, 0644)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open dst for copy")
|
||||
return fmt.Errorf("open dst for copy: %w", err)
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
if _, err := io.Copy(dst, src); err != nil {
|
||||
return errors.Wrap(err, "copy src to dst")
|
||||
return fmt.Errorf("copy src to dst: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -590,11 +590,11 @@ func copyTarget(srcPath, dstPath string) error {
|
|||
func updatesGenKey(repo *tuf.Repo, role string) error {
|
||||
keyids, err := repo.GenKeyWithExpires(role, time.Now().Add(keyExpirationDuration))
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "generate %s key", role)
|
||||
return fmt.Errorf("generate %s key: %w", role, err)
|
||||
}
|
||||
|
||||
if len(keyids) != 1 {
|
||||
return errors.Errorf("expected 1 keyid for %s key: got %d", role, len(keyids))
|
||||
return fmt.Errorf("expected 1 keyid for %s key: got %d", role, len(keyids))
|
||||
}
|
||||
fmt.Printf("Generated %s key with ID: %s\n", role, keyids[0])
|
||||
|
||||
|
|
@ -605,10 +605,10 @@ func openLocalStore(path string) (tuf.LocalStore, error) {
|
|||
store := tuf.FileSystemStore(path, passHandler.getPassphrase)
|
||||
meta, err := store.GetMeta()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "get repo meta")
|
||||
return nil, fmt.Errorf("get repo meta: %w", err)
|
||||
}
|
||||
if len(meta) == 0 {
|
||||
return nil, errors.Errorf("repo not initialized: %s", path)
|
||||
return nil, fmt.Errorf("repo not initialized: %s", path)
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
|
@ -621,7 +621,7 @@ func openRepo(path string) (*tuf.Repo, error) {
|
|||
|
||||
repo, err := tuf.NewRepo(store)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new repo from store")
|
||||
return nil, fmt.Errorf("new repo from store: %w", err)
|
||||
}
|
||||
|
||||
return repo, nil
|
||||
|
|
@ -686,7 +686,7 @@ func (p *passphraseHandler) readPassphrase(role string, confirm bool) ([]byte, e
|
|||
passphrase, err := terminal.ReadPassword(int(syscall.Stdin)) //nolint:unconvert
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "read password")
|
||||
return nil, fmt.Errorf("read password: %w", err)
|
||||
}
|
||||
|
||||
if !confirm {
|
||||
|
|
@ -698,7 +698,7 @@ func (p *passphraseHandler) readPassphrase(role string, confirm bool) ([]byte, e
|
|||
confirmation, err := terminal.ReadPassword(int(syscall.Stdin)) //nolint:unconvert
|
||||
fmt.Println()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "read password confirmation")
|
||||
return nil, fmt.Errorf("read password confirmation: %w", err)
|
||||
}
|
||||
|
||||
if bytes.Equal(passphrase, confirmation) {
|
||||
|
|
@ -725,7 +725,7 @@ func (p *passphraseHandler) checkPassphrase(store tuf.LocalStore, role string) e
|
|||
if p.getPassphraseFromEnv(role) != nil {
|
||||
// Fatal error if environment variable passphrase is
|
||||
// incorrect
|
||||
return errors.Errorf("%s passphrase from %s is invalid", role, p.passphraseEnvName(role))
|
||||
return fmt.Errorf("%s passphrase from %s is invalid", role, p.passphraseEnvName(role))
|
||||
}
|
||||
|
||||
fmt.Printf("Failed to decrypt %s key. Try again.\n", role)
|
||||
|
|
@ -733,7 +733,7 @@ func (p *passphraseHandler) checkPassphrase(store tuf.LocalStore, role string) e
|
|||
}
|
||||
continue
|
||||
} else if len(keys) == 0 {
|
||||
return errors.Errorf("%s key not found", role)
|
||||
return fmt.Errorf("%s key not found", role)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,11 +5,12 @@ import (
|
|||
"crypto/x509"
|
||||
_ "embed"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -29,13 +30,13 @@ func loadPublicKey() (*ecdsa.PublicKey, error) {
|
|||
|
||||
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to parse ecdsa key")
|
||||
return nil, fmt.Errorf("failed to parse ecdsa key: %w", err)
|
||||
}
|
||||
|
||||
if pub, ok := pub.(*ecdsa.PublicKey); ok {
|
||||
return pub, nil
|
||||
}
|
||||
return nil, errors.Errorf("%T is not *ecdsa.PublicKey", pub)
|
||||
return nil, fmt.Errorf("%T is not *ecdsa.PublicKey", pub)
|
||||
}
|
||||
|
||||
// LoadLicense loads and validates the license key.
|
||||
|
|
@ -58,14 +59,14 @@ func LoadLicense(licenseKey string) (*fleet.LicenseInfo, error) {
|
|||
|
||||
// if the ONLY error is that it's expired, then we ignore it
|
||||
if v == nil || v.Errors != jwt.ValidationErrorExpired {
|
||||
return nil, errors.Wrap(err, "parse license")
|
||||
return nil, fmt.Errorf("parse license: %w", err)
|
||||
}
|
||||
parsedToken.Valid = true
|
||||
}
|
||||
|
||||
license, err := validate(parsedToken)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "validate license")
|
||||
return nil, fmt.Errorf("validate license: %w", err)
|
||||
}
|
||||
|
||||
// Force premium license
|
||||
|
|
@ -92,29 +93,29 @@ func validate(token *jwt.Token) (*fleet.LicenseInfo, error) {
|
|||
}
|
||||
|
||||
if token.Method.Alg() != expectedAlgorithm {
|
||||
return nil, errors.Errorf("unexpected algorithm %s", token.Method.Alg())
|
||||
return nil, fmt.Errorf("unexpected algorithm %s", token.Method.Alg())
|
||||
}
|
||||
|
||||
var claims *licenseClaims
|
||||
claims, ok := token.Claims.(*licenseClaims)
|
||||
if !ok || claims == nil {
|
||||
return nil, errors.Errorf("unexpected claims type %T", token.Claims)
|
||||
return nil, fmt.Errorf("unexpected claims type %T", token.Claims)
|
||||
}
|
||||
|
||||
if claims.Devices == 0 {
|
||||
return nil, errors.Errorf("missing devices")
|
||||
return nil, errors.New("missing devices")
|
||||
}
|
||||
|
||||
if claims.Tier == "" {
|
||||
return nil, errors.Errorf("missing tier")
|
||||
return nil, errors.New("missing tier")
|
||||
}
|
||||
|
||||
if claims.ExpiresAt == 0 {
|
||||
return nil, errors.Errorf("missing exp")
|
||||
return nil, errors.New("missing exp")
|
||||
}
|
||||
|
||||
if claims.Issuer != expectedIssuer {
|
||||
return nil, errors.Errorf("unexpected issuer %s", claims.Issuer)
|
||||
return nil, fmt.Errorf("unexpected issuer %s", claims.Issuer)
|
||||
}
|
||||
|
||||
return &fleet.LicenseInfo{
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/WatchBeam/clock"
|
||||
"github.com/fleetdm/fleet/v4/server/authz"
|
||||
"github.com/fleetdm/fleet/v4/server/config"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
|
|
@ -32,7 +33,7 @@ func NewService(
|
|||
|
||||
authorizer, err := authz.NewAuthorizer()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new authorizer")
|
||||
return nil, fmt.Errorf("new authorizer: %w", err)
|
||||
}
|
||||
|
||||
return &Service{
|
||||
|
|
|
|||
|
|
@ -7,11 +7,11 @@ import (
|
|||
|
||||
"github.com/fleetdm/fleet/v4/server"
|
||||
"github.com/fleetdm/fleet/v4/server/authz"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/logging"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/ptr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (svc *Service) NewTeam(ctx context.Context, p fleet.TeamPayload) (*fleet.Team, error) {
|
||||
|
|
@ -46,7 +46,7 @@ func (svc *Service) NewTeam(ctx context.Context, p fleet.TeamPayload) (*fleet.Te
|
|||
// Set up a default enroll secret
|
||||
secret, err := server.GenerateRandomText(fleet.EnrollSecretDefaultLength)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "generate enroll secret string")
|
||||
return nil, ctxerr.Wrap(ctx, err, "generate enroll secret string")
|
||||
}
|
||||
team.Secrets = []*fleet.EnrollSecret{{Secret: secret}}
|
||||
}
|
||||
|
|
@ -124,10 +124,10 @@ func (svc *Service) AddTeamUsers(ctx context.Context, teamID uint, users []fleet
|
|||
idMap[user.ID] = user
|
||||
fullUser, err := svc.ds.UserByID(ctx, user.ID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "getting full user with id %d", user.ID)
|
||||
return nil, ctxerr.Wrapf(ctx, err, "getting full user with id %d", user.ID)
|
||||
}
|
||||
if fullUser.GlobalRole != nil && currentUser.GlobalRole == nil {
|
||||
return nil, errors.New("A user with a global role cannot be added to a team by a non global user.")
|
||||
return nil, ctxerr.New(ctx, "A user with a global role cannot be added to a team by a non global user.")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"io/ioutil"
|
||||
|
|
@ -23,7 +24,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/pkg/file"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/oklog/run"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
|
@ -118,7 +118,7 @@ func main() {
|
|||
if logfile := c.String("log-file"); logfile != "" {
|
||||
f, err := secure.OpenFile(logfile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open logfile")
|
||||
return fmt.Errorf("open logfile: %w", err)
|
||||
}
|
||||
log.Logger = log.Output(zerolog.MultiLevelWriter(
|
||||
zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339Nano, NoColor: true},
|
||||
|
|
@ -142,16 +142,16 @@ func main() {
|
|||
|
||||
b, err := ioutil.ReadFile(c.String("enroll-secret-path"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "read enroll secret file")
|
||||
return fmt.Errorf("read enroll secret file: %w", err)
|
||||
}
|
||||
|
||||
if err := c.Set("enroll-secret", strings.TrimSpace(string(b))); err != nil {
|
||||
return errors.Wrap(err, "set enroll secret from file")
|
||||
return fmt.Errorf("set enroll secret from file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := secure.MkdirAll(c.String("root-dir"), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "initialize root dir")
|
||||
return fmt.Errorf("initialize root dir: %w", err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(c.String("root-dir"), "orbit.db")
|
||||
|
|
@ -211,7 +211,7 @@ func main() {
|
|||
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "cleanup old files")
|
||||
return fmt.Errorf("cleanup old files: %w", err)
|
||||
}
|
||||
|
||||
var g run.Group
|
||||
|
|
@ -248,7 +248,7 @@ func main() {
|
|||
if fleetURL != "https://" && c.Bool("insecure") {
|
||||
proxy, err := insecure.NewTLSProxy(fleetURL)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "create TLS proxy")
|
||||
return fmt.Errorf("create TLS proxy: %w", err)
|
||||
}
|
||||
|
||||
g.Add(
|
||||
|
|
@ -272,7 +272,7 @@ func main() {
|
|||
// Write cert that proxy uses
|
||||
err = ioutil.WriteFile(certPath, []byte(insecure.ServerCert), os.ModePerm)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "write server cert")
|
||||
return fmt.Errorf("write server cert: %w", err)
|
||||
}
|
||||
|
||||
// Rewrite URL to the proxy URL. Note the proxy handles any URL
|
||||
|
|
@ -285,7 +285,7 @@ func main() {
|
|||
// Check and log if there are any errors with TLS connection.
|
||||
pool, err := certificate.LoadPEM(certPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "load certificate")
|
||||
return fmt.Errorf("load certificate: %w", err)
|
||||
}
|
||||
if err := certificate.ValidateConnection(pool, fleetURL); err != nil {
|
||||
log.Info().Err(err).Msg("Failed to connect to Fleet server. Osquery connection may fail.")
|
||||
|
|
@ -302,7 +302,7 @@ func main() {
|
|||
|
||||
parsedURL, err := url.Parse(fleetURL)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "parse URL")
|
||||
return fmt.Errorf("parse URL: %w", err)
|
||||
}
|
||||
|
||||
options = append(options,
|
||||
|
|
@ -313,7 +313,7 @@ func main() {
|
|||
// Check and log if there are any errors with TLS connection.
|
||||
pool, err := certificate.LoadPEM(certPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "load certificate")
|
||||
return fmt.Errorf("load certificate: %w", err)
|
||||
}
|
||||
if err := certificate.ValidateConnection(pool, fleetURL); err != nil {
|
||||
log.Info().Err(err).Msg("Failed to connect to Fleet server. Osquery connection may fail.")
|
||||
|
|
@ -327,7 +327,7 @@ func main() {
|
|||
if exists, err := file.Exists(certPath); err == nil && exists {
|
||||
_, err = certificate.LoadPEM(certPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "load certs.pem")
|
||||
return fmt.Errorf("load certs.pem: %w", err)
|
||||
}
|
||||
options = append(options, osquery.WithFlags([]string{"--tls_server_certs", certPath}))
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package main
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
|
|
@ -12,7 +13,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/orbit/pkg/update/filestore"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/oklog/run"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
|
@ -41,7 +41,7 @@ var shellCommand = &cli.Command{
|
|||
}
|
||||
|
||||
if err := secure.MkdirAll(c.String("root-dir"), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "initialize root dir")
|
||||
return fmt.Errorf("initialize root dir: %w", err)
|
||||
}
|
||||
|
||||
localStore, err := filestore.New(filepath.Join(c.String("root-dir"), "tuf-metadata.json"))
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
package constant
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
|
|
@ -28,7 +29,7 @@ var (
|
|||
func mustSID(identifier string) *windows.SID {
|
||||
sid, err := windows.StringToSid(identifier)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "create sid"))
|
||||
panic(fmt.Errorf("create sid: %w", err))
|
||||
}
|
||||
return sid
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/dgraph-io/badger/v2"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -30,7 +31,7 @@ func Open(path string) (*BadgerDB, error) {
|
|||
// TODO implement logging?
|
||||
db, err := badger.Open(badger.DefaultOptions(path).WithLogger(nil))
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "open badger %s", path)
|
||||
return nil, fmt.Errorf("open badger %s: %w", path, err)
|
||||
}
|
||||
|
||||
b := &BadgerDB{DB: db}
|
||||
|
|
@ -50,7 +51,7 @@ func OpenTruncate(path string) (*BadgerDB, error) {
|
|||
// TODO implement logging?
|
||||
db, err := badger.Open(badger.DefaultOptions(path).WithLogger(nil).WithTruncate(true))
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "open badger with truncate %s", path)
|
||||
return nil, fmt.Errorf("open badger with truncate %s: %w", path, err)
|
||||
}
|
||||
|
||||
b := &BadgerDB{DB: db}
|
||||
|
|
|
|||
|
|
@ -8,14 +8,14 @@ package insecure
|
|||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -88,14 +88,14 @@ type TLSProxy struct {
|
|||
func NewTLSProxy(targetURL string) (*TLSProxy, error) {
|
||||
cert, err := tls.X509KeyPair([]byte(ServerCert), []byte(serverKey))
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "load keypair")
|
||||
return nil, fmt.Errorf("load keypair: %w", err)
|
||||
}
|
||||
cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
|
||||
|
||||
// Assign any available port
|
||||
listener, err := tls.Listen("tcp", "localhost:0", cfg)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "bind localhost")
|
||||
return nil, fmt.Errorf("bind localhost: %w", err)
|
||||
}
|
||||
|
||||
addr, ok := listener.Addr().(*net.TCPAddr)
|
||||
|
|
@ -105,7 +105,7 @@ func NewTLSProxy(targetURL string) (*TLSProxy, error) {
|
|||
|
||||
handler, err := newProxyHandler(targetURL)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "make proxy handler")
|
||||
return nil, fmt.Errorf("make proxy handler: %w", err)
|
||||
}
|
||||
|
||||
proxy := &TLSProxy{
|
||||
|
|
@ -124,17 +124,12 @@ func (p *TLSProxy) InsecureServeTLS() error {
|
|||
}
|
||||
|
||||
err := p.server.Serve(p.listener)
|
||||
return errors.Wrap(err, "servetls returned")
|
||||
return fmt.Errorf("servetls returned: %w", err)
|
||||
}
|
||||
|
||||
// Close the server and associated listener. The server may not be reused after
|
||||
// calling Close().
|
||||
func (p *TLSProxy) Close() error {
|
||||
// err := p.listener.Close()
|
||||
// if err != nil {
|
||||
// return errors.Wrap(err, "close listener")
|
||||
// }
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
return p.server.Shutdown(ctx)
|
||||
|
|
@ -143,7 +138,7 @@ func (p *TLSProxy) Close() error {
|
|||
func newProxyHandler(targetURL string) (*httputil.ReverseProxy, error) {
|
||||
target, err := url.Parse(targetURL)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "parse target url")
|
||||
return nil, fmt.Errorf("parse target url: %w", err)
|
||||
}
|
||||
|
||||
reverseProxy := &httputil.ReverseProxy{
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package osquery
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
|
@ -12,7 +13,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/orbit/pkg/constant"
|
||||
"github.com/fleetdm/fleet/v4/orbit/pkg/process"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -44,7 +44,7 @@ func NewRunner(path string, options ...func(*Runner) error) (*Runner, error) {
|
|||
for _, option := range options {
|
||||
err := option(r)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "apply option")
|
||||
return nil, fmt.Errorf("apply option: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -82,7 +82,7 @@ func WithDataPath(path string) func(*Runner) error {
|
|||
r.dataPath = path
|
||||
|
||||
if err := secure.MkdirAll(filepath.Join(path, "logs"), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "initialize osquery data path")
|
||||
return fmt.Errorf("initialize osquery data path: %w", err)
|
||||
}
|
||||
|
||||
r.cmd.Args = append(r.cmd.Args,
|
||||
|
|
@ -97,7 +97,7 @@ func WithDataPath(path string) func(*Runner) error {
|
|||
func WithLogPath(path string) func(*Runner) error {
|
||||
return func(r *Runner) error {
|
||||
if err := secure.MkdirAll(path, constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "initialize osquery log path")
|
||||
return fmt.Errorf("initialize osquery log path: %w", err)
|
||||
}
|
||||
|
||||
r.cmd.Args = append(r.cmd.Args,
|
||||
|
|
@ -118,11 +118,11 @@ func (r *Runner) Execute() error {
|
|||
r.cancel = cancel
|
||||
|
||||
if err := r.proc.Start(); err != nil {
|
||||
return errors.Wrap(err, "start osqueryd")
|
||||
return fmt.Errorf("start osqueryd: %w", err)
|
||||
}
|
||||
|
||||
if err := r.proc.WaitOrKill(ctx, 10*time.Second); err != nil {
|
||||
return errors.Wrap(err, "osqueryd exited with error")
|
||||
return fmt.Errorf("osqueryd exited with error: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package packaging
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
|
@ -12,7 +13,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/goreleaser/nfpm/v2"
|
||||
"github.com/goreleaser/nfpm/v2/files"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -26,11 +26,11 @@ func buildNFPM(opt Options, pkger nfpm.Packager) (string, error) {
|
|||
|
||||
filesystemRoot := filepath.Join(tmpDir, "root")
|
||||
if err := secure.MkdirAll(filesystemRoot, constant.DefaultDirMode); err != nil {
|
||||
return "", errors.Wrap(err, "create root dir")
|
||||
return "", fmt.Errorf("create root dir: %w", err)
|
||||
}
|
||||
orbitRoot := filepath.Join(filesystemRoot, "var", "lib", "orbit")
|
||||
if err := secure.MkdirAll(orbitRoot, constant.DefaultDirMode); err != nil {
|
||||
return "", errors.Wrap(err, "create orbit dir")
|
||||
return "", fmt.Errorf("create orbit dir: %w", err)
|
||||
}
|
||||
|
||||
// Initialize autoupdate metadata
|
||||
|
|
@ -46,35 +46,35 @@ func buildNFPM(opt Options, pkger nfpm.Packager) (string, error) {
|
|||
}
|
||||
|
||||
if err := InitializeUpdates(updateOpt); err != nil {
|
||||
return "", errors.Wrap(err, "initialize updates")
|
||||
return "", fmt.Errorf("initialize updates: %w", err)
|
||||
}
|
||||
|
||||
// Write files
|
||||
|
||||
if err := writeSystemdUnit(opt, filesystemRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write systemd unit")
|
||||
return "", fmt.Errorf("write systemd unit: %w", err)
|
||||
}
|
||||
|
||||
if err := writeEnvFile(opt, filesystemRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write env file")
|
||||
return "", fmt.Errorf("write env file: %w", err)
|
||||
}
|
||||
|
||||
if err := writeOsqueryFlagfile(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write flagfile")
|
||||
return "", fmt.Errorf("write flagfile: %w", err)
|
||||
}
|
||||
|
||||
if err := writeOsqueryCertPEM(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write certs.pem")
|
||||
return "", fmt.Errorf("write certs.pem: %w", err)
|
||||
}
|
||||
|
||||
postInstallPath := filepath.Join(tmpDir, "postinstall.sh")
|
||||
if err := writePostInstall(opt, postInstallPath); err != nil {
|
||||
return "", errors.Wrap(err, "write postinstall script")
|
||||
return "", fmt.Errorf("write postinstall script: %w", err)
|
||||
}
|
||||
|
||||
if opt.FleetCertificate != "" {
|
||||
if err := writeCertificate(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write fleet certificate")
|
||||
return "", fmt.Errorf("write fleet certificate: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -106,7 +106,7 @@ func buildNFPM(opt Options, pkger nfpm.Packager) (string, error) {
|
|||
}
|
||||
contents, err = files.ExpandContentGlobs(contents, false)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "glob contents")
|
||||
return "", fmt.Errorf("glob contents: %w", err)
|
||||
}
|
||||
for _, c := range contents {
|
||||
log.Debug().Interface("file", c).Msg("added file")
|
||||
|
|
@ -136,15 +136,15 @@ func buildNFPM(opt Options, pkger nfpm.Packager) (string, error) {
|
|||
|
||||
out, err := secure.OpenFile(filename, os.O_CREATE|os.O_RDWR, constant.DefaultFileMode)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "open output file")
|
||||
return "", fmt.Errorf("open output file: %w", err)
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if err := pkger.Package(info, out); err != nil {
|
||||
return "", errors.Wrap(err, "write package")
|
||||
return "", fmt.Errorf("write package: %w", err)
|
||||
}
|
||||
if err := out.Sync(); err != nil {
|
||||
return "", errors.Wrap(err, "sync output file")
|
||||
return "", fmt.Errorf("sync output file: %w", err)
|
||||
}
|
||||
log.Info().Str("path", filename).Msg("wrote package")
|
||||
|
||||
|
|
@ -154,7 +154,7 @@ func buildNFPM(opt Options, pkger nfpm.Packager) (string, error) {
|
|||
func writeSystemdUnit(opt Options, rootPath string) error {
|
||||
systemdRoot := filepath.Join(rootPath, "usr", "lib", "systemd", "system")
|
||||
if err := secure.MkdirAll(systemdRoot, constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "create systemd dir")
|
||||
return fmt.Errorf("create systemd dir: %w", err)
|
||||
}
|
||||
if err := ioutil.WriteFile(
|
||||
filepath.Join(systemdRoot, "orbit.service"),
|
||||
|
|
@ -179,7 +179,7 @@ WantedBy=multi-user.target
|
|||
`),
|
||||
constant.DefaultFileMode,
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -199,12 +199,12 @@ ORBIT_OSQUERYD_CHANNEL={{ .OsquerydChannel }}
|
|||
func writeEnvFile(opt Options, rootPath string) error {
|
||||
envRoot := filepath.Join(rootPath, "etc", "default")
|
||||
if err := secure.MkdirAll(envRoot, constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "create env dir")
|
||||
return fmt.Errorf("create env dir: %w", err)
|
||||
}
|
||||
|
||||
var contents bytes.Buffer
|
||||
if err := envTemplate.Execute(&contents, opt); err != nil {
|
||||
return errors.Wrap(err, "execute template")
|
||||
return fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(
|
||||
|
|
@ -212,7 +212,7 @@ func writeEnvFile(opt Options, rootPath string) error {
|
|||
contents.Bytes(),
|
||||
constant.DefaultFileMode,
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -236,11 +236,11 @@ fi
|
|||
func writePostInstall(opt Options, path string) error {
|
||||
var contents bytes.Buffer
|
||||
if err := postInstallTemplate.Execute(&contents, opt); err != nil {
|
||||
return errors.Wrap(err, "execute template")
|
||||
return fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, contents.Bytes(), constant.DefaultFileMode); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/orbit/pkg/update"
|
||||
"github.com/fleetdm/fleet/v4/pkg/file"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -31,11 +30,11 @@ func BuildPkg(opt Options) (string, error) {
|
|||
|
||||
filesystemRoot := filepath.Join(tmpDir, "root")
|
||||
if err := secure.MkdirAll(filesystemRoot, constant.DefaultDirMode); err != nil {
|
||||
return "", errors.Wrap(err, "create root dir")
|
||||
return "", fmt.Errorf("create root dir: %w", err)
|
||||
}
|
||||
orbitRoot := filepath.Join(filesystemRoot, "var", "lib", "orbit")
|
||||
if err := secure.MkdirAll(orbitRoot, constant.DefaultDirMode); err != nil {
|
||||
return "", errors.Wrap(err, "create orbit dir")
|
||||
return "", fmt.Errorf("create orbit dir: %w", err)
|
||||
}
|
||||
|
||||
// Initialize autoupdate metadata
|
||||
|
|
@ -51,38 +50,38 @@ func BuildPkg(opt Options) (string, error) {
|
|||
}
|
||||
|
||||
if err := InitializeUpdates(updateOpt); err != nil {
|
||||
return "", errors.Wrap(err, "initialize updates")
|
||||
return "", fmt.Errorf("initialize updates: %w", err)
|
||||
}
|
||||
|
||||
// Write files
|
||||
|
||||
if err := writePackageInfo(opt, tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "write PackageInfo")
|
||||
return "", fmt.Errorf("write PackageInfo: %w", err)
|
||||
}
|
||||
if err := writeDistribution(opt, tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "write Distribution")
|
||||
return "", fmt.Errorf("write Distribution: %w", err)
|
||||
}
|
||||
if err := writeScripts(opt, tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "write postinstall")
|
||||
return "", fmt.Errorf("write postinstall: %w", err)
|
||||
}
|
||||
if err := writeSecret(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write enroll secret")
|
||||
return "", fmt.Errorf("write enroll secret: %w", err)
|
||||
}
|
||||
if err := writeOsqueryFlagfile(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write flagfile")
|
||||
return "", fmt.Errorf("write flagfile: %w", err)
|
||||
}
|
||||
if err := writeOsqueryCertPEM(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write certs.pem")
|
||||
return "", fmt.Errorf("write certs.pem: %w", err)
|
||||
}
|
||||
|
||||
if opt.StartService {
|
||||
if err := writeLaunchd(opt, filesystemRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write launchd")
|
||||
return "", fmt.Errorf("write launchd: %w", err)
|
||||
}
|
||||
}
|
||||
if opt.FleetCertificate != "" {
|
||||
if err := writeCertificate(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write fleet certificate")
|
||||
return "", fmt.Errorf("write fleet certificate: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -98,7 +97,7 @@ func BuildPkg(opt Options) (string, error) {
|
|||
// Build package
|
||||
|
||||
if err := xarBom(opt, tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "build pkg")
|
||||
return "", fmt.Errorf("build pkg: %w", err)
|
||||
}
|
||||
|
||||
generatedPath := filepath.Join(tmpDir, "orbit.pkg")
|
||||
|
|
@ -106,7 +105,7 @@ func BuildPkg(opt Options) (string, error) {
|
|||
if len(opt.SignIdentity) != 0 {
|
||||
log.Info().Str("identity", opt.SignIdentity).Msg("productsign package")
|
||||
if err := signPkg(generatedPath, opt.SignIdentity); err != nil {
|
||||
return "", errors.Wrap(err, "productsign")
|
||||
return "", fmt.Errorf("productsign: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -118,7 +117,7 @@ func BuildPkg(opt Options) (string, error) {
|
|||
|
||||
filename := "fleet-osquery.pkg"
|
||||
if err := file.Copy(generatedPath, filename, constant.DefaultFileMode); err != nil {
|
||||
return "", errors.Wrap(err, "rename pkg")
|
||||
return "", fmt.Errorf("rename pkg: %w", err)
|
||||
}
|
||||
log.Info().Str("path", filename).Msg("wrote pkg package")
|
||||
|
||||
|
|
@ -129,16 +128,16 @@ func writePackageInfo(opt Options, rootPath string) error {
|
|||
// PackageInfo is metadata for the pkg
|
||||
path := filepath.Join(rootPath, "flat", "base.pkg", "PackageInfo")
|
||||
if err := secure.MkdirAll(filepath.Dir(path), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "mkdir")
|
||||
return fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
|
||||
var contents bytes.Buffer
|
||||
if err := macosPackageInfoTemplate.Execute(&contents, opt); err != nil {
|
||||
return errors.Wrap(err, "execute template")
|
||||
return fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, contents.Bytes(), constant.DefaultFileMode); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -148,16 +147,16 @@ func writeScripts(opt Options, rootPath string) error {
|
|||
// Postinstall script
|
||||
path := filepath.Join(rootPath, "scripts", "postinstall")
|
||||
if err := secure.MkdirAll(filepath.Dir(path), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "mkdir")
|
||||
return fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
|
||||
var contents bytes.Buffer
|
||||
if err := macosPostinstallTemplate.Execute(&contents, opt); err != nil {
|
||||
return errors.Wrap(err, "execute template")
|
||||
return fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, contents.Bytes(), 0744); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -167,16 +166,16 @@ func writeLaunchd(opt Options, rootPath string) error {
|
|||
// launchd is the service mechanism on macOS
|
||||
path := filepath.Join(rootPath, "Library", "LaunchDaemons", "com.fleetdm.orbit.plist")
|
||||
if err := secure.MkdirAll(filepath.Dir(path), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "mkdir")
|
||||
return fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
|
||||
var contents bytes.Buffer
|
||||
if err := macosLaunchdTemplate.Execute(&contents, opt); err != nil {
|
||||
return errors.Wrap(err, "execute template")
|
||||
return fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, contents.Bytes(), 0644); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -186,16 +185,16 @@ func writeDistribution(opt Options, rootPath string) error {
|
|||
// Distribution file is metadata for the pkg
|
||||
path := filepath.Join(rootPath, "flat", "Distribution")
|
||||
if err := secure.MkdirAll(filepath.Dir(path), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "mkdir")
|
||||
return fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
|
||||
var contents bytes.Buffer
|
||||
if err := macosDistributionTemplate.Execute(&contents, opt); err != nil {
|
||||
return errors.Wrap(err, "execute template")
|
||||
return fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, contents.Bytes(), constant.DefaultFileMode); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -206,7 +205,7 @@ func writeCertificate(opt Options, orbitRoot string) error {
|
|||
dstPath := filepath.Join(orbitRoot, "fleet.pem")
|
||||
|
||||
if err := file.Copy(opt.FleetCertificate, dstPath, 0644); err != nil {
|
||||
return errors.Wrap(err, "write orbit")
|
||||
return fmt.Errorf("write orbit: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -223,13 +222,13 @@ func xarBom(opt Options, rootPath string) error {
|
|||
filepath.Join(rootPath, "root"),
|
||||
filepath.Join(rootPath, "flat", "base.pkg", "Payload"),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "cpio Payload")
|
||||
return fmt.Errorf("cpio Payload: %w", err)
|
||||
}
|
||||
if err := cpio(
|
||||
filepath.Join(rootPath, "scripts"),
|
||||
filepath.Join(rootPath, "flat", "base.pkg", "Scripts"),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "cpio Scripts")
|
||||
return fmt.Errorf("cpio Scripts: %w", err)
|
||||
}
|
||||
|
||||
// Make bom
|
||||
|
|
@ -250,7 +249,7 @@ func xarBom(opt Options, rootPath string) error {
|
|||
cmdMkbom.Stdout = os.Stdout
|
||||
cmdMkbom.Stderr = os.Stderr
|
||||
if err := cmdMkbom.Run(); err != nil {
|
||||
return errors.Wrap(err, "mkbom")
|
||||
return fmt.Errorf("mkbom: %w", err)
|
||||
}
|
||||
|
||||
// List files for xar
|
||||
|
|
@ -267,7 +266,7 @@ func xarBom(opt Options, rootPath string) error {
|
|||
},
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "iterate files")
|
||||
return fmt.Errorf("iterate files: %w", err)
|
||||
}
|
||||
|
||||
// Make xar
|
||||
|
|
@ -287,7 +286,7 @@ func xarBom(opt Options, rootPath string) error {
|
|||
cmdXar.Stderr = os.Stderr
|
||||
|
||||
if err := cmdXar.Run(); err != nil {
|
||||
return errors.Wrap(err, "run xar")
|
||||
return fmt.Errorf("run xar: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -297,7 +296,7 @@ func cpio(srcPath, dstPath string) error {
|
|||
// This is the compression routine that is expected for pkg files.
|
||||
dst, err := secure.OpenFile(dstPath, os.O_RDWR|os.O_CREATE, 0755)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open dst")
|
||||
return fmt.Errorf("open dst: %w", err)
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
|
|
@ -310,37 +309,37 @@ func cpio(srcPath, dstPath string) error {
|
|||
// Pipes like this: find | cpio | gzip > dstPath
|
||||
cmdCpio.Stdin, err = cmdFind.StdoutPipe()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "pipe cpio")
|
||||
return fmt.Errorf("pipe cpio: %w", err)
|
||||
}
|
||||
cmdGzip.Stdin, err = cmdCpio.StdoutPipe()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "pipe gzip")
|
||||
return fmt.Errorf("pipe gzip: %w", err)
|
||||
}
|
||||
cmdGzip.Stdout = dst
|
||||
|
||||
err = cmdGzip.Start()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "start gzip")
|
||||
return fmt.Errorf("start gzip: %w", err)
|
||||
}
|
||||
err = cmdCpio.Start()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "start cpio")
|
||||
return fmt.Errorf("start cpio: %w", err)
|
||||
}
|
||||
err = cmdFind.Run()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "run find")
|
||||
return fmt.Errorf("run find: %w", err)
|
||||
}
|
||||
err = cmdCpio.Wait()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "wait cpio")
|
||||
return fmt.Errorf("wait cpio: %w", err)
|
||||
}
|
||||
err = cmdGzip.Wait()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "wait gzip")
|
||||
return fmt.Errorf("wait gzip: %w", err)
|
||||
}
|
||||
err = dst.Sync()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "sync dst")
|
||||
return fmt.Errorf("sync dst: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -358,11 +357,11 @@ func signPkg(pkgPath, identity string) error {
|
|||
cmdProductsign.Stderr = &outBuf
|
||||
if err := cmdProductsign.Run(); err != nil {
|
||||
fmt.Println(outBuf.String())
|
||||
return errors.Wrap(err, "productsign")
|
||||
return fmt.Errorf("productsign: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(pkgPath+".signed", pkgPath); err != nil {
|
||||
return errors.Wrap(err, "rename signed")
|
||||
return fmt.Errorf("rename signed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,13 +2,14 @@ package packaging
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/mitchellh/gon/notarize"
|
||||
"github.com/mitchellh/gon/staple"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -36,13 +37,13 @@ func notarizePkg(pkgPath string) error {
|
|||
},
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "notarize")
|
||||
return fmt.Errorf("notarize: %w", err)
|
||||
}
|
||||
|
||||
log.Info().Str("logs", info.LogFileURL).Msg("notarization completed")
|
||||
|
||||
if err := staple.Staple(context.Background(), &staple.Options{File: pkgPath}); err != nil {
|
||||
return errors.Wrap(err, "staple notarization")
|
||||
return fmt.Errorf("staple notarization: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package packaging
|
|||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
|
@ -12,7 +13,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/orbit/pkg/update/filestore"
|
||||
"github.com/fleetdm/fleet/v4/pkg/file"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -56,12 +56,12 @@ func initializeTempDir() (string, error) {
|
|||
// Initialize directories
|
||||
tmpDir, err := ioutil.TempDir("", "orbit-package")
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "failed to create temp dir")
|
||||
return "", fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Chmod(tmpDir, 0755); err != nil {
|
||||
_ = os.RemoveAll(tmpDir)
|
||||
return "", errors.Wrap(err, "change temp directory permissions")
|
||||
return "", fmt.Errorf("change temp directory permissions: %w", err)
|
||||
}
|
||||
log.Debug().Str("path", tmpDir).Msg("created temp directory")
|
||||
|
||||
|
|
@ -71,26 +71,26 @@ func initializeTempDir() (string, error) {
|
|||
func InitializeUpdates(updateOpt update.Options) error {
|
||||
localStore, err := filestore.New(filepath.Join(updateOpt.RootDirectory, "tuf-metadata.json"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create local metadata store")
|
||||
return fmt.Errorf("failed to create local metadata store: %w", err)
|
||||
}
|
||||
updateOpt.LocalStore = localStore
|
||||
|
||||
updater, err := update.New(updateOpt)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to init updater")
|
||||
return fmt.Errorf("failed to init updater: %w", err)
|
||||
}
|
||||
if err := updater.UpdateMetadata(); err != nil {
|
||||
return errors.Wrap(err, "failed to update metadata")
|
||||
return fmt.Errorf("failed to update metadata: %w", err)
|
||||
}
|
||||
osquerydPath, err := updater.Get("osqueryd", updateOpt.OsquerydChannel)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get osqueryd")
|
||||
return fmt.Errorf("failed to get osqueryd: %w", err)
|
||||
}
|
||||
log.Debug().Str("path", osquerydPath).Msg("got osqueryd")
|
||||
|
||||
orbitPath, err := updater.Get("orbit", updateOpt.OrbitChannel)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get orbit")
|
||||
return fmt.Errorf("failed to get orbit: %w", err)
|
||||
}
|
||||
log.Debug().Str("path", orbitPath).Msg("got orbit")
|
||||
|
||||
|
|
@ -101,11 +101,11 @@ func writeSecret(opt Options, orbitRoot string) error {
|
|||
// Enroll secret
|
||||
path := filepath.Join(orbitRoot, "secret.txt")
|
||||
if err := secure.MkdirAll(filepath.Dir(path), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "mkdir")
|
||||
return fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, []byte(opt.EnrollSecret), 0600); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -117,14 +117,14 @@ func writeOsqueryFlagfile(opt Options, orbitRoot string) error {
|
|||
if opt.OsqueryFlagfile == "" {
|
||||
// Write empty flagfile
|
||||
if err := os.WriteFile(dstPath, []byte(""), constant.DefaultFileMode); err != nil {
|
||||
return errors.Wrap(err, "write empty flagfile")
|
||||
return fmt.Errorf("write empty flagfile: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := file.Copy(opt.OsqueryFlagfile, dstPath, constant.DefaultFileMode); err != nil {
|
||||
return errors.Wrap(err, "copy flagfile")
|
||||
return fmt.Errorf("copy flagfile: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -139,7 +139,7 @@ func writeOsqueryCertPEM(opt Options, orbitRoot string) error {
|
|||
dstPath := filepath.Join(orbitRoot, "certs.pem")
|
||||
|
||||
if err := ioutil.WriteFile(dstPath, osqueryCerts, 0644); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -14,7 +14,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/orbit/pkg/update"
|
||||
"github.com/fleetdm/fleet/v4/pkg/file"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -28,11 +27,11 @@ func BuildMSI(opt Options) (string, error) {
|
|||
|
||||
filesystemRoot := filepath.Join(tmpDir, "root")
|
||||
if err := secure.MkdirAll(filesystemRoot, constant.DefaultDirMode); err != nil {
|
||||
return "", errors.Wrap(err, "create root dir")
|
||||
return "", fmt.Errorf("create root dir: %w", err)
|
||||
}
|
||||
orbitRoot := filesystemRoot
|
||||
if err := secure.MkdirAll(orbitRoot, constant.DefaultDirMode); err != nil {
|
||||
return "", errors.Wrap(err, "create orbit dir")
|
||||
return "", fmt.Errorf("create orbit dir: %w", err)
|
||||
}
|
||||
|
||||
// Initialize autoupdate metadata
|
||||
|
|
@ -48,31 +47,31 @@ func BuildMSI(opt Options) (string, error) {
|
|||
}
|
||||
|
||||
if err := InitializeUpdates(updateOpt); err != nil {
|
||||
return "", errors.Wrap(err, "initialize updates")
|
||||
return "", fmt.Errorf("initialize updates: %w", err)
|
||||
}
|
||||
|
||||
// Write files
|
||||
|
||||
if err := writeSecret(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write enroll secret")
|
||||
return "", fmt.Errorf("write enroll secret: %w", err)
|
||||
}
|
||||
|
||||
if err := writeOsqueryFlagfile(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write flagfile")
|
||||
return "", fmt.Errorf("write flagfile: %w", err)
|
||||
}
|
||||
|
||||
if err := writeOsqueryCertPEM(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write certs.pem")
|
||||
return "", fmt.Errorf("write certs.pem: %w", err)
|
||||
}
|
||||
|
||||
if opt.FleetCertificate != "" {
|
||||
if err := writeCertificate(opt, orbitRoot); err != nil {
|
||||
return "", errors.Wrap(err, "write fleet certificate")
|
||||
return "", fmt.Errorf("write fleet certificate: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := writeWixFile(opt, tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "write wix file")
|
||||
return "", fmt.Errorf("write wix file: %w", err)
|
||||
}
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
|
|
@ -81,29 +80,29 @@ func BuildMSI(opt Options) (string, error) {
|
|||
out, err := exec.Command("icacls", tmpDir, "/grant", "everyone:R", "/t").CombinedOutput()
|
||||
if err != nil {
|
||||
fmt.Println(string(out))
|
||||
return "", errors.Wrap(err, "icacls")
|
||||
return "", fmt.Errorf("icacls: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := wix.Heat(tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "package root files")
|
||||
return "", fmt.Errorf("package root files: %w", err)
|
||||
}
|
||||
|
||||
if err := wix.TransformHeat(filepath.Join(tmpDir, "heat.wxs")); err != nil {
|
||||
return "", errors.Wrap(err, "transform heat")
|
||||
return "", fmt.Errorf("transform heat: %w", err)
|
||||
}
|
||||
|
||||
if err := wix.Candle(tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "build package")
|
||||
return "", fmt.Errorf("build package: %w", err)
|
||||
}
|
||||
|
||||
if err := wix.Light(tmpDir); err != nil {
|
||||
return "", errors.Wrap(err, "build package")
|
||||
return "", fmt.Errorf("build package: %w", err)
|
||||
}
|
||||
|
||||
filename := "fleet-osquery.msi"
|
||||
if err := file.Copy(filepath.Join(tmpDir, "orbit.msi"), filename, constant.DefaultFileMode); err != nil {
|
||||
return "", errors.Wrap(err, "rename msi")
|
||||
return "", fmt.Errorf("rename msi: %w", err)
|
||||
}
|
||||
log.Info().Str("path", filename).Msg("wrote msi package")
|
||||
|
||||
|
|
@ -114,16 +113,16 @@ func writeWixFile(opt Options, rootPath string) error {
|
|||
// PackageInfo is metadata for the pkg
|
||||
path := filepath.Join(rootPath, "main.wxs")
|
||||
if err := secure.MkdirAll(filepath.Dir(path), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "mkdir")
|
||||
return fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
|
||||
var contents bytes.Buffer
|
||||
if err := windowsWixTemplate.Execute(&contents, opt); err != nil {
|
||||
return errors.Wrap(err, "execute template")
|
||||
return fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, contents.Bytes(), 0o666); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -3,11 +3,10 @@ package wix
|
|||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type node struct {
|
||||
|
|
@ -45,7 +44,7 @@ func xmlNode(name string, attrs ...*xml.Attr) *node {
|
|||
func TransformHeat(path string) error {
|
||||
contents, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "read file")
|
||||
return fmt.Errorf("read file: %w", err)
|
||||
}
|
||||
|
||||
// Eliminate line feeds (they cause extra junk in the result)
|
||||
|
|
@ -53,26 +52,26 @@ func TransformHeat(path string) error {
|
|||
|
||||
var n node
|
||||
if err := xml.Unmarshal(contents, &n); err != nil {
|
||||
return errors.Wrap(err, "unmarshal xml")
|
||||
return fmt.Errorf("unmarshal xml: %w", err)
|
||||
}
|
||||
|
||||
stack := []*node{}
|
||||
if err := transform(&n, &stack); err != nil {
|
||||
return errors.Wrap(err, "in transform")
|
||||
return fmt.Errorf("in transform: %w", err)
|
||||
}
|
||||
|
||||
contents, err = xml.MarshalIndent(n, "", " ")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "marshal xml")
|
||||
return fmt.Errorf("marshal xml: %w", err)
|
||||
}
|
||||
|
||||
// Remove first as we encounter permission errors on some Linux configurations.
|
||||
if err := os.Remove(path); err != nil {
|
||||
return errors.Wrap(err, "remove old file")
|
||||
return fmt.Errorf("remove old file: %w", err)
|
||||
}
|
||||
|
||||
if err := ioutil.WriteFile(path, contents, 0o600); err != nil {
|
||||
return errors.Wrap(err, "write file")
|
||||
return fmt.Errorf("write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -4,10 +4,9 @@
|
|||
package wix
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -35,7 +34,7 @@ func Heat(path string) error {
|
|||
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errors.Wrap(err, "heat failed")
|
||||
return fmt.Errorf("heat failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -57,7 +56,7 @@ func Candle(path string) error {
|
|||
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errors.Wrap(err, "candle failed")
|
||||
return fmt.Errorf("candle failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -81,7 +80,7 @@ func Light(path string) error {
|
|||
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errors.Wrap(err, "light failed")
|
||||
return fmt.Errorf("light failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -4,17 +4,17 @@
|
|||
package platform
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/orbit/pkg/constant"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// ChmodExecutableDirectory sets the appropriate permissions on an executable
|
||||
// file. On POSIX this is a normal chmod call.
|
||||
func ChmodExecutableDirectory(path string) error {
|
||||
if err := os.Chmod(path, constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "chmod executable directory")
|
||||
return fmt.Errorf("chmod executable directory: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -23,7 +23,7 @@ func ChmodExecutableDirectory(path string) error {
|
|||
// an executable file. On POSIX this is a regular chmod call.
|
||||
func ChmodExecutable(path string) error {
|
||||
if err := os.Chmod(path, constant.DefaultExecutableMode); err != nil {
|
||||
return errors.Wrap(err, "chmod executable")
|
||||
return fmt.Errorf("chmod executable: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,9 @@
|
|||
package platform
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/orbit/pkg/constant"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/hectane/go-acl"
|
||||
)
|
||||
|
|
@ -26,7 +27,7 @@ func ChmodExecutableDirectory(path string) error {
|
|||
acl.GrantSid(fullControl, constant.AdminSID),
|
||||
acl.GrantSid(readAndExecute, constant.UserSID),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "apply ACLs")
|
||||
return fmt.Errorf("apply ACLs: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -43,7 +44,7 @@ func ChmodExecutable(path string) error {
|
|||
acl.GrantSid(fullControl, constant.AdminSID),
|
||||
acl.GrantSid(readAndExecute, constant.UserSID),
|
||||
); err != nil {
|
||||
return errors.Wrap(err, "apply ACLs")
|
||||
return fmt.Errorf("apply ACLs: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,11 +2,12 @@ package filestore
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/orbit/pkg/constant"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/theupdateframework/go-tuf/client"
|
||||
)
|
||||
|
||||
|
|
@ -72,7 +73,7 @@ func (s *fileStore) DeleteMeta(name string) error {
|
|||
func (s *fileStore) readData() error {
|
||||
stat, err := os.Stat(s.filename)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return errors.Wrap(err, "stat file store")
|
||||
return fmt.Errorf("stat file store: %w", err)
|
||||
} else if errors.Is(err, os.ErrNotExist) {
|
||||
// initialize empty
|
||||
s.metadata = metadataMap{}
|
||||
|
|
@ -83,13 +84,13 @@ func (s *fileStore) readData() error {
|
|||
|
||||
f, err := secure.OpenFile(s.filename, os.O_RDWR|os.O_CREATE, constant.DefaultFileMode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open file store")
|
||||
return fmt.Errorf("open file store: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var meta metadataMap
|
||||
if err := json.NewDecoder(f).Decode(&meta); err != nil {
|
||||
return errors.Wrap(err, "read file store")
|
||||
return fmt.Errorf("read file store: %w", err)
|
||||
}
|
||||
|
||||
s.metadata = meta
|
||||
|
|
@ -99,15 +100,15 @@ func (s *fileStore) readData() error {
|
|||
func (s *fileStore) writeData() error {
|
||||
f, err := secure.OpenFile(s.filename, os.O_RDWR|os.O_CREATE, constant.DefaultFileMode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open file store")
|
||||
return fmt.Errorf("open file store: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if err := json.NewEncoder(f).Encode(s.metadata); err != nil {
|
||||
return errors.Wrap(err, "write file store")
|
||||
return fmt.Errorf("write file store: %w", err)
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
return errors.Wrap(err, "sync file store")
|
||||
return fmt.Errorf("sync file store: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -4,11 +4,11 @@ import (
|
|||
"bytes"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/theupdateframework/go-tuf/data"
|
||||
)
|
||||
|
||||
|
|
@ -22,16 +22,16 @@ func CheckFileHash(meta *data.TargetFileMeta, localPath string) error {
|
|||
|
||||
f, err := os.Open(localPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open file for hash")
|
||||
return fmt.Errorf("open file for hash: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if _, err := io.Copy(hashFunc, f); err != nil {
|
||||
return errors.Wrap(err, "read file for hash")
|
||||
return fmt.Errorf("read file for hash: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(hashVal, hashFunc.Sum(nil)) {
|
||||
return errors.Errorf("hash %s does not match expected: %s", data.HexBytes(hashFunc.Sum(nil)), data.HexBytes(hashVal))
|
||||
return fmt.Errorf("hash %s does not match expected: %s", data.HexBytes(hashFunc.Sum(nil)), data.HexBytes(hashVal))
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -55,5 +55,5 @@ func selectHashFunction(meta *data.TargetFileMeta) (hash.Hash, []byte, error) {
|
|||
}
|
||||
}
|
||||
|
||||
return nil, nil, errors.Errorf("no matching hash function found: %v", meta.HashAlgorithms())
|
||||
return nil, nil, fmt.Errorf("no matching hash function found: %v", meta.HashAlgorithms())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,11 +2,12 @@ package update
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
|
|
@ -42,12 +43,12 @@ func NewRunner(client *Updater, opt RunnerOptions) (*Runner, error) {
|
|||
for target, channel := range opt.Targets {
|
||||
meta, err := client.Lookup(target, channel)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "initialize update cache")
|
||||
return nil, fmt.Errorf("initialize update cache: %w", err)
|
||||
}
|
||||
|
||||
_, hash, err := selectHashFunction(meta)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "select hash for cache")
|
||||
return nil, fmt.Errorf("select hash for cache: %w", err)
|
||||
}
|
||||
cache[target] = hash
|
||||
}
|
||||
|
|
@ -93,26 +94,26 @@ func (r *Runner) updateAction() (bool, error) {
|
|||
if err := r.client.UpdateMetadata(); err != nil {
|
||||
// Consider this a non-fatal error since it will be common to be offline
|
||||
// or otherwise unable to retrieve the metadata.
|
||||
return didUpdate, errors.Wrap(err, "update metadata")
|
||||
return didUpdate, fmt.Errorf("update metadata: %w", err)
|
||||
}
|
||||
|
||||
for target, channel := range r.opt.Targets {
|
||||
meta, err := r.client.Lookup(target, channel)
|
||||
if err != nil {
|
||||
return didUpdate, errors.Wrapf(err, "lookup failed")
|
||||
return didUpdate, fmt.Errorf("lookup failed: %w", err)
|
||||
}
|
||||
|
||||
// Check whether the hash has changed
|
||||
_, hash, err := selectHashFunction(meta)
|
||||
if err != nil {
|
||||
return didUpdate, errors.Wrap(err, "select hash for cache")
|
||||
return didUpdate, fmt.Errorf("select hash for cache: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(r.hashCache[target], hash) {
|
||||
// Update detected
|
||||
log.Info().Str("target", target).Str("channel", channel).Msg("update detected")
|
||||
if err := r.updateTarget(target, channel); err != nil {
|
||||
return didUpdate, errors.Wrapf(err, "update %s@%s", target, channel)
|
||||
return didUpdate, fmt.Errorf("update %s@%s: %w", target, channel, err)
|
||||
}
|
||||
log.Info().Str("target", target).Str("channel", channel).Msg("update completed")
|
||||
didUpdate = true
|
||||
|
|
@ -127,7 +128,7 @@ func (r *Runner) updateAction() (bool, error) {
|
|||
func (r *Runner) updateTarget(target, channel string) error {
|
||||
path, err := r.client.Get(target, channel)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "get binary")
|
||||
return fmt.Errorf("get binary: %w", err)
|
||||
}
|
||||
|
||||
if target != "orbit" {
|
||||
|
|
@ -138,10 +139,10 @@ func (r *Runner) updateTarget(target, channel string) error {
|
|||
linkPath := filepath.Join(r.client.opt.RootDirectory, "bin", "orbit", filepath.Base(path))
|
||||
// Rename the old file otherwise overwrite fails
|
||||
if err := os.Rename(linkPath, linkPath+".old"); err != nil {
|
||||
return errors.Wrap(err, "move old symlink current")
|
||||
return fmt.Errorf("move old symlink current: %w", err)
|
||||
}
|
||||
if err := os.Symlink(path, linkPath); err != nil {
|
||||
return errors.Wrap(err, "symlink current")
|
||||
return fmt.Errorf("symlink current: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ package update
|
|||
import (
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
|
@ -14,7 +16,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/orbit/pkg/platform"
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/theupdateframework/go-tuf/client"
|
||||
"github.com/theupdateframework/go-tuf/data"
|
||||
|
|
@ -76,23 +77,23 @@ func New(opt Options) (*Updater, error) {
|
|||
|
||||
remoteStore, err := client.HTTPRemoteStore(opt.ServerURL, nil, httpClient)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "init remote store")
|
||||
return nil, fmt.Errorf("init remote store: %w", err)
|
||||
}
|
||||
|
||||
tufClient := client.NewClient(opt.LocalStore, remoteStore)
|
||||
var rootKeys []*data.Key
|
||||
if err := json.Unmarshal([]byte(opt.RootKeys), &rootKeys); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshal root keys")
|
||||
return nil, fmt.Errorf("unmarshal root keys: %w", err)
|
||||
}
|
||||
|
||||
meta, err := opt.LocalStore.GetMeta()
|
||||
if err != nil || meta["root.json"] == nil {
|
||||
var rootKeys []*data.Key
|
||||
if err := json.Unmarshal([]byte(opt.RootKeys), &rootKeys); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshal root keys")
|
||||
return nil, fmt.Errorf("unmarshal root keys: %w", err)
|
||||
}
|
||||
if err := tufClient.Init(rootKeys, 1); err != nil {
|
||||
return nil, errors.Wrap(err, "init tuf client")
|
||||
return nil, fmt.Errorf("init tuf client: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -113,7 +114,7 @@ func (u *Updater) UpdateMetadata() error {
|
|||
// An error is returned if we are already up-to-date. We can ignore that
|
||||
// error.
|
||||
if !client.IsLatestSnapshot(ctxerr.Cause(err)) {
|
||||
return errors.Wrap(err, "update metadata")
|
||||
return fmt.Errorf("update metadata: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
|
@ -132,7 +133,7 @@ func (u *Updater) LocalPath(target, channel string) string {
|
|||
func (u *Updater) Lookup(target, channel string) (*data.TargetFileMeta, error) {
|
||||
t, err := u.client.Target(u.RepoPath(target, channel))
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "lookup %s@%s", target, channel)
|
||||
return nil, fmt.Errorf("lookup %s@%s: %w", target, channel, err)
|
||||
}
|
||||
|
||||
return &t, nil
|
||||
|
|
@ -142,7 +143,7 @@ func (u *Updater) Lookup(target, channel string) (*data.TargetFileMeta, error) {
|
|||
func (u *Updater) Targets() (data.TargetFiles, error) {
|
||||
targets, err := u.client.Targets()
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "get targets")
|
||||
return nil, fmt.Errorf("get targets: %w", err)
|
||||
}
|
||||
|
||||
return targets, nil
|
||||
|
|
@ -166,7 +167,7 @@ func (u *Updater) Get(target, channel string) (string, error) {
|
|||
return localPath, u.Download(repoPath, localPath)
|
||||
}
|
||||
if !stat.Mode().IsRegular() {
|
||||
return "", errors.Errorf("expected %s to be regular file", localPath)
|
||||
return "", fmt.Errorf("expected %s to be regular file", localPath)
|
||||
}
|
||||
|
||||
meta, err := u.Lookup(target, channel)
|
||||
|
|
@ -190,7 +191,7 @@ func (u *Updater) Download(repoPath, localPath string) error {
|
|||
staging := filepath.Join(u.opt.RootDirectory, stagingDir)
|
||||
|
||||
if err := secure.MkdirAll(staging, constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "initialize download dir")
|
||||
return fmt.Errorf("initialize download dir: %w", err)
|
||||
}
|
||||
|
||||
// Additional chmod only necessary on Windows, effectively a no-op on other
|
||||
|
|
@ -205,18 +206,18 @@ func (u *Updater) Download(repoPath, localPath string) error {
|
|||
constant.DefaultExecutableMode,
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open temp file for download")
|
||||
return fmt.Errorf("open temp file for download: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
tmp.Close()
|
||||
os.Remove(tmp.Name())
|
||||
}()
|
||||
if err := platform.ChmodExecutable(tmp.Name()); err != nil {
|
||||
return errors.Wrap(err, "chmod download")
|
||||
return fmt.Errorf("chmod download: %w", err)
|
||||
}
|
||||
|
||||
if err := secure.MkdirAll(filepath.Dir(localPath), constant.DefaultDirMode); err != nil {
|
||||
return errors.Wrap(err, "initialize download dir")
|
||||
return fmt.Errorf("initialize download dir: %w", err)
|
||||
}
|
||||
|
||||
// Additional chmod only necessary on Windows, effectively a no-op on other
|
||||
|
|
@ -227,10 +228,10 @@ func (u *Updater) Download(repoPath, localPath string) error {
|
|||
|
||||
// The go-tuf client handles checking of max size and hash.
|
||||
if err := u.client.Download(repoPath, &fileDestination{tmp}); err != nil {
|
||||
return errors.Wrapf(err, "download target %s", repoPath)
|
||||
return fmt.Errorf("download target %s: %w", repoPath, err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return errors.Wrap(err, "close tmp file")
|
||||
return fmt.Errorf("close tmp file: %w", err)
|
||||
}
|
||||
|
||||
// Attempt to exec the new binary only if the platform matches. This will
|
||||
|
|
@ -240,19 +241,19 @@ func (u *Updater) Download(repoPath, localPath string) error {
|
|||
// Note that this would fail for any binary that returns nonzero for --help.
|
||||
out, err := exec.Command(tmp.Name(), "--help").CombinedOutput()
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "exec new version: %s", string(out))
|
||||
return fmt.Errorf("exec new version: %s: %w", string(out), err)
|
||||
}
|
||||
}
|
||||
|
||||
if constant.PlatformName == "windows" {
|
||||
// Remove old file first
|
||||
if err := os.Rename(localPath, localPath+".old"); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return errors.Wrap(err, "rename old")
|
||||
return fmt.Errorf("rename old: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.Rename(tmp.Name(), localPath); err != nil {
|
||||
return errors.Wrap(err, "move download")
|
||||
return fmt.Errorf("move download: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -268,7 +269,7 @@ func (u *Updater) initializeDirectories() error {
|
|||
} {
|
||||
err := secure.MkdirAll(dir, constant.DefaultDirMode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "initialize directories")
|
||||
return fmt.Errorf("initialize directories: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,10 +5,11 @@ import (
|
|||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
)
|
||||
|
||||
// LoadPEM loads certificates from a PEM file and returns a cert pool containing
|
||||
|
|
@ -18,11 +19,11 @@ func LoadPEM(path string) (*x509.CertPool, error) {
|
|||
|
||||
contents, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "read certificate file")
|
||||
return nil, fmt.Errorf("read certificate file: %w", err)
|
||||
}
|
||||
|
||||
if ok := pool.AppendCertsFromPEM(contents); !ok {
|
||||
return nil, errors.Errorf("no valid certificates found in %s", path)
|
||||
return nil, fmt.Errorf("no valid certificates found in %s", path)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
|
|
@ -41,7 +42,7 @@ func ValidateConnection(pool *x509.CertPool, fleetURL string) error {
|
|||
func ValidateConnectionContext(ctx context.Context, pool *x509.CertPool, fleetURL string) error {
|
||||
parsed, err := url.Parse(fleetURL)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "parse url")
|
||||
return ctxerr.Wrap(ctx, err, "parse url")
|
||||
}
|
||||
|
||||
dialer := &tls.Dialer{
|
||||
|
|
@ -50,7 +51,7 @@ func ValidateConnectionContext(ctx context.Context, pool *x509.CertPool, fleetUR
|
|||
InsecureSkipVerify: true,
|
||||
VerifyConnection: func(state tls.ConnectionState) error {
|
||||
if len(state.PeerCertificates) == 0 {
|
||||
return errors.New("no peer certificates")
|
||||
return ctxerr.New(ctx, "no peer certificates")
|
||||
}
|
||||
|
||||
cert := state.PeerCertificates[0]
|
||||
|
|
@ -58,7 +59,7 @@ func ValidateConnectionContext(ctx context.Context, pool *x509.CertPool, fleetUR
|
|||
DNSName: parsed.Hostname(),
|
||||
Roots: pool,
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "verify certificate")
|
||||
return ctxerr.Wrap(ctx, err, "verify certificate")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -67,7 +68,7 @@ func ValidateConnectionContext(ctx context.Context, pool *x509.CertPool, fleetUR
|
|||
}
|
||||
conn, err := dialer.DialContext(ctx, "tcp", parsed.Host)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "dial for validate")
|
||||
return ctxerr.Wrap(ctx, err, "dial for validate")
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
package file
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Copy copies the file from srcPath to dstPath, using the provided permissions.
|
||||
|
|
@ -16,25 +17,25 @@ import (
|
|||
func Copy(srcPath, dstPath string, perm os.FileMode) error {
|
||||
src, err := os.Open(srcPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open src for copy")
|
||||
return fmt.Errorf("open src for copy: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
if err := secure.MkdirAll(filepath.Dir(dstPath), os.ModeDir|perm); err != nil {
|
||||
return errors.Wrap(err, "create dst dir for copy")
|
||||
return fmt.Errorf("create dst dir for copy: %w", err)
|
||||
}
|
||||
|
||||
dst, err := secure.OpenFile(dstPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, perm)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "open dst for copy")
|
||||
return fmt.Errorf("open dst for copy: %w", err)
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
if _, err := io.Copy(dst, src); err != nil {
|
||||
return errors.Wrap(err, "copy src to dst")
|
||||
return fmt.Errorf("copy src to dst: %w", err)
|
||||
}
|
||||
if err := dst.Sync(); err != nil {
|
||||
return errors.Wrap(err, "sync dst after copy")
|
||||
return fmt.Errorf("sync dst after copy: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -46,7 +47,7 @@ func Copy(srcPath, dstPath string, perm os.FileMode) error {
|
|||
func CopyWithPerms(srcPath, dstPath string) error {
|
||||
stat, err := os.Stat(srcPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "get permissions for copy")
|
||||
return fmt.Errorf("get permissions for copy: %w", err)
|
||||
}
|
||||
|
||||
return Copy(srcPath, dstPath, stat.Mode().Perm())
|
||||
|
|
@ -59,7 +60,7 @@ func Exists(path string) (bool, error) {
|
|||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return false, errors.Wrap(err, "check file exists")
|
||||
return false, fmt.Errorf("check file exists: %w", err)
|
||||
}
|
||||
|
||||
return info.Mode().IsRegular(), nil
|
||||
|
|
|
|||
|
|
@ -4,11 +4,11 @@
|
|||
package secure
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"syscall"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func isMorePermissive(currentMode, newMode os.FileMode) bool {
|
||||
|
|
@ -29,7 +29,7 @@ func checkPermPath(path string, perm os.FileMode) error {
|
|||
if err == nil {
|
||||
if dir.IsDir() {
|
||||
if isMorePermissive(dir.Mode(), perm) {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"Path %s already exists with mode %o instead of the expected %o", path, dir.Mode(), perm)
|
||||
}
|
||||
return nil
|
||||
|
|
@ -66,7 +66,7 @@ func checkPermPath(path string, perm os.FileMode) error {
|
|||
|
||||
func checkPermFile(filePath string, perm os.FileMode) error {
|
||||
if f, err := os.Stat(filePath); !errors.Is(err, os.ErrNotExist) && f != nil && f.Mode() != perm {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"File %s already exists with mode %o instead of the expected %o", filePath, f.Mode(), perm)
|
||||
}
|
||||
if err := checkPermPath(path.Dir(filePath), perm); err != nil {
|
||||
|
|
|
|||
|
|
@ -18,7 +18,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/open-policy-agent/opa/rego"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Authorizer stores the compiled policy and performs authorization checks.
|
||||
|
|
@ -39,7 +38,7 @@ func NewAuthorizer() (*Authorizer, error) {
|
|||
rego.Module("policy.rego", policy),
|
||||
).PrepareForEval(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "prepare query")
|
||||
return nil, fmt.Errorf("prepare query: %w", err)
|
||||
}
|
||||
|
||||
return &Authorizer{query: query}, nil
|
||||
|
|
@ -142,7 +141,7 @@ func jsonToInterface(in interface{}) (interface{}, error) {
|
|||
// map[string]interface{} (structs, maps, etc.)
|
||||
buf := bytes.Buffer{}
|
||||
if err := json.NewEncoder(&buf).Encode(in); err != nil {
|
||||
return nil, errors.Wrap(err, "encode input")
|
||||
return nil, fmt.Errorf("encode input: %w", err)
|
||||
}
|
||||
|
||||
d := json.NewDecoder(&buf)
|
||||
|
|
@ -151,7 +150,7 @@ func jsonToInterface(in interface{}) (interface{}, error) {
|
|||
d.UseNumber()
|
||||
var out map[string]interface{}
|
||||
if err := d.Decode(&out); err != nil {
|
||||
return nil, errors.Wrap(err, "decode input")
|
||||
return nil, fmt.Errorf("decode input: %w", err)
|
||||
}
|
||||
|
||||
// Add the `type` property if the AuthzTyper interface is implemented.
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package config
|
|||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
|
@ -11,7 +12,6 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cast"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
|
@ -256,7 +256,7 @@ func (t *TLS) ToTLSConfig() (*tls.Config, error) {
|
|||
rootCertPool = x509.NewCertPool()
|
||||
pem, err := ioutil.ReadFile(t.TLSCA)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "read server-ca pem")
|
||||
return nil, fmt.Errorf("read server-ca pem: %w", err)
|
||||
}
|
||||
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
|
||||
return nil, errors.New("failed to append PEM.")
|
||||
|
|
@ -270,7 +270,7 @@ func (t *TLS) ToTLSConfig() (*tls.Config, error) {
|
|||
clientCert := make([]tls.Certificate, 0, 1)
|
||||
certs, err := tls.LoadX509KeyPair(t.TLSCert, t.TLSKey)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "load client cert and key")
|
||||
return nil, fmt.Errorf("load client cert and key: %w", err)
|
||||
}
|
||||
clientCert = append(clientCert, certs)
|
||||
cfg.Certificates = clientCert
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/errorstore"
|
||||
"github.com/rotisserie/eris"
|
||||
"github.com/rotisserie/eris" //nolint:depguard
|
||||
)
|
||||
|
||||
type key int
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/datastore/redis/redistest"
|
||||
"github.com/fleetdm/fleet/v4/server/errorstore"
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
pkgerrors "github.com/pkg/errors"
|
||||
pkgerrors "github.com/pkg/errors" //nolint:depguard
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,11 +3,12 @@ package logging
|
|||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
|
|
@ -26,7 +27,7 @@ func TestLoggingErrs(t *testing.T) {
|
|||
t.Run("one error", func(t *testing.T) {
|
||||
buf, logger, lc, ctx := setupTest()
|
||||
|
||||
WithErr(ctx, errors.Wrap(errors.New("AAAA"), "BLAH"))
|
||||
WithErr(ctx, fmt.Errorf("BLAH: %w", errors.New("AAAA")))
|
||||
lc.Log(ctx, logger)
|
||||
logLine := buf.String()
|
||||
checkLogEnds(t, logLine, `err="BLAH: AAAA"`)
|
||||
|
|
@ -34,8 +35,8 @@ func TestLoggingErrs(t *testing.T) {
|
|||
t.Run("two errors", func(t *testing.T) {
|
||||
buf, logger, lc, ctx := setupTest()
|
||||
|
||||
WithErr(ctx, errors.Wrap(errors.New("AAAA"), "BLAH"))
|
||||
WithErr(ctx, errors.Wrap(errors.New("BBBB"), "FOO"))
|
||||
WithErr(ctx, fmt.Errorf("BLAH: %w", errors.New("AAAA")))
|
||||
WithErr(ctx, fmt.Errorf("FOO: %w", errors.New("BBBB")))
|
||||
lc.Log(ctx, logger)
|
||||
logLine := buf.String()
|
||||
checkLogEnds(t, logLine, `err="BLAH: AAAA || FOO: BBBB"`)
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ import (
|
|||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
redigo "github.com/gomodule/redigo/redis"
|
||||
"github.com/rotisserie/eris"
|
||||
"github.com/rotisserie/eris" //nolint:depguard
|
||||
)
|
||||
|
||||
// Handler defines an error handler. Call Handler.Store to handle an error, and
|
||||
|
|
|
|||
|
|
@ -17,8 +17,8 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/datastore/redis/redistest"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
pkgErrors "github.com/pkg/errors"
|
||||
"github.com/rotisserie/eris"
|
||||
pkgErrors "github.com/pkg/errors" //nolint:depguard
|
||||
"github.com/rotisserie/eris" //nolint:depguard
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@ package fleet
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/config"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// SMTP settings names returned from API, these map to SMTPAuthType and
|
||||
|
|
@ -164,7 +164,7 @@ func (d *Duration) UnmarshalJSON(b []byte) error {
|
|||
}
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid duration type: %T", value)
|
||||
return fmt.Errorf("invalid duration type: %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,8 @@
|
|||
package fleet
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// ModifyLabelPayload is used to change editable fields for a Label
|
||||
|
|
@ -37,7 +36,7 @@ func (t LabelType) MarshalJSON() ([]byte, error) {
|
|||
case LabelTypeBuiltIn:
|
||||
return []byte(`"builtin"`), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid LabelType: %d", t)
|
||||
return nil, fmt.Errorf("invalid LabelType: %d", t)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -48,7 +47,7 @@ func (t *LabelType) UnmarshalJSON(b []byte) error {
|
|||
case `"builtin"`, "1":
|
||||
*t = LabelTypeBuiltIn
|
||||
default:
|
||||
return errors.Errorf("invalid LabelType: %s", string(b))
|
||||
return fmt.Errorf("invalid LabelType: %s", string(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -71,7 +70,7 @@ func (t LabelMembershipType) MarshalJSON() ([]byte, error) {
|
|||
case LabelMembershipTypeManual:
|
||||
return []byte(`"manual"`), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid LabelMembershipType: %d", t)
|
||||
return nil, fmt.Errorf("invalid LabelMembershipType: %d", t)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -82,7 +81,7 @@ func (t *LabelMembershipType) UnmarshalJSON(b []byte) error {
|
|||
case `"manual"`:
|
||||
*t = LabelMembershipTypeManual
|
||||
default:
|
||||
return errors.Errorf("invalid LabelMembershipType: %s", string(b))
|
||||
return fmt.Errorf("invalid LabelMembershipType: %s", string(b))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/ghodss/yaml"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryPayload struct {
|
||||
|
|
@ -83,7 +82,7 @@ func LoadQueriesFromYaml(yml string) ([]*Query, error) {
|
|||
var q QueryObject
|
||||
err := yaml.Unmarshal([]byte(s), &q)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshal yaml")
|
||||
return nil, fmt.Errorf("unmarshal yaml: %w", err)
|
||||
}
|
||||
queries = append(queries,
|
||||
&Query{Name: q.Spec.Name, Description: q.Spec.Description, Query: q.Spec.Query},
|
||||
|
|
@ -109,7 +108,7 @@ func WriteQueriesToYaml(queries []*Query) (string, error) {
|
|||
}
|
||||
yml, err := yaml.Marshal(qYaml)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "marshal YAML")
|
||||
return "", fmt.Errorf("marshal YAML: %w", err)
|
||||
}
|
||||
ymlStrings = append(ymlStrings, string(yml))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,16 +10,16 @@ package launcher
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/kolide/osquery-go/plugin/distributed"
|
||||
"github.com/kolide/osquery-go/plugin/logger"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/host"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/health"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/kolide/osquery-go/plugin/distributed"
|
||||
"github.com/kolide/osquery-go/plugin/logger"
|
||||
)
|
||||
|
||||
// launcherWrapper wraps the TLS interface.
|
||||
|
|
@ -49,7 +49,7 @@ func (svc *launcherWrapper) RequestConfig(ctx context.Context, nodeKey string) (
|
|||
|
||||
config, err := svc.tls.GetClientConfig(newCtx)
|
||||
if err != nil {
|
||||
return "", false, errors.Wrap(err, "get config for launcher")
|
||||
return "", false, ctxerr.Wrap(ctx, err, "get config for launcher")
|
||||
}
|
||||
|
||||
if options, ok := config["options"].(map[string]interface{}); ok {
|
||||
|
|
@ -61,7 +61,7 @@ func (svc *launcherWrapper) RequestConfig(ctx context.Context, nodeKey string) (
|
|||
|
||||
configJSON, err := json.Marshal(config)
|
||||
if err != nil {
|
||||
return "", false, errors.Wrap(err, "encoding config for launcher")
|
||||
return "", false, ctxerr.Wrap(ctx, err, "encoding config for launcher")
|
||||
}
|
||||
|
||||
return string(configJSON), false, nil
|
||||
|
|
@ -75,7 +75,7 @@ func (svc *launcherWrapper) RequestQueries(ctx context.Context, nodeKey string)
|
|||
|
||||
queryMap, accelerate, err := svc.tls.GetDistributedQueries(newCtx)
|
||||
if err != nil {
|
||||
return nil, false, errors.Wrap(err, "get queries for launcher")
|
||||
return nil, false, ctxerr.Wrap(ctx, err, "get queries for launcher")
|
||||
}
|
||||
|
||||
result := &distributed.GetQueriesResult{
|
||||
|
|
@ -89,7 +89,7 @@ func (svc *launcherWrapper) RequestQueries(ctx context.Context, nodeKey string)
|
|||
func (svc *launcherWrapper) PublishLogs(ctx context.Context, nodeKey string, logType logger.LogType, logs []string) (string, string, bool, error) {
|
||||
newCtx, invalid, err := svc.authenticateHost(ctx, nodeKey)
|
||||
if err != nil {
|
||||
return "", "", invalid, errors.Wrap(err, "authenticate launcher")
|
||||
return "", "", invalid, ctxerr.Wrap(ctx, err, "authenticate launcher")
|
||||
}
|
||||
|
||||
switch logType {
|
||||
|
|
@ -99,14 +99,14 @@ func (svc *launcherWrapper) PublishLogs(ctx context.Context, nodeKey string, log
|
|||
statuses = append(statuses, []byte(log))
|
||||
}
|
||||
err = svc.tls.SubmitStatusLogs(newCtx, statuses)
|
||||
return "", "", false, errors.Wrap(err, "submit status logs from launcher")
|
||||
return "", "", false, ctxerr.Wrap(ctx, err, "submit status logs from launcher")
|
||||
case logger.LogTypeSnapshot, logger.LogTypeString:
|
||||
var results []json.RawMessage
|
||||
for _, log := range logs {
|
||||
results = append(results, []byte(log))
|
||||
}
|
||||
err = svc.tls.SubmitResultLogs(newCtx, results)
|
||||
return "", "", false, errors.Wrap(err, "submit result logs from launcher")
|
||||
return "", "", false, ctxerr.Wrap(ctx, err, "submit result logs from launcher")
|
||||
default:
|
||||
// We have a logTypeAgent which is not there in the osquery-go enum.
|
||||
// See https://github.com/kolide/launcher/issues/183
|
||||
|
|
@ -131,7 +131,7 @@ func (svc *launcherWrapper) PublishResults(ctx context.Context, nodeKey string,
|
|||
// TODO can Launcher expose the error messages?
|
||||
messages := make(map[string]string)
|
||||
err = svc.tls.SubmitDistributedQueryResults(newCtx, osqueryResults, statuses, messages)
|
||||
return "", "", false, errors.Wrap(err, "submit launcher results")
|
||||
return "", "", false, ctxerr.Wrap(ctx, err, "submit launcher results")
|
||||
}
|
||||
|
||||
func (svc *launcherWrapper) CheckHealth(ctx context.Context) (int32, error) {
|
||||
|
|
|
|||
|
|
@ -40,6 +40,8 @@
|
|||
package live_query
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
|
@ -47,7 +49,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
redigo "github.com/gomodule/redigo/redis"
|
||||
"github.com/mna/redisc"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -183,11 +184,11 @@ func (r *redisLiveQuery) RunQuery(name, sql string, hostIDs []uint) error {
|
|||
// client reads that the query exists but cannot look up the SQL.
|
||||
err := conn.Send("SET", sqlKey, sql, "EX", queryExpiration.Seconds())
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "set sql")
|
||||
return fmt.Errorf("set sql: %w", err)
|
||||
}
|
||||
_, err = conn.Do("SET", targetKey, targets, "EX", queryExpiration.Seconds())
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "set targets")
|
||||
return fmt.Errorf("set targets: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -199,7 +200,7 @@ func (r *redisLiveQuery) StopQuery(name string) error {
|
|||
|
||||
targetKey, sqlKey := generateKeys(name)
|
||||
if _, err := conn.Do("DEL", targetKey, sqlKey); err != nil {
|
||||
return errors.Wrap(err, "del query keys")
|
||||
return fmt.Errorf("del query keys: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -209,7 +210,7 @@ func (r *redisLiveQuery) QueriesForHost(hostID uint) (map[string]string, error)
|
|||
// Get keys for active queries
|
||||
queryKeys, err := redis.ScanKeys(r.pool, queryKeyPrefix+"*", 100)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "scan active queries")
|
||||
return nil, fmt.Errorf("scan active queries: %w", err)
|
||||
}
|
||||
|
||||
keysBySlot := redis.SplitKeysBySlot(r.pool, queryKeys...)
|
||||
|
|
@ -230,7 +231,7 @@ func (r *redisLiveQuery) collectBatchQueriesForHost(hostID uint, queryKeys []str
|
|||
// targets of the query.
|
||||
for _, key := range queryKeys {
|
||||
if err := conn.Send("GETBIT", key, hostID); err != nil {
|
||||
return errors.Wrap(err, "getbit query targets")
|
||||
return fmt.Errorf("getbit query targets: %w", err)
|
||||
}
|
||||
|
||||
// Additionally get SQL even though we don't yet know whether this query
|
||||
|
|
@ -238,13 +239,13 @@ func (r *redisLiveQuery) collectBatchQueriesForHost(hostID uint, queryKeys []str
|
|||
// roundtrip to the Redis server and likely has little cost due to the
|
||||
// small number of queries and limited size of SQL
|
||||
if err := conn.Send("GET", sqlKeyPrefix+key); err != nil {
|
||||
return errors.Wrap(err, "get query sql")
|
||||
return fmt.Errorf("get query sql: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Flush calls to begin receiving results.
|
||||
if err := conn.Flush(); err != nil {
|
||||
return errors.Wrap(err, "flush pipeline")
|
||||
return fmt.Errorf("flush pipeline: %w", err)
|
||||
}
|
||||
|
||||
// Receive target and SQL in order of pipelined calls.
|
||||
|
|
@ -253,7 +254,7 @@ func (r *redisLiveQuery) collectBatchQueriesForHost(hostID uint, queryKeys []str
|
|||
|
||||
targeted, err := redigo.Int(conn.Receive())
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "receive target")
|
||||
return fmt.Errorf("receive target: %w", err)
|
||||
}
|
||||
|
||||
// Be sure to read SQL even if we are not going to include this query.
|
||||
|
|
@ -266,7 +267,7 @@ func (r *redisLiveQuery) collectBatchQueriesForHost(hostID uint, queryKeys []str
|
|||
// stopped since we did the key scan. In any case, attempt to clean
|
||||
// up here.
|
||||
_ = r.StopQuery(name)
|
||||
return errors.Wrap(err, "receive sql")
|
||||
return fmt.Errorf("receive sql: %w", err)
|
||||
}
|
||||
|
||||
if targeted == 0 {
|
||||
|
|
@ -286,7 +287,7 @@ func (r *redisLiveQuery) QueryCompletedByHost(name string, hostID uint) error {
|
|||
|
||||
// Update the bitfield for this host.
|
||||
if _, err := conn.Do("SETBIT", targetKey, hostID, 0); err != nil {
|
||||
return errors.Wrap(err, "setbit query key")
|
||||
return fmt.Errorf("setbit query key: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import (
|
|||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
|
@ -11,10 +13,10 @@ import (
|
|||
"syscall"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/pkg/secure"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
lumberjack "gopkg.in/natefinch/lumberjack.v2"
|
||||
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type filesystemLogWriter struct {
|
||||
|
|
@ -31,7 +33,7 @@ func NewFilesystemLogWriter(path string, appLogger log.Logger, enableRotation bo
|
|||
// permissions to open the file at path.
|
||||
file, err := openFile(path)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "perm check")
|
||||
return nil, fmt.Errorf("perm check: %w", err)
|
||||
}
|
||||
if !enableRotation {
|
||||
// no log rotation, use "raw" bufio implementation
|
||||
|
|
@ -74,12 +76,12 @@ func (l *filesystemLogWriter) Write(ctx context.Context, logs []json.RawMessage)
|
|||
// Add newline to separate logs in output file
|
||||
log = append(log, '\n')
|
||||
if _, err := l.writer.Write(log); err != nil {
|
||||
return errors.Wrap(err, "writing log")
|
||||
return ctxerr.Wrap(ctx, err, "writing log")
|
||||
}
|
||||
}
|
||||
if flusher, ok := l.writer.(flusher); ok {
|
||||
if err := flusher.Flush(); err != nil {
|
||||
return errors.Wrap(err, "flushing log")
|
||||
return ctxerr.Wrap(ctx, err, "flushing log")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
|
@ -107,7 +109,7 @@ func (l *rawLogWriter) Write(b []byte) (int, error) {
|
|||
if _, statErr := os.Stat(l.file.Name()); errors.Is(statErr, os.ErrNotExist) {
|
||||
f, err := secure.OpenFile(l.file.Name(), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
|
||||
if err != nil {
|
||||
return 0, errors.Wrapf(err, "create file for filesystemLogWriter %s", l.file.Name())
|
||||
return 0, fmt.Errorf("create file for filesystemLogWriter %s: %w", l.file.Name(), err)
|
||||
}
|
||||
l.file = f
|
||||
l.buff = bufio.NewWriter(f)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
|
@ -77,7 +77,7 @@ func TestFilesystemLoggerPermission(t *testing.T) {
|
|||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := NewFilesystemLogWriter(fileName, log.NewNopLogger(), tc.rotation, false)
|
||||
require.Error(t, err)
|
||||
require.True(t, stderrors.Is(err, fs.ErrPermission), err)
|
||||
require.True(t, errors.Is(err, fs.ErrPermission), err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ package logging
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
|
|
@ -13,9 +15,9 @@ import (
|
|||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/firehose"
|
||||
"github.com/aws/aws-sdk-go/service/firehose/firehoseiface"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -49,7 +51,7 @@ func NewFirehoseLogWriter(region, endpointURL, id, secret, stsAssumeRoleArn, str
|
|||
|
||||
sess, err := session.NewSession(conf)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create Firehose client")
|
||||
return nil, fmt.Errorf("create Firehose client: %w", err)
|
||||
}
|
||||
|
||||
if stsAssumeRoleArn != "" {
|
||||
|
|
@ -59,7 +61,7 @@ func NewFirehoseLogWriter(region, endpointURL, id, secret, stsAssumeRoleArn, str
|
|||
sess, err = session.NewSession(conf)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create Firehose client")
|
||||
return nil, fmt.Errorf("create Firehose client: %w", err)
|
||||
}
|
||||
}
|
||||
client := firehose.New(sess)
|
||||
|
|
@ -70,7 +72,7 @@ func NewFirehoseLogWriter(region, endpointURL, id, secret, stsAssumeRoleArn, str
|
|||
logger: logger,
|
||||
}
|
||||
if err := f.validateStream(); err != nil {
|
||||
return nil, errors.Wrap(err, "create Firehose writer")
|
||||
return nil, fmt.Errorf("create Firehose writer: %w", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
|
@ -82,11 +84,11 @@ func (f *firehoseLogWriter) validateStream() error {
|
|||
},
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "describe stream %s", f.stream)
|
||||
return fmt.Errorf("describe stream %s: %w", f.stream, err)
|
||||
}
|
||||
|
||||
if (*(*out.DeliveryStreamDescription).DeliveryStreamStatus) != firehose.DeliveryStreamStatusActive {
|
||||
return errors.Errorf("delivery stream %s not active", f.stream)
|
||||
return fmt.Errorf("delivery stream %s not active", f.stream)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -121,7 +123,7 @@ func (f *firehoseLogWriter) Write(ctx context.Context, logs []json.RawMessage) e
|
|||
if len(records) >= firehoseMaxRecordsInBatch ||
|
||||
totalBytes+len(log) > firehoseMaxSizeOfBatch {
|
||||
if err := f.putRecordBatch(0, records); err != nil {
|
||||
return errors.Wrap(err, "put records")
|
||||
return ctxerr.Wrap(ctx, err, "put records")
|
||||
}
|
||||
totalBytes = 0
|
||||
records = nil
|
||||
|
|
@ -134,7 +136,7 @@ func (f *firehoseLogWriter) Write(ctx context.Context, logs []json.RawMessage) e
|
|||
// Push the final batch
|
||||
if len(records) > 0 {
|
||||
if err := f.putRecordBatch(0, records); err != nil {
|
||||
return errors.Wrap(err, "put records")
|
||||
return ctxerr.Wrap(ctx, err, "put records")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -178,7 +180,7 @@ func (f *firehoseLogWriter) putRecordBatch(try int, records []*firehose.Record)
|
|||
}
|
||||
}
|
||||
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"failed to put %d records, retries exhausted. First error: %s",
|
||||
*output.FailedPutCount, errMsg,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import (
|
|||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -65,12 +65,12 @@ func (l *kafkaRESTProducer) Write(ctx context.Context, logs []json.RawMessage) e
|
|||
|
||||
output, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "kafka rest marshal")
|
||||
return ctxerr.Wrap(ctx, err, "kafka rest marshal")
|
||||
}
|
||||
|
||||
resp, err := l.post(l.URL, bytes.NewBuffer(output))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "kafka rest post")
|
||||
return ctxerr.Wrap(ctx, err, "kafka rest post")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
|
@ -80,7 +80,7 @@ func (l *kafkaRESTProducer) Write(ctx context.Context, logs []json.RawMessage) e
|
|||
func checkResponse(resp *http.Response) (err error) {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
return errors.Errorf("Error: %d. %s", resp.StatusCode, string(body))
|
||||
return fmt.Errorf("Error: %d. %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -89,7 +89,7 @@ func checkResponse(resp *http.Response) (err error) {
|
|||
func (l *kafkaRESTProducer) checkTopic() (err error) {
|
||||
resp, err := l.client.Get(l.CheckURL)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "kafka rest topic check")
|
||||
return fmt.Errorf("kafka rest topic check: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
|
@ -99,7 +99,7 @@ func (l *kafkaRESTProducer) checkTopic() (err error) {
|
|||
func (l *kafkaRESTProducer) post(url string, buf *bytes.Buffer) (*http.Response, error) {
|
||||
req, err := http.NewRequest(http.MethodPost, url, buf)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "kafka rest new request")
|
||||
return nil, fmt.Errorf("kafka rest new request: %w", err)
|
||||
}
|
||||
|
||||
now := float64(time.Now().UnixNano()) / float64(time.Second)
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package logging
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand"
|
||||
|
|
@ -15,9 +16,9 @@ import (
|
|||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -52,7 +53,7 @@ func NewKinesisLogWriter(region, endpointURL, id, secret, stsAssumeRoleArn, stre
|
|||
|
||||
sess, err := session.NewSession(conf)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create Kinesis client")
|
||||
return nil, fmt.Errorf("create Kinesis client: %w", err)
|
||||
}
|
||||
|
||||
if stsAssumeRoleArn != "" {
|
||||
|
|
@ -62,7 +63,7 @@ func NewKinesisLogWriter(region, endpointURL, id, secret, stsAssumeRoleArn, stre
|
|||
sess, err = session.NewSession(conf)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create Kinesis client")
|
||||
return nil, fmt.Errorf("create Kinesis client: %w", err)
|
||||
}
|
||||
}
|
||||
client := kinesis.New(sess)
|
||||
|
|
@ -78,7 +79,7 @@ func NewKinesisLogWriter(region, endpointURL, id, secret, stsAssumeRoleArn, stre
|
|||
rand: rand,
|
||||
}
|
||||
if err := k.validateStream(); err != nil {
|
||||
return nil, errors.Wrap(err, "create Kinesis writer")
|
||||
return nil, fmt.Errorf("create Kinesis writer: %w", err)
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
|
@ -90,11 +91,11 @@ func (k *kinesisLogWriter) validateStream() error {
|
|||
},
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "describe stream %s", k.stream)
|
||||
return fmt.Errorf("describe stream %s: %w", k.stream, err)
|
||||
}
|
||||
|
||||
if (*(*out.StreamDescription).StreamStatus) != kinesis.StreamStatusActive {
|
||||
return errors.Errorf("stream %s not active", k.stream)
|
||||
return fmt.Errorf("stream %s not active", k.stream)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -129,7 +130,7 @@ func (k *kinesisLogWriter) Write(ctx context.Context, logs []json.RawMessage) er
|
|||
if len(records) >= kinesisMaxRecordsInBatch ||
|
||||
totalBytes+len(log)+len(partitionKey) > kinesisMaxSizeOfBatch {
|
||||
if err := k.putRecords(0, records); err != nil {
|
||||
return errors.Wrap(err, "put records")
|
||||
return ctxerr.Wrap(ctx, err, "put records")
|
||||
}
|
||||
totalBytes = 0
|
||||
records = nil
|
||||
|
|
@ -142,7 +143,7 @@ func (k *kinesisLogWriter) Write(ctx context.Context, logs []json.RawMessage) er
|
|||
// Push the final batch
|
||||
if len(records) > 0 {
|
||||
if err := k.putRecords(0, records); err != nil {
|
||||
return errors.Wrap(err, "put records")
|
||||
return ctxerr.Wrap(ctx, err, "put records")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -186,7 +187,7 @@ func (k *kinesisLogWriter) putRecords(try int, records []*kinesis.PutRecordsRequ
|
|||
}
|
||||
}
|
||||
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"failed to put %d records, retries exhausted. First error: %s",
|
||||
*output.FailedRecordCount, errMsg,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package logging
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
|
|
@ -12,7 +13,6 @@ import (
|
|||
"github.com/aws/aws-sdk-go/service/lambda/lambdaiface"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -43,7 +43,7 @@ func NewLambdaLogWriter(region, id, secret, stsAssumeRoleArn, functionName strin
|
|||
|
||||
sess, err := session.NewSession(conf)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create Lambda client")
|
||||
return nil, fmt.Errorf("create Lambda client: %w", err)
|
||||
}
|
||||
|
||||
if stsAssumeRoleArn != "" {
|
||||
|
|
@ -53,7 +53,7 @@ func NewLambdaLogWriter(region, id, secret, stsAssumeRoleArn, functionName strin
|
|||
sess, err = session.NewSession(conf)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create Lambda client")
|
||||
return nil, fmt.Errorf("create Lambda client: %w", err)
|
||||
}
|
||||
}
|
||||
client := lambda.New(sess)
|
||||
|
|
@ -64,7 +64,7 @@ func NewLambdaLogWriter(region, id, secret, stsAssumeRoleArn, functionName strin
|
|||
logger: logger,
|
||||
}
|
||||
if err := f.validateFunction(); err != nil {
|
||||
return nil, errors.Wrap(err, "validate lambda")
|
||||
return nil, fmt.Errorf("validate lambda: %w", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
|
@ -77,10 +77,10 @@ func (f *lambdaLogWriter) validateFunction() error {
|
|||
},
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "dry run %s", f.functionName)
|
||||
return fmt.Errorf("dry run %s: %w", f.functionName, err)
|
||||
}
|
||||
if out.FunctionError != nil {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"dry run %s function error: %s",
|
||||
f.functionName,
|
||||
*out.FunctionError,
|
||||
|
|
@ -111,10 +111,10 @@ func (f *lambdaLogWriter) Write(ctx context.Context, logs []json.RawMessage) err
|
|||
},
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "run %s", f.functionName)
|
||||
return fmt.Errorf("run %s: %w", f.functionName, err)
|
||||
}
|
||||
if out.FunctionError != nil {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"run %s function error: %s",
|
||||
f.functionName,
|
||||
*out.FunctionError,
|
||||
|
|
|
|||
|
|
@ -3,11 +3,12 @@
|
|||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/config"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type OsqueryLogger struct {
|
||||
|
|
@ -32,7 +33,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
config.Filesystem.EnableLogCompression,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create filesystem status logger")
|
||||
return nil, fmt.Errorf("create filesystem status logger: %w", err)
|
||||
}
|
||||
case "firehose":
|
||||
status, err = NewFirehoseLogWriter(
|
||||
|
|
@ -45,7 +46,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create firehose status logger")
|
||||
return nil, fmt.Errorf("create firehose status logger: %w", err)
|
||||
}
|
||||
case "kinesis":
|
||||
status, err = NewKinesisLogWriter(
|
||||
|
|
@ -58,7 +59,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create kinesis status logger")
|
||||
return nil, fmt.Errorf("create kinesis status logger: %w", err)
|
||||
}
|
||||
case "lambda":
|
||||
status, err = NewLambdaLogWriter(
|
||||
|
|
@ -70,7 +71,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create lambda status logger")
|
||||
return nil, fmt.Errorf("create lambda status logger: %w", err)
|
||||
}
|
||||
case "pubsub":
|
||||
status, err = NewPubSubLogWriter(
|
||||
|
|
@ -80,12 +81,12 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create pubsub status logger")
|
||||
return nil, fmt.Errorf("create pubsub status logger: %w", err)
|
||||
}
|
||||
case "stdout":
|
||||
status, err = NewStdoutLogWriter()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create stdout status logger")
|
||||
return nil, fmt.Errorf("create stdout status logger: %w", err)
|
||||
}
|
||||
case "kafkarest":
|
||||
status, err = NewKafkaRESTWriter(&KafkaRESTParams{
|
||||
|
|
@ -94,10 +95,10 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
KafkaTimeout: config.KafkaREST.Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create kafka rest status logger")
|
||||
return nil, fmt.Errorf("create kafka rest status logger: %w", err)
|
||||
}
|
||||
default:
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"unknown status log plugin: %s", config.Osquery.StatusLogPlugin,
|
||||
)
|
||||
}
|
||||
|
|
@ -115,7 +116,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
config.Filesystem.EnableLogCompression,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create filesystem result logger")
|
||||
return nil, fmt.Errorf("create filesystem result logger: %w", err)
|
||||
}
|
||||
case "firehose":
|
||||
result, err = NewFirehoseLogWriter(
|
||||
|
|
@ -128,7 +129,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create firehose result logger")
|
||||
return nil, fmt.Errorf("create firehose result logger: %w", err)
|
||||
}
|
||||
case "kinesis":
|
||||
result, err = NewKinesisLogWriter(
|
||||
|
|
@ -141,7 +142,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create kinesis result logger")
|
||||
return nil, fmt.Errorf("create kinesis result logger: %w", err)
|
||||
}
|
||||
case "lambda":
|
||||
result, err = NewLambdaLogWriter(
|
||||
|
|
@ -153,7 +154,7 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create lambda result logger")
|
||||
return nil, fmt.Errorf("create lambda result logger: %w", err)
|
||||
}
|
||||
case "pubsub":
|
||||
result, err = NewPubSubLogWriter(
|
||||
|
|
@ -163,12 +164,12 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create pubsub result logger")
|
||||
return nil, fmt.Errorf("create pubsub result logger: %w", err)
|
||||
}
|
||||
case "stdout":
|
||||
result, err = NewStdoutLogWriter()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create stdout result logger")
|
||||
return nil, fmt.Errorf("create stdout result logger: %w", err)
|
||||
}
|
||||
case "kafkarest":
|
||||
result, err = NewKafkaRESTWriter(&KafkaRESTParams{
|
||||
|
|
@ -177,10 +178,10 @@ func New(config config.FleetConfig, logger log.Logger) (*OsqueryLogger, error) {
|
|||
KafkaTimeout: config.KafkaREST.Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create kafka rest result logger")
|
||||
return nil, fmt.Errorf("create kafka rest result logger: %w", err)
|
||||
}
|
||||
default:
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"unknown result log plugin: %s", config.Osquery.StatusLogPlugin,
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,12 +3,13 @@ package logging
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"cloud.google.com/go/pubsub"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type pubSubLogWriter struct {
|
||||
|
|
@ -28,7 +29,7 @@ func NewPubSubLogWriter(projectId string, topicName string, addAttributes bool,
|
|||
|
||||
client, err := pubsub.NewClient(ctx, projectId)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "create pubsub client")
|
||||
return nil, fmt.Errorf("create pubsub client: %w", err)
|
||||
}
|
||||
|
||||
topic := client.Topic(topicName)
|
||||
|
|
@ -62,7 +63,7 @@ func (w *pubSubLogWriter) Write(ctx context.Context, logs []json.RawMessage) err
|
|||
for i, log := range logs {
|
||||
data, err := log.MarshalJSON()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "marshal message into JSON")
|
||||
return ctxerr.Wrap(ctx, err, "marshal message into JSON")
|
||||
}
|
||||
|
||||
attributes := make(map[string]string)
|
||||
|
|
@ -71,7 +72,7 @@ func (w *pubSubLogWriter) Write(ctx context.Context, logs []json.RawMessage) err
|
|||
var unmarshaled PubSubAttributes
|
||||
|
||||
if err := json.Unmarshal(log, &unmarshaled); err != nil {
|
||||
return errors.Wrap(err, "unmarshalling log message JSON")
|
||||
return ctxerr.Wrap(ctx, err, "unmarshalling log message JSON")
|
||||
}
|
||||
attributes["name"] = unmarshaled.Name
|
||||
attributes["timestamp"] = time.Unix(unmarshaled.UnixTime, 0).Format(time.RFC3339)
|
||||
|
|
@ -101,7 +102,7 @@ func (w *pubSubLogWriter) Write(ctx context.Context, logs []json.RawMessage) err
|
|||
for _, result := range results {
|
||||
_, err := result.Get(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "pubsub publish")
|
||||
return ctxerr.Wrap(ctx, err, "pubsub publish")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ package mail
|
|||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net"
|
||||
|
|
@ -13,7 +14,6 @@ import (
|
|||
|
||||
"github.com/fleetdm/fleet/v4/server/bindata"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func NewService() fleet.MailService {
|
||||
|
|
@ -29,7 +29,7 @@ type sender interface {
|
|||
func Test(mailer fleet.MailService, e fleet.Email) error {
|
||||
mailBody, err := getMessageBody(e)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get message body")
|
||||
return fmt.Errorf("failed to get message body: %w", err)
|
||||
}
|
||||
|
||||
svc, ok := mailer.(sender)
|
||||
|
|
@ -39,7 +39,7 @@ func Test(mailer fleet.MailService, e fleet.Email) error {
|
|||
|
||||
err = svc.sendMail(e, mailBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "sending mail")
|
||||
return fmt.Errorf("sending mail: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -53,7 +53,7 @@ const (
|
|||
func getMessageBody(e fleet.Email) ([]byte, error) {
|
||||
body, err := e.Mailer.Message()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "get mailer message")
|
||||
return nil, fmt.Errorf("get mailer message: %w", err)
|
||||
}
|
||||
mime := `MIME-version: 1.0;` + "\r\n"
|
||||
content := `Content-Type: text/html; charset="UTF-8";` + "\r\n"
|
||||
|
|
@ -145,20 +145,20 @@ func (m mailService) sendMail(e fleet.Email, msg []byte) error {
|
|||
"%s:%d", e.Config.SMTPSettings.SMTPServer, e.Config.SMTPSettings.SMTPPort)
|
||||
auth, err := smtpAuth(e)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to get smtp auth")
|
||||
return fmt.Errorf("failed to get smtp auth: %w", err)
|
||||
}
|
||||
|
||||
if e.Config.SMTPSettings.SMTPAuthenticationMethod == fleet.AuthMethodNameCramMD5 {
|
||||
err = smtp.SendMail(smtpHost, auth, e.Config.SMTPSettings.SMTPSenderAddress, e.To, msg)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to send mail. cramd5 auth method")
|
||||
return fmt.Errorf("failed to send mail. cramd5 auth method: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
client, err := dialTimeout(smtpHost)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not dial smtp host")
|
||||
return fmt.Errorf("could not dial smtp host: %w", err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
|
|
@ -169,39 +169,39 @@ func (m mailService) sendMail(e fleet.Email, msg []byte) error {
|
|||
InsecureSkipVerify: !e.Config.SMTPSettings.SMTPVerifySSLCerts,
|
||||
}
|
||||
if err = client.StartTLS(config); err != nil {
|
||||
return errors.Wrap(err, "startTLS error")
|
||||
return fmt.Errorf("startTLS error: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if auth != nil {
|
||||
if err = client.Auth(auth); err != nil {
|
||||
return errors.Wrap(err, "client auth error")
|
||||
return fmt.Errorf("client auth error: %w", err)
|
||||
}
|
||||
}
|
||||
if err = client.Mail(e.Config.SMTPSettings.SMTPSenderAddress); err != nil {
|
||||
return errors.Wrap(err, "could not issue mail to provided address")
|
||||
return fmt.Errorf("could not issue mail to provided address: %w", err)
|
||||
}
|
||||
for _, recip := range e.To {
|
||||
if err = client.Rcpt(recip); err != nil {
|
||||
return errors.Wrap(err, "failed to get recipient")
|
||||
return fmt.Errorf("failed to get recipient: %w", err)
|
||||
}
|
||||
}
|
||||
writer, err := client.Data()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "getting client data")
|
||||
return fmt.Errorf("getting client data: %w", err)
|
||||
}
|
||||
|
||||
_, err = writer.Write(msg)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to write")
|
||||
return fmt.Errorf("failed to write: %w", err)
|
||||
}
|
||||
|
||||
if err = writer.Close(); err != nil {
|
||||
return errors.Wrap(err, "failed to close writer")
|
||||
return fmt.Errorf("failed to close writer: %w", err)
|
||||
}
|
||||
|
||||
if err := client.Quit(); err != nil {
|
||||
return errors.Wrap(err, "error on client quit")
|
||||
return fmt.Errorf("error on client quit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -222,11 +222,11 @@ func dialTimeout(addr string) (client *smtp.Client, err error) {
|
|||
|
||||
conn, err := net.DialTimeout("tcp", addr, 28*time.Second)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "dialing with timeout")
|
||||
return nil, fmt.Errorf("dialing with timeout: %w", err)
|
||||
}
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "split host port")
|
||||
return nil, fmt.Errorf("split host port: %w", err)
|
||||
}
|
||||
|
||||
// Set a deadline to ensure we time out quickly when there is a TCP
|
||||
|
|
|
|||
|
|
@ -7,10 +7,10 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/datastore/redis"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
redigo "github.com/gomodule/redigo/redis"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type redisQueryResults struct {
|
||||
|
|
@ -45,7 +45,7 @@ func (r *redisQueryResults) WriteResult(result fleet.DistributedQueryResult) err
|
|||
|
||||
jsonVal, err := json.Marshal(&result)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "marshalling JSON for result")
|
||||
return fmt.Errorf("marshalling JSON for result: %w", err)
|
||||
}
|
||||
|
||||
hasSubs, err := redis.PublishHasListeners(r.pool, conn, channelName, string(jsonVal))
|
||||
|
|
@ -56,7 +56,7 @@ func (r *redisQueryResults) WriteResult(result fleet.DistributedQueryResult) err
|
|||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "PUBLISH failed to channel "+channelName)
|
||||
return fmt.Errorf("PUBLISH failed to channel "+channelName+": %w", err)
|
||||
}
|
||||
if !hasSubs {
|
||||
return noSubscriberError{channelName}
|
||||
|
|
@ -117,7 +117,7 @@ func (r *redisQueryResults) ReadChannel(ctx context.Context, query fleet.Distrib
|
|||
if err := psc.Subscribe(pubSubName); err != nil {
|
||||
// Explicit conn.Close() here because we can't defer it until in the goroutine
|
||||
_ = conn.Close()
|
||||
return nil, errors.Wrapf(err, "subscribe to channel %s", pubSubName)
|
||||
return nil, ctxerr.Wrapf(ctx, err, "subscribe to channel %s", pubSubName)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
|
@ -140,7 +140,7 @@ func (r *redisQueryResults) ReadChannel(ctx context.Context, query fleet.Distrib
|
|||
select {
|
||||
case msg, ok := <-msgChannel:
|
||||
if !ok {
|
||||
writeOrDone(ctx, outChannel, errors.New("unexpected exit in receiveMessages"))
|
||||
writeOrDone(ctx, outChannel, ctxerr.New(ctx, "unexpected exit in receiveMessages"))
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -157,7 +157,7 @@ func (r *redisQueryResults) ReadChannel(ctx context.Context, query fleet.Distrib
|
|||
return
|
||||
}
|
||||
case error:
|
||||
if writeOrDone(ctx, outChannel, errors.Wrap(msg, "read from redis")) {
|
||||
if writeOrDone(ctx, outChannel, ctxerr.Wrap(ctx, msg, "read from redis")) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
@ -184,7 +184,7 @@ func (r *redisQueryResults) HealthCheck() error {
|
|||
defer conn.Close()
|
||||
|
||||
if _, err := conn.Do("PING"); err != nil {
|
||||
return errors.Wrap(err, "reading from redis")
|
||||
return fmt.Errorf("reading from redis: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,12 +8,12 @@ import (
|
|||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/datastore/redis"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
redigo "github.com/gomodule/redigo/redis"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -108,11 +108,11 @@ func (t *Task) RecordLabelQueryExecutions(ctx context.Context, host *fleet.Host,
|
|||
conn := t.Pool.Get()
|
||||
defer conn.Close()
|
||||
if err := redis.BindConn(t.Pool, conn, keySet, keyTs); err != nil {
|
||||
return errors.Wrap(err, "bind redis connection")
|
||||
return ctxerr.Wrap(ctx, err, "bind redis connection")
|
||||
}
|
||||
|
||||
if _, err := script.Do(conn, args...); err != nil {
|
||||
return err
|
||||
return ctxerr.Wrap(ctx, err, "run redis script")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -147,7 +147,7 @@ func (t *Task) collectLabelQueryExecutions(ctx context.Context, ds fleet.Datasto
|
|||
|
||||
vals, err := redigo.Ints(conn.Do("ZPOPMIN", key, t.RedisPopCount))
|
||||
if err != nil {
|
||||
return hostID, nil, nil, errors.Wrap(err, "redis ZPOPMIN")
|
||||
return hostID, nil, nil, ctxerr.Wrap(ctx, err, "redis ZPOPMIN")
|
||||
}
|
||||
items := len(vals) / 2 // each item has the label id and the score (-1=delete, +1=insert)
|
||||
stats.Items += items
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
|
|
@ -15,8 +16,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// httpClient interface allows the HTTP methods to be mocked.
|
||||
|
|
@ -42,7 +43,7 @@ func NewClient(addr string, insecureSkipVerify bool, rootCA, urlPrefix string, o
|
|||
// API breaking change, needs a major version release
|
||||
baseURL, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "parsing URL")
|
||||
return nil, fmt.Errorf("parsing URL: %w", err)
|
||||
}
|
||||
|
||||
if baseURL.Scheme != "https" && !strings.Contains(baseURL.Host, "localhost") && !strings.Contains(baseURL.Host, "127.0.0.1") {
|
||||
|
|
@ -54,7 +55,7 @@ func NewClient(addr string, insecureSkipVerify bool, rootCA, urlPrefix string, o
|
|||
// read in the root cert file specified in the context
|
||||
certs, err := ioutil.ReadFile(rootCA)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "reading root CA")
|
||||
return nil, fmt.Errorf("reading root CA: %w", err)
|
||||
}
|
||||
|
||||
// add certs to pool
|
||||
|
|
@ -65,7 +66,7 @@ func NewClient(addr string, insecureSkipVerify bool, rootCA, urlPrefix string, o
|
|||
// Use only the system certs (doesn't work on Windows)
|
||||
rootCAPool, err = x509.SystemCertPool()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "loading system cert pool")
|
||||
return nil, fmt.Errorf("loading system cert pool: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -121,7 +122,7 @@ func (c *Client) doContextWithHeaders(ctx context.Context, verb, path, rawQuery
|
|||
if params != nil {
|
||||
bodyBytes, err = json.Marshal(params)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "marshaling json")
|
||||
return nil, ctxerr.Wrap(ctx, err, "marshaling json")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -132,7 +133,7 @@ func (c *Client) doContextWithHeaders(ctx context.Context, verb, path, rawQuery
|
|||
bytes.NewBuffer(bodyBytes),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "creating request object")
|
||||
return nil, ctxerr.Wrap(ctx, err, "creating request object")
|
||||
}
|
||||
for k, v := range headers {
|
||||
request.Header.Set(k, v)
|
||||
|
|
@ -140,7 +141,7 @@ func (c *Client) doContextWithHeaders(ctx context.Context, verb, path, rawQuery
|
|||
|
||||
resp, err := c.http.Do(request)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "do request")
|
||||
return nil, ctxerr.Wrap(ctx, err, "do request")
|
||||
}
|
||||
|
||||
if resp.Header.Get(fleet.HeaderLicenseKey) == fleet.HeaderLicenseValueExpired {
|
||||
|
|
@ -238,12 +239,12 @@ func (l *logRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|||
func (c *Client) authenticatedRequestWithQuery(params interface{}, verb string, path string, responseDest interface{}, query string) error {
|
||||
response, err := c.AuthenticatedDo(verb, path, query, params)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "%s %s", verb, path)
|
||||
return fmt.Errorf("%s %s: %w", verb, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"%s %s received status %d %s",
|
||||
verb, path,
|
||||
response.StatusCode,
|
||||
|
|
@ -253,12 +254,12 @@ func (c *Client) authenticatedRequestWithQuery(params interface{}, verb string,
|
|||
|
||||
err = json.NewDecoder(response.Body).Decode(&responseDest)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "decode %s %s response", verb, path)
|
||||
return fmt.Errorf("decode %s %s response: %w", verb, path, err)
|
||||
}
|
||||
|
||||
if e, ok := responseDest.(errorer); ok {
|
||||
if e.error() != nil {
|
||||
return errors.Errorf("%s %s error: %s", verb, path, e.error())
|
||||
return fmt.Errorf("%s %s error: %s", verb, path, e.error())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,22 +2,22 @@ package service
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// ApplyAppConfig sends the application config to be applied to the Fleet instance.
|
||||
func (c *Client) ApplyAppConfig(payload interface{}) error {
|
||||
response, err := c.AuthenticatedDo("PATCH", "/api/v1/fleet/config", "", payload)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "PATCH /api/v1/fleet/config")
|
||||
return fmt.Errorf("PATCH /api/v1/fleet/config: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"apply config received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -27,11 +27,11 @@ func (c *Client) ApplyAppConfig(payload interface{}) error {
|
|||
var responseBody appConfigResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode apply config response")
|
||||
return fmt.Errorf("decode apply config response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("apply config: %s", responseBody.Err)
|
||||
return fmt.Errorf("apply config: %s", responseBody.Err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -40,12 +40,12 @@ func (c *Client) ApplyAppConfig(payload interface{}) error {
|
|||
func (c *Client) GetAppConfig() (*fleet.EnrichedAppConfig, error) {
|
||||
response, err := c.AuthenticatedDo("GET", "/api/v1/fleet/config", "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/config")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/config: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get config received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -55,7 +55,7 @@ func (c *Client) GetAppConfig() (*fleet.EnrichedAppConfig, error) {
|
|||
var responseBody *fleet.EnrichedAppConfig
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get config response")
|
||||
return nil, fmt.Errorf("decode get config response: %w", err)
|
||||
}
|
||||
|
||||
return responseBody, nil
|
||||
|
|
@ -65,12 +65,12 @@ func (c *Client) GetAppConfig() (*fleet.EnrichedAppConfig, error) {
|
|||
func (c *Client) GetEnrollSecretSpec() (*fleet.EnrollSecretSpec, error) {
|
||||
response, err := c.AuthenticatedDo("GET", "/api/v1/fleet/spec/enroll_secret", "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/spec/enroll_secret")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/spec/enroll_secret: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get enroll_secrets received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -80,11 +80,11 @@ func (c *Client) GetEnrollSecretSpec() (*fleet.EnrollSecretSpec, error) {
|
|||
var responseBody getEnrollSecretSpecResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get enroll secret spec response")
|
||||
return nil, fmt.Errorf("decode get enroll secret spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get enroll secret spec: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get enroll secret spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Spec, nil
|
||||
|
|
@ -95,12 +95,12 @@ func (c *Client) ApplyEnrollSecretSpec(spec *fleet.EnrollSecretSpec) error {
|
|||
req := applyEnrollSecretSpecRequest{Spec: spec}
|
||||
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/spec/enroll_secret", "", req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "POST /api/v1/fleet/spec/enroll_secret")
|
||||
return fmt.Errorf("POST /api/v1/fleet/spec/enroll_secret: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"apply enroll secret received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -110,11 +110,11 @@ func (c *Client) ApplyEnrollSecretSpec(spec *fleet.EnrollSecretSpec) error {
|
|||
var responseBody applyEnrollSecretSpecResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode apply enroll secret response")
|
||||
return fmt.Errorf("decode apply enroll secret response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("apply enroll secret: %s", responseBody.Err)
|
||||
return fmt.Errorf("apply enroll secret: %s", responseBody.Err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import (
|
|||
"net/http"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// ListCarves lists the file carving sessions
|
||||
|
|
@ -19,12 +18,12 @@ func (c *Client) ListCarves(opt fleet.CarveListOptions) ([]*fleet.CarveMetadata,
|
|||
}
|
||||
response, err := c.AuthenticatedDo("GET", endpoint, rawQuery, nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/carves")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/carves: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"list carves received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -34,10 +33,10 @@ func (c *Client) ListCarves(opt fleet.CarveListOptions) ([]*fleet.CarveMetadata,
|
|||
var responseBody listCarvesResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get carves response")
|
||||
return nil, fmt.Errorf("decode get carves response: %w", err)
|
||||
}
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get carves: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get carves: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
carves := []*fleet.CarveMetadata{}
|
||||
|
|
@ -53,12 +52,12 @@ func (c *Client) GetCarve(carveId int64) (*fleet.CarveMetadata, error) {
|
|||
endpoint := fmt.Sprintf("/api/v1/fleet/carves/%d", carveId)
|
||||
response, err := c.AuthenticatedDo("GET", endpoint, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET "+endpoint)
|
||||
return nil, fmt.Errorf("GET "+endpoint+": %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get carve received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -67,10 +66,10 @@ func (c *Client) GetCarve(carveId int64) (*fleet.CarveMetadata, error) {
|
|||
var responseBody getCarveResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode carve response")
|
||||
return nil, fmt.Errorf("decode carve response: %w", err)
|
||||
}
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get carve: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get carve: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return &responseBody.Carve, nil
|
||||
|
|
@ -84,12 +83,12 @@ func (c *Client) getCarveBlock(carveId, blockId int64) ([]byte, error) {
|
|||
)
|
||||
response, err := c.AuthenticatedDo("GET", path, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "GET %s", path)
|
||||
return nil, fmt.Errorf("GET %s: %w", path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get carve block received status %d: %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -99,10 +98,10 @@ func (c *Client) getCarveBlock(carveId, blockId int64) ([]byte, error) {
|
|||
var responseBody getCarveBlockResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get carve block response")
|
||||
return nil, fmt.Errorf("decode get carve block response: %w", err)
|
||||
}
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get carve block: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get carve block: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Data, nil
|
||||
|
|
@ -139,7 +138,7 @@ func (r *carveReader) Read(p []byte) (n int, err error) {
|
|||
var err error
|
||||
r.buffer, err = r.client.getCarveBlock(r.carve.ID, r.curBlock)
|
||||
if err != nil {
|
||||
return 0, errors.Wrapf(err, "get block %d", r.curBlock)
|
||||
return 0, fmt.Errorf("get block %d: %w", r.curBlock, err)
|
||||
}
|
||||
r.curBlock++
|
||||
}
|
||||
|
|
@ -164,12 +163,12 @@ func (c *Client) DownloadCarve(id int64) (io.Reader, error) {
|
|||
path := fmt.Sprintf("/api/v1/fleet/carves/%d", id)
|
||||
response, err := c.AuthenticatedDo("GET", path, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "GET %s", path)
|
||||
return nil, fmt.Errorf("GET %s: %w", path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"download carve received status %d: %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -179,10 +178,10 @@ func (c *Client) DownloadCarve(id int64) (io.Reader, error) {
|
|||
var responseBody getCarveResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get carve by name response")
|
||||
return nil, fmt.Errorf("decode get carve by name response: %w", err)
|
||||
}
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get carve by name: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get carve by name: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
reader := newCarveReader(responseBody.Carve, c)
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// DebugPprof calls the /debug/pprof/ endpoints.
|
||||
|
|
@ -12,12 +11,12 @@ func (c *Client) DebugPprof(name string) ([]byte, error) {
|
|||
endpoint := "/debug/pprof/" + name
|
||||
response, err := c.AuthenticatedDo("GET", endpoint, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "GET %s", endpoint)
|
||||
return nil, fmt.Errorf("GET %s: %w", endpoint, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get pprof received status %d",
|
||||
response.StatusCode,
|
||||
)
|
||||
|
|
@ -25,7 +24,7 @@ func (c *Client) DebugPprof(name string) ([]byte, error) {
|
|||
|
||||
body, err := ioutil.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "read pprof response body")
|
||||
return nil, fmt.Errorf("read pprof response body: %w", err)
|
||||
}
|
||||
|
||||
return body, nil
|
||||
|
|
|
|||
|
|
@ -7,19 +7,18 @@ import (
|
|||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/ptr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// GetHosts retrieves the list of all Hosts
|
||||
func (c *Client) GetHosts(query string) ([]HostResponse, error) {
|
||||
response, err := c.AuthenticatedDo("GET", "/api/v1/fleet/hosts", query, nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/hosts")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/hosts: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get hosts received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -28,10 +27,10 @@ func (c *Client) GetHosts(query string) ([]HostResponse, error) {
|
|||
var responseBody listHostsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode list hosts response")
|
||||
return nil, fmt.Errorf("decode list hosts response: %w", err)
|
||||
}
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("list hosts: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("list hosts: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Hosts, nil
|
||||
|
|
@ -42,12 +41,12 @@ func (c *Client) GetHosts(query string) ([]HostResponse, error) {
|
|||
func (c *Client) HostByIdentifier(identifier string) (*HostDetailResponse, error) {
|
||||
response, err := c.AuthenticatedDo("GET", "/api/v1/fleet/hosts/identifier/"+identifier, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/hosts/identifier")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/hosts/identifier: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get host by identifier received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -56,10 +55,10 @@ func (c *Client) HostByIdentifier(identifier string) (*HostDetailResponse, error
|
|||
var responseBody getHostResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode host response")
|
||||
return nil, fmt.Errorf("decode host response: %w", err)
|
||||
}
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get host by identifier: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get host by identifier: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Host, nil
|
||||
|
|
@ -71,7 +70,7 @@ func (c *Client) DeleteHost(id uint) error {
|
|||
path := fmt.Sprintf("/api/v1/fleet/hosts/%d", id)
|
||||
response, err := c.AuthenticatedDo(verb, path, "", nil)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "%s %s", verb, path)
|
||||
return fmt.Errorf("%s %s: %w", verb, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -80,7 +79,7 @@ func (c *Client) DeleteHost(id uint) error {
|
|||
return notFoundErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"delete host received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -90,11 +89,11 @@ func (c *Client) DeleteHost(id uint) error {
|
|||
var responseBody deleteHostResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode delete host response")
|
||||
return fmt.Errorf("decode delete host response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("delete host: %s", responseBody.Err)
|
||||
return fmt.Errorf("delete host: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@ package service
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// ApplyLabels sends the list of Labels to be applied (upserted) to the
|
||||
|
|
@ -15,12 +15,12 @@ func (c *Client) ApplyLabels(specs []*fleet.LabelSpec) error {
|
|||
req := applyLabelSpecsRequest{Specs: specs}
|
||||
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/spec/labels", "", req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "POST /api/v1/fleet/spec/labels")
|
||||
return fmt.Errorf("POST /api/v1/fleet/spec/labels: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"apply labels received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -30,11 +30,11 @@ func (c *Client) ApplyLabels(specs []*fleet.LabelSpec) error {
|
|||
var responseBody applyLabelSpecsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode apply label spec response")
|
||||
return fmt.Errorf("decode apply label spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("apply label spec: %s", responseBody.Err)
|
||||
return fmt.Errorf("apply label spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -45,7 +45,7 @@ func (c *Client) GetLabel(name string) (*fleet.LabelSpec, error) {
|
|||
verb, path := "GET", "/api/v1/fleet/spec/labels/"+url.PathEscape(name)
|
||||
response, err := c.AuthenticatedDo(verb, path, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/spec/labels")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/spec/labels: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -54,7 +54,7 @@ func (c *Client) GetLabel(name string) (*fleet.LabelSpec, error) {
|
|||
return nil, notFoundErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get label received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -64,11 +64,11 @@ func (c *Client) GetLabel(name string) (*fleet.LabelSpec, error) {
|
|||
var responseBody getLabelSpecResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get label spec response")
|
||||
return nil, fmt.Errorf("decode get label spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get label spec: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get label spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Spec, nil
|
||||
|
|
@ -78,12 +78,12 @@ func (c *Client) GetLabel(name string) (*fleet.LabelSpec, error) {
|
|||
func (c *Client) GetLabels() ([]*fleet.LabelSpec, error) {
|
||||
response, err := c.AuthenticatedDo("GET", "/api/v1/fleet/spec/labels", "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/spec/labels")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/spec/labels: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get labels received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -93,11 +93,11 @@ func (c *Client) GetLabels() ([]*fleet.LabelSpec, error) {
|
|||
var responseBody getLabelSpecsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get label spec response")
|
||||
return nil, fmt.Errorf("decode get label spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get label spec: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get label spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Specs, nil
|
||||
|
|
@ -108,7 +108,7 @@ func (c *Client) DeleteLabel(name string) error {
|
|||
verb, path := "DELETE", "/api/v1/fleet/labels/"+url.PathEscape(name)
|
||||
response, err := c.AuthenticatedDo(verb, path, "", nil)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "%s %s", verb, path)
|
||||
return fmt.Errorf("%s %s: %w", verb, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -117,7 +117,7 @@ func (c *Client) DeleteLabel(name string) error {
|
|||
return notFoundErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"delete label received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -127,11 +127,11 @@ func (c *Client) DeleteLabel(name string) error {
|
|||
var responseBody deleteLabelResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode get label spec response")
|
||||
return fmt.Errorf("decode get label spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("get label spec: %s", responseBody.Err)
|
||||
return fmt.Errorf("get label spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -4,16 +4,17 @@ import (
|
|||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
|
||||
ws "github.com/fleetdm/fleet/v4/server/websocket"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// LiveQueryResultsHandler provides access to all of the information about an
|
||||
|
|
@ -72,12 +73,13 @@ func (c *Client) LiveQueryWithContext(ctx context.Context, query string, labels
|
|||
}
|
||||
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/queries/run_by_names", "", req)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "POST /api/v1/fleet/queries/run_by_names")
|
||||
return nil, ctxerr.Wrap(ctx, err, "POST /api/v1/fleet/queries/run_by_names")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, ctxerr.Errorf(
|
||||
ctx,
|
||||
"create live query received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -87,10 +89,10 @@ func (c *Client) LiveQueryWithContext(ctx context.Context, query string, labels
|
|||
var responseBody createDistributedQueryCampaignResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode create live query response")
|
||||
return nil, ctxerr.Wrap(ctx, err, "decode create live query response")
|
||||
}
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("create live query: %s", responseBody.Err)
|
||||
return nil, ctxerr.Errorf(ctx, "create live query: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
// Copy default dialer but skip cert verification if set.
|
||||
|
|
@ -108,7 +110,7 @@ func (c *Client) LiveQueryWithContext(ctx context.Context, query string, labels
|
|||
wssURL.Path = c.urlPrefix + "/api/v1/fleet/results/websocket"
|
||||
conn, _, err := dialer.Dial(wssURL.String(), nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "upgrade live query result websocket")
|
||||
return nil, ctxerr.Wrap(ctx, err, "upgrade live query result websocket")
|
||||
}
|
||||
// Cannot defer connection closing here because we need it to remain
|
||||
// open for the goroutine below. Manually close for the couple of error
|
||||
|
|
@ -120,7 +122,7 @@ func (c *Client) LiveQueryWithContext(ctx context.Context, query string, labels
|
|||
})
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, errors.Wrap(err, "auth for results")
|
||||
return nil, ctxerr.Wrap(ctx, err, "auth for results")
|
||||
}
|
||||
|
||||
err = conn.WriteJSON(ws.JSONMessage{
|
||||
|
|
@ -129,7 +131,7 @@ func (c *Client) LiveQueryWithContext(ctx context.Context, query string, labels
|
|||
})
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, errors.Wrap(err, "selecting results")
|
||||
return nil, ctxerr.Wrap(ctx, err, "selecting results")
|
||||
}
|
||||
|
||||
resHandler := NewLiveQueryResultsHandler()
|
||||
|
|
@ -152,7 +154,7 @@ func (c *Client) LiveQueryWithContext(ctx context.Context, query string, labels
|
|||
return
|
||||
case err := <-doneReadingChan:
|
||||
if err != nil {
|
||||
resHandler.errors <- errors.Wrap(err, "receive ws message")
|
||||
resHandler.errors <- ctxerr.Wrap(ctx, err, "receive ws message")
|
||||
if errors.Is(err, websocket.ErrCloseSent) {
|
||||
return
|
||||
}
|
||||
|
|
@ -164,26 +166,26 @@ func (c *Client) LiveQueryWithContext(ctx context.Context, query string, labels
|
|||
case "result":
|
||||
var res fleet.DistributedQueryResult
|
||||
if err := json.Unmarshal(msg.Data, &res); err != nil {
|
||||
resHandler.errors <- errors.Wrap(err, "unmarshal results")
|
||||
resHandler.errors <- ctxerr.Wrap(ctx, err, "unmarshal results")
|
||||
}
|
||||
resHandler.results <- res
|
||||
|
||||
case "totals":
|
||||
var totals targetTotals
|
||||
if err := json.Unmarshal(msg.Data, &totals); err != nil {
|
||||
resHandler.errors <- errors.Wrap(err, "unmarshal totals")
|
||||
resHandler.errors <- ctxerr.Wrap(ctx, err, "unmarshal totals")
|
||||
}
|
||||
resHandler.totals.Store(&totals)
|
||||
|
||||
case "status":
|
||||
var status campaignStatus
|
||||
if err := json.Unmarshal(msg.Data, &status); err != nil {
|
||||
resHandler.errors <- errors.Wrap(err, "unmarshal status")
|
||||
resHandler.errors <- ctxerr.Wrap(ctx, err, "unmarshal status")
|
||||
}
|
||||
resHandler.status.Store(&status)
|
||||
|
||||
default:
|
||||
resHandler.errors <- errors.Errorf("unknown msg type %s", msg.Type)
|
||||
resHandler.errors <- ctxerr.Errorf(ctx, "unknown msg type %s", msg.Type)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@ package service
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// ApplyPacks sends the list of Packs to be applied (upserted) to the
|
||||
|
|
@ -15,12 +15,12 @@ func (c *Client) ApplyPacks(specs []*fleet.PackSpec) error {
|
|||
req := applyPackSpecsRequest{Specs: specs}
|
||||
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/spec/packs", "", req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "POST /api/v1/fleet/spec/packs")
|
||||
return fmt.Errorf("POST /api/v1/fleet/spec/packs: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"apply packs received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -30,11 +30,11 @@ func (c *Client) ApplyPacks(specs []*fleet.PackSpec) error {
|
|||
var responseBody applyPackSpecsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode apply pack spec response")
|
||||
return fmt.Errorf("decode apply pack spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("apply pack spec: %s", responseBody.Err)
|
||||
return fmt.Errorf("apply pack spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -45,7 +45,7 @@ func (c *Client) GetPack(name string) (*fleet.PackSpec, error) {
|
|||
verb, path := "GET", "/api/v1/fleet/spec/packs/"+url.PathEscape(name)
|
||||
response, err := c.AuthenticatedDo(verb, path, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/spec/packs")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/spec/packs: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -54,7 +54,7 @@ func (c *Client) GetPack(name string) (*fleet.PackSpec, error) {
|
|||
return nil, notFoundErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get pack received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -64,11 +64,11 @@ func (c *Client) GetPack(name string) (*fleet.PackSpec, error) {
|
|||
var responseBody getPackSpecResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get pack spec response")
|
||||
return nil, fmt.Errorf("decode get pack spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get pack spec: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get pack spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Spec, nil
|
||||
|
|
@ -78,12 +78,12 @@ func (c *Client) GetPack(name string) (*fleet.PackSpec, error) {
|
|||
func (c *Client) GetPacks() ([]*fleet.PackSpec, error) {
|
||||
response, err := c.AuthenticatedDo("GET", "/api/v1/fleet/spec/packs", "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/spec/packs")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/spec/packs: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get packs received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -93,11 +93,11 @@ func (c *Client) GetPacks() ([]*fleet.PackSpec, error) {
|
|||
var responseBody getPackSpecsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get pack spec response")
|
||||
return nil, fmt.Errorf("decode get pack spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get pack spec: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get pack spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Specs, nil
|
||||
|
|
@ -108,7 +108,7 @@ func (c *Client) DeletePack(name string) error {
|
|||
verb, path := "DELETE", "/api/v1/fleet/packs/"+url.PathEscape(name)
|
||||
response, err := c.AuthenticatedDo(verb, path, "", nil)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "%s %s", verb, path)
|
||||
return fmt.Errorf("%s %s: %w", verb, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -117,7 +117,7 @@ func (c *Client) DeletePack(name string) error {
|
|||
return notFoundErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"delete pack received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -127,11 +127,11 @@ func (c *Client) DeletePack(name string) error {
|
|||
var responseBody deletePackResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode get pack spec response")
|
||||
return fmt.Errorf("decode get pack spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("get pack spec: %s", responseBody.Err)
|
||||
return fmt.Errorf("get pack spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@ package service
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// ApplyQueries sends the list of Queries to be applied (upserted) to the
|
||||
|
|
@ -15,12 +15,12 @@ func (c *Client) ApplyQueries(specs []*fleet.QuerySpec) error {
|
|||
req := applyQuerySpecsRequest{Specs: specs}
|
||||
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/spec/queries", "", req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "POST /api/v1/fleet/spec/queries")
|
||||
return fmt.Errorf("POST /api/v1/fleet/spec/queries: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"apply queries received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -30,11 +30,11 @@ func (c *Client) ApplyQueries(specs []*fleet.QuerySpec) error {
|
|||
var responseBody applyQuerySpecsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode apply query spec response")
|
||||
return fmt.Errorf("decode apply query spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("apply query spec: %s", responseBody.Err)
|
||||
return fmt.Errorf("apply query spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -45,7 +45,7 @@ func (c *Client) GetQuery(name string) (*fleet.QuerySpec, error) {
|
|||
verb, path := "GET", "/api/v1/fleet/spec/queries/"+url.PathEscape(name)
|
||||
response, err := c.AuthenticatedDo(verb, path, "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "%s %s", verb, path)
|
||||
return nil, fmt.Errorf("%s %s: %w", verb, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -54,7 +54,7 @@ func (c *Client) GetQuery(name string) (*fleet.QuerySpec, error) {
|
|||
return nil, notFoundErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get query received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -64,11 +64,11 @@ func (c *Client) GetQuery(name string) (*fleet.QuerySpec, error) {
|
|||
var responseBody getQuerySpecResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get query spec response")
|
||||
return nil, fmt.Errorf("decode get query spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get query spec: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get query spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Spec, nil
|
||||
|
|
@ -78,12 +78,12 @@ func (c *Client) GetQuery(name string) (*fleet.QuerySpec, error) {
|
|||
func (c *Client) GetQueries() ([]*fleet.QuerySpec, error) {
|
||||
response, err := c.AuthenticatedDo("GET", "/api/v1/fleet/spec/queries", "", nil)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "GET /api/v1/fleet/spec/queries")
|
||||
return nil, fmt.Errorf("GET /api/v1/fleet/spec/queries: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"get queries received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -93,11 +93,11 @@ func (c *Client) GetQueries() ([]*fleet.QuerySpec, error) {
|
|||
var responseBody getQuerySpecsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode get query spec response")
|
||||
return nil, fmt.Errorf("decode get query spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("get query spec: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("get query spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Specs, nil
|
||||
|
|
@ -108,7 +108,7 @@ func (c *Client) DeleteQuery(name string) error {
|
|||
verb, path := "DELETE", "/api/v1/fleet/queries/"+url.PathEscape(name)
|
||||
response, err := c.AuthenticatedDo(verb, path, "", nil)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "%s %s", verb, path)
|
||||
return fmt.Errorf("%s %s: %w", verb, path, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -117,7 +117,7 @@ func (c *Client) DeleteQuery(name string) error {
|
|||
return notFoundErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"delete query received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -127,11 +127,11 @@ func (c *Client) DeleteQuery(name string) error {
|
|||
var responseBody deleteQueryResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode get query spec response")
|
||||
return fmt.Errorf("decode get query spec response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("get query spec: %s", responseBody.Err)
|
||||
return fmt.Errorf("get query spec: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,9 +2,8 @@ package service
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Login attempts to login to the current Fleet instance. If login is successful,
|
||||
|
|
@ -17,7 +16,7 @@ func (c *Client) Login(email, password string) (string, error) {
|
|||
|
||||
response, err := c.Do("POST", "/api/v1/fleet/login", "", params)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "POST /api/v1/fleet/login")
|
||||
return "", fmt.Errorf("POST /api/v1/fleet/login: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -26,7 +25,7 @@ func (c *Client) Login(email, password string) (string, error) {
|
|||
return "", notSetupErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", errors.Errorf(
|
||||
return "", fmt.Errorf(
|
||||
"login received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -36,11 +35,11 @@ func (c *Client) Login(email, password string) (string, error) {
|
|||
var responseBody loginResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "decode login response")
|
||||
return "", fmt.Errorf("decode login response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return "", errors.Errorf("login: %s", responseBody.Err)
|
||||
return "", fmt.Errorf("login: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return responseBody.Token, nil
|
||||
|
|
@ -50,12 +49,12 @@ func (c *Client) Login(email, password string) (string, error) {
|
|||
func (c *Client) Logout() error {
|
||||
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/logout", "", nil)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "POST /api/v1/fleet/logout")
|
||||
return fmt.Errorf("POST /api/v1/fleet/logout: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.Errorf(
|
||||
return fmt.Errorf(
|
||||
"logout received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -65,11 +64,11 @@ func (c *Client) Logout() error {
|
|||
var responseBody logoutResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "decode logout response")
|
||||
return fmt.Errorf("decode logout response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return errors.Errorf("logout: %s", responseBody.Err)
|
||||
return fmt.Errorf("logout: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@ package service
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Setup attempts to setup the current Fleet instance. If setup is successful,
|
||||
|
|
@ -25,7 +25,7 @@ func (c *Client) Setup(email, name, password, org string) (string, error) {
|
|||
|
||||
response, err := c.Do("POST", "/api/v1/setup", "", params)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "POST /api/v1/setup")
|
||||
return "", fmt.Errorf("POST /api/v1/setup: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ func (c *Client) Setup(email, name, password, org string) (string, error) {
|
|||
return "", setupAlreadyErr{}
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", errors.Errorf(
|
||||
return "", fmt.Errorf(
|
||||
"setup received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -43,17 +43,17 @@ func (c *Client) Setup(email, name, password, org string) (string, error) {
|
|||
}
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", errors.Errorf("setup got HTTP %d, expected 200", response.StatusCode)
|
||||
return "", fmt.Errorf("setup got HTTP %d, expected 200", response.StatusCode)
|
||||
}
|
||||
|
||||
var responseBody setupResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "decode setup response")
|
||||
return "", fmt.Errorf("decode setup response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return "", errors.Errorf("setup: %s", responseBody.Err)
|
||||
return "", fmt.Errorf("setup: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
return *responseBody.Token, nil
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@ package service
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// SearchTargets searches for the supplied targets in the Fleet instance.
|
||||
|
|
@ -21,12 +21,12 @@ func (c *Client) SearchTargets(query string, hostIDs, labelIDs []uint) (*fleet.T
|
|||
|
||||
response, err := c.AuthenticatedDo("POST", "/api/v1/fleet/targets", "", req)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "POST /api/v1/fleet/targets")
|
||||
return nil, fmt.Errorf("POST /api/v1/fleet/targets: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, errors.Errorf(
|
||||
return nil, fmt.Errorf(
|
||||
"SearchTargets received status %d %s",
|
||||
response.StatusCode,
|
||||
extractServerErrorText(response.Body),
|
||||
|
|
@ -36,11 +36,11 @@ func (c *Client) SearchTargets(query string, hostIDs, labelIDs []uint) (*fleet.T
|
|||
var responseBody searchTargetsResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&responseBody)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "decode SearchTargets response")
|
||||
return nil, fmt.Errorf("decode SearchTargets response: %w", err)
|
||||
}
|
||||
|
||||
if responseBody.Err != nil {
|
||||
return nil, errors.Errorf("SearchTargets: %s", responseBody.Err)
|
||||
return nil, fmt.Errorf("SearchTargets: %s", responseBody.Err)
|
||||
}
|
||||
|
||||
hosts := make([]*fleet.Host, len(responseBody.Targets.Hosts))
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// CreateUser creates a new user, skipping the invitation process.
|
||||
|
|
|
|||
|
|
@ -2,13 +2,13 @@ package service
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/config"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -3,13 +3,13 @@ package service
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/logging"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
hostctx "github.com/fleetdm/fleet/v4/server/contexts/host"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/token"
|
||||
|
|
@ -20,7 +20,7 @@ import (
|
|||
func logJSON(logger log.Logger, v interface{}, key string) {
|
||||
jsonV, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
level.Debug(logger).Log("err", errors.Wrapf(err, "marshaling %s for debug", key))
|
||||
level.Debug(logger).Log("err", fmt.Errorf("marshaling %s for debug: %w", key, err))
|
||||
return
|
||||
}
|
||||
level.Debug(logger).Log(key, string(jsonV))
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package service
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -10,7 +11,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/mock"
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -3,10 +3,10 @@ package service
|
|||
import (
|
||||
"context"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/ptr"
|
||||
"github.com/go-kit/kit/endpoint"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type setupRequest struct {
|
||||
|
|
@ -43,18 +43,18 @@ func makeSetupEndpoint(svc fleet.Service) endpoint.Endpoint {
|
|||
}
|
||||
|
||||
if req.Admin == nil {
|
||||
return setupResponse{Err: errors.New("setup request must provide admin")}, nil
|
||||
return setupResponse{Err: ctxerr.New(ctx, "setup request must provide admin")}, nil
|
||||
}
|
||||
|
||||
// creating the user should be the last action. If there's a user
|
||||
// present and other errors occur, the setup endpoint closes.
|
||||
adminPayload := *req.Admin
|
||||
if adminPayload.Email == nil || *adminPayload.Email == "" {
|
||||
err := errors.Errorf("admin email cannot be empty")
|
||||
err := ctxerr.New(ctx, "admin email cannot be empty")
|
||||
return setupResponse{Err: err}, nil
|
||||
}
|
||||
if adminPayload.Password == nil || *adminPayload.Password == "" {
|
||||
err := errors.Errorf("admin password cannot be empty")
|
||||
err := ctxerr.New(ctx, "admin password cannot be empty")
|
||||
return setupResponse{Err: err}, nil
|
||||
}
|
||||
// Make the user an admin
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
|
@ -14,7 +15,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
kithttp "github.com/go-kit/kit/transport/http"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type handlerFunc func(ctx context.Context, request interface{}, svc fleet.Service) (interface{}, error)
|
||||
|
|
@ -24,13 +24,13 @@ func parseTag(tag string) (string, bool, error) {
|
|||
parts := strings.Split(tag, ",")
|
||||
switch len(parts) {
|
||||
case 0:
|
||||
return "", false, errors.Errorf("Error parsing %s: too few parts", tag)
|
||||
return "", false, fmt.Errorf("Error parsing %s: too few parts", tag)
|
||||
case 1:
|
||||
return tag, false, nil
|
||||
case 2:
|
||||
return parts[0], parts[1] == "optional", nil
|
||||
default:
|
||||
return "", false, errors.Errorf("Error parsing %s: too many parts", tag)
|
||||
return "", false, fmt.Errorf("Error parsing %s: too many parts", tag)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -153,7 +153,7 @@ func makeDecoder(iface interface{}) kithttp.DecodeRequestFunc {
|
|||
if optional {
|
||||
continue
|
||||
}
|
||||
return nil, errors.Errorf("Param %s is required", f.Name)
|
||||
return nil, fmt.Errorf("Param %s is required", f.Name)
|
||||
}
|
||||
if field.Kind() == reflect.Ptr {
|
||||
// create the new instance of whatever it is
|
||||
|
|
@ -166,7 +166,7 @@ func makeDecoder(iface interface{}) kithttp.DecodeRequestFunc {
|
|||
case reflect.Uint:
|
||||
queryValUint, err := strconv.Atoi(queryVal)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "parsing uint from query")
|
||||
return nil, fmt.Errorf("parsing uint from query: %w", err)
|
||||
}
|
||||
field.SetUint(uint64(queryValUint))
|
||||
case reflect.Bool:
|
||||
|
|
@ -189,12 +189,12 @@ func makeDecoder(iface interface{}) kithttp.DecodeRequestFunc {
|
|||
default:
|
||||
queryValInt, err = strconv.Atoi(queryVal)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "parsing uint from query")
|
||||
return nil, fmt.Errorf("parsing uint from query: %w", err)
|
||||
}
|
||||
}
|
||||
field.SetInt(int64(queryValInt))
|
||||
default:
|
||||
return nil, errors.Errorf("Cant handle type for field %s %s", f.Name, field.Kind())
|
||||
return nil, fmt.Errorf("Cant handle type for field %s %s", f.Name, field.Kind())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ package service
|
|||
import (
|
||||
"context"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////
|
||||
|
|
@ -165,7 +165,7 @@ func (svc Service) ApplyPolicySpecs(ctx context.Context, policies []*fleet.Polic
|
|||
if policy.Team != "" {
|
||||
team, err := svc.ds.TeamByName(ctx, policy.Team)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "getting team by name")
|
||||
return ctxerr.Wrap(ctx, err, "getting team by name")
|
||||
}
|
||||
if err := svc.authz.Authorize(ctx, &fleet.Policy{TeamID: &team.ID}, fleet.ActionWrite); err != nil {
|
||||
return err
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package service
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
|
|
@ -15,7 +16,6 @@ import (
|
|||
"github.com/go-kit/kit/log/level"
|
||||
kithttp "github.com/go-kit/kit/transport/http"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/throttled/throttled/v2"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/mock"
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/throttled/throttled/v2/store/memstore"
|
||||
|
|
@ -228,13 +227,13 @@ func TestAPIRoutesConflicts(t *testing.T) {
|
|||
path, err := route.GetPathTemplate()
|
||||
if err != nil {
|
||||
// all our routes should have paths
|
||||
return errors.Wrap(err, name)
|
||||
return fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
meths, err := route.GetMethods()
|
||||
if err != nil || len(meths) == 0 {
|
||||
// only route without method is distributed_query_results (websocket)
|
||||
if name != "distributed_query_results" {
|
||||
return errors.Wrap(err, name+" "+path)
|
||||
return fmt.Errorf(name+" "+path+": %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ package service
|
|||
import (
|
||||
"context"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
|
@ -197,7 +197,7 @@ func (svc Service) checkWriteForHostIDs(ctx context.Context, ids []uint) error {
|
|||
for _, id := range ids {
|
||||
host, err := svc.ds.Host(ctx, id, false)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "get host for delete")
|
||||
return ctxerr.Wrap(ctx, err, "get host for delete")
|
||||
}
|
||||
|
||||
// Authorize again with team loaded now that we have team_id
|
||||
|
|
|
|||
|
|
@ -120,7 +120,8 @@ func (s *integrationLoggerTestSuite) TestOsqueryEndpointsLogErrors() {
|
|||
require.Nil(t, err)
|
||||
|
||||
logString := s.buf.String()
|
||||
assert.Equal(t, `{"err":"decoding JSON: invalid character '}' looking for beginning of value","level":"info","path":"/api/v1/osquery/log"}
|
||||
assert.Contains(t, logString, `{"err":"decoding JSON:`)
|
||||
assert.Contains(t, logString, `invalid character '}' looking for beginning of value","level":"info","path":"/api/v1/osquery/log"}
|
||||
`, logString)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,10 +8,10 @@ import (
|
|||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/logging"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/ptr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type runLiveQueryRequest struct {
|
||||
|
|
@ -147,7 +147,7 @@ func (svc *Service) GetCampaignReader(ctx context.Context, campaign *fleet.Distr
|
|||
campaign.Status = fleet.QueryRunning
|
||||
if err := svc.ds.SaveDistributedQueryCampaign(ctx, campaign); err != nil {
|
||||
cancelFunc()
|
||||
return nil, nil, errors.Wrap(err, "error saving campaign state")
|
||||
return nil, nil, ctxerr.Wrap(ctx, err, "error saving campaign state")
|
||||
}
|
||||
|
||||
return readChan, cancelFunc, nil
|
||||
|
|
@ -157,11 +157,11 @@ func (svc *Service) CompleteCampaign(ctx context.Context, campaign *fleet.Distri
|
|||
campaign.Status = fleet.QueryComplete
|
||||
err := svc.ds.SaveDistributedQueryCampaign(ctx, campaign)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "saving distributed campaign after complete")
|
||||
return ctxerr.Wrap(ctx, err, "saving distributed campaign after complete")
|
||||
}
|
||||
err = svc.liveQueryStore.StopQuery(strconv.Itoa(int(campaign.ID)))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "stopping query after after complete")
|
||||
return ctxerr.Wrap(ctx, err, "stopping query after after complete")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,8 +7,8 @@ import (
|
|||
"reflect"
|
||||
"runtime"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/go-kit/kit/endpoint"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/throttled/throttled/v2"
|
||||
)
|
||||
|
||||
|
|
@ -42,10 +42,10 @@ func (m *Middleware) Limit(quota throttled.RateQuota) endpoint.Middleware {
|
|||
return func(ctx context.Context, req interface{}) (response interface{}, err error) {
|
||||
limited, result, err := limiter.RateLimit(funcName, 1)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "check rate limit")
|
||||
return nil, ctxerr.Wrap(ctx, err, "check rate limit")
|
||||
}
|
||||
if limited {
|
||||
return nil, &ratelimitError{result: result}
|
||||
return nil, ctxerr.Wrap(ctx, &ratelimitError{result: result})
|
||||
}
|
||||
|
||||
return next(ctx, req)
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package ratelimit
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -28,5 +29,6 @@ func TestLimit(t *testing.T) {
|
|||
// Hits rate limit
|
||||
_, err = wrapped(context.Background(), struct{}{})
|
||||
assert.Error(t, err)
|
||||
assert.Implements(t, (*Error)(nil), err)
|
||||
var rle Error
|
||||
assert.True(t, errors.As(err, &rle))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/go-kit/kit/log"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
|
|
@ -149,7 +148,7 @@ var detailQueries = map[string]DetailQuery{
|
|||
case "distributed_interval":
|
||||
interval, err := strconv.Atoi(EmptyToZero(row["value"]))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "parsing distributed_interval")
|
||||
return fmt.Errorf("parsing distributed_interval: %w", err)
|
||||
}
|
||||
host.DistributedInterval = uint(interval)
|
||||
|
||||
|
|
@ -158,7 +157,7 @@ var detailQueries = map[string]DetailQuery{
|
|||
// called `config_tls_refresh`.
|
||||
interval, err := strconv.Atoi(EmptyToZero(row["value"]))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "parsing config_tls_refresh")
|
||||
return fmt.Errorf("parsing config_tls_refresh: %w", err)
|
||||
}
|
||||
configTLSRefresh = uint(interval)
|
||||
configTLSRefreshSeen = true
|
||||
|
|
@ -168,7 +167,7 @@ var detailQueries = map[string]DetailQuery{
|
|||
// aliased to `config_refresh`.
|
||||
interval, err := strconv.Atoi(EmptyToZero(row["value"]))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "parsing config_refresh")
|
||||
return fmt.Errorf("parsing config_refresh: %w", err)
|
||||
}
|
||||
configRefresh = uint(interval)
|
||||
configRefreshSeen = true
|
||||
|
|
@ -176,7 +175,7 @@ var detailQueries = map[string]DetailQuery{
|
|||
case "logger_tls_period":
|
||||
interval, err := strconv.Atoi(EmptyToZero(row["value"]))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "parsing logger_tls_period")
|
||||
return fmt.Errorf("parsing logger_tls_period: %w", err)
|
||||
}
|
||||
host.LoggerTLSPeriod = uint(interval)
|
||||
}
|
||||
|
|
@ -338,16 +337,16 @@ var detailQueries = map[string]DetailQuery{
|
|||
},
|
||||
"disk_space_unix": {
|
||||
Query: `
|
||||
SELECT (blocks_available * 100 / blocks) AS percent_disk_space_available,
|
||||
round((blocks_available * blocks_size *10e-10),2) AS gigs_disk_space_available
|
||||
SELECT (blocks_available * 100 / blocks) AS percent_disk_space_available,
|
||||
round((blocks_available * blocks_size *10e-10),2) AS gigs_disk_space_available
|
||||
FROM mounts WHERE path = '/' LIMIT 1;`,
|
||||
Platforms: []string{"darwin", "linux", "rhel", "ubuntu", "centos"},
|
||||
IngestFunc: ingestDiskSpace,
|
||||
},
|
||||
"disk_space_windows": {
|
||||
Query: `
|
||||
SELECT ROUND((sum(free_space) * 100 * 10e-10) / (sum(size) * 10e-10)) AS percent_disk_space_available,
|
||||
ROUND(sum(free_space) * 10e-10) AS gigs_disk_space_available
|
||||
SELECT ROUND((sum(free_space) * 100 * 10e-10) / (sum(size) * 10e-10)) AS percent_disk_space_available,
|
||||
ROUND(sum(free_space) * 10e-10) AS gigs_disk_space_available
|
||||
FROM logical_drives WHERE file_system = 'NTFS' LIMIT 1;`,
|
||||
Platforms: []string{"windows"},
|
||||
IngestFunc: ingestDiskSpace,
|
||||
|
|
@ -525,7 +524,7 @@ var usersQuery = DetailQuery{
|
|||
for _, row := range rows {
|
||||
uid, err := strconv.Atoi(row["uid"])
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "converting uid %s to int", row["uid"])
|
||||
return fmt.Errorf("converting uid %s to int: %w", row["uid"], err)
|
||||
}
|
||||
username := row["username"]
|
||||
type_ := row["type"]
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"sync"
|
||||
|
||||
|
|
@ -14,7 +15,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/service/async"
|
||||
"github.com/fleetdm/fleet/v4/server/sso"
|
||||
kitlog "github.com/go-kit/kit/log"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Service is the struct implementing fleet.Service. Create a new one with NewService.
|
||||
|
|
@ -58,7 +58,7 @@ func NewService(
|
|||
|
||||
authorizer, err := authz.NewAuthorizer()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new authorizer")
|
||||
return nil, fmt.Errorf("new authorizer: %w", err)
|
||||
}
|
||||
|
||||
svc = &Service{
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import (
|
|||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (svc *Service) AgentOptionsForHost(ctx context.Context, host *fleet.Host) (json.RawMessage, error) {
|
||||
|
|
@ -13,13 +13,13 @@ func (svc *Service) AgentOptionsForHost(ctx context.Context, host *fleet.Host) (
|
|||
if host.TeamID != nil {
|
||||
team, err := svc.ds.Team(ctx, *host.TeamID)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "load team for host")
|
||||
return nil, ctxerr.Wrap(ctx, err, "load team for host")
|
||||
}
|
||||
|
||||
if team.AgentOptions != nil && len(*team.AgentOptions) > 0 {
|
||||
var options fleet.AgentOptions
|
||||
if err := json.Unmarshal(*team.AgentOptions, &options); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshal team agent options")
|
||||
return nil, ctxerr.Wrap(ctx, err, "unmarshal team agent options")
|
||||
}
|
||||
|
||||
return options.ForPlatform(host.Platform), nil
|
||||
|
|
@ -29,13 +29,13 @@ func (svc *Service) AgentOptionsForHost(ctx context.Context, host *fleet.Host) (
|
|||
// Otherwise return the appropriate override for global options.
|
||||
appConfig, err := svc.ds.AppConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "load global agent options")
|
||||
return nil, ctxerr.Wrap(ctx, err, "load global agent options")
|
||||
}
|
||||
|
||||
var options fleet.AgentOptions
|
||||
if appConfig.AgentOptions != nil {
|
||||
if err := json.Unmarshal(*appConfig.AgentOptions, &options); err != nil {
|
||||
return nil, errors.Wrap(err, "unmarshal global agent options")
|
||||
return nil, ctxerr.Wrap(ctx, err, "unmarshal global agent options")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,11 +9,11 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/fleetdm/fleet/v4/server"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
|
||||
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
|
||||
"github.com/fleetdm/fleet/v4/server/fleet"
|
||||
"github.com/fleetdm/fleet/v4/server/mail"
|
||||
"github.com/kolide/kit/version"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// mailError is set when an error performing mail operations
|
||||
|
|
@ -46,7 +46,7 @@ func (svc *Service) NewAppConfig(ctx context.Context, p fleet.AppConfig) (*fleet
|
|||
// Set up a default enroll secret
|
||||
secret, err := server.GenerateRandomText(fleet.EnrollSecretDefaultLength)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "generate enroll secret string")
|
||||
return nil, ctxerr.Wrap(ctx, err, "generate enroll secret string")
|
||||
}
|
||||
secrets := []*fleet.EnrollSecret{
|
||||
{
|
||||
|
|
@ -55,7 +55,7 @@ func (svc *Service) NewAppConfig(ctx context.Context, p fleet.AppConfig) (*fleet
|
|||
}
|
||||
err = svc.ds.ApplyEnrollSecrets(ctx, nil, secrets)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "save enroll secret")
|
||||
return nil, ctxerr.Wrap(ctx, err, "save enroll secret")
|
||||
}
|
||||
|
||||
return newConfig, nil
|
||||
|
|
@ -134,7 +134,7 @@ func (svc *Service) ApplyEnrollSecretSpec(ctx context.Context, spec *fleet.Enrol
|
|||
|
||||
for _, s := range spec.Secrets {
|
||||
if s.Secret == "" {
|
||||
return errors.New("enroll secret must not be empty")
|
||||
return ctxerr.New(ctx, "enroll secret must not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -258,7 +258,7 @@ func (svc *Service) LoggingConfig(ctx context.Context) (*fleet.Logging, error) {
|
|||
},
|
||||
}
|
||||
default:
|
||||
return nil, errors.Errorf("unrecognized logging plugin: %s", conf.Osquery.StatusLogPlugin)
|
||||
return nil, ctxerr.Errorf(ctx, "unrecognized logging plugin: %s", conf.Osquery.StatusLogPlugin)
|
||||
}
|
||||
|
||||
switch conf.Osquery.ResultLogPlugin {
|
||||
|
|
@ -312,7 +312,7 @@ func (svc *Service) LoggingConfig(ctx context.Context) (*fleet.Logging, error) {
|
|||
},
|
||||
}
|
||||
default:
|
||||
return nil, errors.Errorf("unrecognized logging plugin: %s", conf.Osquery.ResultLogPlugin)
|
||||
return nil, ctxerr.Errorf(ctx, "unrecognized logging plugin: %s", conf.Osquery.ResultLogPlugin)
|
||||
|
||||
}
|
||||
return logging, nil
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ import (
|
|||
"github.com/fleetdm/fleet/v4/server/websocket"
|
||||
"github.com/go-kit/kit/log/level"
|
||||
"github.com/igm/sockjs-go/v3/sockjs"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (svc Service) NewDistributedQueryCampaignByNames(ctx context.Context, queryString string, queryID *uint, hosts []string, labels []string) (*fleet.DistributedQueryCampaign, error) {
|
||||
|
|
@ -27,12 +26,12 @@ func (svc Service) NewDistributedQueryCampaignByNames(ctx context.Context, query
|
|||
|
||||
hostIDs, err := svc.ds.HostIDsByName(ctx, filter, hosts)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "finding host IDs")
|
||||
return nil, ctxerr.Wrap(ctx, err, "finding host IDs")
|
||||
}
|
||||
|
||||
labelIDs, err := svc.ds.LabelIDsByName(ctx, labels)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "finding label IDs")
|
||||
return nil, ctxerr.Wrap(ctx, err, "finding label IDs")
|
||||
}
|
||||
|
||||
targets := fleet.HostTargets{HostIDs: hostIDs, LabelIDs: labelIDs}
|
||||
|
|
@ -77,7 +76,7 @@ func (svc Service) NewDistributedQueryCampaign(ctx context.Context, queryString
|
|||
}
|
||||
query, err = svc.ds.NewQuery(ctx, query)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new query")
|
||||
return nil, ctxerr.Wrap(ctx, err, "new query")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -93,7 +92,7 @@ func (svc Service) NewDistributedQueryCampaign(ctx context.Context, queryString
|
|||
UserID: vc.UserID(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "new campaign")
|
||||
return nil, ctxerr.Wrap(ctx, err, "new campaign")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
|
|
@ -112,7 +111,7 @@ func (svc Service) NewDistributedQueryCampaign(ctx context.Context, queryString
|
|||
TargetID: hid,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "adding host target")
|
||||
return nil, ctxerr.Wrap(ctx, err, "adding host target")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -124,7 +123,7 @@ func (svc Service) NewDistributedQueryCampaign(ctx context.Context, queryString
|
|||
TargetID: lid,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "adding label target")
|
||||
return nil, ctxerr.Wrap(ctx, err, "adding label target")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -136,23 +135,23 @@ func (svc Service) NewDistributedQueryCampaign(ctx context.Context, queryString
|
|||
TargetID: tid,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "adding team target")
|
||||
return nil, ctxerr.Wrap(ctx, err, "adding team target")
|
||||
}
|
||||
}
|
||||
|
||||
hostIDs, err := svc.ds.HostIDsInTargets(ctx, filter, targets)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "get target IDs")
|
||||
return nil, ctxerr.Wrap(ctx, err, "get target IDs")
|
||||
}
|
||||
|
||||
err = svc.liveQueryStore.RunQuery(strconv.Itoa(int(campaign.ID)), queryString, hostIDs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "run query")
|
||||
return nil, ctxerr.Wrap(ctx, err, "run query")
|
||||
}
|
||||
|
||||
campaign.Metrics, err = svc.ds.CountHostsInTargets(ctx, filter, targets, time.Now())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "counting hosts")
|
||||
return nil, ctxerr.Wrap(ctx, err, "counting hosts")
|
||||
}
|
||||
|
||||
if err := svc.ds.NewActivity(
|
||||
|
|
@ -266,9 +265,9 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
|
|||
metrics, err := svc.CountHostsInTargets(ctx, &campaign.QueryID, *targets)
|
||||
if err != nil {
|
||||
if err = conn.WriteJSONError("error retrieving target counts"); err != nil {
|
||||
return errors.Wrap(err, "retrieve target counts, write failed")
|
||||
return ctxerr.Wrap(ctx, err, "retrieve target counts, write failed")
|
||||
}
|
||||
return errors.Wrap(err, "retrieve target counts")
|
||||
return ctxerr.Wrap(ctx, err, "retrieve target counts")
|
||||
}
|
||||
|
||||
totals := targetTotals{
|
||||
|
|
@ -280,7 +279,7 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
|
|||
if lastTotals != totals {
|
||||
lastTotals = totals
|
||||
if err = conn.WriteJSONMessage("totals", totals); err != nil {
|
||||
return errors.Wrap(err, "write totals")
|
||||
return ctxerr.Wrap(ctx, err, "write totals")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -292,7 +291,7 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
|
|||
if lastStatus != status {
|
||||
lastStatus = status
|
||||
if err = conn.WriteJSONMessage("status", status); err != nil {
|
||||
return errors.Wrap(err, "write status")
|
||||
return ctxerr.Wrap(ctx, err, "write status")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue