From b9833aa6048ada6b62dd4f0c828773115b099828 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Wed, 25 Mar 2020 11:34:49 +0100 Subject: [PATCH 01/15] change ports --- cmd/zitadel/startup.yaml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cmd/zitadel/startup.yaml b/cmd/zitadel/startup.yaml index 9a8a4bce69..c84f9015a1 100644 --- a/cmd/zitadel/startup.yaml +++ b/cmd/zitadel/startup.yaml @@ -12,30 +12,30 @@ Log: Mgmt: API: GRPC: - ServerPort: 60020 - GatewayPort: 60021 + ServerPort: 50010 + GatewayPort: 50011 CustomHeaders: - x-caos- Auth: API: GRPC: - ServerPort: 60050 - GatewayPort: 60051 + ServerPort: 50020 + GatewayPort: 50021 CustomHeaders: - x-caos- Login: - +# will get port range 5003x Admin: API: GRPC: - ServerPort: 60090 - GatewayPort: 60091 + ServerPort: 50040 + GatewayPort: 50041 CustomHeaders: - x-caos- Console: - Port: '9090' - StaticDir: '/app/console/dist' + Port: 50050 + StaticDir: /app/console/dist From eb1d22c6a3fc2b424aa8d0e7636698477aa4a58a Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Fri, 27 Mar 2020 13:44:50 +0100 Subject: [PATCH 02/15] clarify array_flag.go --- internal/config/array_flag.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/internal/config/array_flag.go b/internal/config/array_flag.go index bb99d0a52c..5a779545d0 100644 --- a/internal/config/array_flag.go +++ b/internal/config/array_flag.go @@ -1,7 +1,14 @@ package config -import "strings" +import ( + "flag" + "strings" +) +var _ flag.Value = (*ArrayFlags)(nil) + +//ArrayFlags implements the flag/Value interface +//allowing to set multiple string flags with the same name type ArrayFlags []string func (i *ArrayFlags) String() string { From f280da5a760972ea8ef9631be0d2008448552c97 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Fri, 27 Mar 2020 13:45:08 +0100 Subject: [PATCH 03/15] remove empty lines --- internal/api/auth/authorization_test.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/internal/api/auth/authorization_test.go b/internal/api/auth/authorization_test.go index 5282e10c92..ac1193385e 100644 --- a/internal/api/auth/authorization_test.go +++ b/internal/api/auth/authorization_test.go @@ -210,7 +210,6 @@ func Test_GetFieldFromReq(t *testing.T) { } func Test_HasGlobalPermission(t *testing.T) { - type args struct { perms []string } @@ -245,7 +244,6 @@ func Test_HasGlobalPermission(t *testing.T) { } func Test_GetPermissionCtxIDs(t *testing.T) { - type args struct { perms []string } From f5af4461ad812bf3d4db2f83a84fdece000270e9 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Fri, 27 Mar 2020 13:57:16 +0100 Subject: [PATCH 04/15] remove pointers on configs --- cmd/zitadel/main.go | 12 ++++++------ internal/api/grpc/config.go | 8 ++++---- pkg/admin/admin.go | 2 +- pkg/auth/auth.go | 2 +- pkg/console/console.go | 2 +- pkg/login/login.go | 6 +++--- pkg/management/api/config.go | 2 +- pkg/management/management.go | 6 +++--- 8 files changed, 20 insertions(+), 20 deletions(-) diff --git a/cmd/zitadel/main.go b/cmd/zitadel/main.go index e56940361d..5d0b1e6a9c 100644 --- a/cmd/zitadel/main.go +++ b/cmd/zitadel/main.go @@ -16,15 +16,15 @@ import ( ) type Config struct { - Mgmt *management.Config - Auth *auth.Config - Login *login.Config - Admin *admin.Config - Console *console.Config + Mgmt management.Config + Auth auth.Config + Login login.Config + Admin admin.Config + Console console.Config //Log //TODO: add //Tracing tracing.TracingConfig //TODO: add - AuthZ *authz.Config + AuthZ authz.Config } func main() { diff --git a/internal/api/grpc/config.go b/internal/api/grpc/config.go index 1b3179d5a5..03b743fdc1 100644 --- a/internal/api/grpc/config.go +++ b/internal/api/grpc/config.go @@ -6,14 +6,14 @@ type Config struct { CustomHeaders []string } -func (c *Config) ToServerConfig() *ServerConfig { - return &ServerConfig{ +func (c Config) ToServerConfig() ServerConfig { + return ServerConfig{ Port: c.ServerPort, } } -func (c *Config) ToGatewayConfig() *GatewayConfig { - return &GatewayConfig{ +func (c Config) ToGatewayConfig() GatewayConfig { + return GatewayConfig{ Port: c.GatewayPort, GRPCEndpoint: c.ServerPort, CustomHeaders: c.CustomHeaders, diff --git a/pkg/admin/admin.go b/pkg/admin/admin.go index 968bb7fa75..bdf9010253 100644 --- a/pkg/admin/admin.go +++ b/pkg/admin/admin.go @@ -14,6 +14,6 @@ type Config struct { API *api.Config } -func Start(ctx context.Context, config *Config, authZ *auth.Config) error { +func Start(ctx context.Context, config Config, authZ auth.Config) error { return errors.ThrowUnimplemented(nil, "ADMIN-n8vw5", "not implemented yet") //TODO: implement } diff --git a/pkg/auth/auth.go b/pkg/auth/auth.go index 21f3229f67..43527dc43b 100644 --- a/pkg/auth/auth.go +++ b/pkg/auth/auth.go @@ -14,6 +14,6 @@ type Config struct { API *api.Config } -func Start(ctx context.Context, config *Config, authZ *auth.Config) error { +func Start(ctx context.Context, config Config, authZ auth.Config) error { return errors.ThrowUnimplemented(nil, "AUTH-l7Hdx", "not implemented yet") //TODO: implement } diff --git a/pkg/console/console.go b/pkg/console/console.go index 8a17d33c2f..663a1197a7 100644 --- a/pkg/console/console.go +++ b/pkg/console/console.go @@ -11,6 +11,6 @@ type Config struct { StaticDir string } -func Start(ctx context.Context, config *Config) error { +func Start(ctx context.Context, config Config) error { return errors.ThrowUnimplemented(nil, "CONSO-4cT5D", "not implemented yet") //TODO: implement } diff --git a/pkg/login/login.go b/pkg/login/login.go index 8a593092a3..462ba37aa1 100644 --- a/pkg/login/login.go +++ b/pkg/login/login.go @@ -9,10 +9,10 @@ import ( ) type Config struct { - App *app.Config - API *api.Config + App app.Config + API api.Config } -func Start(ctx context.Context, config *Config) error { +func Start(ctx context.Context, config Config) error { return errors.ThrowUnimplemented(nil, "LOGIN-3fwvD", "not implemented yet") //TODO: implement } diff --git a/pkg/management/api/config.go b/pkg/management/api/config.go index b63086cc83..8fce0aca62 100644 --- a/pkg/management/api/config.go +++ b/pkg/management/api/config.go @@ -3,5 +3,5 @@ package api import "github.com/caos/zitadel/internal/api/grpc" type Config struct { - GRPC *grpc.Config + GRPC grpc.Config } diff --git a/pkg/management/management.go b/pkg/management/management.go index 2ba24ff227..9f6af48229 100644 --- a/pkg/management/management.go +++ b/pkg/management/management.go @@ -10,10 +10,10 @@ import ( ) type Config struct { - App *app.Config - API *api.Config + App app.Config + API api.Config } -func Start(ctx context.Context, config *Config, authZ *auth.Config) error { +func Start(ctx context.Context, config Config, authZ auth.Config) error { return errors.ThrowUnimplemented(nil, "MANAG-h3k3x", "not implemented yet") //TODO: implement } From b753e06f0b984a9a191ba3da79eeae9e99821665 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 07:04:21 +0200 Subject: [PATCH 05/15] improve some functions --- internal/api/html/i18n.go | 14 +++++++------- internal/api/html/renderer.go | 5 ++--- internal/api/http/cookie.go | 5 +---- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/internal/api/html/i18n.go b/internal/api/html/i18n.go index 17f1cb4e14..79b35ccc2e 100644 --- a/internal/api/html/i18n.go +++ b/internal/api/html/i18n.go @@ -98,12 +98,12 @@ func (t *Translator) localizer(langs ...string) *i18n.Localizer { func (t *Translator) langsFromRequest(r *http.Request) []string { langs := make([]string, 0) - if r != nil { - lang, err := t.cookieHandler.GetCookieValue(r, t.cookieName) - if err == nil { - langs = append(langs, lang) - } - langs = append(langs, r.Header.Get(api.AcceptLanguage)) + if r == nil { + return langs } - return langs + lang, err := t.cookieHandler.GetCookieValue(r, t.cookieName) + if err == nil { + langs = append(langs, lang) + } + return append(langs, r.Header.Get(api.AcceptLanguage)) } diff --git a/internal/api/html/renderer.go b/internal/api/html/renderer.go index 182087e31d..97a684263a 100644 --- a/internal/api/html/renderer.go +++ b/internal/api/html/renderer.go @@ -31,9 +31,8 @@ func NewRenderer(templatesDir string, tmplMapping map[string]string, funcs map[s func (r *Renderer) RenderTemplate(w http.ResponseWriter, req *http.Request, tmpl *template.Template, data interface{}, reqFuncs map[string]interface{}) { reqFuncs = r.registerTranslateFn(req, reqFuncs) - if err := tmpl.Funcs(reqFuncs).Execute(w, data); err != nil { - logging.Log("HTML-lF8F6w").WithError(err).WithField("template", tmpl.Name).Error("error rendering template") - } + err := tmpl.Funcs(reqFuncs).Execute(w, data) + logging.LogWithFields("HTML-lF8F6w", "template", tmpl.Name).OnError(err).Error("error rendering template") } func (r *Renderer) Localize(id string, args map[string]interface{}) string { diff --git a/internal/api/http/cookie.go b/internal/api/http/cookie.go index a28791aafc..f2e28b5294 100644 --- a/internal/api/http/cookie.go +++ b/internal/api/http/cookie.go @@ -85,10 +85,7 @@ func (c *CookieHandler) GetEncryptedCookieValue(r *http.Request, name string, va if c.securecookie == nil { return errors.ThrowInternal(nil, "HTTP-X6XpnL", "securecookie not configured") } - if err := c.securecookie.Decode(name, cookie.Value, value); err != nil { - return err - } - return nil + return c.securecookie.Decode(name, cookie.Value, value) } func (c *CookieHandler) SetCookie(w http.ResponseWriter, name string, value string) { From fa750a506829774a4418e6c78b89f92f37815af2 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 07:23:43 +0200 Subject: [PATCH 06/15] improve some functions --- internal/proto/struct.go | 7 +------ internal/tracing/caller.go | 10 ++++------ internal/tracing/config/config.go | 12 +++++------- internal/tracing/google/config.go | 5 ++--- internal/tracing/span.go | 4 +++- pkg/admin/admin.go | 4 ++-- pkg/admin/api/config.go | 2 +- pkg/auth/api/config.go | 2 +- pkg/auth/auth.go | 4 ++-- 9 files changed, 21 insertions(+), 29 deletions(-) diff --git a/internal/proto/struct.go b/internal/proto/struct.go index 24a6ce0e36..f1b5eb29f9 100644 --- a/internal/proto/struct.go +++ b/internal/proto/struct.go @@ -13,7 +13,6 @@ import ( func MustToPBStruct(object interface{}) *pb_struct.Struct { s, err := ToPBStruct(object) logging.Log("PROTO-7Aa3t").OnError(err).Panic("unable to map object to pb-struct") - return s } @@ -24,15 +23,12 @@ func BytesToPBStruct(b []byte) (*pb_struct.Struct, error) { } func ToPBStruct(object interface{}) (*pb_struct.Struct, error) { - fields := new(pb_struct.Struct) - marshalled, err := json.Marshal(object) if err != nil { return nil, err } - + fields := new(pb_struct.Struct) err = jsonpb.Unmarshal(bytes.NewReader(marshalled), fields) - return fields, err } @@ -47,6 +43,5 @@ func FromPBStruct(object interface{}, s *pb_struct.Struct) error { if err != nil { return err } - return json.Unmarshal([]byte(jsonString), object) } diff --git a/internal/tracing/caller.go b/internal/tracing/caller.go index c5dfb9a319..c8ab9071b0 100644 --- a/internal/tracing/caller.go +++ b/internal/tracing/caller.go @@ -8,17 +8,15 @@ import ( func GetCaller() string { fpcs := make([]uintptr, 1) - n := runtime.Callers(3, fpcs) if n == 0 { - logging.Log("HELPE-rWjfC").Debug("no caller") + logging.Log("TRACE-rWjfC").Debug("no caller") + return "" } - caller := runtime.FuncForPC(fpcs[0] - 1) if caller == nil { - logging.Log("HELPE-25POw").Debug("caller was nil") + logging.Log("TRACE-25POw").Debug("caller was nil") + return "" } - - // Print the name of the function return caller.Name() } diff --git a/internal/tracing/config/config.go b/internal/tracing/config/config.go index e2310fbce3..3681ddf107 100644 --- a/internal/tracing/config/config.go +++ b/internal/tracing/config/config.go @@ -3,9 +3,7 @@ package config import ( "encoding/json" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - + "github.com/caos/zitadel/internal/errors" "github.com/caos/zitadel/internal/tracing" tracing_g "github.com/caos/zitadel/internal/tracing/google" tracing_log "github.com/caos/zitadel/internal/tracing/log" @@ -28,7 +26,7 @@ func (c *TracingConfig) UnmarshalJSON(data []byte) error { } if err := json.Unmarshal(data, &rc); err != nil { - return status.Errorf(codes.Internal, "%v parse config: %v", "TRACE-vmjS", err) + return errors.ThrowInternal(err, "TRACE-vmjS", "error parsing config") } c.Type = rc.Type @@ -36,7 +34,7 @@ func (c *TracingConfig) UnmarshalJSON(data []byte) error { var err error c.Config, err = newTracingConfig(c.Type, rc.Config) if err != nil { - return status.Errorf(codes.Internal, "%v parse config: %v", "TRACE-Ws9E", err) + return err } return c.Config.NewTracer() @@ -45,7 +43,7 @@ func (c *TracingConfig) UnmarshalJSON(data []byte) error { func newTracingConfig(tracerType string, configData []byte) (tracing.Config, error) { t, ok := tracer[tracerType] if !ok { - return nil, status.Errorf(codes.Internal, "%v No config: %v", "TRACE-HMEJ", tracerType) + return nil, errors.ThrowInternalf(nil, "TRACE-HMEJ", "config type %s not supported", tracerType) } tracingConfig := t() @@ -54,7 +52,7 @@ func newTracingConfig(tracerType string, configData []byte) (tracing.Config, err } if err := json.Unmarshal(configData, tracingConfig); err != nil { - return nil, status.Errorf(codes.Internal, "%v Could not read conifg: %v", "TRACE-1tSS", err) + return nil, errors.ThrowInternal(err, "TRACE-1tSS", "Could not read config: %v") } return tracingConfig, nil diff --git a/internal/tracing/google/config.go b/internal/tracing/google/config.go index 92d93f61bd..64ee3223ba 100644 --- a/internal/tracing/google/config.go +++ b/internal/tracing/google/config.go @@ -2,9 +2,8 @@ package google import ( "go.opencensus.io/trace" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" + "github.com/caos/zitadel/internal/errors" "github.com/caos/zitadel/internal/tracing" ) @@ -16,7 +15,7 @@ type Config struct { func (c *Config) NewTracer() error { if !envIsSet() { - return status.Error(codes.InvalidArgument, "env not properly set, GOOGLE_APPLICATION_CREDENTIALS is misconfigured or missing") + return errors.ThrowInvalidArgument(nil, "GOOGL-sdh3a", "env not properly set, GOOGLE_APPLICATION_CREDENTIALS is misconfigured or missing") } tracing.T = &Tracer{projectID: c.ProjectID, metricPrefix: c.MetricPrefix, sampler: trace.ProbabilitySampler(c.Fraction)} diff --git a/internal/tracing/span.go b/internal/tracing/span.go index d958cb4b52..1ad46ca0b1 100644 --- a/internal/tracing/span.go +++ b/internal/tracing/span.go @@ -7,6 +7,8 @@ import ( "go.opencensus.io/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/caos/zitadel/internal/errors" ) type Span struct { @@ -80,7 +82,7 @@ func toTraceAttribute(key string, value interface{}) (attr trace.Attribute, err if valueInt, err := convertToInt64(value); err == nil { return trace.Int64Attribute(key, valueInt), nil } - return attr, status.Error(codes.InvalidArgument, "Attribute is not of type bool, string or int64") + return attr, errors.ThrowInternal(nil, "TRACE-jlq3s", "Attribute is not of type bool, string or int64") } func convertToInt64(value interface{}) (int64, error) { diff --git a/pkg/admin/admin.go b/pkg/admin/admin.go index bdf9010253..0a18a4b145 100644 --- a/pkg/admin/admin.go +++ b/pkg/admin/admin.go @@ -10,8 +10,8 @@ import ( ) type Config struct { - App *app.Config - API *api.Config + App app.Config + API api.Config } func Start(ctx context.Context, config Config, authZ auth.Config) error { diff --git a/pkg/admin/api/config.go b/pkg/admin/api/config.go index b63086cc83..8fce0aca62 100644 --- a/pkg/admin/api/config.go +++ b/pkg/admin/api/config.go @@ -3,5 +3,5 @@ package api import "github.com/caos/zitadel/internal/api/grpc" type Config struct { - GRPC *grpc.Config + GRPC grpc.Config } diff --git a/pkg/auth/api/config.go b/pkg/auth/api/config.go index b63086cc83..8fce0aca62 100644 --- a/pkg/auth/api/config.go +++ b/pkg/auth/api/config.go @@ -3,5 +3,5 @@ package api import "github.com/caos/zitadel/internal/api/grpc" type Config struct { - GRPC *grpc.Config + GRPC grpc.Config } diff --git a/pkg/auth/auth.go b/pkg/auth/auth.go index 43527dc43b..f8838f83c0 100644 --- a/pkg/auth/auth.go +++ b/pkg/auth/auth.go @@ -10,8 +10,8 @@ import ( ) type Config struct { - App *app.Config - API *api.Config + App app.Config + API api.Config } func Start(ctx context.Context, config Config, authZ auth.Config) error { From 59dc4dbe85485982e5123f70e843d1d95f1b1a18 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 09:28:00 +0200 Subject: [PATCH 07/15] improve some functions --- internal/api/auth/permissions_test.go | 7 +- internal/crypto/aes.go | 2 +- internal/crypto/bcrypt.go | 2 +- internal/crypto/code.go | 16 ++--- internal/crypto/code_test.go | 6 +- internal/crypto/crypto.go | 24 +++---- internal/crypto/crypto_mock.go | 98 +++++++++++++-------------- internal/crypto/crypto_test.go | 10 +-- 8 files changed, 81 insertions(+), 84 deletions(-) diff --git a/internal/api/auth/permissions_test.go b/internal/api/auth/permissions_test.go index 6d0857d792..83e5a7f784 100644 --- a/internal/api/auth/permissions_test.go +++ b/internal/api/auth/permissions_test.go @@ -74,10 +74,8 @@ func Test_GetUserMethodPermissions(t *testing.T) { }, }, wantErr: true, - errFunc: func(err error) bool { - return caos_errs.IsUnauthenticated(err) - }, - result: []string{"project.read"}, + errFunc: caos_errs.IsUnauthenticated, + result: []string{"project.read"}, }, { name: "No Grants", @@ -393,7 +391,6 @@ func Test_AddRoleContextIDToPerm(t *testing.T) { } func Test_ExistisPerm(t *testing.T) { - type args struct { existing []string perm string diff --git a/internal/crypto/aes.go b/internal/crypto/aes.go index 31d3e46847..0aca064941 100644 --- a/internal/crypto/aes.go +++ b/internal/crypto/aes.go @@ -10,7 +10,7 @@ import ( "github.com/caos/zitadel/internal/errors" ) -var _ EncryptionAlg = (*AESCrypto)(nil) +var _ EncryptionAlgorithm = (*AESCrypto)(nil) type AESCrypto struct { keys map[string]string diff --git a/internal/crypto/bcrypt.go b/internal/crypto/bcrypt.go index e7daffb27d..d9b172478f 100644 --- a/internal/crypto/bcrypt.go +++ b/internal/crypto/bcrypt.go @@ -4,7 +4,7 @@ import ( "golang.org/x/crypto/bcrypt" ) -var _ HashAlg = (*BCrypt)(nil) +var _ HashAlgorithm = (*BCrypt)(nil) type BCrypt struct { cost int diff --git a/internal/crypto/code.go b/internal/crypto/code.go index 0537710da6..8738aef074 100644 --- a/internal/crypto/code.go +++ b/internal/crypto/code.go @@ -24,7 +24,7 @@ type Generator interface { type EncryptionGenerator struct { length uint expiry time.Duration - alg EncryptionAlg + alg EncryptionAlgorithm runes []rune } @@ -44,7 +44,7 @@ func (g *EncryptionGenerator) Runes() []rune { return g.runes } -func NewEncryptionGenerator(length uint, expiry time.Duration, alg EncryptionAlg, runes []rune) *EncryptionGenerator { +func NewEncryptionGenerator(length uint, expiry time.Duration, alg EncryptionAlgorithm, runes []rune) *EncryptionGenerator { return &EncryptionGenerator{ length: length, expiry: expiry, @@ -56,7 +56,7 @@ func NewEncryptionGenerator(length uint, expiry time.Duration, alg EncryptionAlg type HashGenerator struct { length uint expiry time.Duration - alg HashAlg + alg HashAlgorithm runes []rune } @@ -76,7 +76,7 @@ func (g *HashGenerator) Runes() []rune { return g.runes } -func NewHashGenerator(length uint, expiry time.Duration, alg HashAlg, runes []rune) *HashGenerator { +func NewHashGenerator(length uint, expiry time.Duration, alg HashAlgorithm, runes []rune) *HashGenerator { return &HashGenerator{ length: length, expiry: expiry, @@ -106,9 +106,9 @@ func VerifyCode(creationDate time.Time, expiry time.Duration, cryptoCode *Crypto return errors.ThrowPreconditionFailed(nil, "CODE-QvUQ4P", "verification code is expired") } switch alg := g.Alg().(type) { - case EncryptionAlg: + case EncryptionAlgorithm: return verifyEncryptedCode(cryptoCode, verificationCode, alg) - case HashAlg: + case HashAlgorithm: return verifyHashedCode(cryptoCode, verificationCode, alg) } return errors.ThrowInvalidArgument(nil, "CODE-fW2gNa", "generator alg is not supported") @@ -136,7 +136,7 @@ func generateRandomString(length uint, chars []rune) (string, error) { return "", nil } -func verifyEncryptedCode(cryptoCode *CryptoValue, verificationCode string, alg EncryptionAlg) error { +func verifyEncryptedCode(cryptoCode *CryptoValue, verificationCode string, alg EncryptionAlgorithm) error { code, err := DecryptString(cryptoCode, alg) if err != nil { return err @@ -148,6 +148,6 @@ func verifyEncryptedCode(cryptoCode *CryptoValue, verificationCode string, alg E return nil } -func verifyHashedCode(cryptoCode *CryptoValue, verificationCode string, alg HashAlg) error { +func verifyHashedCode(cryptoCode *CryptoValue, verificationCode string, alg HashAlgorithm) error { return CompareHash(cryptoCode, []byte(verificationCode), alg) } diff --git a/internal/crypto/code_test.go b/internal/crypto/code_test.go index f7f55390e7..4f62f22898 100644 --- a/internal/crypto/code_test.go +++ b/internal/crypto/code_test.go @@ -9,7 +9,7 @@ import ( ) func Test_Encrypted_OK(t *testing.T) { - mCrypto := NewMockEncryptionAlg(gomock.NewController(t)) + mCrypto := NewMockEncryptionAlgorithm(gomock.NewController(t)) mCrypto.EXPECT().Algorithm().AnyTimes().Return("enc") mCrypto.EXPECT().EncryptionKeyID().AnyTimes().Return("id") mCrypto.EXPECT().DecryptionKeyIDs().AnyTimes().Return([]string{"id"}) @@ -35,7 +35,7 @@ func Test_Encrypted_OK(t *testing.T) { } func Test_Verify_Encrypted_OK(t *testing.T) { - mCrypto := NewMockEncryptionAlg(gomock.NewController(t)) + mCrypto := NewMockEncryptionAlgorithm(gomock.NewController(t)) mCrypto.EXPECT().Algorithm().AnyTimes().Return("enc") mCrypto.EXPECT().EncryptionKeyID().AnyTimes().Return("id") mCrypto.EXPECT().DecryptionKeyIDs().AnyTimes().Return([]string{"id"}) @@ -57,7 +57,7 @@ func Test_Verify_Encrypted_OK(t *testing.T) { assert.NoError(t, err) } func Test_Verify_Encrypted_Invalid_Err(t *testing.T) { - mCrypto := NewMockEncryptionAlg(gomock.NewController(t)) + mCrypto := NewMockEncryptionAlgorithm(gomock.NewController(t)) mCrypto.EXPECT().Algorithm().AnyTimes().Return("enc") mCrypto.EXPECT().EncryptionKeyID().AnyTimes().Return("id") mCrypto.EXPECT().DecryptionKeyIDs().AnyTimes().Return([]string{"id"}) diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index 38ee06577b..c1b46d69d5 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -13,7 +13,7 @@ type Crypto interface { Algorithm() string } -type EncryptionAlg interface { +type EncryptionAlgorithm interface { Crypto EncryptionKeyID() string DecryptionKeyIDs() []string @@ -22,7 +22,7 @@ type EncryptionAlg interface { DecryptString(hashed []byte, keyID string) (string, error) } -type HashAlg interface { +type HashAlgorithm interface { Crypto Hash(value []byte) ([]byte, error) CompareHash(hashed, comparer []byte) error @@ -39,15 +39,15 @@ type CryptoType int func Crypt(value []byte, c Crypto) (*CryptoValue, error) { switch alg := c.(type) { - case EncryptionAlg: + case EncryptionAlgorithm: return Encrypt(value, alg) - case HashAlg: + case HashAlgorithm: return Hash(value, alg) } return nil, errors.ThrowInternal(nil, "CRYPT-r4IaHZ", "algorithm not supported") } -func Encrypt(value []byte, alg EncryptionAlg) (*CryptoValue, error) { +func Encrypt(value []byte, alg EncryptionAlgorithm) (*CryptoValue, error) { encrypted, err := alg.Encrypt(value) if err != nil { return nil, errors.ThrowInternal(err, "CRYPT-qCD0JB", "error encrypting value") @@ -60,21 +60,21 @@ func Encrypt(value []byte, alg EncryptionAlg) (*CryptoValue, error) { }, nil } -func Decrypt(value *CryptoValue, alg EncryptionAlg) ([]byte, error) { - if err := checkEncAlg(value, alg); err != nil { +func Decrypt(value *CryptoValue, alg EncryptionAlgorithm) ([]byte, error) { + if err := checkEncryptionAlgorithm(value, alg); err != nil { return nil, err } return alg.Decrypt(value.Crypted, value.KeyID) } -func DecryptString(value *CryptoValue, alg EncryptionAlg) (string, error) { - if err := checkEncAlg(value, alg); err != nil { +func DecryptString(value *CryptoValue, alg EncryptionAlgorithm) (string, error) { + if err := checkEncryptionAlgorithm(value, alg); err != nil { return "", err } return alg.DecryptString(value.Crypted, value.KeyID) } -func checkEncAlg(value *CryptoValue, alg EncryptionAlg) error { +func checkEncryptionAlgorithm(value *CryptoValue, alg EncryptionAlgorithm) error { if value.Algorithm != alg.Algorithm() { return errors.ThrowInvalidArgument(nil, "CRYPT-Nx7XlT", "value was encrypted with a different key") } @@ -86,7 +86,7 @@ func checkEncAlg(value *CryptoValue, alg EncryptionAlg) error { return errors.ThrowInvalidArgument(nil, "CRYPT-Kq12vn", "value was encrypted with a different key") } -func Hash(value []byte, alg HashAlg) (*CryptoValue, error) { +func Hash(value []byte, alg HashAlgorithm) (*CryptoValue, error) { hashed, err := alg.Hash(value) if err != nil { return nil, errors.ThrowInternal(err, "CRYPT-rBVaJU", "error hashing value") @@ -98,6 +98,6 @@ func Hash(value []byte, alg HashAlg) (*CryptoValue, error) { }, nil } -func CompareHash(value *CryptoValue, comparer []byte, alg HashAlg) error { +func CompareHash(value *CryptoValue, comparer []byte, alg HashAlgorithm) error { return alg.CompareHash(value.Crypted, comparer) } diff --git a/internal/crypto/crypto_mock.go b/internal/crypto/crypto_mock.go index 3785c285ae..439db21969 100644 --- a/internal/crypto/crypto_mock.go +++ b/internal/crypto/crypto_mock.go @@ -46,31 +46,31 @@ func (mr *MockCryptoMockRecorder) Algorithm() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Algorithm", reflect.TypeOf((*MockCrypto)(nil).Algorithm)) } -// MockEncryptionAlg is a mock of EncryptionAlg interface -type MockEncryptionAlg struct { +// MockEncryptionAlgorithm is a mock of EncryptionAlgorithm interface +type MockEncryptionAlgorithm struct { ctrl *gomock.Controller - recorder *MockEncryptionAlgMockRecorder + recorder *MockEncryptionAlgorithmMockRecorder } -// MockEncryptionAlgMockRecorder is the mock recorder for MockEncryptionAlg -type MockEncryptionAlgMockRecorder struct { - mock *MockEncryptionAlg +// MockEncryptionAlgorithmMockRecorder is the mock recorder for MockEncryptionAlgorithm +type MockEncryptionAlgorithmMockRecorder struct { + mock *MockEncryptionAlgorithm } -// NewMockEncryptionAlg creates a new mock instance -func NewMockEncryptionAlg(ctrl *gomock.Controller) *MockEncryptionAlg { - mock := &MockEncryptionAlg{ctrl: ctrl} - mock.recorder = &MockEncryptionAlgMockRecorder{mock} +// NewMockEncryptionAlgorithm creates a new mock instance +func NewMockEncryptionAlgorithm(ctrl *gomock.Controller) *MockEncryptionAlgorithm { + mock := &MockEncryptionAlgorithm{ctrl: ctrl} + mock.recorder = &MockEncryptionAlgorithmMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use -func (m *MockEncryptionAlg) EXPECT() *MockEncryptionAlgMockRecorder { +func (m *MockEncryptionAlgorithm) EXPECT() *MockEncryptionAlgorithmMockRecorder { return m.recorder } // Algorithm mocks base method -func (m *MockEncryptionAlg) Algorithm() string { +func (m *MockEncryptionAlgorithm) Algorithm() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Algorithm") ret0, _ := ret[0].(string) @@ -78,13 +78,13 @@ func (m *MockEncryptionAlg) Algorithm() string { } // Algorithm indicates an expected call of Algorithm -func (mr *MockEncryptionAlgMockRecorder) Algorithm() *gomock.Call { +func (mr *MockEncryptionAlgorithmMockRecorder) Algorithm() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Algorithm", reflect.TypeOf((*MockEncryptionAlg)(nil).Algorithm)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Algorithm", reflect.TypeOf((*MockEncryptionAlgorithm)(nil).Algorithm)) } // EncryptionKeyID mocks base method -func (m *MockEncryptionAlg) EncryptionKeyID() string { +func (m *MockEncryptionAlgorithm) EncryptionKeyID() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "EncryptionKeyID") ret0, _ := ret[0].(string) @@ -92,13 +92,13 @@ func (m *MockEncryptionAlg) EncryptionKeyID() string { } // EncryptionKeyID indicates an expected call of EncryptionKeyID -func (mr *MockEncryptionAlgMockRecorder) EncryptionKeyID() *gomock.Call { +func (mr *MockEncryptionAlgorithmMockRecorder) EncryptionKeyID() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EncryptionKeyID", reflect.TypeOf((*MockEncryptionAlg)(nil).EncryptionKeyID)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EncryptionKeyID", reflect.TypeOf((*MockEncryptionAlgorithm)(nil).EncryptionKeyID)) } // DecryptionKeyIDs mocks base method -func (m *MockEncryptionAlg) DecryptionKeyIDs() []string { +func (m *MockEncryptionAlgorithm) DecryptionKeyIDs() []string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DecryptionKeyIDs") ret0, _ := ret[0].([]string) @@ -106,13 +106,13 @@ func (m *MockEncryptionAlg) DecryptionKeyIDs() []string { } // DecryptionKeyIDs indicates an expected call of DecryptionKeyIDs -func (mr *MockEncryptionAlgMockRecorder) DecryptionKeyIDs() *gomock.Call { +func (mr *MockEncryptionAlgorithmMockRecorder) DecryptionKeyIDs() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DecryptionKeyIDs", reflect.TypeOf((*MockEncryptionAlg)(nil).DecryptionKeyIDs)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DecryptionKeyIDs", reflect.TypeOf((*MockEncryptionAlgorithm)(nil).DecryptionKeyIDs)) } // Encrypt mocks base method -func (m *MockEncryptionAlg) Encrypt(value []byte) ([]byte, error) { +func (m *MockEncryptionAlgorithm) Encrypt(value []byte) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Encrypt", value) ret0, _ := ret[0].([]byte) @@ -121,13 +121,13 @@ func (m *MockEncryptionAlg) Encrypt(value []byte) ([]byte, error) { } // Encrypt indicates an expected call of Encrypt -func (mr *MockEncryptionAlgMockRecorder) Encrypt(value interface{}) *gomock.Call { +func (mr *MockEncryptionAlgorithmMockRecorder) Encrypt(value interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Encrypt", reflect.TypeOf((*MockEncryptionAlg)(nil).Encrypt), value) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Encrypt", reflect.TypeOf((*MockEncryptionAlgorithm)(nil).Encrypt), value) } // Decrypt mocks base method -func (m *MockEncryptionAlg) Decrypt(hashed []byte, keyID string) ([]byte, error) { +func (m *MockEncryptionAlgorithm) Decrypt(hashed []byte, keyID string) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Decrypt", hashed, keyID) ret0, _ := ret[0].([]byte) @@ -136,13 +136,13 @@ func (m *MockEncryptionAlg) Decrypt(hashed []byte, keyID string) ([]byte, error) } // Decrypt indicates an expected call of Decrypt -func (mr *MockEncryptionAlgMockRecorder) Decrypt(hashed, keyID interface{}) *gomock.Call { +func (mr *MockEncryptionAlgorithmMockRecorder) Decrypt(hashed, keyID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Decrypt", reflect.TypeOf((*MockEncryptionAlg)(nil).Decrypt), hashed, keyID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Decrypt", reflect.TypeOf((*MockEncryptionAlgorithm)(nil).Decrypt), hashed, keyID) } // DecryptString mocks base method -func (m *MockEncryptionAlg) DecryptString(hashed []byte, keyID string) (string, error) { +func (m *MockEncryptionAlgorithm) DecryptString(hashed []byte, keyID string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DecryptString", hashed, keyID) ret0, _ := ret[0].(string) @@ -151,36 +151,36 @@ func (m *MockEncryptionAlg) DecryptString(hashed []byte, keyID string) (string, } // DecryptString indicates an expected call of DecryptString -func (mr *MockEncryptionAlgMockRecorder) DecryptString(hashed, keyID interface{}) *gomock.Call { +func (mr *MockEncryptionAlgorithmMockRecorder) DecryptString(hashed, keyID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DecryptString", reflect.TypeOf((*MockEncryptionAlg)(nil).DecryptString), hashed, keyID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DecryptString", reflect.TypeOf((*MockEncryptionAlgorithm)(nil).DecryptString), hashed, keyID) } -// MockHashAlg is a mock of HashAlg interface -type MockHashAlg struct { +// MockHashAlgorithm is a mock of HashAlgorithm interface +type MockHashAlgorithm struct { ctrl *gomock.Controller - recorder *MockHashAlgMockRecorder + recorder *MockHashAlgorithmMockRecorder } -// MockHashAlgMockRecorder is the mock recorder for MockHashAlg -type MockHashAlgMockRecorder struct { - mock *MockHashAlg +// MockHashAlgorithmMockRecorder is the mock recorder for MockHashAlgorithm +type MockHashAlgorithmMockRecorder struct { + mock *MockHashAlgorithm } -// NewMockHashAlg creates a new mock instance -func NewMockHashAlg(ctrl *gomock.Controller) *MockHashAlg { - mock := &MockHashAlg{ctrl: ctrl} - mock.recorder = &MockHashAlgMockRecorder{mock} +// NewMockHashAlgorithm creates a new mock instance +func NewMockHashAlgorithm(ctrl *gomock.Controller) *MockHashAlgorithm { + mock := &MockHashAlgorithm{ctrl: ctrl} + mock.recorder = &MockHashAlgorithmMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use -func (m *MockHashAlg) EXPECT() *MockHashAlgMockRecorder { +func (m *MockHashAlgorithm) EXPECT() *MockHashAlgorithmMockRecorder { return m.recorder } // Algorithm mocks base method -func (m *MockHashAlg) Algorithm() string { +func (m *MockHashAlgorithm) Algorithm() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Algorithm") ret0, _ := ret[0].(string) @@ -188,13 +188,13 @@ func (m *MockHashAlg) Algorithm() string { } // Algorithm indicates an expected call of Algorithm -func (mr *MockHashAlgMockRecorder) Algorithm() *gomock.Call { +func (mr *MockHashAlgorithmMockRecorder) Algorithm() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Algorithm", reflect.TypeOf((*MockHashAlg)(nil).Algorithm)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Algorithm", reflect.TypeOf((*MockHashAlgorithm)(nil).Algorithm)) } // Hash mocks base method -func (m *MockHashAlg) Hash(value []byte) ([]byte, error) { +func (m *MockHashAlgorithm) Hash(value []byte) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Hash", value) ret0, _ := ret[0].([]byte) @@ -203,13 +203,13 @@ func (m *MockHashAlg) Hash(value []byte) ([]byte, error) { } // Hash indicates an expected call of Hash -func (mr *MockHashAlgMockRecorder) Hash(value interface{}) *gomock.Call { +func (mr *MockHashAlgorithmMockRecorder) Hash(value interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Hash", reflect.TypeOf((*MockHashAlg)(nil).Hash), value) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Hash", reflect.TypeOf((*MockHashAlgorithm)(nil).Hash), value) } // CompareHash mocks base method -func (m *MockHashAlg) CompareHash(hashed, comparer []byte) error { +func (m *MockHashAlgorithm) CompareHash(hashed, comparer []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CompareHash", hashed, comparer) ret0, _ := ret[0].(error) @@ -217,7 +217,7 @@ func (m *MockHashAlg) CompareHash(hashed, comparer []byte) error { } // CompareHash indicates an expected call of CompareHash -func (mr *MockHashAlgMockRecorder) CompareHash(hashed, comparer interface{}) *gomock.Call { +func (mr *MockHashAlgorithmMockRecorder) CompareHash(hashed, comparer interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompareHash", reflect.TypeOf((*MockHashAlg)(nil).CompareHash), hashed, comparer) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompareHash", reflect.TypeOf((*MockHashAlgorithm)(nil).CompareHash), hashed, comparer) } diff --git a/internal/crypto/crypto_test.go b/internal/crypto/crypto_test.go index 76334884b9..fa5c4a5194 100644 --- a/internal/crypto/crypto_test.go +++ b/internal/crypto/crypto_test.go @@ -104,7 +104,7 @@ func TestCrypt(t *testing.T) { func TestEncrypt(t *testing.T) { type args struct { value []byte - c EncryptionAlg + c EncryptionAlgorithm } tests := []struct { name string @@ -136,7 +136,7 @@ func TestEncrypt(t *testing.T) { func TestDecrypt(t *testing.T) { type args struct { value *CryptoValue - c EncryptionAlg + c EncryptionAlgorithm } tests := []struct { name string @@ -174,7 +174,7 @@ func TestDecrypt(t *testing.T) { func TestDecryptString(t *testing.T) { type args struct { value *CryptoValue - c EncryptionAlg + c EncryptionAlgorithm } tests := []struct { name string @@ -212,7 +212,7 @@ func TestDecryptString(t *testing.T) { func TestHash(t *testing.T) { type args struct { value []byte - c HashAlg + c HashAlgorithm } tests := []struct { name string @@ -245,7 +245,7 @@ func TestCompareHash(t *testing.T) { type args struct { value *CryptoValue comparer []byte - c HashAlg + c HashAlgorithm } tests := []struct { name string From 501d45382224a06deac734d15fca1819a67ead4e Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 09:58:55 +0200 Subject: [PATCH 08/15] remove x-grpc-web header in cors --- internal/api/http/middleware/cors_interceptor.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/api/http/middleware/cors_interceptor.go b/internal/api/http/middleware/cors_interceptor.go index 6fd154b469..379fbc38b7 100644 --- a/internal/api/http/middleware/cors_interceptor.go +++ b/internal/api/http/middleware/cors_interceptor.go @@ -18,7 +18,6 @@ var ( api.AcceptLanguage, api.Authorization, api.ZitadelOrgID, - "x-grpc-web", //TODO: needed }, AllowedMethods: []string{ http.MethodOptions, From e5e39b3a6a54e0e9a92ad9dddcf482a3c96b7784 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 10:06:48 +0200 Subject: [PATCH 09/15] remove pointer on ctxData --- internal/api/auth/context.go | 20 +++++--------------- internal/api/auth/permissions_test.go | 2 +- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/internal/api/auth/context.go b/internal/api/auth/context.go index b17affec28..78ef0bc252 100644 --- a/internal/api/auth/context.go +++ b/internal/api/auth/context.go @@ -2,7 +2,6 @@ package auth import ( "context" - "time" "github.com/caos/logging" ) @@ -43,24 +42,15 @@ func VerifyTokenAndWriteCtxData(ctx context.Context, token, orgID string, t Toke projectID, err := t.GetProjectIDByClientID(ctx, clientID) logging.LogWithFields("AUTH-GfAoV", "clientID", clientID).OnError(err).Warn("could not read projectid by clientid") - return context.WithValue(ctx, CtxKeyData{}, &CtxData{UserID: userID, OrgID: orgID, ProjectID: projectID, AgentID: agentID}), nil + return context.WithValue(ctx, CtxKeyData{}, CtxData{UserID: userID, OrgID: orgID, ProjectID: projectID, AgentID: agentID}), nil } func GetCtxData(ctx context.Context) CtxData { - if data := ctx.Value(CtxKeyData{}); data != nil { - ctxData, ok := data.(*CtxData) - if ok { - return *ctxData - } - time.Now() - } - return CtxData{} + ctxData, _ := ctx.Value(CtxKeyData{}).(CtxData) + return ctxData } func GetPermissionsFromCtx(ctx context.Context) []string { - if data := ctx.Value(CtxKeyPermissions{}); data != nil { - ctxPermission, _ := data.([]string) - return ctxPermission - } - return nil + ctxPermission, _ := ctx.Value(CtxKeyPermissions{}).([]string) + return ctxPermission } diff --git a/internal/api/auth/permissions_test.go b/internal/api/auth/permissions_test.go index 83e5a7f784..0a433f43c6 100644 --- a/internal/api/auth/permissions_test.go +++ b/internal/api/auth/permissions_test.go @@ -8,7 +8,7 @@ import ( ) func getTestCtx(userID, orgID string) context.Context { - return context.WithValue(context.Background(), CtxKeyData{}, &CtxData{UserID: userID, OrgID: orgID}) + return context.WithValue(context.Background(), CtxKeyData{}, CtxData{UserID: userID, OrgID: orgID}) } type testVerifier struct { From 106a6ec1435a59f3e3df29a1c9f701f587e68df5 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 10:09:38 +0200 Subject: [PATCH 10/15] fix test --- internal/api/auth/permissions_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/api/auth/permissions_test.go b/internal/api/auth/permissions_test.go index 0a433f43c6..d2afc36dfc 100644 --- a/internal/api/auth/permissions_test.go +++ b/internal/api/auth/permissions_test.go @@ -27,7 +27,7 @@ func (v *testVerifier) GetProjectIDByClientID(ctx context.Context, clientID stri return "", nil } -func EqualStringArray(a, b []string) bool { +func equalStringArray(a, b []string) bool { if len(a) != len(b) { return false } @@ -133,7 +133,7 @@ func Test_GetUserMethodPermissions(t *testing.T) { t.Errorf("got wrong err: %v ", err) } - if !tt.wantErr && !EqualStringArray(perms, tt.result) { + if !tt.wantErr && !equalStringArray(perms, tt.result) { t.Errorf("got wrong result, expecting: %v, actual: %v ", tt.result, perms) } }) @@ -239,7 +239,7 @@ func Test_MapGrantsToPermissions(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := mapGrantsToPermissions(tt.args.requiredPerm, tt.args.grants, tt.args.authConfig) - if !EqualStringArray(result, tt.result) { + if !equalStringArray(result, tt.result) { t.Errorf("got wrong result, expecting: %v, actual: %v ", tt.result, result) } }) @@ -346,7 +346,7 @@ func Test_MapRoleToPerm(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := mapRoleToPerm(tt.args.requiredPerm, tt.args.actualRole, tt.args.authConfig, tt.args.resolvedPermissions) - if !EqualStringArray(result, tt.result) { + if !equalStringArray(result, tt.result) { t.Errorf("got wrong result, expecting: %v, actual: %v ", tt.result, result) } }) From e04c0116f5e5c9d5ef53b83d43d862fddcb19d4a Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 11:26:02 +0200 Subject: [PATCH 11/15] refactor crypto tests --- internal/crypto/code.go | 6 + internal/crypto/code_test.go | 376 +++++++++++++++++++++++++++++------ internal/crypto/crypto.go | 3 + internal/crypto/generate.go | 1 + 4 files changed, 328 insertions(+), 58 deletions(-) diff --git a/internal/crypto/code.go b/internal/crypto/code.go index 8738aef074..7cff29a746 100644 --- a/internal/crypto/code.go +++ b/internal/crypto/code.go @@ -137,6 +137,9 @@ func generateRandomString(length uint, chars []rune) (string, error) { } func verifyEncryptedCode(cryptoCode *CryptoValue, verificationCode string, alg EncryptionAlgorithm) error { + if cryptoCode == nil { + return errors.ThrowInvalidArgument(nil, "CRYPT-aqrFV", "cryptoCode must not be nil") + } code, err := DecryptString(cryptoCode, alg) if err != nil { return err @@ -149,5 +152,8 @@ func verifyEncryptedCode(cryptoCode *CryptoValue, verificationCode string, alg E } func verifyHashedCode(cryptoCode *CryptoValue, verificationCode string, alg HashAlgorithm) error { + if cryptoCode == nil { + return errors.ThrowInvalidArgument(nil, "CRYPT-2q3r", "cryptoCode must not be nil") + } return CompareHash(cryptoCode, []byte(verificationCode), alg) } diff --git a/internal/crypto/code_test.go b/internal/crypto/code_test.go index 4f62f22898..8e1947c2d8 100644 --- a/internal/crypto/code_test.go +++ b/internal/crypto/code_test.go @@ -5,10 +5,11 @@ import ( "time" "github.com/golang/mock/gomock" - "github.com/stretchr/testify/assert" + + "github.com/caos/zitadel/internal/errors" ) -func Test_Encrypted_OK(t *testing.T) { +func createMockEncryptionAlg(t *testing.T) EncryptionAlgorithm { mCrypto := NewMockEncryptionAlgorithm(gomock.NewController(t)) mCrypto.EXPECT().Algorithm().AnyTimes().Return("enc") mCrypto.EXPECT().EncryptionKeyID().AnyTimes().Return("id") @@ -19,74 +20,333 @@ func Test_Encrypted_OK(t *testing.T) { }, ) mCrypto.EXPECT().DecryptString(gomock.Any(), gomock.Any()).DoAndReturn( - func(code []byte, _ string) (string, error) { + func(code []byte, keyID string) (string, error) { + if keyID != "id" { + return "", errors.ThrowInternal(nil, "id", "invalid key id") + } return string(code), nil }, ) - generator := NewEncryptionGenerator(6, 0, mCrypto, Digits) - - crypto, code, err := NewCode(generator) - assert.NoError(t, err) - - decrypted, err := DecryptString(crypto, generator.alg) - assert.NoError(t, err) - assert.Equal(t, code, decrypted) - assert.Equal(t, 6, len(decrypted)) + return mCrypto } -func Test_Verify_Encrypted_OK(t *testing.T) { - mCrypto := NewMockEncryptionAlgorithm(gomock.NewController(t)) - mCrypto.EXPECT().Algorithm().AnyTimes().Return("enc") - mCrypto.EXPECT().EncryptionKeyID().AnyTimes().Return("id") - mCrypto.EXPECT().DecryptionKeyIDs().AnyTimes().Return([]string{"id"}) - mCrypto.EXPECT().DecryptString(gomock.Any(), gomock.Any()).DoAndReturn( - func(code []byte, _ string) (string, error) { - return string(code), nil +func createMockHashAlg(t *testing.T) HashAlgorithm { + mCrypto := NewMockHashAlgorithm(gomock.NewController(t)) + mCrypto.EXPECT().Algorithm().AnyTimes().Return("hash") + mCrypto.EXPECT().Hash(gomock.Any()).DoAndReturn( + func(code []byte) ([]byte, error) { + return code, nil }, ) - creationDate := time.Now() - code := &CryptoValue{ - CryptoType: TypeEncryption, - Algorithm: "enc", - KeyID: "id", - Crypted: []byte("code"), + mCrypto.EXPECT().CompareHash(gomock.Any(), gomock.Any()).DoAndReturn( + func(hashed, comparer []byte) error { + if string(hashed) != string(comparer) { + return errors.ThrowInternal(nil, "id", "invalid") + } + return nil + }, + ) + return mCrypto +} + +func createMockCrypto(t *testing.T) Crypto { + mCrypto := NewMockCrypto(gomock.NewController(t)) + mCrypto.EXPECT().Algorithm().AnyTimes().Return("crypto") + return mCrypto +} + +func createMockGenerator(t *testing.T, crypto Crypto) Generator { + mGenerator := NewMockGenerator(gomock.NewController(t)) + mGenerator.EXPECT().Alg().AnyTimes().Return(crypto) + return mGenerator +} + +func TestIsCodeExpired(t *testing.T) { + type args struct { + creationDate time.Time + expiry time.Duration } - generator := NewEncryptionGenerator(6, 0, mCrypto, Digits) - - err := VerifyCode(creationDate, 1*time.Hour, code, "code", generator) - assert.NoError(t, err) -} -func Test_Verify_Encrypted_Invalid_Err(t *testing.T) { - mCrypto := NewMockEncryptionAlgorithm(gomock.NewController(t)) - mCrypto.EXPECT().Algorithm().AnyTimes().Return("enc") - mCrypto.EXPECT().EncryptionKeyID().AnyTimes().Return("id") - mCrypto.EXPECT().DecryptionKeyIDs().AnyTimes().Return([]string{"id"}) - mCrypto.EXPECT().DecryptString(gomock.Any(), gomock.Any()).DoAndReturn( - func(code []byte, _ string) (string, error) { - return string(code), nil + tests := []struct { + name string + args args + want bool + }{ + { + "not expired", + args{ + creationDate: time.Now(), + expiry: time.Duration(5 * time.Minute), + }, + false, + }, + { + "expired", + args{ + creationDate: time.Now().Add(-5 * time.Minute), + expiry: time.Duration(5 * time.Minute), + }, + true, }, - ) - creationDate := time.Now() - code := &CryptoValue{ - CryptoType: TypeEncryption, - Algorithm: "enc", - KeyID: "id", - Crypted: []byte("code"), } - generator := NewEncryptionGenerator(6, 0, mCrypto, Digits) - - err := VerifyCode(creationDate, 1*time.Hour, code, "wrong", generator) - assert.Error(t, err) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := IsCodeExpired(tt.args.creationDate, tt.args.expiry); got != tt.want { + t.Errorf("IsCodeExpired() = %v, want %v", got, tt.want) + } + }) + } } -func TestIsCodeExpired_Expired(t *testing.T) { - creationDate := time.Date(2019, time.April, 1, 0, 0, 0, 0, time.UTC) - expired := IsCodeExpired(creationDate, 1*time.Hour) - assert.True(t, expired) +func TestVerifyCode(t *testing.T) { + type args struct { + creationDate time.Time + expiry time.Duration + cryptoCode *CryptoValue + verificationCode string + g Generator + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + "expired", + args{ + creationDate: time.Now().Add(-5 * time.Minute), + expiry: 5 * time.Minute, + cryptoCode: nil, + verificationCode: "", + g: nil, + }, + true, + }, + { + "unsupported alg err", + args{ + creationDate: time.Now(), + expiry: 5 * time.Minute, + cryptoCode: nil, + verificationCode: "code", + g: createMockGenerator(t, createMockCrypto(t)), + }, + true, + }, + { + "encryption alg ok", + args{ + creationDate: time.Now(), + expiry: 5 * time.Minute, + cryptoCode: &CryptoValue{ + CryptoType: TypeEncryption, + Algorithm: "enc", + KeyID: "id", + Crypted: []byte("code"), + }, + verificationCode: "code", + g: createMockGenerator(t, createMockEncryptionAlg(t)), + }, + false, + }, + { + "hash alg ok", + args{ + creationDate: time.Now(), + expiry: 5 * time.Minute, + cryptoCode: &CryptoValue{ + CryptoType: TypeHash, + Algorithm: "hash", + Crypted: []byte("code"), + }, + verificationCode: "code", + g: createMockGenerator(t, createMockHashAlg(t)), + }, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := VerifyCode(tt.args.creationDate, tt.args.expiry, tt.args.cryptoCode, tt.args.verificationCode, tt.args.g); (err != nil) != tt.wantErr { + t.Errorf("VerifyCode() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } -func TestIsCodeExpired_NotExpired(t *testing.T) { - creationDate := time.Now() - expired := IsCodeExpired(creationDate, 1*time.Hour) - assert.False(t, expired) +func Test_verifyEncryptedCode(t *testing.T) { + type args struct { + cryptoCode *CryptoValue + verificationCode string + alg EncryptionAlgorithm + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + "nil error", + args{ + cryptoCode: nil, + verificationCode: "", + alg: createMockEncryptionAlg(t), + }, + true, + }, + { + "wrong cryptotype error", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeHash, + Crypted: nil, + }, + verificationCode: "", + alg: createMockEncryptionAlg(t), + }, + true, + }, + { + "wrong algorithm error", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeEncryption, + Algorithm: "enc2", + Crypted: nil, + }, + verificationCode: "", + alg: createMockEncryptionAlg(t), + }, + true, + }, + { + "wrong key id error", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeEncryption, + Algorithm: "enc", + Crypted: nil, + }, + verificationCode: "wrong", + alg: createMockEncryptionAlg(t), + }, + true, + }, + { + "wrong verification code error", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeEncryption, + Algorithm: "enc", + KeyID: "id", + Crypted: []byte("code"), + }, + verificationCode: "wrong", + alg: createMockEncryptionAlg(t), + }, + true, + }, + { + "verification code ok", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeEncryption, + Algorithm: "enc", + KeyID: "id", + Crypted: []byte("code"), + }, + verificationCode: "code", + alg: createMockEncryptionAlg(t), + }, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := verifyEncryptedCode(tt.args.cryptoCode, tt.args.verificationCode, tt.args.alg); (err != nil) != tt.wantErr { + t.Errorf("verifyEncryptedCode() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_verifyHashedCode(t *testing.T) { + type args struct { + cryptoCode *CryptoValue + verificationCode string + alg HashAlgorithm + } + tests := []struct { + name string + args args + wantErr bool + }{ + + { + "nil error", + args{ + cryptoCode: nil, + verificationCode: "", + alg: createMockHashAlg(t), + }, + true, + }, + { + "wrong cryptotype error", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeEncryption, + Crypted: nil, + }, + verificationCode: "", + alg: createMockHashAlg(t), + }, + true, + }, + { + "wrong algorithm error", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeHash, + Algorithm: "hash2", + Crypted: nil, + }, + verificationCode: "", + alg: createMockHashAlg(t), + }, + true, + }, + { + "wrong verification code error", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeHash, + Algorithm: "hash", + Crypted: []byte("code"), + }, + verificationCode: "wrong", + alg: createMockHashAlg(t), + }, + true, + }, + { + "verification code ok", + args{ + cryptoCode: &CryptoValue{ + CryptoType: TypeHash, + Algorithm: "hash", + Crypted: []byte("code"), + }, + verificationCode: "code", + alg: createMockHashAlg(t), + }, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := verifyHashedCode(tt.args.cryptoCode, tt.args.verificationCode, tt.args.alg); (err != nil) != tt.wantErr { + t.Errorf("verifyHashedCode() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index c1b46d69d5..d7f3269321 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -99,5 +99,8 @@ func Hash(value []byte, alg HashAlgorithm) (*CryptoValue, error) { } func CompareHash(value *CryptoValue, comparer []byte, alg HashAlgorithm) error { + if value.Algorithm != alg.Algorithm() { + return errors.ThrowInvalidArgument(nil, "CRYPT-HF32f", "value was hash with a different algorithm") + } return alg.CompareHash(value.Crypted, comparer) } diff --git a/internal/crypto/generate.go b/internal/crypto/generate.go index 4c43e7e9b3..fd3de9f759 100644 --- a/internal/crypto/generate.go +++ b/internal/crypto/generate.go @@ -1,3 +1,4 @@ package crypto //go:generate mockgen -source crypto.go -destination ./crypto_mock.go -package crypto +//go:generate mockgen -source code.go -destination ./code_mock.go -package crypto From 96b1817d62a0877061dbc675fe9a2f70dd501d2b Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 11:44:17 +0200 Subject: [PATCH 12/15] add multi files config test and some more --- internal/config/config_test.go | 37 +++++++++- internal/config/testdata/more_data.yaml | 1 + internal/crypto/aes_test.go | 1 + internal/crypto/code_mock.go | 90 +++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 internal/config/testdata/more_data.yaml create mode 100644 internal/crypto/code_mock.go diff --git a/internal/config/config_test.go b/internal/config/config_test.go index ba517b6061..98221851dc 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -17,6 +17,11 @@ type validatable struct { Test bool } +type multiple struct { + Test bool + MoreData string +} + func (v *validatable) Validate() error { if v.Test { return nil @@ -33,22 +38,25 @@ func TestRead(t *testing.T) { name string args args wantErr bool + want interface{} }{ { "not supoorted config file error", args{ configFiles: []string{"notsupported.unknown"}, - obj: nil, + obj: &test{}, }, true, + &test{}, }, { "non existing config file error", args{ configFiles: []string{"nonexisting.yaml"}, - obj: nil, + obj: &test{}, }, true, + &test{}, }, { "non parsable config file error", @@ -57,6 +65,7 @@ func TestRead(t *testing.T) { obj: &test{}, }, true, + &test{}, }, { "invalid parsable config file error", @@ -65,6 +74,16 @@ func TestRead(t *testing.T) { obj: &validatable{}, }, true, + &validatable{}, + }, + { + "multiple files, one non parsable error ", + args{ + configFiles: []string{"./testdata/non_parsable.json", "./testdata/more_data.yaml"}, + obj: &multiple{}, + }, + true, + &multiple{}, }, { "parsable config file ok", @@ -73,6 +92,16 @@ func TestRead(t *testing.T) { obj: &test{}, }, false, + &test{Test: true}, + }, + { + "multiple parsable config files ok", + args{ + configFiles: []string{"./testdata/valid.json", "./testdata/more_data.yaml"}, + obj: &multiple{}, + }, + false, + &multiple{Test: true, MoreData: "data"}, }, { "valid parsable config file ok", @@ -81,6 +110,7 @@ func TestRead(t *testing.T) { obj: &validatable{}, }, false, + &validatable{Test: true}, }, } for _, tt := range tests { @@ -88,6 +118,9 @@ func TestRead(t *testing.T) { if err := Read(tt.args.obj, tt.args.configFiles...); (err != nil) != tt.wantErr { t.Errorf("Read() error = %v, wantErr %v", err, tt.wantErr) } + if !reflect.DeepEqual(tt.args.obj, tt.want) { + t.Errorf("Read() got = %v, want = %v", tt.args.obj, tt.want) + } }) } } diff --git a/internal/config/testdata/more_data.yaml b/internal/config/testdata/more_data.yaml new file mode 100644 index 0000000000..d8fc5877da --- /dev/null +++ b/internal/config/testdata/more_data.yaml @@ -0,0 +1 @@ +MoreData: data diff --git a/internal/crypto/aes_test.go b/internal/crypto/aes_test.go index c7e31de3d5..87af88d0be 100644 --- a/internal/crypto/aes_test.go +++ b/internal/crypto/aes_test.go @@ -6,6 +6,7 @@ import ( "github.com/stretchr/testify/assert" ) +//TODO: refactor test style func TestDecrypt_OK(t *testing.T) { encryptedpw, err := EncryptAESString("ThisIsMySecretPw", "passphrasewhichneedstobe32bytes!") assert.NoError(t, err) diff --git a/internal/crypto/code_mock.go b/internal/crypto/code_mock.go new file mode 100644 index 0000000000..916a7c225d --- /dev/null +++ b/internal/crypto/code_mock.go @@ -0,0 +1,90 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: code.go + +// Package crypto is a generated GoMock package. +package crypto + +import ( + gomock "github.com/golang/mock/gomock" + reflect "reflect" + time "time" +) + +// MockGenerator is a mock of Generator interface +type MockGenerator struct { + ctrl *gomock.Controller + recorder *MockGeneratorMockRecorder +} + +// MockGeneratorMockRecorder is the mock recorder for MockGenerator +type MockGeneratorMockRecorder struct { + mock *MockGenerator +} + +// NewMockGenerator creates a new mock instance +func NewMockGenerator(ctrl *gomock.Controller) *MockGenerator { + mock := &MockGenerator{ctrl: ctrl} + mock.recorder = &MockGeneratorMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use +func (m *MockGenerator) EXPECT() *MockGeneratorMockRecorder { + return m.recorder +} + +// Length mocks base method +func (m *MockGenerator) Length() uint { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Length") + ret0, _ := ret[0].(uint) + return ret0 +} + +// Length indicates an expected call of Length +func (mr *MockGeneratorMockRecorder) Length() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Length", reflect.TypeOf((*MockGenerator)(nil).Length)) +} + +// Expiry mocks base method +func (m *MockGenerator) Expiry() time.Duration { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Expiry") + ret0, _ := ret[0].(time.Duration) + return ret0 +} + +// Expiry indicates an expected call of Expiry +func (mr *MockGeneratorMockRecorder) Expiry() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Expiry", reflect.TypeOf((*MockGenerator)(nil).Expiry)) +} + +// Alg mocks base method +func (m *MockGenerator) Alg() Crypto { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Alg") + ret0, _ := ret[0].(Crypto) + return ret0 +} + +// Alg indicates an expected call of Alg +func (mr *MockGeneratorMockRecorder) Alg() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Alg", reflect.TypeOf((*MockGenerator)(nil).Alg)) +} + +// Runes mocks base method +func (m *MockGenerator) Runes() []rune { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Runes") + ret0, _ := ret[0].([]rune) + return ret0 +} + +// Runes indicates an expected call of Runes +func (mr *MockGeneratorMockRecorder) Runes() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Runes", reflect.TypeOf((*MockGenerator)(nil).Runes)) +} From 40e4f69ca3711d04e406f6af303034d5fc7fb155 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 11:52:08 +0200 Subject: [PATCH 13/15] change context keys and fix tests --- internal/api/auth/authorization_test.go | 2 +- internal/api/auth/context.go | 14 +++++++++----- internal/api/auth/permissions.go | 2 +- internal/api/auth/permissions_test.go | 2 +- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/internal/api/auth/authorization_test.go b/internal/api/auth/authorization_test.go index ac1193385e..d140758321 100644 --- a/internal/api/auth/authorization_test.go +++ b/internal/api/auth/authorization_test.go @@ -270,7 +270,7 @@ func Test_GetPermissionCtxIDs(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := GetPermissionCtxIDs(tt.args.perms) - if !EqualStringArray(result, tt.result) { + if !equalStringArray(result, tt.result) { t.Errorf("got wrong result, expecting: %v, actual: %v ", tt.result, result) } }) diff --git a/internal/api/auth/context.go b/internal/api/auth/context.go index 78ef0bc252..e0c87929e5 100644 --- a/internal/api/auth/context.go +++ b/internal/api/auth/context.go @@ -6,8 +6,12 @@ import ( "github.com/caos/logging" ) -type CtxKeyPermissions struct{} -type CtxKeyData struct{} +type key int + +var ( + permissionsKey key + dataKey key +) type CtxData struct { UserID string @@ -42,15 +46,15 @@ func VerifyTokenAndWriteCtxData(ctx context.Context, token, orgID string, t Toke projectID, err := t.GetProjectIDByClientID(ctx, clientID) logging.LogWithFields("AUTH-GfAoV", "clientID", clientID).OnError(err).Warn("could not read projectid by clientid") - return context.WithValue(ctx, CtxKeyData{}, CtxData{UserID: userID, OrgID: orgID, ProjectID: projectID, AgentID: agentID}), nil + return context.WithValue(ctx, dataKey, CtxData{UserID: userID, OrgID: orgID, ProjectID: projectID, AgentID: agentID}), nil } func GetCtxData(ctx context.Context) CtxData { - ctxData, _ := ctx.Value(CtxKeyData{}).(CtxData) + ctxData, _ := ctx.Value(dataKey).(CtxData) return ctxData } func GetPermissionsFromCtx(ctx context.Context) []string { - ctxPermission, _ := ctx.Value(CtxKeyPermissions{}).([]string) + ctxPermission, _ := ctx.Value(permissionsKey).([]string) return ctxPermission } diff --git a/internal/api/auth/permissions.go b/internal/api/auth/permissions.go index d7ca516a9d..04c6713915 100644 --- a/internal/api/auth/permissions.go +++ b/internal/api/auth/permissions.go @@ -16,7 +16,7 @@ func getUserMethodPermissions(ctx context.Context, t TokenVerifier, requiredPerm return nil, nil, err } permissions := mapGrantsToPermissions(requiredPerm, grants, authConfig) - return context.WithValue(ctx, CtxKeyPermissions{}, permissions), permissions, nil + return context.WithValue(ctx, permissionsKey, permissions), permissions, nil } func mapGrantsToPermissions(requiredPerm string, grants []*Grant, authConfig *Config) []string { diff --git a/internal/api/auth/permissions_test.go b/internal/api/auth/permissions_test.go index d2afc36dfc..ba67f0d25f 100644 --- a/internal/api/auth/permissions_test.go +++ b/internal/api/auth/permissions_test.go @@ -8,7 +8,7 @@ import ( ) func getTestCtx(userID, orgID string) context.Context { - return context.WithValue(context.Background(), CtxKeyData{}, CtxData{UserID: userID, OrgID: orgID}) + return context.WithValue(context.Background(), dataKey, CtxData{UserID: userID, OrgID: orgID}) } type testVerifier struct { From affd2da40a47d01e483a8f12f852db51a8ae0b2c Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 11:57:56 +0200 Subject: [PATCH 14/15] update logging version --- cmd/zitadel/main.go | 7 ++++--- cmd/zitadel/startup.yaml | 3 ++- go.mod | 5 +++-- go.sum | 10 ++++++---- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/cmd/zitadel/main.go b/cmd/zitadel/main.go index 5d0b1e6a9c..fc5f748139 100644 --- a/cmd/zitadel/main.go +++ b/cmd/zitadel/main.go @@ -8,6 +8,7 @@ import ( authz "github.com/caos/zitadel/internal/api/auth" "github.com/caos/zitadel/internal/config" + tracing "github.com/caos/zitadel/internal/tracing/config" "github.com/caos/zitadel/pkg/admin" "github.com/caos/zitadel/pkg/auth" "github.com/caos/zitadel/pkg/console" @@ -22,9 +23,9 @@ type Config struct { Admin admin.Config Console console.Config - //Log //TODO: add - //Tracing tracing.TracingConfig //TODO: add - AuthZ authz.Config + Log logging.Config + Tracing tracing.TracingConfig + AuthZ authz.Config } func main() { diff --git a/cmd/zitadel/startup.yaml b/cmd/zitadel/startup.yaml index c84f9015a1..abf809b34b 100644 --- a/cmd/zitadel/startup.yaml +++ b/cmd/zitadel/startup.yaml @@ -7,7 +7,8 @@ Tracing: Log: Level: debug - Formatter: text + Formatter: + Format: text Mgmt: API: diff --git a/go.mod b/go.mod index 731d99ee77..4f7af60649 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.22.0+incompatible github.com/aws/aws-sdk-go v1.29.16 // indirect - github.com/caos/logging v0.0.0-20191210002624-b3260f690a6a + github.com/caos/logging v0.0.1 github.com/ghodss/yaml v1.0.0 github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b github.com/golang/mock v1.4.3 @@ -25,11 +25,12 @@ require ( github.com/mitchellh/copystructure v1.0.0 // indirect github.com/nicksnyder/go-i18n/v2 v2.0.3 github.com/rs/cors v1.7.0 + github.com/sirupsen/logrus v1.5.0 // indirect github.com/stretchr/testify v1.5.1 go.opencensus.io v0.22.3 golang.org/x/crypto v0.0.0-20200320181102-891825fb96df golang.org/x/net v0.0.0-20200320220750-118fecf932d8 // indirect - golang.org/x/sys v0.0.0-20200321134203-328b4cd54aae // indirect + golang.org/x/sys v0.0.0-20200327173247-9dae0f8f5775 // indirect golang.org/x/text v0.3.2 golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56 google.golang.org/api v0.20.0 // indirect diff --git a/go.sum b/go.sum index c277b44880..f253cef29c 100644 --- a/go.sum +++ b/go.sum @@ -32,8 +32,8 @@ github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQY github.com/aws/aws-sdk-go v1.23.20/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.29.16 h1:Gbtod7Y4W/Ai7wPtesdvgGVTkFN8JxAaGouRLlcQfQs= github.com/aws/aws-sdk-go v1.29.16/go.mod h1:1KvfttTE3SPKMpo8g2c6jL3ZKfXtFvKscTgahTma5Xg= -github.com/caos/logging v0.0.0-20191210002624-b3260f690a6a h1:HOU/3xL/afsZ+2aCstfJlrzRkwYMTFR1TIEgps5ny8s= -github.com/caos/logging v0.0.0-20191210002624-b3260f690a6a/go.mod h1:9LKiDE2ChuGv6CHYif/kiugrfEXu9AwDiFWSreX7Wp0= +github.com/caos/logging v0.0.1 h1:YSGtO2/+5OWdwilBCou50akoDHAT/OhkbrolkVlR6U0= +github.com/caos/logging v0.0.1/go.mod h1:9LKiDE2ChuGv6CHYif/kiugrfEXu9AwDiFWSreX7Wp0= github.com/census-instrumentation/opencensus-proto v0.2.1 h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= @@ -140,6 +140,8 @@ github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.5.0 h1:1N5EYkVAPEywqZRJd7cwnRtCb6xJx7NH3T3WUTF980Q= +github.com/sirupsen/logrus v1.5.0/go.mod h1:+F7Ogzej0PZc/94MaYx/nvG9jOFMD2osvC3s+Squfpo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= @@ -234,8 +236,8 @@ golang.org/x/sys v0.0.0-20191206220618-eeba5f6aabab h1:FvshnhkKW+LO3HWHodML8kuVX golang.org/x/sys v0.0.0-20191206220618-eeba5f6aabab/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200321134203-328b4cd54aae h1:3tcmuaB7wwSZtelmiv479UjUB+vviwABz7a133ZwOKQ= -golang.org/x/sys v0.0.0-20200321134203-328b4cd54aae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200327173247-9dae0f8f5775 h1:TC0v2RSO1u2kn1ZugjrFXkRZAEaqMN/RW+OTZkBzmLE= +golang.org/x/sys v0.0.0-20200327173247-9dae0f8f5775/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= From 39039dde626a975fff5a0f77cfb69fc99b8d17a6 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Mon, 30 Mar 2020 13:17:49 +0200 Subject: [PATCH 15/15] fix tracing/statusFromError --- internal/api/grpc/caos_errors.go | 4 ++-- internal/tracing/span.go | 9 +++------ 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/internal/api/grpc/caos_errors.go b/internal/api/grpc/caos_errors.go index 5ed7fa95da..413a2fd128 100644 --- a/internal/api/grpc/caos_errors.go +++ b/internal/api/grpc/caos_errors.go @@ -11,14 +11,14 @@ func CaosToGRPCError(err error) error { if err == nil { return nil } - code, msg, ok := extract(err) + code, msg, ok := Extract(err) if !ok { return status.Convert(err).Err() } return status.Error(code, msg) } -func extract(err error) (c codes.Code, msg string, ok bool) { +func Extract(err error) (c codes.Code, msg string, ok bool) { switch caosErr := err.(type) { case *caos_errs.AlreadyExistsError: return codes.AlreadyExists, caosErr.GetMessage(), true diff --git a/internal/tracing/span.go b/internal/tracing/span.go index 1ad46ca0b1..aff92822c2 100644 --- a/internal/tracing/span.go +++ b/internal/tracing/span.go @@ -5,9 +5,8 @@ import ( "strconv" "go.opencensus.io/trace" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" + "github.com/caos/zitadel/internal/api/grpc" "github.com/caos/zitadel/internal/errors" ) @@ -41,10 +40,8 @@ func (s *Span) SetStatusByError(err error) { } func statusFromError(err error) trace.Status { - if statusErr, ok := status.FromError(err); ok { - return trace.Status{Code: int32(statusErr.Code()), Message: statusErr.Message()} - } - return trace.Status{Code: int32(codes.Unknown), Message: "Unknown"} + code, msg, _ := grpc.Extract(err) + return trace.Status{Code: int32(code), Message: msg} } // AddAnnotation creates an annotation. The annotation will not be added to the tracing use Annotate(msg) afterwards