Merge remote-tracking branch 'origin/basics' into basics

This commit is contained in:
Fabiennne 2020-03-30 14:11:24 +02:00
commit 8ced7fb04c
40 changed files with 639 additions and 259 deletions

View File

@ -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"
@ -16,15 +17,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
Log logging.Config
Tracing tracing.TracingConfig
AuthZ authz.Config
}
func main() {

View File

@ -7,35 +7,36 @@ Tracing:
Log:
Level: debug
Formatter: text
Formatter:
Format: text
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

5
go.mod
View File

@ -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

10
go.sum
View File

@ -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=

View File

@ -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
}
@ -272,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)
}
})

View File

@ -2,13 +2,16 @@ package auth
import (
"context"
"time"
"github.com/caos/logging"
)
type CtxKeyPermissions struct{}
type CtxKeyData struct{}
type key int
var (
permissionsKey key
dataKey key
)
type CtxData struct {
UserID string
@ -43,24 +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 {
if data := ctx.Value(CtxKeyData{}); data != nil {
ctxData, ok := data.(*CtxData)
if ok {
return *ctxData
}
time.Now()
}
return CtxData{}
ctxData, _ := ctx.Value(dataKey).(CtxData)
return ctxData
}
func GetPermissionsFromCtx(ctx context.Context) []string {
if data := ctx.Value(CtxKeyPermissions{}); data != nil {
ctxPermission, _ := data.([]string)
ctxPermission, _ := ctx.Value(permissionsKey).([]string)
return ctxPermission
}
return nil
}

View File

@ -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 {

View File

@ -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 {
@ -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
}
@ -74,9 +74,7 @@ func Test_GetUserMethodPermissions(t *testing.T) {
},
},
wantErr: true,
errFunc: func(err error) bool {
return caos_errs.IsUnauthenticated(err)
},
errFunc: caos_errs.IsUnauthenticated,
result: []string{"project.read"},
},
{
@ -135,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)
}
})
@ -241,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)
}
})
@ -348,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)
}
})
@ -393,7 +391,6 @@ func Test_AddRoleContextIDToPerm(t *testing.T) {
}
func Test_ExistisPerm(t *testing.T) {
type args struct {
existing []string
perm string

View File

@ -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

View File

@ -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,

View File

@ -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 {
if r == nil {
return langs
}
lang, err := t.cookieHandler.GetCookieValue(r, t.cookieName)
if err == nil {
langs = append(langs, lang)
}
langs = append(langs, r.Header.Get(api.AcceptLanguage))
}
return langs
return append(langs, r.Header.Get(api.AcceptLanguage))
}

View File

@ -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 {

View File

@ -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) {

View File

@ -18,7 +18,6 @@ var (
api.AcceptLanguage,
api.Authorization,
api.ZitadelOrgID,
"x-grpc-web", //TODO: needed
},
AllowedMethods: []string{
http.MethodOptions,

View File

@ -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 {

View File

@ -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)
}
})
}
}

View File

@ -0,0 +1 @@
MoreData: data

View File

@ -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

View File

@ -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)

View File

@ -4,7 +4,7 @@ import (
"golang.org/x/crypto/bcrypt"
)
var _ HashAlg = (*BCrypt)(nil)
var _ HashAlgorithm = (*BCrypt)(nil)
type BCrypt struct {
cost int

View File

@ -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,10 @@ 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 {
if cryptoCode == nil {
return errors.ThrowInvalidArgument(nil, "CRYPT-aqrFV", "cryptoCode must not be nil")
}
code, err := DecryptString(cryptoCode, alg)
if err != nil {
return err
@ -148,6 +151,9 @@ 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 {
if cryptoCode == nil {
return errors.ThrowInvalidArgument(nil, "CRYPT-2q3r", "cryptoCode must not be nil")
}
return CompareHash(cryptoCode, []byte(verificationCode), alg)
}

View File

@ -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))
}

View File

@ -5,11 +5,12 @@ 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) {
mCrypto := NewMockEncryptionAlg(gomock.NewController(t))
func createMockEncryptionAlg(t *testing.T) EncryptionAlgorithm {
mCrypto := NewMockEncryptionAlgorithm(gomock.NewController(t))
mCrypto.EXPECT().Algorithm().AnyTimes().Return("enc")
mCrypto.EXPECT().EncryptionKeyID().AnyTimes().Return("id")
mCrypto.EXPECT().DecryptionKeyIDs().AnyTimes().Return([]string{"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 := NewMockEncryptionAlg(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{
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
}
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,
},
}
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 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"),
}
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 := NewMockEncryptionAlg(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
},
)
creationDate := time.Now()
code := &CryptoValue{
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 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)
}
})
}
generator := NewEncryptionGenerator(6, 0, mCrypto, Digits)
err := VerifyCode(creationDate, 1*time.Hour, code, "wrong", generator)
assert.Error(t, err)
}
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 Test_verifyHashedCode(t *testing.T) {
type args struct {
cryptoCode *CryptoValue
verificationCode string
alg HashAlgorithm
}
tests := []struct {
name string
args args
wantErr bool
}{
func TestIsCodeExpired_NotExpired(t *testing.T) {
creationDate := time.Now()
expired := IsCodeExpired(creationDate, 1*time.Hour)
assert.False(t, expired)
{
"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)
}
})
}
}

View File

@ -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,9 @@ 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 {
if value.Algorithm != alg.Algorithm() {
return errors.ThrowInvalidArgument(nil, "CRYPT-HF32f", "value was hash with a different algorithm")
}
return alg.CompareHash(value.Crypted, comparer)
}

View File

@ -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)
}

View File

@ -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

View File

@ -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

View File

@ -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)
}

View File

@ -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()
}

View File

@ -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

View File

@ -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)}

View File

@ -5,8 +5,9 @@ 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"
)
type Span struct {
@ -39,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
@ -80,7 +79,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) {

View File

@ -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, "ADMIN-n8vw5", "not implemented yet") //TODO: implement
}

View File

@ -3,5 +3,5 @@ package api
import "github.com/caos/zitadel/internal/api/grpc"
type Config struct {
GRPC *grpc.Config
GRPC grpc.Config
}

View File

@ -3,5 +3,5 @@ package api
import "github.com/caos/zitadel/internal/api/grpc"
type Config struct {
GRPC *grpc.Config
GRPC grpc.Config
}

View File

@ -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, "AUTH-l7Hdx", "not implemented yet") //TODO: implement
}

View File

@ -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
}

View File

@ -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
}

View File

@ -3,5 +3,5 @@ package api
import "github.com/caos/zitadel/internal/api/grpc"
type Config struct {
GRPC *grpc.Config
GRPC grpc.Config
}

View File

@ -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
}