mirror of
https://github.com/zitadel/zitadel.git
synced 2025-08-12 16:47:32 +00:00
feat: encryption keys in database (#3265)
* enable overwrite of adminUser fields in defaults.yaml * create schema and table * cli: create keys * cli: create keys * read encryptionkey from db * merge v2 * file names * cleanup defaults.yaml * remove custom errors * load encryptionKeys on start * cleanup * fix merge * update system defaults * fix error message
This commit is contained in:
@@ -53,11 +53,11 @@ func (s *Server) SetUpOrg(ctx context.Context, req *admin_pb.SetUpOrgRequest) (*
|
||||
human := setUpOrgHumanToDomain(req.User.(*admin_pb.SetUpOrgRequest_Human_).Human) //TODO: handle machine
|
||||
org := setUpOrgOrgToDomain(req.Org)
|
||||
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.UserCodeAlg)
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@@ -1,7 +1,6 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/caos/zitadel/internal/admin/repository"
|
||||
@@ -9,6 +8,7 @@ import (
|
||||
"github.com/caos/zitadel/internal/api/authz"
|
||||
"github.com/caos/zitadel/internal/api/grpc/server"
|
||||
"github.com/caos/zitadel/internal/command"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/caos/zitadel/internal/query"
|
||||
"github.com/caos/zitadel/pkg/grpc/admin"
|
||||
)
|
||||
@@ -26,22 +26,27 @@ type Server struct {
|
||||
administrator repository.AdministratorRepository
|
||||
iamDomain string
|
||||
assetsAPIDomain string
|
||||
|
||||
UserCodeAlg crypto.EncryptionAlgorithm
|
||||
userCodeAlg crypto.EncryptionAlgorithm
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Repository eventsourcing.Config
|
||||
}
|
||||
|
||||
func CreateServer(command *command.Commands, query *query.Queries, repo repository.Repository, iamDomain, assetsAPIDomain string, userCrypto *crypto.AESCrypto) *Server {
|
||||
func CreateServer(command *command.Commands,
|
||||
query *query.Queries,
|
||||
repo repository.Repository,
|
||||
iamDomain,
|
||||
assetsAPIDomain string,
|
||||
userCodeAlg crypto.EncryptionAlgorithm,
|
||||
) *Server {
|
||||
return &Server{
|
||||
command: command,
|
||||
query: query,
|
||||
administrator: repo,
|
||||
iamDomain: iamDomain,
|
||||
assetsAPIDomain: assetsAPIDomain,
|
||||
UserCodeAlg: userCrypto,
|
||||
userCodeAlg: userCodeAlg,
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -27,7 +27,7 @@ func (s *Server) GetMyEmail(ctx context.Context, _ *auth_pb.GetMyEmailRequest) (
|
||||
}
|
||||
|
||||
func (s *Server) SetMyEmail(ctx context.Context, req *auth_pb.SetMyEmailRequest) (*auth_pb.SetMyEmailResponse, error) {
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.UserCodeAlg)
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func (s *Server) SetMyEmail(ctx context.Context, req *auth_pb.SetMyEmailRequest)
|
||||
}
|
||||
|
||||
func (s *Server) VerifyMyEmail(ctx context.Context, req *auth_pb.VerifyMyEmailRequest) (*auth_pb.VerifyMyEmailResponse, error) {
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.UserCodeAlg)
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func (s *Server) VerifyMyEmail(ctx context.Context, req *auth_pb.VerifyMyEmailRe
|
||||
|
||||
func (s *Server) ResendMyEmailVerification(ctx context.Context, _ *auth_pb.ResendMyEmailVerificationRequest) (*auth_pb.ResendMyEmailVerificationResponse, error) {
|
||||
ctxData := authz.GetCtxData(ctx)
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.UserCodeAlg)
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@@ -3,13 +3,13 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/caos/zitadel/internal/query"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
|
||||
"github.com/caos/zitadel/internal/api/authz"
|
||||
"github.com/caos/zitadel/internal/api/grpc/object"
|
||||
user_grpc "github.com/caos/zitadel/internal/api/grpc/user"
|
||||
"github.com/caos/zitadel/internal/domain"
|
||||
"github.com/caos/zitadel/internal/query"
|
||||
auth_pb "github.com/caos/zitadel/pkg/grpc/auth"
|
||||
user_pb "github.com/caos/zitadel/pkg/grpc/user"
|
||||
)
|
||||
@@ -57,7 +57,7 @@ func (s *Server) AddMyPasswordless(ctx context.Context, _ *auth_pb.AddMyPassword
|
||||
|
||||
func (s *Server) AddMyPasswordlessLink(ctx context.Context, _ *auth_pb.AddMyPasswordlessLinkRequest) (*auth_pb.AddMyPasswordlessLinkResponse, error) {
|
||||
ctxData := authz.GetCtxData(ctx)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.UserCodeAlg)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -74,7 +74,7 @@ func (s *Server) AddMyPasswordlessLink(ctx context.Context, _ *auth_pb.AddMyPass
|
||||
|
||||
func (s *Server) SendMyPasswordlessLink(ctx context.Context, _ *auth_pb.SendMyPasswordlessLinkRequest) (*auth_pb.SendMyPasswordlessLinkResponse, error) {
|
||||
ctxData := authz.GetCtxData(ctx)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.UserCodeAlg)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@@ -27,7 +27,7 @@ func (s *Server) GetMyPhone(ctx context.Context, _ *auth_pb.GetMyPhoneRequest) (
|
||||
}
|
||||
|
||||
func (s *Server) SetMyPhone(ctx context.Context, req *auth_pb.SetMyPhoneRequest) (*auth_pb.SetMyPhoneResponse, error) {
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func (s *Server) SetMyPhone(ctx context.Context, req *auth_pb.SetMyPhoneRequest)
|
||||
|
||||
func (s *Server) VerifyMyPhone(ctx context.Context, req *auth_pb.VerifyMyPhoneRequest) (*auth_pb.VerifyMyPhoneResponse, error) {
|
||||
ctxData := authz.GetCtxData(ctx)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func (s *Server) VerifyMyPhone(ctx context.Context, req *auth_pb.VerifyMyPhoneRe
|
||||
|
||||
func (s *Server) ResendMyPhoneVerification(ctx context.Context, _ *auth_pb.ResendMyPhoneVerificationRequest) (*auth_pb.ResendMyPhoneVerificationResponse, error) {
|
||||
ctxData := authz.GetCtxData(ctx)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@@ -1,7 +1,6 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/caos/zitadel/internal/api/authz"
|
||||
@@ -10,6 +9,7 @@ import (
|
||||
"github.com/caos/zitadel/internal/auth/repository/eventsourcing"
|
||||
"github.com/caos/zitadel/internal/command"
|
||||
"github.com/caos/zitadel/internal/config/systemdefaults"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/caos/zitadel/internal/query"
|
||||
"github.com/caos/zitadel/pkg/grpc/auth"
|
||||
)
|
||||
@@ -27,21 +27,27 @@ type Server struct {
|
||||
repo repository.Repository
|
||||
defaults systemdefaults.SystemDefaults
|
||||
assetsAPIDomain string
|
||||
UserCodeAlg crypto.EncryptionAlgorithm
|
||||
userCodeAlg crypto.EncryptionAlgorithm
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Repository eventsourcing.Config
|
||||
}
|
||||
|
||||
func CreateServer(command *command.Commands, query *query.Queries, authRepo repository.Repository, defaults systemdefaults.SystemDefaults, assetsAPIDomain string, userCrypto *crypto.AESCrypto) *Server {
|
||||
func CreateServer(command *command.Commands,
|
||||
query *query.Queries,
|
||||
authRepo repository.Repository,
|
||||
defaults systemdefaults.SystemDefaults,
|
||||
assetsAPIDomain string,
|
||||
userCodeAlg crypto.EncryptionAlgorithm,
|
||||
) *Server {
|
||||
return &Server{
|
||||
command: command,
|
||||
query: query,
|
||||
repo: authRepo,
|
||||
defaults: defaults,
|
||||
assetsAPIDomain: assetsAPIDomain,
|
||||
UserCodeAlg: userCrypto,
|
||||
userCodeAlg: userCodeAlg,
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -58,7 +58,7 @@ func (s *Server) ListAppChanges(ctx context.Context, req *mgmt_pb.ListAppChanges
|
||||
}
|
||||
|
||||
func (s *Server) AddOIDCApp(ctx context.Context, req *mgmt_pb.AddOIDCAppRequest) (*mgmt_pb.AddOIDCAppResponse, error) {
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.PasswordHashAlg)
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.passwordHashAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -77,7 +77,7 @@ func (s *Server) AddOIDCApp(ctx context.Context, req *mgmt_pb.AddOIDCAppRequest)
|
||||
}
|
||||
|
||||
func (s *Server) AddAPIApp(ctx context.Context, req *mgmt_pb.AddAPIAppRequest) (*mgmt_pb.AddAPIAppResponse, error) {
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.PasswordHashAlg)
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.passwordHashAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -162,7 +162,7 @@ func (s *Server) RemoveApp(ctx context.Context, req *mgmt_pb.RemoveAppRequest) (
|
||||
}
|
||||
|
||||
func (s *Server) RegenerateOIDCClientSecret(ctx context.Context, req *mgmt_pb.RegenerateOIDCClientSecretRequest) (*mgmt_pb.RegenerateOIDCClientSecretResponse, error) {
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.PasswordHashAlg)
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.passwordHashAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -181,7 +181,7 @@ func (s *Server) RegenerateOIDCClientSecret(ctx context.Context, req *mgmt_pb.Re
|
||||
}
|
||||
|
||||
func (s *Server) RegenerateAPIClientSecret(ctx context.Context, req *mgmt_pb.RegenerateAPIClientSecretRequest) (*mgmt_pb.RegenerateAPIClientSecretResponse, error) {
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.PasswordHashAlg)
|
||||
appSecretGenerator, err := s.query.InitHashGenerator(ctx, domain.SecretGeneratorTypeAppSecret, s.passwordHashAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@@ -1,13 +1,13 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/caos/zitadel/internal/api/authz"
|
||||
"github.com/caos/zitadel/internal/api/grpc/server"
|
||||
"github.com/caos/zitadel/internal/command"
|
||||
"github.com/caos/zitadel/internal/config/systemdefaults"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/caos/zitadel/internal/query"
|
||||
"github.com/caos/zitadel/pkg/grpc/management"
|
||||
)
|
||||
@@ -24,18 +24,23 @@ type Server struct {
|
||||
query *query.Queries
|
||||
systemDefaults systemdefaults.SystemDefaults
|
||||
assetAPIPrefix string
|
||||
PasswordHashAlg crypto.HashAlgorithm
|
||||
UserCodeAlg crypto.EncryptionAlgorithm
|
||||
passwordHashAlg crypto.HashAlgorithm
|
||||
userCodeAlg crypto.EncryptionAlgorithm
|
||||
}
|
||||
|
||||
func CreateServer(command *command.Commands, query *query.Queries, sd systemdefaults.SystemDefaults, assetAPIPrefix string, userCrypto *crypto.AESCrypto) *Server {
|
||||
func CreateServer(command *command.Commands,
|
||||
query *query.Queries,
|
||||
sd systemdefaults.SystemDefaults,
|
||||
assetAPIPrefix string,
|
||||
userCodeAlg crypto.EncryptionAlgorithm,
|
||||
) *Server {
|
||||
return &Server{
|
||||
command: command,
|
||||
query: query,
|
||||
systemDefaults: sd,
|
||||
assetAPIPrefix: assetAPIPrefix,
|
||||
PasswordHashAlg: crypto.NewBCrypt(sd.SecretGenerators.PasswordSaltCost),
|
||||
UserCodeAlg: userCrypto,
|
||||
passwordHashAlg: crypto.NewBCrypt(sd.SecretGenerators.PasswordSaltCost),
|
||||
userCodeAlg: userCodeAlg,
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -192,11 +192,11 @@ func (s *Server) BulkRemoveUserMetadata(ctx context.Context, req *mgmt_pb.BulkRe
|
||||
}
|
||||
|
||||
func (s *Server) AddHumanUser(ctx context.Context, req *mgmt_pb.AddHumanUserRequest) (*mgmt_pb.AddHumanUserResponse, error) {
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.UserCodeAlg)
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -216,15 +216,15 @@ func (s *Server) AddHumanUser(ctx context.Context, req *mgmt_pb.AddHumanUserRequ
|
||||
|
||||
func (s *Server) ImportHumanUser(ctx context.Context, req *mgmt_pb.ImportHumanUserRequest) (*mgmt_pb.ImportHumanUserResponse, error) {
|
||||
human, passwordless := ImportHumanUserRequestToDomain(req)
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.UserCodeAlg)
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.UserCodeAlg)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -408,7 +408,7 @@ func (s *Server) GetHumanEmail(ctx context.Context, req *mgmt_pb.GetHumanEmailRe
|
||||
}
|
||||
|
||||
func (s *Server) UpdateHumanEmail(ctx context.Context, req *mgmt_pb.UpdateHumanEmailRequest) (*mgmt_pb.UpdateHumanEmailResponse, error) {
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.UserCodeAlg)
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -426,7 +426,7 @@ func (s *Server) UpdateHumanEmail(ctx context.Context, req *mgmt_pb.UpdateHumanE
|
||||
}
|
||||
|
||||
func (s *Server) ResendHumanInitialization(ctx context.Context, req *mgmt_pb.ResendHumanInitializationRequest) (*mgmt_pb.ResendHumanInitializationResponse, error) {
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.UserCodeAlg)
|
||||
initCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -440,7 +440,7 @@ func (s *Server) ResendHumanInitialization(ctx context.Context, req *mgmt_pb.Res
|
||||
}
|
||||
|
||||
func (s *Server) ResendHumanEmailVerification(ctx context.Context, req *mgmt_pb.ResendHumanEmailVerificationRequest) (*mgmt_pb.ResendHumanEmailVerificationResponse, error) {
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.UserCodeAlg)
|
||||
emailCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyEmailCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -474,7 +474,7 @@ func (s *Server) GetHumanPhone(ctx context.Context, req *mgmt_pb.GetHumanPhoneRe
|
||||
}
|
||||
|
||||
func (s *Server) UpdateHumanPhone(ctx context.Context, req *mgmt_pb.UpdateHumanPhoneRequest) (*mgmt_pb.UpdateHumanPhoneResponse, error) {
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -502,7 +502,7 @@ func (s *Server) RemoveHumanPhone(ctx context.Context, req *mgmt_pb.RemoveHumanP
|
||||
}
|
||||
|
||||
func (s *Server) ResendHumanPhoneVerification(ctx context.Context, req *mgmt_pb.ResendHumanPhoneVerificationRequest) (*mgmt_pb.ResendHumanPhoneVerificationResponse, error) {
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.UserCodeAlg)
|
||||
phoneCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypeVerifyPhoneCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -547,7 +547,7 @@ func (s *Server) SetHumanPassword(ctx context.Context, req *mgmt_pb.SetHumanPass
|
||||
}
|
||||
|
||||
func (s *Server) SendHumanResetPasswordNotification(ctx context.Context, req *mgmt_pb.SendHumanResetPasswordNotificationRequest) (*mgmt_pb.SendHumanResetPasswordNotificationResponse, error) {
|
||||
passwordCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordResetCode, s.UserCodeAlg)
|
||||
passwordCodeGenerator, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordResetCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -628,7 +628,7 @@ func (s *Server) ListHumanPasswordless(ctx context.Context, req *mgmt_pb.ListHum
|
||||
|
||||
func (s *Server) AddPasswordlessRegistration(ctx context.Context, req *mgmt_pb.AddPasswordlessRegistrationRequest) (*mgmt_pb.AddPasswordlessRegistrationResponse, error) {
|
||||
ctxData := authz.GetCtxData(ctx)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.UserCodeAlg)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -645,7 +645,7 @@ func (s *Server) AddPasswordlessRegistration(ctx context.Context, req *mgmt_pb.A
|
||||
|
||||
func (s *Server) SendPasswordlessRegistration(ctx context.Context, req *mgmt_pb.SendPasswordlessRegistrationRequest) (*mgmt_pb.SendPasswordlessRegistrationResponse, error) {
|
||||
ctxData := authz.GetCtxData(ctx)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.UserCodeAlg)
|
||||
passwordlessInitCode, err := s.query.InitEncryptionGenerator(ctx, domain.SecretGeneratorTypePasswordlessInitCode, s.userCodeAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@@ -6,7 +6,6 @@ import (
|
||||
"time"
|
||||
|
||||
http_utils "github.com/caos/zitadel/internal/api/http"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/caos/zitadel/internal/errors"
|
||||
"github.com/caos/zitadel/internal/id"
|
||||
)
|
||||
@@ -35,16 +34,10 @@ type userAgentHandler struct {
|
||||
|
||||
type UserAgentCookieConfig struct {
|
||||
Name string
|
||||
Key *crypto.KeyConfig
|
||||
MaxAge time.Duration
|
||||
}
|
||||
|
||||
func NewUserAgentHandler(config *UserAgentCookieConfig, domain string, idGenerator id.Generator, externalSecure bool) (func(http.Handler) http.Handler, error) {
|
||||
key, err := crypto.LoadKey(config.Key, config.Key.EncryptionKeyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cookieKey := []byte(key)
|
||||
func NewUserAgentHandler(config *UserAgentCookieConfig, cookieKey []byte, domain string, idGenerator id.Generator, externalSecure bool) (func(http.Handler) http.Handler, error) {
|
||||
opts := []http_utils.CookieHandlerOpt{
|
||||
http_utils.WithEncryption(cookieKey, cookieKey),
|
||||
http_utils.WithDomain(domain),
|
||||
|
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/caos/zitadel/internal/command"
|
||||
"github.com/caos/zitadel/internal/config/systemdefaults"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
caos_errs "github.com/caos/zitadel/internal/errors"
|
||||
"github.com/caos/zitadel/internal/eventstore"
|
||||
"github.com/caos/zitadel/internal/eventstore/handler/crdb"
|
||||
"github.com/caos/zitadel/internal/i18n"
|
||||
@@ -44,7 +45,6 @@ type Config struct {
|
||||
DefaultRefreshTokenExpiration time.Duration
|
||||
UserAgentCookieConfig *middleware.UserAgentCookieConfig
|
||||
Cache *middleware.CacheConfig
|
||||
KeyConfig *crypto.KeyConfig
|
||||
CustomEndpoints *EndpointConfig
|
||||
}
|
||||
|
||||
@@ -83,18 +83,15 @@ type OPStorage struct {
|
||||
assetAPIPrefix string
|
||||
}
|
||||
|
||||
func NewProvider(ctx context.Context, config Config, issuer, defaultLogoutRedirectURI string, command *command.Commands, query *query.Queries, repo repository.Repository, keyConfig systemdefaults.KeyConfig, es *eventstore.Eventstore, projections *sql.DB, keyChan <-chan interface{}, userAgentCookie func(http.Handler) http.Handler) (op.OpenIDProvider, error) {
|
||||
opConfig, err := createOPConfig(config, issuer, defaultLogoutRedirectURI)
|
||||
func NewProvider(ctx context.Context, config Config, issuer, defaultLogoutRedirectURI string, command *command.Commands, query *query.Queries, repo repository.Repository, keyConfig systemdefaults.KeyConfig, encryptionAlg crypto.EncryptionAlgorithm, cryptoKey []byte, es *eventstore.Eventstore, projections *sql.DB, keyChan <-chan interface{}, userAgentCookie func(http.Handler) http.Handler) (op.OpenIDProvider, error) {
|
||||
opConfig, err := createOPConfig(config, issuer, defaultLogoutRedirectURI, cryptoKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot create op config: %w", err)
|
||||
}
|
||||
storage, err := newStorage(config, command, query, repo, keyConfig, config.KeyConfig, es, projections, keyChan)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot create storage: %w", err)
|
||||
return nil, caos_errs.ThrowInternal(err, "OIDC-EGrqd", "cannot create op config: %w")
|
||||
}
|
||||
storage := newStorage(config, command, query, repo, keyConfig, encryptionAlg, es, projections, keyChan)
|
||||
options, err := createOptions(config, userAgentCookie)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot create options: %w", err)
|
||||
return nil, caos_errs.ThrowInternal(err, "OIDC-D3gq1", "cannot create options: %w")
|
||||
}
|
||||
provider, err := op.NewOpenIDProvider(
|
||||
ctx,
|
||||
@@ -103,7 +100,7 @@ func NewProvider(ctx context.Context, config Config, issuer, defaultLogoutRedire
|
||||
options...,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot create provider: %w", err)
|
||||
return nil, caos_errs.ThrowInternal(err, "OIDC-DAtg3", "cannot create provider: %w")
|
||||
}
|
||||
return provider, nil
|
||||
}
|
||||
@@ -112,7 +109,7 @@ func Issuer(domain string, port uint16, externalSecure bool) string {
|
||||
return http_utils.BuildHTTP(domain, port, externalSecure) + HandlerPrefix
|
||||
}
|
||||
|
||||
func createOPConfig(config Config, issuer, defaultLogoutRedirectURI string) (*op.Config, error) {
|
||||
func createOPConfig(config Config, issuer, defaultLogoutRedirectURI string, cryptoKey []byte) (*op.Config, error) {
|
||||
supportedLanguages, err := getSupportedLanguages()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -127,25 +124,13 @@ func createOPConfig(config Config, issuer, defaultLogoutRedirectURI string) (*op
|
||||
RequestObjectSupported: config.RequestObjectSupported,
|
||||
SupportedUILocales: supportedLanguages,
|
||||
}
|
||||
if err := cryptoKey(opConfig, config.KeyConfig); err != nil {
|
||||
return nil, err
|
||||
if cryptoLength := len(cryptoKey); cryptoLength != 32 {
|
||||
return nil, caos_errs.ThrowInternalf(nil, "OIDC-D43gf", "crypto key must be 32 bytes, but is %d", cryptoLength)
|
||||
}
|
||||
copy(opConfig.CryptoKey[:], cryptoKey)
|
||||
return opConfig, nil
|
||||
}
|
||||
|
||||
func cryptoKey(config *op.Config, keyConfig *crypto.KeyConfig) error {
|
||||
tokenKey, err := crypto.LoadKey(keyConfig, keyConfig.EncryptionKeyID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot load OP crypto key: %w", err)
|
||||
}
|
||||
cryptoKey := []byte(tokenKey)
|
||||
if len(cryptoKey) != 32 {
|
||||
return fmt.Errorf("OP crypto key must be exactly 32 bytes")
|
||||
}
|
||||
copy(config.CryptoKey[:], cryptoKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
func createOptions(config Config, userAgentCookie func(http.Handler) http.Handler) ([]op.Option, error) {
|
||||
metricTypes := []metrics.MetricType{metrics.MetricTypeRequestCount, metrics.MetricTypeStatusCode, metrics.MetricTypeTotalCount}
|
||||
interceptor := op.WithHttpInterceptors(
|
||||
@@ -191,11 +176,7 @@ func customEndpoints(endpointConfig *EndpointConfig) []op.Option {
|
||||
return options
|
||||
}
|
||||
|
||||
func newStorage(config Config, command *command.Commands, query *query.Queries, repo repository.Repository, keyConfig systemdefaults.KeyConfig, c *crypto.KeyConfig, es *eventstore.Eventstore, projections *sql.DB, keyChan <-chan interface{}) (*OPStorage, error) {
|
||||
encAlg, err := crypto.NewAESCrypto(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
func newStorage(config Config, command *command.Commands, query *query.Queries, repo repository.Repository, keyConfig systemdefaults.KeyConfig, encAlg crypto.EncryptionAlgorithm, es *eventstore.Eventstore, projections *sql.DB, keyChan <-chan interface{}) *OPStorage {
|
||||
return &OPStorage{
|
||||
repo: repo,
|
||||
command: command,
|
||||
@@ -213,7 +194,7 @@ func newStorage(config Config, command *command.Commands, query *query.Queries,
|
||||
locker: crdb.NewLocker(projections, locksTable, signingKey),
|
||||
keyChan: keyChan,
|
||||
assetAPIPrefix: assets.HandlerPrefix,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (o *OPStorage) Health(ctx context.Context) error {
|
||||
|
@@ -74,7 +74,7 @@ func (l *Login) handleExternalLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if authReq == nil {
|
||||
http.Redirect(w, r, l.zitadelURL, http.StatusFound)
|
||||
http.Redirect(w, r, l.consolePath, http.StatusFound)
|
||||
return
|
||||
}
|
||||
l.handleIDP(w, r, authReq, data.IDPConfigID)
|
||||
@@ -121,7 +121,7 @@ func (l *Login) handleJWTAuthorize(w http.ResponseWriter, r *http.Request, authR
|
||||
l.renderLogin(w, r, authReq, caos_errors.ThrowPreconditionFailed(nil, "LOGIN-dsgg3", "Errors.AuthRequest.UserAgentNotFound"))
|
||||
return
|
||||
}
|
||||
nonce, err := l.IDPConfigAesCrypto.Encrypt([]byte(userAgentID))
|
||||
nonce, err := l.idpConfigAlg.Encrypt([]byte(userAgentID))
|
||||
if err != nil {
|
||||
l.renderLogin(w, r, authReq, err)
|
||||
return
|
||||
@@ -167,7 +167,7 @@ func (l *Login) handleExternalLoginCallback(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
|
||||
func (l *Login) getRPConfig(idpConfig *iam_model.IDPConfigView, callbackEndpoint string) (rp.RelyingParty, error) {
|
||||
oidcClientSecret, err := crypto.DecryptString(idpConfig.OIDCClientSecret, l.IDPConfigAesCrypto)
|
||||
oidcClientSecret, err := crypto.DecryptString(idpConfig.OIDCClientSecret, l.idpConfigAlg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@@ -58,7 +58,7 @@ func (l *Login) handleExternalRegister(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if authReq == nil {
|
||||
http.Redirect(w, r, l.zitadelURL, http.StatusFound)
|
||||
http.Redirect(w, r, l.consolePath, http.StatusFound)
|
||||
return
|
||||
}
|
||||
idpConfig, err := l.getIDPConfigByID(r, data.IDPConfigID)
|
||||
@@ -145,12 +145,12 @@ func (l *Login) registerExternalUser(w http.ResponseWriter, r *http.Request, aut
|
||||
memberRoles = nil
|
||||
resourceOwner = authReq.RequestedOrgID
|
||||
}
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.UserCodeAlg)
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegisterOption(w, r, authReq, err)
|
||||
return
|
||||
}
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.UserCodeAlg)
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegisterOption(w, r, authReq, err)
|
||||
return
|
||||
@@ -226,12 +226,12 @@ func (l *Login) handleExternalRegisterCheck(w http.ResponseWriter, r *http.Reque
|
||||
l.renderRegisterOption(w, r, authReq, err)
|
||||
return
|
||||
}
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.UserCodeAlg)
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegisterOption(w, r, authReq, err)
|
||||
return
|
||||
}
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.UserCodeAlg)
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegisterOption(w, r, authReq, err)
|
||||
return
|
||||
|
@@ -70,7 +70,7 @@ func (l *Login) checkPWCode(w http.ResponseWriter, r *http.Request, authReq *dom
|
||||
userOrg = authReq.UserOrgID
|
||||
}
|
||||
userAgentID, _ := http_mw.UserAgentIDFromCtx(r.Context())
|
||||
passwordCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordResetCode, l.UserCodeAlg)
|
||||
passwordCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordResetCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderInitPassword(w, r, authReq, data.UserID, "", err)
|
||||
return
|
||||
@@ -97,7 +97,7 @@ func (l *Login) resendPasswordSet(w http.ResponseWriter, r *http.Request, authRe
|
||||
l.renderInitPassword(w, r, authReq, authReq.UserID, "", err)
|
||||
return
|
||||
}
|
||||
passwordCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordResetCode, l.UserCodeAlg)
|
||||
passwordCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordResetCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderInitPassword(w, r, authReq, authReq.UserID, "", err)
|
||||
return
|
||||
|
@@ -73,7 +73,7 @@ func (l *Login) checkUserInitCode(w http.ResponseWriter, r *http.Request, authRe
|
||||
if authReq != nil {
|
||||
userOrgID = authReq.UserOrgID
|
||||
}
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.UserCodeAlg)
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderInitUser(w, r, authReq, data.UserID, "", data.PasswordSet, err)
|
||||
return
|
||||
@@ -91,7 +91,7 @@ func (l *Login) resendUserInit(w http.ResponseWriter, r *http.Request, authReq *
|
||||
if authReq != nil {
|
||||
userOrgID = authReq.UserOrgID
|
||||
}
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.UserCodeAlg)
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderInitUser(w, r, authReq, userID, "", showPassword, err)
|
||||
return
|
||||
|
@@ -39,7 +39,7 @@ func (l *Login) handleJWTRequest(w http.ResponseWriter, r *http.Request) {
|
||||
l.renderError(w, r, nil, err)
|
||||
return
|
||||
}
|
||||
userAgentID, err := l.IDPConfigAesCrypto.DecryptString(id, l.IDPConfigAesCrypto.EncryptionKeyID())
|
||||
userAgentID, err := l.idpConfigAlg.DecryptString(id, l.idpConfigAlg.EncryptionKeyID())
|
||||
if err != nil {
|
||||
l.renderError(w, r, nil, err)
|
||||
return
|
||||
@@ -181,7 +181,7 @@ func (l *Login) redirectToJWTCallback(authReq *domain.AuthRequest) (string, erro
|
||||
}
|
||||
q := redirect.Query()
|
||||
q.Set(QueryAuthRequestID, authReq.ID)
|
||||
nonce, err := l.IDPConfigAesCrypto.Encrypt([]byte(authReq.AgentID))
|
||||
nonce, err := l.idpConfigAlg.Encrypt([]byte(authReq.AgentID))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -202,7 +202,7 @@ func (l *Login) handleJWTCallback(w http.ResponseWriter, r *http.Request) {
|
||||
l.renderError(w, r, nil, err)
|
||||
return
|
||||
}
|
||||
userAgentID, err := l.IDPConfigAesCrypto.DecryptString(id, l.IDPConfigAesCrypto.EncryptionKeyID())
|
||||
userAgentID, err := l.idpConfigAlg.DecryptString(id, l.idpConfigAlg.EncryptionKeyID())
|
||||
if err != nil {
|
||||
l.renderError(w, r, nil, err)
|
||||
return
|
||||
|
@@ -35,47 +35,54 @@ type Login struct {
|
||||
//staticCache cache.Cache //TODO: enable when storage is implemented again
|
||||
authRepo auth_repository.Repository
|
||||
baseURL string
|
||||
zitadelURL string
|
||||
consolePath string
|
||||
oidcAuthCallbackURL string
|
||||
IDPConfigAesCrypto crypto.EncryptionAlgorithm
|
||||
UserCodeAlg crypto.EncryptionAlgorithm
|
||||
idpConfigAlg crypto.EncryptionAlgorithm
|
||||
userCodeAlg crypto.EncryptionAlgorithm
|
||||
iamDomain string
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
LanguageCookieName string
|
||||
CSRF CSRF
|
||||
CSRFCookieName string
|
||||
Cache middleware.CacheConfig
|
||||
//StaticCache cache_config.CacheConfig //TODO: enable when storage is implemented again
|
||||
}
|
||||
|
||||
type CSRF struct {
|
||||
CookieName string
|
||||
Key *crypto.KeyConfig
|
||||
}
|
||||
|
||||
const (
|
||||
login = "LOGIN"
|
||||
HandlerPrefix = "/ui/login"
|
||||
DefaultLoggedOutPath = HandlerPrefix + EndpointLogoutDone
|
||||
)
|
||||
|
||||
func CreateLogin(config Config, command *command.Commands, query *query.Queries, authRepo *eventsourcing.EsRepository, staticStorage static.Storage, systemDefaults systemdefaults.SystemDefaults, zitadelURL, domain, oidcAuthCallbackURL string, externalSecure bool, userAgentCookie mux.MiddlewareFunc, userCrypto *crypto.AESCrypto) (*Login, error) {
|
||||
aesCrypto, err := crypto.NewAESCrypto(systemDefaults.IDPConfigVerificationKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error create new aes crypto: %w", err)
|
||||
}
|
||||
func CreateLogin(config Config,
|
||||
command *command.Commands,
|
||||
query *query.Queries,
|
||||
authRepo *eventsourcing.EsRepository,
|
||||
staticStorage static.Storage,
|
||||
systemDefaults systemdefaults.SystemDefaults,
|
||||
consolePath,
|
||||
domain,
|
||||
baseURL,
|
||||
oidcAuthCallbackURL string,
|
||||
externalSecure bool,
|
||||
userAgentCookie mux.MiddlewareFunc,
|
||||
userCodeAlg crypto.EncryptionAlgorithm,
|
||||
idpConfigAlg crypto.EncryptionAlgorithm,
|
||||
csrfCookieKey []byte,
|
||||
) (*Login, error) {
|
||||
|
||||
login := &Login{
|
||||
oidcAuthCallbackURL: oidcAuthCallbackURL,
|
||||
baseURL: HandlerPrefix,
|
||||
zitadelURL: zitadelURL,
|
||||
baseURL: baseURL + HandlerPrefix,
|
||||
consolePath: consolePath,
|
||||
command: command,
|
||||
query: query,
|
||||
staticStorage: staticStorage,
|
||||
authRepo: authRepo,
|
||||
IDPConfigAesCrypto: aesCrypto,
|
||||
iamDomain: domain,
|
||||
UserCodeAlg: userCrypto,
|
||||
idpConfigAlg: idpConfigAlg,
|
||||
userCodeAlg: userCodeAlg,
|
||||
}
|
||||
//TODO: enable when storage is implemented again
|
||||
//login.staticCache, err = config.StaticCache.Config.NewCache()
|
||||
@@ -88,7 +95,7 @@ func CreateLogin(config Config, command *command.Commands, query *query.Queries,
|
||||
return nil, fmt.Errorf("unable to create filesystem: %w", err)
|
||||
}
|
||||
|
||||
csrfInterceptor, err := createCSRFInterceptor(config.CSRF, externalSecure, login.csrfErrorHandler())
|
||||
csrfInterceptor, err := createCSRFInterceptor(config.CSRFCookieName, csrfCookieKey, externalSecure, login.csrfErrorHandler())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to create csrfInterceptor: %w", err)
|
||||
}
|
||||
@@ -111,15 +118,11 @@ func csp() *middleware.CSP {
|
||||
return &csp
|
||||
}
|
||||
|
||||
func createCSRFInterceptor(config CSRF, externalSecure bool, errorHandler http.Handler) (func(http.Handler) http.Handler, error) {
|
||||
csrfKey, err := crypto.LoadKey(config.Key, config.Key.EncryptionKeyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
func createCSRFInterceptor(cookieName string, csrfCookieKey []byte, externalSecure bool, errorHandler http.Handler) (func(http.Handler) http.Handler, error) {
|
||||
path := "/"
|
||||
return csrf.Protect([]byte(csrfKey),
|
||||
return csrf.Protect(csrfCookieKey,
|
||||
csrf.Secure(externalSecure),
|
||||
csrf.CookieName(http_utils.SetCookiePrefix(config.CookieName, "", path, externalSecure)),
|
||||
csrf.CookieName(http_utils.SetCookiePrefix(cookieName, "", path, externalSecure)),
|
||||
csrf.Path(path),
|
||||
csrf.ErrorHandler(errorHandler),
|
||||
), nil
|
||||
|
@@ -24,7 +24,7 @@ func (l *Login) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if authReq == nil {
|
||||
http.Redirect(w, r, l.zitadelURL, http.StatusFound)
|
||||
http.Redirect(w, r, l.consolePath, http.StatusFound)
|
||||
return
|
||||
}
|
||||
l.renderNextStep(w, r, authReq)
|
||||
|
@@ -51,7 +51,7 @@ func (l *Login) handleMailVerificationCheck(w http.ResponseWriter, r *http.Reque
|
||||
if authReq != nil {
|
||||
userOrg = authReq.UserOrgID
|
||||
}
|
||||
emailCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyEmailCode, l.UserCodeAlg)
|
||||
emailCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyEmailCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.checkMailCode(w, r, authReq, data.UserID, data.Code)
|
||||
return
|
||||
@@ -66,7 +66,7 @@ func (l *Login) checkMailCode(w http.ResponseWriter, r *http.Request, authReq *d
|
||||
userID = authReq.UserID
|
||||
userOrg = authReq.UserOrgID
|
||||
}
|
||||
emailCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyEmailCode, l.UserCodeAlg)
|
||||
emailCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyEmailCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderMailVerification(w, r, authReq, userID, err)
|
||||
return
|
||||
|
@@ -27,7 +27,7 @@ func (l *Login) handlePasswordReset(w http.ResponseWriter, r *http.Request) {
|
||||
l.renderPasswordResetDone(w, r, authReq, err)
|
||||
return
|
||||
}
|
||||
passwordCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordResetCode, l.UserCodeAlg)
|
||||
passwordCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordResetCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderPasswordResetDone(w, r, authReq, err)
|
||||
return
|
||||
|
@@ -74,12 +74,12 @@ func (l *Login) handleRegisterCheck(w http.ResponseWriter, r *http.Request) {
|
||||
memberRoles = nil
|
||||
resourceOwner = authRequest.RequestedOrgID
|
||||
}
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.UserCodeAlg)
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeInitCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegister(w, r, authRequest, data, err)
|
||||
return
|
||||
}
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.UserCodeAlg)
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegister(w, r, authRequest, data, err)
|
||||
return
|
||||
@@ -90,7 +90,7 @@ func (l *Login) handleRegisterCheck(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if authRequest == nil {
|
||||
http.Redirect(w, r, l.zitadelURL, http.StatusFound)
|
||||
http.Redirect(w, r, l.consolePath, http.StatusFound)
|
||||
return
|
||||
}
|
||||
userAgentID, _ := http_mw.UserAgentIDFromCtx(r.Context())
|
||||
|
@@ -65,12 +65,12 @@ func (l *Login) handleRegisterOrgCheck(w http.ResponseWriter, r *http.Request) {
|
||||
l.renderRegisterOrg(w, r, authRequest, data, err)
|
||||
return
|
||||
}
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordlessInitCode, l.UserCodeAlg)
|
||||
initCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypePasswordlessInitCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegisterOrg(w, r, authRequest, data, err)
|
||||
return
|
||||
}
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.UserCodeAlg)
|
||||
phoneCodeGenerator, err := l.query.InitEncryptionGenerator(r.Context(), domain.SecretGeneratorTypeVerifyPhoneCode, l.userCodeAlg)
|
||||
if err != nil {
|
||||
l.renderRegisterOrg(w, r, authRequest, data, err)
|
||||
return
|
||||
@@ -81,7 +81,7 @@ func (l *Login) handleRegisterOrgCheck(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if authRequest == nil {
|
||||
http.Redirect(w, r, l.zitadelURL, http.StatusFound)
|
||||
http.Redirect(w, r, l.consolePath, http.StatusFound)
|
||||
return
|
||||
}
|
||||
l.renderNextStep(w, r, authRequest)
|
||||
|
@@ -5,13 +5,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/caos/logging"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
|
||||
"github.com/caos/zitadel/internal/api/authz"
|
||||
"github.com/caos/zitadel/internal/auth/repository/eventsourcing/view"
|
||||
"github.com/caos/zitadel/internal/auth_request/model"
|
||||
cache "github.com/caos/zitadel/internal/auth_request/repository"
|
||||
"github.com/caos/zitadel/internal/command"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/caos/zitadel/internal/domain"
|
||||
"github.com/caos/zitadel/internal/errors"
|
||||
v1 "github.com/caos/zitadel/internal/eventstore/v1"
|
||||
@@ -666,15 +666,20 @@ func queryLoginPolicyToDomain(policy *query.LoginPolicy) *domain.LoginPolicy {
|
||||
CreationDate: policy.CreationDate,
|
||||
ChangeDate: policy.ChangeDate,
|
||||
},
|
||||
Default: policy.IsDefault,
|
||||
AllowUsernamePassword: policy.AllowUsernamePassword,
|
||||
AllowRegister: policy.AllowRegister,
|
||||
AllowExternalIDP: policy.AllowExternalIDPs,
|
||||
ForceMFA: policy.ForceMFA,
|
||||
SecondFactors: policy.SecondFactors,
|
||||
MultiFactors: policy.MultiFactors,
|
||||
PasswordlessType: policy.PasswordlessType,
|
||||
HidePasswordReset: policy.HidePasswordReset,
|
||||
Default: policy.IsDefault,
|
||||
AllowUsernamePassword: policy.AllowUsernamePassword,
|
||||
AllowRegister: policy.AllowRegister,
|
||||
AllowExternalIDP: policy.AllowExternalIDPs,
|
||||
ForceMFA: policy.ForceMFA,
|
||||
SecondFactors: policy.SecondFactors,
|
||||
MultiFactors: policy.MultiFactors,
|
||||
PasswordlessType: policy.PasswordlessType,
|
||||
HidePasswordReset: policy.HidePasswordReset,
|
||||
PasswordCheckLifetime: policy.PasswordCheckLifetime,
|
||||
ExternalLoginCheckLifetime: policy.ExternalLoginCheckLifetime,
|
||||
MFAInitSkipLifetime: policy.MFAInitSkipLifetime,
|
||||
SecondFactorCheckLifetime: policy.SecondFactorCheckLifetime,
|
||||
MultiFactorCheckLifetime: policy.MultiFactorCheckLifetime,
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -33,19 +33,14 @@ type EsRepository struct {
|
||||
eventstore.OrgRepository
|
||||
}
|
||||
|
||||
func Start(conf Config, systemDefaults sd.SystemDefaults, command *command.Commands, queries *query.Queries, dbClient *sql.DB, keyConfig *crypto.KeyConfig, assetsPrefix string, userCrypto *crypto.AESCrypto) (*EsRepository, error) {
|
||||
func Start(conf Config, systemDefaults sd.SystemDefaults, command *command.Commands, queries *query.Queries, dbClient *sql.DB, assetsPrefix string, oidcEncryption crypto.EncryptionAlgorithm, userEncryption crypto.EncryptionAlgorithm) (*EsRepository, error) {
|
||||
es, err := v1.Start(dbClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keyAlgorithm, err := crypto.NewAESCrypto(keyConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
idGenerator := id.SonyFlakeGenerator
|
||||
|
||||
view, err := auth_view.StartView(dbClient, keyAlgorithm, queries, idGenerator, assetsPrefix)
|
||||
view, err := auth_view.StartView(dbClient, oidcEncryption, queries, idGenerator, assetsPrefix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -80,7 +75,7 @@ func Start(conf Config, systemDefaults sd.SystemDefaults, command *command.Comma
|
||||
AuthRequests: authReq,
|
||||
View: view,
|
||||
Eventstore: es,
|
||||
UserCodeAlg: userCrypto,
|
||||
UserCodeAlg: userEncryption,
|
||||
UserSessionViewProvider: view,
|
||||
UserViewProvider: view,
|
||||
UserCommandProvider: command,
|
||||
@@ -101,7 +96,7 @@ func Start(conf Config, systemDefaults sd.SystemDefaults, command *command.Comma
|
||||
View: view,
|
||||
Eventstore: es,
|
||||
SearchLimit: conf.SearchLimit,
|
||||
KeyAlgorithm: keyAlgorithm,
|
||||
KeyAlgorithm: oidcEncryption,
|
||||
},
|
||||
eventstore.UserSessionRepo{
|
||||
View: view,
|
||||
|
@@ -14,6 +14,6 @@ type Config struct {
|
||||
Repository eventsourcing.Config
|
||||
}
|
||||
|
||||
func Start(config Config, systemDefaults sd.SystemDefaults, queries *query.Queries, dbClient *sql.DB, keyConfig *crypto.KeyConfig) (repository.Repository, error) {
|
||||
return eventsourcing.Start(config.Repository, systemDefaults, queries, dbClient, keyConfig)
|
||||
func Start(config Config, systemDefaults sd.SystemDefaults, queries *query.Queries, dbClient *sql.DB, keyEncryptionAlgorithm crypto.EncryptionAlgorithm) (repository.Repository, error) {
|
||||
return eventsourcing.Start(config.Repository, systemDefaults, queries, dbClient, keyEncryptionAlgorithm)
|
||||
}
|
||||
|
@@ -26,7 +26,7 @@ type EsRepository struct {
|
||||
eventstore.TokenVerifierRepo
|
||||
}
|
||||
|
||||
func Start(conf Config, systemDefaults sd.SystemDefaults, queries *query.Queries, dbClient *sql.DB, keyConfig *crypto.KeyConfig) (repository.Repository, error) {
|
||||
func Start(conf Config, systemDefaults sd.SystemDefaults, queries *query.Queries, dbClient *sql.DB, keyEncryptionAlgorithm crypto.EncryptionAlgorithm) (repository.Repository, error) {
|
||||
es, err := v1.Start(dbClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -40,18 +40,13 @@ func Start(conf Config, systemDefaults sd.SystemDefaults, queries *query.Queries
|
||||
|
||||
spool := spooler.StartSpooler(conf.Spooler, es, view, dbClient, systemDefaults)
|
||||
|
||||
keyAlgorithm, err := crypto.NewAESCrypto(keyConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &EsRepository{
|
||||
spool,
|
||||
eventstore.UserMembershipRepo{
|
||||
View: view,
|
||||
},
|
||||
eventstore.TokenVerifierRepo{
|
||||
TokenVerificationKey: keyAlgorithm,
|
||||
TokenVerificationKey: keyEncryptionAlgorithm,
|
||||
Eventstore: es,
|
||||
View: view,
|
||||
Query: queries,
|
||||
|
@@ -54,28 +54,33 @@ type orgFeatureChecker interface {
|
||||
CheckOrgFeatures(ctx context.Context, orgID string, requiredFeatures ...string) error
|
||||
}
|
||||
|
||||
func StartCommands(
|
||||
es *eventstore.Eventstore,
|
||||
func StartCommands(es *eventstore.Eventstore,
|
||||
defaults sd.SystemDefaults,
|
||||
authZConfig authz.Config,
|
||||
staticStore static.Storage,
|
||||
authZRepo authz_repo.Repository,
|
||||
keyConfig *crypto.KeyConfig,
|
||||
webAuthN webauthn_helper.Config,
|
||||
smtpPasswordEncAlg crypto.EncryptionAlgorithm,
|
||||
smsHashAlg crypto.EncryptionAlgorithm,
|
||||
idpConfigEncryption,
|
||||
otpEncryption,
|
||||
smtpEncryption,
|
||||
smsEncryption,
|
||||
domainVerificationEncryption,
|
||||
oidcEncryption crypto.EncryptionAlgorithm,
|
||||
) (repo *Commands, err error) {
|
||||
repo = &Commands{
|
||||
eventstore: es,
|
||||
static: staticStore,
|
||||
idGenerator: id.SonyFlakeGenerator,
|
||||
iamDomain: defaults.Domain,
|
||||
zitadelRoles: authZConfig.RolePermissionMappings,
|
||||
keySize: defaults.KeyConfig.Size,
|
||||
privateKeyLifetime: defaults.KeyConfig.PrivateKeyLifetime,
|
||||
publicKeyLifetime: defaults.KeyConfig.PublicKeyLifetime,
|
||||
smtpPasswordCrypto: smtpPasswordEncAlg,
|
||||
smsCrypto: smsHashAlg,
|
||||
eventstore: es,
|
||||
static: staticStore,
|
||||
idGenerator: id.SonyFlakeGenerator,
|
||||
iamDomain: defaults.Domain,
|
||||
zitadelRoles: authZConfig.RolePermissionMappings,
|
||||
keySize: defaults.KeyConfig.Size,
|
||||
privateKeyLifetime: defaults.KeyConfig.PrivateKeyLifetime,
|
||||
publicKeyLifetime: defaults.KeyConfig.PublicKeyLifetime,
|
||||
idpConfigSecretCrypto: idpConfigEncryption,
|
||||
smtpPasswordCrypto: smtpEncryption,
|
||||
smsCrypto: smsEncryption,
|
||||
domainVerificationAlg: domainVerificationEncryption,
|
||||
keyAlgorithm: oidcEncryption,
|
||||
}
|
||||
iam_repo.RegisterEventMappers(repo.eventstore)
|
||||
org.RegisterEventMappers(repo.eventstore)
|
||||
@@ -85,30 +90,17 @@ func StartCommands(
|
||||
keypair.RegisterEventMappers(repo.eventstore)
|
||||
action.RegisterEventMappers(repo.eventstore)
|
||||
|
||||
repo.idpConfigSecretCrypto, err = crypto.NewAESCrypto(defaults.IDPConfigVerificationKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
repo.userPasswordAlg = crypto.NewBCrypt(defaults.SecretGenerators.PasswordSaltCost)
|
||||
repo.machineKeySize = int(defaults.SecretGenerators.MachineKeySize)
|
||||
repo.applicationKeySize = int(defaults.SecretGenerators.ApplicationKeySize)
|
||||
|
||||
aesOTPCrypto, err := crypto.NewAESCrypto(defaults.Multifactors.OTP.VerificationKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repo.multifactors = domain.MultifactorConfigs{
|
||||
OTP: domain.OTPConfig{
|
||||
CryptoMFA: aesOTPCrypto,
|
||||
CryptoMFA: otpEncryption,
|
||||
Issuer: defaults.Multifactors.OTP.Issuer,
|
||||
},
|
||||
}
|
||||
|
||||
repo.domainVerificationAlg, err = crypto.NewAESCrypto(defaults.DomainVerification.VerificationKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repo.domainVerificationGenerator = crypto.NewEncryptionGenerator(defaults.DomainVerification.VerificationGenerator, repo.domainVerificationAlg)
|
||||
repo.domainVerificationValidator = http.ValidateDomain
|
||||
web, err := webauthn_helper.StartServer(webAuthN)
|
||||
@@ -117,12 +109,6 @@ func StartCommands(
|
||||
}
|
||||
repo.webauthn = web
|
||||
|
||||
keyAlgorithm, err := crypto.NewAESCrypto(keyConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
repo.keyAlgorithm = keyAlgorithm
|
||||
|
||||
repo.tokenVerifier = authZRepo
|
||||
return repo, nil
|
||||
}
|
||||
|
@@ -6,25 +6,17 @@ import (
|
||||
"golang.org/x/text/language"
|
||||
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/caos/zitadel/internal/notification/channels/fs"
|
||||
"github.com/caos/zitadel/internal/notification/channels/log"
|
||||
"github.com/caos/zitadel/internal/notification/channels/twilio"
|
||||
"github.com/caos/zitadel/internal/notification/templates"
|
||||
)
|
||||
|
||||
type SystemDefaults struct {
|
||||
DefaultLanguage language.Tag
|
||||
Domain string
|
||||
ZitadelDocs ZitadelDocs
|
||||
SecretGenerators SecretGenerators
|
||||
UserVerificationKey *crypto.KeyConfig
|
||||
IDPConfigVerificationKey *crypto.KeyConfig
|
||||
SMTPPasswordVerificationKey *crypto.KeyConfig
|
||||
SMSVerificationKey *crypto.KeyConfig
|
||||
Multifactors MultifactorConfig
|
||||
DomainVerification DomainVerification
|
||||
Notifications Notifications
|
||||
KeyConfig KeyConfig
|
||||
DefaultLanguage language.Tag
|
||||
Domain string
|
||||
ZitadelDocs ZitadelDocs
|
||||
SecretGenerators SecretGenerators
|
||||
Multifactors MultifactorConfig
|
||||
DomainVerification DomainVerification
|
||||
Notifications Notifications
|
||||
KeyConfig KeyConfig
|
||||
}
|
||||
|
||||
type ZitadelDocs struct {
|
||||
@@ -43,20 +35,16 @@ type MultifactorConfig struct {
|
||||
}
|
||||
|
||||
type OTPConfig struct {
|
||||
Issuer string
|
||||
VerificationKey *crypto.KeyConfig
|
||||
Issuer string
|
||||
}
|
||||
|
||||
type DomainVerification struct {
|
||||
VerificationKey *crypto.KeyConfig
|
||||
VerificationGenerator crypto.GeneratorConfig
|
||||
}
|
||||
|
||||
type Notifications struct {
|
||||
DebugMode bool
|
||||
Endpoints Endpoints
|
||||
FileSystemPath string
|
||||
//Providers Channels
|
||||
}
|
||||
|
||||
type Endpoints struct {
|
||||
@@ -67,20 +55,6 @@ type Endpoints struct {
|
||||
PasswordlessRegistration string
|
||||
}
|
||||
|
||||
type Channels struct {
|
||||
Twilio twilio.TwilioConfig
|
||||
FileSystem fs.FSConfig
|
||||
Log log.LogConfig
|
||||
}
|
||||
|
||||
type TemplateData struct {
|
||||
InitCode templates.TemplateData
|
||||
PasswordReset templates.TemplateData
|
||||
VerifyEmail templates.TemplateData
|
||||
VerifyPhone templates.TemplateData
|
||||
DomainClaimed templates.TemplateData
|
||||
}
|
||||
|
||||
type KeyConfig struct {
|
||||
Size int
|
||||
PrivateKeyLifetime time.Duration
|
||||
|
@@ -18,8 +18,8 @@ type AESCrypto struct {
|
||||
keyIDs []string
|
||||
}
|
||||
|
||||
func NewAESCrypto(config *KeyConfig) (*AESCrypto, error) {
|
||||
keys, ids, err := LoadKeys(config)
|
||||
func NewAESCrypto(config *KeyConfig, keyStorage KeyStorage) (*AESCrypto, error) {
|
||||
keys, ids, err := LoadKeys(config, keyStorage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
133
internal/crypto/database/database.go
Normal file
133
internal/crypto/database/database.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
sq "github.com/Masterminds/squirrel"
|
||||
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
caos_errs "github.com/caos/zitadel/internal/errors"
|
||||
)
|
||||
|
||||
type database struct {
|
||||
client *sql.DB
|
||||
masterKey string
|
||||
encrypt func(key, masterKey string) (encryptedKey string, err error)
|
||||
decrypt func(encryptedKey, masterKey string) (key string, err error)
|
||||
}
|
||||
|
||||
const (
|
||||
EncryptionKeysTable = "system.encryption_keys"
|
||||
encryptionKeysIDCol = "id"
|
||||
encryptionKeysKeyCol = "key"
|
||||
)
|
||||
|
||||
func NewKeyStorage(client *sql.DB, masterKey string) (*database, error) {
|
||||
if err := checkMasterKeyLength(masterKey); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &database{
|
||||
client: client,
|
||||
masterKey: masterKey,
|
||||
encrypt: crypto.EncryptAESString,
|
||||
decrypt: crypto.DecryptAESString,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *database) ReadKeys() (crypto.Keys, error) {
|
||||
keys := make(map[string]string)
|
||||
stmt, args, err := sq.Select(encryptionKeysIDCol, encryptionKeysKeyCol).
|
||||
From(EncryptionKeysTable).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to read keys")
|
||||
}
|
||||
rows, err := d.client.Query(stmt, args...)
|
||||
if err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to read keys")
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, encryptionKey string
|
||||
err = rows.Scan(&id, &encryptionKey)
|
||||
if err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to read keys")
|
||||
}
|
||||
key, err := d.decrypt(encryptionKey, d.masterKey)
|
||||
if err != nil {
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to close rows")
|
||||
}
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to decrypt key")
|
||||
}
|
||||
keys[id] = key
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to close rows")
|
||||
}
|
||||
return keys, err
|
||||
}
|
||||
|
||||
func (d *database) ReadKey(id string) (*crypto.Key, error) {
|
||||
stmt, args, err := sq.Select(encryptionKeysKeyCol).
|
||||
From(EncryptionKeysTable).
|
||||
Where(sq.Eq{encryptionKeysIDCol: id}).
|
||||
PlaceholderFormat(sq.Dollar).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to read key")
|
||||
}
|
||||
row := d.client.QueryRow(stmt, args...)
|
||||
if err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to read key")
|
||||
}
|
||||
var encryptionKey string
|
||||
err = row.Scan(&encryptionKey)
|
||||
if err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to read key")
|
||||
}
|
||||
key, err := d.decrypt(encryptionKey, d.masterKey)
|
||||
if err != nil {
|
||||
return nil, caos_errs.ThrowInternal(err, "", "unable to decrypt key")
|
||||
}
|
||||
return &crypto.Key{
|
||||
ID: id,
|
||||
Value: key,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *database) CreateKeys(keys ...*crypto.Key) error {
|
||||
insert := sq.Insert(EncryptionKeysTable).
|
||||
Columns(encryptionKeysIDCol, encryptionKeysKeyCol).PlaceholderFormat(sq.Dollar)
|
||||
for _, key := range keys {
|
||||
encryptionKey, err := d.encrypt(key.Value, d.masterKey)
|
||||
if err != nil {
|
||||
return caos_errs.ThrowInternal(err, "", "unable to encrypt key")
|
||||
}
|
||||
insert = insert.Values(key.ID, encryptionKey)
|
||||
}
|
||||
stmt, args, err := insert.ToSql()
|
||||
if err != nil {
|
||||
return caos_errs.ThrowInternal(err, "", "unable to insert new keys")
|
||||
}
|
||||
tx, err := d.client.Begin()
|
||||
if err != nil {
|
||||
return caos_errs.ThrowInternal(err, "", "unable to insert new keys")
|
||||
}
|
||||
_, err = tx.Exec(stmt, args...)
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
return caos_errs.ThrowInternal(err, "", "unable to insert new keys")
|
||||
}
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
return caos_errs.ThrowInternal(err, "", "unable to insert new keys")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkMasterKeyLength(masterKey string) error {
|
||||
if length := len([]byte(masterKey)); length != 32 {
|
||||
return caos_errs.ThrowInternalf(nil, "", "masterkey must be 32 bytes, but is %d", length)
|
||||
}
|
||||
return nil
|
||||
}
|
524
internal/crypto/database/database_test.go
Normal file
524
internal/crypto/database/database_test.go
Normal file
@@ -0,0 +1,524 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
caos_errs "github.com/caos/zitadel/internal/errors"
|
||||
)
|
||||
|
||||
func Test_database_ReadKeys(t *testing.T) {
|
||||
type fields struct {
|
||||
client db
|
||||
masterKey string
|
||||
decrypt func(encryptedKey, masterKey string) (key string, err error)
|
||||
}
|
||||
type res struct {
|
||||
keys crypto.Keys
|
||||
err func(error) bool
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
res res
|
||||
}{
|
||||
{
|
||||
"query fails, error",
|
||||
fields{
|
||||
client: dbMock(t, expectQueryErr("SELECT id, key FROM system.encryption_keys", sql.ErrConnDone)),
|
||||
masterKey: "",
|
||||
decrypt: nil,
|
||||
},
|
||||
res{
|
||||
err: func(err error) bool {
|
||||
return errors.Is(err, sql.ErrConnDone)
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"decryption error",
|
||||
fields{
|
||||
client: dbMock(t, expectQuery(
|
||||
"SELECT id, key FROM system.encryption_keys",
|
||||
[]string{"id", "key"},
|
||||
[][]driver.Value{
|
||||
{
|
||||
"id1",
|
||||
"key1",
|
||||
},
|
||||
})),
|
||||
masterKey: "wrong key",
|
||||
decrypt: func(encryptedKey, masterKey string) (key string, err error) {
|
||||
return "", fmt.Errorf("wrong masterkey")
|
||||
},
|
||||
},
|
||||
res{
|
||||
err: caos_errs.IsInternal,
|
||||
},
|
||||
},
|
||||
{
|
||||
"single key ok",
|
||||
fields{
|
||||
client: dbMock(t, expectQuery(
|
||||
"SELECT id, key FROM system.encryption_keys",
|
||||
[]string{"id", "key"},
|
||||
[][]driver.Value{
|
||||
{
|
||||
"id1",
|
||||
"key1",
|
||||
},
|
||||
})),
|
||||
masterKey: "masterKey",
|
||||
decrypt: func(encryptedKey, masterKey string) (key string, err error) {
|
||||
return encryptedKey, nil
|
||||
},
|
||||
},
|
||||
res{
|
||||
keys: crypto.Keys(map[string]string{"id1": "key1"}),
|
||||
},
|
||||
},
|
||||
{
|
||||
"multiple keys ok",
|
||||
fields{
|
||||
client: dbMock(t, expectQuery(
|
||||
"SELECT id, key FROM system.encryption_keys",
|
||||
[]string{"id", "key"},
|
||||
[][]driver.Value{
|
||||
{
|
||||
"id1",
|
||||
"key1",
|
||||
},
|
||||
{
|
||||
"id2",
|
||||
"key2",
|
||||
},
|
||||
})),
|
||||
masterKey: "masterKey",
|
||||
decrypt: func(encryptedKey, masterKey string) (key string, err error) {
|
||||
return encryptedKey, nil
|
||||
},
|
||||
},
|
||||
res{
|
||||
keys: crypto.Keys(map[string]string{"id1": "key1", "id2": "key2"}),
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
d := &database{
|
||||
client: tt.fields.client.db,
|
||||
masterKey: tt.fields.masterKey,
|
||||
decrypt: tt.fields.decrypt,
|
||||
}
|
||||
got, err := d.ReadKeys()
|
||||
if tt.res.err == nil {
|
||||
assert.NoError(t, err)
|
||||
} else if tt.res.err != nil && !tt.res.err(err) {
|
||||
t.Errorf("got wrong err: %v", err)
|
||||
}
|
||||
if tt.res.err == nil {
|
||||
assert.Equal(t, tt.res.keys, got)
|
||||
}
|
||||
if err := tt.fields.client.mock.ExpectationsWereMet(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_database_ReadKey(t *testing.T) {
|
||||
type fields struct {
|
||||
client db
|
||||
masterKey string
|
||||
decrypt func(encryptedKey, masterKey string) (key string, err error)
|
||||
}
|
||||
type args struct {
|
||||
id string
|
||||
}
|
||||
type res struct {
|
||||
key *crypto.Key
|
||||
err func(error) bool
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
args args
|
||||
res res
|
||||
}{
|
||||
{
|
||||
"query fails, error",
|
||||
fields{
|
||||
client: dbMock(t, expectQueryErr("SELECT key FROM system.encryption_keys WHERE id = $1", sql.ErrConnDone)),
|
||||
masterKey: "",
|
||||
decrypt: nil,
|
||||
},
|
||||
args{
|
||||
id: "id1",
|
||||
},
|
||||
res{
|
||||
err: func(err error) bool {
|
||||
return errors.Is(err, sql.ErrConnDone)
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"key not found err",
|
||||
fields{
|
||||
client: dbMock(t, expectQuery(
|
||||
"SELECT key FROM system.encryption_keys WHERE id = $1",
|
||||
nil,
|
||||
nil,
|
||||
"id1")),
|
||||
masterKey: "masterKey",
|
||||
decrypt: func(encryptedKey, masterKey string) (key string, err error) {
|
||||
return encryptedKey, nil
|
||||
},
|
||||
},
|
||||
args{
|
||||
id: "id1",
|
||||
},
|
||||
res{
|
||||
err: caos_errs.IsInternal,
|
||||
},
|
||||
},
|
||||
{
|
||||
"decryption error",
|
||||
fields{
|
||||
client: dbMock(t, expectQuery(
|
||||
"SELECT key FROM system.encryption_keys WHERE id = $1",
|
||||
[]string{"key"},
|
||||
[][]driver.Value{
|
||||
{
|
||||
"key1",
|
||||
},
|
||||
},
|
||||
"id1",
|
||||
)),
|
||||
masterKey: "wrong key",
|
||||
decrypt: func(encryptedKey, masterKey string) (key string, err error) {
|
||||
return "", fmt.Errorf("wrong masterkey")
|
||||
},
|
||||
},
|
||||
args{
|
||||
id: "id1",
|
||||
},
|
||||
res{
|
||||
err: caos_errs.IsInternal,
|
||||
},
|
||||
},
|
||||
{
|
||||
"key ok",
|
||||
fields{
|
||||
client: dbMock(t, expectQuery(
|
||||
"SELECT key FROM system.encryption_keys WHERE id = $1",
|
||||
[]string{"key"},
|
||||
[][]driver.Value{
|
||||
{
|
||||
"key1",
|
||||
},
|
||||
},
|
||||
"id1",
|
||||
)),
|
||||
masterKey: "masterKey",
|
||||
decrypt: func(encryptedKey, masterKey string) (key string, err error) {
|
||||
return encryptedKey, nil
|
||||
},
|
||||
},
|
||||
args{
|
||||
id: "id1",
|
||||
},
|
||||
res{
|
||||
key: &crypto.Key{
|
||||
ID: "id1",
|
||||
Value: "key1",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
d := &database{
|
||||
client: tt.fields.client.db,
|
||||
masterKey: tt.fields.masterKey,
|
||||
decrypt: tt.fields.decrypt,
|
||||
}
|
||||
got, err := d.ReadKey(tt.args.id)
|
||||
if tt.res.err == nil {
|
||||
assert.NoError(t, err)
|
||||
} else if tt.res.err != nil && !tt.res.err(err) {
|
||||
t.Errorf("got wrong err: %v", err)
|
||||
}
|
||||
if tt.res.err == nil {
|
||||
assert.Equal(t, tt.res.key, got)
|
||||
}
|
||||
if err := tt.fields.client.mock.ExpectationsWereMet(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_database_CreateKeys(t *testing.T) {
|
||||
type fields struct {
|
||||
client db
|
||||
masterKey string
|
||||
encrypt func(key, masterKey string) (encryptedKey string, err error)
|
||||
}
|
||||
type args struct {
|
||||
keys []*crypto.Key
|
||||
}
|
||||
type res struct {
|
||||
err func(error) bool
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
args args
|
||||
res res
|
||||
}{
|
||||
{
|
||||
"encryption fails, error",
|
||||
fields{
|
||||
client: dbMock(t),
|
||||
masterKey: "",
|
||||
encrypt: func(key, masterKey string) (encryptedKey string, err error) {
|
||||
return "", fmt.Errorf("encryption failed")
|
||||
},
|
||||
},
|
||||
args{
|
||||
keys: []*crypto.Key{
|
||||
{
|
||||
"id1",
|
||||
"key1",
|
||||
},
|
||||
},
|
||||
},
|
||||
res{
|
||||
err: caos_errs.IsInternal,
|
||||
},
|
||||
},
|
||||
{
|
||||
"insert fails, error",
|
||||
fields{
|
||||
client: dbMock(t,
|
||||
expectBegin(nil),
|
||||
expectExec("INSERT INTO system.encryption_keys (id,key) VALUES ($1,$2)", sql.ErrTxDone),
|
||||
expectRollback(nil),
|
||||
),
|
||||
masterKey: "masterkey",
|
||||
encrypt: func(key, masterKey string) (encryptedKey string, err error) {
|
||||
return key, nil
|
||||
},
|
||||
},
|
||||
args{
|
||||
keys: []*crypto.Key{
|
||||
{
|
||||
"id1",
|
||||
"key1",
|
||||
},
|
||||
},
|
||||
},
|
||||
res{
|
||||
err: func(err error) bool {
|
||||
return errors.Is(err, sql.ErrTxDone)
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"single insert ok",
|
||||
fields{
|
||||
client: dbMock(t,
|
||||
expectBegin(nil),
|
||||
expectExec("INSERT INTO system.encryption_keys (id,key) VALUES ($1,$2)", nil, "id1", "key1"),
|
||||
expectCommit(nil),
|
||||
),
|
||||
masterKey: "masterkey",
|
||||
encrypt: func(key, masterKey string) (encryptedKey string, err error) {
|
||||
return key, nil
|
||||
},
|
||||
},
|
||||
args{
|
||||
keys: []*crypto.Key{
|
||||
{
|
||||
"id1",
|
||||
"key1",
|
||||
},
|
||||
},
|
||||
},
|
||||
res{
|
||||
err: nil,
|
||||
},
|
||||
},
|
||||
{
|
||||
"multiple insert ok",
|
||||
fields{
|
||||
client: dbMock(t,
|
||||
expectBegin(nil),
|
||||
expectExec("INSERT INTO system.encryption_keys (id,key) VALUES ($1,$2)", nil, "id1", "key1", "id2", "key2"),
|
||||
expectCommit(nil),
|
||||
),
|
||||
masterKey: "masterkey",
|
||||
encrypt: func(key, masterKey string) (encryptedKey string, err error) {
|
||||
return key, nil
|
||||
},
|
||||
},
|
||||
args{
|
||||
keys: []*crypto.Key{
|
||||
{
|
||||
"id1",
|
||||
"key1",
|
||||
},
|
||||
{
|
||||
"id2",
|
||||
"key2",
|
||||
},
|
||||
},
|
||||
},
|
||||
res{
|
||||
err: nil,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
d := &database{
|
||||
client: tt.fields.client.db,
|
||||
masterKey: tt.fields.masterKey,
|
||||
encrypt: tt.fields.encrypt,
|
||||
}
|
||||
err := d.CreateKeys(tt.args.keys...)
|
||||
if tt.res.err == nil {
|
||||
assert.NoError(t, err)
|
||||
} else if tt.res.err != nil && !tt.res.err(err) {
|
||||
t.Errorf("got wrong err: %v", err)
|
||||
}
|
||||
if err := tt.fields.client.mock.ExpectationsWereMet(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_checkMasterKeyLength(t *testing.T) {
|
||||
type args struct {
|
||||
masterKey string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
err func(error) bool
|
||||
}{
|
||||
{
|
||||
"invalid length",
|
||||
args{
|
||||
masterKey: "",
|
||||
},
|
||||
caos_errs.IsInternal,
|
||||
},
|
||||
{
|
||||
"valid length",
|
||||
args{
|
||||
masterKey: "!themasterkeywhichis32byteslong!",
|
||||
},
|
||||
nil,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := checkMasterKeyLength(tt.args.masterKey)
|
||||
if tt.err == nil {
|
||||
assert.NoError(t, err)
|
||||
} else if tt.err != nil && !tt.err(err) {
|
||||
t.Errorf("got wrong err: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type db struct {
|
||||
mock sqlmock.Sqlmock
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func dbMock(t *testing.T, expectations ...func(m sqlmock.Sqlmock)) db {
|
||||
t.Helper()
|
||||
client, mock, err := sqlmock.New()
|
||||
if err != nil {
|
||||
t.Fatalf("unable to create sql mock: %v", err)
|
||||
}
|
||||
for _, expectation := range expectations {
|
||||
expectation(mock)
|
||||
}
|
||||
return db{
|
||||
mock: mock,
|
||||
db: client,
|
||||
}
|
||||
}
|
||||
|
||||
func expectQueryErr(query string, err error, args ...driver.Value) func(m sqlmock.Sqlmock) {
|
||||
return func(m sqlmock.Sqlmock) {
|
||||
m.ExpectQuery(regexp.QuoteMeta(query)).WithArgs(args...).WillReturnError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func expectQuery(stmt string, cols []string, rows [][]driver.Value, args ...driver.Value) func(m sqlmock.Sqlmock) {
|
||||
return func(m sqlmock.Sqlmock) {
|
||||
q := m.ExpectQuery(regexp.QuoteMeta(stmt)).WithArgs(args...)
|
||||
result := sqlmock.NewRows(cols)
|
||||
count := uint64(len(rows))
|
||||
for _, row := range rows {
|
||||
if cols[len(cols)-1] == "count" {
|
||||
row = append(row, count)
|
||||
}
|
||||
result.AddRow(row...)
|
||||
}
|
||||
q.WillReturnRows(result)
|
||||
q.RowsWillBeClosed()
|
||||
}
|
||||
}
|
||||
|
||||
func expectExec(stmt string, err error, args ...driver.Value) func(m sqlmock.Sqlmock) {
|
||||
return func(m sqlmock.Sqlmock) {
|
||||
query := m.ExpectExec(regexp.QuoteMeta(stmt)).WithArgs(args...)
|
||||
if err != nil {
|
||||
query.WillReturnError(err)
|
||||
return
|
||||
}
|
||||
query.WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
}
|
||||
}
|
||||
|
||||
func expectBegin(err error) func(m sqlmock.Sqlmock) {
|
||||
return func(m sqlmock.Sqlmock) {
|
||||
query := m.ExpectBegin()
|
||||
if err != nil {
|
||||
query.WillReturnError(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func expectCommit(err error) func(m sqlmock.Sqlmock) {
|
||||
return func(m sqlmock.Sqlmock) {
|
||||
query := m.ExpectCommit()
|
||||
if err != nil {
|
||||
query.WillReturnError(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func expectRollback(err error) func(m sqlmock.Sqlmock) {
|
||||
return func(m sqlmock.Sqlmock) {
|
||||
query := m.ExpectRollback()
|
||||
if err != nil {
|
||||
query.WillReturnError(err)
|
||||
}
|
||||
}
|
||||
}
|
44
internal/crypto/file/file.go
Normal file
44
internal/crypto/file/file.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/caos/zitadel/internal/config"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
)
|
||||
|
||||
const (
|
||||
ZitadelKeyPath = "ZITADEL_KEY_PATH"
|
||||
)
|
||||
|
||||
type Storage struct{}
|
||||
|
||||
func (d *Storage) ReadKeys() (crypto.Keys, error) {
|
||||
path := os.Getenv(ZitadelKeyPath)
|
||||
if path == "" {
|
||||
return nil, fmt.Errorf("no path set, %s is empty", ZitadelKeyPath)
|
||||
}
|
||||
keys := new(crypto.Keys)
|
||||
err := config.Read(keys, path)
|
||||
return *keys, err
|
||||
}
|
||||
|
||||
func (d *Storage) ReadKey(id string) (*crypto.Key, error) {
|
||||
keys, err := d.ReadKeys()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, ok := keys[id]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("key no found")
|
||||
}
|
||||
return &crypto.Key{
|
||||
ID: id,
|
||||
Value: key,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Storage) CreateKeys(keys ...*crypto.Key) error {
|
||||
return fmt.Errorf("this provider is not able to store new keys")
|
||||
}
|
@@ -1,51 +1,49 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"os"
|
||||
"crypto/rand"
|
||||
|
||||
"github.com/caos/logging"
|
||||
|
||||
"github.com/caos/zitadel/internal/config"
|
||||
"github.com/caos/zitadel/internal/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
ZitadelKeyPath = "ZITADEL_KEY_PATH"
|
||||
)
|
||||
|
||||
type KeyConfig struct {
|
||||
EncryptionKeyID string
|
||||
DecryptionKeyIDs []string
|
||||
Path string
|
||||
}
|
||||
|
||||
type Keys map[string]string
|
||||
|
||||
func ReadKeys(path string) (Keys, error) {
|
||||
if path == "" {
|
||||
path = os.Getenv(ZitadelKeyPath)
|
||||
if path == "" {
|
||||
return nil, errors.ThrowInvalidArgument(nil, "CRYPT-56lka", "no path set")
|
||||
}
|
||||
}
|
||||
keys := new(Keys)
|
||||
err := config.Read(keys, path)
|
||||
return *keys, err
|
||||
type Key struct {
|
||||
ID string
|
||||
Value string
|
||||
}
|
||||
|
||||
func LoadKey(config *KeyConfig, id string) (string, error) {
|
||||
keys, _, err := LoadKeys(config)
|
||||
func NewKey(id string) (*Key, error) {
|
||||
randBytes := make([]byte, 32)
|
||||
if _, err := rand.Read(randBytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Key{
|
||||
ID: id,
|
||||
Value: string(randBytes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadKey(id string, keyStorage KeyStorage) (string, error) {
|
||||
key, err := keyStorage.ReadKey(id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return keys[id], nil
|
||||
return key.Value, nil
|
||||
}
|
||||
|
||||
func LoadKeys(config *KeyConfig) (map[string]string, []string, error) {
|
||||
func LoadKeys(config *KeyConfig, keyStorage KeyStorage) (map[string]string, []string, error) {
|
||||
if config == nil {
|
||||
return nil, nil, errors.ThrowInvalidArgument(nil, "CRYPT-dJK8s", "config must not be nil")
|
||||
}
|
||||
readKeys, err := ReadKeys(config.Path)
|
||||
readKeys, err := keyStorage.ReadKeys()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -54,7 +52,7 @@ func LoadKeys(config *KeyConfig) (map[string]string, []string, error) {
|
||||
if config.EncryptionKeyID != "" {
|
||||
key, ok := readKeys[config.EncryptionKeyID]
|
||||
if !ok {
|
||||
return nil, nil, errors.ThrowInternalf(nil, "CRYPT-v2Kas", "encryption key not found")
|
||||
return nil, nil, errors.ThrowInternalf(nil, "CRYPT-v2Kas", "encryption key %s not found", config.EncryptionKeyID)
|
||||
}
|
||||
keys[config.EncryptionKeyID] = key
|
||||
ids = append(ids, config.EncryptionKeyID)
|
||||
@@ -62,7 +60,7 @@ func LoadKeys(config *KeyConfig) (map[string]string, []string, error) {
|
||||
for _, id := range config.DecryptionKeyIDs {
|
||||
key, ok := readKeys[id]
|
||||
if !ok {
|
||||
logging.Log("CRYPT-s23rf").Warnf("description key %s not found", id)
|
||||
logging.Errorf("description key %s not found", id)
|
||||
continue
|
||||
}
|
||||
keys[id] = key
|
||||
|
7
internal/crypto/key_storage.go
Normal file
7
internal/crypto/key_storage.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package crypto
|
||||
|
||||
type KeyStorage interface {
|
||||
ReadKeys() (Keys, error)
|
||||
ReadKey(id string) (*Key, error)
|
||||
CreateKeys(...*Key) error
|
||||
}
|
@@ -4,9 +4,10 @@ import (
|
||||
"database/sql"
|
||||
|
||||
"github.com/caos/logging"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/rakyll/statik/fs"
|
||||
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
|
||||
"github.com/caos/zitadel/internal/command"
|
||||
sd "github.com/caos/zitadel/internal/config/systemdefaults"
|
||||
"github.com/caos/zitadel/internal/notification/repository/eventsourcing"
|
||||
@@ -18,10 +19,19 @@ type Config struct {
|
||||
Repository eventsourcing.Config
|
||||
}
|
||||
|
||||
func Start(config Config, systemDefaults sd.SystemDefaults, command *command.Commands, queries *query.Queries, dbClient *sql.DB, assetsPrefix string, smtpPasswordEncAlg crypto.EncryptionAlgorithm, smsCrypto *crypto.AESCrypto) {
|
||||
func Start(config Config,
|
||||
systemDefaults sd.SystemDefaults,
|
||||
command *command.Commands,
|
||||
queries *query.Queries,
|
||||
dbClient *sql.DB,
|
||||
assetsPrefix string,
|
||||
userEncryption crypto.EncryptionAlgorithm,
|
||||
smtpEncryption crypto.EncryptionAlgorithm,
|
||||
smsEncryption crypto.EncryptionAlgorithm,
|
||||
) {
|
||||
statikFS, err := fs.NewWithNamespace("notification")
|
||||
logging.OnError(err).Panic("unable to start listener")
|
||||
|
||||
_, err = eventsourcing.Start(config.Repository, statikFS, systemDefaults, command, queries, dbClient, assetsPrefix, smtpPasswordEncAlg, smsCrypto)
|
||||
_, err = eventsourcing.Start(config.Repository, statikFS, systemDefaults, command, queries, dbClient, assetsPrefix, userEncryption, smtpEncryption, smsEncryption)
|
||||
logging.OnError(err).Panic("unable to start app")
|
||||
}
|
||||
|
@@ -4,8 +4,6 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/caos/logging"
|
||||
|
||||
"github.com/caos/zitadel/internal/command"
|
||||
sd "github.com/caos/zitadel/internal/config/systemdefaults"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
@@ -34,10 +32,20 @@ func (h *handler) Eventstore() v1.Eventstore {
|
||||
return h.es
|
||||
}
|
||||
|
||||
func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es v1.Eventstore, command *command.Commands, queries *query.Queries, systemDefaults sd.SystemDefaults, dir http.FileSystem, assetsPrefix string, smtpPasswordEncAlg crypto.EncryptionAlgorithm, smsCrypto *crypto.AESCrypto) []queryv1.Handler {
|
||||
aesCrypto, err := crypto.NewAESCrypto(systemDefaults.UserVerificationKey)
|
||||
logging.OnError(err).Fatal("error create new aes crypto")
|
||||
|
||||
func Register(configs Configs,
|
||||
bulkLimit,
|
||||
errorCount uint64,
|
||||
view *view.View,
|
||||
es v1.Eventstore,
|
||||
command *command.Commands,
|
||||
queries *query.Queries,
|
||||
systemDefaults sd.SystemDefaults,
|
||||
dir http.FileSystem,
|
||||
assetsPrefix string,
|
||||
userEncryption crypto.EncryptionAlgorithm,
|
||||
smtpEncryption crypto.EncryptionAlgorithm,
|
||||
smsEncryption crypto.EncryptionAlgorithm,
|
||||
) []queryv1.Handler {
|
||||
return []queryv1.Handler{
|
||||
newNotifyUser(
|
||||
handler{view, bulkLimit, configs.cycleDuration("User"), errorCount, es},
|
||||
@@ -48,11 +56,11 @@ func Register(configs Configs, bulkLimit, errorCount uint64, view *view.View, es
|
||||
command,
|
||||
queries,
|
||||
systemDefaults,
|
||||
aesCrypto,
|
||||
dir,
|
||||
assetsPrefix,
|
||||
smtpPasswordEncAlg,
|
||||
smsCrypto,
|
||||
userEncryption,
|
||||
smtpEncryption,
|
||||
smsEncryption,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/caos/logging"
|
||||
|
||||
"github.com/caos/zitadel/internal/notification/channels/fs"
|
||||
"github.com/caos/zitadel/internal/notification/channels/log"
|
||||
"github.com/caos/zitadel/internal/notification/channels/twilio"
|
||||
@@ -40,26 +41,36 @@ type Notification struct {
|
||||
handler
|
||||
command *command.Commands
|
||||
systemDefaults sd.SystemDefaults
|
||||
AesCrypto crypto.EncryptionAlgorithm
|
||||
statikDir http.FileSystem
|
||||
subscription *v1.Subscription
|
||||
assetsPrefix string
|
||||
queries *query.Queries
|
||||
userDataCrypto crypto.EncryptionAlgorithm
|
||||
smtpPasswordCrypto crypto.EncryptionAlgorithm
|
||||
smsTokenCrypto crypto.EncryptionAlgorithm
|
||||
}
|
||||
|
||||
func newNotification(handler handler, command *command.Commands, query *query.Queries, defaults sd.SystemDefaults, aesCrypto crypto.EncryptionAlgorithm, statikDir http.FileSystem, assetsPrefix string, smtpPasswordEncAlg crypto.EncryptionAlgorithm, smsCrypto *crypto.AESCrypto) *Notification {
|
||||
func newNotification(
|
||||
handler handler,
|
||||
command *command.Commands,
|
||||
query *query.Queries,
|
||||
defaults sd.SystemDefaults,
|
||||
statikDir http.FileSystem,
|
||||
assetsPrefix string,
|
||||
userEncryption crypto.EncryptionAlgorithm,
|
||||
smtpEncryption crypto.EncryptionAlgorithm,
|
||||
smsEncryption crypto.EncryptionAlgorithm,
|
||||
) *Notification {
|
||||
h := &Notification{
|
||||
handler: handler,
|
||||
command: command,
|
||||
systemDefaults: defaults,
|
||||
statikDir: statikDir,
|
||||
AesCrypto: aesCrypto,
|
||||
assetsPrefix: assetsPrefix,
|
||||
queries: query,
|
||||
smtpPasswordCrypto: smtpPasswordEncAlg,
|
||||
smsTokenCrypto: smsCrypto,
|
||||
userDataCrypto: userEncryption,
|
||||
smtpPasswordCrypto: smtpEncryption,
|
||||
smsTokenCrypto: smsEncryption,
|
||||
}
|
||||
|
||||
h.subscribe()
|
||||
@@ -161,7 +172,7 @@ func (n *Notification) handleInitUserCode(event *models.Event) (err error) {
|
||||
return err
|
||||
}
|
||||
|
||||
err = types.SendUserInitCode(ctx, string(template.Template), translator, user, initCode, n.systemDefaults, n.getSMTPConfig, n.getFileSystemProvider, n.getLogProvider, n.AesCrypto, colors, n.assetsPrefix)
|
||||
err = types.SendUserInitCode(ctx, string(template.Template), translator, user, initCode, n.systemDefaults, n.getSMTPConfig, n.getFileSystemProvider, n.getLogProvider, n.userDataCrypto, colors, n.assetsPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -199,7 +210,7 @@ func (n *Notification) handlePasswordCode(event *models.Event) (err error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = types.SendPasswordCode(ctx, string(template.Template), translator, user, pwCode, n.systemDefaults, n.getSMTPConfig, n.getTwilioConfig, n.getFileSystemProvider, n.getLogProvider, n.AesCrypto, colors, n.assetsPrefix)
|
||||
err = types.SendPasswordCode(ctx, string(template.Template), translator, user, pwCode, n.systemDefaults, n.getSMTPConfig, n.getTwilioConfig, n.getFileSystemProvider, n.getLogProvider, n.userDataCrypto, colors, n.assetsPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -238,7 +249,7 @@ func (n *Notification) handleEmailVerificationCode(event *models.Event) (err err
|
||||
return err
|
||||
}
|
||||
|
||||
err = types.SendEmailVerificationCode(ctx, string(template.Template), translator, user, emailCode, n.systemDefaults, n.getSMTPConfig, n.getFileSystemProvider, n.getLogProvider, n.AesCrypto, colors, n.assetsPrefix)
|
||||
err = types.SendEmailVerificationCode(ctx, string(template.Template), translator, user, emailCode, n.systemDefaults, n.getSMTPConfig, n.getFileSystemProvider, n.getLogProvider, n.userDataCrypto, colors, n.assetsPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -264,7 +275,7 @@ func (n *Notification) handlePhoneVerificationCode(event *models.Event) (err err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = types.SendPhoneVerificationCode(context.Background(), translator, user, phoneCode, n.systemDefaults, n.getTwilioConfig, n.getFileSystemProvider, n.getLogProvider, n.AesCrypto)
|
||||
err = types.SendPhoneVerificationCode(context.Background(), translator, user, phoneCode, n.systemDefaults, n.getTwilioConfig, n.getFileSystemProvider, n.getLogProvider, n.userDataCrypto)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -351,7 +362,7 @@ func (n *Notification) handlePasswordlessRegistrationLink(event *models.Event) (
|
||||
return err
|
||||
}
|
||||
|
||||
err = types.SendPasswordlessRegistrationLink(ctx, string(template.Template), translator, user, addedEvent, n.systemDefaults, n.getSMTPConfig, n.getFileSystemProvider, n.getLogProvider, n.AesCrypto, colors, n.assetsPrefix)
|
||||
err = types.SendPasswordlessRegistrationLink(ctx, string(template.Template), translator, user, addedEvent, n.systemDefaults, n.getSMTPConfig, n.getFileSystemProvider, n.getLogProvider, n.userDataCrypto, colors, n.assetsPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@@ -22,7 +22,17 @@ type EsRepository struct {
|
||||
spooler *es_spol.Spooler
|
||||
}
|
||||
|
||||
func Start(conf Config, dir http.FileSystem, systemDefaults sd.SystemDefaults, command *command.Commands, queries *query.Queries, dbClient *sql.DB, assetsPrefix string, smtpPasswordEncAlg crypto.EncryptionAlgorithm, smsCrypto *crypto.AESCrypto) (*EsRepository, error) {
|
||||
func Start(conf Config,
|
||||
dir http.FileSystem,
|
||||
systemDefaults sd.SystemDefaults,
|
||||
command *command.Commands,
|
||||
queries *query.Queries,
|
||||
dbClient *sql.DB,
|
||||
assetsPrefix string,
|
||||
userEncryption crypto.EncryptionAlgorithm,
|
||||
smtpEncryption crypto.EncryptionAlgorithm,
|
||||
smsEncryption crypto.EncryptionAlgorithm,
|
||||
) (*EsRepository, error) {
|
||||
es, err := v1.Start(dbClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -33,7 +43,7 @@ func Start(conf Config, dir http.FileSystem, systemDefaults sd.SystemDefaults, c
|
||||
return nil, err
|
||||
}
|
||||
|
||||
spool := spooler.StartSpooler(conf.Spooler, es, view, dbClient, command, queries, systemDefaults, dir, assetsPrefix, smtpPasswordEncAlg, smsCrypto)
|
||||
spool := spooler.StartSpooler(conf.Spooler, es, view, dbClient, command, queries, systemDefaults, dir, assetsPrefix, userEncryption, smtpEncryption, smsEncryption)
|
||||
|
||||
return &EsRepository{
|
||||
spool,
|
||||
|
@@ -21,12 +21,24 @@ type SpoolerConfig struct {
|
||||
Handlers handler.Configs
|
||||
}
|
||||
|
||||
func StartSpooler(c SpoolerConfig, es v1.Eventstore, view *view.View, sql *sql.DB, command *command.Commands, queries *query.Queries, systemDefaults sd.SystemDefaults, dir http.FileSystem, assetsPrefix string, smtpPasswordEncAlg crypto.EncryptionAlgorithm, smsCrypto *crypto.AESCrypto) *spooler.Spooler {
|
||||
func StartSpooler(c SpoolerConfig,
|
||||
es v1.Eventstore,
|
||||
view *view.View,
|
||||
sql *sql.DB,
|
||||
command *command.Commands,
|
||||
queries *query.Queries,
|
||||
systemDefaults sd.SystemDefaults,
|
||||
dir http.FileSystem,
|
||||
assetsPrefix string,
|
||||
userEncryption crypto.EncryptionAlgorithm,
|
||||
smtpEncryption crypto.EncryptionAlgorithm,
|
||||
smsEncryption crypto.EncryptionAlgorithm,
|
||||
) *spooler.Spooler {
|
||||
spoolerConfig := spooler.Config{
|
||||
Eventstore: es,
|
||||
Locker: &locker{dbClient: sql},
|
||||
ConcurrentWorkers: c.ConcurrentWorkers,
|
||||
ViewHandlers: handler.Register(c.Handlers, c.BulkLimit, c.FailureCountUntilSkip, view, es, command, queries, systemDefaults, dir, assetsPrefix, smtpPasswordEncAlg, smsCrypto),
|
||||
ViewHandlers: handler.Register(c.Handlers, c.BulkLimit, c.FailureCountUntilSkip, view, es, command, queries, systemDefaults, dir, assetsPrefix, userEncryption, smtpEncryption, smsEncryption),
|
||||
}
|
||||
spool := spoolerConfig.New()
|
||||
spool.Start()
|
||||
|
@@ -26,17 +26,15 @@ const (
|
||||
KeyPublicTable = KeyProjectionTable + "_" + publicKeyTableSuffix
|
||||
)
|
||||
|
||||
func NewKeyProjection(ctx context.Context, config crdb.StatementHandlerConfig, keyConfig *crypto.KeyConfig, keyChan chan<- interface{}) (_ *KeyProjection, err error) {
|
||||
func NewKeyProjection(ctx context.Context, config crdb.StatementHandlerConfig, keyEncryptionAlgorithm crypto.EncryptionAlgorithm, keyChan chan<- interface{}) *KeyProjection {
|
||||
p := new(KeyProjection)
|
||||
config.ProjectionName = KeyProjectionTable
|
||||
config.Reducers = p.reducers()
|
||||
p.StatementHandler = crdb.NewStatementHandler(ctx, config)
|
||||
p.keyChan = keyChan
|
||||
p.encryptionAlgorithm, err = crypto.NewAESCrypto(keyConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
p.encryptionAlgorithm = keyEncryptionAlgorithm
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *KeyProjection) reducers() []handler.AggregateReducer {
|
||||
|
@@ -17,7 +17,7 @@ const (
|
||||
FailedEventsTable = "projections.failed_events"
|
||||
)
|
||||
|
||||
func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, config Config, keyConfig *crypto.KeyConfig, keyChan chan<- interface{}) error {
|
||||
func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, config Config, keyEncryptionAlgorithm crypto.EncryptionAlgorithm, keyChan chan<- interface{}) error {
|
||||
projectionConfig := crdb.StatementHandlerConfig{
|
||||
ProjectionHandlerConfig: handler.ProjectionHandlerConfig{
|
||||
HandlerConfig: handler.HandlerConfig{
|
||||
@@ -73,10 +73,9 @@ func Start(ctx context.Context, sqlClient *sql.DB, es *eventstore.Eventstore, co
|
||||
NewSMTPConfigProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["smtp_configs"]))
|
||||
NewSMSConfigProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["sms_config"]))
|
||||
NewOIDCSettingsProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["oidc_settings"]))
|
||||
_, err := NewKeyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["keys"]), keyConfig, keyChan)
|
||||
NewDebugNotificationProviderProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["debug_notification_provider"]))
|
||||
|
||||
return err
|
||||
NewKeyProjection(ctx, applyCustomConfig(projectionConfig, config.Customizations["keys"]), keyEncryptionAlgorithm, keyChan)
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyCustomConfig(config crdb.StatementHandlerConfig, customConfig CustomConfig) crdb.StatementHandlerConfig {
|
||||
|
@@ -11,7 +11,6 @@ import (
|
||||
"golang.org/x/text/language"
|
||||
|
||||
"github.com/caos/zitadel/internal/api/authz"
|
||||
sd "github.com/caos/zitadel/internal/config/systemdefaults"
|
||||
"github.com/caos/zitadel/internal/crypto"
|
||||
"github.com/caos/zitadel/internal/eventstore"
|
||||
"github.com/caos/zitadel/internal/query/projection"
|
||||
@@ -38,7 +37,7 @@ type Queries struct {
|
||||
zitadelRoles []authz.RoleMapping
|
||||
}
|
||||
|
||||
func StartQueries(ctx context.Context, es *eventstore.Eventstore, sqlClient *sql.DB, projections projection.Config, defaults sd.SystemDefaults, keyConfig *crypto.KeyConfig, keyChan chan<- interface{}, zitadelRoles []authz.RoleMapping) (repo *Queries, err error) {
|
||||
func StartQueries(ctx context.Context, es *eventstore.Eventstore, sqlClient *sql.DB, projections projection.Config, keyEncryptionAlgorithm crypto.EncryptionAlgorithm, keyChan chan<- interface{}, zitadelRoles []authz.RoleMapping) (repo *Queries, err error) {
|
||||
statikLoginFS, err := fs.NewWithNamespace("login")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to start login statik dir")
|
||||
@@ -67,7 +66,7 @@ func StartQueries(ctx context.Context, es *eventstore.Eventstore, sqlClient *sql
|
||||
keypair.RegisterEventMappers(repo.eventstore)
|
||||
usergrant.RegisterEventMappers(repo.eventstore)
|
||||
|
||||
err = projection.Start(ctx, sqlClient, es, projections, keyConfig, keyChan)
|
||||
err = projection.Start(ctx, sqlClient, es, projections, keyEncryptionAlgorithm, keyChan)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
Reference in New Issue
Block a user