Exemple #1
0
func (p *swarmProvisioner) NodeForNodeData(nodeData provision.NodeStatusData) (provision.Node, error) {
	client, err := chooseDBSwarmNode()
	if err != nil {
		if errors.Cause(err) == errNoSwarmNode {
			return nil, provision.ErrNodeNotFound
		}
	}
	tasks, err := client.ListTasks(docker.ListTasksOptions{})
	if err != nil {
		return nil, err
	}
	var task *swarm.Task
	for _, unitData := range nodeData.Units {
		task, err = findTaskByContainerId(tasks, unitData.ID)
		if err == nil {
			break
		}
		if _, isNotFound := errors.Cause(err).(*provision.UnitNotFoundError); !isNotFound {
			return nil, err
		}
	}
	if task != nil {
		node, err := client.InspectNode(task.NodeID)
		if err != nil {
			if _, notFound := err.(*docker.NoSuchNode); notFound {
				return nil, provision.ErrNodeNotFound
			}
			return nil, err
		}
		return &swarmNodeWrapper{Node: node, provisioner: p}, nil
	}
	return provision.FindNodeByAddrs(p, nodeData.Addrs)
}
Exemple #2
0
// The TLS KEK and the KEK for the headers should be in sync, and so failing
// to decrypt the TLS key should be mean we won't be able to decrypt the headers.
// However, the TLS Key encryption uses AES-256-CBC (golang as of 1.7.x does not seem
// to support GCM, so no cipher modes with digests) so sometimes decrypting with
// the wrong passphrase will not result in an error.  This means we will ultimately
// have to rely on the header encryption mechanism, which does include a digest, to
// determine if the KEK is valid.
func TestDecryptTLSKeyFalsePositive(t *testing.T) {
	badKey := []byte(`
-----BEGIN EC PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,e7927e79e748233776c03c2eb7275f09
kek-version: 392
raft-dek: CAESMBrzZ0gNVPe3FRs42743q8RtkUBrK1ICQpHWX2vdQ8iqSKt1WoKdFDFD2r28LYAVLxoYQguwHbijMx9k+BALUNBAI3s199S5tvnr

JfGenNvzm++AvsOh+UmcBY+JgI6lnfzaCB68agmlmEZYLYi5tqtAU7gif6VIJpCW
+Pj23Fzkw8sKKOOBeapSC5lp+Cjx9OsCci/R9xrdx+uxnnzKJNxOB/qzqcQfZDMh
id2LxdliFcPEk/Yj5gNGpT0UMFJ4G52enbOwOru46f0=
-----END EC PRIVATE KEY-----
`)

	// not actually a real swarm cert - generated a cert corresponding to the key that expires in 20 years
	matchingCert := []byte(`
-----BEGIN CERTIFICATE-----
MIIB9jCCAZygAwIBAgIRAIdzF3Z9VT2OXbRvEw5cR68wCgYIKoZIzj0EAwIwYDEi
MCAGA1UEChMZbWRwMXU5Z3FoOTV1NXN2MmNodDRrcDB1cTEWMBQGA1UECxMNc3dh
cm0tbWFuYWdlcjEiMCAGA1UEAxMZcXJzYmwza2FqOWhiZWprM2R5aWFlc3FiYTAg
GA8wMDAxMDEwMTAwMDAwMFoXDTM2MTEwODA2MjMwMlowYDEiMCAGA1UEChMZbWRw
MXU5Z3FoOTV1NXN2MmNodDRrcDB1cTEWMBQGA1UECxMNc3dhcm0tbWFuYWdlcjEi
MCAGA1UEAxMZcXJzYmwza2FqOWhiZWprM2R5aWFlc3FiYTBZMBMGByqGSM49AgEG
CCqGSM49AwEHA0IABGOivD25E/zcupRFQdKOKbPHS9Mx7JlUhlWnl0iR0K5VhVIU
XjUHt98GuX6gDjs4yUzEKSGxYPsSYlnG9zQqbQSjNTAzMA4GA1UdDwEB/wQEAwIF
oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMAoGCCqGSM49BAMC
A0gAMEUCIQDWtjg1ITGznQILipaEe70G/NgZAOtFfuPXTVkUl3el+wIgSVOVKB/Q
O0T3aXuZGYNyh//KqAoA3erCmh6HauMz84Y=
-----END CERTIFICATE-----
	`)

	var wrongKEK []byte // empty passphrase doesn't decrypt without errors
	falsePositiveKEK, err := base64.RawStdEncoding.DecodeString("bIQgLAAMoGCrHdjMLVhEVqnYTAM7ZNF2xWMiwtw7AiQ")
	require.NoError(t, err)
	realKEK, err := base64.RawStdEncoding.DecodeString("fDg9YejLnMjU+FpulWR62oJLzVpkD2j7VQuP5xiK9QA")
	require.NoError(t, err)

	tempdir, err := ioutil.TempDir("", "KeyReadWriter-false-positive-decryption")
	require.NoError(t, err)
	defer os.RemoveAll(tempdir)

	path := ca.NewConfigPaths(tempdir)
	require.NoError(t, ioutil.WriteFile(path.Node.Key, badKey, 0600))
	require.NoError(t, ioutil.WriteFile(path.Node.Cert, matchingCert, 0644))

	krw := ca.NewKeyReadWriter(path.Node, wrongKEK, RaftDEKData{})
	_, _, err = krw.Read()
	require.IsType(t, ca.ErrInvalidKEK{}, errors.Cause(err))

	krw = ca.NewKeyReadWriter(path.Node, falsePositiveKEK, RaftDEKData{})
	_, _, err = krw.Read()
	require.Error(t, err)
	require.IsType(t, ca.ErrInvalidKEK{}, errors.Cause(err))

	krw = ca.NewKeyReadWriter(path.Node, realKEK, RaftDEKData{})
	_, _, err = krw.Read()
	require.NoError(t, err)
}
Exemple #3
0
func isErr(err error, expected error) bool {
	err = errors.Cause(err)
	switch pe := err.(type) {
	case nil:
		return false
	case *OpErr:
		err = errors.Cause(pe.Err)
	}
	return err == expected
}
Exemple #4
0
func printErr(name string, err error) {
	fmt.Printf("== %s ==\n", name)
	fmt.Printf("Message: %v\n", err)
	fmt.Printf("Type: %T\n", err)
	fmt.Printf("Original error? %v\n", errors.Cause(err))
	fmt.Printf("Original type? %T\n", errors.Cause(err))
	printStack(err)

	fmt.Println()
}
// ErrorToJSONAPIError returns the JSONAPI representation
// of an error and the HTTP status code that will be associated with it.
// This function knows about the models package and the errors from there
// as well as goa error classes.
func ErrorToJSONAPIError(err error) (app.JSONAPIError, int) {
	cause := errs.Cause(err)
	detail := cause.Error()
	var title, code string
	var statusCode int
	var id *string
	switch cause.(type) {
	case errors.NotFoundError:
		code = ErrorCodeNotFound
		title = "Not found error"
		statusCode = http.StatusNotFound
	case errors.ConversionError:
		code = ErrorCodeConversionError
		title = "Conversion error"
		statusCode = http.StatusBadRequest
	case errors.BadParameterError:
		code = ErrorCodeBadParameter
		title = "Bad parameter error"
		statusCode = http.StatusBadRequest
	case errors.VersionConflictError:
		code = ErrorCodeVersionConflict
		title = "Version conflict error"
		statusCode = http.StatusBadRequest
	case errors.InternalError:
		code = ErrorCodeInternalError
		title = "Internal error"
		statusCode = http.StatusInternalServerError
	default:
		code = ErrorCodeUnknownError
		title = "Unknown error"
		statusCode = http.StatusInternalServerError

		cause := errs.Cause(err)
		if err, ok := cause.(goa.ServiceError); ok {
			statusCode = err.ResponseStatus()
			idStr := err.Token()
			id = &idStr
			title = http.StatusText(statusCode)
		}
		if errResp, ok := cause.(*goa.ErrorResponse); ok {
			code = errResp.Code
			detail = errResp.Detail
		}
	}
	statusCodeStr := strconv.Itoa(statusCode)
	jerr := app.JSONAPIError{
		ID:     id,
		Code:   &code,
		Status: &statusCodeStr,
		Title:  &title,
		Detail: detail,
	}
	return jerr, statusCode
}
Exemple #6
0
func main() {
	fmt.Println("Hello world!")
	err := getError()
	err = errors.Wrap(err, "open failed")
	err = subErr(err)
	err = errors.Wrap(err, "read config failed")

	pp.Println("Cause: ", errors.Cause(err))
	err = errors.Wrap(err, "New message")
	pp.Println("Error: ", err)
	fmt.Printf("[%+v]\n", err)
	fmt.Printf("{%+v}\n", errors.Cause(err))
	fmt.Printf("[%v]\n", err)
}
Exemple #7
0
// New creates a new Cluster instance using provided config.
func New(config Config) (*Cluster, error) {
	root := filepath.Join(config.Root, swarmDirName)
	if err := os.MkdirAll(root, 0700); err != nil {
		return nil, err
	}
	if config.RuntimeRoot == "" {
		config.RuntimeRoot = root
	}
	if err := os.MkdirAll(config.RuntimeRoot, 0700); err != nil {
		return nil, err
	}
	c := &Cluster{
		root:        root,
		config:      config,
		configEvent: make(chan struct{}, 10),
		runtimeRoot: config.RuntimeRoot,
		attachers:   make(map[string]*attacher),
	}

	nodeConfig, err := c.loadState()
	if err != nil {
		if os.IsNotExist(err) {
			return c, nil
		}
		return nil, err
	}

	n, err := c.startNewNode(*nodeConfig)
	if err != nil {
		return nil, err
	}

	select {
	case <-time.After(swarmConnectTimeout):
		logrus.Error("swarm component could not be started before timeout was reached")
	case <-n.Ready():
	case <-n.done:
		if errors.Cause(c.err) == ErrSwarmLocked {
			return c, nil
		}
		if err, ok := errors.Cause(c.err).(x509.CertificateInvalidError); ok && err.Reason == x509.Expired {
			c.err = ErrSwarmCertificatesExpired
			return c, nil
		}
		return nil, fmt.Errorf("swarm component could not be started: %v", c.err)
	}
	go c.reconnectOnFailure(n)
	return c, nil
}
Exemple #8
0
// New creates a new Cluster instance using provided config.
func New(config Config) (*Cluster, error) {
	root := filepath.Join(config.Root, swarmDirName)
	if err := os.MkdirAll(root, 0700); err != nil {
		return nil, err
	}
	if config.RuntimeRoot == "" {
		config.RuntimeRoot = root
	}
	if err := os.MkdirAll(config.RuntimeRoot, 0700); err != nil {
		return nil, err
	}
	c := &Cluster{
		root:        root,
		config:      config,
		configEvent: make(chan struct{}, 10),
		runtimeRoot: config.RuntimeRoot,
		attachers:   make(map[string]*attacher),
	}

	nodeConfig, err := loadPersistentState(root)
	if err != nil {
		if os.IsNotExist(err) {
			return c, nil
		}
		return nil, err
	}

	nr, err := c.newNodeRunner(*nodeConfig)
	if err != nil {
		return nil, err
	}
	c.nr = nr

	select {
	case <-time.After(swarmConnectTimeout):
		logrus.Error("swarm component could not be started before timeout was reached")
	case err := <-nr.Ready():
		if err != nil {
			if errors.Cause(err) == errSwarmLocked {
				return c, nil
			}
			if err, ok := errors.Cause(c.nr.err).(x509.CertificateInvalidError); ok && err.Reason == x509.Expired {
				return c, nil
			}
			return nil, errors.Wrap(err, "swarm component could not be started")
		}
	}
	return c, nil
}
func TestCreateToolhelp32Snapshot(t *testing.T) {
	handle, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
	if err != nil {
		t.Fatal(err)
	}
	defer syscall.CloseHandle(syscall.Handle(handle))

	// Iterate over the snapshots until our PID is found.
	pid := uint32(syscall.Getpid())
	for {
		process, err := Process32Next(handle)
		if errors.Cause(err) == syscall.ERROR_NO_MORE_FILES {
			break
		}
		if err != nil {
			t.Fatal(err)
		}

		t.Logf("CreateToolhelp32Snapshot: ProcessEntry32=%v", process)

		if process.ProcessID == pid {
			assert.EqualValues(t, syscall.Getppid(), process.ParentProcessID)
			return
		}
	}

	assert.Fail(t, "Snapshot not found for PID=%v", pid)
}
Exemple #10
0
func (nc *NameCache) dbAddNamesForID(id int64, ins []string) error {
	add, err := nc.DB.Prepare("insert or replace into docker_search_name " +
		"(metadata_id, name) values ($1, $2)")
	if err != nil {
		return errors.Wrap(err, "adding names")
	}

	for _, n := range ins {
		_, err := add.Exec(id, n)
		if err != nil {
			Log.Vomit.Printf("%v %T", errors.Cause(err), errors.Cause(err))
			return errors.Wrapf(err, "adding name: %s", n)
		}
	}
	return nil
}
Exemple #11
0
func (nc *NameCache) ensureInDB(sel, ins string, args ...interface{}) (id int64, err error) {
	selN := len(sqlBindingRE.FindAllString(sel, -1))
	insN := len(sqlBindingRE.FindAllString(ins, -1))
	if selN > len(args) {
		return 0, errors.Errorf("only %d args when %d needed for %q", len(args), selN, sel)
	}
	if insN > len(args) {
		return 0, errors.Errorf("only %d args when %d needed for %q", len(args), insN, ins)
	}

	row := nc.DB.QueryRow(sel, args[0:selN]...)
	err = row.Scan(&id)
	if err == nil {
		Log.Vomit.Printf("Found id: %d with %q %v", id, sel, args)
		return
	}

	if errors.Cause(err) != sql.ErrNoRows {
		return 0, errors.Wrapf(err, "getting id with %q %v", sel, args[0:selN])
	}

	nr, err := nc.DB.Exec(ins, args[0:insN]...)
	if err != nil {
		return 0, errors.Wrapf(err, "inserting new value: %q %v", ins, args[0:insN])
	}
	id, err = nr.LastInsertId()
	Log.Vomit.Printf("Made (?err: %v) id: %d with %q", err, id, ins)
	return id, errors.Wrapf(err, "getting id of new value: %q %v", ins, args[0:insN])
}
Exemple #12
0
func (f decodeJSONFields) Run(event common.MapStr) (common.MapStr, error) {
	var errs []string

	for _, field := range f.fields {
		data, err := event.GetValue(field)
		if err != nil && errors.Cause(err) != common.ErrKeyNotFound {
			debug("Error trying to GetValue for field : %s in event : %v", field, event)
			errs = append(errs, err.Error())
			continue
		}
		text, ok := data.(string)
		if ok {
			var output interface{}
			err := unmarshal(f.maxDepth, []byte(text), &output, f.processArray)
			if err != nil {
				debug("Error trying to unmarshal %s", event[field])
				errs = append(errs, err.Error())
				continue
			}

			_, err = event.Put(field, output)
			if err != nil {
				debug("Error trying to Put value %v for field : %s", output, field)
				errs = append(errs, err.Error())
				continue
			}
		}
	}

	if len(errs) > 0 {
		return event, fmt.Errorf(strings.Join(errs, ", "))
	}
	return event, nil
}
func (s *workItemTypeRepoBlackBoxTest) TestCreateLoadWITWithList() {
	bt := "string"
	wit, err := s.repo.Create(context.Background(), nil, "foo_bar", map[string]app.FieldDefinition{
		"foo": {
			Required: true,
			Type: &app.FieldType{
				ComponentType: &bt,
				Kind:          string(workitem.KindList),
			},
		},
	})
	assert.Nil(s.T(), err)
	assert.NotNil(s.T(), wit)

	wit3, err := s.repo.Create(context.Background(), nil, "foo_bar", map[string]app.FieldDefinition{})
	assert.IsType(s.T(), errors.BadParameterError{}, errs.Cause(err))
	assert.Nil(s.T(), wit3)

	wit2, err := s.repo.Load(context.Background(), "foo_bar")
	assert.Nil(s.T(), err)
	require.NotNil(s.T(), wit2)
	field := wit2.Fields["foo"]
	require.NotNil(s.T(), field)
	assert.Equal(s.T(), string(workitem.KindList), field.Type.Kind)
	assert.Equal(s.T(), true, field.Required)
	assert.Nil(s.T(), field.Type.BaseType)
	assert.Nil(s.T(), field.Type.Values)
}
Exemple #14
0
func (gsm *GitStateManager) needCommit() bool {
	err := gsm.git("diff-index", "--exit-code", "HEAD")
	if ee, is := errors.Cause(err).(*exec.ExitError); is {
		return !ee.Success()
	}
	return false
}
func (c *OpenIDConnectExplicitHandler) PopulateTokenEndpointResponse(ctx context.Context, req *http.Request, requester fosite.AccessRequester, responder fosite.AccessResponder) error {
	if !requester.GetGrantTypes().Exact("authorization_code") {
		return errors.Wrap(fosite.ErrUnknownRequest, "")
	}

	authorize, err := c.OpenIDConnectRequestStorage.GetOpenIDConnectSession(ctx, requester.GetRequestForm().Get("code"), requester)
	if errors.Cause(err) == ErrNoSessionFound {
		return errors.Wrap(fosite.ErrUnknownRequest, err.Error())
	} else if err != nil {
		return errors.Wrap(fosite.ErrServerError, err.Error())
	}

	if !authorize.GetGrantedScopes().Has("openid") {
		return errors.Wrap(fosite.ErrMisconfiguration, "The an openid connect session was found but the openid scope is missing in it")
	}

	if !requester.GetClient().GetGrantTypes().Has("authorization_code") {
		return errors.Wrap(fosite.ErrInvalidGrant, "The client is not allowed to use the authorization_code grant type")
	}

	if !requester.GetClient().GetResponseTypes().Has("id_token") {
		return errors.Wrap(fosite.ErrInvalidGrant, "The client is not allowed to use response type id_token")
	}

	return c.IssueExplicitIDToken(ctx, req, authorize, responder)
}
Exemple #16
0
// Get returns an enabled plugin matching the given name and capability.
func (ps *Store) Get(name, capability string, mode int) (plugingetter.CompatPlugin, error) {
	var (
		p   *v2.Plugin
		err error
	)

	// Lookup using new model.
	if ps != nil {
		p, err = ps.GetV2Plugin(name)
		if err == nil {
			p.AddRefCount(mode)
			if p.IsEnabled() {
				return p.FilterByCap(capability)
			}
			// Plugin was found but it is disabled, so we should not fall back to legacy plugins
			// but we should error out right away
			return nil, ErrNotFound(name)
		}
		if _, ok := errors.Cause(err).(ErrNotFound); !ok {
			return nil, err
		}
	}

	// Lookup using legacy model.
	if allowV1PluginsFallback {
		p, err := plugins.Get(name, capability)
		if err != nil {
			return nil, fmt.Errorf("legacy plugin: %v", err)
		}
		return p, nil
	}

	return nil, err
}
Exemple #17
0
// BuildGRPCError returns the error with a GRPC code
func BuildGRPCError(err error) error {
	if err == nil {
		return nil
	}
	code := grpc.Code(err)
	if code != codes.Unknown {
		return err // it already is a gRPC error
	}
	switch errs.Cause(err).(type) {
	case *ErrAlreadyExists:
		code = codes.AlreadyExists
	case *ErrInternal:
		code = codes.Internal
	case *ErrInvalidArgument:
		code = codes.InvalidArgument
	case *ErrNotFound:
		code = codes.NotFound
	case *ErrPermissionDenied:
		code = codes.PermissionDenied
	}
	switch err {
	case context.Canceled:
		code = codes.Canceled
	case io.EOF:
		code = codes.OutOfRange
	}
	return grpc.Errorf(code, err.Error())
}
func createWorkItemLink(ctx *workItemLinkContext, funcs createWorkItemLinkFuncs, payload *app.CreateWorkItemLinkPayload) error {
	// Convert payload from app to model representation
	model := link.WorkItemLink{}
	in := app.WorkItemLinkSingle{
		Data: payload.Data,
	}
	err := link.ConvertLinkToModel(in, &model)
	if err != nil {
		jerrors, _ := jsonapi.ErrorToJSONAPIErrors(err)
		return funcs.BadRequest(jerrors)
	}
	link, err := ctx.Application.WorkItemLinks().Create(ctx.Context, model.SourceID, model.TargetID, model.LinkTypeID)
	if err != nil {
		cause := errs.Cause(err)
		switch cause.(type) {
		case errors.NotFoundError:
			jerrors, _ := jsonapi.ErrorToJSONAPIErrors(goa.ErrBadRequest(err.Error()))
			return funcs.BadRequest(jerrors)
		case errors.BadParameterError:
			jerrors, _ := jsonapi.ErrorToJSONAPIErrors(goa.ErrBadRequest(err.Error()))
			return funcs.BadRequest(jerrors)
		default:
			jerrors, httpStatusCode := jsonapi.ErrorToJSONAPIErrors(err)
			return ctx.ResponseData.Service.Send(ctx.Context, httpStatusCode, jerrors)
		}
	}
	if err := enrichLinkSingle(ctx, link); err != nil {
		jerrors, httpStatusCode := jsonapi.ErrorToJSONAPIErrors(err)
		return ctx.ResponseData.Service.Send(ctx.Context, httpStatusCode, jerrors)
	}

	ctx.ResponseData.Header().Set("Location", app.WorkItemLinkHref(link.Data.ID))
	return funcs.Created(link)
}
Exemple #19
0
func maybeDecorateGRPCError(wrapped cmdFn) cmdFn {
	return func(cmd *cobra.Command, args []string) error {
		err := wrapped(cmd, args)

		{
			unwrappedErr := errors.Cause(err)
			if unwrappedErr == nil {
				return err
			}
			_, isSendError := unwrappedErr.(*roachpb.SendError)
			isGRPCError := grpcutil.IsClosedConnection(unwrappedErr)
			_, isNetError := unwrappedErr.(*net.OpError)
			if !(isSendError || isGRPCError || isNetError) {
				return err // intentionally return original to keep wrapping
			}
		}

		format := `unable to connect or connection lost.

Please check the address and credentials such as certificates (if attempting to
communicate with a secure cluster).

%s`

		return errors.Errorf(format, err)
	}
}
Exemple #20
0
// ShouldRetry looks at an error and tries to work out if retrying the
// operation that caused it would be a good idea. It returns true if
// the error implements Timeout() or Temporary() or if the error
// indicates a premature closing of the connection.
func ShouldRetry(err error) bool {
	if err == nil {
		return false
	}

	// Find root cause if available
	err = errors.Cause(err)

	// Unwrap url.Error
	if urlErr, ok := err.(*url.Error); ok {
		err = urlErr.Err
	}

	// Look for premature closing of connection
	if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
		return true
	}

	// Check for net error Timeout()
	if x, ok := err.(interface {
		Timeout() bool
	}); ok && x.Timeout() {
		return true
	}

	// Check for net error Temporary()
	if x, ok := err.(interface {
		Temporary() bool
	}); ok && x.Temporary() {
		return true
	}

	return false
}
Exemple #21
0
func run(args []string, stderr io.Writer) int {
	rootCmd := newRoot().Command()
	rootCmd.SetArgs(args)
	rootCmd.SetOutput(stderr)
	if cmd, err := rootCmd.ExecuteC(); err != nil {
		err = errors.Cause(err)
		switch err := err.(type) {
		case usageError:
			cmd.Println("")
			cmd.Println(cmd.UsageString())
		case *transport.APIError:
			switch {
			case err.IsMissing():
				cmd.Println(strings.Join([]string{
					"Error: Service API endpoint not found. This usually means that there is a mismatch between the client and the service. Please visit",
					"    https://github.com/weaveworks/flux/releases",
					"to download a new release of the client."}, "\n"))
			default:
				cmd.Println("Problem communicating with the service: ", err.Error())
				cmd.Printf("Run '%v --help' for usage.\n", cmd.CommandPath())
			}
		default:
			cmd.Println("Error: ", err.Error())
			cmd.Printf("Run '%v --help' for usage.\n", cmd.CommandPath())
		}
		return 1
	}
	return 0
}
Exemple #22
0
func (n *Node) readFromDisk(ctx context.Context) (*raftpb.Snapshot, storage.WALData, error) {
	keys := n.keyRotator.GetKeys()

	n.raftLogger = &storage.EncryptedRaftLogger{
		StateDir:      n.opts.StateDir,
		EncryptionKey: keys.CurrentDEK,
	}
	if keys.PendingDEK != nil {
		n.raftLogger.EncryptionKey = keys.PendingDEK
	}

	snap, walData, err := n.raftLogger.BootstrapFromDisk(ctx)

	if keys.PendingDEK != nil {
		switch errors.Cause(err).(type) {
		case nil:
			if err = n.keyRotator.UpdateKeys(EncryptionKeys{CurrentDEK: keys.PendingDEK}); err != nil {
				err = errors.Wrap(err, "previous key rotation was successful, but unable mark rotation as complete")
			}
		case encryption.ErrCannotDecrypt:
			snap, walData, err = n.raftLogger.BootstrapFromDisk(ctx, keys.CurrentDEK)
		}
	}

	if err != nil {
		return nil, storage.WALData{}, err
	}
	return snap, walData, nil
}
Exemple #23
0
func (n *nodeRunner) State() nodeState {
	if n == nil {
		return nodeState{status: types.LocalNodeStateInactive}
	}
	n.mu.RLock()
	defer n.mu.RUnlock()

	ns := n.nodeState

	if ns.err != nil || n.cancelReconnect != nil {
		if errors.Cause(ns.err) == errSwarmLocked {
			ns.status = types.LocalNodeStateLocked
		} else {
			ns.status = types.LocalNodeStateError
		}
	} else {
		select {
		case <-n.ready:
			ns.status = types.LocalNodeStateActive
		default:
			ns.status = types.LocalNodeStatePending
		}
	}

	return ns
}
Exemple #24
0
// Update runs the update action.
func (c *TrackerqueryController) Update(ctx *app.UpdateTrackerqueryContext) error {
	result := application.Transactional(c.db, func(appl application.Application) error {

		toSave := app.TrackerQuery{
			ID:        ctx.ID,
			Query:     ctx.Payload.Query,
			Schedule:  ctx.Payload.Schedule,
			TrackerID: ctx.Payload.TrackerID,
		}
		tq, err := appl.TrackerQueries().Save(ctx.Context, toSave)

		if err != nil {
			cause := errs.Cause(err)
			switch cause.(type) {
			case remoteworkitem.BadParameterError, remoteworkitem.ConversionError:
				jerrors, _ := jsonapi.ErrorToJSONAPIErrors(goa.ErrBadRequest(err.Error()))
				return ctx.BadRequest(jerrors)
			default:
				jerrors, _ := jsonapi.ErrorToJSONAPIErrors(goa.ErrInternal(err.Error()))
				return ctx.InternalServerError(jerrors)
			}
		}
		return ctx.OK(tq)
	})
	c.scheduler.ScheduleAllQueries()
	return result
}
Exemple #25
0
func (p *swarmProvisioner) ListNodes(addressFilter []string) ([]provision.Node, error) {
	client, err := chooseDBSwarmNode()
	if err != nil {
		if errors.Cause(err) == errNoSwarmNode {
			return nil, nil
		}
		return nil, err
	}
	nodes, err := listValidNodes(client)
	if err != nil {
		return nil, err
	}
	var filterMap map[string]struct{}
	if len(addressFilter) > 0 {
		filterMap = map[string]struct{}{}
		for _, addr := range addressFilter {
			filterMap[addr] = struct{}{}
		}
	}
	nodeList := make([]provision.Node, 0, len(nodes))
	for i := range nodes {
		wrapped := &swarmNodeWrapper{Node: &nodes[i], provisioner: p}
		toAdd := true
		if filterMap != nil {
			_, toAdd = filterMap[wrapped.Address()]
		}
		if toAdd {
			nodeList = append(nodeList, wrapped)
		}
	}
	return nodeList, nil
}
Exemple #26
0
// UnlockSwarm provides a key to decrypt data that is encrypted at rest.
func (c *Cluster) UnlockSwarm(req types.UnlockRequest) error {
	key, err := encryption.ParseHumanReadableKey(req.UnlockKey)
	if err != nil {
		return err
	}

	c.Lock()
	if c.node != nil || c.locked != true {
		c.Unlock()
		return errors.New("swarm is not locked")
	}

	config := *c.lastNodeConfig
	config.lockKey = key
	n, err := c.startNewNode(config)
	if err != nil {
		c.Unlock()
		return err
	}
	c.Unlock()
	select {
	case <-n.Ready():
	case <-n.done:
		if errors.Cause(c.err) == ErrSwarmLocked {
			return errors.New("swarm could not be unlocked: invalid key provided")
		}
		return fmt.Errorf("swarm component could not be started: %v", c.err)
	}
	go c.reconnectOnFailure(n)
	return nil
}
func TestResourceOwnerFlow_HandleTokenEndpointRequest(t *testing.T) {
	ctrl := gomock.NewController(t)
	store := internal.NewMockResourceOwnerPasswordCredentialsGrantStorage(ctrl)
	defer ctrl.Finish()

	areq := fosite.NewAccessRequest(nil)
	httpreq := &http.Request{PostForm: url.Values{}}

	h := ResourceOwnerPasswordCredentialsGrantHandler{
		ResourceOwnerPasswordCredentialsGrantStorage: store,
		HandleHelper: &HandleHelper{
			AccessTokenStorage:  store,
			AccessTokenLifespan: time.Hour,
		},
		ScopeStrategy: fosite.HierarchicScopeStrategy,
	}
	for k, c := range []struct {
		description string
		setup       func()
		expectErr   error
	}{
		{
			description: "should fail because not responsible",
			expectErr:   fosite.ErrUnknownRequest,
			setup: func() {
				areq.GrantTypes = fosite.Arguments{"123"}
			},
		},
		{
			description: "should fail because because invalid credentials",
			setup: func() {
				areq.GrantTypes = fosite.Arguments{"password"}
				areq.Client = &fosite.DefaultClient{GrantTypes: fosite.Arguments{"password"}}
				httpreq.PostForm.Set("username", "peter")
				httpreq.PostForm.Set("password", "pan")
				store.EXPECT().Authenticate(nil, "peter", "pan").Return(fosite.ErrNotFound)
			},
			expectErr: fosite.ErrInvalidRequest,
		},
		{
			description: "should fail because because error on lookup",
			setup: func() {
				store.EXPECT().Authenticate(nil, "peter", "pan").Return(errors.New(""))
			},
			expectErr: fosite.ErrServerError,
		},
		{
			description: "should pass",
			setup: func() {
				store.EXPECT().Authenticate(nil, "peter", "pan").Return(nil)
			},
		},
	} {
		c.setup()
		err := h.HandleTokenEndpointRequest(nil, httpreq, areq)
		assert.True(t, errors.Cause(err) == c.expectErr, "(%d) %s\n%s\n%s", k, c.description, err, c.expectErr)
		t.Logf("Passed test case %d", k)
	}
}
func TestHandleTokenEndpointRequest(t *testing.T) {
	h := &OpenIDConnectExplicitHandler{}
	areq := fosite.NewAccessRequest(nil)
	areq.Client = &fosite.DefaultClient{
		ResponseTypes: fosite.Arguments{"id_token"},
	}
	assert.True(t, errors.Cause(h.HandleTokenEndpointRequest(nil, nil, areq)) == fosite.ErrUnknownRequest)
}
func ExampleCause() {
	err := fn()
	fmt.Println(err)
	fmt.Println(errors.Cause(err))

	// Output: outer: middle: inner: error
	// error
}
// InternalError produces an HTTP 500 error, basically means a bug in the system
func InternalError(w http.ResponseWriter, r *http.Request, err error) {
	log.WithFields(log.Fields{
		"cause":  errors.Cause(err).Error(),
		"method": r.Method,
		"path":   r.URL.EscapedPath() + "?" + r.URL.RawQuery,
	}).Errorf("HTTP Error: %s", err.Error())
	sendRequestProblem(w, r, http.StatusInternalServerError, err)
}