From 1bee6849f1dcc84e396ed31df70786de9d7fa87d Mon Sep 17 00:00:00 2001 From: Lukas Vogel Date: Mon, 21 Oct 2019 23:39:00 +0200 Subject: [PATCH 1/3] errors: Use common.ErrMsg for constants This PR prepares for migration from common.NewBasicError towards serrors. --- go/beacon_srv/internal/beacon/db.go | 4 +- go/beacon_srv/main.go | 4 +- go/border/rpkt/extns.go | 2 +- go/border/rpkt/validate.go | 6 +- go/cert_srv/internal/config/config.go | 5 +- go/cert_srv/internal/reiss/handler.go | 9 +- go/cert_srv/setup.go | 10 +- .../internal/registration/errors.go | 20 ++-- .../internal/registration/iatable.go | 4 +- .../internal/registration/iatable_test.go | 4 +- go/godispatcher/network/overlay.go | 10 +- go/godispatcher/network/overlay_test.go | 4 +- go/lib/healthpool/pool.go | 2 +- go/lib/hiddenpath/group.go | 48 +++++----- go/lib/infra/disp/disp.go | 24 ++--- go/lib/infra/errors.go | 10 +- go/lib/infra/infraenv/infraenv.go | 2 +- go/lib/infra/modules/db/errors.go | 11 ++- go/lib/keyconf/keyconf.go | 9 +- go/lib/l4/common.go | 4 +- go/lib/scmp/hdr.go | 4 +- go/lib/scrypto/asym.go | 53 ++++++----- go/lib/scrypto/cert/cert.go | 24 ++--- go/lib/scrypto/cert/chain.go | 2 +- go/lib/scrypto/cert/json.go | 10 +- go/lib/scrypto/cert/v2/BUILD.bazel | 2 + go/lib/scrypto/cert/v2/as.go | 18 ++-- go/lib/scrypto/cert/v2/as_json_test.go | 2 +- go/lib/scrypto/cert/v2/as_signed.go | 2 +- go/lib/scrypto/cert/v2/as_test.go | 23 ++--- go/lib/scrypto/cert/v2/base.go | 48 +++++----- go/lib/scrypto/cert/v2/base_signed.go | 12 +-- go/lib/scrypto/cert/v2/base_test.go | 19 ++-- go/lib/scrypto/cert/v2/chain.go | 6 +- go/lib/scrypto/cert/v2/chain_json_test.go | 4 +- go/lib/scrypto/cert/v2/issuer.go | 2 +- go/lib/scrypto/cert/v2/issuer_json_test.go | 2 +- go/lib/scrypto/cert/v2/issuer_signed.go | 2 +- go/lib/scrypto/cert/v2/issuer_test.go | 19 ++-- go/lib/scrypto/cert/v2/verify.go | 38 ++++---- go/lib/scrypto/cert/v2/verify_test.go | 23 ++--- go/lib/scrypto/mac.go | 8 +- go/lib/scrypto/rand.go | 8 +- go/lib/scrypto/trc/entries.go | 2 +- go/lib/scrypto/trc/json.go | 10 +- go/lib/scrypto/trc/trc.go | 32 ++++--- go/lib/scrypto/trc/v2/BUILD.bazel | 1 + go/lib/scrypto/trc/v2/keychanges.go | 14 +-- go/lib/scrypto/trc/v2/pop.go | 12 +-- go/lib/scrypto/trc/v2/primary.go | 50 +++++----- go/lib/scrypto/trc/v2/primary_json_test.go | 2 +- go/lib/scrypto/trc/v2/primary_test.go | 23 ++--- go/lib/scrypto/trc/v2/signed.go | 14 +-- go/lib/scrypto/trc/v2/trc.go | 23 ++--- go/lib/scrypto/trc/v2/trc_test.go | 34 +++---- go/lib/scrypto/trc/v2/update.go | 71 +++++++------- go/lib/scrypto/trc/v2/update_test.go | 95 +++++++++---------- go/lib/scrypto/trc/v2/verify.go | 65 ++++++------- go/lib/scrypto/trc/v2/verify_test.go | 28 +++--- go/lib/scrypto/validity.go | 6 +- go/lib/scrypto/version.go | 8 +- go/lib/snet/internal/pathsource/pathsource.go | 8 +- go/lib/snet/writer.go | 18 ++-- go/lib/sock/reliable/BUILD.bazel | 3 + go/lib/sock/reliable/errors.go | 24 ++--- go/lib/sock/reliable/frame_test.go | 9 +- go/lib/sock/reliable/registration_test.go | 14 +-- go/lib/spath/info.go | 13 +-- go/lib/spkt/cmnhdr.go | 2 +- go/lib/svc/resolver.go | 16 ++-- go/lib/svc/svc.go | 2 +- go/lib/topology/BUILD.bazel | 2 + go/lib/topology/addr.go | 20 ++-- go/lib/topology/addr_test.go | 68 +++++-------- go/lib/topology/raw.go | 6 +- go/path_srv/main.go | 2 +- go/protobuf/BUILD.bazel | 16 ++++ go/sciond/main.go | 2 +- go/tools/scion-pki/internal/conf/BUILD.bazel | 1 + go/tools/scion-pki/internal/conf/as.go | 16 ++-- go/tools/scion-pki/internal/conf/as_test.go | 4 +- go/tools/scion-pki/internal/conf/isd.go | 12 +-- go/tools/scion-pki/internal/conf/isd_test.go | 3 +- go/tools/scion-pki/internal/pkicmn/pkicmn.go | 28 +++--- .../scion-pki/internal/pkicmn/pkicmn_test.go | 2 +- .../scion-pki/internal/v2/conf/BUILD.bazel | 1 + go/tools/scion-pki/internal/v2/conf/as.go | 22 ++--- .../scion-pki/internal/v2/conf/as_test.go | 11 +-- go/tools/scion-pki/internal/v2/conf/isd.go | 10 +- .../scion-pki/internal/v2/conf/isd_test.go | 14 +-- 90 files changed, 682 insertions(+), 680 deletions(-) create mode 100644 go/protobuf/BUILD.bazel diff --git a/go/beacon_srv/internal/beacon/db.go b/go/beacon_srv/internal/beacon/db.go index bcd63229db..a7761050a2 100644 --- a/go/beacon_srv/internal/beacon/db.go +++ b/go/beacon_srv/internal/beacon/db.go @@ -31,9 +31,9 @@ import ( const ( // ErrReadingRows is the error message in case we fail to read more from // the database. - ErrReadingRows = "Failed to read rows" + ErrReadingRows common.ErrMsg = "Failed to read rows" // ErrParse is the error message in case the parsing a db entry fails. - ErrParse = "Failed to parse entry" + ErrParse common.ErrMsg = "Failed to parse entry" ) // DBRead defines all read operations of the beacon DB. diff --git a/go/beacon_srv/main.go b/go/beacon_srv/main.go index 1c8d200696..f9385fffbb 100644 --- a/go/beacon_srv/main.go +++ b/go/beacon_srv/main.go @@ -147,7 +147,7 @@ func realMain() int { } msgr, err := nc.Messenger() if err != nil { - log.Crit(infraenv.ErrAppUnableToInitMessenger, "err", err) + log.Crit(infraenv.ErrAppUnableToInitMessenger.Error(), "err", err) return 1 } defer msgr.CloseServer() @@ -215,7 +215,7 @@ func realMain() int { } signer, err := tasks.createSigner(topo.IA()) if err != nil { - log.Crit(infraenv.ErrAppUnableToInitMessenger, "err", err) + log.Crit(infraenv.ErrAppUnableToInitMessenger.Error(), "err", err) return 1 } msgr.UpdateSigner(signer, []infra.MessageType{infra.Seg}) diff --git a/go/border/rpkt/extns.go b/go/border/rpkt/extns.go index b2d3396874..2dee7e60a1 100644 --- a/go/border/rpkt/extns.go +++ b/go/border/rpkt/extns.go @@ -35,7 +35,7 @@ type rExtension interface { const ( // FIXME(kormat): remove when generic header walker is implemented. - ErrExtChainTooLong = "Extension header chain longer than packet" + ErrExtChainTooLong common.ErrMsg = "Extension header chain longer than packet" ) // extnParseHBH parses a specified hop-by-hop extension in a packet. diff --git a/go/border/rpkt/validate.go b/go/border/rpkt/validate.go index c35bcbd8f0..f76fe03317 100644 --- a/go/border/rpkt/validate.go +++ b/go/border/rpkt/validate.go @@ -23,9 +23,9 @@ import ( ) const ( - errCurrIntfInvalid = "Invalid current interface" - errIntfRevoked = "Interface revoked" - errHookResponse = "Extension hook return value unrecognised" + errCurrIntfInvalid common.ErrMsg = "Invalid current interface" + errIntfRevoked common.ErrMsg = "Interface revoked" + errHookResponse common.ErrMsg = "Extension hook return value unrecognised" ) // Validate performs basic validation of a packet, including calling any diff --git a/go/cert_srv/internal/config/config.go b/go/cert_srv/internal/config/config.go index 5b2a7bd888..d1e08414df 100644 --- a/go/cert_srv/internal/config/config.go +++ b/go/cert_srv/internal/config/config.go @@ -18,6 +18,7 @@ import ( "io" "time" + "github.com/scionproto/scion/go/lib/common" "github.com/scionproto/scion/go/lib/config" "github.com/scionproto/scion/go/lib/env" "github.com/scionproto/scion/go/lib/infra/modules/idiscovery" @@ -39,8 +40,8 @@ const ( // ReissueReqTimeout is the default timeout of a reissue request. ReissueReqTimeout = 5 * time.Second - ErrorKeyConf = "Unable to load KeyConf" - ErrorCustomers = "Unable to load Customers" + ErrorKeyConf common.ErrMsg = "Unable to load KeyConf" + ErrorCustomers common.ErrMsg = "Unable to load Customers" ) var _ config.Config = (*Config)(nil) diff --git a/go/cert_srv/internal/reiss/handler.go b/go/cert_srv/internal/reiss/handler.go index 3a49c18a2e..de5384975a 100644 --- a/go/cert_srv/internal/reiss/handler.go +++ b/go/cert_srv/internal/reiss/handler.go @@ -37,9 +37,12 @@ import ( const ( HandlerTimeout = 5 * time.Second +) - KeyChanged = "Verifying key has changed in the meantime" - NotACustomer = "ISD-AS not in customer mapping" +// Errors +const ( + ErrKeyChanged common.ErrMsg = "Verifying key has changed in the meantime" + ErrNotACustomer common.ErrMsg = "ISD-AS not in customer mapping" ) // Handler handles certificate chain reissue requests. @@ -258,7 +261,7 @@ func (h *Handler) getVerifyingKey(ctx context.Context, return nil, 0, err } if k == nil { - return nil, 0, common.NewBasicError(NotACustomer, nil, "ISD-AS", ia) + return nil, 0, common.NewBasicError(ErrNotACustomer, nil, "ISD-AS", ia) } return k.Key, k.Version, nil } diff --git a/go/cert_srv/setup.go b/go/cert_srv/setup.go index 85b8e13667..f1a7bc57e5 100644 --- a/go/cert_srv/setup.go +++ b/go/cert_srv/setup.go @@ -40,11 +40,11 @@ import ( ) const ( - ErrorConf = "Unable to load configuration" - ErrorDispClose = "Unable to close dispatcher" - ErrorDispInit = "Unable to initialize dispatcher" - ErrorSign = "Unable to create sign" - ErrorSNET = "Unable to create local SCION Network context" + ErrorConf common.ErrMsg = "Unable to load configuration" + ErrorDispClose common.ErrMsg = "Unable to close dispatcher" + ErrorDispInit common.ErrMsg = "Unable to initialize dispatcher" + ErrorSign common.ErrMsg = "Unable to create sign" + ErrorSNET common.ErrMsg = "Unable to create local SCION Network context" ) // setupBasic loads the config from file and initializes logging. diff --git a/go/godispatcher/internal/registration/errors.go b/go/godispatcher/internal/registration/errors.go index 04d079d1ab..80605d318c 100644 --- a/go/godispatcher/internal/registration/errors.go +++ b/go/godispatcher/internal/registration/errors.go @@ -14,14 +14,16 @@ package registration +import "github.com/scionproto/scion/go/lib/common" + const ( - ErrNoPublicAddress = "no public address" - ErrBindWithoutSvc = "bind address without svc address" - ErrOverlappingAddress = "overlapping address" - ErrNoValue = "nil value" - ErrZeroIP = "zero address" - ErrZeroPort = "zero port" - ErrNilAddress = "nil address" - ErrSvcNone = "svc none" - ErrNoPorts = "no free ports" + ErrNoPublicAddress common.ErrMsg = "no public address" + ErrBindWithoutSvc common.ErrMsg = "bind address without svc address" + ErrOverlappingAddress common.ErrMsg = "overlapping address" + ErrNoValue common.ErrMsg = "nil value" + ErrZeroIP common.ErrMsg = "zero address" + ErrZeroPort common.ErrMsg = "zero port" + ErrNilAddress common.ErrMsg = "nil address" + ErrSvcNone common.ErrMsg = "svc none" + ErrNoPorts common.ErrMsg = "no free ports" ) diff --git a/go/godispatcher/internal/registration/iatable.go b/go/godispatcher/internal/registration/iatable.go index 1eace91f52..982801e842 100644 --- a/go/godispatcher/internal/registration/iatable.go +++ b/go/godispatcher/internal/registration/iatable.go @@ -23,8 +23,8 @@ import ( ) const ( - ErrBadISD = "0 is not valid ISD" - ErrBadAS = "0 is not valid AS" + ErrBadISD common.ErrMsg = "0 is not valid ISD" + ErrBadAS common.ErrMsg = "0 is not valid AS" ) // Reference tracks an object from a collection. diff --git a/go/godispatcher/internal/registration/iatable_test.go b/go/godispatcher/internal/registration/iatable_test.go index a6cfe06426..2bd19577eb 100644 --- a/go/godispatcher/internal/registration/iatable_test.go +++ b/go/godispatcher/internal/registration/iatable_test.go @@ -90,12 +90,12 @@ func TestIATableRegister(t *testing.T) { value := "test value" Convey("ISD zero is error", func() { ref, err := table.Register(addr.IA{I: 0, A: 1}, public, nil, addr.SvcNone, value) - xtest.SoMsgErrorStr("err", err, ErrBadISD) + xtest.SoMsgErrorStr("err", err, ErrBadISD.Error()) SoMsg("ref", ref, ShouldBeNil) }) Convey("AS zero is error", func() { ref, err := table.Register(addr.IA{I: 1, A: 0}, public, nil, addr.SvcNone, value) - xtest.SoMsgErrorStr("err", err, ErrBadAS) + xtest.SoMsgErrorStr("err", err, ErrBadAS.Error()) SoMsg("ref", ref, ShouldBeNil) }) Convey("for a good AS number", func() { diff --git a/go/godispatcher/network/overlay.go b/go/godispatcher/network/overlay.go index 5965abfcc3..14ed6e2333 100644 --- a/go/godispatcher/network/overlay.go +++ b/go/godispatcher/network/overlay.go @@ -31,11 +31,11 @@ import ( ) const ( - ErrUnsupportedL4 = "unsupported SCION L4 protocol" - ErrUnsupportedDestination = "unsupported destination address type" - ErrUnsupportedSCMPDestination = "unsupported SCMP destination address type" - ErrUnsupportedQuotedL4Type = "unsupported quoted L4 protocol type" - ErrMalformedL4Quote = "malformed L4 quote" + ErrUnsupportedL4 common.ErrMsg = "unsupported SCION L4 protocol" + ErrUnsupportedDestination common.ErrMsg = "unsupported destination address type" + ErrUnsupportedSCMPDestination common.ErrMsg = "unsupported SCMP destination address type" + ErrUnsupportedQuotedL4Type common.ErrMsg = "unsupported quoted L4 protocol type" + ErrMalformedL4Quote common.ErrMsg = "malformed L4 quote" ) // NetToRingDataplane reads SCION packets from the overlay socket, routes them diff --git a/go/godispatcher/network/overlay_test.go b/go/godispatcher/network/overlay_test.go index 6e6d5c0c35..03a51be416 100644 --- a/go/godispatcher/network/overlay_test.go +++ b/go/godispatcher/network/overlay_test.go @@ -41,7 +41,7 @@ func TestComputeDestination(t *testing.T) { Description string Packet *spkt.ScnPkt ExpectedDst Destination - ExpectedErr string + ExpectedErr common.ErrMsg } var testCases = []*TestCase{ { @@ -212,7 +212,7 @@ func TestComputeDestination(t *testing.T) { for _, test := range testCases { Convey(test.Description, func() { destination, err := ComputeDestination(test.Packet) - xtest.SoMsgErrorStr("err", err, test.ExpectedErr) + xtest.SoMsgErrorStr("err", err, test.ExpectedErr.Error()) SoMsg("destination", destination, ShouldResemble, test.ExpectedDst) }) } diff --git a/go/lib/healthpool/pool.go b/go/lib/healthpool/pool.go index c43d6a4bd2..000362b078 100644 --- a/go/lib/healthpool/pool.go +++ b/go/lib/healthpool/pool.go @@ -26,7 +26,7 @@ import ( // ErrPoolClosed is the error returned when operations on a closed pool are // executed. -const ErrPoolClosed = "Pool closed" +const ErrPoolClosed common.ErrMsg = "Pool closed" // InfoSet is a set of infos. type InfoSet map[Info]struct{} diff --git a/go/lib/hiddenpath/group.go b/go/lib/hiddenpath/group.go index 17594731eb..ccdfedf7e8 100644 --- a/go/lib/hiddenpath/group.go +++ b/go/lib/hiddenpath/group.go @@ -27,26 +27,26 @@ import ( // Parsing errors const ( - // InvalidGroupIdFormat indicates an invalid GroupId format - InvalidGroupIdFormat = "Invalid GroupId format" - // InvalidGroupIdSuffix indicates an invalid GroupId suffix - InvalidGroupIdSuffix = "Invalid GroupId suffix" + // ErrInvalidGroupIdFormat indicates an invalid GroupId format + ErrInvalidGroupIdFormat common.ErrMsg = "Invalid GroupId format" + // ErrInvalidGroupIdSuffix indicates an invalid GroupId suffix + ErrInvalidGroupIdSuffix common.ErrMsg = "Invalid GroupId suffix" ) // Validation errors const ( - // MissingGroupId indicates a missing GroupId - MissingGroupId = "Missing GroupId" - // InvalidVersion indicates a missing version - InvalidVersion = "Invalid version" - // MissingOwner indicates a missing Owner - MissingOwner = "Missing Owner" - // OwnerMismatch indicates a mismatch between Owner and GroupId.OwnerAS - OwnerMismatch = "Owner mismatch" - // EmptyWriters indicatres an empty Writer section - EmptyWriters = "Writer section cannot be empty" - // EmptyWriters indicatres an empty Writer section - EmptyRegistries = "Registry section cannot be empty" + // ErrMissingGroupId indicates a missing GroupId + ErrMissingGroupId common.ErrMsg = "Missing GroupId" + // ErrInvalidVersion indicates a missing version + ErrInvalidVersion common.ErrMsg = "Invalid version" + // ErrMissingOwner indicates a missing Owner + ErrMissingOwner common.ErrMsg = "Missing Owner" + // ErrOwnerMismatch indicates a mismatch between Owner and GroupId.OwnerAS + ErrOwnerMismatch common.ErrMsg = "Owner mismatch" + // ErrEmptyWriters indicates an empty Writer section + ErrEmptyWriters common.ErrMsg = "Writer section cannot be empty" + // ErrEmptyRegistries indicates an empty Registires section + ErrEmptyRegistries common.ErrMsg = "Registry section cannot be empty" ) type GroupId struct { @@ -63,7 +63,7 @@ func (id *GroupId) UnmarshalText(data []byte) error { v = strings.Replace(v, "_", ":", 2) parts := strings.Split(v, "-") if len(parts) != 2 { - return common.NewBasicError(InvalidGroupIdFormat, nil, "GroupId", v) + return common.NewBasicError(ErrInvalidGroupIdFormat, nil, "GroupId", v) } ownerAS, err := addr.ASFromString(parts[0]) if err != nil { @@ -71,7 +71,7 @@ func (id *GroupId) UnmarshalText(data []byte) error { } suffix, err := strconv.ParseUint(parts[1], 16, 16) if err != nil { - return common.NewBasicError(InvalidGroupIdSuffix, err, "Suffix", parts[1]) + return common.NewBasicError(ErrInvalidGroupIdSuffix, err, "Suffix", parts[1]) } id.OwnerAS = ownerAS id.Suffix = uint16(suffix) @@ -126,23 +126,23 @@ func (g *Group) UnmarshalJSON(data []byte) (err error) { return err } if v.Id == (GroupId{}) { - return common.NewBasicError(MissingGroupId, nil) + return common.NewBasicError(ErrMissingGroupId, nil) } if v.Version == 0 { - return common.NewBasicError(InvalidVersion, nil) + return common.NewBasicError(ErrInvalidVersion, nil) } if v.Owner == (addr.IA{}) { - return common.NewBasicError(MissingOwner, nil) + return common.NewBasicError(ErrMissingOwner, nil) } if v.Owner.A != v.Id.OwnerAS { - return common.NewBasicError(OwnerMismatch, nil, + return common.NewBasicError(ErrOwnerMismatch, nil, "OwnerAS", v.Owner.A, "GroupId.OwnerAS", v.Id.OwnerAS) } if len(v.Writers) == 0 { - return common.NewBasicError(EmptyWriters, nil) + return common.NewBasicError(ErrEmptyWriters, nil) } if len(v.Registries) == 0 { - return common.NewBasicError(EmptyRegistries, nil) + return common.NewBasicError(ErrEmptyRegistries, nil) } *g = Group(v) return nil diff --git a/go/lib/infra/disp/disp.go b/go/lib/infra/disp/disp.go index e14813960c..29ffd2c8e9 100644 --- a/go/lib/infra/disp/disp.go +++ b/go/lib/infra/disp/disp.go @@ -107,23 +107,23 @@ func New(conn net.PacketConn, adapter MessageAdapter, logger log.Logger) *Dispat func (d *Dispatcher) Request(ctx context.Context, msg proto.Cerealizable, address net.Addr) (proto.Cerealizable, error) { if err := d.waitTable.addRequest(msg); err != nil { - return nil, common.NewBasicError(infra.StrInternalError, err, "op", "waitTable.AddRequest") + return nil, common.NewBasicError(infra.ErrInternal, err, "op", "waitTable.AddRequest") } // Delete request entry when we exit this context defer d.waitTable.cancelRequest(msg) b, err := d.adapter.MsgToRaw(msg) if err != nil { - return nil, common.NewBasicError(infra.StrAdapterError, err, "op", "MsgToRaw") + return nil, common.NewBasicError(infra.ErrAdapter, err, "op", "MsgToRaw") } // FIXME(scrye): Writes rarely block on packet conns. if _, err := d.conn.WriteTo(b, address); err != nil { - return nil, common.NewBasicError(infra.StrTransportError, err, "op", "WriteTo") + return nil, common.NewBasicError(infra.ErrTransport, err, "op", "WriteTo") } reply, err := d.waitTable.waitForReply(ctx, msg) if err != nil { - return nil, common.NewBasicError(infra.StrInternalError, err, + return nil, common.NewBasicError(infra.ErrInternal, err, "op", "waitTable.WaitForReply") } return reply, nil @@ -135,10 +135,10 @@ func (d *Dispatcher) Request(ctx context.Context, msg proto.Cerealizable, func (d *Dispatcher) Notify(ctx context.Context, msg proto.Cerealizable, address net.Addr) error { b, err := d.adapter.MsgToRaw(msg) if err != nil { - return common.NewBasicError(infra.StrAdapterError, err, "op", "MsgToRaw") + return common.NewBasicError(infra.ErrAdapter, err, "op", "MsgToRaw") } if _, err := d.conn.WriteTo(b, address); err != nil { - return common.NewBasicError(infra.StrTransportError, err, "op", "WriteTo") + return common.NewBasicError(infra.ErrTransport, err, "op", "WriteTo") } return nil } @@ -148,10 +148,10 @@ func (d *Dispatcher) NotifyUnreliable(ctx context.Context, msg proto.Cerealizabl address net.Addr) error { b, err := d.adapter.MsgToRaw(msg) if err != nil { - return common.NewBasicError(infra.StrAdapterError, err, "op", "MsgToRaw") + return common.NewBasicError(infra.ErrAdapter, err, "op", "MsgToRaw") } if _, err := d.conn.WriteTo(b, address); err != nil { - return common.NewBasicError(infra.StrTransportError, err, "op", "WriteTo") + return common.NewBasicError(infra.ErrTransport, err, "op", "WriteTo") } return nil } @@ -166,7 +166,7 @@ func (d *Dispatcher) RecvFrom(ctx context.Context) (proto.Cerealizable, int, net return nil, 0, nil, ctx.Err() case <-d.closedChan: // Some other goroutine closed the dispatcher - return nil, 0, nil, common.NewBasicError(infra.StrClosedError, nil) + return nil, 0, nil, common.NewBasicError(infra.ErrLayerClosed, nil) } } @@ -202,7 +202,7 @@ func (d *Dispatcher) recvNext() bool { return true } else { d.log.Warn("error", "err", - common.NewBasicError(infra.StrTransportError, err, "op", "RecvFrom")) + common.NewBasicError(infra.ErrTransport, err, "op", "RecvFrom")) } return false } @@ -210,14 +210,14 @@ func (d *Dispatcher) recvNext() bool { msg, err := d.adapter.RawToMsg(b) if err != nil { d.log.Warn("error", "err", - common.NewBasicError(infra.StrAdapterError, err, "op", "RawToMsg")) + common.NewBasicError(infra.ErrAdapter, err, "op", "RawToMsg")) return false } found, err := d.waitTable.reply(msg) if err != nil { d.log.Warn("error", "err", - common.NewBasicError(infra.StrInternalError, err, "op", "waitTable.Reply")) + common.NewBasicError(infra.ErrInternal, err, "op", "waitTable.Reply")) return false } if found { diff --git a/go/lib/infra/errors.go b/go/lib/infra/errors.go index dc7cadb49c..6bd20d2d8d 100644 --- a/go/lib/infra/errors.go +++ b/go/lib/infra/errors.go @@ -16,9 +16,11 @@ // messaging layer. package infra +import "github.com/scionproto/scion/go/lib/common" + const ( - StrClosedError = "layer closed" - StrAdapterError = "msg adapter error" - StrInternalError = "internal error" - StrTransportError = "transport error" + ErrLayerClosed common.ErrMsg = "layer closed" + ErrAdapter common.ErrMsg = "msg adapter error" + ErrInternal common.ErrMsg = "internal error" + ErrTransport common.ErrMsg = "transport error" ) diff --git a/go/lib/infra/infraenv/infraenv.go b/go/lib/infra/infraenv/infraenv.go index 1eb3a5d9ee..a3536ad669 100644 --- a/go/lib/infra/infraenv/infraenv.go +++ b/go/lib/infra/infraenv/infraenv.go @@ -39,7 +39,7 @@ import ( ) const ( - ErrAppUnableToInitMessenger = "Unable to initialize SCION Infra Messenger" + ErrAppUnableToInitMessenger common.ErrMsg = "Unable to initialize SCION Infra Messenger" ) var resolutionRequestPayload = []byte{0x00, 0x00, 0x00, 0x00} diff --git a/go/lib/infra/modules/db/errors.go b/go/lib/infra/modules/db/errors.go index 34f6ded318..e6d7292ac1 100644 --- a/go/lib/infra/modules/db/errors.go +++ b/go/lib/infra/modules/db/errors.go @@ -15,6 +15,7 @@ package db import ( + "github.com/scionproto/scion/go/lib/common" "github.com/scionproto/scion/go/lib/serrors" ) @@ -31,27 +32,27 @@ var ( ErrTx = serrors.New("db: transaction error") ) -func NewTxError(msg string, err error, logCtx ...interface{}) error { +func NewTxError(msg common.ErrMsg, err error, logCtx ...interface{}) error { return serrors.Wrap(ErrTx, err, append([]interface{}{"detailMsg", msg}, logCtx...)...) } -func NewInputDataError(msg string, err error, logCtx ...interface{}) error { +func NewInputDataError(msg common.ErrMsg, err error, logCtx ...interface{}) error { return serrors.Wrap(ErrInvalidInputData, err, append([]interface{}{"detailMsg", msg}, logCtx...)...) } -func NewDataError(msg string, err error, logCtx ...interface{}) error { +func NewDataError(msg common.ErrMsg, err error, logCtx ...interface{}) error { return serrors.Wrap(ErrDataInvalid, err, append([]interface{}{"detailMsg", msg}, logCtx...)...) } -func NewReadError(msg string, err error, logCtx ...interface{}) error { +func NewReadError(msg common.ErrMsg, err error, logCtx ...interface{}) error { return serrors.Wrap(ErrReadFailed, err, append([]interface{}{"detailMsg", msg}, logCtx...)...) } -func NewWriteError(msg string, err error, logCtx ...interface{}) error { +func NewWriteError(msg common.ErrMsg, err error, logCtx ...interface{}) error { return serrors.Wrap(ErrWriteFailed, err, append([]interface{}{"detailMsg", msg}, logCtx...)...) } diff --git a/go/lib/keyconf/keyconf.go b/go/lib/keyconf/keyconf.go index b96ef3bc0a..7862ae4995 100644 --- a/go/lib/keyconf/keyconf.go +++ b/go/lib/keyconf/keyconf.go @@ -65,10 +65,13 @@ const ( TRCIssuingKeyFile = "trc-issuing.key" RawKey = "raw" +) - ErrorOpen = "Unable to load key" - ErrorParse = "Unable to parse key file" - ErrorUnknown = "Unknown algorithm" +// Errors +const ( + ErrorOpen common.ErrMsg = "Unable to load key" + ErrorParse common.ErrMsg = "Unable to parse key file" + ErrorUnknown common.ErrMsg = "Unknown algorithm" ) // Load loads key configuration from specified path. diff --git a/go/lib/l4/common.go b/go/lib/l4/common.go index e98694a3d0..59e492bea8 100644 --- a/go/lib/l4/common.go +++ b/go/lib/l4/common.go @@ -22,7 +22,7 @@ import ( "github.com/scionproto/scion/go/lib/util" ) -const ErrorInvalidChksum = "Invalid L4 checksum" +const ErrInvalidChksum common.ErrMsg = "Invalid L4 checksum" type L4Header interface { fmt.Stringer @@ -65,7 +65,7 @@ func CheckCSum(h L4Header, addr, pld common.RawBytes) error { } exp := h.GetCSum() if bytes.Compare(exp, calc) != 0 { - return common.NewBasicError(ErrorInvalidChksum, nil, + return common.NewBasicError(ErrInvalidChksum, nil, "expected", exp, "actual", calc, "proto", h.L4Type()) } return nil diff --git a/go/lib/scmp/hdr.go b/go/lib/scmp/hdr.go index 4556e9beb9..6a75d6c1f0 100644 --- a/go/lib/scmp/hdr.go +++ b/go/lib/scmp/hdr.go @@ -31,7 +31,7 @@ const ( ) const ( - ErrorSCMPHdrUnpack = "Failed to unpack SCMP header" + ErrSCMPHdrUnpack common.ErrMsg = "Failed to unpack SCMP header" ) type Hdr struct { @@ -53,7 +53,7 @@ func NewHdr(ct ClassType, len int) *Hdr { func HdrFromRaw(b common.RawBytes) (*Hdr, error) { h := &Hdr{} if err := restruct.Unpack(b, common.Order, h); err != nil { - return nil, common.NewBasicError(ErrorSCMPHdrUnpack, err) + return nil, common.NewBasicError(ErrSCMPHdrUnpack, err) } return h, nil } diff --git a/go/lib/scrypto/asym.go b/go/lib/scrypto/asym.go index 8eaa087ce0..88dc44e474 100644 --- a/go/lib/scrypto/asym.go +++ b/go/lib/scrypto/asym.go @@ -39,16 +39,17 @@ const ( ) const ( - InvalidPubKeySize = "Invalid public key size" - InvalidPrivKeySize = "Invalid private key size" - InvalidSignatureSize = "Invalid signature size" - InvalidSignatureFormat = "Invalid signature format: sig[63]&224 should equal 0" - VerificationError = "Signature verification failed" - UnableToGenerateKeyPair = "Unable to generate key pair" - UnableToDecrypt = "Unable to decrypt message" - UnsupportedAlgo = "Unsupported algorithm" - UnsupportedSignAlgo = "Unsupported signing algorithm" - UnsupportedEncAlgo = "Unsupported encryption algorithm" + ErrInvalidPubKeySize common.ErrMsg = "Invalid public key size" + ErrInvalidPrivKeySize common.ErrMsg = "Invalid private key size" + ErrInvalidSignatureSize common.ErrMsg = "Invalid signature size" + ErrInvalidSignatureFormat common.ErrMsg = "Invalid signature format: " + + "sig[63]&224 should equal 0" + ErrVerification common.ErrMsg = "Signature verification failed" + ErrUnableToGenerateKeyPair common.ErrMsg = "Unable to generate key pair" + ErrUnableToDecrypt common.ErrMsg = "Unable to decrypt message" + ErrUnsupportedAlgo common.ErrMsg = "Unsupported algorithm" + ErrUnsupportedSignAlgo common.ErrMsg = "Unsupported signing algorithm" + ErrUnsupportedEncAlgo common.ErrMsg = "Unsupported encryption algorithm" ) // GenKeyPair generates a public/private key pair. @@ -57,19 +58,19 @@ func GenKeyPair(algo string) (common.RawBytes, common.RawBytes, error) { case Curve25519xSalsa20Poly1305: pubkey, privkey, err := box.GenerateKey(rand.Reader) if err != nil { - return nil, nil, common.NewBasicError(UnableToGenerateKeyPair, err, + return nil, nil, common.NewBasicError(ErrUnableToGenerateKeyPair, err, "algo", algo) } return pubkey[:], privkey[:], nil case Ed25519: pubkey, privkey, err := ed25519.GenerateKey(rand.Reader) if err != nil { - return nil, nil, common.NewBasicError(UnableToGenerateKeyPair, err, + return nil, nil, common.NewBasicError(ErrUnableToGenerateKeyPair, err, "algo", algo) } return common.RawBytes(pubkey), common.RawBytes(privkey), nil default: - return nil, nil, common.NewBasicError(UnsupportedAlgo, nil, "algo", algo) + return nil, nil, common.NewBasicError(ErrUnsupportedAlgo, nil, "algo", algo) } } @@ -100,12 +101,12 @@ func Sign(sigInput, signKey common.RawBytes, signAlgo string) (common.RawBytes, switch strings.ToLower(signAlgo) { case Ed25519: if len(signKey) != ed25519.PrivateKeySize { - return nil, common.NewBasicError(InvalidPrivKeySize, nil, "expected", + return nil, common.NewBasicError(ErrInvalidPrivKeySize, nil, "expected", ed25519.PrivateKeySize, "actual", len(signKey)) } return ed25519.Sign(ed25519.PrivateKey(signKey), sigInput), nil default: - return nil, common.NewBasicError(UnsupportedSignAlgo, nil, "algo", signAlgo) + return nil, common.NewBasicError(ErrUnsupportedSignAlgo, nil, "algo", signAlgo) } } @@ -115,22 +116,22 @@ func Verify(sigInput, sig, verifyKey common.RawBytes, signAlgo string) error { switch strings.ToLower(signAlgo) { case Ed25519: if len(verifyKey) != ed25519.PublicKeySize { - return common.NewBasicError(InvalidPubKeySize, nil, + return common.NewBasicError(ErrInvalidPubKeySize, nil, "expected", ed25519.PublicKeySize, "actual", len(verifyKey)) } if len(sig) != ed25519.SignatureSize { - return common.NewBasicError(InvalidSignatureSize, nil, + return common.NewBasicError(ErrInvalidSignatureSize, nil, "expected", ed25519.SignatureSize, "actual", len(sig)) } if sig[63]&224 != 0 { - return common.NewBasicError(InvalidSignatureFormat, nil) + return common.NewBasicError(ErrInvalidSignatureFormat, nil) } if !ed25519.Verify(ed25519.PublicKey(verifyKey), sigInput, sig) { - return common.NewBasicError(VerificationError, nil, "msg", sigInput) + return common.NewBasicError(ErrVerification, nil, "msg", sigInput) } return nil default: - return common.NewBasicError(UnsupportedSignAlgo, nil, "algo", signAlgo) + return common.NewBasicError(ErrUnsupportedSignAlgo, nil, "algo", signAlgo) } } @@ -146,7 +147,7 @@ func Encrypt(msg, nonce, pubkey, privkey common.RawBytes, algo string) (common.R } return box.Seal(nil, msg, nonceRaw, pubKeyRaw, privKeyRaw), nil default: - return nil, common.NewBasicError(UnsupportedEncAlgo, nil, "algo", algo) + return nil, common.NewBasicError(ErrUnsupportedEncAlgo, nil, "algo", algo) } } @@ -160,11 +161,11 @@ func Decrypt(msg, nonce, pubkey, privkey common.RawBytes, algo string) (common.R } dec, ok := box.Open(nil, msg, nonceRaw, pubKeyRaw, privKeyRaw) if !ok { - return nil, common.NewBasicError(UnableToDecrypt, nil, "algo", algo) + return nil, common.NewBasicError(ErrUnableToDecrypt, nil, "algo", algo) } return dec, nil default: - return nil, common.NewBasicError(UnsupportedEncAlgo, nil, "algo", algo) + return nil, common.NewBasicError(ErrUnsupportedEncAlgo, nil, "algo", algo) } } @@ -172,16 +173,16 @@ func prepNaClBox(nonce, pubkey, privkey common.RawBytes) (*[NaClBoxNonceSize]byt *[NaClBoxKeySize]byte, *[NaClBoxKeySize]byte, error) { if len(nonce) != NaClBoxNonceSize { - return nil, nil, nil, common.NewBasicError(InvalidNonceSize, nil, "algo", + return nil, nil, nil, common.NewBasicError(ErrInvalidNonceSize, nil, "algo", Curve25519xSalsa20Poly1305, "expected size", NaClBoxNonceSize, "actual size", len(nonce)) } if len(pubkey) != NaClBoxKeySize { - return nil, nil, nil, common.NewBasicError(InvalidPubKeySize, nil, "algo", + return nil, nil, nil, common.NewBasicError(ErrInvalidPubKeySize, nil, "algo", Curve25519xSalsa20Poly1305, "expected size", NaClBoxKeySize, "actual size", len(pubkey)) } if len(privkey) != NaClBoxKeySize { - return nil, nil, nil, common.NewBasicError(InvalidPrivKeySize, nil, "algo", + return nil, nil, nil, common.NewBasicError(ErrInvalidPrivKeySize, nil, "algo", Curve25519xSalsa20Poly1305, "expected size", NaClBoxKeySize, "actual size", len(privkey)) } diff --git a/go/lib/scrypto/cert/cert.go b/go/lib/scrypto/cert/cert.go index ffac063d55..2d60e4d78d 100644 --- a/go/lib/scrypto/cert/cert.go +++ b/go/lib/scrypto/cert/cert.go @@ -32,11 +32,11 @@ import ( ) const ( - EarlyUsage = "Certificate IssuingTime in the future" - Expired = "Certificate expired" - InvalidSubject = "Invalid subject" - ReservedVersion = "Invalid version 0" - UnableSigPack = "Cert: Unable to create signature input" + ErrEarlyUsage common.ErrMsg = "Certificate IssuingTime in the future" + ErrExpired common.ErrMsg = "Certificate expired" + ErrInvalidSubject common.ErrMsg = "Invalid subject" + ErrReservedVersion common.ErrMsg = "Invalid version 0" + ErrUnableSigPack common.ErrMsg = "Cert: Unable to create signature input" ) const ( @@ -91,7 +91,7 @@ func CertificateFromRaw(raw common.RawBytes) (*Certificate, error) { return nil, common.NewBasicError("Unable to parse Certificate", err) } if cert.Version.IsLatest() { - return nil, common.NewBasicError(ReservedVersion, nil) + return nil, common.NewBasicError(ErrReservedVersion, nil) } return cert, nil } @@ -101,7 +101,7 @@ func CertificateFromRaw(raw common.RawBytes) (*Certificate, error) { // subject, and that it is valid at the current time. func (c *Certificate) Verify(subject addr.IA, verifyKey common.RawBytes, signAlgo string) error { if !subject.Equal(c.Subject) { - return common.NewBasicError(InvalidSubject, nil, + return common.NewBasicError(ErrInvalidSubject, nil, "expected", c.Subject, "actual", subject) } if err := c.VerifyTime(util.TimeToSecs(time.Now())); err != nil { @@ -114,12 +114,12 @@ func (c *Certificate) Verify(subject addr.IA, verifyKey common.RawBytes, signAlg // not check the validity of the signature. func (c *Certificate) VerifyTime(ts uint32) error { if ts < c.IssuingTime { - return common.NewBasicError(EarlyUsage, nil, + return common.NewBasicError(ErrEarlyUsage, nil, "IssuingTime", util.SecsToCompact(c.IssuingTime), "current", util.SecsToCompact(ts)) } if ts > c.ExpirationTime { - return common.NewBasicError(Expired, nil, + return common.NewBasicError(ErrExpired, nil, "ExpirationTime", util.SecsToCompact(c.ExpirationTime), "current", util.SecsToCompact(ts)) } @@ -131,7 +131,7 @@ func (c *Certificate) VerifyTime(ts uint32) error { func (c *Certificate) VerifySignature(verifyKey common.RawBytes, signAlgo string) error { sigInput, err := c.sigPack() if err != nil { - return common.NewBasicError(UnableSigPack, err) + return common.NewBasicError(ErrUnableSigPack, err) } return scrypto.Verify(sigInput, c.Signature, verifyKey, signAlgo) } @@ -154,7 +154,7 @@ func (c *Certificate) Sign(signKey common.RawBytes, signAlgo string) error { // sigPack creates a sorted json object of all fields, except for the signature field. func (c *Certificate) sigPack() (common.RawBytes, error) { if c.Version.IsLatest() { - return nil, common.NewBasicError(ReservedVersion, nil) + return nil, common.NewBasicError(ErrReservedVersion, nil) } m := make(map[string]interface{}) m[canIssue] = c.CanIssue @@ -216,7 +216,7 @@ func (c *Certificate) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, certFields); err != nil { - return common.NewBasicError(UnableValidateFields, err) + return common.NewBasicError(ErrUnableValidateFields, err) } // XXX(roosd): Unmarshalling twice might affect performance. // After switching to go 1.10 we might make use of diff --git a/go/lib/scrypto/cert/chain.go b/go/lib/scrypto/cert/chain.go index a61d031151..67bc146c64 100644 --- a/go/lib/scrypto/cert/chain.go +++ b/go/lib/scrypto/cert/chain.go @@ -239,7 +239,7 @@ func (c *Chain) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, chainFields); err != nil { - return common.NewBasicError(UnableValidateFields, err) + return common.NewBasicError(ErrUnableValidateFields, err) } // XXX(roosd): Unmarshalling twice might affect performance. // After switching to go 1.10 we might make use of diff --git a/go/lib/scrypto/cert/json.go b/go/lib/scrypto/cert/json.go index 55a2371b13..39b0685b01 100644 --- a/go/lib/scrypto/cert/json.go +++ b/go/lib/scrypto/cert/json.go @@ -17,9 +17,9 @@ package cert import "github.com/scionproto/scion/go/lib/common" const ( - InvalidNumFields = "Invalid number of fields" - MissingField = "Missing json field" - UnableValidateFields = "Unable to validate fields" + ErrInvalidNumFields common.ErrMsg = "Invalid number of fields" + ErrMissingField common.ErrMsg = "Missing json field" + ErrUnableValidateFields common.ErrMsg = "Unable to validate fields" ) var certFields = []string{canIssue, comment, encAlgorithm, expirationTime, @@ -31,11 +31,11 @@ var chainFields = []string{"0", "1"} func validateFields(m map[string]interface{}, fields []string) error { for _, field := range fields { if _, ok := m[field]; !ok { - return common.NewBasicError(MissingField, nil, "field", field) + return common.NewBasicError(ErrMissingField, nil, "field", field) } } if len(m) != len(fields) { - return common.NewBasicError(InvalidNumFields, nil, + return common.NewBasicError(ErrInvalidNumFields, nil, "expected", len(fields), "actual", len(m)) } return nil diff --git a/go/lib/scrypto/cert/v2/BUILD.bazel b/go/lib/scrypto/cert/v2/BUILD.bazel index 8d9e2aed40..5fb51f1378 100644 --- a/go/lib/scrypto/cert/v2/BUILD.bazel +++ b/go/lib/scrypto/cert/v2/BUILD.bazel @@ -41,11 +41,13 @@ go_test( embed = [":go_default_library"], deps = [ "//go/lib/addr:go_default_library", + "//go/lib/common:go_default_library", "//go/lib/scrypto:go_default_library", "//go/lib/scrypto/trc/v2:go_default_library", "//go/lib/util:go_default_library", "//go/lib/xtest:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", + "@org_golang_x_xerrors//:go_default_library", ], ) diff --git a/go/lib/scrypto/cert/v2/as.go b/go/lib/scrypto/cert/v2/as.go index 79309ba60f..19de1466ec 100644 --- a/go/lib/scrypto/cert/v2/as.go +++ b/go/lib/scrypto/cert/v2/as.go @@ -25,12 +25,12 @@ import ( ) const ( - // WildcardIssuer indicates the issuer is a wildcard IA. - WildcardIssuer = "issuer.ia is wildcard" - // IssuerDifferentISD indicates that the issuing AS is in a different ISD. - IssuerDifferentISD = "issuing.ia in different ISD" - // InvalidCertificateType indicates the certificate type is invalid. - InvalidCertificateType = "invalid certificate_type" + // ErrWildcardIssuer indicates the issuer is a wildcard IA. + ErrWildcardIssuer common.ErrMsg = "issuer.ia is wildcard" + // ErrIssuerDifferentISD indicates that the issuing AS is in a different ISD. + ErrIssuerDifferentISD common.ErrMsg = "issuing.ia in different ISD" + // ErrInvalidCertificateType indicates the certificate type is invalid. + ErrInvalidCertificateType common.ErrMsg = "invalid certificate_type" ) var ( @@ -58,10 +58,10 @@ func (c *AS) Validate() error { return err } if c.Issuer.IA.IsWildcard() { - return common.NewBasicError(WildcardIssuer, nil, "issuer", c.Issuer.IA) + return common.NewBasicError(ErrWildcardIssuer, nil, "issuer", c.Issuer.IA) } if c.Subject.I != c.Issuer.IA.I { - return common.NewBasicError(IssuerDifferentISD, nil, + return common.NewBasicError(ErrIssuerDifferentISD, nil, "subject", c.Subject, "issuer", c.Issuer.IA) } return nil @@ -144,7 +144,7 @@ type TypeAS struct{} // UnmarshalText checks that the certificate type matches. func (TypeAS) UnmarshalText(b []byte) error { if TypeASJSON != string(b) { - return common.NewBasicError(InvalidCertificateType, nil, + return common.NewBasicError(ErrInvalidCertificateType, nil, "expected", TypeASJSON, "actual", string(b)) } return nil diff --git a/go/lib/scrypto/cert/v2/as_json_test.go b/go/lib/scrypto/cert/v2/as_json_test.go index 4aad4b128d..629db35089 100644 --- a/go/lib/scrypto/cert/v2/as_json_test.go +++ b/go/lib/scrypto/cert/v2/as_json_test.go @@ -68,7 +68,7 @@ func TestASUnmarshalJSON(t *testing.T) { Modify: func(g *genCert) { g.CertificateType = "issuer" }, - ExpectedErrMsg: cert.InvalidCertificateType, + ExpectedErrMsg: cert.ErrInvalidCertificateType.Error(), }, }, "Missing issuer.ia": { diff --git a/go/lib/scrypto/cert/v2/as_signed.go b/go/lib/scrypto/cert/v2/as_signed.go index d70e50dffb..5bfdeb4a0b 100644 --- a/go/lib/scrypto/cert/v2/as_signed.go +++ b/go/lib/scrypto/cert/v2/as_signed.go @@ -157,7 +157,7 @@ type SignatureTypeCertificate struct{} // UnmarshalText checks the signature type is correct. func (t *SignatureTypeCertificate) UnmarshalText(b []byte) error { if string(b) != SignatureTypeCertificateJSON { - return common.NewBasicError(InvalidSignatureType, nil, "input", string(b)) + return common.NewBasicError(ErrInvalidSignatureType, nil, "input", string(b)) } return nil } diff --git a/go/lib/scrypto/cert/v2/as_test.go b/go/lib/scrypto/cert/v2/as_test.go index 6277bb4f97..c3596fca9c 100644 --- a/go/lib/scrypto/cert/v2/as_test.go +++ b/go/lib/scrypto/cert/v2/as_test.go @@ -19,7 +19,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/scrypto" "github.com/scionproto/scion/go/lib/scrypto/cert/v2" @@ -28,7 +28,7 @@ import ( func TestASValidate(t *testing.T) { tests := map[string]struct { Modify func(*cert.AS) - ExpectedErrMsg string + ExpectedErrMsg error }{ "Valid": { Modify: func(_ *cert.AS) {}, @@ -46,7 +46,7 @@ func TestASValidate(t *testing.T) { Modify: func(c *cert.AS) { c.Subject.A = 0 }, - ExpectedErrMsg: cert.InvalidSubject, + ExpectedErrMsg: cert.ErrInvalidSubject, }, "Issuing Key": { Modify: func(c *cert.AS) { @@ -56,31 +56,31 @@ func TestASValidate(t *testing.T) { Key: []byte{2, 110, 1}, } }, - ExpectedErrMsg: cert.UnexpectedKey, + ExpectedErrMsg: cert.ErrUnexpectedKey, }, "No SigningKey": { Modify: func(c *cert.AS) { delete(c.Keys, cert.SigningKey) }, - ExpectedErrMsg: cert.MissingKey, + ExpectedErrMsg: cert.ErrMissingKey, }, "No EncryptionKey": { Modify: func(c *cert.AS) { delete(c.Keys, cert.EncryptionKey) }, - ExpectedErrMsg: cert.MissingKey, + ExpectedErrMsg: cert.ErrMissingKey, }, "Issuer ISD mismatch": { Modify: func(c *cert.AS) { c.Issuer.IA.I = c.Subject.I + 1 }, - ExpectedErrMsg: cert.IssuerDifferentISD, + ExpectedErrMsg: cert.ErrIssuerDifferentISD, }, "Wildcard Issuer": { Modify: func(c *cert.AS) { c.Issuer.IA.A = 0 }, - ExpectedErrMsg: cert.WildcardIssuer, + ExpectedErrMsg: cert.ErrWildcardIssuer, }, } for name, test := range tests { @@ -88,12 +88,7 @@ func TestASValidate(t *testing.T) { c := newASCert(time.Now()) test.Modify(&c) err := c.Validate() - if test.ExpectedErrMsg == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) - } + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) }) } } diff --git a/go/lib/scrypto/cert/v2/base.go b/go/lib/scrypto/cert/v2/base.go index dad9cc0b08..db7cdf2355 100644 --- a/go/lib/scrypto/cert/v2/base.go +++ b/go/lib/scrypto/cert/v2/base.go @@ -25,26 +25,26 @@ import ( // Parsing errors with context. const ( - // InvalidKeyType indicates an inexistent key type. - InvalidKeyType = "invalid key type" - // InvalidVersion indicates an invalid certificate version. - InvalidVersion = "Invalid certificate version" - // UnsupportedFormat indicates an invalid certificate format. - UnsupportedFormat = "Unsupported certificate format" + // ErrInvalidKeyType indicates an inexistent key type. + ErrInvalidKeyType common.ErrMsg = "invalid key type" + // ErrInvalidVersion indicates an invalid certificate version. + ErrInvalidVersion common.ErrMsg = "Invalid certificate version" + // ErrUnsupportedFormat indicates an invalid certificate format. + ErrUnsupportedFormat common.ErrMsg = "Unsupported certificate format" ) // Validation errors with context. const ( - // InvalidValidityPeriod indicates an invalid validity period. - InvalidValidityPeriod = "invalid validity period" - // InvalidSubject indicates that the subject contains a wildcard. - InvalidSubject = "subject contains wildcard" - // InvalidDistributionPoint indicates that the distribution point is a wildcard. - InvalidDistributionPoint = "distribution point contains wildcard" - // UnexpectedKey indicates that the certificate holds an excess key. - UnexpectedKey = "unexpected key" - // MissingKey indicates that the certificate is missing a key. - MissingKey = "missing key" + // ErrInvalidValidityPeriod indicates an invalid validity period. + ErrInvalidValidityPeriod common.ErrMsg = "invalid validity period" + // ErrInvalidSubject indicates that the subject contains a wildcard. + ErrInvalidSubject common.ErrMsg = "subject contains wildcard" + // ErrInvalidDistributionPoint indicates that the distribution point is a wildcard. + ErrInvalidDistributionPoint common.ErrMsg = "distribution point contains wildcard" + // ErrUnexpectedKey indicates that the certificate holds an excess key. + ErrUnexpectedKey common.ErrMsg = "unexpected key" + // ErrMissingKey indicates that the certificate is missing a key. + ErrMissingKey common.ErrMsg = "missing key" ) // Parsing errors. @@ -97,13 +97,13 @@ type Base struct { // Validate validates the shared fields are set correctly. func (b *Base) Validate() error { if b.Subject.IsWildcard() { - return common.NewBasicError(InvalidSubject, nil, "subject", b.Subject) + return common.NewBasicError(ErrInvalidSubject, nil, "subject", b.Subject) } if err := b.validateDistributionPoints(); err != nil { return err } if err := b.Validity.Validate(); err != nil { - return common.NewBasicError(InvalidValidityPeriod, err, "validity", b.Validity) + return common.NewBasicError(ErrInvalidValidityPeriod, err, "validity", b.Validity) } return nil } @@ -111,7 +111,7 @@ func (b *Base) Validate() error { func (b *Base) validateDistributionPoints() error { for _, ia := range b.OptionalDistributionPoints { if ia.IsWildcard() { - return common.NewBasicError(InvalidDistributionPoint, nil, "IA", ia) + return common.NewBasicError(ErrInvalidDistributionPoint, nil, "IA", ia) } } return nil @@ -133,10 +133,10 @@ func (b *Base) validateKeys(issuerCertificate bool) error { func (b *Base) checkKeyExistence(keyType KeyType, shouldExist bool) error { _, ok := b.Keys[keyType] if ok && !shouldExist { - return common.NewBasicError(UnexpectedKey, nil, "type", keyType) + return common.NewBasicError(ErrUnexpectedKey, nil, "type", keyType) } if !ok && shouldExist { - return common.NewBasicError(MissingKey, nil, "type", keyType) + return common.NewBasicError(ErrMissingKey, nil, "type", keyType) } return nil } @@ -198,7 +198,7 @@ func (t *KeyType) UnmarshalText(b []byte) error { case RevocationKeyJSON: *t = RevocationKey default: - return common.NewBasicError(InvalidKeyType, nil, "input", string(b)) + return common.NewBasicError(ErrInvalidKeyType, nil, "input", string(b)) } return nil } @@ -217,7 +217,7 @@ func (t KeyType) MarshalText() ([]byte, error) { case RevocationKey: return []byte(RevocationKeyJSON), nil } - return nil, common.NewBasicError(InvalidKeyType, nil, "type", int(t)) + return nil, common.NewBasicError(ErrInvalidKeyType, nil, "type", int(t)) } // FormatVersion indicates the certificate format version. Currently, only format @@ -231,7 +231,7 @@ func (v *FormatVersion) UnmarshalJSON(b []byte) error { return err } if parsed != 1 { - return common.NewBasicError(UnsupportedFormat, nil, "fmt", parsed) + return common.NewBasicError(ErrUnsupportedFormat, nil, "fmt", parsed) } *v = FormatVersion(parsed) return nil diff --git a/go/lib/scrypto/cert/v2/base_signed.go b/go/lib/scrypto/cert/v2/base_signed.go index 1e6b3beb9c..7fe2e06a31 100644 --- a/go/lib/scrypto/cert/v2/base_signed.go +++ b/go/lib/scrypto/cert/v2/base_signed.go @@ -22,10 +22,10 @@ import ( ) const ( - // InvalidCrit indicates that the value for the crit key is invalid. - InvalidCrit = "invalid crit" - // InvalidSignatureType indicates an invalid signature type. - InvalidSignatureType = "invalid signature type" + // ErrInvalidCrit indicates that the value for the crit key is invalid. + ErrInvalidCrit common.ErrMsg = "invalid crit" + // ErrInvalidSignatureType indicates an invalid signature type. + ErrInvalidSignatureType common.ErrMsg = "invalid signature type" ) var ( @@ -43,11 +43,11 @@ func checkCrit(b []byte, critFields []string) error { return err } if len(list) != len(critFields) { - return common.NewBasicError(InvalidCrit, nil, "len", len(list)) + return common.NewBasicError(ErrInvalidCrit, nil, "len", len(list)) } for i, expected := range critFields { if list[i] != expected { - return common.NewBasicError(InvalidCrit, nil, "idx", i, + return common.NewBasicError(ErrInvalidCrit, nil, "idx", i, "expected", expected, "actual", list[i]) } } diff --git a/go/lib/scrypto/cert/v2/base_test.go b/go/lib/scrypto/cert/v2/base_test.go index 049727bc84..c1f302222b 100644 --- a/go/lib/scrypto/cert/v2/base_test.go +++ b/go/lib/scrypto/cert/v2/base_test.go @@ -19,7 +19,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/addr" "github.com/scionproto/scion/go/lib/scrypto" @@ -36,7 +36,7 @@ var ( func TestBaseValidate(t *testing.T) { tests := map[string]struct { Modify func(*cert.Base) - ExpectedErrMsg string + ExpectedErrMsg error }{ "Valid": { Modify: func(_ *cert.Base) {}, @@ -45,25 +45,25 @@ func TestBaseValidate(t *testing.T) { Modify: func(c *cert.Base) { c.Subject.A = 0 }, - ExpectedErrMsg: cert.InvalidSubject, + ExpectedErrMsg: cert.ErrInvalidSubject, }, "Subject wildcard ISD": { Modify: func(c *cert.Base) { c.Subject.I = 0 }, - ExpectedErrMsg: cert.InvalidSubject, + ExpectedErrMsg: cert.ErrInvalidSubject, }, "DistributionPoint wildcard": { Modify: func(c *cert.Base) { c.OptionalDistributionPoints = append(c.OptionalDistributionPoints, addr.IA{I: 1}) }, - ExpectedErrMsg: cert.InvalidDistributionPoint, + ExpectedErrMsg: cert.ErrInvalidDistributionPoint, }, "Wrong validity period": { Modify: func(c *cert.Base) { c.Validity.NotAfter.Time = c.Validity.NotBefore.Time }, - ExpectedErrMsg: cert.InvalidValidityPeriod, + ExpectedErrMsg: cert.ErrInvalidValidityPeriod, }, } for name, test := range tests { @@ -71,12 +71,7 @@ func TestBaseValidate(t *testing.T) { c := newBaseCert(time.Now()) test.Modify(&c) err := c.Validate() - if test.ExpectedErrMsg == "" { - assert.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) - } + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) }) } } diff --git a/go/lib/scrypto/cert/v2/chain.go b/go/lib/scrypto/cert/v2/chain.go index a9528bbe20..623349a106 100644 --- a/go/lib/scrypto/cert/v2/chain.go +++ b/go/lib/scrypto/cert/v2/chain.go @@ -20,8 +20,8 @@ import ( "github.com/scionproto/scion/go/lib/common" ) -// InvalidChainLength indicates an invalid chain length. -const InvalidChainLength = "invalid chain length" +// ErrInvalidChainLength indicates an invalid chain length. +const ErrInvalidChainLength common.ErrMsg = "invalid chain length" // Chain represents the certificate chain. type Chain struct { @@ -45,7 +45,7 @@ func (c *Chain) UnmarshalJSON(b []byte) error { return err } if len(tmp) != 2 { - return common.NewBasicError(InvalidChainLength, nil, "expected", 2, "actual", len(tmp)) + return common.NewBasicError(ErrInvalidChainLength, nil, "expected", 2, "actual", len(tmp)) } return nil diff --git a/go/lib/scrypto/cert/v2/chain_json_test.go b/go/lib/scrypto/cert/v2/chain_json_test.go index 7eb2b261fe..4b8ea64ef2 100644 --- a/go/lib/scrypto/cert/v2/chain_json_test.go +++ b/go/lib/scrypto/cert/v2/chain_json_test.go @@ -76,7 +76,7 @@ func TestChainUnmarshalJSONError(t *testing.T) { } ] `, - ExpectedErrMsg: cert.InvalidChainLength, + ExpectedErrMsg: cert.ErrInvalidChainLength.Error(), }, "too long": { Input: ` @@ -98,7 +98,7 @@ func TestChainUnmarshalJSONError(t *testing.T) { } ] `, - ExpectedErrMsg: cert.InvalidChainLength, + ExpectedErrMsg: cert.ErrInvalidChainLength.Error(), }, } for name, test := range tests { diff --git a/go/lib/scrypto/cert/v2/issuer.go b/go/lib/scrypto/cert/v2/issuer.go index e1017f9555..52eeb87c32 100644 --- a/go/lib/scrypto/cert/v2/issuer.go +++ b/go/lib/scrypto/cert/v2/issuer.go @@ -124,7 +124,7 @@ type TypeIssuer struct{} // UnmarshalText checks that the certificate type matches. func (TypeIssuer) UnmarshalText(b []byte) error { if TypeIssuerJSON != string(b) { - return common.NewBasicError(InvalidCertificateType, nil, + return common.NewBasicError(ErrInvalidCertificateType, nil, "expected", TypeIssuerJSON, "actual", string(b)) } return nil diff --git a/go/lib/scrypto/cert/v2/issuer_json_test.go b/go/lib/scrypto/cert/v2/issuer_json_test.go index e303159944..dfdcd3ee98 100644 --- a/go/lib/scrypto/cert/v2/issuer_json_test.go +++ b/go/lib/scrypto/cert/v2/issuer_json_test.go @@ -68,7 +68,7 @@ func TestIssuerUnmarshalJSON(t *testing.T) { Modify: func(g *genCert) { g.CertificateType = "as" }, - ExpectedErrMsg: cert.InvalidCertificateType, + ExpectedErrMsg: cert.ErrInvalidCertificateType.Error(), }, }, "Missing issuer.trc_version": { diff --git a/go/lib/scrypto/cert/v2/issuer_signed.go b/go/lib/scrypto/cert/v2/issuer_signed.go index 384b0e4190..a95b1298a0 100644 --- a/go/lib/scrypto/cert/v2/issuer_signed.go +++ b/go/lib/scrypto/cert/v2/issuer_signed.go @@ -153,7 +153,7 @@ type SignatureTypeTRC struct{} // UnmarshalText checks the signature type is correct. func (t *SignatureTypeTRC) UnmarshalText(b []byte) error { if string(b) != SignatureTypeTRCJSON { - return common.NewBasicError(InvalidSignatureType, nil, "input", string(b)) + return common.NewBasicError(ErrInvalidSignatureType, nil, "input", string(b)) } return nil } diff --git a/go/lib/scrypto/cert/v2/issuer_test.go b/go/lib/scrypto/cert/v2/issuer_test.go index 57b70c2b9a..ebdb2689b6 100644 --- a/go/lib/scrypto/cert/v2/issuer_test.go +++ b/go/lib/scrypto/cert/v2/issuer_test.go @@ -19,7 +19,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/scrypto" "github.com/scionproto/scion/go/lib/scrypto/cert/v2" @@ -28,7 +28,7 @@ import ( func TestIssuerValidate(t *testing.T) { tests := map[string]struct { Modify func(*cert.Issuer) - ExpectedErrMsg string + ExpectedErrMsg error }{ "Valid": { Modify: func(_ *cert.Issuer) {}, @@ -46,13 +46,13 @@ func TestIssuerValidate(t *testing.T) { Modify: func(c *cert.Issuer) { c.Subject.A = 0 }, - ExpectedErrMsg: cert.InvalidSubject, + ExpectedErrMsg: cert.ErrInvalidSubject, }, "No Issuing Key": { Modify: func(c *cert.Issuer) { delete(c.Keys, cert.IssuingKey) }, - ExpectedErrMsg: cert.MissingKey, + ExpectedErrMsg: cert.ErrMissingKey, }, "SigningKey": { Modify: func(c *cert.Issuer) { @@ -62,7 +62,7 @@ func TestIssuerValidate(t *testing.T) { Key: []byte{2, 110, 1}, } }, - ExpectedErrMsg: cert.UnexpectedKey, + ExpectedErrMsg: cert.ErrUnexpectedKey, }, "EncryptionKey": { Modify: func(c *cert.Issuer) { @@ -72,7 +72,7 @@ func TestIssuerValidate(t *testing.T) { Key: []byte{1, 110, 1}, } }, - ExpectedErrMsg: cert.UnexpectedKey, + ExpectedErrMsg: cert.ErrUnexpectedKey, }, } for name, test := range tests { @@ -80,12 +80,7 @@ func TestIssuerValidate(t *testing.T) { c := newIssuerCert(time.Now()) test.Modify(&c) err := c.Validate() - if test.ExpectedErrMsg == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) - } + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) }) } } diff --git a/go/lib/scrypto/cert/v2/verify.go b/go/lib/scrypto/cert/v2/verify.go index 7700001bcd..382b0b5209 100644 --- a/go/lib/scrypto/cert/v2/verify.go +++ b/go/lib/scrypto/cert/v2/verify.go @@ -23,20 +23,20 @@ import ( ) const ( - // ASValidityNotCovered indicates the AS certificate's validity period is + // ErrASValidityNotCovered indicates the AS certificate's validity period is // not covered by the issuer certificate's validity period. - ASValidityNotCovered = "AS validity not covered" - // IssuerValidityNotCovered indicates the issuer certificate's validity + ErrASValidityNotCovered common.ErrMsg = "AS validity not covered" + // ErrIssuerValidityNotCovered indicates the issuer certificate's validity // period is not covered by the TRC's validity period. - IssuerValidityNotCovered = "AS validity not covered" - // UnexpectedIssuer indicates another issuer is expected. - UnexpectedIssuer = "wrong issuer" - // UnexpectedCertificateVersion indicates another issuer certificate version is expected. - UnexpectedCertificateVersion = "wrong certificate version" - // UnexpectedTRCVersion indicates another TRC version is expected. - UnexpectedTRCVersion = "wrong TRC version" - // InvalidProtected indicates an invalid protected meta. - InvalidProtected = "invalid protected meta" + ErrIssuerValidityNotCovered common.ErrMsg = "AS validity not covered" + // ErrUnexpectedIssuer indicates another issuer is expected. + ErrUnexpectedIssuer common.ErrMsg = "wrong issuer" + // ErrUnexpectedCertificateVersion indicates another issuer certificate version is expected. + ErrUnexpectedCertificateVersion common.ErrMsg = "wrong certificate version" + // ErrUnexpectedTRCVersion indicates another TRC version is expected. + ErrUnexpectedTRCVersion common.ErrMsg = "wrong TRC version" + // ErrInvalidProtected indicates an invalid protected meta. + ErrInvalidProtected common.ErrMsg = "invalid protected meta" ) var ( @@ -73,15 +73,15 @@ func (v ASVerifier) Verify() error { func (v ASVerifier) checkIssuer(p ProtectedAS) error { if !v.Issuer.Subject.Equal(v.AS.Issuer.IA) { - return common.NewBasicError(UnexpectedIssuer, nil, + return common.NewBasicError(ErrUnexpectedIssuer, nil, "expected", v.AS.Issuer.IA, "actual", v.Issuer.Subject) } if v.Issuer.Version != v.AS.Issuer.CertificateVersion { - return common.NewBasicError(UnexpectedCertificateVersion, nil, + return common.NewBasicError(ErrUnexpectedCertificateVersion, nil, "expected", v.AS.Issuer.CertificateVersion, "actual", v.Issuer.Version) } if !v.Issuer.Validity.Covers(*v.AS.Validity) { - return common.NewBasicError(ASValidityNotCovered, nil, + return common.NewBasicError(ErrASValidityNotCovered, nil, "issuer", v.Issuer.Validity, "as", v.AS.Validity) } expected := ProtectedAS{ @@ -90,7 +90,7 @@ func (v ASVerifier) checkIssuer(p ProtectedAS) error { IA: v.Issuer.Subject, } if p != expected { - return common.NewBasicError(InvalidProtected, nil, "expected", expected, "actual", p) + return common.NewBasicError(ErrInvalidProtected, nil, "expected", expected, "actual", p) } return nil } @@ -128,11 +128,11 @@ func (v IssuerVerifier) checkIssuer(p ProtectedIssuer) error { return ErrNotIssuing } if v.TRC.Version != v.Issuer.Issuer.TRCVersion { - return common.NewBasicError(UnexpectedTRCVersion, nil, + return common.NewBasicError(ErrUnexpectedTRCVersion, nil, "expected", v.Issuer.Issuer.TRCVersion, "actual", v.TRC.Version) } if !v.TRC.Validity.Covers(*v.Issuer.Validity) { - return common.NewBasicError(IssuerValidityNotCovered, nil, + return common.NewBasicError(ErrIssuerValidityNotCovered, nil, "trc", v.TRC.Validity, "issuer", v.Issuer.Validity) } expected := ProtectedIssuer{ @@ -140,7 +140,7 @@ func (v IssuerVerifier) checkIssuer(p ProtectedIssuer) error { TRCVersion: v.TRC.Version, } if p != expected { - return common.NewBasicError(InvalidProtected, nil, "expected", expected, "actual", p) + return common.NewBasicError(ErrInvalidProtected, nil, "expected", expected, "actual", p) } return nil } diff --git a/go/lib/scrypto/cert/v2/verify_test.go b/go/lib/scrypto/cert/v2/verify_test.go index 09be773f6a..c4f4dd3cf2 100644 --- a/go/lib/scrypto/cert/v2/verify_test.go +++ b/go/lib/scrypto/cert/v2/verify_test.go @@ -21,6 +21,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/scionproto/scion/go/lib/common" "github.com/scionproto/scion/go/lib/scrypto" "github.com/scionproto/scion/go/lib/scrypto/cert/v2" "github.com/scionproto/scion/go/lib/scrypto/trc/v2" @@ -31,7 +32,7 @@ func TestASVerifierVerify(t *testing.T) { tests := map[string]struct { Modify func(as *cert.AS, issuer *cert.Issuer, p *cert.ProtectedAS) ModifySigned func(signed *cert.SignedAS) - ExpectedErrMsg string + ExpectedErrMsg common.ErrMsg }{ "valid": { Modify: func(*cert.AS, *cert.Issuer, *cert.ProtectedAS) {}, @@ -49,14 +50,14 @@ func TestASVerifierVerify(t *testing.T) { issuer.Subject.A++ }, ModifySigned: func(*cert.SignedAS) {}, - ExpectedErrMsg: cert.UnexpectedIssuer, + ExpectedErrMsg: cert.ErrUnexpectedIssuer, }, "Issuer version mismatch": { Modify: func(_ *cert.AS, issuer *cert.Issuer, _ *cert.ProtectedAS) { issuer.Version++ }, ModifySigned: func(*cert.SignedAS) {}, - ExpectedErrMsg: cert.UnexpectedCertificateVersion, + ExpectedErrMsg: cert.ErrUnexpectedCertificateVersion, }, "Validity not covered": { Modify: func(cert *cert.AS, issuer *cert.Issuer, _ *cert.ProtectedAS) { @@ -64,28 +65,28 @@ func TestASVerifierVerify(t *testing.T) { issuer.Validity.NotAfter.Time = cert.Validity.NotAfter.Add(-time.Second) }, ModifySigned: func(*cert.SignedAS) {}, - ExpectedErrMsg: cert.ASValidityNotCovered, + ExpectedErrMsg: cert.ErrASValidityNotCovered, }, "Protected.IA mismatch": { Modify: func(_ *cert.AS, _ *cert.Issuer, p *cert.ProtectedAS) { p.IA.A++ }, ModifySigned: func(*cert.SignedAS) {}, - ExpectedErrMsg: cert.InvalidProtected, + ExpectedErrMsg: cert.ErrInvalidProtected, }, "Protected.Algorithm mismatch": { Modify: func(_ *cert.AS, _ *cert.Issuer, p *cert.ProtectedAS) { p.Algorithm = "other" }, ModifySigned: func(*cert.SignedAS) {}, - ExpectedErrMsg: cert.InvalidProtected, + ExpectedErrMsg: cert.ErrInvalidProtected, }, "Protected.CertificateVersion mismatch": { Modify: func(_ *cert.AS, _ *cert.Issuer, p *cert.ProtectedAS) { p.CertificateVersion++ }, ModifySigned: func(*cert.SignedAS) {}, - ExpectedErrMsg: cert.InvalidProtected, + ExpectedErrMsg: cert.ErrInvalidProtected, }, "Mangled signature": { Modify: func(*cert.AS, *cert.Issuer, *cert.ProtectedAS) {}, @@ -179,7 +180,7 @@ func TestIssuerVerifierVerify(t *testing.T) { trc.Version++ }, ModifySigned: func(*cert.SignedIssuer) {}, - ExpectedErrMsg: cert.UnexpectedTRCVersion, + ExpectedErrMsg: cert.ErrUnexpectedTRCVersion.Error(), }, "Validity not covered": { Modify: func(issuer *cert.Issuer, trc *trc.TRC, _ *cert.ProtectedIssuer) { @@ -187,21 +188,21 @@ func TestIssuerVerifierVerify(t *testing.T) { trc.Validity.NotAfter.Time = issuer.Validity.NotAfter.Time.Add(-time.Second) }, ModifySigned: func(*cert.SignedIssuer) {}, - ExpectedErrMsg: cert.ASValidityNotCovered, + ExpectedErrMsg: cert.ErrASValidityNotCovered.Error(), }, "Protected.Algorithm mismatch": { Modify: func(_ *cert.Issuer, _ *trc.TRC, p *cert.ProtectedIssuer) { p.Algorithm = "other" }, ModifySigned: func(*cert.SignedIssuer) {}, - ExpectedErrMsg: cert.InvalidProtected, + ExpectedErrMsg: cert.ErrInvalidProtected.Error(), }, "Protected.TRCVersion mismatch": { Modify: func(_ *cert.Issuer, _ *trc.TRC, p *cert.ProtectedIssuer) { p.TRCVersion++ }, ModifySigned: func(*cert.SignedIssuer) {}, - ExpectedErrMsg: cert.InvalidProtected, + ExpectedErrMsg: cert.ErrInvalidProtected.Error(), }, "Mangled signature": { Modify: func(*cert.Issuer, *trc.TRC, *cert.ProtectedIssuer) {}, diff --git a/go/lib/scrypto/mac.go b/go/lib/scrypto/mac.go index 959c8050b4..27dbd5d58d 100644 --- a/go/lib/scrypto/mac.go +++ b/go/lib/scrypto/mac.go @@ -26,8 +26,8 @@ import ( ) const ( - ErrorCipherFailure = "Unable to initialize AES cipher" - ErrorMacFailure = "Unable to initialize Mac" + ErrCipherFailure common.ErrMsg = "Unable to initialize AES cipher" + ErrMacFailure common.ErrMsg = "Unable to initialize Mac" ) var ( @@ -37,11 +37,11 @@ var ( func InitMac(key []byte) (hash.Hash, error) { block, err := aes.NewCipher(key) if err != nil { - return nil, common.NewBasicError(ErrorCipherFailure, err) + return nil, common.NewBasicError(ErrCipherFailure, err) } mac, err := cmac.New(block) if err != nil { - return nil, common.NewBasicError(ErrorMacFailure, err) + return nil, common.NewBasicError(ErrMacFailure, err) } return mac, nil } diff --git a/go/lib/scrypto/rand.go b/go/lib/scrypto/rand.go index 140211483e..3c5b236481 100644 --- a/go/lib/scrypto/rand.go +++ b/go/lib/scrypto/rand.go @@ -23,8 +23,8 @@ import ( ) const ( - InvalidNonceSize = "Invalid nonce size" - UnableToGenerateNonce = "Unable to generate nonce" + ErrInvalidNonceSize common.ErrMsg = "Invalid nonce size" + ErrUnableToGenerateNonce common.ErrMsg = "Unable to generate nonce" ) func init() { @@ -50,12 +50,12 @@ func RandInt64() int64 { // Nonce takes an input length and returns a random nonce of the given length. func Nonce(l int) (common.RawBytes, error) { if l <= 0 { - return nil, common.NewBasicError(InvalidNonceSize, nil) + return nil, common.NewBasicError(ErrInvalidNonceSize, nil) } nonce := make([]byte, l) _, err := io.ReadFull(rand.Reader, nonce) if err != nil { - return nil, common.NewBasicError(UnableToGenerateNonce, err) + return nil, common.NewBasicError(ErrUnableToGenerateNonce, err) } return nonce, nil } diff --git a/go/lib/scrypto/trc/entries.go b/go/lib/scrypto/trc/entries.go index 33509fa81b..bbce923dae 100644 --- a/go/lib/scrypto/trc/entries.go +++ b/go/lib/scrypto/trc/entries.go @@ -46,7 +46,7 @@ func (t *CoreAS) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, coreASFields); err != nil { - return common.NewBasicError(UnableValidateFields, err) + return common.NewBasicError(ErrUnableValidateFields, err) } return json.Unmarshal(b, (*Alias)(t)) } diff --git a/go/lib/scrypto/trc/json.go b/go/lib/scrypto/trc/json.go index f500a3c64f..e23ff5009b 100644 --- a/go/lib/scrypto/trc/json.go +++ b/go/lib/scrypto/trc/json.go @@ -17,9 +17,9 @@ package trc import "github.com/scionproto/scion/go/lib/common" const ( - InvalidNumFields = "Invalid number of fields" - MissingField = "Missing json field" - UnableValidateFields = "Unable to validate fields" + ErrInvalidNumFields common.ErrMsg = "Invalid number of fields" + ErrMissingField common.ErrMsg = "Missing json field" + ErrUnableValidateFields common.ErrMsg = "Unable to validate fields" ) var trcFields = []string{certLogs, coreASes, creationTime, description, @@ -31,11 +31,11 @@ var coreASFields = []string{"OfflineKey", "OfflineKeyAlg", "OnlineKey", "OnlineK func validateFields(m map[string]interface{}, fields []string) error { for _, field := range fields { if _, ok := m[field]; !ok { - return common.NewBasicError(MissingField, nil, "field", field) + return common.NewBasicError(ErrMissingField, nil, "field", field) } } if len(m) != len(fields) { - return common.NewBasicError(InvalidNumFields, nil, + return common.NewBasicError(ErrInvalidNumFields, nil, "expected", len(fields), "actual", len(m)) } return nil diff --git a/go/lib/scrypto/trc/trc.go b/go/lib/scrypto/trc/trc.go index 4a0e762de6..4bd9ab395f 100644 --- a/go/lib/scrypto/trc/trc.go +++ b/go/lib/scrypto/trc/trc.go @@ -35,20 +35,22 @@ import ( const ( MaxTRCByteLength uint32 = 1 << 20 +) - // Error strings - EarlyUsage = "Creation time in the future" - EarlyAnnouncement = "Early announcement" - Expired = "TRC expired" - GracePeriodPassed = "TRC grace period has passed" - InactiveVersion = "Inactive TRC version" - InvalidCreationTime = "Invalid TRC creation time" - InvalidISD = "Invalid TRC ISD" - InvalidQuorum = "Not enough valid signatures" - InvalidVersion = "Invalid TRC version" - ReservedVersion = "Invalid version 0" - SignatureMissing = "Signature missing" - UnableSigPack = "TRC: Unable to create signature input" +// Error strings +const ( + EarlyUsage common.ErrMsg = "Creation time in the future" + EarlyAnnouncement common.ErrMsg = "Early announcement" + Expired common.ErrMsg = "TRC expired" + GracePeriodPassed common.ErrMsg = "TRC grace period has passed" + InactiveVersion common.ErrMsg = "Inactive TRC version" + InvalidCreationTime common.ErrMsg = "Invalid TRC creation time" + InvalidISD common.ErrMsg = "Invalid TRC ISD" + InvalidQuorum common.ErrMsg = "Not enough valid signatures" + ErrInvalidVersion common.ErrMsg = "Invalid TRC version" + ReservedVersion common.ErrMsg = "Invalid version 0" + SignatureMissing common.ErrMsg = "Signature missing" + UnableSigPack common.ErrMsg = "TRC: Unable to create signature input" ) const ( @@ -287,7 +289,7 @@ func (t *TRC) verifyUpdate(old *TRC) (*TRCVerResult, error) { return nil, common.NewBasicError(InvalidISD, nil, "expected", old.ISD, "actual", t.ISD) } if old.Version+1 != t.Version { - return nil, common.NewBasicError(InvalidVersion, nil, + return nil, common.NewBasicError(ErrInvalidVersion, nil, "expected", old.Version+1, "actual", t.Version) } if t.CreationTime < old.CreationTime+old.GracePeriod { @@ -410,7 +412,7 @@ func (t *TRC) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, trcFields); err != nil { - return common.NewBasicError(UnableValidateFields, err) + return common.NewBasicError(ErrUnableValidateFields, err) } // XXX(roosd): Unmarshalling twice might affect performance. // After switching to go 1.10 we might make use of diff --git a/go/lib/scrypto/trc/v2/BUILD.bazel b/go/lib/scrypto/trc/v2/BUILD.bazel index 0316927944..f496f13a9d 100644 --- a/go/lib/scrypto/trc/v2/BUILD.bazel +++ b/go/lib/scrypto/trc/v2/BUILD.bazel @@ -42,5 +42,6 @@ go_test( "//go/lib/xtest:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", + "@org_golang_x_xerrors//:go_default_library", ], ) diff --git a/go/lib/scrypto/trc/v2/keychanges.go b/go/lib/scrypto/trc/v2/keychanges.go index f6a6a6d45c..39e8cacbab 100644 --- a/go/lib/scrypto/trc/v2/keychanges.go +++ b/go/lib/scrypto/trc/v2/keychanges.go @@ -23,10 +23,10 @@ import ( ) const ( - // InvalidKeyMeta indicates an invalid key metadata. - InvalidKeyMeta = "invalid key meta" - // InvalidKeyVersion indicates an invalid key version. - InvalidKeyVersion = "invalid key_version" + // ErrInvalidKeyMeta indicates an invalid key metadata. + ErrInvalidKeyMeta common.ErrMsg = "invalid key meta" + // ErrInvalidKeyVersion indicates an invalid key version. + ErrInvalidKeyVersion common.ErrMsg = "invalid key_version" ) // ASToKeyMeta maps an AS to its key metadata for a single key type. @@ -69,7 +69,7 @@ func (c *KeyChanges) insertModifications(as addr.AS, prev, next PrimaryAS) error } modified, err := ValidateKeyUpdate(prevMeta, meta) if err != nil { - return common.NewBasicError(InvalidKeyMeta, err, "as", as, "key_type", keyType) + return common.NewBasicError(ErrInvalidKeyMeta, err, "as", as, "key_type", keyType) } if modified { c.Modified[keyType][as] = meta @@ -86,10 +86,10 @@ func ValidateKeyUpdate(prev, next scrypto.KeyMeta) (bool, error) { modified := next.Algorithm != prev.Algorithm || !bytes.Equal(next.Key, prev.Key) switch { case modified && next.KeyVersion != prev.KeyVersion+1: - return modified, common.NewBasicError(InvalidKeyVersion, nil, "modified", modified, + return modified, common.NewBasicError(ErrInvalidKeyVersion, nil, "modified", modified, "expected", prev.KeyVersion+1, "actual", next.KeyVersion) case !modified && next.KeyVersion != prev.KeyVersion: - return modified, common.NewBasicError(InvalidKeyVersion, nil, "modified", modified, + return modified, common.NewBasicError(ErrInvalidKeyVersion, nil, "modified", modified, "expected", prev.KeyVersion, "actual", next.KeyVersion) } return modified, nil diff --git a/go/lib/scrypto/trc/v2/pop.go b/go/lib/scrypto/trc/v2/pop.go index 927edd168e..ca10bf0b3c 100644 --- a/go/lib/scrypto/trc/v2/pop.go +++ b/go/lib/scrypto/trc/v2/pop.go @@ -21,10 +21,10 @@ import ( ) const ( - // MissingProofOfPossession indicates that the proof_of_possession is missing. - MissingProofOfPossession = "missing proof_of_possession" - // UnexpectedProofOfPossession indicates an unexpected proof_of_possession. - UnexpectedProofOfPossession = "unexpected proof_of_possession" + // ErrMissingProofOfPossession indicates that the proof_of_possession is missing. + ErrMissingProofOfPossession common.ErrMsg = "missing proof_of_possession" + // ErrUnexpectedProofOfPossession indicates an unexpected proof_of_possession. + ErrUnexpectedProofOfPossession common.ErrMsg = "unexpected proof_of_possession" ) type keyTypeSet map[KeyType]struct{} @@ -52,7 +52,7 @@ func (v *popValidator) checkProofOfPossession() error { } for as, types := range v.pops { if len(types) > 0 { - return common.NewBasicError(UnexpectedProofOfPossession, nil, + return common.NewBasicError(ErrUnexpectedProofOfPossession, nil, "as", as, "key_types", types) } } @@ -73,7 +73,7 @@ func (v *popValidator) popForModType(changes map[KeyType]ASToKeyMeta) error { func (v *popValidator) popForKeyType(keyType KeyType, m map[addr.AS]scrypto.KeyMeta) error { for as := range m { if !v.hasPop(v.TRC.ProofOfPossession[as], keyType) { - return common.NewBasicError(MissingProofOfPossession, nil, + return common.NewBasicError(ErrMissingProofOfPossession, nil, "as", as, "key_type", keyType) } delete(v.pops[as], keyType) diff --git a/go/lib/scrypto/trc/v2/primary.go b/go/lib/scrypto/trc/v2/primary.go index d84bbf6011..dbd68381a8 100644 --- a/go/lib/scrypto/trc/v2/primary.go +++ b/go/lib/scrypto/trc/v2/primary.go @@ -26,29 +26,29 @@ import ( // Parsing errors with context. const ( - // InvalidKeyType indicates an inexistent key type. - InvalidKeyType = "invalid key type" - // InvalidAttribute indicates an inexistent attribute. - InvalidAttribute = "invalid attribute" - // InvalidAttributesSize indicates invalid number of attributes in the attributes list. - InvalidAttributesSize = "invalid attributes size" - // DuplicateAttributes indicates attribute duplication in the attributes list. - DuplicateAttributes = "duplicate attributes" + // ErrInvalidKeyType indicates an inexistent key type. + ErrInvalidKeyType common.ErrMsg = "invalid key type" + // ErrInvalidAttribute indicates an inexistent attribute. + ErrInvalidAttribute common.ErrMsg = "invalid attribute" + // ErrInvalidAttributesSize indicates invalid number of attributes in the attributes list. + ErrInvalidAttributesSize common.ErrMsg = "invalid attributes size" + // ErrDuplicateAttributes indicates attribute duplication in the attributes list. + ErrDuplicateAttributes common.ErrMsg = "duplicate attributes" ) // Invariant errors const ( - // AuthoritativeButNotCore indicates a primary AS that is authoritative but not core. - AuthoritativeButNotCore = "authoritative but not core" - // UnexpectedKey indicates that a primary AS has an excess key. Voting ASes must + // ErrAuthoritativeButNotCore indicates a primary AS that is authoritative but not core. + ErrAuthoritativeButNotCore common.ErrMsg = "authoritative but not core" + // ErrUnexpectedKey indicates that a primary AS has an excess key. Voting ASes must // have an online and offline key. Non-Voting ASes must not have an offline // key. Issuer ASes must have an online key. Core-only ASes must not have // any key. - UnexpectedKey = "unexpected key" - // MissingKey indicates that the primary AS is missing a key. - MissingKey = "missing key" - // InvalidPrimaryAS indicates an invalid primary AS entry. - InvalidPrimaryAS = "invalid primary as entry" + ErrUnexpectedKey common.ErrMsg = "unexpected key" + // ErrMissingKey indicates that the primary AS is missing a key. + ErrMissingKey common.ErrMsg = "missing key" + // ErrInvalidPrimaryAS indicates an invalid primary AS entry. + ErrInvalidPrimaryAS common.ErrMsg = "invalid primary as entry" ) // Parsing errors @@ -66,7 +66,7 @@ type PrimaryASes map[addr.AS]PrimaryAS func (p *PrimaryASes) ValidateInvariant() error { for as, primary := range *p { if err := primary.ValidateInvariant(); err != nil { - return common.NewBasicError(InvalidPrimaryAS, err, "as", as) + return common.NewBasicError(ErrInvalidPrimaryAS, err, "as", as) } } return nil @@ -134,10 +134,10 @@ func (p *PrimaryAS) ValidateInvariant() error { func (p *PrimaryAS) checkKeyExistence(keyType KeyType, shouldExist bool) error { _, ok := p.Keys[keyType] if ok && !shouldExist { - return common.NewBasicError(UnexpectedKey, nil, "key_type", keyType) + return common.NewBasicError(ErrUnexpectedKey, nil, "key_type", keyType) } if !ok && shouldExist { - return common.NewBasicError(MissingKey, nil, "key_type", keyType) + return common.NewBasicError(ErrMissingKey, nil, "key_type", keyType) } return nil } @@ -171,7 +171,7 @@ type Attributes []Attribute // Validate checks that the attributes list is valid. func (t *Attributes) Validate() error { if len(*t) > 4 || len(*t) <= 0 { - return common.NewBasicError(InvalidAttributesSize, nil, "len", len(*t)) + return common.NewBasicError(ErrInvalidAttributesSize, nil, "len", len(*t)) } var core, authoritative bool for i := 0; i < len(*t); i++ { @@ -179,12 +179,12 @@ func (t *Attributes) Validate() error { authoritative = authoritative || (*t)[i] == Authoritative for j := i + 1; j < len(*t); j++ { if (*t)[i] == (*t)[j] { - return common.NewBasicError(DuplicateAttributes, nil, "attribute", (*t)[i]) + return common.NewBasicError(ErrDuplicateAttributes, nil, "attribute", (*t)[i]) } } } if authoritative && !core { - return common.NewBasicError(AuthoritativeButNotCore, nil) + return common.NewBasicError(ErrAuthoritativeButNotCore, nil) } return nil } @@ -233,7 +233,7 @@ func (t *Attribute) UnmarshalText(b []byte) error { case Core: *t = Core default: - return common.NewBasicError(InvalidAttribute, nil, "input", string(b)) + return common.NewBasicError(ErrInvalidAttribute, nil, "input", string(b)) } return nil } @@ -270,7 +270,7 @@ func (t *KeyType) UnmarshalText(b []byte) error { case IssuingKeyJSON: *t = IssuingKey default: - return common.NewBasicError(InvalidKeyType, nil, "input", string(b)) + return common.NewBasicError(ErrInvalidKeyType, nil, "input", string(b)) } return nil @@ -288,5 +288,5 @@ func (t KeyType) MarshalText() ([]byte, error) { case IssuingKey: return []byte(IssuingKeyJSON), nil } - return nil, common.NewBasicError(InvalidKeyType, nil, "key_type", int(t)) + return nil, common.NewBasicError(ErrInvalidKeyType, nil, "key_type", int(t)) } diff --git a/go/lib/scrypto/trc/v2/primary_json_test.go b/go/lib/scrypto/trc/v2/primary_json_test.go index a002032b13..4f908afdaf 100644 --- a/go/lib/scrypto/trc/v2/primary_json_test.go +++ b/go/lib/scrypto/trc/v2/primary_json_test.go @@ -102,7 +102,7 @@ func TestPrimaryASUnmarshalJSON(t *testing.T) { } } }`, - ExpectedErrMsg: trc.InvalidKeyType, + ExpectedErrMsg: trc.ErrInvalidKeyType.Error(), }, } for name, test := range tests { diff --git a/go/lib/scrypto/trc/v2/primary_test.go b/go/lib/scrypto/trc/v2/primary_test.go index c8bb74af49..1d54c57798 100644 --- a/go/lib/scrypto/trc/v2/primary_test.go +++ b/go/lib/scrypto/trc/v2/primary_test.go @@ -18,7 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/scrypto" trc "github.com/scionproto/scion/go/lib/scrypto/trc/v2" @@ -159,7 +159,7 @@ func TestPrimaryASesCount(t *testing.T) { func TestPrimaryASValidateInvariant(t *testing.T) { tests := map[string]struct { Primary trc.PrimaryAS - ExpectedErrMsg string + ExpectedErrMsg error }{ "Non-Core and Authoritative": { Primary: trc.PrimaryAS{ @@ -169,7 +169,7 @@ func TestPrimaryASValidateInvariant(t *testing.T) { trc.OfflineKey: {}, }, }, - ExpectedErrMsg: trc.AuthoritativeButNotCore, + ExpectedErrMsg: trc.ErrAuthoritativeButNotCore, }, "Voting AS without online key": { Primary: trc.PrimaryAS{ @@ -178,7 +178,7 @@ func TestPrimaryASValidateInvariant(t *testing.T) { trc.OfflineKey: {}, }, }, - ExpectedErrMsg: trc.MissingKey, + ExpectedErrMsg: trc.ErrMissingKey, }, "Voting AS without offline key": { Primary: trc.PrimaryAS{ @@ -187,7 +187,7 @@ func TestPrimaryASValidateInvariant(t *testing.T) { trc.OnlineKey: {}, }, }, - ExpectedErrMsg: trc.MissingKey, + ExpectedErrMsg: trc.ErrMissingKey, }, "Voting AS with issuing key": { Primary: trc.PrimaryAS{ @@ -198,14 +198,14 @@ func TestPrimaryASValidateInvariant(t *testing.T) { trc.IssuingKey: {}, }, }, - ExpectedErrMsg: trc.UnexpectedKey, + ExpectedErrMsg: trc.ErrUnexpectedKey, }, "Issuer AS without issuing key": { Primary: trc.PrimaryAS{ Attributes: trc.Attributes{trc.Issuing}, Keys: make(map[trc.KeyType]scrypto.KeyMeta), }, - ExpectedErrMsg: trc.MissingKey, + ExpectedErrMsg: trc.ErrMissingKey, }, "Issuer AS with online key": { Primary: trc.PrimaryAS{ @@ -215,7 +215,7 @@ func TestPrimaryASValidateInvariant(t *testing.T) { trc.IssuingKey: {}, }, }, - ExpectedErrMsg: trc.UnexpectedKey, + ExpectedErrMsg: trc.ErrUnexpectedKey, }, "Valid Core": { Primary: trc.PrimaryAS{ @@ -258,12 +258,7 @@ func TestPrimaryASValidateInvariant(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { err := test.Primary.ValidateInvariant() - if test.ExpectedErrMsg == "" { - assert.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) - } + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) }) } } diff --git a/go/lib/scrypto/trc/v2/signed.go b/go/lib/scrypto/trc/v2/signed.go index df0184e78f..6a280d05a4 100644 --- a/go/lib/scrypto/trc/v2/signed.go +++ b/go/lib/scrypto/trc/v2/signed.go @@ -26,10 +26,10 @@ import ( ) const ( - // InvalidCrit indicates that the value for the crit key is invalid. - InvalidCrit = "invalid crit" - // InvalidSignatureType indicates an invalid signature type. - InvalidSignatureType = "invalid signature type" + // ErrInvalidCrit indicates that the value for the crit key is invalid. + ErrInvalidCrit common.ErrMsg = "invalid crit" + // ErrInvalidSignatureType indicates an invalid signature type. + ErrInvalidSignatureType common.ErrMsg = "invalid signature type" ) var ( @@ -202,7 +202,7 @@ func (t *SignatureType) UnmarshalText(b []byte) error { case VoteSignature: *t = VoteSignature default: - return common.NewBasicError(InvalidSignatureType, nil, "input", string(b)) + return common.NewBasicError(ErrInvalidSignatureType, nil, "input", string(b)) } return nil } @@ -225,11 +225,11 @@ func (c Crit) UnmarshalJSON(b []byte) error { return err } if len(list) != len(allCritFields) { - return common.NewBasicError(InvalidCrit, nil, "len", len(list)) + return common.NewBasicError(ErrInvalidCrit, nil, "len", len(list)) } for i, expected := range allCritFields { if list[i] != expected { - return common.NewBasicError(InvalidCrit, nil, "idx", i, + return common.NewBasicError(ErrInvalidCrit, nil, "idx", i, "expected", expected, "actual", list[i]) } } diff --git a/go/lib/scrypto/trc/v2/trc.go b/go/lib/scrypto/trc/v2/trc.go index e1e7349133..3768c852b4 100644 --- a/go/lib/scrypto/trc/v2/trc.go +++ b/go/lib/scrypto/trc/v2/trc.go @@ -28,17 +28,17 @@ import ( // Invariant errors with context const ( - // InvariantViolation indicates a TRC invariant violation. - InvariantViolation = "TRC invariant violation" - // InvalidValidityPeriod indicates an invalid validity period. - InvalidValidityPeriod = "invalid validity period" - // VotingQuorumTooLarge indicates that the number of voting ASes is smaller + // ErrInvariantViolation indicates a TRC invariant violation. + ErrInvariantViolation common.ErrMsg = "TRC invariant violation" + // ErrInvalidValidityPeriod indicates an invalid validity period. + ErrInvalidValidityPeriod common.ErrMsg = "invalid validity period" + // ErrVotingQuorumTooLarge indicates that the number of voting ASes is smaller // than the voting quorum. - VotingQuorumTooLarge = "voting quorum too large" + ErrVotingQuorumTooLarge common.ErrMsg = "voting quorum too large" ) -// UnsupportedFormat indicates an invalid TRC format. -const UnsupportedFormat = "unsupported TRC format" +// ErrUnsupportedFormat indicates an invalid TRC format. +const ErrUnsupportedFormat common.ErrMsg = "unsupported TRC format" // Invariant errors var ( @@ -159,14 +159,15 @@ func (t *TRC) Base() bool { // ValidateInvariant ensures that the TRC invariant holds. func (t *TRC) ValidateInvariant() error { if err := t.Validity.Validate(); err != nil { - return common.NewBasicError(InvalidValidityPeriod, err, "validity", t.Validity) + return common.NewBasicError(ErrInvalidValidityPeriod, err, "validity", t.Validity) } if t.VotingQuorum() <= 0 { return ErrZeroVotingQuorum } c := t.PrimaryASes.Count(Voting) if t.VotingQuorum() > c { - return common.NewBasicError(VotingQuorumTooLarge, nil, "max", c, "actual", t.VotingQuorum) + return common.NewBasicError(ErrVotingQuorumTooLarge, nil, + "max", c, "actual", t.VotingQuorum) } if t.PrimaryASes.Count(Issuing) <= 0 { return ErrNoIssuingAS @@ -298,7 +299,7 @@ func (v *FormatVersion) UnmarshalJSON(b []byte) error { return err } if parsed != 1 { - return common.NewBasicError(UnsupportedFormat, nil, "fmt", parsed) + return common.NewBasicError(ErrUnsupportedFormat, nil, "fmt", parsed) } *v = FormatVersion(parsed) return nil diff --git a/go/lib/scrypto/trc/v2/trc_test.go b/go/lib/scrypto/trc/v2/trc_test.go index 3b4bc4007b..a7ffd652fb 100644 --- a/go/lib/scrypto/trc/v2/trc_test.go +++ b/go/lib/scrypto/trc/v2/trc_test.go @@ -19,6 +19,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/addr" "github.com/scionproto/scion/go/lib/scrypto" @@ -41,7 +42,7 @@ var ( func TestTRCValidateInvariant(t *testing.T) { tests := map[string]struct { Modify func(base *trc.TRC) - ExpectedErrMsg string + ExpectedErrMsg error }{ "Valid invariant": { Modify: func(_ *trc.TRC) {}, @@ -50,7 +51,7 @@ func TestTRCValidateInvariant(t *testing.T) { Modify: func(base *trc.TRC) { base.Validity.NotAfter.Time = base.Validity.NotBefore.Time }, - ExpectedErrMsg: trc.InvalidValidityPeriod, + ExpectedErrMsg: trc.ErrInvalidValidityPeriod, }, "No Issuing AS": { Modify: func(base *trc.TRC) { @@ -61,51 +62,51 @@ func TestTRCValidateInvariant(t *testing.T) { delete(base.PrimaryASes, a130) delete(base.ProofOfPossession, a130) }, - ExpectedErrMsg: trc.ErrNoIssuingAS.Error(), + ExpectedErrMsg: trc.ErrNoIssuingAS, }, "Zero VotingQuorum": { Modify: func(base *trc.TRC) { quorum := uint8(0) base.VotingQuorumPtr = &quorum }, - ExpectedErrMsg: trc.ErrZeroVotingQuorum.Error(), + ExpectedErrMsg: trc.ErrZeroVotingQuorum, }, "VotingQuorum larger than voting ASes": { Modify: func(base *trc.TRC) { quorum := uint8(base.PrimaryASes.Count(trc.Voting) + 1) base.VotingQuorumPtr = &quorum }, - ExpectedErrMsg: trc.VotingQuorumTooLarge, + ExpectedErrMsg: trc.ErrVotingQuorumTooLarge, }, "PrimaryASes invariant violated": { Modify: func(base *trc.TRC) { delete(base.PrimaryASes[a110].Keys, trc.OfflineKey) }, - ExpectedErrMsg: trc.MissingKey, + ExpectedErrMsg: trc.ErrMissingKey, }, "Zero GracePeriod, TRCVersion != BaseVersion": { Modify: func(base *trc.TRC) { base.Version = 2 }, - ExpectedErrMsg: trc.ErrUpdateWithZeroGracePeriod.Error(), + ExpectedErrMsg: trc.ErrUpdateWithZeroGracePeriod, }, "Non-Zero GracePeriod, TRCVersion == BaseVersion": { Modify: func(base *trc.TRC) { base.GracePeriod = &trc.Period{Duration: time.Hour} }, - ExpectedErrMsg: trc.ErrBaseWithNonZeroGracePeriod.Error(), + ExpectedErrMsg: trc.ErrBaseWithNonZeroGracePeriod, }, "Base missing AS in pops": { Modify: func(base *trc.TRC) { delete(base.ProofOfPossession, a130) }, - ExpectedErrMsg: trc.MissingProofOfPossession, + ExpectedErrMsg: trc.ErrMissingProofOfPossession, }, "Base missing pop for AS": { Modify: func(base *trc.TRC) { base.ProofOfPossession[a110] = base.ProofOfPossession[a110][:1] }, - ExpectedErrMsg: trc.MissingProofOfPossession, + ExpectedErrMsg: trc.ErrMissingProofOfPossession, }, "Base with votes": { Modify: func(base *trc.TRC) { @@ -114,19 +115,19 @@ func TestTRCValidateInvariant(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.ErrBaseWithVotes.Error(), + ExpectedErrMsg: trc.ErrBaseWithVotes, }, "Base pop for unexpected key": { Modify: func(base *trc.TRC) { base.ProofOfPossession[a130] = append(base.ProofOfPossession[a130], trc.OnlineKey) }, - ExpectedErrMsg: trc.UnexpectedProofOfPossession, + ExpectedErrMsg: trc.ErrUnexpectedProofOfPossession, }, "Base pop from unexpected AS": { Modify: func(base *trc.TRC) { base.ProofOfPossession[a190] = []trc.KeyType{trc.OnlineKey} }, - ExpectedErrMsg: trc.UnexpectedProofOfPossession, + ExpectedErrMsg: trc.ErrUnexpectedProofOfPossession, }, } for name, test := range tests { @@ -134,12 +135,7 @@ func TestTRCValidateInvariant(t *testing.T) { base := newBaseTRC(time.Now()) test.Modify(base) err := base.ValidateInvariant() - if test.ExpectedErrMsg == "" { - assert.NoError(t, err) - } else { - assert.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) - } + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) }) } } diff --git a/go/lib/scrypto/trc/v2/update.go b/go/lib/scrypto/trc/v2/update.go index 53f20241c6..b98bca7102 100644 --- a/go/lib/scrypto/trc/v2/update.go +++ b/go/lib/scrypto/trc/v2/update.go @@ -23,33 +23,33 @@ import ( // Update validation errors with context. const ( - // ImmutableBaseVersion indicates an invalid update to the base_version. - ImmutableBaseVersion = "base_version is immutable" - // ImmutableISD indicates an invalid update to the ISD identifier. - ImmutableISD = "isd is immutable" - // ImmutableTrustResetAllowed indicates an invalid update to trust_reset_allowed. - ImmutableTrustResetAllowed = "trust_reset_allowed is immutable" - // InvalidVersionIncrement indicates an invalid version increment. - InvalidVersionIncrement = "TRC version must be incremented by one" - // MissingVote indicates an AS has not cast vote during a regular update + // ErrImmutableBaseVersion indicates an invalid update to the base_version. + ErrImmutableBaseVersion common.ErrMsg = "base_version is immutable" + // ErrImmutableISD indicates an invalid update to the ISD identifier. + ErrImmutableISD common.ErrMsg = "isd is immutable" + // ErrImmutableTrustResetAllowed indicates an invalid update to trust_reset_allowed. + ErrImmutableTrustResetAllowed common.ErrMsg = "trust_reset_allowed is immutable" + // ErrInvalidVersionIncrement indicates an invalid version increment. + ErrInvalidVersionIncrement common.ErrMsg = "TRC version must be incremented by one" + // ErrMissingVote indicates an AS has not cast vote during a regular update // that changes its online key. - MissingVote = "missing vote" - // NotInsidePreviousValidityPeriod indicates the validity periods do not overlap. - NotInsidePreviousValidityPeriod = "not inside previous validity period" - // QuorumUnmet indicates that not enough votes have been cast. - QuorumUnmet = "voting_quorum unmet" - // WrongVotingKeyType indicates the vote is cast with the wrong key type. - WrongVotingKeyType = "vote with wrong key type" - // WrongVotingKeyVersion indicates the vote is cast with the wrong key version - WrongVotingKeyVersion = "vote with wrong key version" + ErrMissingVote common.ErrMsg = "missing vote" + // ErrNotInsidePreviousValidityPeriod indicates the validity periods do not overlap. + ErrNotInsidePreviousValidityPeriod common.ErrMsg = "not inside previous validity period" + // ErrQuorumUnmet indicates that not enough votes have been cast. + ErrQuorumUnmet common.ErrMsg = "voting_quorum unmet" + // ErrWrongVotingKeyType indicates the vote is cast with the wrong key type. + ErrWrongVotingKeyType common.ErrMsg = "vote with wrong key type" + // ErrWrongVotingKeyVersion indicates the vote is cast with the wrong key version + ErrWrongVotingKeyVersion common.ErrMsg = "vote with wrong key version" ) // Update validation error wrappers. const ( - // InvalidVote indicates an invalid vote. - InvalidVote = "invalid vote" - // SanityCheckError indicates a sanity check error. - SanityCheckError = "sanity check error" + // ErrInvalidVote indicates an invalid vote. + ErrInvalidVote common.ErrMsg = "invalid vote" + // ErrSanityCheck indicates a sanity check error. + ErrSanityCheck common.ErrMsg = "sanity check error" ) // Update validation errors. @@ -84,7 +84,7 @@ type UpdateValidator struct { // attribute changes are returned. func (v *UpdateValidator) Validate() (UpdateInfo, error) { if err := v.sanity(); err != nil { - return UpdateInfo{}, common.NewBasicError(SanityCheckError, err) + return UpdateInfo{}, common.NewBasicError(ErrSanityCheck, err) } keyChanges, err := v.keyChanges() if err != nil { @@ -110,25 +110,26 @@ func (v *UpdateValidator) sanity() error { return ErrBaseNotUpdate } if err := v.Next.ValidateInvariant(); err != nil { - return common.NewBasicError(InvariantViolation, err) + return common.NewBasicError(ErrInvariantViolation, err) } if v.Next.ISD != v.Prev.ISD { - return common.NewBasicError(ImmutableISD, nil, "expected", v.Prev.ISD, "actual", v.Next.ISD) + return common.NewBasicError(ErrImmutableISD, nil, + "expected", v.Prev.ISD, "actual", v.Next.ISD) } if v.Next.TrustResetAllowed() != v.Prev.TrustResetAllowed() { - return common.NewBasicError(ImmutableTrustResetAllowed, nil, "expected", + return common.NewBasicError(ErrImmutableTrustResetAllowed, nil, "expected", v.Prev.TrustResetAllowed, "actual", v.Next.TrustResetAllowed) } if v.Next.Version != v.Prev.Version+1 { - return common.NewBasicError(InvalidVersionIncrement, nil, "expected", v.Prev.Version+1, + return common.NewBasicError(ErrInvalidVersionIncrement, nil, "expected", v.Prev.Version+1, "actual", v.Next.Version) } if v.Next.BaseVersion != v.Prev.BaseVersion { - return common.NewBasicError(ImmutableBaseVersion, nil, "expected", v.Prev.BaseVersion, + return common.NewBasicError(ErrImmutableBaseVersion, nil, "expected", v.Prev.BaseVersion, "actual", v.Next.BaseVersion) } if !v.Prev.Validity.Contains(v.Next.Validity.NotBefore.Time) { - return common.NewBasicError(NotInsidePreviousValidityPeriod, nil, + return common.NewBasicError(ErrNotInsidePreviousValidityPeriod, nil, "previous validity", v.Prev.Validity, "not_before", v.Next.Validity.NotBefore) } return nil @@ -186,7 +187,7 @@ func (v *UpdateValidator) checkVotes(info UpdateInfo) error { } } if len(v.Next.Votes) < v.Prev.VotingQuorum() { - return common.NewBasicError(QuorumUnmet, nil, + return common.NewBasicError(ErrQuorumUnmet, nil, "min", v.Prev.VotingQuorum(), "actual", len(v.Next.Votes)) } return nil @@ -200,13 +201,13 @@ func (v *UpdateValidator) checkVotesRegular(info UpdateInfo) error { expectedKeyType = OfflineKey } if err := v.hasVotingRights(as, vote, expectedKeyType); err != nil { - return common.NewBasicError(InvalidVote, err, "as", as, "vote", vote) + return common.NewBasicError(ErrInvalidVote, err, "as", as, "vote", vote) } } // Check all ASes with changed online key have cast a vote. for as := range info.KeyChanges.Modified[OnlineKey] { if _, ok := v.Next.Votes[as]; !ok { - return common.NewBasicError(MissingVote, nil, "as", as) + return common.NewBasicError(ErrMissingVote, nil, "as", as) } } return nil @@ -216,7 +217,7 @@ func (v *UpdateValidator) checkVotesSensitive(info UpdateInfo) error { // Check all votes from voting ASes with offline keys. for as, vote := range v.Next.Votes { if err := v.hasVotingRights(as, vote, OfflineKey); err != nil { - return common.NewBasicError(InvalidVote, err, "as", as, "vote", vote) + return common.NewBasicError(ErrInvalidVote, err, "as", as, "vote", vote) } } return nil @@ -231,11 +232,11 @@ func (v *UpdateValidator) hasVotingRights(as addr.AS, vote Vote, keyType KeyType return ErrNoVotingRight } if vote.KeyType != keyType { - return common.NewBasicError(WrongVotingKeyType, nil, + return common.NewBasicError(ErrWrongVotingKeyType, nil, "expected", keyType, "actual", vote.KeyType) } if primary.Keys[keyType].KeyVersion != vote.KeyVersion { - return common.NewBasicError(WrongVotingKeyVersion, nil, + return common.NewBasicError(ErrWrongVotingKeyVersion, nil, "expected", primary.Keys[keyType].KeyVersion, "actual", vote.KeyVersion) } return nil diff --git a/go/lib/scrypto/trc/v2/update_test.go b/go/lib/scrypto/trc/v2/update_test.go index cba0ecb1d6..d2edbffe4f 100644 --- a/go/lib/scrypto/trc/v2/update_test.go +++ b/go/lib/scrypto/trc/v2/update_test.go @@ -19,7 +19,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/addr" "github.com/scionproto/scion/go/lib/scrypto" @@ -31,38 +31,38 @@ import ( func TestCommonUpdate(t *testing.T) { tests := map[string]struct { Modify func(updated, prev *trc.TRC) - ExpectedErrMsg string + ExpectedErrMsg error }{ "Trust reset": { Modify: func(updated, _ *trc.TRC) { *updated = *newBaseTRC(time.Now()) updated.BaseVersion = updated.Version }, - ExpectedErrMsg: trc.ErrBaseNotUpdate.Error(), + ExpectedErrMsg: trc.ErrBaseNotUpdate, }, "Invariant violation": { Modify: func(updated, _ *trc.TRC) { updated.Validity.NotAfter = updated.Validity.NotBefore }, - ExpectedErrMsg: trc.InvalidValidityPeriod, + ExpectedErrMsg: trc.ErrInvalidValidityPeriod, }, "Wrong ISD": { Modify: func(updated, _ *trc.TRC) { updated.ISD = updated.ISD + 1 }, - ExpectedErrMsg: trc.ImmutableISD, + ExpectedErrMsg: trc.ErrImmutableISD, }, "Wrong Version": { Modify: func(updated, prev *trc.TRC) { updated.Version = prev.Version + 2 }, - ExpectedErrMsg: trc.InvalidVersionIncrement, + ExpectedErrMsg: trc.ErrInvalidVersionIncrement, }, "Changed TrustResetAllowed": { Modify: func(updated, prev *trc.TRC) { *updated.TrustResetAllowedPtr = !prev.TrustResetAllowed() }, - ExpectedErrMsg: trc.ImmutableTrustResetAllowed, + ExpectedErrMsg: trc.ErrImmutableTrustResetAllowed, }, "New NotBefore not in Validity": { Modify: func(updated, prev *trc.TRC) { @@ -71,7 +71,7 @@ func TestCommonUpdate(t *testing.T) { NotAfter: util.UnixTime{Time: prev.Validity.NotAfter.Add(8760 * time.Hour)}, } }, - ExpectedErrMsg: trc.NotInsidePreviousValidityPeriod, + ExpectedErrMsg: trc.ErrNotInsidePreviousValidityPeriod, }, "Changed BaseVersion": { Modify: func(updated, prev *trc.TRC) { @@ -79,7 +79,7 @@ func TestCommonUpdate(t *testing.T) { updated.Version = 6 updated.BaseVersion = 2 }, - ExpectedErrMsg: trc.ImmutableBaseVersion, + ExpectedErrMsg: trc.ErrImmutableBaseVersion, }, } for name, test := range tests { @@ -91,12 +91,9 @@ func TestCommonUpdate(t *testing.T) { Next: updated, } info, err := v.Validate() - if test.ExpectedErrMsg == "" { - require.NoError(t, err) + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) + if test.ExpectedErrMsg == nil { assert.Equal(t, ut, info.Type) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) } } t.Run(name+" (regular)", func(t *testing.T) { @@ -117,7 +114,7 @@ func TestSensitiveUpdate(t *testing.T) { tests := map[string]struct { Modify func(updated, prev *trc.TRC) Info trc.UpdateInfo - ExpectedErrMsg string + ExpectedErrMsg error }{ // Valid updates @@ -351,19 +348,19 @@ func TestSensitiveUpdate(t *testing.T) { Modify: func(updated, _ *trc.TRC) { *updated.VotingQuorumPtr = 0 }, - ExpectedErrMsg: trc.ErrZeroVotingQuorum.Error(), + ExpectedErrMsg: trc.ErrZeroVotingQuorum, }, "VotingQuorum larger than voting ASes": { Modify: func(updated, _ *trc.TRC) { *updated.VotingQuorumPtr = uint8(updated.PrimaryASes.Count(trc.Voting) + 1) }, - ExpectedErrMsg: trc.VotingQuorumTooLarge, + ExpectedErrMsg: trc.ErrVotingQuorumTooLarge, }, "Underflow voting quorum": { Modify: func(updated, _ *trc.TRC) { delete(updated.PrimaryASes, a140) }, - ExpectedErrMsg: trc.VotingQuorumTooLarge, + ExpectedErrMsg: trc.ErrVotingQuorumTooLarge, }, "Vote quorum too small": { Modify: func(updated, _ *trc.TRC) { @@ -372,7 +369,7 @@ func TestSensitiveUpdate(t *testing.T) { delete(updated.Votes, a120) delete(updated.Votes, a140) }, - ExpectedErrMsg: trc.QuorumUnmet, + ExpectedErrMsg: trc.ErrQuorumUnmet, }, "New Voting AS that does not sign with offline key": { Modify: func(updated, _ *trc.TRC) { @@ -393,7 +390,7 @@ func TestSensitiveUpdate(t *testing.T) { } updated.ProofOfPossession[a190] = []trc.KeyType{trc.OnlineKey} }, - ExpectedErrMsg: trc.MissingProofOfPossession, + ExpectedErrMsg: trc.ErrMissingProofOfPossession, }, "New Voting AS that does not sign with online key": { Modify: func(updated, _ *trc.TRC) { @@ -414,7 +411,7 @@ func TestSensitiveUpdate(t *testing.T) { } updated.ProofOfPossession[a190] = []trc.KeyType{trc.OnlineKey} }, - ExpectedErrMsg: trc.MissingProofOfPossession, + ExpectedErrMsg: trc.ErrMissingProofOfPossession, }, "Promoted Issuing AS has no key": { Modify: func(updated, _ *trc.TRC) { @@ -422,7 +419,7 @@ func TestSensitiveUpdate(t *testing.T) { primary.Attributes = append(primary.Attributes, trc.Issuing) updated.PrimaryASes[a150] = primary }, - ExpectedErrMsg: trc.MissingKey, + ExpectedErrMsg: trc.ErrMissingKey, }, "Demoted AS keeps offline key": { Modify: func(updated, _ *trc.TRC) { @@ -431,14 +428,14 @@ func TestSensitiveUpdate(t *testing.T) { primary.Attributes = trc.Attributes{trc.Issuing, trc.Core} updated.PrimaryASes[a110] = primary }, - ExpectedErrMsg: trc.UnexpectedKey, + ExpectedErrMsg: trc.ErrUnexpectedKey, }, "Unexpected proof of possession": { Modify: func(updated, _ *trc.TRC) { *updated.VotingQuorumPtr -= 1 updated.ProofOfPossession[a110] = []trc.KeyType{trc.OnlineKey} }, - ExpectedErrMsg: trc.UnexpectedProofOfPossession, + ExpectedErrMsg: trc.ErrUnexpectedProofOfPossession, }, "Update offline key without proof of possession": { Modify: func(updated, _ *trc.TRC) { @@ -448,7 +445,7 @@ func TestSensitiveUpdate(t *testing.T) { Key: []byte{1, 110, 2}, } }, - ExpectedErrMsg: trc.MissingProofOfPossession, + ExpectedErrMsg: trc.ErrMissingProofOfPossession, }, "Increase offline key version without modification": { Modify: func(updated, _ *trc.TRC) { @@ -458,7 +455,7 @@ func TestSensitiveUpdate(t *testing.T) { updated.ProofOfPossession[a110] = append(updated.ProofOfPossession[a110], trc.OfflineKey) }, - ExpectedErrMsg: trc.InvalidKeyVersion, + ExpectedErrMsg: trc.ErrInvalidKeyVersion, }, "Modify offline key without increasing version": { Modify: func(updated, _ *trc.TRC) { @@ -468,7 +465,7 @@ func TestSensitiveUpdate(t *testing.T) { updated.ProofOfPossession[a110] = append(updated.ProofOfPossession[a110], trc.OfflineKey) }, - ExpectedErrMsg: trc.InvalidKeyVersion, + ExpectedErrMsg: trc.ErrInvalidKeyVersion, }, "Increase offline key version by 2": { Modify: func(updated, _ *trc.TRC) { @@ -479,7 +476,7 @@ func TestSensitiveUpdate(t *testing.T) { updated.ProofOfPossession[a110] = append(updated.ProofOfPossession[a110], trc.OfflineKey) }, - ExpectedErrMsg: trc.InvalidKeyVersion, + ExpectedErrMsg: trc.ErrInvalidKeyVersion, }, "Signature from non-Voting AS": { Modify: func(updated, _ *trc.TRC) { @@ -489,7 +486,7 @@ func TestSensitiveUpdate(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.ErrNoVotingRight.Error(), + ExpectedErrMsg: trc.ErrNoVotingRight, }, "Signature from unknown AS": { Modify: func(updated, _ *trc.TRC) { @@ -501,7 +498,7 @@ func TestSensitiveUpdate(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.ErrUnexpectedVote.Error(), + ExpectedErrMsg: trc.ErrUnexpectedVote, }, "Wrong KeyType on Vote": { Modify: func(updated, _ *trc.TRC) { @@ -511,7 +508,7 @@ func TestSensitiveUpdate(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.WrongVotingKeyType, + ExpectedErrMsg: trc.ErrWrongVotingKeyType, }, "Wrong KeyVersion": { Modify: func(updated, _ *trc.TRC) { @@ -521,7 +518,7 @@ func TestSensitiveUpdate(t *testing.T) { KeyVersion: 10, } }, - ExpectedErrMsg: trc.WrongVotingKeyVersion, + ExpectedErrMsg: trc.ErrWrongVotingKeyVersion, }, } for name, test := range tests { @@ -533,15 +530,12 @@ func TestSensitiveUpdate(t *testing.T) { Next: updated, } info, err := v.Validate() - if test.ExpectedErrMsg == "" { - require.NoError(t, err) + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) + if test.ExpectedErrMsg == nil { assert.Equal(t, trc.SensitiveUpdate, info.Type) initKeyChanges(&test.Info) assert.Equal(t, test.Info.KeyChanges, info.KeyChanges) //assert.Equal(t, test.Info, info) - } else { - assert.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) } }) } @@ -551,7 +545,7 @@ func TestRegularUpdate(t *testing.T) { tests := map[string]struct { Modify func(updated, prev *trc.TRC) Info trc.UpdateInfo - ExpectedErrMsg string + ExpectedErrMsg error }{ // Valid updates @@ -631,7 +625,7 @@ func TestRegularUpdate(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.ErrUnexpectedVote.Error(), + ExpectedErrMsg: trc.ErrUnexpectedVote, }, "Signature from non-Voting AS": { Modify: func(updated, prev *trc.TRC) { @@ -640,7 +634,7 @@ func TestRegularUpdate(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.ErrNoVotingRight.Error(), + ExpectedErrMsg: trc.ErrNoVotingRight, }, "Wrong KeyType": { Modify: func(updated, _ *trc.TRC) { @@ -649,7 +643,7 @@ func TestRegularUpdate(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.WrongVotingKeyType, + ExpectedErrMsg: trc.ErrWrongVotingKeyType, }, "Wrong KeyVersion": { Modify: func(updated, _ *trc.TRC) { @@ -658,13 +652,13 @@ func TestRegularUpdate(t *testing.T) { KeyVersion: 10, } }, - ExpectedErrMsg: trc.WrongVotingKeyVersion, + ExpectedErrMsg: trc.ErrWrongVotingKeyVersion, }, "Signature Quorum too small": { Modify: func(updated, _ *trc.TRC) { delete(updated.Votes, a140) }, - ExpectedErrMsg: trc.QuorumUnmet, + ExpectedErrMsg: trc.ErrQuorumUnmet, }, "Missing proof of possession": { Modify: func(updated, _ *trc.TRC) { @@ -678,13 +672,13 @@ func TestRegularUpdate(t *testing.T) { KeyVersion: 1, } }, - ExpectedErrMsg: trc.MissingProofOfPossession, + ExpectedErrMsg: trc.ErrMissingProofOfPossession, }, "Unexpected proof of possession": { Modify: func(updated, _ *trc.TRC) { updated.ProofOfPossession[a110] = []trc.KeyType{trc.IssuingKey} }, - ExpectedErrMsg: trc.UnexpectedProofOfPossession, + ExpectedErrMsg: trc.ErrUnexpectedProofOfPossession, }, "Update online key with online vote": { Modify: func(updated, _ *trc.TRC) { @@ -695,7 +689,7 @@ func TestRegularUpdate(t *testing.T) { } updated.ProofOfPossession[a110] = []trc.KeyType{trc.OnlineKey} }, - ExpectedErrMsg: trc.WrongVotingKeyType, + ExpectedErrMsg: trc.ErrWrongVotingKeyType, }, "Update online key without any vote": { Modify: func(updated, prev *trc.TRC) { @@ -709,7 +703,7 @@ func TestRegularUpdate(t *testing.T) { updated.ProofOfPossession[a110] = []trc.KeyType{trc.OnlineKey} delete(updated.Votes, a110) }, - ExpectedErrMsg: trc.MissingVote, + ExpectedErrMsg: trc.ErrMissingVote, }, } for name, test := range tests { @@ -721,15 +715,12 @@ func TestRegularUpdate(t *testing.T) { Next: updated, } info, err := v.Validate() - if test.ExpectedErrMsg == "" { - require.NoError(t, err) + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) + if test.ExpectedErrMsg == nil { assert.Equal(t, trc.RegularUpdate, info.Type) initKeyChanges(&test.Info) assert.Equal(t, test.Info.KeyChanges, info.KeyChanges) //assert.Equal(t, test.Info, info) - } else { - assert.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) } }) } diff --git a/go/lib/scrypto/trc/v2/verify.go b/go/lib/scrypto/trc/v2/verify.go index d787121f8f..56559d03ac 100644 --- a/go/lib/scrypto/trc/v2/verify.go +++ b/go/lib/scrypto/trc/v2/verify.go @@ -21,27 +21,27 @@ import ( ) const ( - // DecodeProtectedFailed indicates the signatrue metadata fails to decode. - DecodeProtectedFailed = "unable to decode protected signature metadata" - // UnexpectedVoteSignature indicates an unexpected voting signature. - UnexpectedVoteSignature = "unexpected vote signature" - // UnexpectedPOPSignature indicates an unexpected proof of possession signature. - UnexpectedPOPSignature = "unexpected proof of possession signature" - // InvalidProtected indicates that the protected signature metadata is invalid. - InvalidProtected = "invalid protected signature metadata" - // MissingVoteSignature indicates a voting signature of an AS is missing. - MissingVoteSignature = "missing vote signature" - // MissingPOPSignature indicates a missing proof of possession signature. - MissingPOPSignature = "missing proof of possession signature" - // VoteVerificationError indicates the signature verification of a vote failed. - VoteVerificationError = "vote signature verification error" - // POPVerificationError indicates the signature verification of a proof of possession failed. - POPVerificationError = "proof of possession signature verification error" - // DuplicateVoteSignature indicates a duplicate voting signature for the same AS. - DuplicateVoteSignature = "duplicate vote signature" - // DuplicatePOPSignature indicates a duplicate proof of possession signature + // ErrDecodeProtectedFailed indicates the signatrue metadata fails to decode. + ErrDecodeProtectedFailed common.ErrMsg = "unable to decode protected signature metadata" + // ErrUnexpectedVoteSignature indicates an unexpected voting signature. + ErrUnexpectedVoteSignature common.ErrMsg = "unexpected vote signature" + // ErrUnexpectedPOPSignature indicates an unexpected proof of possession signature. + ErrUnexpectedPOPSignature common.ErrMsg = "unexpected proof of possession signature" + // ErrInvalidProtected indicates that the protected signature metadata is invalid. + ErrInvalidProtected common.ErrMsg = "invalid protected signature metadata" + // ErrErrMissingVoteSignature indicates a voting signature of an AS is missing. + ErrErrMissingVoteSignature common.ErrMsg = "missing vote signature" + // ErrMissingPOPSignature indicates a missing proof of possession signature. + ErrMissingPOPSignature common.ErrMsg = "missing proof of possession signature" + // ErrVoteVerification indicates the signature verification of a vote failed. + ErrVoteVerification common.ErrMsg = "vote signature verification error" + // ErrPOPVerification indicates the signature verification of a proof of possession failed. + ErrPOPVerification common.ErrMsg = "proof of possession signature verification error" + // ErrDuplicateVoteSignature indicates a duplicate voting signature for the same AS. + ErrDuplicateVoteSignature common.ErrMsg = "duplicate vote signature" + // ErrDuplicatePOPSignature indicates a duplicate proof of possession signature // for the same AS and key type. - DuplicatePOPSignature = "duplicate proof of possession signature" + ErrDuplicatePOPSignature common.ErrMsg = "duplicate proof of possession signature" ) // Votes maps ASes to their decoded vote. @@ -69,7 +69,7 @@ type UpdateVerifier struct { func (v UpdateVerifier) Verify() error { votes, pops, err := decodeSignatures(v.Signatures) if err != nil { - return common.NewBasicError(DecodeProtectedFailed, err) + return common.NewBasicError(ErrDecodeProtectedFailed, err) } pv := popVerifier{ TRC: v.Next, @@ -95,7 +95,7 @@ func (v UpdateVerifier) checkVotes(votes Votes) error { for as, sig := range votes { vote, ok := v.Next.Votes[as] if !ok { - return common.NewBasicError(UnexpectedVoteSignature, nil, "as", as) + return common.NewBasicError(ErrUnexpectedVoteSignature, nil, "as", as) } expected := Protected{ Algorithm: v.Prev.PrimaryASes[as].Keys[vote.KeyType].Algorithm, @@ -105,13 +105,13 @@ func (v UpdateVerifier) checkVotes(votes Votes) error { AS: as, } if sig.Protected != expected { - return common.NewBasicError(InvalidProtected, nil, + return common.NewBasicError(ErrInvalidProtected, nil, "expected", expected, "actual", sig.Protected) } } for as := range v.Next.Votes { if _, ok := votes[as]; !ok { - return common.NewBasicError(MissingVoteSignature, nil, "as", as) + return common.NewBasicError(ErrErrMissingVoteSignature, nil, "as", as) } } return nil @@ -122,7 +122,7 @@ func (v UpdateVerifier) verifyVotes(votes Votes) error { meta := v.Prev.PrimaryASes[as].Keys[sig.Protected.KeyType] input := SigInput(sig.EncodedProtected, v.NextEncoded) if err := scrypto.Verify(input, sig.Signature, meta.Key, meta.Algorithm); err != nil { - return common.NewBasicError(VoteVerificationError, err, "as", as, "meta", meta) + return common.NewBasicError(ErrVoteVerification, err, "as", as, "meta", meta) } } return nil @@ -145,7 +145,7 @@ type POPVerifier struct { func (v POPVerifier) Verify() error { _, pops, err := decodeSignatures(v.Signatures) if err != nil { - return common.NewBasicError(DecodeProtectedFailed, err) + return common.NewBasicError(ErrDecodeProtectedFailed, err) } pv := popVerifier{ TRC: v.TRC, @@ -171,7 +171,7 @@ func (v *popVerifier) check() error { for as, pops := range v.signatures { for _, sig := range pops { if !containsKeyType(sig.Protected.KeyType, v.TRC.ProofOfPossession[as]) { - return common.NewBasicError(UnexpectedPOPSignature, nil, + return common.NewBasicError(ErrUnexpectedPOPSignature, nil, "as", as, "key_type", sig.Protected.KeyType) } meta := v.TRC.PrimaryASes[as].Keys[sig.Protected.KeyType] @@ -183,7 +183,7 @@ func (v *popVerifier) check() error { AS: as, } if sig.Protected != expected { - return common.NewBasicError(InvalidProtected, nil, + return common.NewBasicError(ErrInvalidProtected, nil, "expected", expected, "actual", sig.Protected) } } @@ -191,7 +191,8 @@ func (v *popVerifier) check() error { for as, keyTypes := range v.TRC.ProofOfPossession { for _, keyType := range keyTypes { if _, ok := v.signatures[as][keyType]; !ok { - return common.NewBasicError(MissingPOPSignature, nil, "as", as, "key_type", keyType) + return common.NewBasicError(ErrMissingPOPSignature, nil, + "as", as, "key_type", keyType) } } } @@ -204,7 +205,7 @@ func (v *popVerifier) verify() error { meta := v.TRC.PrimaryASes[as].Keys[keyType] input := SigInput(sig.EncodedProtected, v.Encoded) if err := scrypto.Verify(input, sig.Signature, meta.Key, meta.Algorithm); err != nil { - return common.NewBasicError(POPVerificationError, err, + return common.NewBasicError(ErrPOPVerification, err, "as", as, "key_type", keyType) } } @@ -238,13 +239,13 @@ func decodeSignatures(signatures []Signature) (Votes, POPs, error) { switch sig.Protected.Type { case VoteSignature: if _, ok := votes[sig.Protected.AS]; ok { - return nil, nil, common.NewBasicError(DuplicateVoteSignature, nil, + return nil, nil, common.NewBasicError(ErrDuplicateVoteSignature, nil, "as", sig.Protected.AS) } votes[sig.Protected.AS] = sig case POPSignature: if _, ok := pops[sig.Protected.AS][sig.Protected.KeyType]; ok { - return nil, nil, common.NewBasicError(DuplicatePOPSignature, nil, + return nil, nil, common.NewBasicError(ErrDuplicatePOPSignature, nil, "as", sig.Protected.AS, "key_type", sig.Protected.KeyType) } if _, ok := pops[sig.Protected.AS]; !ok { diff --git a/go/lib/scrypto/trc/v2/verify_test.go b/go/lib/scrypto/trc/v2/verify_test.go index ce356152cc..357bf8a0fb 100644 --- a/go/lib/scrypto/trc/v2/verify_test.go +++ b/go/lib/scrypto/trc/v2/verify_test.go @@ -30,7 +30,7 @@ import ( type verifyTestCase struct { Modify func(*testing.T, *[]trc.Signature) - ExpectedErrMsg string + ExpectedErrMsg common.ErrMsg } var ( @@ -64,21 +64,21 @@ var ( "de2a08ae2a09de2a091"), }) }, - ExpectedErrMsg: trc.UnexpectedPOPSignature, + ExpectedErrMsg: trc.ErrUnexpectedPOPSignature, }, "Duplicate proof of possession": { Modify: func(t *testing.T, sigs *[]trc.Signature) { i := findSignature(t, *sigs, a110, trc.POPSignature) *sigs = append((*sigs), (*sigs)[i]) }, - ExpectedErrMsg: trc.DuplicatePOPSignature, + ExpectedErrMsg: trc.ErrDuplicatePOPSignature, }, "Missing proof of possession": { Modify: func(t *testing.T, sigs *[]trc.Signature) { i := findSignature(t, *sigs, a110, trc.POPSignature) *sigs = append((*sigs)[:i], (*sigs)[i+1:]...) }, - ExpectedErrMsg: trc.MissingPOPSignature, + ExpectedErrMsg: trc.ErrMissingPOPSignature, }, "Proof of possession wrong Algorithm": { Modify: func(t *testing.T, sigs *[]trc.Signature) { @@ -87,7 +87,7 @@ var ( p.Algorithm = "invalid" }) }, - ExpectedErrMsg: trc.InvalidProtected, + ExpectedErrMsg: trc.ErrInvalidProtected, }, // A wrong KeyType would be caught by a previous check. "Proof of possession wrong KeyVersion": { @@ -97,14 +97,14 @@ var ( p.KeyVersion += 1 }) }, - ExpectedErrMsg: trc.InvalidProtected, + ExpectedErrMsg: trc.ErrInvalidProtected, }, "Mangled proof of possession signature": { Modify: func(t *testing.T, sigs *[]trc.Signature) { sig := &(*sigs)[findSignature(t, *sigs, a110, trc.POPSignature)] sig.Signature[0] ^= 0xFF }, - ExpectedErrMsg: trc.POPVerificationError, + ExpectedErrMsg: trc.ErrPOPVerification, }, } @@ -126,21 +126,21 @@ var ( "0e2a08ee2a08ae2a09be2a09de2a081e2a09ee2a0a5e2a097e2a091"), }) }, - ExpectedErrMsg: trc.UnexpectedVoteSignature, + ExpectedErrMsg: trc.ErrUnexpectedVoteSignature, }, "Duplicate vote": { Modify: func(t *testing.T, sigs *[]trc.Signature) { i := findSignature(t, *sigs, a110, trc.VoteSignature) *sigs = append((*sigs), (*sigs)[i]) }, - ExpectedErrMsg: trc.DuplicateVoteSignature, + ExpectedErrMsg: trc.ErrDuplicateVoteSignature, }, "Missing vote": { Modify: func(t *testing.T, sigs *[]trc.Signature) { i := findSignature(t, *sigs, a110, trc.VoteSignature) *sigs = append((*sigs)[:i], (*sigs)[i+1:]...) }, - ExpectedErrMsg: trc.MissingVoteSignature, + ExpectedErrMsg: trc.ErrErrMissingVoteSignature, }, "Vote wrong Algorithm": { Modify: func(t *testing.T, sigs *[]trc.Signature) { @@ -149,7 +149,7 @@ var ( p.Algorithm = "invalid" }) }, - ExpectedErrMsg: trc.InvalidProtected, + ExpectedErrMsg: trc.ErrInvalidProtected, }, "Vote wrong KeyType": { Modify: func(t *testing.T, sigs *[]trc.Signature) { @@ -158,7 +158,7 @@ var ( p.KeyType = trc.OnlineKey }) }, - ExpectedErrMsg: trc.InvalidProtected, + ExpectedErrMsg: trc.ErrInvalidProtected, }, "Vote wrong KeyVersion": { Modify: func(t *testing.T, sigs *[]trc.Signature) { @@ -167,14 +167,14 @@ var ( p.KeyVersion += 1 }) }, - ExpectedErrMsg: trc.InvalidProtected, + ExpectedErrMsg: trc.ErrInvalidProtected, }, "Mangled Vote signature": { Modify: func(t *testing.T, sigs *[]trc.Signature) { sig := &(*sigs)[findSignature(t, *sigs, a110, trc.VoteSignature)] sig.Signature[0] ^= 0xFF }, - ExpectedErrMsg: trc.VoteVerificationError, + ExpectedErrMsg: trc.ErrVoteVerification, }, } ) diff --git a/go/lib/scrypto/validity.go b/go/lib/scrypto/validity.go index 0a728653c6..6284af8863 100644 --- a/go/lib/scrypto/validity.go +++ b/go/lib/scrypto/validity.go @@ -29,8 +29,8 @@ var ( ErrNotAfterNotSet = errors.New("not_after not set") // ErrNotBeforeNotSet indicates not_before is not set. ErrNotBeforeNotSet = errors.New("not_before not set") - // ErrInvalidValidityPeriod indicates an invalid validity period. - ErrInvalidValidityPeriod = errors.New("not_after before not_before") + // ErrErrInvalidValidityPeriod indicates an invalid validity period. + ErrErrInvalidValidityPeriod = errors.New("not_after before not_before") ) // Validity indicates a validity period. @@ -52,7 +52,7 @@ func (v Validity) Covers(other Validity) bool { // Validate checks that NotAfter is after NotBefore. func (v Validity) Validate() error { if !v.NotAfter.After(v.NotBefore.Time) { - return ErrInvalidValidityPeriod + return ErrErrInvalidValidityPeriod } return nil } diff --git a/go/lib/scrypto/version.go b/go/lib/scrypto/version.go index 0ccb6e6220..5a6b784a07 100644 --- a/go/lib/scrypto/version.go +++ b/go/lib/scrypto/version.go @@ -24,8 +24,8 @@ import ( // when requesting certificate chains and TRCs. const LatestVer Version = 0 -// ErrInvalidVersion indicates an invalid trust file version. -var ErrInvalidVersion = errors.New("version must not be zero") +// ErrErrInvalidVersion indicates an invalid trust file version. +var ErrErrInvalidVersion = errors.New("version must not be zero") var _ json.Unmarshaler = (*Version)(nil) var _ json.Marshaler = (*Version)(nil) @@ -46,7 +46,7 @@ func (v *Version) UnmarshalJSON(b []byte) error { return err } if Version(parsed) == LatestVer { - return ErrInvalidVersion + return ErrErrInvalidVersion } *v = Version(parsed) return nil @@ -55,7 +55,7 @@ func (v *Version) UnmarshalJSON(b []byte) error { // MarshalJSON checks that the value is not LatestVer. func (v Version) MarshalJSON() ([]byte, error) { if v == LatestVer { - return nil, ErrInvalidVersion + return nil, ErrErrInvalidVersion } return json.Marshal(uint64(v)) } diff --git a/go/lib/snet/internal/pathsource/pathsource.go b/go/lib/snet/internal/pathsource/pathsource.go index 104ca5f8cc..2637315598 100644 --- a/go/lib/snet/internal/pathsource/pathsource.go +++ b/go/lib/snet/internal/pathsource/pathsource.go @@ -26,10 +26,10 @@ import ( ) const ( - ErrNoResolver = "no resolver set" - ErrNoPath = "path not found" - ErrInitPath = "raw forwarding path offsets could not be initialized" - ErrBadOverlay = "unable to extract next hop from sciond path entry" + ErrNoResolver common.ErrMsg = "no resolver set" + ErrNoPath common.ErrMsg = "path not found" + ErrInitPath common.ErrMsg = "raw forwarding path offsets could not be initialized" + ErrBadOverlay common.ErrMsg = "unable to extract next hop from sciond path entry" ) // PathSource is a source of paths and overlay addresses for snet. diff --git a/go/lib/snet/writer.go b/go/lib/snet/writer.go index 79bfd4efa8..1a530592c9 100644 --- a/go/lib/snet/writer.go +++ b/go/lib/snet/writer.go @@ -31,14 +31,16 @@ import ( // Possible write errors const ( - ErrNoAddr = "remote address required, but none set" - ErrDuplicateAddr = "remote address specified as argument, but address set in conn" - ErrAddressIsNil = "address is nil" - ErrNoApplicationAddress = "SCION host address is missing" - ErrExtraPath = "path set, but none required for local AS" - ErrBadOverlay = "overlay address not set, and construction from SCION address failed" - ErrMustHavePath = "overlay address set, but no path set" - ErrPath = "no path set, and error during path resolution" + ErrNoAddr common.ErrMsg = "remote address required, but none set" + ErrDuplicateAddr common.ErrMsg = "remote address specified as argument, " + + "but address set in conn" + ErrAddressIsNil common.ErrMsg = "address is nil" + ErrNoApplicationAddress common.ErrMsg = "SCION host address is missing" + ErrExtraPath common.ErrMsg = "path set, but none required for local AS" + ErrBadOverlay common.ErrMsg = "overlay address not set, " + + "and construction from SCION address failed" + ErrMustHavePath common.ErrMsg = "overlay address set, but no path set" + ErrPath common.ErrMsg = "no path set, and error during path resolution" ) const ( diff --git a/go/lib/sock/reliable/BUILD.bazel b/go/lib/sock/reliable/BUILD.bazel index 28cbf2f003..b771cf659e 100644 --- a/go/lib/sock/reliable/BUILD.bazel +++ b/go/lib/sock/reliable/BUILD.bazel @@ -32,9 +32,12 @@ go_test( embed = [":go_default_library"], deps = [ "//go/lib/addr:go_default_library", + "//go/lib/common:go_default_library", "//go/lib/mocks/net/mock_net:go_default_library", "//go/lib/xtest:go_default_library", "@com_github_golang_mock//gomock:go_default_library", "@com_github_smartystreets_goconvey//convey:go_default_library", + "@com_github_stretchr_testify//assert:go_default_library", + "@org_golang_x_xerrors//:go_default_library", ], ) diff --git a/go/lib/sock/reliable/errors.go b/go/lib/sock/reliable/errors.go index 6cdb0913e8..661b5c284b 100644 --- a/go/lib/sock/reliable/errors.go +++ b/go/lib/sock/reliable/errors.go @@ -24,18 +24,18 @@ import ( ) const ( - ErrNoAddress = "no address found" - ErrNoPort = "missing port" - ErrPayloadTooLong = "payload too long" - ErrIncompleteFrameHeader = "incomplete frame header" - ErrBadFrameLength = "bad frame length" - ErrBadCookie = "bad cookie" - ErrBadAddressType = "bad address type" - ErrIncompleteAddress = "incomplete IP address" - ErrIncompletePort = "incomplete UDP port" - ErrIncompleteMessage = "incomplete message" - ErrBadLength = "bad length" - ErrBufferTooSmall = "buffer too small" + ErrNoAddress common.ErrMsg = "no address found" + ErrNoPort common.ErrMsg = "missing port" + ErrPayloadTooLong common.ErrMsg = "payload too long" + ErrIncompleteFrameHeader common.ErrMsg = "incomplete frame header" + ErrBadFrameLength common.ErrMsg = "bad frame length" + ErrBadCookie common.ErrMsg = "bad cookie" + ErrBadAddressType common.ErrMsg = "bad address type" + ErrIncompleteAddress common.ErrMsg = "incomplete IP address" + ErrIncompletePort common.ErrMsg = "incomplete UDP port" + ErrIncompleteMessage common.ErrMsg = "incomplete message" + ErrBadLength common.ErrMsg = "bad length" + ErrBufferTooSmall common.ErrMsg = "buffer too small" ) func IsDispatcherError(err error) bool { diff --git a/go/lib/sock/reliable/frame_test.go b/go/lib/sock/reliable/frame_test.go index fa1308239f..910e274b2a 100644 --- a/go/lib/sock/reliable/frame_test.go +++ b/go/lib/sock/reliable/frame_test.go @@ -20,6 +20,7 @@ import ( . "github.com/smartystreets/goconvey/convey" + "github.com/scionproto/scion/go/lib/common" "github.com/scionproto/scion/go/lib/xtest" ) @@ -28,7 +29,7 @@ func TestOverlayPacketSerializeTo(t *testing.T) { Name string Packet *OverlayPacket ExpectedData []byte - ExpectedError string + ExpectedError common.ErrMsg } testCases := []TestCase{ { @@ -101,7 +102,7 @@ func TestOverlayPacketSerializeTo(t *testing.T) { Convey(tc.Name, func() { b := make([]byte, 1500) n, err := tc.Packet.SerializeTo(b) - xtest.SoMsgErrorStr("err", err, tc.ExpectedError) + xtest.SoMsgErrorStr("err", err, tc.ExpectedError.Error()) SoMsg("data", b[:n], ShouldResemble, tc.ExpectedData) }) } @@ -113,7 +114,7 @@ func TestOverlayPacketDecodeFromBytes(t *testing.T) { Name string Buffer []byte ExpectedPacket OverlayPacket - ExpectedError string + ExpectedError common.ErrMsg } testCases := []TestCase{ { @@ -187,7 +188,7 @@ func TestOverlayPacketDecodeFromBytes(t *testing.T) { Convey(tc.Name, func() { var p OverlayPacket err := p.DecodeFromBytes(tc.Buffer) - xtest.SoMsgErrorStr("err", err, tc.ExpectedError) + xtest.SoMsgErrorStr("err", err, tc.ExpectedError.Error()) SoMsg("packet", p, ShouldResemble, tc.ExpectedPacket) }) } diff --git a/go/lib/sock/reliable/registration_test.go b/go/lib/sock/reliable/registration_test.go index 5b6935634d..d91b0b79b9 100644 --- a/go/lib/sock/reliable/registration_test.go +++ b/go/lib/sock/reliable/registration_test.go @@ -19,6 +19,8 @@ import ( "testing" . "github.com/smartystreets/goconvey/convey" + "github.com/stretchr/testify/assert" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/addr" "github.com/scionproto/scion/go/lib/xtest" @@ -28,7 +30,7 @@ func TestRegistrationMessageSerializeTo(t *testing.T) { type TestCase struct { Name string Registration *Registration - ExpectedError string + ExpectedError error ExpectedData []byte } testCases := []TestCase{ @@ -110,7 +112,7 @@ func TestRegistrationMessageSerializeTo(t *testing.T) { Convey(tc.Name, func() { b := make([]byte, 1500) n, err := tc.Registration.SerializeTo(b) - xtest.SoMsgErrorStr("err", err, tc.ExpectedError) + assert.True(t, xerrors.Is(err, tc.ExpectedError)) SoMsg("data", b[:n], ShouldResemble, tc.ExpectedData) }) } @@ -121,7 +123,7 @@ func TestRegistrationMessageDecodeFromBytes(t *testing.T) { type TestCase struct { Name string Data []byte - ExpectedError string + ExpectedError error ExpectedRegistration Registration } testCases := []TestCase{ @@ -243,7 +245,7 @@ func TestRegistrationMessageDecodeFromBytes(t *testing.T) { Convey(tc.Name, func() { var r Registration err := r.DecodeFromBytes(tc.Data) - xtest.SoMsgErrorStr("err", err, tc.ExpectedError) + assert.True(t, xerrors.Is(err, tc.ExpectedError)) SoMsg("registration", r, ShouldResemble, tc.ExpectedRegistration) }) } @@ -256,7 +258,7 @@ func TestConfirmationMessageSerializeTo(t *testing.T) { Convey("bad buffer", func() { b := make([]byte, 1) n, err := confirmation.SerializeTo(b) - xtest.SoMsgErrorStr("err", err, ErrBufferTooSmall) + xtest.SoMsgErrorStr("err", err, ErrBufferTooSmall.Error()) SoMsg("n", n, ShouldEqual, 0) }) Convey("success", func() { @@ -274,7 +276,7 @@ func TestConfirmationDecodeFromBytes(t *testing.T) { Convey("bad buffer", func() { b := []byte{0xaa} err := confirmation.DecodeFromBytes(b) - xtest.SoMsgErrorStr("err", err, ErrIncompletePort) + xtest.SoMsgErrorStr("err", err, ErrIncompletePort.Error()) SoMsg("data", confirmation, ShouldResemble, Confirmation{}) }) Convey("success", func() { diff --git a/go/lib/spath/info.go b/go/lib/spath/info.go index c827e2b225..f4dff23c23 100644 --- a/go/lib/spath/info.go +++ b/go/lib/spath/info.go @@ -24,12 +24,13 @@ import ( "github.com/scionproto/scion/go/lib/util" ) -const ( - InfoFieldLength = common.LineLen - ErrorInfoFTooShort = "InfoF too short" -) +// InfoFieldLength is the length of the info field. +const InfoFieldLength = common.LineLen + +// ErrInfoFTooShort indicates that the info field is to short to be parsed. +const ErrInfoFTooShort common.ErrMsg = "InfoF too short" -// Info Field format: +// InfoField hast the following format: // // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 @@ -54,7 +55,7 @@ type InfoField struct { func InfoFFromRaw(b []byte) (*InfoField, error) { if len(b) < InfoFieldLength { - return nil, common.NewBasicError(ErrorInfoFTooShort, nil, + return nil, common.NewBasicError(ErrInfoFTooShort, nil, "min", InfoFieldLength, "actual", len(b)) } inf := &InfoField{} diff --git a/go/lib/spkt/cmnhdr.go b/go/lib/spkt/cmnhdr.go index e39c006560..cccf4a74f5 100644 --- a/go/lib/spkt/cmnhdr.go +++ b/go/lib/spkt/cmnhdr.go @@ -39,7 +39,7 @@ type CmnHdr struct { } const ( - ErrorUnsuppVersion = "Unsupported SCION version" + ErrorUnsuppVersion common.ErrMsg = "Unsupported SCION version" ) func CmnHdrFromRaw(b common.RawBytes) (*CmnHdr, error) { diff --git a/go/lib/svc/resolver.go b/go/lib/svc/resolver.go index 5fbf835852..d88b2de154 100644 --- a/go/lib/svc/resolver.go +++ b/go/lib/svc/resolver.go @@ -34,14 +34,14 @@ import ( // Internal resolver errors. These are implementation details and can change, // and calling code should not depend on them. const ( - errNilPacket = "packet is nil" - errNilOverlay = "overlay is nil" - errUnsupportedPld = "unsupported payload type" - errRegistration = "unable to open conn" - errWrite = "unable to write" - errRead = "unable to read" - errDecode = "decode failed" - errBadPath = "unable to parse return path" + errNilPacket common.ErrMsg = "packet is nil" + errNilOverlay common.ErrMsg = "overlay is nil" + errUnsupportedPld common.ErrMsg = "unsupported payload type" + errRegistration common.ErrMsg = "unable to open conn" + errWrite common.ErrMsg = "unable to write" + errRead common.ErrMsg = "unable to read" + errDecode common.ErrMsg = "decode failed" + errBadPath common.ErrMsg = "unable to parse return path" ) // Resolver performs SVC address resolution. diff --git a/go/lib/svc/svc.go b/go/lib/svc/svc.go index ce115cbc3d..3235f4dc5b 100644 --- a/go/lib/svc/svc.go +++ b/go/lib/svc/svc.go @@ -26,7 +26,7 @@ import ( "github.com/scionproto/scion/go/lib/spath" ) -const ErrHandler = "Unable to handle SVC request" +const ErrHandler common.ErrMsg = "Unable to handle SVC request" // Result is used to inform Handler users on the outcome of handler execution. type Result int diff --git a/go/lib/topology/BUILD.bazel b/go/lib/topology/BUILD.bazel index 8d8074d474..ca580f276c 100644 --- a/go/lib/topology/BUILD.bazel +++ b/go/lib/topology/BUILD.bazel @@ -36,5 +36,7 @@ go_test( "//go/lib/overlay:go_default_library", "//go/proto:go_default_library", "@com_github_smartystreets_goconvey//convey:go_default_library", + "@com_github_stretchr_testify//assert:go_default_library", + "@org_golang_x_xerrors//:go_default_library", ], ) diff --git a/go/lib/topology/addr.go b/go/lib/topology/addr.go index c5fed45275..a10af56164 100644 --- a/go/lib/topology/addr.go +++ b/go/lib/topology/addr.go @@ -24,16 +24,16 @@ import ( ) const ( - ErrUnsupportedOverlay = "Unsupported overlay" - ErrUnsupportedAddrType = "Unsupported address type" - ErrInvalidPub = "Invalid public address" - ErrInvalidBind = "Invalid bind address" - ErrAtLeastOnePub = "Overlay requires at least one public address" - ErrOverlayPort = "Overlay port set for non-UDP overlay" - ErrBindAddrEqPubAddr = "Bind address equal to Public address" - ErrMismatchOverlayAddr = "Mismatch overlay type and address" - ErrMismatchPubAddrType = "Mismatch public address and type " - ErrMismatchBindAddrType = "Mismatch bind address and type" + ErrUnsupportedOverlay common.ErrMsg = "Unsupported overlay" + ErrUnsupportedAddrType common.ErrMsg = "Unsupported address type" + ErrInvalidPub common.ErrMsg = "Invalid public address" + ErrInvalidBind common.ErrMsg = "Invalid bind address" + ErrAtLeastOnePub common.ErrMsg = "Overlay requires at least one public address" + ErrOverlayPort common.ErrMsg = "Overlay port set for non-UDP overlay" + ErrBindAddrEqPubAddr common.ErrMsg = "Bind address equal to Public address" + ErrMismatchOverlayAddr common.ErrMsg = "Mismatch overlay type and address" + ErrMismatchPubAddrType common.ErrMsg = "Mismatch public address and type " + ErrMismatchBindAddrType common.ErrMsg = "Mismatch bind address and type" ) // TopoAddr wraps the possible addresses of a SCION service and describes diff --git a/go/lib/topology/addr_test.go b/go/lib/topology/addr_test.go index bcefe6f182..9762b9d8f5 100644 --- a/go/lib/topology/addr_test.go +++ b/go/lib/topology/addr_test.go @@ -18,10 +18,10 @@ import ( "fmt" "testing" - . "github.com/smartystreets/goconvey/convey" + "github.com/stretchr/testify/assert" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/addr" - "github.com/scionproto/scion/go/lib/common" "github.com/scionproto/scion/go/lib/overlay" ) @@ -40,7 +40,7 @@ func Test_topoAddrFromRaw(t *testing.T) { var basic_tests = []struct { name string overlay overlay.Type - err string + err error ram RawAddrMap ipv4 *pubBindAddr ipv6 *pubBindAddr @@ -82,12 +82,12 @@ func Test_topoAddrFromRaw(t *testing.T) { ErrBindAddrEqPubAddr, newRAM(nil, pubIPv6, nil, &pubIPv6.RawAddrPort), nil, nil}, // IPv46 - {"IPv46 PubBind", overlay.IPv46, "", + {"IPv46 PubBind", overlay.IPv46, nil, newRAM(pubIPv4, pubIPv6, bindIPv4, bindIPv6), &pubBindAddr{newPub(pubIPv4), newBind(bindIPv4), newOverlay(pubIPv4)}, &pubBindAddr{newPub(pubIPv6), newBind(bindIPv6), newOverlay(pubIPv6)}}, // IPv46+UDP - {"IPv46+UDP PubBind", overlay.UDPIPv46, "", + {"IPv46+UDP PubBind", overlay.UDPIPv46, nil, newRAM(pubUDPIPv4, pubUDPIPv6, bindIPv4, bindIPv6), &pubBindAddr{newPub(pubUDPIPv4), newBind(bindIPv4), newOverlay(pubUDPIPv4)}, &pubBindAddr{newPub(pubUDPIPv6), newBind(bindIPv6), newOverlay(pubUDPIPv6)}}, @@ -99,15 +99,11 @@ func Test_topoAddrFromRaw(t *testing.T) { IPv6: test.ipv6, Overlay: test.overlay, } - Convey(desc, t, func() { - t, err := topoAddrFromRAM(test.ram, test.overlay) - if test.err == "" { - SoMsg("Error", err, ShouldBeNil) - SoMsg("TopoAddr", t, shouldEqTopoAddr, exp) - } else { - SoMsg("TopoAddr", t, ShouldBeNil) - SoMsg("Error", err, ShouldNotBeNil) - SoMsg("Error description", err, shouldBeErrorMsg, test.err) + t.Run(desc, func(t *testing.T) { + ta, err := topoAddrFromRAM(test.ram, test.overlay) + assert.True(t, xerrors.Is(err, test.err)) + if test.err == nil { + assert.Equal(t, exp, ta) } }) } @@ -120,26 +116,26 @@ func Test_pubBindAddr(t *testing.T) { pub *RawAddrPortOverlay overlay *RawAddrPortOverlay bind *RawAddrPort - err string + err error }{ // Errors {"Invaild Public IP Address", false, pubBad, nil, nil, ErrInvalidPub}, {"Invaild Bind IP Address", false, pubIPv4, nil, bindBad, ErrInvalidBind}, {"No UDP Overlay", false, pubUDPIPv4, nil, bindBad, ErrOverlayPort}, // IPv4 Overlay - {"IPv4 Pub", false, pubIPv4, nil, nil, ""}, - {"IPv4 PubBind", false, pubIPv4, nil, bindIPv4, ""}, + {"IPv4 Pub", false, pubIPv4, nil, nil, nil}, + {"IPv4 PubBind", false, pubIPv4, nil, bindIPv4, nil}, // IPv4+UDP Overlay - {"IPv4+UDP Pub", true, pubUDPIPv4, nil, nil, ""}, - {"IPv4+UDP Pub Default Port", true, pubIPv4, pubUDPIPv4, nil, ""}, - {"IPv4+UDP PubBind", true, pubUDPIPv4, nil, bindIPv4, ""}, + {"IPv4+UDP Pub", true, pubUDPIPv4, nil, nil, nil}, + {"IPv4+UDP Pub Default Port", true, pubIPv4, pubUDPIPv4, nil, nil}, + {"IPv4+UDP PubBind", true, pubUDPIPv4, nil, bindIPv4, nil}, // IPv6 Overlay - {"IPv6 Pub", false, pubIPv6, nil, nil, ""}, - {"IPv6 PubBind", false, pubIPv6, nil, bindIPv6, ""}, + {"IPv6 Pub", false, pubIPv6, nil, nil, nil}, + {"IPv6 PubBind", false, pubIPv6, nil, bindIPv6, nil}, // IPv6+UDP Overlay - {"IPv6+UDP Pub", true, pubUDPIPv6, nil, nil, ""}, - {"IPv4+UDP Pub Default Port", true, pubIPv6, pubUDPIPv6, nil, ""}, - {"IPv6+UDP PubBind", true, pubUDPIPv6, nil, bindIPv6, ""}, + {"IPv6+UDP Pub", true, pubUDPIPv6, nil, nil, nil}, + {"IPv4+UDP Pub Default Port", true, pubIPv6, pubUDPIPv6, nil, nil}, + {"IPv6+UDP PubBind", true, pubUDPIPv6, nil, bindIPv6, nil}, } for i, test := range basic_tests { desc := fmt.Sprintf("pubBindAddr_%d. %s", i, test.name) @@ -149,15 +145,12 @@ func Test_pubBindAddr(t *testing.T) { overlay = test.overlay } exp := &pubBindAddr{newPub(test.pub), newBind(test.bind), newOverlay(overlay)} - Convey(desc, t, func() { + t.Run(desc, func(t *testing.T) { pbo := &pubBindAddr{} err := pbo.fromRaw(rpbo, test.udpOverlay) - if test.err == "" { - SoMsg("Error", err, ShouldBeNil) - SoMsg("pubBindAddr", pbo, shouldEqPubBindAddr, exp) - } else { - SoMsg("Error", err, ShouldNotBeNil) - SoMsg("Error description", err, shouldBeErrorMsg, test.err) + assert.True(t, xerrors.Is(err, test.err)) + if test.err == nil { + assert.Equal(t, exp, pbo) } }) } @@ -226,14 +219,3 @@ func shouldEqPubBindAddr(actual interface{}, expected ...interface{}) string { } return fmt.Sprintf("Expected:\n\t%+v\nActual:\n\t%+v", expected[0], actual) } - -func shouldBeErrorMsg(actual interface{}, expected ...interface{}) string { - expError := expected[0].(string) - for curErr := actual.(error); curErr != nil; curErr = common.GetNestedError(curErr) { - errMsg := common.GetErrorMsg(curErr) - if errMsg == expError { - return "" - } - } - return fmt.Sprintf("Expected error: %+q\nActual: %+q", expected, actual) -} diff --git a/go/lib/topology/raw.go b/go/lib/topology/raw.go index dca9183855..ffbb218186 100644 --- a/go/lib/topology/raw.go +++ b/go/lib/topology/raw.go @@ -29,9 +29,9 @@ import ( const CfgName = "topology.json" const ( - ErrorOpen = "Unable to open topology" - ErrorParse = "Unable to parse topology from JSON" - ErrorConvert = "Unable to convert RawTopo to Topo" + ErrorOpen common.ErrMsg = "Unable to open topology" + ErrorParse common.ErrMsg = "Unable to parse topology from JSON" + ErrorConvert common.ErrMsg = "Unable to convert RawTopo to Topo" ) // Structures directly filled from JSON diff --git a/go/path_srv/main.go b/go/path_srv/main.go index 74a103ff2d..60832a86d4 100644 --- a/go/path_srv/main.go +++ b/go/path_srv/main.go @@ -139,7 +139,7 @@ func realMain() int { } msger, err := nc.Messenger() if err != nil { - log.Crit(infraenv.ErrAppUnableToInitMessenger, "err", err) + log.Crit(infraenv.ErrAppUnableToInitMessenger.Error(), "err", err) return 1 } defer msger.CloseServer() diff --git a/go/protobuf/BUILD.bazel b/go/protobuf/BUILD.bazel new file mode 100644 index 0000000000..fe9a5b973d --- /dev/null +++ b/go/protobuf/BUILD.bazel @@ -0,0 +1,16 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "go_default_library", + srcs = [ + "common.pb.go", + "conf_agent.pb.go", + "sig_mgmt.pb.go", + ], + importpath = "github.com/scionproto/scion/go/protobuf", + visibility = ["//visibility:public"], + deps = [ + "@com_github_golang_protobuf//proto:go_default_library", + "@org_golang_google_grpc//:go_default_library", + ], +) diff --git a/go/sciond/main.go b/go/sciond/main.go index 2b31e3dc8f..5726eeada1 100644 --- a/go/sciond/main.go +++ b/go/sciond/main.go @@ -132,7 +132,7 @@ func realMain() int { } msger, err := nc.Messenger() if err != nil { - log.Crit(infraenv.ErrAppUnableToInitMessenger, "err", err) + log.Crit(infraenv.ErrAppUnableToInitMessenger.Error(), "err", err) return 1 } // Route messages to their correct handlers diff --git a/go/tools/scion-pki/internal/conf/BUILD.bazel b/go/tools/scion-pki/internal/conf/BUILD.bazel index aefb5627fb..e0eab44f08 100644 --- a/go/tools/scion-pki/internal/conf/BUILD.bazel +++ b/go/tools/scion-pki/internal/conf/BUILD.bazel @@ -28,6 +28,7 @@ go_test( embed = [":go_default_library"], deps = [ "//go/lib/addr:go_default_library", + "//go/lib/common:go_default_library", "//go/lib/xtest:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", ], diff --git a/go/tools/scion-pki/internal/conf/as.go b/go/tools/scion-pki/internal/conf/as.go index 0f0cc00da1..77a0887f25 100644 --- a/go/tools/scion-pki/internal/conf/as.go +++ b/go/tools/scion-pki/internal/conf/as.go @@ -29,14 +29,14 @@ import ( ) const ( - ErrAsCertMissing = "AS Certificate section missing" - ErrInvalidValidityDuration = "Invalid validity duration" - ErrIssuerMissing = "Parameter Issuer not set in AS certificate" - ErrTRCVersionNotSet = "Parameter TRCVersion not set in Base Certificate" - ErrValidityDurationNotSet = "Validity duration not set" - ErrVersionNotSet = "Parameter Version not set for Base Certificate" - ErrInvalidSignAlgorithm = "Invalid sign algorithm" - ErrInvalidEncAlgorithm = "Invalid encryption algorithm" + ErrAsCertMissing common.ErrMsg = "AS Certificate section missing" + ErrInvalidValidityDuration common.ErrMsg = "Invalid validity duration" + ErrIssuerMissing common.ErrMsg = "Parameter Issuer not set in AS certificate" + ErrTRCVersionNotSet common.ErrMsg = "Parameter TRCVersion not set in Base Certificate" + ErrValidityDurationNotSet common.ErrMsg = "Validity duration not set" + ErrVersionNotSet common.ErrMsg = "Parameter Version not set for Base Certificate" + ErrInvalidSignAlgorithm common.ErrMsg = "Invalid sign algorithm" + ErrInvalidEncAlgorithm common.ErrMsg = "Invalid encryption algorithm" ) const ( diff --git a/go/tools/scion-pki/internal/conf/as_test.go b/go/tools/scion-pki/internal/conf/as_test.go index 9b0be6008b..2d2e4f6a7e 100644 --- a/go/tools/scion-pki/internal/conf/as_test.go +++ b/go/tools/scion-pki/internal/conf/as_test.go @@ -19,12 +19,14 @@ import ( "testing" "github.com/stretchr/testify/assert" + + "github.com/scionproto/scion/go/lib/common" ) func TestValidatingAsConf(t *testing.T) { tests := map[string]struct { as *As - err string + err common.ErrMsg }{ "With empty AS": { as: &As{}, diff --git a/go/tools/scion-pki/internal/conf/isd.go b/go/tools/scion-pki/internal/conf/isd.go index 6aaaf23365..2dc5b76f9e 100644 --- a/go/tools/scion-pki/internal/conf/isd.go +++ b/go/tools/scion-pki/internal/conf/isd.go @@ -31,12 +31,12 @@ import ( const IsdConfFileName = "isd.ini" const ( - ErrCoreIANotSet = "Core ASes are not specified" - ErrInvalidCoreIA = "Invalid Core ASes" - ErrInvalidGracePeriod = "Invalid Grace Period Duration" - ErrQuorumTrcGreaterThanCoreIA = "QuorumTRC > # Core ASes" - ErrQuorumTrcNotSet = "Quorum TRC not set" - ErrTrcVersionNotSet = "Version not set for TRC" + ErrCoreIANotSet common.ErrMsg = "Core ASes are not specified" + ErrInvalidCoreIA common.ErrMsg = "Invalid Core ASes" + ErrInvalidGracePeriod common.ErrMsg = "Invalid Grace Period Duration" + ErrQuorumTrcGreaterThanCoreIA common.ErrMsg = "QuorumTRC > # Core ASes" + ErrQuorumTrcNotSet common.ErrMsg = "Quorum TRC not set" + ErrTrcVersionNotSet common.ErrMsg = "Version not set for TRC" ) // Isd holds config parameters read from isd.ini. diff --git a/go/tools/scion-pki/internal/conf/isd_test.go b/go/tools/scion-pki/internal/conf/isd_test.go index 4133111f32..446c645ca1 100644 --- a/go/tools/scion-pki/internal/conf/isd_test.go +++ b/go/tools/scion-pki/internal/conf/isd_test.go @@ -21,6 +21,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/scionproto/scion/go/lib/addr" + "github.com/scionproto/scion/go/lib/common" "github.com/scionproto/scion/go/lib/xtest" ) @@ -28,7 +29,7 @@ func TestValidatingTrc(t *testing.T) { var coreIA = []addr.IA{xtest.MustParseIA("1-ff00:0:10")} tests := map[string]struct { trc *Trc - err string + err common.ErrMsg }{ "Empty TRC": { trc: &Trc{ diff --git a/go/tools/scion-pki/internal/pkicmn/pkicmn.go b/go/tools/scion-pki/internal/pkicmn/pkicmn.go index 07fdaa9b0f..c7b6a1269e 100644 --- a/go/tools/scion-pki/internal/pkicmn/pkicmn.go +++ b/go/tools/scion-pki/internal/pkicmn/pkicmn.go @@ -28,18 +28,22 @@ import ( ) const ( - CertNameFmt = "ISD%d-AS%s-V%d.crt" - CoreCertNameFmt = "ISD%d-AS%s-V%d-core.crt" - TrcNameFmt = "ISD%d-V%d.trc" - TRCPartsDirFmt = "ISD%d-V%d.parts" - TRCSigPartFmt = "ISD%d-V%d.sig.%s" - TRCProtoNameFmt = "ISD%d-V%d.proto" - ErrInvalidSelector = "Invalid selector." - ErrNoISDDirFound = "No ISD directories found" - ErrNoASDirFound = "No AS directories found" - TRCsDir = "trcs" - CertsDir = "certs" - KeysDir = "keys" + CertNameFmt = "ISD%d-AS%s-V%d.crt" + CoreCertNameFmt = "ISD%d-AS%s-V%d-core.crt" + TrcNameFmt = "ISD%d-V%d.trc" + TRCPartsDirFmt = "ISD%d-V%d.parts" + TRCSigPartFmt = "ISD%d-V%d.sig.%s" + TRCProtoNameFmt = "ISD%d-V%d.proto" + TRCsDir = "trcs" + CertsDir = "certs" + KeysDir = "keys" +) + +// Error values +const ( + ErrInvalidSelector common.ErrMsg = "Invalid selector." + ErrNoISDDirFound common.ErrMsg = "No ISD directories found" + ErrNoASDirFound common.ErrMsg = "No AS directories found" ) var ( diff --git a/go/tools/scion-pki/internal/pkicmn/pkicmn_test.go b/go/tools/scion-pki/internal/pkicmn/pkicmn_test.go index f828785220..03b858b7f4 100644 --- a/go/tools/scion-pki/internal/pkicmn/pkicmn_test.go +++ b/go/tools/scion-pki/internal/pkicmn/pkicmn_test.go @@ -66,7 +66,7 @@ func TestProcessSelector(t *testing.T) { tests := map[string]struct { selector string isdAsMap map[addr.ISD][]addr.IA - err string + err common.ErrMsg }{ "Empty selector string": { err: ErrInvalidSelector, diff --git a/go/tools/scion-pki/internal/v2/conf/BUILD.bazel b/go/tools/scion-pki/internal/v2/conf/BUILD.bazel index 0bdd465a16..7fdc82d62a 100644 --- a/go/tools/scion-pki/internal/v2/conf/BUILD.bazel +++ b/go/tools/scion-pki/internal/v2/conf/BUILD.bazel @@ -42,5 +42,6 @@ go_test( "//go/tools/scion-pki/internal/v2/conf/testdata:go_default_library", "@com_github_stretchr_testify//assert:go_default_library", "@com_github_stretchr_testify//require:go_default_library", + "@org_golang_x_xerrors//:go_default_library", ], ) diff --git a/go/tools/scion-pki/internal/v2/conf/as.go b/go/tools/scion-pki/internal/v2/conf/as.go index 04d4459f5a..63ab3eda8a 100644 --- a/go/tools/scion-pki/internal/v2/conf/as.go +++ b/go/tools/scion-pki/internal/v2/conf/as.go @@ -30,17 +30,17 @@ import ( ) const ( - ErrASCertMissing = "AS Certificate section missing" - ErrInvalidValidityDuration = "invalid validity duration" - ErrIssuerMissing = "issuer not set in AS certificate" - ErrInvalidIssuer = "issuer is not valid" - ErrInvalidIssuerCertVersion = "issuer certificate version must not be zero" - ErrInvalidIssuerTRCVersion = "TRC version must not be zero" - ErrInvalidOptDistPoint = "invalid optional distribution point" - ErrValidityDurationNotSet = "validity duration not set" - ErrVersionNotSet = "version not set for certificate" - ErrInvalidSignAlgorithm = "invalid signature algorithm" - ErrInvalidEncAlgorithm = "invalid encryption algorithm" + ErrASCertMissing common.ErrMsg = "AS Certificate section missing" + ErrInvalidValidityDuration common.ErrMsg = "invalid validity duration" + ErrIssuerMissing common.ErrMsg = "issuer not set in AS certificate" + ErrInvalidIssuer common.ErrMsg = "issuer is not valid" + ErrInvalidIssuerCertVersion common.ErrMsg = "issuer certificate version must not be zero" + ErrInvalidIssuerTRCVersion common.ErrMsg = "TRC version must not be zero" + ErrInvalidOptDistPoint common.ErrMsg = "invalid optional distribution point" + ErrValidityDurationNotSet common.ErrMsg = "validity duration not set" + ErrVersionNotSet common.ErrMsg = "version not set for certificate" + ErrInvalidSignAlgorithm common.ErrMsg = "invalid signature algorithm" + ErrInvalidEncAlgorithm common.ErrMsg = "invalid encryption algorithm" ) const ( diff --git a/go/tools/scion-pki/internal/v2/conf/as_test.go b/go/tools/scion-pki/internal/v2/conf/as_test.go index 038b967386..60fbbd0443 100644 --- a/go/tools/scion-pki/internal/v2/conf/as_test.go +++ b/go/tools/scion-pki/internal/v2/conf/as_test.go @@ -18,7 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "golang.org/x/xerrors" "github.com/scionproto/scion/go/lib/addr" "github.com/scionproto/scion/go/lib/scrypto" @@ -29,7 +29,7 @@ import ( func TestAsValidate(t *testing.T) { tests := map[string]struct { Modify func(*conf.ASCfg) - ExpectedErrMsg string + ExpectedErrMsg error }{ "valid AS cert from template": { Modify: func(cfg *conf.ASCfg) { @@ -189,12 +189,7 @@ func TestAsValidate(t *testing.T) { } test.Modify(&as) err := as.Validate() - if test.ExpectedErrMsg == "" { - require.NoError(t, err) - } else { - require.Error(t, err) - assert.Contains(t, err.Error(), test.ExpectedErrMsg) - } + assert.True(t, xerrors.Is(err, test.ExpectedErrMsg)) }) } } diff --git a/go/tools/scion-pki/internal/v2/conf/isd.go b/go/tools/scion-pki/internal/v2/conf/isd.go index 9afc777505..67106e352f 100644 --- a/go/tools/scion-pki/internal/v2/conf/isd.go +++ b/go/tools/scion-pki/internal/v2/conf/isd.go @@ -31,11 +31,11 @@ import ( const ISDCfgFileName = "isd.ini" const ( - ErrAuthoritativeNotCore = "authoritative must be core" - ErrInvalidGracePeriod = "invalid GracePeriod duration" - ErrVotingQuorumGreaterThanVotingASes = "VotingQuorun > # Voting ASes" - ErrVotingQuorumNotSet = "VotingQuorum not set" - ErrTrcVersionNotSet = "Version not set for TRC" + ErrAuthoritativeNotCore common.ErrMsg = "authoritative must be core" + ErrInvalidGracePeriod common.ErrMsg = "invalid GracePeriod duration" + ErrVotingQuorumGreaterThanVotingASes common.ErrMsg = "VotingQuorun > # Voting ASes" + ErrVotingQuorumNotSet common.ErrMsg = "VotingQuorum not set" + ErrTrcVersionNotSet common.ErrMsg = "Version not set for TRC" ) // ISDCfg holds config parameters read from isd.ini. diff --git a/go/tools/scion-pki/internal/v2/conf/isd_test.go b/go/tools/scion-pki/internal/v2/conf/isd_test.go index c88d073c5f..3645b145d5 100644 --- a/go/tools/scion-pki/internal/v2/conf/isd_test.go +++ b/go/tools/scion-pki/internal/v2/conf/isd_test.go @@ -61,13 +61,13 @@ func TestValidatingTrc(t *testing.T) { Modify: func(trc *conf.TRC) { trc.Version = 0 }, - ExpectedErrMsg: conf.ErrTrcVersionNotSet, + ExpectedErrMsg: conf.ErrTrcVersionNotSet.Error(), }, "invalid validity duration": { Modify: func(trc *conf.TRC) { trc.RawValidity = "18" }, - ExpectedErrMsg: conf.ErrInvalidValidityDuration, + ExpectedErrMsg: conf.ErrInvalidValidityDuration.Error(), }, "authoritative not set": { Modify: func(trc *conf.TRC) { @@ -109,31 +109,31 @@ func TestValidatingTrc(t *testing.T) { Modify: func(trc *conf.TRC) { trc.RawCoreASes = trc.RawCoreASes[:len(trc.RawCoreASes)-2] }, - ExpectedErrMsg: conf.ErrAuthoritativeNotCore, + ExpectedErrMsg: conf.ErrAuthoritativeNotCore.Error(), }, "VotingQuorum not set": { Modify: func(trc *conf.TRC) { trc.VotingQuorum = 0 }, - ExpectedErrMsg: conf.ErrVotingQuorumNotSet, + ExpectedErrMsg: conf.ErrVotingQuorumNotSet.Error(), }, "invalid GracePeriod": { Modify: func(trc *conf.TRC) { trc.RawGracePeriod = "18" }, - ExpectedErrMsg: conf.ErrInvalidGracePeriod, + ExpectedErrMsg: conf.ErrInvalidGracePeriod.Error(), }, "base and non-zero GracePeriod": { Modify: func(trc *conf.TRC) { trc.RawGracePeriod = "6h" }, - ExpectedErrMsg: conf.ErrInvalidGracePeriod, + ExpectedErrMsg: conf.ErrInvalidGracePeriod.Error(), }, "VotingQuorum greater than number of voting ASes": { Modify: func(trc *conf.TRC) { trc.VotingQuorum = len(trc.RawVotingASes) + 1 }, - ExpectedErrMsg: conf.ErrVotingQuorumGreaterThanVotingASes, + ExpectedErrMsg: conf.ErrVotingQuorumGreaterThanVotingASes.Error(), }, } From 9afff391bd1bf23bc85f45b6a5bdb5e642c48661 Mon Sep 17 00:00:00 2001 From: Lukas Vogel Date: Tue, 5 Nov 2019 08:56:07 +0100 Subject: [PATCH 2/3] remove wrongly checked in file --- go/protobuf/BUILD.bazel | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 go/protobuf/BUILD.bazel diff --git a/go/protobuf/BUILD.bazel b/go/protobuf/BUILD.bazel deleted file mode 100644 index fe9a5b973d..0000000000 --- a/go/protobuf/BUILD.bazel +++ /dev/null @@ -1,16 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "go_default_library", - srcs = [ - "common.pb.go", - "conf_agent.pb.go", - "sig_mgmt.pb.go", - ], - importpath = "github.com/scionproto/scion/go/protobuf", - visibility = ["//visibility:public"], - deps = [ - "@com_github_golang_protobuf//proto:go_default_library", - "@org_golang_google_grpc//:go_default_library", - ], -) From d2098dc32be14cc4fa21672c50a56399c8f70ea1 Mon Sep 17 00:00:00 2001 From: Lukas Vogel Date: Tue, 5 Nov 2019 14:27:16 +0100 Subject: [PATCH 3/3] r1 --- go/cert_srv/internal/config/config.go | 7 +++- go/cert_srv/internal/config/state.go | 2 +- go/cert_srv/setup.go | 10 ++--- go/lib/keyconf/keyconf.go | 12 +++--- go/lib/scrypto/cert/cert.go | 2 +- go/lib/scrypto/cert/chain.go | 2 +- go/lib/scrypto/cert/json.go | 6 +-- go/lib/scrypto/trc/entries.go | 2 +- go/lib/scrypto/trc/json.go | 6 +-- go/lib/scrypto/trc/trc.go | 54 +++++++++++++-------------- go/lib/scrypto/trc/v2/verify.go | 6 +-- go/lib/scrypto/trc/v2/verify_test.go | 2 +- go/lib/scrypto/validity.go | 6 +-- go/lib/scrypto/version.go | 8 ++-- go/lib/spkt/cmnhdr.go | 4 +- go/lib/topology/raw.go | 16 ++++---- 16 files changed, 74 insertions(+), 71 deletions(-) diff --git a/go/cert_srv/internal/config/config.go b/go/cert_srv/internal/config/config.go index d1e08414df..f6d8821ccb 100644 --- a/go/cert_srv/internal/config/config.go +++ b/go/cert_srv/internal/config/config.go @@ -39,9 +39,12 @@ const ( ReissReqRate = 10 * time.Second // ReissueReqTimeout is the default timeout of a reissue request. ReissueReqTimeout = 5 * time.Second +) - ErrorKeyConf common.ErrMsg = "Unable to load KeyConf" - ErrorCustomers common.ErrMsg = "Unable to load Customers" +// Error values +const ( + ErrKeyConf common.ErrMsg = "Unable to load KeyConf" + ErrCustomers common.ErrMsg = "Unable to load Customers" ) var _ config.Config = (*Config)(nil) diff --git a/go/cert_srv/internal/config/state.go b/go/cert_srv/internal/config/state.go index 2fb9b96d99..765cecce22 100644 --- a/go/cert_srv/internal/config/state.go +++ b/go/cert_srv/internal/config/state.go @@ -62,7 +62,7 @@ func (s *State) loadKeyConf(confDir string, isCore bool) error { var err error s.keyConf, err = keyconf.Load(filepath.Join(confDir, "keys"), isCore, isCore, false, true) if err != nil { - return common.NewBasicError(ErrorKeyConf, err) + return common.NewBasicError(ErrKeyConf, err) } return nil } diff --git a/go/cert_srv/setup.go b/go/cert_srv/setup.go index f1a7bc57e5..19cb7a7957 100644 --- a/go/cert_srv/setup.go +++ b/go/cert_srv/setup.go @@ -40,11 +40,11 @@ import ( ) const ( - ErrorConf common.ErrMsg = "Unable to load configuration" - ErrorDispClose common.ErrMsg = "Unable to close dispatcher" - ErrorDispInit common.ErrMsg = "Unable to initialize dispatcher" - ErrorSign common.ErrMsg = "Unable to create sign" - ErrorSNET common.ErrMsg = "Unable to create local SCION Network context" + ErrConf common.ErrMsg = "Unable to load configuration" + ErrDispClose common.ErrMsg = "Unable to close dispatcher" + ErrDispInit common.ErrMsg = "Unable to initialize dispatcher" + ErrSign common.ErrMsg = "Unable to create sign" + ErrSNET common.ErrMsg = "Unable to create local SCION Network context" ) // setupBasic loads the config from file and initializes logging. diff --git a/go/lib/keyconf/keyconf.go b/go/lib/keyconf/keyconf.go index 7862ae4995..c6f50d59aa 100644 --- a/go/lib/keyconf/keyconf.go +++ b/go/lib/keyconf/keyconf.go @@ -69,9 +69,9 @@ const ( // Errors const ( - ErrorOpen common.ErrMsg = "Unable to load key" - ErrorParse common.ErrMsg = "Unable to parse key file" - ErrorUnknown common.ErrMsg = "Unknown algorithm" + ErrOpen common.ErrMsg = "Unable to load key" + ErrParse common.ErrMsg = "Unable to parse key file" + ErrUnknown common.ErrMsg = "Unknown algorithm" ) // Load loads key configuration from specified path. @@ -125,12 +125,12 @@ func loadMasterCond(path string, load bool) (Master, error) { func LoadKey(file string, algo string) (common.RawBytes, error) { b, err := ioutil.ReadFile(file) if err != nil { - return nil, common.NewBasicError(ErrorOpen, err) + return nil, common.NewBasicError(ErrOpen, err) } dbuf := make([]byte, base64.StdEncoding.DecodedLen(len(b))) n, err := base64.StdEncoding.Decode(dbuf, b) if err != nil { - return nil, common.NewBasicError(ErrorParse, err) + return nil, common.NewBasicError(ErrParse, err) } dbuf = dbuf[:n] switch strings.ToLower(algo) { @@ -139,7 +139,7 @@ func LoadKey(file string, algo string) (common.RawBytes, error) { case scrypto.Ed25519: return common.RawBytes(ed25519.NewKeyFromSeed(dbuf)), nil default: - return nil, common.NewBasicError(ErrorUnknown, nil, "algo", algo) + return nil, common.NewBasicError(ErrUnknown, nil, "algo", algo) } } diff --git a/go/lib/scrypto/cert/cert.go b/go/lib/scrypto/cert/cert.go index 2d60e4d78d..9f6603f2c1 100644 --- a/go/lib/scrypto/cert/cert.go +++ b/go/lib/scrypto/cert/cert.go @@ -216,7 +216,7 @@ func (c *Certificate) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, certFields); err != nil { - return common.NewBasicError(ErrUnableValidateFields, err) + return common.NewBasicError(ErrValidatingFields, err) } // XXX(roosd): Unmarshalling twice might affect performance. // After switching to go 1.10 we might make use of diff --git a/go/lib/scrypto/cert/chain.go b/go/lib/scrypto/cert/chain.go index 67bc146c64..0b593fa63b 100644 --- a/go/lib/scrypto/cert/chain.go +++ b/go/lib/scrypto/cert/chain.go @@ -239,7 +239,7 @@ func (c *Chain) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, chainFields); err != nil { - return common.NewBasicError(ErrUnableValidateFields, err) + return common.NewBasicError(ErrValidatingFields, err) } // XXX(roosd): Unmarshalling twice might affect performance. // After switching to go 1.10 we might make use of diff --git a/go/lib/scrypto/cert/json.go b/go/lib/scrypto/cert/json.go index 39b0685b01..1a99a88fd5 100644 --- a/go/lib/scrypto/cert/json.go +++ b/go/lib/scrypto/cert/json.go @@ -17,9 +17,9 @@ package cert import "github.com/scionproto/scion/go/lib/common" const ( - ErrInvalidNumFields common.ErrMsg = "Invalid number of fields" - ErrMissingField common.ErrMsg = "Missing json field" - ErrUnableValidateFields common.ErrMsg = "Unable to validate fields" + ErrInvalidNumFields common.ErrMsg = "Invalid number of fields" + ErrMissingField common.ErrMsg = "Missing json field" + ErrValidatingFields common.ErrMsg = "Unable to validate fields" ) var certFields = []string{canIssue, comment, encAlgorithm, expirationTime, diff --git a/go/lib/scrypto/trc/entries.go b/go/lib/scrypto/trc/entries.go index bbce923dae..ef27cb164b 100644 --- a/go/lib/scrypto/trc/entries.go +++ b/go/lib/scrypto/trc/entries.go @@ -46,7 +46,7 @@ func (t *CoreAS) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, coreASFields); err != nil { - return common.NewBasicError(ErrUnableValidateFields, err) + return common.NewBasicError(ErrValidatingFields, err) } return json.Unmarshal(b, (*Alias)(t)) } diff --git a/go/lib/scrypto/trc/json.go b/go/lib/scrypto/trc/json.go index e23ff5009b..cbf621ba50 100644 --- a/go/lib/scrypto/trc/json.go +++ b/go/lib/scrypto/trc/json.go @@ -17,9 +17,9 @@ package trc import "github.com/scionproto/scion/go/lib/common" const ( - ErrInvalidNumFields common.ErrMsg = "Invalid number of fields" - ErrMissingField common.ErrMsg = "Missing json field" - ErrUnableValidateFields common.ErrMsg = "Unable to validate fields" + ErrInvalidNumFields common.ErrMsg = "Invalid number of fields" + ErrMissingField common.ErrMsg = "Missing json field" + ErrValidatingFields common.ErrMsg = "Unable to validate fields" ) var trcFields = []string{certLogs, coreASes, creationTime, description, diff --git a/go/lib/scrypto/trc/trc.go b/go/lib/scrypto/trc/trc.go index 4bd9ab395f..8fbdb56584 100644 --- a/go/lib/scrypto/trc/trc.go +++ b/go/lib/scrypto/trc/trc.go @@ -37,20 +37,20 @@ const ( MaxTRCByteLength uint32 = 1 << 20 ) -// Error strings +// Error constants const ( - EarlyUsage common.ErrMsg = "Creation time in the future" - EarlyAnnouncement common.ErrMsg = "Early announcement" - Expired common.ErrMsg = "TRC expired" - GracePeriodPassed common.ErrMsg = "TRC grace period has passed" - InactiveVersion common.ErrMsg = "Inactive TRC version" - InvalidCreationTime common.ErrMsg = "Invalid TRC creation time" - InvalidISD common.ErrMsg = "Invalid TRC ISD" - InvalidQuorum common.ErrMsg = "Not enough valid signatures" - ErrInvalidVersion common.ErrMsg = "Invalid TRC version" - ReservedVersion common.ErrMsg = "Invalid version 0" - SignatureMissing common.ErrMsg = "Signature missing" - UnableSigPack common.ErrMsg = "TRC: Unable to create signature input" + ErrEarlyUsage common.ErrMsg = "Creation time in the future" + ErrEarlyAnnouncement common.ErrMsg = "Early announcement" + ErrExpired common.ErrMsg = "TRC expired" + ErrGracePeriodPassed common.ErrMsg = "TRC grace period has passed" + ErrInactiveVersion common.ErrMsg = "Inactive TRC version" + ErrInvalidCreationTime common.ErrMsg = "Invalid TRC creation time" + ErrInvalidISD common.ErrMsg = "Invalid TRC ISD" + ErrInvalidQuorum common.ErrMsg = "Not enough valid signatures" + ErrInvalidVersion common.ErrMsg = "Invalid TRC version" + ErrReservedVersion common.ErrMsg = "Invalid version 0" + ErrSignatureMissing common.ErrMsg = "Signature missing" + ErrUnableSigPack common.ErrMsg = "TRC: Unable to create signature input" ) const ( @@ -177,7 +177,7 @@ func TRCFromRaw(raw common.RawBytes, lz4_ bool) (*TRC, error) { return nil, err } if t.Version.IsLatest() { - return nil, common.NewBasicError(ReservedVersion, nil) + return nil, common.NewBasicError(ErrReservedVersion, nil) } return t, nil } @@ -234,27 +234,27 @@ func (t *TRC) Key() *Key { // the newest active TRC of the same ISD which we know of. func (t *TRC) IsActive(maxTRC *TRC) error { if t.Quarantine { - return common.NewBasicError(EarlyAnnouncement, nil) + return common.NewBasicError(ErrEarlyAnnouncement, nil) } currTime := util.TimeToSecs(time.Now()) if currTime < t.CreationTime { - return common.NewBasicError(EarlyUsage, nil, + return common.NewBasicError(ErrEarlyUsage, nil, "now", util.SecsToCompact(currTime), "creation", util.SecsToCompact(t.CreationTime)) } else if currTime > t.ExpirationTime { - return common.NewBasicError(Expired, nil, + return common.NewBasicError(ErrExpired, nil, "now", util.SecsToCompact(currTime), "expiration", util.SecsToCompact(t.ExpirationTime)) } else if t.Version == maxTRC.Version { return nil } else if t.Version+1 != maxTRC.Version { return common.NewBasicError( - InactiveVersion, nil, + ErrInactiveVersion, nil, "expected", fmt.Sprintf("%d or %d", maxTRC.Version-1, maxTRC.Version), "actual", t.Version, ) } else if currTime > maxTRC.CreationTime+maxTRC.GracePeriod { - return common.NewBasicError(GracePeriodPassed, nil, "now", util.SecsToCompact(currTime), + return common.NewBasicError(ErrGracePeriodPassed, nil, "now", util.SecsToCompact(currTime), "expiration", util.SecsToCompact(maxTRC.CreationTime+maxTRC.GracePeriod)) } return nil @@ -286,7 +286,7 @@ func (t *TRC) Verify(trust *TRC) (*TRCVerResult, error) { // verifyUpdate checks the validity of a updated TRC. func (t *TRC) verifyUpdate(old *TRC) (*TRCVerResult, error) { if old.ISD != t.ISD { - return nil, common.NewBasicError(InvalidISD, nil, "expected", old.ISD, "actual", t.ISD) + return nil, common.NewBasicError(ErrInvalidISD, nil, "expected", old.ISD, "actual", t.ISD) } if old.Version+1 != t.Version { return nil, common.NewBasicError(ErrInvalidVersion, nil, @@ -294,13 +294,13 @@ func (t *TRC) verifyUpdate(old *TRC) (*TRCVerResult, error) { } if t.CreationTime < old.CreationTime+old.GracePeriod { return nil, common.NewBasicError( - InvalidCreationTime, nil, + ErrInvalidCreationTime, nil, "expected >", util.SecsToCompact(old.CreationTime+old.GracePeriod), "actual", util.SecsToCompact(t.CreationTime), ) } if t.Quarantine || old.Quarantine { - return nil, common.NewBasicError(EarlyAnnouncement, nil) + return nil, common.NewBasicError(ErrEarlyAnnouncement, nil) } return t.verifySignatures(old) } @@ -316,7 +316,7 @@ func (t *TRC) verifySignatures(old *TRC) (*TRCVerResult, error) { for signer, coreAS := range old.CoreASes { sig, ok := t.Signatures[signer.String()] if !ok { - tvr.Failed[signer] = common.NewBasicError(SignatureMissing, nil, "as", signer) + tvr.Failed[signer] = common.NewBasicError(ErrSignatureMissing, nil, "as", signer) continue } err = scrypto.Verify(sigInput, sig, coreAS.OnlineKey, coreAS.OnlineKeyAlg) @@ -327,7 +327,7 @@ func (t *TRC) verifySignatures(old *TRC) (*TRCVerResult, error) { } } if !tvr.QuorumOk() { - return tvr, common.NewBasicError(InvalidQuorum, nil, + return tvr, common.NewBasicError(ErrInvalidQuorum, nil, "expected", old.QuorumTRC, "actual", len(tvr.Verified)) } return tvr, nil @@ -342,7 +342,7 @@ func (t *TRC) verifyXSig(trust *TRC) error { // sigPack creates a sorted json object of all fields, except for the signature map. func (t *TRC) sigPack() (common.RawBytes, error) { if t.Version.IsLatest() { - return nil, common.NewBasicError(ReservedVersion, nil) + return nil, common.NewBasicError(ErrReservedVersion, nil) } m := make(map[string]interface{}) m[certLogs] = t.CertLogs @@ -361,7 +361,7 @@ func (t *TRC) sigPack() (common.RawBytes, error) { m[coreASes] = t.CoreASes sigInput, err := json.Marshal(m) if err != nil { - return nil, common.NewBasicError(UnableSigPack, err) + return nil, common.NewBasicError(ErrUnableSigPack, err) } return sigInput, nil } @@ -412,7 +412,7 @@ func (t *TRC) UnmarshalJSON(b []byte) error { return err } if err = validateFields(m, trcFields); err != nil { - return common.NewBasicError(ErrUnableValidateFields, err) + return common.NewBasicError(ErrValidatingFields, err) } // XXX(roosd): Unmarshalling twice might affect performance. // After switching to go 1.10 we might make use of diff --git a/go/lib/scrypto/trc/v2/verify.go b/go/lib/scrypto/trc/v2/verify.go index 56559d03ac..6204110529 100644 --- a/go/lib/scrypto/trc/v2/verify.go +++ b/go/lib/scrypto/trc/v2/verify.go @@ -29,8 +29,8 @@ const ( ErrUnexpectedPOPSignature common.ErrMsg = "unexpected proof of possession signature" // ErrInvalidProtected indicates that the protected signature metadata is invalid. ErrInvalidProtected common.ErrMsg = "invalid protected signature metadata" - // ErrErrMissingVoteSignature indicates a voting signature of an AS is missing. - ErrErrMissingVoteSignature common.ErrMsg = "missing vote signature" + // ErrMissingVoteSignature indicates a voting signature of an AS is missing. + ErrMissingVoteSignature common.ErrMsg = "missing vote signature" // ErrMissingPOPSignature indicates a missing proof of possession signature. ErrMissingPOPSignature common.ErrMsg = "missing proof of possession signature" // ErrVoteVerification indicates the signature verification of a vote failed. @@ -111,7 +111,7 @@ func (v UpdateVerifier) checkVotes(votes Votes) error { } for as := range v.Next.Votes { if _, ok := votes[as]; !ok { - return common.NewBasicError(ErrErrMissingVoteSignature, nil, "as", as) + return common.NewBasicError(ErrMissingVoteSignature, nil, "as", as) } } return nil diff --git a/go/lib/scrypto/trc/v2/verify_test.go b/go/lib/scrypto/trc/v2/verify_test.go index 357bf8a0fb..2bcd617326 100644 --- a/go/lib/scrypto/trc/v2/verify_test.go +++ b/go/lib/scrypto/trc/v2/verify_test.go @@ -140,7 +140,7 @@ var ( i := findSignature(t, *sigs, a110, trc.VoteSignature) *sigs = append((*sigs)[:i], (*sigs)[i+1:]...) }, - ExpectedErrMsg: trc.ErrErrMissingVoteSignature, + ExpectedErrMsg: trc.ErrMissingVoteSignature, }, "Vote wrong Algorithm": { Modify: func(t *testing.T, sigs *[]trc.Signature) { diff --git a/go/lib/scrypto/validity.go b/go/lib/scrypto/validity.go index 6284af8863..0a728653c6 100644 --- a/go/lib/scrypto/validity.go +++ b/go/lib/scrypto/validity.go @@ -29,8 +29,8 @@ var ( ErrNotAfterNotSet = errors.New("not_after not set") // ErrNotBeforeNotSet indicates not_before is not set. ErrNotBeforeNotSet = errors.New("not_before not set") - // ErrErrInvalidValidityPeriod indicates an invalid validity period. - ErrErrInvalidValidityPeriod = errors.New("not_after before not_before") + // ErrInvalidValidityPeriod indicates an invalid validity period. + ErrInvalidValidityPeriod = errors.New("not_after before not_before") ) // Validity indicates a validity period. @@ -52,7 +52,7 @@ func (v Validity) Covers(other Validity) bool { // Validate checks that NotAfter is after NotBefore. func (v Validity) Validate() error { if !v.NotAfter.After(v.NotBefore.Time) { - return ErrErrInvalidValidityPeriod + return ErrInvalidValidityPeriod } return nil } diff --git a/go/lib/scrypto/version.go b/go/lib/scrypto/version.go index 5a6b784a07..0ccb6e6220 100644 --- a/go/lib/scrypto/version.go +++ b/go/lib/scrypto/version.go @@ -24,8 +24,8 @@ import ( // when requesting certificate chains and TRCs. const LatestVer Version = 0 -// ErrErrInvalidVersion indicates an invalid trust file version. -var ErrErrInvalidVersion = errors.New("version must not be zero") +// ErrInvalidVersion indicates an invalid trust file version. +var ErrInvalidVersion = errors.New("version must not be zero") var _ json.Unmarshaler = (*Version)(nil) var _ json.Marshaler = (*Version)(nil) @@ -46,7 +46,7 @@ func (v *Version) UnmarshalJSON(b []byte) error { return err } if Version(parsed) == LatestVer { - return ErrErrInvalidVersion + return ErrInvalidVersion } *v = Version(parsed) return nil @@ -55,7 +55,7 @@ func (v *Version) UnmarshalJSON(b []byte) error { // MarshalJSON checks that the value is not LatestVer. func (v Version) MarshalJSON() ([]byte, error) { if v == LatestVer { - return nil, ErrErrInvalidVersion + return nil, ErrInvalidVersion } return json.Marshal(uint64(v)) } diff --git a/go/lib/spkt/cmnhdr.go b/go/lib/spkt/cmnhdr.go index cccf4a74f5..013220bcf8 100644 --- a/go/lib/spkt/cmnhdr.go +++ b/go/lib/spkt/cmnhdr.go @@ -39,7 +39,7 @@ type CmnHdr struct { } const ( - ErrorUnsuppVersion common.ErrMsg = "Unsupported SCION version" + ErrUnsuppVersion common.ErrMsg = "Unsupported SCION version" ) func CmnHdrFromRaw(b common.RawBytes) (*CmnHdr, error) { @@ -74,7 +74,7 @@ func (c *CmnHdr) Parse(b common.RawBytes) error { // This can only usefully be replied to if the version specified is one // that the current router supports, but has deprecated. return common.NewBasicError( - ErrorUnsuppVersion, + ErrUnsuppVersion, scmp.NewError(scmp.C_CmnHdr, scmp.T_C_BadVersion, nil, nil), "expected", SCIONVersion, "actual", c.Ver, ) diff --git a/go/lib/topology/raw.go b/go/lib/topology/raw.go index ffbb218186..63e6dc5585 100644 --- a/go/lib/topology/raw.go +++ b/go/lib/topology/raw.go @@ -29,9 +29,9 @@ import ( const CfgName = "topology.json" const ( - ErrorOpen common.ErrMsg = "Unable to open topology" - ErrorParse common.ErrMsg = "Unable to parse topology from JSON" - ErrorConvert common.ErrMsg = "Unable to convert RawTopo to Topo" + ErrOpen common.ErrMsg = "Unable to open topology" + ErrParse common.ErrMsg = "Unable to parse topology from JSON" + ErrConvert common.ErrMsg = "Unable to convert RawTopo to Topo" ) // Structures directly filled from JSON @@ -216,11 +216,11 @@ func (a RawAddr) String() string { func Load(b common.RawBytes) (*Topo, error) { rt := &RawTopo{} if err := json.Unmarshal(b, rt); err != nil { - return nil, common.NewBasicError(ErrorParse, err) + return nil, common.NewBasicError(ErrParse, err) } ct, err := TopoFromRaw(rt) if err != nil { - return nil, common.NewBasicError(ErrorConvert, err) + return nil, common.NewBasicError(ErrConvert, err) } return ct, nil } @@ -228,7 +228,7 @@ func Load(b common.RawBytes) (*Topo, error) { func LoadFromFile(path string) (*Topo, error) { b, err := ioutil.ReadFile(path) if err != nil { - return nil, common.NewBasicError(ErrorOpen, err, "path", path) + return nil, common.NewBasicError(ErrOpen, err, "path", path) } return Load(b) } @@ -236,7 +236,7 @@ func LoadFromFile(path string) (*Topo, error) { func LoadRaw(b common.RawBytes) (*RawTopo, error) { rt := &RawTopo{} if err := json.Unmarshal(b, rt); err != nil { - return nil, common.NewBasicError(ErrorParse, err) + return nil, common.NewBasicError(ErrParse, err) } return rt, nil } @@ -244,7 +244,7 @@ func LoadRaw(b common.RawBytes) (*RawTopo, error) { func LoadRawFromFile(path string) (*RawTopo, error) { b, err := ioutil.ReadFile(path) if err != nil { - return nil, common.NewBasicError(ErrorOpen, err, "path", path) + return nil, common.NewBasicError(ErrOpen, err, "path", path) } return LoadRaw(b) }