refactor: rename package errors to zerrors (#7039)

* chore: rename package errors to zerrors

* rename package errors to gerrors

* fix error related linting issues

* fix zitadel error assertion

* fix gosimple linting issues

* fix deprecated linting issues

* resolve gci linting issues

* fix import structure

---------

Co-authored-by: Elio Bischof <elio@zitadel.com>
This commit is contained in:
Tim Möhlmann 2023-12-08 16:30:55 +02:00 committed by GitHub
parent ddbea119f1
commit f680dd934d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
798 changed files with 5809 additions and 5813 deletions

View File

@ -9,11 +9,10 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"sigs.k8s.io/yaml" "sigs.k8s.io/yaml"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
cryptoDB "github.com/zitadel/zitadel/internal/crypto/database" cryptoDB "github.com/zitadel/zitadel/internal/crypto/database"
"github.com/zitadel/zitadel/internal/database" "github.com/zitadel/zitadel/internal/database"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -86,7 +85,7 @@ func keysFromArgs(args []string) ([]*crypto.Key, error) {
for i, arg := range args { for i, arg := range args {
key := strings.Split(arg, "=") key := strings.Split(arg, "=")
if len(key) != 2 { if len(key) != 2 {
return nil, caos_errs.ThrowInternal(nil, "KEY-JKd82", "argument is not in the valid format [keyID=key]") return nil, zerrors.ThrowInternal(nil, "KEY-JKd82", "argument is not in the valid format [keyID=key]")
} }
keys[i] = &crypto.Key{ keys[i] = &crypto.Key{
ID: key[0], ID: key[0],
@ -99,11 +98,11 @@ func keysFromArgs(args []string) ([]*crypto.Key, error) {
func keysFromYAML(file io.Reader) ([]*crypto.Key, error) { func keysFromYAML(file io.Reader) ([]*crypto.Key, error) {
data, err := io.ReadAll(file) data, err := io.ReadAll(file)
if err != nil { if err != nil {
return nil, caos_errs.ThrowInternal(err, "KEY-ajGFr", "unable to extract keys from file") return nil, zerrors.ThrowInternal(err, "KEY-ajGFr", "unable to extract keys from file")
} }
keysYAML := make(map[string]string) keysYAML := make(map[string]string)
if err = yaml.Unmarshal(data, &keysYAML); err != nil { if err = yaml.Unmarshal(data, &keysYAML); err != nil {
return nil, caos_errs.ThrowInternal(err, "KEY-sd34K", "unable to extract keys from file") return nil, zerrors.ThrowInternal(err, "KEY-sd34K", "unable to extract keys from file")
} }
keys := make([]*crypto.Key, 0, len(keysYAML)) keys := make([]*crypto.Key, 0, len(keysYAML))
for id, key := range keysYAML { for id, key := range keysYAML {
@ -118,7 +117,7 @@ func keysFromYAML(file io.Reader) ([]*crypto.Key, error) {
func openFile(fileName string) (io.Reader, error) { func openFile(fileName string) (io.Reader, error) {
file, err := os.Open(fileName) file, err := os.Open(fileName)
if err != nil { if err != nil {
return nil, caos_errs.ThrowInternalf(err, "KEY-asGr2", "failed to open file: %s", fileName) return nil, zerrors.ThrowInternalf(err, "KEY-asGr2", "failed to open file: %s", fileName)
} }
return file, nil return file, nil
} }

View File

@ -8,9 +8,8 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
caos_errors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/zerrors"
) )
func Test_keysFromArgs(t *testing.T) { func Test_keysFromArgs(t *testing.T) {
@ -39,7 +38,7 @@ func Test_keysFromArgs(t *testing.T) {
args: []string{"keyID", "value"}, args: []string{"keyID", "value"},
}, },
res{ res{
err: caos_errors.IsInternal, err: zerrors.IsInternal,
}, },
}, },
{ {
@ -110,7 +109,7 @@ func Test_keysFromYAML(t *testing.T) {
file: bytes.NewReader([]byte("keyID=ds")), file: bytes.NewReader([]byte("keyID=ds")),
}, },
res{ res{
err: caos_errors.IsInternal, err: zerrors.IsInternal,
}, },
}, },
{ {

View File

@ -2,7 +2,7 @@ package start
import ( import (
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
var ( var (
@ -106,7 +106,7 @@ func verifyDefaultKeys(keyStorage crypto.KeyStorage) (err error) {
return nil return nil
} }
if err := keyStorage.CreateKeys(keys...); err != nil { if err := keyStorage.CreateKeys(keys...); err != nil {
return caos_errs.ThrowInternal(err, "START-aGBq2", "cannot create default keys") return zerrors.ThrowInternal(err, "START-aGBq2", "cannot create default keys")
} }
return nil return nil
} }

View File

@ -8,8 +8,8 @@ import (
"github.com/dop251/goja_nodejs/require" "github.com/dop251/goja_nodejs/require"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
z_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type Config struct { type Config struct {
@ -32,7 +32,7 @@ func actionFailedMessage(err error) string {
func Run(ctx context.Context, ctxParam contextFields, apiParam apiFields, script, name string, opts ...Option) (err error) { func Run(ctx context.Context, ctxParam contextFields, apiParam apiFields, script, name string, opts ...Option) (err error) {
config := newRunConfig(ctx, append(opts, withLogger(ctx))...) config := newRunConfig(ctx, append(opts, withLogger(ctx))...)
if config.functionTimeout == 0 { if config.functionTimeout == 0 {
return z_errs.ThrowInternal(nil, "ACTIO-uCpCx", "Errrors.Internal") return zerrors.ThrowInternal(nil, "ACTIO-uCpCx", "Errrors.Internal")
} }
remaining := logstoreService.Limit(ctx, config.instanceID) remaining := logstoreService.Limit(ctx, config.instanceID)
@ -40,7 +40,7 @@ func Run(ctx context.Context, ctxParam contextFields, apiParam apiFields, script
config.logger.Log(actionStartedMessage) config.logger.Log(actionStartedMessage)
if remaining != nil && *remaining == 0 { if remaining != nil && *remaining == 0 {
return z_errs.ThrowResourceExhausted(nil, "ACTIO-f19Ii", "Errors.Quota.Execution.Exhausted") return zerrors.ThrowResourceExhausted(nil, "ACTIO-f19Ii", "Errors.Quota.Execution.Exhausted")
} }
defer func() { defer func() {

View File

@ -13,7 +13,7 @@ import (
"github.com/dop251/goja" "github.com/dop251/goja"
"github.com/zitadel/logging" "github.com/zitadel/logging"
z_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func WithHTTP(ctx context.Context) Option { func WithHTTP(ctx context.Context) Option {
@ -66,7 +66,7 @@ func (c *HTTP) fetchConfigFromArg(arg *goja.Object, config *fetchConfig) (err er
} }
config.Body = bytes.NewReader(body) config.Body = bytes.NewReader(body)
default: default:
return z_errs.ThrowInvalidArgument(nil, "ACTIO-OfUeA", "key is invalid") return zerrors.ThrowInvalidArgument(nil, "ACTIO-OfUeA", "key is invalid")
} }
} }
return nil return nil
@ -177,7 +177,7 @@ func (*transport) RoundTrip(req *http.Request) (*http.Response, error) {
return http.DefaultTransport.RoundTrip(req) return http.DefaultTransport.RoundTrip(req)
} }
if isHostBlocked(httpConfig.DenyList, req.URL) { if isHostBlocked(httpConfig.DenyList, req.URL) {
return nil, z_errs.ThrowInvalidArgument(nil, "ACTIO-N72d0", "host is denied") return nil, zerrors.ThrowInvalidArgument(nil, "ACTIO-N72d0", "host is denied")
} }
return http.DefaultTransport.RoundTrip(req) return http.DefaultTransport.RoundTrip(req)
} }

View File

@ -5,7 +5,7 @@ import (
"reflect" "reflect"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
z_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func SetHTTPConfig(config *HTTPConfig) { func SetHTTPConfig(config *HTTPConfig) {
@ -68,7 +68,7 @@ func NewIPChecker(i string) (AddressChecker, error) {
if ip := net.ParseIP(i); ip != nil { if ip := net.ParseIP(i); ip != nil {
return &IPChecker{IP: ip}, nil return &IPChecker{IP: ip}, nil
} }
return nil, z_errs.ThrowInvalidArgument(nil, "ACTIO-ddJ7h", "invalid ip") return nil, zerrors.ThrowInvalidArgument(nil, "ACTIO-ddJ7h", "invalid ip")
} }
type IPChecker struct { type IPChecker struct {

View File

@ -11,9 +11,9 @@ import (
"github.com/dop251/goja" "github.com/dop251/goja"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/logstore" "github.com/zitadel/zitadel/internal/logstore"
"github.com/zitadel/zitadel/internal/logstore/record" "github.com/zitadel/zitadel/internal/logstore/record"
"github.com/zitadel/zitadel/internal/zerrors"
) )
func Test_isHostBlocked(t *testing.T) { func Test_isHostBlocked(t *testing.T) {
@ -208,7 +208,7 @@ func TestHTTP_fetchConfigFromArg(t *testing.T) {
}, },
wantConfig: fetchConfig{}, wantConfig: fetchConfig{},
wantErr: func(err error) bool { wantErr: func(err error) bool {
return errors.IsErrorInvalidArgument(err) return zerrors.IsErrorInvalidArgument(err)
}, },
}, },
} }

View File

@ -19,10 +19,10 @@ import (
http_util "github.com/zitadel/zitadel/internal/api/http" http_util "github.com/zitadel/zitadel/internal/api/http"
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware" http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/api/ui/login" "github.com/zitadel/zitadel/internal/api/ui/login"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/metrics" "github.com/zitadel/zitadel/internal/telemetry/metrics"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type API struct { type API struct {
@ -196,7 +196,7 @@ func (a *API) healthHandler() http.Handler {
checks := []ValidationFunction{ checks := []ValidationFunction{
func(ctx context.Context) error { func(ctx context.Context) error {
if err := a.health.Health(ctx); err != nil { if err := a.health.Health(ctx); err != nil {
return errors.ThrowInternal(err, "API-F24h2", "DB CONNECTION ERROR") return zerrors.ThrowInternal(err, "API-F24h2", "DB CONNECTION ERROR")
} }
return nil return nil
}, },

View File

@ -4,7 +4,7 @@ import (
"context" "context"
"testing" "testing"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func Test_extractBearerToken(t *testing.T) { func Test_extractBearerToken(t *testing.T) {
@ -58,7 +58,7 @@ func Test_extractBearerToken(t *testing.T) {
t.Errorf("got wrong result, should not get err: actual: %v ", err) t.Errorf("got wrong result, should not get err: actual: %v ", err)
} }
if tt.wantErr && !errors.IsUnauthenticated(err) { if tt.wantErr && !zerrors.IsUnauthenticated(err) {
t.Errorf("got wrong err: %v ", err) t.Errorf("got wrong err: %v ", err)
} }
}) })

View File

@ -6,8 +6,8 @@ import (
"reflect" "reflect"
"strings" "strings"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -56,7 +56,7 @@ func CheckUserAuthorization(ctx context.Context, req interface{}, token, orgID,
func checkUserPermissions(req interface{}, userPerms []string, authOpt Option) error { func checkUserPermissions(req interface{}, userPerms []string, authOpt Option) error {
if len(userPerms) == 0 { if len(userPerms) == 0 {
return errors.ThrowPermissionDenied(nil, "AUTH-5mWD2", "No matching permissions found") return zerrors.ThrowPermissionDenied(nil, "AUTH-5mWD2", "No matching permissions found")
} }
if authOpt.CheckParam == "" { if authOpt.CheckParam == "" {
@ -71,7 +71,7 @@ func checkUserPermissions(req interface{}, userPerms []string, authOpt Option) e
return nil return nil
} }
return errors.ThrowPermissionDenied(nil, "AUTH-3jknH", "No matching permissions found") return zerrors.ThrowPermissionDenied(nil, "AUTH-3jknH", "No matching permissions found")
} }
func SplitPermission(perm string) (string, string) { func SplitPermission(perm string) (string, string) {

View File

@ -3,7 +3,7 @@ package authz
import ( import (
"testing" "testing"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
type TestRequest struct { type TestRequest struct {
@ -77,7 +77,7 @@ func Test_CheckUserPermissions(t *testing.T) {
t.Errorf("shouldn't get err: %v ", err) t.Errorf("shouldn't get err: %v ", err)
} }
if tt.wantErr && !errors.IsPermissionDenied(err) { if tt.wantErr && !zerrors.IsPermissionDenied(err) {
t.Errorf("got wrong err: %v ", err) t.Errorf("got wrong err: %v ", err)
} }
}) })

View File

@ -11,8 +11,8 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc" "github.com/zitadel/zitadel/internal/api/grpc"
http_util "github.com/zitadel/zitadel/internal/api/http" http_util "github.com/zitadel/zitadel/internal/api/http"
zitadel_errors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type key int type key int
@ -105,7 +105,7 @@ func VerifyTokenAndCreateCtxData(ctx context.Context, token, orgID, orgDomain st
} }
userID, clientID, agentID, prefLang, resourceOwner, err := t.VerifyAccessToken(ctx, tokenWOBearer) userID, clientID, agentID, prefLang, resourceOwner, err := t.VerifyAccessToken(ctx, tokenWOBearer)
var sysMemberships Memberships var sysMemberships Memberships
if err != nil && !zitadel_errors.IsUnauthenticated(err) { if err != nil && !zerrors.IsUnauthenticated(err) {
return CtxData{}, err return CtxData{}, err
} }
if err != nil { if err != nil {
@ -113,7 +113,7 @@ func VerifyTokenAndCreateCtxData(ctx context.Context, token, orgID, orgDomain st
var sysTokenErr error var sysTokenErr error
sysMemberships, userID, sysTokenErr = t.VerifySystemToken(ctx, tokenWOBearer, orgID) sysMemberships, userID, sysTokenErr = t.VerifySystemToken(ctx, tokenWOBearer, orgID)
if sysTokenErr != nil || sysMemberships == nil { if sysTokenErr != nil || sysMemberships == nil {
return CtxData{}, zitadel_errors.ThrowUnauthenticated(errors.Join(err, sysTokenErr), "AUTH-7fs1e", "Errors.Token.Invalid") return CtxData{}, zerrors.ThrowUnauthenticated(errors.Join(err, sysTokenErr), "AUTH-7fs1e", "Errors.Token.Invalid")
} }
} }
var projectID string var projectID string
@ -121,7 +121,7 @@ func VerifyTokenAndCreateCtxData(ctx context.Context, token, orgID, orgDomain st
if clientID != "" { if clientID != "" {
projectID, origins, err = t.ProjectIDAndOriginsByClientID(ctx, clientID) projectID, origins, err = t.ProjectIDAndOriginsByClientID(ctx, clientID)
if err != nil { if err != nil {
return CtxData{}, zitadel_errors.ThrowPermissionDenied(err, "AUTH-GHpw2", "could not read projectid by clientid") return CtxData{}, zerrors.ThrowPermissionDenied(err, "AUTH-GHpw2", "could not read projectid by clientid")
} }
// We used to check origins for every token, but service users shouldn't be used publicly (native app / SPA). // We used to check origins for every token, but service users shouldn't be used publicly (native app / SPA).
// Therefore, mostly won't send an origin and aren't able to configure them anyway. // Therefore, mostly won't send an origin and aren't able to configure them anyway.
@ -137,7 +137,7 @@ func VerifyTokenAndCreateCtxData(ctx context.Context, token, orgID, orgDomain st
if orgID != "" { if orgID != "" {
orgID, err = t.ExistsOrg(ctx, orgID, orgDomain) orgID, err = t.ExistsOrg(ctx, orgID, orgDomain)
if err != nil { if err != nil {
return CtxData{}, zitadel_errors.ThrowPermissionDenied(nil, "AUTH-Bs7Ds", "Organisation doesn't exist") return CtxData{}, zerrors.ThrowPermissionDenied(nil, "AUTH-Bs7Ds", "Organisation doesn't exist")
} }
} }
return CtxData{ return CtxData{
@ -176,13 +176,13 @@ func checkOrigin(ctx context.Context, origins []string) error {
if http_util.IsOriginAllowed(origins, origin) { if http_util.IsOriginAllowed(origins, origin) {
return nil return nil
} }
return zitadel_errors.ThrowPermissionDenied(nil, "AUTH-DZG21", "Errors.OriginNotAllowed") return zerrors.ThrowPermissionDenied(nil, "AUTH-DZG21", "Errors.OriginNotAllowed")
} }
func extractBearerToken(token string) (part string, err error) { func extractBearerToken(token string) (part string, err error) {
parts := strings.Split(token, BearerPrefix) parts := strings.Split(token, BearerPrefix)
if len(parts) != 2 { if len(parts) != 2 {
return "", zitadel_errors.ThrowUnauthenticated(nil, "AUTH-7fs1e", "invalid auth header") return "", zerrors.ThrowUnauthenticated(nil, "AUTH-7fs1e", "invalid auth header")
} }
return parts[1], nil return parts[1], nil
} }

View File

@ -3,8 +3,8 @@ package authz
import ( import (
"context" "context"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
func CheckPermission(ctx context.Context, resolver MembershipsResolver, roleMappings []RoleMapping, permission, orgID, resourceID string) (err error) { func CheckPermission(ctx context.Context, resolver MembershipsResolver, roleMappings []RoleMapping, permission, orgID, resourceID string) (err error) {
@ -27,7 +27,7 @@ func getUserPermissions(ctx context.Context, resolver MembershipsResolver, requi
defer func() { span.EndWithError(err) }() defer func() { span.EndWithError(err) }()
if ctxData.IsZero() { if ctxData.IsZero() {
return nil, nil, errors.ThrowUnauthenticated(nil, "AUTH-rKLWEH", "context missing") return nil, nil, zerrors.ThrowUnauthenticated(nil, "AUTH-rKLWEH", "context missing")
} }
if ctxData.SystemMemberships != nil { if ctxData.SystemMemberships != nil {
@ -43,7 +43,7 @@ func getUserPermissions(ctx context.Context, resolver MembershipsResolver, requi
if len(memberships) == 0 { if len(memberships) == 0 {
memberships, err = resolver.SearchMyMemberships(ctx, orgID, true) memberships, err = resolver.SearchMyMemberships(ctx, orgID, true)
if len(memberships) == 0 { if len(memberships) == 0 {
return nil, nil, errors.ThrowNotFound(nil, "AUTHZ-cdgFk", "membership not found") return nil, nil, zerrors.ThrowNotFound(nil, "AUTHZ-cdgFk", "membership not found")
} }
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -57,7 +57,7 @@ func getUserPermissions(ctx context.Context, resolver MembershipsResolver, requi
// or the specific resource (project.write:123) // or the specific resource (project.write:123)
func checkUserResourcePermissions(userPerms []string, resourceID string) error { func checkUserResourcePermissions(userPerms []string, resourceID string) error {
if len(userPerms) == 0 { if len(userPerms) == 0 {
return errors.ThrowPermissionDenied(nil, "AUTH-AWfge", "No matching permissions found") return zerrors.ThrowPermissionDenied(nil, "AUTH-AWfge", "No matching permissions found")
} }
if resourceID == "" { if resourceID == "" {
@ -72,7 +72,7 @@ func checkUserResourcePermissions(userPerms []string, resourceID string) error {
return nil return nil
} }
return errors.ThrowPermissionDenied(nil, "AUTH-Swrgg2", "No matching permissions found") return zerrors.ThrowPermissionDenied(nil, "AUTH-Swrgg2", "No matching permissions found")
} }
func hasContextResourcePermission(permissions []string, resourceID string) bool { func hasContextResourcePermission(permissions []string, resourceID string) bool {

View File

@ -4,7 +4,7 @@ import (
"context" "context"
"testing" "testing"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func equalStringArray(a, b []string) bool { func equalStringArray(a, b []string) bool {
@ -61,7 +61,7 @@ func Test_GetUserPermissions(t *testing.T) {
}, },
}, },
wantErr: true, wantErr: true,
errFunc: caos_errs.IsUnauthenticated, errFunc: zerrors.IsUnauthenticated,
result: []string{"project.read"}, result: []string{"project.read"},
}, },
{ {
@ -563,7 +563,7 @@ func Test_CheckUserResourcePermissions(t *testing.T) {
t.Errorf("shouldn't get err: %v ", err) t.Errorf("shouldn't get err: %v ", err)
} }
if tt.wantErr && !caos_errs.IsPermissionDenied(err) { if tt.wantErr && !zerrors.IsPermissionDenied(err) {
t.Errorf("got wrong err: %v ", err) t.Errorf("got wrong err: %v ", err)
} }
}) })

View File

@ -6,8 +6,8 @@ import (
"fmt" "fmt"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
zitadel_errors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -25,7 +25,7 @@ func SessionTokenVerifier(algorithm crypto.EncryptionAlgorithm) func(ctx context
token, err := algorithm.DecryptString(decodedToken, algorithm.EncryptionKeyID()) token, err := algorithm.DecryptString(decodedToken, algorithm.EncryptionKeyID())
spanPasswordComparison.EndWithError(err) spanPasswordComparison.EndWithError(err)
if err != nil || token != fmt.Sprintf(SessionTokenFormat, sessionID, tokenID) { if err != nil || token != fmt.Sprintf(SessionTokenFormat, sessionID, tokenID) {
return zitadel_errors.ThrowPermissionDenied(err, "COMMAND-sGr42", "Errors.Session.Token.Invalid") return zerrors.ThrowPermissionDenied(err, "COMMAND-sGr42", "Errors.Session.Token.Invalid")
} }
return nil return nil
} }

View File

@ -12,7 +12,7 @@ import (
"github.com/zitadel/oidc/v3/pkg/op" "github.com/zitadel/oidc/v3/pkg/op"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
zitadel_errors "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
var _ SystemTokenVerifier = (*SystemTokenVerifierFromConfig)(nil) var _ SystemTokenVerifier = (*SystemTokenVerifierFromConfig)(nil)
@ -61,7 +61,7 @@ func (s *SystemTokenVerifierFromConfig) VerifySystemToken(ctx context.Context, t
} }
systemUserMemberships, ok := s.systemUsers[jwtReq.Subject] systemUserMemberships, ok := s.systemUsers[jwtReq.Subject]
if !ok { if !ok {
return nil, "", zitadel_errors.ThrowPermissionDenied(nil, "AUTH-Bohd2", "Errors.User.UserIDWrong") return nil, "", zerrors.ThrowPermissionDenied(nil, "AUTH-Bohd2", "Errors.User.UserIDWrong")
} }
matchingMemberships = make(Memberships, 0, len(systemUserMemberships)) matchingMemberships = make(Memberships, 0, len(systemUserMemberships))
for _, membership := range systemUserMemberships { for _, membership := range systemUserMemberships {
@ -91,7 +91,7 @@ func (s *SystemAPIUser) readKey() (*rsa.PublicKey, error) {
var err error var err error
s.KeyData, err = os.ReadFile(s.Path) s.KeyData, err = os.ReadFile(s.Path)
if err != nil { if err != nil {
return nil, zitadel_errors.ThrowInternal(err, "AUTHZ-JK31F", "Errors.NotFound") return nil, zerrors.ThrowInternal(err, "AUTHZ-JK31F", "Errors.NotFound")
} }
} }
return crypto.BytesToPublicKey(s.KeyData) return crypto.BytesToPublicKey(s.KeyData)
@ -104,7 +104,7 @@ func (s *systemJWTStorage) GetKeyByIDAndClientID(_ context.Context, _, userID st
} }
key, ok := s.keys[userID] key, ok := s.keys[userID]
if !ok { if !ok {
return nil, zitadel_errors.ThrowNotFound(nil, "AUTHZ-asfd3", "Errors.User.NotFound") return nil, zerrors.ThrowNotFound(nil, "AUTHZ-asfd3", "Errors.User.NotFound")
} }
s.mutex.Lock() s.mutex.Lock()
defer s.mutex.Unlock() defer s.mutex.Unlock()

View File

@ -3,14 +3,14 @@ package authz
import ( import (
"context" "context"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
// UserIDInCTX checks if the userID // UserIDInCTX checks if the userID
// equals the authenticated user in the context. // equals the authenticated user in the context.
func UserIDInCTX(ctx context.Context, userID string) error { func UserIDInCTX(ctx context.Context, userID string) error {
if GetCtxData(ctx).UserID != userID { if GetCtxData(ctx).UserID != userID {
return errors.ThrowPermissionDenied(nil, "AUTH-Bohd2", "Errors.User.UserIDWrong") return zerrors.ThrowPermissionDenied(nil, "AUTH-Bohd2", "Errors.User.UserIDWrong")
} }
return nil return nil
} }

View File

@ -9,9 +9,9 @@ import (
authn_grpc "github.com/zitadel/zitadel/internal/api/grpc/authn" authn_grpc "github.com/zitadel/zitadel/internal/api/grpc/authn"
text_grpc "github.com/zitadel/zitadel/internal/api/grpc/text" text_grpc "github.com/zitadel/zitadel/internal/api/grpc/text"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin" admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin"
app_pb "github.com/zitadel/zitadel/pkg/grpc/app" app_pb "github.com/zitadel/zitadel/pkg/grpc/app"
idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp" idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp"
@ -325,7 +325,7 @@ func (s *Server) getIDPs(ctx context.Context, orgID string) (_ []*v1_pb.DataOIDC
for _, idp := range idps.IDPs { for _, idp := range idps.IDPs {
if idp.OIDCIDP != nil { if idp.OIDCIDP != nil {
clientSecret, err := s.query.GetOIDCIDPClientSecret(ctx, false, orgID, idp.ID, false) clientSecret, err := s.query.GetOIDCIDPClientSecret(ctx, false, orgID, idp.ID, false)
if err != nil && !caos_errors.IsNotFound(err) { if err != nil && !zerrors.IsNotFound(err) {
return nil, nil, err return nil, nil, err
} }
oidcIdps = append(oidcIdps, &v1_pb.DataOIDCIDP{ oidcIdps = append(oidcIdps, &v1_pb.DataOIDCIDP{
@ -590,7 +590,7 @@ func (s *Server) getUsers(ctx context.Context, org string, withPasswords bool, w
ctx, pwspan := tracing.NewSpan(ctx) ctx, pwspan := tracing.NewSpan(ctx)
encodedHash, err := s.query.GetHumanPassword(ctx, org, user.ID) encodedHash, err := s.query.GetHumanPassword(ctx, org, user.ID)
pwspan.EndWithError(err) pwspan.EndWithError(err)
if err != nil && !caos_errors.IsNotFound(err) { if err != nil && !zerrors.IsNotFound(err) {
return nil, nil, nil, nil, err return nil, nil, nil, nil, err
} }
if err == nil && encodedHash != "" { if err == nil && encodedHash != "" {
@ -603,7 +603,7 @@ func (s *Server) getUsers(ctx context.Context, org string, withPasswords bool, w
ctx, otpspan := tracing.NewSpan(ctx) ctx, otpspan := tracing.NewSpan(ctx)
code, err := s.query.GetHumanOTPSecret(ctx, user.ID, org) code, err := s.query.GetHumanOTPSecret(ctx, user.ID, org)
otpspan.EndWithError(err) otpspan.EndWithError(err)
if err != nil && !caos_errors.IsNotFound(err) { if err != nil && !zerrors.IsNotFound(err) {
return nil, nil, nil, nil, err return nil, nil, nil, nil, err
} }
if err == nil && code != "" { if err == nil && code != "" {

View File

@ -7,9 +7,9 @@ import (
obj_grpc "github.com/zitadel/zitadel/internal/api/grpc/object" obj_grpc "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/notification/channels/smtp" "github.com/zitadel/zitadel/internal/notification/channels/smtp"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin" admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin"
settings_pb "github.com/zitadel/zitadel/pkg/grpc/settings" settings_pb "github.com/zitadel/zitadel/pkg/grpc/settings"
) )
@ -47,7 +47,7 @@ func SecretGeneratorQueryToModel(apiQuery *settings_pb.SecretGeneratorQuery) (qu
domainType := SecretGeneratorTypeToDomain(q.TypeQuery.GeneratorType) domainType := SecretGeneratorTypeToDomain(q.TypeQuery.GeneratorType)
return query.NewSecretGeneratorTypeSearchQuery(int32(domainType)) return query.NewSecretGeneratorTypeSearchQuery(int32(domainType))
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ORG-fm9es", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ORG-fm9es", "List.Query.Invalid")
} }
} }

View File

@ -7,9 +7,9 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore/v1/models" "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin" admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin"
idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp" idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp"
) )
@ -126,7 +126,7 @@ func idpQueryToModel(idpQuery *admin_pb.IDPQuery) (query.SearchQuery, error) {
case *admin_pb.IDPQuery_IdpIdQuery: case *admin_pb.IDPQuery_IdpIdQuery:
return query.NewIDPIDSearchQuery(q.IdpIdQuery.Id) return query.NewIDPIDSearchQuery(q.IdpIdQuery.Id)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ADMIN-VmqQu", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ADMIN-VmqQu", "List.Query.Invalid")
} }
} }
@ -200,7 +200,7 @@ func providerQueryToQuery(idpQuery *admin_pb.ProviderQuery) (query.SearchQuery,
case *admin_pb.ProviderQuery_IdpIdQuery: case *admin_pb.ProviderQuery_IdpIdQuery:
return query.NewIDPTemplateIDSearchQuery(q.IdpIdQuery.Id) return query.NewIDPTemplateIDSearchQuery(q.IdpIdQuery.Id)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ADMIN-Dr2aa", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ADMIN-Dr2aa", "List.Query.Invalid")
} }
} }

View File

@ -2,9 +2,9 @@ package admin
import ( import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/repository/milestone" "github.com/zitadel/zitadel/internal/repository/milestone"
"github.com/zitadel/zitadel/internal/zerrors"
admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin" admin_pb "github.com/zitadel/zitadel/pkg/grpc/admin"
milestone_pb "github.com/zitadel/zitadel/pkg/grpc/milestone" milestone_pb "github.com/zitadel/zitadel/pkg/grpc/milestone"
"google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/timestamppb"
@ -48,7 +48,7 @@ func milestoneQueryToModel(milestoneQuery *milestone_pb.MilestoneQuery) (query.S
} }
return query.NewIsNullQuery(query.MilestoneReachedDateColID) return query.NewIsNullQuery(query.MilestoneReachedDateColID)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ADMIN-sE7pc", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ADMIN-sE7pc", "List.Query.Invalid")
} }
} }

View File

@ -1,63 +0,0 @@
package errors
import (
"context"
"github.com/zitadel/logging"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/pkg/grpc/message"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func CaosToGRPCError(ctx context.Context, err error) error {
if err == nil {
return nil
}
code, key, id, ok := ExtractCaosError(err)
if !ok {
return status.Convert(err).Err()
}
msg := key
msg += " (" + id + ")"
s, err := status.New(code, msg).WithDetails(&message.ErrorDetail{Id: id, Message: key})
if err != nil {
logging.Log("GRPC-gIeRw").WithError(err).Debug("unable to add detail")
return status.New(code, msg).Err()
}
return s.Err()
}
func ExtractCaosError(err error) (c codes.Code, msg, id string, ok bool) {
if err == nil {
return codes.OK, "", "", false
}
switch caosErr := err.(type) {
case *caos_errs.AlreadyExistsError:
return codes.AlreadyExists, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.DeadlineExceededError:
return codes.DeadlineExceeded, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.InternalError:
return codes.Internal, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.InvalidArgumentError:
return codes.InvalidArgument, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.NotFoundError:
return codes.NotFound, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.PermissionDeniedError:
return codes.PermissionDenied, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.PreconditionFailedError:
return codes.FailedPrecondition, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.UnauthenticatedError:
return codes.Unauthenticated, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.UnavailableError:
return codes.Unavailable, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.UnimplementedError:
return codes.Unimplemented, caosErr.GetMessage(), caosErr.GetID(), true
case *caos_errs.ResourceExhaustedError:
return codes.ResourceExhausted, caosErr.GetMessage(), caosErr.GetID(), true
default:
return codes.Unknown, err.Error(), "", false
}
}

View File

@ -4,8 +4,8 @@ import (
"google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
eventpb "github.com/zitadel/zitadel/pkg/grpc/event" eventpb "github.com/zitadel/zitadel/pkg/grpc/event"
"github.com/zitadel/zitadel/pkg/grpc/message" "github.com/zitadel/zitadel/pkg/grpc/message"
) )
@ -28,7 +28,7 @@ func EventToPb(event *query.Event) (response *eventpb.Event, err error) {
if len(event.Payload) > 0 { if len(event.Payload) > 0 {
payload = new(structpb.Struct) payload = new(structpb.Struct)
if err := payload.UnmarshalJSON(event.Payload); err != nil { if err := payload.UnmarshalJSON(event.Payload); err != nil {
return nil, errors.ThrowInternal(err, "ADMIN-eaimD", "Errors.Internal") return nil, zerrors.ThrowInternal(err, "ADMIN-eaimD", "Errors.Internal")
} }
} }
return &eventpb.Event{ return &eventpb.Event{

View File

@ -0,0 +1,68 @@
package gerrors
import (
"errors"
"github.com/zitadel/logging"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/zitadel/zitadel/internal/zerrors"
"github.com/zitadel/zitadel/pkg/grpc/message"
)
func ZITADELToGRPCError(err error) error {
if err == nil {
return nil
}
code, key, id, ok := ExtractZITADELError(err)
if !ok {
return status.Convert(err).Err()
}
msg := key
msg += " (" + id + ")"
s, err := status.New(code, msg).WithDetails(&message.ErrorDetail{Id: id, Message: key})
if err != nil {
logging.WithError(err).WithField("logID", "GRPC-gIeRw").Debug("unable to add detail")
return status.New(code, msg).Err()
}
return s.Err()
}
func ExtractZITADELError(err error) (c codes.Code, msg, id string, ok bool) {
if err == nil {
return codes.OK, "", "", false
}
zitadelErr := new(zerrors.ZitadelError)
if ok := errors.As(err, &zitadelErr); !ok {
return codes.Unknown, err.Error(), "", false
}
switch {
case zerrors.IsErrorAlreadyExists(err):
return codes.AlreadyExists, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsDeadlineExceeded(err):
return codes.DeadlineExceeded, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsInternal(err):
return codes.Internal, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsErrorInvalidArgument(err):
return codes.InvalidArgument, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsNotFound(err):
return codes.NotFound, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsPermissionDenied(err):
return codes.PermissionDenied, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsPreconditionFailed(err):
return codes.FailedPrecondition, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsUnauthenticated(err):
return codes.Unauthenticated, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsUnavailable(err):
return codes.Unavailable, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsUnimplemented(err):
return codes.Unimplemented, zitadelErr.GetMessage(), zitadelErr.GetID(), true
case zerrors.IsResourceExhausted(err):
return codes.ResourceExhausted, zitadelErr.GetMessage(), zitadelErr.GetID(), true
default:
return codes.Unknown, err.Error(), "", false
}
}

View File

@ -1,13 +1,12 @@
package errors package gerrors
import ( import (
"context"
"errors" "errors"
"testing" "testing"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func TestCaosToGRPCError(t *testing.T) { func TestCaosToGRPCError(t *testing.T) {
@ -31,14 +30,14 @@ func TestCaosToGRPCError(t *testing.T) {
}, },
{ {
"caos error", "caos error",
args{caos_errs.ThrowInternal(nil, "", "message")}, args{zerrors.ThrowInternal(nil, "", "message")},
true, true,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if err := CaosToGRPCError(context.Background(), tt.args.err); (err != nil) != tt.wantErr { if err := ZITADELToGRPCError(tt.args.err); (err != nil) != tt.wantErr {
t.Errorf("CaosToGRPCError() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("ZITADELToGRPCError() error = %v, wantErr %v", err, tt.wantErr)
} }
}) })
} }
@ -58,7 +57,7 @@ func Test_Extract(t *testing.T) {
}{ }{
{ {
"already exists", "already exists",
args{caos_errs.ThrowAlreadyExists(nil, "id", "already exists")}, args{zerrors.ThrowAlreadyExists(nil, "id", "already exists")},
codes.AlreadyExists, codes.AlreadyExists,
"already exists", "already exists",
"id", "id",
@ -66,7 +65,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"deadline exceeded", "deadline exceeded",
args{caos_errs.ThrowDeadlineExceeded(nil, "id", "deadline exceeded")}, args{zerrors.ThrowDeadlineExceeded(nil, "id", "deadline exceeded")},
codes.DeadlineExceeded, codes.DeadlineExceeded,
"deadline exceeded", "deadline exceeded",
"id", "id",
@ -74,7 +73,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"internal error", "internal error",
args{caos_errs.ThrowInternal(nil, "id", "internal error")}, args{zerrors.ThrowInternal(nil, "id", "internal error")},
codes.Internal, codes.Internal,
"internal error", "internal error",
"id", "id",
@ -82,7 +81,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"invalid argument", "invalid argument",
args{caos_errs.ThrowInvalidArgument(nil, "id", "invalid argument")}, args{zerrors.ThrowInvalidArgument(nil, "id", "invalid argument")},
codes.InvalidArgument, codes.InvalidArgument,
"invalid argument", "invalid argument",
"id", "id",
@ -90,7 +89,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"not found", "not found",
args{caos_errs.ThrowNotFound(nil, "id", "not found")}, args{zerrors.ThrowNotFound(nil, "id", "not found")},
codes.NotFound, codes.NotFound,
"not found", "not found",
"id", "id",
@ -98,7 +97,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"permission denied", "permission denied",
args{caos_errs.ThrowPermissionDenied(nil, "id", "permission denied")}, args{zerrors.ThrowPermissionDenied(nil, "id", "permission denied")},
codes.PermissionDenied, codes.PermissionDenied,
"permission denied", "permission denied",
"id", "id",
@ -106,7 +105,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"precondition failed", "precondition failed",
args{caos_errs.ThrowPreconditionFailed(nil, "id", "precondition failed")}, args{zerrors.ThrowPreconditionFailed(nil, "id", "precondition failed")},
codes.FailedPrecondition, codes.FailedPrecondition,
"precondition failed", "precondition failed",
"id", "id",
@ -114,7 +113,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"unauthenticated", "unauthenticated",
args{caos_errs.ThrowUnauthenticated(nil, "id", "unauthenticated")}, args{zerrors.ThrowUnauthenticated(nil, "id", "unauthenticated")},
codes.Unauthenticated, codes.Unauthenticated,
"unauthenticated", "unauthenticated",
"id", "id",
@ -122,7 +121,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"unavailable", "unavailable",
args{caos_errs.ThrowUnavailable(nil, "id", "unavailable")}, args{zerrors.ThrowUnavailable(nil, "id", "unavailable")},
codes.Unavailable, codes.Unavailable,
"unavailable", "unavailable",
"id", "id",
@ -130,7 +129,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"unimplemented", "unimplemented",
args{caos_errs.ThrowUnimplemented(nil, "id", "unimplemented")}, args{zerrors.ThrowUnimplemented(nil, "id", "unimplemented")},
codes.Unimplemented, codes.Unimplemented,
"unimplemented", "unimplemented",
"id", "id",
@ -138,7 +137,7 @@ func Test_Extract(t *testing.T) {
}, },
{ {
"exhausted", "exhausted",
args{caos_errs.ThrowResourceExhausted(nil, "id", "exhausted")}, args{zerrors.ThrowResourceExhausted(nil, "id", "exhausted")},
codes.ResourceExhausted, codes.ResourceExhausted,
"exhausted", "exhausted",
"id", "id",
@ -155,7 +154,7 @@ func Test_Extract(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
gotC, gotMsg, gotID, gotOk := ExtractCaosError(tt.args.err) gotC, gotMsg, gotID, gotOk := ExtractZITADELError(tt.args.err)
if gotC != tt.wantC { if gotC != tt.wantC {
t.Errorf("extract() gotC = %v, want %v", gotC, tt.wantC) t.Errorf("extract() gotC = %v, want %v", gotC, tt.wantC)
} }

View File

@ -3,8 +3,8 @@ package org
import ( import (
"github.com/zitadel/zitadel/cmd/build" "github.com/zitadel/zitadel/cmd/build"
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
instance_pb "github.com/zitadel/zitadel/pkg/grpc/instance" instance_pb "github.com/zitadel/zitadel/pkg/grpc/instance"
) )
@ -66,7 +66,7 @@ func InstanceQueryToModel(searchQuery *instance_pb.Query) (query.SearchQuery, er
case *instance_pb.Query_DomainQuery: case *instance_pb.Query_DomainQuery:
return query.NewInstanceDomainsListSearchQuery(q.DomainQuery.Domains...) return query.NewInstanceDomainsListSearchQuery(q.DomainQuery.Domains...)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "INST-3m0se", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "INST-3m0se", "List.Query.Invalid")
} }
} }
@ -90,7 +90,7 @@ func DomainQueryToModel(searchQuery *instance_pb.DomainSearchQuery) (query.Searc
case *instance_pb.DomainSearchQuery_PrimaryQuery: case *instance_pb.DomainSearchQuery_PrimaryQuery:
return query.NewInstanceDomainPrimarySearchQuery(q.PrimaryQuery.Primary) return query.NewInstanceDomainPrimarySearchQuery(q.PrimaryQuery.Primary)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "INST-Ags42", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "INST-Ags42", "List.Query.Invalid")
} }
} }

View File

@ -4,9 +4,9 @@ import (
action_grpc "github.com/zitadel/zitadel/internal/api/grpc/action" action_grpc "github.com/zitadel/zitadel/internal/api/grpc/action"
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore/v1/models" "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management" mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management"
) )
@ -63,5 +63,5 @@ func ActionQueryToQuery(query interface{}) (query.SearchQuery, error) {
case *mgmt_pb.ActionQuery_ActionIdQuery: case *mgmt_pb.ActionQuery_ActionIdQuery:
return action_grpc.ActionIDQuery(q.ActionIdQuery) return action_grpc.ActionIDQuery(q.ActionIdQuery)
} }
return nil, errors.ThrowInvalidArgument(nil, "MGMT-dsg3z", "Errors.Query.InvalidRequest") return nil, zerrors.ThrowInvalidArgument(nil, "MGMT-dsg3z", "Errors.Query.InvalidRequest")
} }

View File

@ -4,7 +4,7 @@ import (
"context" "context"
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
caos_errors "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func checkExplicitProjectPermission(ctx context.Context, grantID, projectID string) error { func checkExplicitProjectPermission(ctx context.Context, grantID, projectID string) error {
@ -19,7 +19,7 @@ func checkExplicitProjectPermission(ctx context.Context, grantID, projectID stri
if listContainsID(ids, projectID) { if listContainsID(ids, projectID) {
return nil return nil
} }
return caos_errors.ThrowPermissionDenied(nil, "EVENT-Shu7e", "Errors.UserGrant.NoPermissionForProject") return zerrors.ThrowPermissionDenied(nil, "EVENT-Shu7e", "Errors.UserGrant.NoPermissionForProject")
} }
func listContainsID(ids []string, id string) bool { func listContainsID(ids []string, id string) bool {

View File

@ -7,7 +7,7 @@ import (
action_grpc "github.com/zitadel/zitadel/internal/api/grpc/action" action_grpc "github.com/zitadel/zitadel/internal/api/grpc/action"
obj_grpc "github.com/zitadel/zitadel/internal/api/grpc/object" obj_grpc "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
action_pb "github.com/zitadel/zitadel/pkg/grpc/action" action_pb "github.com/zitadel/zitadel/pkg/grpc/action"
mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management" mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management"
) )
@ -26,7 +26,7 @@ func (s *Server) ListFlowTypes(ctx context.Context, _ *mgmt_pb.ListFlowTypesRequ
func (s *Server) ListFlowTriggerTypes(ctx context.Context, req *mgmt_pb.ListFlowTriggerTypesRequest) (*mgmt_pb.ListFlowTriggerTypesResponse, error) { func (s *Server) ListFlowTriggerTypes(ctx context.Context, req *mgmt_pb.ListFlowTriggerTypesRequest) (*mgmt_pb.ListFlowTriggerTypesResponse, error) {
triggerTypes := action_grpc.FlowTypeToDomain(req.Type).TriggerTypes() triggerTypes := action_grpc.FlowTypeToDomain(req.Type).TriggerTypes()
if len(triggerTypes) == 0 { if len(triggerTypes) == 0 {
return nil, errors.ThrowNotFound(nil, "MANAG-P2OBk", "Errors.NotFound") return nil, zerrors.ThrowNotFound(nil, "MANAG-P2OBk", "Errors.NotFound")
} }
return &mgmt_pb.ListFlowTriggerTypesResponse{ return &mgmt_pb.ListFlowTriggerTypesResponse{
Result: action_grpc.TriggerTypesToPb(triggerTypes), Result: action_grpc.TriggerTypesToPb(triggerTypes),

View File

@ -10,10 +10,10 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore/v1/models" "github.com/zitadel/zitadel/internal/eventstore/v1/models"
iam_model "github.com/zitadel/zitadel/internal/iam/model" iam_model "github.com/zitadel/zitadel/internal/iam/model"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp" idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp"
mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management" mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management"
) )
@ -132,7 +132,7 @@ func idpQueryToModel(idpQuery *mgmt_pb.IDPQuery) (query.SearchQuery, error) {
case *mgmt_pb.IDPQuery_OwnerTypeQuery: case *mgmt_pb.IDPQuery_OwnerTypeQuery:
return query.NewIDPOwnerTypeSearchQuery(idp_grpc.IDPProviderTypeFromPb(q.OwnerTypeQuery.OwnerType)) return query.NewIDPOwnerTypeSearchQuery(idp_grpc.IDPProviderTypeFromPb(q.OwnerTypeQuery.OwnerType))
default: default:
return nil, errors.ThrowInvalidArgument(nil, "MANAG-WtLPV", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "MANAG-WtLPV", "List.Query.Invalid")
} }
} }
@ -217,7 +217,7 @@ func providerQueryToQuery(idpQuery *mgmt_pb.ProviderQuery) (query.SearchQuery, e
case *mgmt_pb.ProviderQuery_OwnerTypeQuery: case *mgmt_pb.ProviderQuery_OwnerTypeQuery:
return query.NewIDPTemplateOwnerTypeSearchQuery(idp_grpc.IDPProviderTypeFromPb(q.OwnerTypeQuery.OwnerType)) return query.NewIDPTemplateOwnerTypeSearchQuery(idp_grpc.IDPProviderTypeFromPb(q.OwnerTypeQuery.OwnerType))
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ORG-Dr2aa", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ORG-Dr2aa", "List.Query.Invalid")
} }
} }

View File

@ -7,9 +7,9 @@ import (
member_grpc "github.com/zitadel/zitadel/internal/api/grpc/member" member_grpc "github.com/zitadel/zitadel/internal/api/grpc/member"
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore/v1/models" "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management" mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management"
proj_pb "github.com/zitadel/zitadel/pkg/grpc/project" proj_pb "github.com/zitadel/zitadel/pkg/grpc/project"
) )
@ -55,7 +55,7 @@ func ProjectGrantQueryToModel(apiQuery *proj_pb.ProjectGrantQuery) (query.Search
case *proj_pb.ProjectGrantQuery_RoleKeyQuery: case *proj_pb.ProjectGrantQuery_RoleKeyQuery:
return query.NewProjectGrantRoleKeySearchQuery(q.RoleKeyQuery.RoleKey) return query.NewProjectGrantRoleKeySearchQuery(q.RoleKeyQuery.RoleKey)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "PROJECT-M099f", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "PROJECT-M099f", "List.Query.Invalid")
} }
} }
func listAllProjectGrantsRequestToModel(req *mgmt_pb.ListAllProjectGrantsRequest) (*query.ProjectGrantSearchQueries, error) { func listAllProjectGrantsRequestToModel(req *mgmt_pb.ListAllProjectGrantsRequest) (*query.ProjectGrantSearchQueries, error) {
@ -97,7 +97,7 @@ func AllProjectGrantQueryToModel(apiQuery *proj_pb.AllProjectGrantQuery) (query.
case *proj_pb.AllProjectGrantQuery_GrantedOrgIdQuery: case *proj_pb.AllProjectGrantQuery_GrantedOrgIdQuery:
return query.NewProjectGrantGrantedOrgIDSearchQuery(q.GrantedOrgIdQuery.GrantedOrgId) return query.NewProjectGrantGrantedOrgIDSearchQuery(q.GrantedOrgIdQuery.GrantedOrgId)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "PROJECT-M099f", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "PROJECT-M099f", "List.Query.Invalid")
} }
} }
func AddProjectGrantRequestToDomain(req *mgmt_pb.AddProjectGrantRequest) *domain.ProjectGrant { func AddProjectGrantRequestToDomain(req *mgmt_pb.AddProjectGrantRequest) *domain.ProjectGrant {

View File

@ -20,10 +20,10 @@ import (
"github.com/zitadel/zitadel/internal/api/ui/login" "github.com/zitadel/zitadel/internal/api/ui/login"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/repository/user" "github.com/zitadel/zitadel/internal/repository/user"
"github.com/zitadel/zitadel/internal/zerrors"
mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management" mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management"
) )
@ -33,7 +33,7 @@ func (s *Server) getUserByID(ctx context.Context, id string) (*query.User, error
return nil, err return nil, err
} }
if user.ResourceOwner != authz.GetCtxData(ctx).OrgID { if user.ResourceOwner != authz.GetCtxData(ctx).OrgID {
return nil, errors.ThrowNotFound(nil, "MANAG-fpo4B", "Errors.User.NotFound") return nil, zerrors.ThrowNotFound(nil, "MANAG-fpo4B", "Errors.User.NotFound")
} }
return user, nil return user, nil
} }

View File

@ -4,8 +4,8 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/api/grpc/user" "github.com/zitadel/zitadel/internal/api/grpc/user"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
member_pb "github.com/zitadel/zitadel/pkg/grpc/member" member_pb "github.com/zitadel/zitadel/pkg/grpc/member"
) )
@ -66,6 +66,6 @@ func MemberQueryToMember(search *member_pb.SearchQuery) (query.SearchQuery, erro
case *member_pb.SearchQuery_UserIdQuery: case *member_pb.SearchQuery_UserIdQuery:
return query.NewMemberUserIDSearchQuery(q.UserIdQuery.UserId) return query.NewMemberUserIDSearchQuery(q.UserIdQuery.UserId)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "MEMBE-7Bb92", "Errors.Query.InvalidRequest") return nil, zerrors.ThrowInvalidArgument(nil, "MEMBE-7Bb92", "Errors.Query.InvalidRequest")
} }
} }

View File

@ -2,8 +2,8 @@ package metadata
import ( import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
meta_pb "github.com/zitadel/zitadel/pkg/grpc/metadata" meta_pb "github.com/zitadel/zitadel/pkg/grpc/metadata"
) )
@ -65,7 +65,7 @@ func MetadataQueryToQuery(query *meta_pb.MetadataQuery) (query.SearchQuery, erro
case *meta_pb.MetadataQuery_KeyQuery: case *meta_pb.MetadataQuery_KeyQuery:
return MetadataKeyQueryToQuery(q.KeyQuery) return MetadataKeyQueryToQuery(q.KeyQuery)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "METAD-fdg23", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "METAD-fdg23", "List.Query.Invalid")
} }
} }

View File

@ -13,8 +13,8 @@ import (
"github.com/zitadel/zitadel/internal/api/http" "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/oidc" "github.com/zitadel/zitadel/internal/api/oidc"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
oidc_pb "github.com/zitadel/zitadel/pkg/grpc/oidc/v2beta" oidc_pb "github.com/zitadel/zitadel/pkg/grpc/oidc/v2beta"
) )
@ -81,7 +81,7 @@ func (s *Server) CreateCallback(ctx context.Context, req *oidc_pb.CreateCallback
case *oidc_pb.CreateCallbackRequest_Session: case *oidc_pb.CreateCallbackRequest_Session:
return s.linkSessionToAuthRequest(ctx, req.GetAuthRequestId(), v.Session) return s.linkSessionToAuthRequest(ctx, req.GetAuthRequestId(), v.Session)
default: default:
return nil, errors.ThrowUnimplementedf(nil, "OIDCv2-zee7A", "verification oneOf %T in method CreateCallback not implemented", v) return nil, zerrors.ThrowUnimplementedf(nil, "OIDCv2-zee7A", "verification oneOf %T in method CreateCallback not implemented", v)
} }
} }

View File

@ -3,8 +3,8 @@ package org
import ( import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
org_pb "github.com/zitadel/zitadel/pkg/grpc/org" org_pb "github.com/zitadel/zitadel/pkg/grpc/org"
) )
@ -28,7 +28,7 @@ func OrgQueryToModel(apiQuery *org_pb.OrgQuery) (query.SearchQuery, error) {
case *org_pb.OrgQuery_StateQuery: case *org_pb.OrgQuery_StateQuery:
return query.NewOrgStateSearchQuery(OrgStateToDomain(q.StateQuery.State)) return query.NewOrgStateSearchQuery(OrgStateToDomain(q.StateQuery.State))
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ORG-vR9nC", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ORG-vR9nC", "List.Query.Invalid")
} }
} }
@ -52,7 +52,7 @@ func OrgQueryToQuery(search *org_pb.OrgQuery) (query.SearchQuery, error) {
case *org_pb.OrgQuery_StateQuery: case *org_pb.OrgQuery_StateQuery:
return query.NewOrgStateSearchQuery(OrgStateToDomain(q.StateQuery.State)) return query.NewOrgStateSearchQuery(OrgStateToDomain(q.StateQuery.State))
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ADMIN-ADvsd", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ADMIN-ADvsd", "List.Query.Invalid")
} }
} }
@ -137,7 +137,7 @@ func DomainQueryToModel(searchQuery *org_pb.DomainSearchQuery) (query.SearchQuer
case *org_pb.DomainSearchQuery_DomainNameQuery: case *org_pb.DomainSearchQuery_DomainNameQuery:
return query.NewOrgDomainDomainSearchQuery(object.TextMethodToQuery(q.DomainNameQuery.Method), q.DomainNameQuery.Name) return query.NewOrgDomainDomainSearchQuery(object.TextMethodToQuery(q.DomainNameQuery.Method), q.DomainNameQuery.Name)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ORG-Ags42", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ORG-Ags42", "List.Query.Invalid")
} }
} }

View File

@ -6,7 +6,7 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc/object/v2" "github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/api/grpc/user/v2" "github.com/zitadel/zitadel/internal/api/grpc/user/v2"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
org "github.com/zitadel/zitadel/pkg/grpc/org/v2beta" org "github.com/zitadel/zitadel/pkg/grpc/org/v2beta"
) )
@ -62,7 +62,7 @@ func addOrganizationRequestAdminToCommand(admin *org.AddOrganizationRequest_Admi
Roles: admin.GetRoles(), Roles: admin.GetRoles(),
}, nil }, nil
default: default:
return nil, caos_errs.ThrowUnimplementedf(nil, "ORGv2-SD2r1", "userType oneOf %T in method AddOrganization not implemented", a) return nil, zerrors.ThrowUnimplementedf(nil, "ORGv2-SD2r1", "userType oneOf %T in method AddOrganization not implemented", a)
} }
} }

View File

@ -11,7 +11,7 @@ import (
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
org "github.com/zitadel/zitadel/pkg/grpc/org/v2beta" org "github.com/zitadel/zitadel/pkg/grpc/org/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
@ -37,7 +37,7 @@ func Test_addOrganizationRequestToCommand(t *testing.T) {
}, },
}, },
}, },
wantErr: caos_errs.ThrowUnimplementedf(nil, "ORGv2-SD2r1", "userType oneOf %T in method AddOrganization not implemented", nil), wantErr: zerrors.ThrowUnimplementedf(nil, "ORGv2-SD2r1", "userType oneOf %T in method AddOrganization not implemented", nil),
}, },
{ {
name: "user ID", name: "user ID",

View File

@ -5,8 +5,8 @@ import (
object_grpc "github.com/zitadel/zitadel/internal/api/grpc/object" object_grpc "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
app_pb "github.com/zitadel/zitadel/pkg/grpc/app" app_pb "github.com/zitadel/zitadel/pkg/grpc/app"
message_pb "github.com/zitadel/zitadel/pkg/grpc/message" message_pb "github.com/zitadel/zitadel/pkg/grpc/message"
) )
@ -303,6 +303,6 @@ func AppQueryToModel(appQuery *app_pb.AppQuery) (query.SearchQuery, error) {
case *app_pb.AppQuery_NameQuery: case *app_pb.AppQuery_NameQuery:
return query.NewAppNameSearchQuery(object_grpc.TextMethodToQuery(q.NameQuery.Method), q.NameQuery.Name) return query.NewAppNameSearchQuery(object_grpc.TextMethodToQuery(q.NameQuery.Method), q.NameQuery.Name)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "APP-Add46", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "APP-Add46", "List.Query.Invalid")
} }
} }

View File

@ -3,9 +3,9 @@ package project
import ( import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
proj_model "github.com/zitadel/zitadel/internal/project/model" proj_model "github.com/zitadel/zitadel/internal/project/model"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
proj_pb "github.com/zitadel/zitadel/pkg/grpc/project" proj_pb "github.com/zitadel/zitadel/pkg/grpc/project"
) )
@ -75,7 +75,7 @@ func ProjectQueryToModel(apiQuery *proj_pb.ProjectQuery) (query.SearchQuery, err
case *proj_pb.ProjectQuery_ProjectResourceOwnerQuery: case *proj_pb.ProjectQuery_ProjectResourceOwnerQuery:
return query.NewProjectResourceOwnerSearchQuery(q.ProjectResourceOwnerQuery.ResourceOwner) return query.NewProjectResourceOwnerSearchQuery(q.ProjectResourceOwnerQuery.ResourceOwner)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ORG-vR9nC", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ORG-vR9nC", "List.Query.Invalid")
} }
} }
@ -139,7 +139,7 @@ func GrantedProjectQueryToModel(query *proj_pb.ProjectQuery) (*proj_model.Projec
case *proj_pb.ProjectQuery_NameQuery: case *proj_pb.ProjectQuery_NameQuery:
return GrantedProjectQueryNameToModel(q.NameQuery), nil return GrantedProjectQueryNameToModel(q.NameQuery), nil
default: default:
return nil, errors.ThrowInvalidArgument(nil, "ORG-Ags42", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "ORG-Ags42", "List.Query.Invalid")
} }
} }
@ -169,7 +169,7 @@ func RoleQueryToModel(apiQuery *proj_pb.RoleQuery) (query.SearchQuery, error) {
case *proj_pb.RoleQuery_DisplayNameQuery: case *proj_pb.RoleQuery_DisplayNameQuery:
return query.NewProjectRoleDisplayNameSearchQuery(object.TextMethodToQuery(q.DisplayNameQuery.Method), q.DisplayNameQuery.DisplayName) return query.NewProjectRoleDisplayNameSearchQuery(object.TextMethodToQuery(q.DisplayNameQuery.Method), q.DisplayNameQuery.DisplayName)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "PROJECT-fms0e", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "PROJECT-fms0e", "List.Query.Invalid")
} }
} }

View File

@ -9,7 +9,7 @@ import (
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"github.com/zitadel/zitadel/internal/activity" "github.com/zitadel/zitadel/internal/activity"
"github.com/zitadel/zitadel/internal/api/grpc/errors" "github.com/zitadel/zitadel/internal/api/grpc/gerrors"
ainfo "github.com/zitadel/zitadel/internal/api/info" ainfo "github.com/zitadel/zitadel/internal/api/info"
) )
@ -18,7 +18,7 @@ func ActivityInterceptor() grpc.UnaryServerInterceptor {
ctx = activityInfoFromGateway(ctx).SetMethod(info.FullMethod).IntoContext(ctx) ctx = activityInfoFromGateway(ctx).SetMethod(info.FullMethod).IntoContext(ctx)
resp, err := handler(ctx, req) resp, err := handler(ctx, req)
if isResourceAPI(info.FullMethod) { if isResourceAPI(info.FullMethod) {
code, _, _, _ := errors.ExtractCaosError(err) code, _, _, _ := gerrors.ExtractZITADELError(err)
ctx = ainfo.ActivityInfoFromContext(ctx).SetGRPCStatus(code).IntoContext(ctx) ctx = ainfo.ActivityInfoFromContext(ctx).SetGRPCStatus(code).IntoContext(ctx)
activity.TriggerGRPCWithContext(ctx, activity.ResourceAPI) activity.TriggerGRPCWithContext(ctx, activity.ResourceAPI)
} }

View File

@ -10,7 +10,7 @@ import (
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
zitadel_errors "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const anAPIRole = "AN_API_ROLE" const anAPIRole = "AN_API_ROLE"
@ -43,7 +43,7 @@ var (
return "user1", "", "", "", "org1", nil return "user1", "", "", "", "org1", nil
}) })
accessTokenNOK = authz.AccessTokenVerifierFunc(func(ctx context.Context, token string) (userID string, clientID string, agentID string, prefLan string, resourceOwner string, err error) { accessTokenNOK = authz.AccessTokenVerifierFunc(func(ctx context.Context, token string) (userID string, clientID string, agentID string, prefLan string, resourceOwner string, err error) {
return "", "", "", "", "", zitadel_errors.ThrowUnauthenticated(nil, "TEST-fQHDI", "unauthenticaded") return "", "", "", "", "", zerrors.ThrowUnauthenticated(nil, "TEST-fQHDI", "unauthenticaded")
}) })
systemTokenNOK = authz.SystemTokenVerifierFunc(func(ctx context.Context, token string, orgID string) (memberships authz.Memberships, userID string, err error) { systemTokenNOK = authz.SystemTokenVerifierFunc(func(ctx context.Context, token string, orgID string) (memberships authz.Memberships, userID string, err error) {
return nil, "", errors.New("system token error") return nil, "", errors.New("system token error")

View File

@ -3,10 +3,9 @@ package middleware
import ( import (
"context" "context"
"github.com/zitadel/zitadel/internal/api/grpc/errors"
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/zitadel/zitadel/internal/api/grpc/gerrors"
_ "github.com/zitadel/zitadel/internal/statik" _ "github.com/zitadel/zitadel/internal/statik"
) )
@ -18,5 +17,5 @@ func ErrorHandler() grpc.UnaryServerInterceptor {
func toGRPCError(ctx context.Context, req interface{}, handler grpc.UnaryHandler) (interface{}, error) { func toGRPCError(ctx context.Context, req interface{}, handler grpc.UnaryHandler) (interface{}, error) {
resp, err := handler(ctx, req) resp, err := handler(ctx, req)
return resp, errors.CaosToGRPCError(ctx, err) return resp, gerrors.ZITADELToGRPCError(err)
} }

View File

@ -2,7 +2,7 @@ package middleware
import ( import (
"context" "context"
errs "errors" "errors"
"fmt" "fmt"
"strings" "strings"
@ -14,9 +14,9 @@ import (
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/i18n" "github.com/zitadel/zitadel/internal/i18n"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -46,8 +46,8 @@ func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInf
ctx = authz.WithInstanceID(ctx, withInstanceIDProperty.GetInstanceId()) ctx = authz.WithInstanceID(ctx, withInstanceIDProperty.GetInstanceId())
instance, err := verifier.InstanceByID(ctx) instance, err := verifier.InstanceByID(ctx)
if err != nil { if err != nil {
notFoundErr := new(errors.NotFoundError) notFoundErr := new(zerrors.NotFoundError)
if errs.As(err, &notFoundErr) { if errors.As(err, &notFoundErr) {
notFoundErr.Message = translator.LocalizeFromCtx(ctx, notFoundErr.GetMessage(), nil) notFoundErr.Message = translator.LocalizeFromCtx(ctx, notFoundErr.GetMessage(), nil)
} }
return nil, status.Error(codes.NotFound, err.Error()) return nil, status.Error(codes.NotFound, err.Error())
@ -62,8 +62,8 @@ func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInf
} }
instance, err := verifier.InstanceByHost(interceptorCtx, host) instance, err := verifier.InstanceByHost(interceptorCtx, host)
if err != nil { if err != nil {
notFoundErr := new(errors.NotFoundError) notFoundErr := new(zerrors.NotFoundError)
if errs.As(err, &notFoundErr) { if errors.As(err, &notFoundErr) {
notFoundErr.Message = translator.LocalizeFromCtx(ctx, notFoundErr.GetMessage(), nil) notFoundErr.Message = translator.LocalizeFromCtx(ctx, notFoundErr.GetMessage(), nil)
} }
return nil, status.Error(codes.NotFound, err.Error()) return nil, status.Error(codes.NotFound, err.Error())

View File

@ -5,7 +5,7 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func emptyMockHandler(_ context.Context, req interface{}) (interface{}, error) { func emptyMockHandler(_ context.Context, req interface{}) (interface{}, error) {
@ -13,7 +13,7 @@ func emptyMockHandler(_ context.Context, req interface{}) (interface{}, error) {
} }
func errorMockHandler(_ context.Context, req interface{}) (interface{}, error) { func errorMockHandler(_ context.Context, req interface{}) (interface{}, error) {
return nil, errors.ThrowInternal(nil, "test", "error") return nil, zerrors.ThrowInternal(nil, "test", "error")
} }
type mockReq struct{} type mockReq struct{}

View File

@ -7,10 +7,10 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/logstore" "github.com/zitadel/zitadel/internal/logstore"
"github.com/zitadel/zitadel/internal/logstore/record" "github.com/zitadel/zitadel/internal/logstore/record"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
func QuotaExhaustedInterceptor(svc *logstore.Service[*record.AccessLog], ignoreService ...string) grpc.UnaryServerInterceptor { func QuotaExhaustedInterceptor(svc *logstore.Service[*record.AccessLog], ignoreService ...string) grpc.UnaryServerInterceptor {
@ -43,7 +43,7 @@ func QuotaExhaustedInterceptor(svc *logstore.Service[*record.AccessLog], ignoreS
instance := authz.GetInstance(ctx) instance := authz.GetInstance(ctx)
remaining := svc.Limit(interceptorCtx, instance.InstanceID()) remaining := svc.Limit(interceptorCtx, instance.InstanceID())
if remaining != nil && *remaining == 0 { if remaining != nil && *remaining == 0 {
return nil, errors.ThrowResourceExhausted(nil, "QUOTA-vjAy8", "Quota.Access.Exhausted") return nil, zerrors.ThrowResourceExhausted(nil, "QUOTA-vjAy8", "Quota.Access.Exhausted")
} }
span.End() span.End()
return handler(ctx, req) return handler(ctx, req)

View File

@ -4,8 +4,8 @@ import (
"context" "context"
"errors" "errors"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/i18n" "github.com/zitadel/zitadel/internal/i18n"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type localizers interface { type localizers interface {
@ -29,7 +29,7 @@ func translateError(ctx context.Context, err error, translator *i18n.Translator)
if translator == nil || err == nil { if translator == nil || err == nil {
return err return err
} }
caosErr := new(caos_errs.CaosError) caosErr := new(zerrors.ZitadelError)
if errors.As(err, &caosErr) { if errors.As(err, &caosErr) {
caosErr.SetMessage(translator.LocalizeFromCtx(ctx, caosErr.GetMessage(), nil)) caosErr.SetMessage(translator.LocalizeFromCtx(ctx, caosErr.GetMessage(), nil))
} }

View File

@ -7,8 +7,8 @@ import (
"google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/emptypb"
"google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/structpb"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type ValidationFunction func(ctx context.Context) error type ValidationFunction func(ctx context.Context) error
@ -29,7 +29,7 @@ func (v *Validator) Ready(ctx context.Context, e *emptypb.Empty) (*emptypb.Empty
if len(validate(ctx, v.validations)) == 0 { if len(validate(ctx, v.validations)) == 0 {
return e, nil return e, nil
} }
return nil, errors.ThrowInternal(nil, "API-2jD9a", "not ready") return nil, zerrors.ThrowInternal(nil, "API-2jD9a", "not ready")
} }
func (v *Validator) Validate(ctx context.Context, _ *emptypb.Empty) (*structpb.Struct, error) { func (v *Validator) Validate(ctx context.Context, _ *emptypb.Empty) (*structpb.Struct, error) {

View File

@ -7,7 +7,7 @@ import (
"google.golang.org/protobuf/types/known/emptypb" "google.golang.org/protobuf/types/known/emptypb"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func TestValidator_Healthz(t *testing.T) { func TestValidator_Healthz(t *testing.T) {
@ -66,7 +66,7 @@ func TestValidator_Ready(t *testing.T) {
"unready error", "unready error",
fields{validations: map[string]ValidationFunction{ fields{validations: map[string]ValidationFunction{
"error": func(_ context.Context) error { "error": func(_ context.Context) error {
return errors.ThrowInternal(nil, "id", "message") return zerrors.ThrowInternal(nil, "id", "message")
}, },
}}, }},
res{ res{
@ -137,13 +137,13 @@ func Test_validate(t *testing.T) {
return nil return nil
}, },
"error": func(_ context.Context) error { "error": func(_ context.Context) error {
return errors.ThrowInternal(nil, "id", "message") return zerrors.ThrowInternal(nil, "id", "message")
}, },
}, },
}, },
res{ res{
map[string]any{ map[string]any{
"error": errors.ThrowInternal(nil, "id", "message"), "error": zerrors.ThrowInternal(nil, "id", "message"),
}, },
}, },
}, },

View File

@ -15,8 +15,8 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc/object/v2" "github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
objpb "github.com/zitadel/zitadel/pkg/grpc/object" objpb "github.com/zitadel/zitadel/pkg/grpc/object"
session "github.com/zitadel/zitadel/pkg/grpc/session/v2beta" session "github.com/zitadel/zitadel/pkg/grpc/session/v2beta"
) )
@ -284,7 +284,7 @@ func sessionQueryToQuery(sq *session.SearchQuery) (query.SearchQuery, error) {
case *session.SearchQuery_CreationDateQuery: case *session.SearchQuery_CreationDateQuery:
return creationDateQueryToQuery(q.CreationDateQuery) return creationDateQueryToQuery(q.CreationDateQuery)
default: default:
return nil, caos_errs.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid")
} }
} }
@ -447,7 +447,7 @@ func (s *Server) createOTPEmailChallengeCommand(req *session.RequestChallenges_O
case nil: case nil:
return nil, s.command.CreateOTPEmailChallenge(), nil return nil, s.command.CreateOTPEmailChallenge(), nil
default: default:
return nil, nil, caos_errs.ThrowUnimplementedf(nil, "SESSION-k3ng0", "delivery_type oneOf %T in OTPEmailChallenge not implemented", t) return nil, nil, zerrors.ThrowUnimplementedf(nil, "SESSION-k3ng0", "delivery_type oneOf %T in OTPEmailChallenge not implemented", t)
} }
} }
@ -461,7 +461,7 @@ func userCheck(user *session.CheckUser) (userSearch, error) {
case *session.CheckUser_LoginName: case *session.CheckUser_LoginName:
return userByLoginName(s.LoginName) return userByLoginName(s.LoginName)
default: default:
return nil, caos_errs.ThrowUnimplementedf(nil, "SESSION-d3b4g0", "user search %T not implemented", s) return nil, zerrors.ThrowUnimplementedf(nil, "SESSION-d3b4g0", "user search %T not implemented", s)
} }
} }

View File

@ -14,11 +14,10 @@ import (
"google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
objpb "github.com/zitadel/zitadel/pkg/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
objpb "github.com/zitadel/zitadel/pkg/grpc/object"
object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
session "github.com/zitadel/zitadel/pkg/grpc/session/v2beta" session "github.com/zitadel/zitadel/pkg/grpc/session/v2beta"
) )
@ -439,7 +438,7 @@ func Test_listSessionsRequestToQuery(t *testing.T) {
}, },
}, },
}, },
wantErr: caos_errs.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid"), wantErr: zerrors.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid"),
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@ -479,7 +478,7 @@ func Test_sessionQueriesToQuery(t *testing.T) {
{Query: nil}, {Query: nil},
}, },
}, },
wantErr: caos_errs.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid"), wantErr: zerrors.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid"),
}, },
{ {
name: "creator and sessions", name: "creator and sessions",
@ -529,7 +528,7 @@ func Test_sessionQueryToQuery(t *testing.T) {
args: args{&session.SearchQuery{ args: args{&session.SearchQuery{
Query: nil, Query: nil,
}}, }},
wantErr: caos_errs.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid"), wantErr: zerrors.ThrowInvalidArgument(nil, "GRPC-Sfefs", "List.Query.Invalid"),
}, },
{ {
name: "ids query", name: "ids query",
@ -624,7 +623,7 @@ func Test_userCheck(t *testing.T) {
args: args{&session.CheckUser{ args: args{&session.CheckUser{
Search: nil, Search: nil,
}}, }},
wantErr: caos_errs.ThrowUnimplementedf(nil, "SESSION-d3b4g0", "user search %T not implemented", nil), wantErr: zerrors.ThrowUnimplementedf(nil, "SESSION-d3b4g0", "user search %T not implemented", nil),
}, },
} }
for _, tt := range tests { for _, tt := range tests {

View File

@ -5,7 +5,7 @@ import (
object_pb "github.com/zitadel/zitadel/internal/api/grpc/object" object_pb "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
system_pb "github.com/zitadel/zitadel/pkg/grpc/system" system_pb "github.com/zitadel/zitadel/pkg/grpc/system"
) )
@ -23,12 +23,12 @@ func (s *Server) SetInstanceFeature(ctx context.Context, req *system_pb.SetInsta
func (s *Server) setInstanceFeature(ctx context.Context, req *system_pb.SetInstanceFeatureRequest) (*domain.ObjectDetails, error) { func (s *Server) setInstanceFeature(ctx context.Context, req *system_pb.SetInstanceFeatureRequest) (*domain.ObjectDetails, error) {
feat := domain.Feature(req.FeatureId) feat := domain.Feature(req.FeatureId)
if !feat.IsAFeature() { if !feat.IsAFeature() {
return nil, errors.ThrowInvalidArgument(nil, "SYST-SGV45", "Errors.Feature.NotExisting") return nil, zerrors.ThrowInvalidArgument(nil, "SYST-SGV45", "Errors.Feature.NotExisting")
} }
switch t := req.Value.(type) { switch t := req.Value.(type) {
case *system_pb.SetInstanceFeatureRequest_Bool: case *system_pb.SetInstanceFeatureRequest_Bool:
return s.command.SetBooleanInstanceFeature(ctx, feat, t.Bool) return s.command.SetBooleanInstanceFeature(ctx, feat, t.Bool)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "SYST-dag5g", "Errors.Feature.TypeNotSupported") return nil, zerrors.ThrowInvalidArgument(nil, "SYST-dag5g", "Errors.Feature.TypeNotSupported")
} }
} }

View File

@ -2,8 +2,8 @@ package user
import ( import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
user_pb "github.com/zitadel/zitadel/pkg/grpc/user" user_pb "github.com/zitadel/zitadel/pkg/grpc/user"
) )
@ -30,7 +30,7 @@ func MembershipQueryToQuery(req *user_pb.MembershipQuery) (query.SearchQuery, er
case *user_pb.MembershipQuery_IamQuery: case *user_pb.MembershipQuery_IamQuery:
return query.NewMembershipIsIAMQuery() return query.NewMembershipIsIAMQuery()
default: default:
return nil, errors.ThrowInvalidArgument(nil, "USER-dsg3z", "Errors.List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "USER-dsg3z", "Errors.List.Query.Invalid")
} }
} }

View File

@ -2,8 +2,8 @@ package user
import ( import (
"github.com/zitadel/zitadel/internal/api/grpc/object" "github.com/zitadel/zitadel/internal/api/grpc/object"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
user_pb "github.com/zitadel/zitadel/pkg/grpc/user" user_pb "github.com/zitadel/zitadel/pkg/grpc/user"
) )
@ -21,7 +21,7 @@ func UserQueriesToQuery(queries []*user_pb.SearchQuery, level uint8) (_ []query.
func UserQueryToQuery(query *user_pb.SearchQuery, level uint8) (query.SearchQuery, error) { func UserQueryToQuery(query *user_pb.SearchQuery, level uint8) (query.SearchQuery, error) {
if level > 20 { if level > 20 {
// can't go deeper than 20 levels of nesting. // can't go deeper than 20 levels of nesting.
return nil, errors.ThrowInvalidArgument(nil, "USER-zsQ97", "Errors.User.TooManyNestingLevels") return nil, zerrors.ThrowInvalidArgument(nil, "USER-zsQ97", "Errors.User.TooManyNestingLevels")
} }
switch q := query.Query.(type) { switch q := query.Query.(type) {
case *user_pb.SearchQuery_UserNameQuery: case *user_pb.SearchQuery_UserNameQuery:
@ -53,7 +53,7 @@ func UserQueryToQuery(query *user_pb.SearchQuery, level uint8) (query.SearchQuer
case *user_pb.SearchQuery_NotQuery: case *user_pb.SearchQuery_NotQuery:
return NotQueryToQuery(q.NotQuery, level) return NotQueryToQuery(q.NotQuery, level)
default: default:
return nil, errors.ThrowInvalidArgument(nil, "GRPC-vR9nC", "List.Query.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "GRPC-vR9nC", "List.Query.Invalid")
} }
} }

View File

@ -6,7 +6,7 @@ import (
"google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -25,7 +25,7 @@ func (s *Server) SetEmail(ctx context.Context, req *user.SetEmailRequest) (resp
case nil: case nil:
email, err = s.command.ChangeUserEmail(ctx, req.GetUserId(), resourceOwner, req.GetEmail(), s.userCodeAlg) email, err = s.command.ChangeUserEmail(ctx, req.GetUserId(), resourceOwner, req.GetEmail(), s.userCodeAlg)
default: default:
err = caos_errs.ThrowUnimplementedf(nil, "USERv2-Ahng0", "verification oneOf %T in method SetEmail not implemented", v) err = zerrors.ThrowUnimplementedf(nil, "USERv2-Ahng0", "verification oneOf %T in method SetEmail not implemented", v)
} }
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -8,7 +8,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2" "github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
object_pb "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object_pb "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -47,7 +47,7 @@ func webAuthNRegistrationDetailsToPb(details *domain.WebAuthNRegistrationDetails
} }
options := new(structpb.Struct) options := new(structpb.Struct)
if err := options.UnmarshalJSON(details.PublicKeyCredentialCreationOptions); err != nil { if err := options.UnmarshalJSON(details.PublicKeyCredentialCreationOptions); err != nil {
return nil, nil, caos_errs.ThrowInternal(err, "USERv2-Dohr6", "Errors.Internal") return nil, nil, zerrors.ThrowInternal(err, "USERv2-Dohr6", "Errors.Internal")
} }
return object.DomainToDetailsPb(details.ObjectDetails), options, nil return object.DomainToDetailsPb(details.ObjectDetails), options, nil
} }
@ -68,7 +68,7 @@ func (s *Server) VerifyPasskeyRegistration(ctx context.Context, req *user.Verify
resourceOwner := authz.GetCtxData(ctx).OrgID resourceOwner := authz.GetCtxData(ctx).OrgID
pkc, err := req.GetPublicKeyCredential().MarshalJSON() pkc, err := req.GetPublicKeyCredential().MarshalJSON()
if err != nil { if err != nil {
return nil, caos_errs.ThrowInternal(err, "USERv2-Pha2o", "Errors.Internal") return nil, zerrors.ThrowInternal(err, "USERv2-Pha2o", "Errors.Internal")
} }
objectDetails, err := s.command.HumanHumanPasswordlessSetup(ctx, req.GetUserId(), resourceOwner, req.GetPasskeyName(), "", pkc) objectDetails, err := s.command.HumanHumanPasswordlessSetup(ctx, req.GetUserId(), resourceOwner, req.GetPasskeyName(), "", pkc)
if err != nil { if err != nil {
@ -96,7 +96,7 @@ func (s *Server) CreatePasskeyRegistrationLink(ctx context.Context, req *user.Cr
s.command.AddUserPasskeyCodeReturn(ctx, req.GetUserId(), resourceOwner, s.userCodeAlg), s.command.AddUserPasskeyCodeReturn(ctx, req.GetUserId(), resourceOwner, s.userCodeAlg),
) )
default: default:
return nil, caos_errs.ThrowUnimplementedf(nil, "USERv2-gaD8y", "verification oneOf %T in method CreatePasskeyRegistrationLink not implemented", medium) return nil, zerrors.ThrowUnimplementedf(nil, "USERv2-gaD8y", "verification oneOf %T in method CreatePasskeyRegistrationLink not implemented", medium)
} }
} }

View File

@ -13,7 +13,7 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc" "github.com/zitadel/zitadel/internal/api/grpc"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -81,7 +81,7 @@ func Test_passkeyRegistrationDetailsToPb(t *testing.T) {
}, },
err: nil, err: nil,
}, },
wantErr: caos_errs.ThrowInternal(nil, "USERv2-Dohr6", "Errors.Internal"), wantErr: zerrors.ThrowInternal(nil, "USERv2-Dohr6", "Errors.Internal"),
}, },
{ {
name: "ok", name: "ok",

View File

@ -6,7 +6,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2" "github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -22,7 +22,7 @@ func (s *Server) PasswordReset(ctx context.Context, req *user.PasswordResetReque
case nil: case nil:
details, code, err = s.command.RequestPasswordReset(ctx, req.GetUserId()) details, code, err = s.command.RequestPasswordReset(ctx, req.GetUserId())
default: default:
err = caos_errs.ThrowUnimplementedf(nil, "USERv2-SDeeg", "verification oneOf %T in method RequestPasswordReset not implemented", m) err = zerrors.ThrowUnimplementedf(nil, "USERv2-SDeeg", "verification oneOf %T in method RequestPasswordReset not implemented", m)
} }
if err != nil { if err != nil {
return nil, err return nil, err
@ -59,7 +59,7 @@ func (s *Server) SetPassword(ctx context.Context, req *user.SetPasswordRequest)
case nil: case nil:
details, err = s.command.SetPassword(ctx, resourceOwner, req.GetUserId(), req.GetNewPassword().GetPassword(), req.GetNewPassword().GetChangeRequired()) details, err = s.command.SetPassword(ctx, resourceOwner, req.GetUserId(), req.GetNewPassword().GetPassword(), req.GetNewPassword().GetChangeRequired())
default: default:
err = caos_errs.ThrowUnimplementedf(nil, "USERv2-SFdf2", "verification oneOf %T in method SetPasswordRequest not implemented", v) err = zerrors.ThrowUnimplementedf(nil, "USERv2-SFdf2", "verification oneOf %T in method SetPasswordRequest not implemented", v)
} }
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -6,7 +6,7 @@ import (
"google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -25,7 +25,7 @@ func (s *Server) SetPhone(ctx context.Context, req *user.SetPhoneRequest) (resp
case nil: case nil:
phone, err = s.command.ChangeUserPhone(ctx, req.GetUserId(), resourceOwner, req.GetPhone(), s.userCodeAlg) phone, err = s.command.ChangeUserPhone(ctx, req.GetUserId(), resourceOwner, req.GetPhone(), s.userCodeAlg)
default: default:
err = caos_errs.ThrowUnimplementedf(nil, "USERv2-Ahng0", "verification oneOf %T in method SetPhone not implemented", v) err = zerrors.ThrowUnimplementedf(nil, "USERv2-Ahng0", "verification oneOf %T in method SetPhone not implemented", v)
} }
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -6,7 +6,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2" "github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -32,7 +32,7 @@ func (s *Server) VerifyU2FRegistration(ctx context.Context, req *user.VerifyU2FR
resourceOwner := authz.GetCtxData(ctx).OrgID resourceOwner := authz.GetCtxData(ctx).OrgID
pkc, err := req.GetPublicKeyCredential().MarshalJSON() pkc, err := req.GetPublicKeyCredential().MarshalJSON()
if err != nil { if err != nil {
return nil, caos_errs.ThrowInternal(err, "USERv2-IeTh4", "Errors.Internal") return nil, zerrors.ThrowInternal(err, "USERv2-IeTh4", "Errors.Internal")
} }
objectDetails, err := s.command.HumanVerifyU2FSetup(ctx, req.GetUserId(), resourceOwner, req.GetTokenName(), "", pkc) objectDetails, err := s.command.HumanVerifyU2FSetup(ctx, req.GetUserId(), resourceOwner, req.GetTokenName(), "", pkc)
if err != nil { if err != nil {

View File

@ -12,7 +12,7 @@ import (
"github.com/zitadel/zitadel/internal/api/grpc" "github.com/zitadel/zitadel/internal/api/grpc"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -50,7 +50,7 @@ func Test_u2fRegistrationDetailsToPb(t *testing.T) {
}, },
err: nil, err: nil,
}, },
wantErr: caos_errs.ThrowInternal(nil, "USERv2-Dohr6", "Errors.Internal"), wantErr: zerrors.ThrowInternal(nil, "USERv2-Dohr6", "Errors.Internal"),
}, },
{ {
name: "ok", name: "ok",

View File

@ -2,7 +2,7 @@ package user
import ( import (
"context" "context"
errs "errors" "errors"
"io" "io"
"golang.org/x/text/language" "golang.org/x/text/language"
@ -14,10 +14,10 @@ import (
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/idp" "github.com/zitadel/zitadel/internal/idp"
"github.com/zitadel/zitadel/internal/idp/providers/ldap" "github.com/zitadel/zitadel/internal/idp/providers/ldap"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
object_pb "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object_pb "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -135,7 +135,7 @@ func (s *Server) StartIdentityProviderIntent(ctx context.Context, req *user.Star
case *user.StartIdentityProviderIntentRequest_Ldap: case *user.StartIdentityProviderIntentRequest_Ldap:
return s.startLDAPIntent(ctx, req.GetIdpId(), t.Ldap) return s.startLDAPIntent(ctx, req.GetIdpId(), t.Ldap)
default: default:
return nil, errors.ThrowUnimplementedf(nil, "USERv2-S2g21", "type oneOf %T in method StartIdentityProviderIntent not implemented", t) return nil, zerrors.ThrowUnimplementedf(nil, "USERv2-S2g21", "type oneOf %T in method StartIdentityProviderIntent not implemented", t)
} }
} }
@ -220,12 +220,12 @@ func (s *Server) ldapLogin(ctx context.Context, idpID, username, password string
} }
ldapProvider, ok := provider.(*ldap.Provider) ldapProvider, ok := provider.(*ldap.Provider)
if !ok { if !ok {
return nil, "", nil, errors.ThrowInvalidArgument(nil, "IDP-9a02j2n2bh", "Errors.ExternalIDP.IDPTypeNotImplemented") return nil, "", nil, zerrors.ThrowInvalidArgument(nil, "IDP-9a02j2n2bh", "Errors.ExternalIDP.IDPTypeNotImplemented")
} }
session := ldapProvider.GetSession(username, password) session := ldapProvider.GetSession(username, password)
externalUser, err := session.FetchUser(ctx) externalUser, err := session.FetchUser(ctx)
if errs.Is(err, ldap.ErrFailedLogin) || errs.Is(err, ldap.ErrNoSingleUser) { if errors.Is(err, ldap.ErrFailedLogin) || errors.Is(err, ldap.ErrNoSingleUser) {
return nil, "", nil, errors.ThrowInvalidArgument(nil, "COMMAND-nzun2i", "Errors.User.ExternalIDP.LoginFailed") return nil, "", nil, zerrors.ThrowInvalidArgument(nil, "COMMAND-nzun2i", "Errors.User.ExternalIDP.LoginFailed")
} }
if err != nil { if err != nil {
return nil, "", nil, err return nil, "", nil, err
@ -251,7 +251,7 @@ func (s *Server) RetrieveIdentityProviderIntent(ctx context.Context, req *user.R
return nil, err return nil, err
} }
if intent.State != domain.IDPIntentStateSucceeded { if intent.State != domain.IDPIntentStateSucceeded {
return nil, errors.ThrowPreconditionFailed(nil, "IDP-Hk38e", "Errors.Intent.NotSucceeded") return nil, zerrors.ThrowPreconditionFailed(nil, "IDP-Hk38e", "Errors.Intent.NotSucceeded")
} }
return idpIntentToIDPIntentPb(intent, s.idpAlg) return idpIntentToIDPIntentPb(intent, s.idpAlg)
} }

View File

@ -16,8 +16,8 @@ import (
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/zerrors"
object_pb "github.com/zitadel/zitadel/pkg/grpc/object/v2beta" object_pb "github.com/zitadel/zitadel/pkg/grpc/object/v2beta"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta" user "github.com/zitadel/zitadel/pkg/grpc/user/v2beta"
) )
@ -78,11 +78,11 @@ func Test_idpIntentToIDPIntentPb(t *testing.T) {
UserID: "userID", UserID: "userID",
State: domain.IDPIntentStateSucceeded, State: domain.IDPIntentStateSucceeded,
}, },
alg: decryption(caos_errs.ThrowInternal(nil, "id", "invalid key id")), alg: decryption(zerrors.ThrowInternal(nil, "id", "invalid key id")),
}, },
res{ res{
resp: nil, resp: nil,
err: caos_errs.ThrowInternal(nil, "id", "invalid key id"), err: zerrors.ThrowInternal(nil, "id", "invalid key id"),
}, },
}, { }, {
"successful oauth", "successful oauth",

View File

@ -6,7 +6,7 @@ import (
"github.com/gorilla/securecookie" "github.com/gorilla/securecookie"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -102,7 +102,7 @@ func (c *CookieHandler) GetEncryptedCookieValue(r *http.Request, name string, va
return err return err
} }
if c.securecookie == nil { if c.securecookie == nil {
return errors.ThrowInternal(nil, "HTTP-X6XpnL", "securecookie not configured") return zerrors.ThrowInternal(nil, "HTTP-X6XpnL", "securecookie not configured")
} }
return c.securecookie.Decode(name, cookie.Value, value) return c.securecookie.Decode(name, cookie.Value, value)
} }
@ -113,7 +113,7 @@ func (c *CookieHandler) SetCookie(w http.ResponseWriter, name, domain, value str
func (c *CookieHandler) SetEncryptedCookie(w http.ResponseWriter, name, domain string, value interface{}, sameSiteNone bool) error { func (c *CookieHandler) SetEncryptedCookie(w http.ResponseWriter, name, domain string, value interface{}, sameSiteNone bool) error {
if c.securecookie == nil { if c.securecookie == nil {
return errors.ThrowInternal(nil, "HTTP-s2HUtx", "securecookie not configured") return zerrors.ThrowInternal(nil, "HTTP-s2HUtx", "securecookie not configured")
} }
encoded, err := c.securecookie.Encode(name, value) encoded, err := c.securecookie.Encode(name, value)
if err != nil { if err != nil {

View File

@ -7,7 +7,7 @@ import (
"net" "net"
"net/http" "net/http"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
type CheckType int type CheckType int
@ -27,30 +27,30 @@ func ValidateDomain(domain, token, verifier string, checkType CheckType) error {
case CheckTypeDNS: case CheckTypeDNS:
return ValidateDomainDNS(domain, verifier) return ValidateDomainDNS(domain, verifier)
default: default:
return errors.ThrowInvalidArgument(nil, "HTTP-Iqd11", "Errors.Internal") return zerrors.ThrowInvalidArgument(nil, "HTTP-Iqd11", "Errors.Internal")
} }
} }
func ValidateDomainHTTP(domain, token, verifier string) error { func ValidateDomainHTTP(domain, token, verifier string) error {
resp, err := http.Get(tokenUrlHTTP(domain, token)) resp, err := http.Get(tokenUrlHTTP(domain, token))
if err != nil { if err != nil {
return errors.ThrowInternal(err, "HTTP-BH42h", "Errors.Internal") return zerrors.ThrowInternal(err, "HTTP-BH42h", "Errors.Internal")
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
if resp.StatusCode == 404 { if resp.StatusCode == 404 {
return errors.ThrowNotFound(err, "ORG-F4zhw", "Errors.Org.DomainVerificationHTTPNotFound") return zerrors.ThrowNotFound(err, "ORG-F4zhw", "Errors.Org.DomainVerificationHTTPNotFound")
} }
return errors.ThrowInternal(err, "HTTP-G2zsw", "Errors.Internal") return zerrors.ThrowInternal(err, "HTTP-G2zsw", "Errors.Internal")
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
return errors.ThrowInternal(err, "HTTP-HB432", "Errors.Internal") return zerrors.ThrowInternal(err, "HTTP-HB432", "Errors.Internal")
} }
if string(body) == verifier { if string(body) == verifier {
return nil return nil
} }
return errors.ThrowNotFound(err, "ORG-GH422", "Errors.Org.DomainVerificationHTTPNoMatch") return zerrors.ThrowNotFound(err, "ORG-GH422", "Errors.Org.DomainVerificationHTTPNoMatch")
} }
func ValidateDomainDNS(domain, verifier string) error { func ValidateDomainDNS(domain, verifier string) error {
@ -59,13 +59,13 @@ func ValidateDomainDNS(domain, verifier string) error {
var dnsError *net.DNSError var dnsError *net.DNSError
if errorsAs.As(err, &dnsError) { if errorsAs.As(err, &dnsError) {
if dnsError.IsNotFound { if dnsError.IsNotFound {
return errors.ThrowNotFound(err, "ORG-G241f", "Errors.Org.DomainVerificationTXTNotFound") return zerrors.ThrowNotFound(err, "ORG-G241f", "Errors.Org.DomainVerificationTXTNotFound")
} }
if dnsError.IsTimeout { if dnsError.IsTimeout {
return errors.ThrowNotFound(err, "ORG-K563l", "Errors.Org.DomainVerificationTimeout") return zerrors.ThrowNotFound(err, "ORG-K563l", "Errors.Org.DomainVerificationTimeout")
} }
} }
return errors.ThrowInternal(err, "HTTP-Hwsw2", "Errors.Internal") return zerrors.ThrowInternal(err, "HTTP-Hwsw2", "Errors.Internal")
} }
for _, record := range txtRecords { for _, record := range txtRecords {
@ -73,7 +73,7 @@ func ValidateDomainDNS(domain, verifier string) error {
return nil return nil
} }
} }
return errors.ThrowNotFound(err, "ORG-G28if", "Errors.Org.DomainVerificationTXTNoMatch") return zerrors.ThrowNotFound(err, "ORG-G28if", "Errors.Org.DomainVerificationTXTNoMatch")
} }
func TokenUrl(domain, token string, checkType CheckType) (string, error) { func TokenUrl(domain, token string, checkType CheckType) (string, error) {
@ -83,7 +83,7 @@ func TokenUrl(domain, token string, checkType CheckType) (string, error) {
case CheckTypeDNS: case CheckTypeDNS:
return tokenUrlDNS(domain), nil return tokenUrlDNS(domain), nil
default: default:
return "", errors.ThrowInvalidArgument(nil, "HTTP-Iqd11", "") return "", zerrors.ThrowInvalidArgument(nil, "HTTP-Iqd11", "")
} }
} }

View File

@ -4,7 +4,7 @@ import (
"errors" "errors"
"net/http" "net/http"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func ZitadelErrorToHTTPStatusCode(err error) (statusCode int, ok bool) { func ZitadelErrorToHTTPStatusCode(err error) (statusCode int, ok bool) {
@ -13,32 +13,32 @@ func ZitadelErrorToHTTPStatusCode(err error) (statusCode int, ok bool) {
} }
//nolint:errorlint //nolint:errorlint
switch err.(type) { switch err.(type) {
case *caos_errs.AlreadyExistsError: case *zerrors.AlreadyExistsError:
return http.StatusConflict, true return http.StatusConflict, true
case *caos_errs.DeadlineExceededError: case *zerrors.DeadlineExceededError:
return http.StatusGatewayTimeout, true return http.StatusGatewayTimeout, true
case *caos_errs.InternalError: case *zerrors.InternalError:
return http.StatusInternalServerError, true return http.StatusInternalServerError, true
case *caos_errs.InvalidArgumentError: case *zerrors.InvalidArgumentError:
return http.StatusBadRequest, true return http.StatusBadRequest, true
case *caos_errs.NotFoundError: case *zerrors.NotFoundError:
return http.StatusNotFound, true return http.StatusNotFound, true
case *caos_errs.PermissionDeniedError: case *zerrors.PermissionDeniedError:
return http.StatusForbidden, true return http.StatusForbidden, true
case *caos_errs.PreconditionFailedError: case *zerrors.PreconditionFailedError:
// use the same code as grpc-gateway: // use the same code as grpc-gateway:
// https://github.com/grpc-ecosystem/grpc-gateway/blob/9e33e38f15cb7d2f11096366e62ea391a3459ba9/runtime/errors.go#L59 // https://github.com/grpc-ecosystem/grpc-gateway/blob/9e33e38f15cb7d2f11096366e62ea391a3459ba9/runtime/errors.go#L59
return http.StatusBadRequest, true return http.StatusBadRequest, true
case *caos_errs.UnauthenticatedError: case *zerrors.UnauthenticatedError:
return http.StatusUnauthorized, true return http.StatusUnauthorized, true
case *caos_errs.UnavailableError: case *zerrors.UnavailableError:
return http.StatusServiceUnavailable, true return http.StatusServiceUnavailable, true
case *caos_errs.UnimplementedError: case *zerrors.UnimplementedError:
return http.StatusNotImplemented, true return http.StatusNotImplemented, true
case *caos_errs.ResourceExhaustedError: case *zerrors.ResourceExhaustedError:
return http.StatusTooManyRequests, true return http.StatusTooManyRequests, true
default: default:
c := new(caos_errs.CaosError) c := new(zerrors.ZitadelError)
if errors.As(err, &c) { if errors.As(err, &c) {
return ZitadelErrorToHTTPStatusCode(errors.Unwrap(err)) return ZitadelErrorToHTTPStatusCode(errors.Unwrap(err))
} }

View File

@ -6,7 +6,7 @@ import (
"net/http" "net/http"
"testing" "testing"
caos_errors "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func TestZitadelErrorToHTTPStatusCode(t *testing.T) { func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
@ -30,7 +30,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped already exists", name: "wrapped already exists",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowAlreadyExists(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowAlreadyExists(nil, "id", "message")),
}, },
wantStatusCode: http.StatusConflict, wantStatusCode: http.StatusConflict,
wantOk: true, wantOk: true,
@ -38,7 +38,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped deadline exceeded", name: "wrapped deadline exceeded",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowDeadlineExceeded(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowDeadlineExceeded(nil, "id", "message")),
}, },
wantStatusCode: http.StatusGatewayTimeout, wantStatusCode: http.StatusGatewayTimeout,
wantOk: true, wantOk: true,
@ -46,7 +46,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped internal", name: "wrapped internal",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowInternal(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowInternal(nil, "id", "message")),
}, },
wantStatusCode: http.StatusInternalServerError, wantStatusCode: http.StatusInternalServerError,
wantOk: true, wantOk: true,
@ -54,7 +54,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped invalid argument", name: "wrapped invalid argument",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowInvalidArgument(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowInvalidArgument(nil, "id", "message")),
}, },
wantStatusCode: http.StatusBadRequest, wantStatusCode: http.StatusBadRequest,
wantOk: true, wantOk: true,
@ -62,7 +62,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped not found", name: "wrapped not found",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowNotFound(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowNotFound(nil, "id", "message")),
}, },
wantStatusCode: http.StatusNotFound, wantStatusCode: http.StatusNotFound,
wantOk: true, wantOk: true,
@ -70,7 +70,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped permission denied", name: "wrapped permission denied",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowPermissionDenied(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowPermissionDenied(nil, "id", "message")),
}, },
wantStatusCode: http.StatusForbidden, wantStatusCode: http.StatusForbidden,
wantOk: true, wantOk: true,
@ -78,7 +78,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped precondition failed", name: "wrapped precondition failed",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowPreconditionFailed(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowPreconditionFailed(nil, "id", "message")),
}, },
wantStatusCode: http.StatusBadRequest, wantStatusCode: http.StatusBadRequest,
wantOk: true, wantOk: true,
@ -86,7 +86,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped unauthenticated", name: "wrapped unauthenticated",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowUnauthenticated(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowUnauthenticated(nil, "id", "message")),
}, },
wantStatusCode: http.StatusUnauthorized, wantStatusCode: http.StatusUnauthorized,
wantOk: true, wantOk: true,
@ -94,7 +94,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped unavailable", name: "wrapped unavailable",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowUnavailable(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowUnavailable(nil, "id", "message")),
}, },
wantStatusCode: http.StatusServiceUnavailable, wantStatusCode: http.StatusServiceUnavailable,
wantOk: true, wantOk: true,
@ -102,7 +102,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped unimplemented", name: "wrapped unimplemented",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowUnimplemented(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowUnimplemented(nil, "id", "message")),
}, },
wantStatusCode: http.StatusNotImplemented, wantStatusCode: http.StatusNotImplemented,
wantOk: true, wantOk: true,
@ -110,7 +110,7 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
{ {
name: "wrapped resource exhausted", name: "wrapped resource exhausted",
args: args{ args: args{
err: fmt.Errorf("wrapped %w", caos_errors.ThrowResourceExhausted(nil, "id", "message")), err: fmt.Errorf("wrapped %w", zerrors.ThrowResourceExhausted(nil, "id", "message")),
}, },
wantStatusCode: http.StatusTooManyRequests, wantStatusCode: http.StatusTooManyRequests,
wantOk: true, wantOk: true,

View File

@ -13,9 +13,9 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
zitadel_http "github.com/zitadel/zitadel/internal/api/http" zitadel_http "github.com/zitadel/zitadel/internal/api/http"
caos_errors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/i18n" "github.com/zitadel/zitadel/internal/i18n"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type instanceInterceptor struct { type instanceInterceptor struct {
@ -55,7 +55,7 @@ func (a *instanceInterceptor) handleInstance(w http.ResponseWriter, r *http.Requ
} }
ctx, err := setInstance(r, a.verifier, a.headerName) ctx, err := setInstance(r, a.verifier, a.headerName)
if err != nil { if err != nil {
caosErr := new(caos_errors.NotFoundError) caosErr := new(zerrors.NotFoundError)
if errors.As(err, &caosErr) { if errors.As(err, &caosErr) {
caosErr.Message = a.translator.LocalizeFromRequest(r, caosErr.GetMessage(), nil) caosErr.Message = a.translator.LocalizeFromRequest(r, caosErr.GetMessage(), nil)
} }
@ -74,7 +74,7 @@ func setInstance(r *http.Request, verifier authz.InstanceVerifier, headerName st
host, err := HostFromRequest(r, headerName) host, err := HostFromRequest(r, headerName)
if err != nil { if err != nil {
return nil, caos_errors.ThrowNotFound(err, "INST-zWq7X", "Errors.Instance.NotFound") return nil, zerrors.ThrowNotFound(err, "INST-zWq7X", "Errors.Instance.NotFound")
} }
instance, err := verifier.InstanceByHost(authCtx, host) instance, err := verifier.InstanceByHost(authCtx, host)

View File

@ -10,8 +10,8 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http" http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/id" "github.com/zitadel/zitadel/internal/id"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type cookieKey int type cookieKey int
@ -95,7 +95,7 @@ func (ua *userAgentHandler) getUserAgent(r *http.Request) (*UserAgent, error) {
userAgent := new(UserAgent) userAgent := new(UserAgent)
err := ua.cookieHandler.GetEncryptedCookieValue(r, ua.cookieName, userAgent) err := ua.cookieHandler.GetEncryptedCookieValue(r, ua.cookieName, userAgent)
if err != nil { if err != nil {
return nil, errors.ThrowPermissionDenied(err, "HTTP-YULqH4", "cannot read user agent cookie") return nil, zerrors.ThrowPermissionDenied(err, "HTTP-YULqH4", "cannot read user agent cookie")
} }
return userAgent, nil return userAgent, nil
} }
@ -103,7 +103,7 @@ func (ua *userAgentHandler) getUserAgent(r *http.Request) (*UserAgent, error) {
func (ua *userAgentHandler) setUserAgent(w http.ResponseWriter, host string, agent *UserAgent, iframe bool) error { func (ua *userAgentHandler) setUserAgent(w http.ResponseWriter, host string, agent *UserAgent, iframe bool) error {
err := ua.cookieHandler.SetEncryptedCookie(w, ua.cookieName, host, agent, iframe) err := ua.cookieHandler.SetEncryptedCookie(w, ua.cookieName, host, agent, iframe)
if err != nil { if err != nil {
return errors.ThrowPermissionDenied(err, "HTTP-AqgqdA", "cannot set user agent cookie") return zerrors.ThrowPermissionDenied(err, "HTTP-AqgqdA", "cannot set user agent cookie")
} }
return nil return nil
} }

View File

@ -5,7 +5,7 @@ import (
"github.com/gorilla/schema" "github.com/gorilla/schema"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
type Parser struct { type Parser struct {
@ -21,7 +21,7 @@ func NewParser() *Parser {
func (p *Parser) Parse(r *http.Request, data interface{}) error { func (p *Parser) Parse(r *http.Request, data interface{}) error {
err := r.ParseForm() err := r.ParseForm()
if err != nil { if err != nil {
return errors.ThrowInternal(err, "FORM-lCC9zI", "error parsing http form") return zerrors.ThrowInternal(err, "FORM-lCC9zI", "error parsing http form")
} }
return p.decoder.Decode(data, r.Form) return p.decoder.Decode(data, r.Form)

View File

@ -18,7 +18,6 @@ import (
"github.com/zitadel/zitadel/internal/api/ui/login" "github.com/zitadel/zitadel/internal/api/ui/login"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
z_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/form" "github.com/zitadel/zitadel/internal/form"
"github.com/zitadel/zitadel/internal/idp" "github.com/zitadel/zitadel/internal/idp"
"github.com/zitadel/zitadel/internal/idp/providers/apple" "github.com/zitadel/zitadel/internal/idp/providers/apple"
@ -32,6 +31,7 @@ import (
openid "github.com/zitadel/zitadel/internal/idp/providers/oidc" openid "github.com/zitadel/zitadel/internal/idp/providers/oidc"
saml2 "github.com/zitadel/zitadel/internal/idp/providers/saml" saml2 "github.com/zitadel/zitadel/internal/idp/providers/saml"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -147,7 +147,7 @@ func (h *Handler) handleCertificate(w http.ResponseWriter, r *http.Request) {
} }
samlProvider, ok := provider.(*saml2.Provider) samlProvider, ok := provider.(*saml2.Provider)
if !ok { if !ok {
http.Error(w, z_errs.ThrowInvalidArgument(nil, "SAML-lrud8s9coi", "Errors.Intent.IDPInvalid").Error(), http.StatusBadRequest) http.Error(w, zerrors.ThrowInvalidArgument(nil, "SAML-lrud8s9coi", "Errors.Intent.IDPInvalid").Error(), http.StatusBadRequest)
return return
} }
@ -178,7 +178,7 @@ func (h *Handler) handleMetadata(w http.ResponseWriter, r *http.Request) {
samlProvider, ok := provider.(*saml2.Provider) samlProvider, ok := provider.(*saml2.Provider)
if !ok { if !ok {
http.Error(w, z_errs.ThrowInvalidArgument(nil, "SAML-lrud8s9coi", "Errors.Intent.IDPInvalid").Error(), http.StatusBadRequest) http.Error(w, zerrors.ThrowInvalidArgument(nil, "SAML-lrud8s9coi", "Errors.Intent.IDPInvalid").Error(), http.StatusBadRequest)
return return
} }
@ -225,7 +225,7 @@ func (h *Handler) handleACS(w http.ResponseWriter, r *http.Request) {
} }
samlProvider, ok := provider.(*saml2.Provider) samlProvider, ok := provider.(*saml2.Provider)
if !ok { if !ok {
err := z_errs.ThrowInvalidArgument(nil, "SAML-ui9wyux0hp", "Errors.Intent.IDPInvalid") err := zerrors.ThrowInvalidArgument(nil, "SAML-ui9wyux0hp", "Errors.Intent.IDPInvalid")
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
@ -237,7 +237,7 @@ func (h *Handler) handleACS(w http.ResponseWriter, r *http.Request) {
intent, err := h.commands.GetActiveIntent(ctx, data.RelayState) intent, err := h.commands.GetActiveIntent(ctx, data.RelayState)
if err != nil { if err != nil {
if z_errs.IsNotFound(err) { if zerrors.IsNotFound(err) {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
@ -264,7 +264,7 @@ func (h *Handler) handleACS(w http.ResponseWriter, r *http.Request) {
token, err := h.commands.SucceedSAMLIDPIntent(ctx, intent, idpUser, userID, session.Assertion) token, err := h.commands.SucceedSAMLIDPIntent(ctx, intent, idpUser, userID, session.Assertion)
if err != nil { if err != nil {
redirectToFailureURLErr(w, r, intent, z_errs.ThrowInternal(err, "IDP-JdD3g", "Errors.Intent.TokenCreationFailed")) redirectToFailureURLErr(w, r, intent, zerrors.ThrowInternal(err, "IDP-JdD3g", "Errors.Intent.TokenCreationFailed"))
return return
} }
redirectToSuccessURL(w, r, intent, token, userID) redirectToSuccessURL(w, r, intent, token, userID)
@ -279,7 +279,7 @@ func (h *Handler) handleCallback(w http.ResponseWriter, r *http.Request) {
} }
intent, err := h.commands.GetActiveIntent(ctx, data.State) intent, err := h.commands.GetActiveIntent(ctx, data.State)
if err != nil { if err != nil {
if z_errs.IsNotFound(err) { if zerrors.IsNotFound(err) {
http.Error(w, err.Error(), http.StatusBadRequest) http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
@ -320,7 +320,7 @@ func (h *Handler) handleCallback(w http.ResponseWriter, r *http.Request) {
token, err := h.commands.SucceedIDPIntent(ctx, intent, idpUser, idpSession, userID) token, err := h.commands.SucceedIDPIntent(ctx, intent, idpUser, idpSession, userID)
if err != nil { if err != nil {
redirectToFailureURLErr(w, r, intent, z_errs.ThrowInternal(err, "IDP-JdD3g", "Errors.Intent.TokenCreationFailed")) redirectToFailureURLErr(w, r, intent, zerrors.ThrowInternal(err, "IDP-JdD3g", "Errors.Intent.TokenCreationFailed"))
return return
} }
redirectToSuccessURL(w, r, intent, token, userID) redirectToSuccessURL(w, r, intent, token, userID)
@ -349,7 +349,7 @@ func (h *Handler) parseCallbackRequest(r *http.Request) (*externalIDPCallbackDat
return nil, err return nil, err
} }
if data.State == "" { if data.State == "" {
return nil, z_errs.ThrowInvalidArgument(nil, "IDP-Hk38e", "Errors.Intent.StateMissing") return nil, zerrors.ThrowInvalidArgument(nil, "IDP-Hk38e", "Errors.Intent.StateMissing")
} }
return data, nil return data, nil
} }
@ -368,7 +368,7 @@ func redirectToSuccessURL(w http.ResponseWriter, r *http.Request, intent *comman
func redirectToFailureURLErr(w http.ResponseWriter, r *http.Request, i *command.IDPIntentWriteModel, err error) { func redirectToFailureURLErr(w http.ResponseWriter, r *http.Request, i *command.IDPIntentWriteModel, err error) {
msg := err.Error() msg := err.Error()
var description string var description string
zErr := new(z_errs.CaosError) zErr := new(zerrors.ZitadelError)
if errors.As(err, &zErr) { if errors.As(err, &zErr) {
msg = zErr.GetID() msg = zErr.GetID()
description = zErr.GetMessage() // TODO: i18n? description = zErr.GetMessage() // TODO: i18n?
@ -403,9 +403,9 @@ func (h *Handler) fetchIDPUserFromCode(ctx context.Context, identityProvider idp
case *apple.Provider: case *apple.Provider:
session = &apple.Session{Session: &openid.Session{Provider: provider.Provider, Code: code}, UserFormValue: appleUser} session = &apple.Session{Session: &openid.Session{Provider: provider.Provider, Code: code}, UserFormValue: appleUser}
case *jwt.Provider, *ldap.Provider, *saml2.Provider: case *jwt.Provider, *ldap.Provider, *saml2.Provider:
return nil, nil, z_errs.ThrowInvalidArgument(nil, "IDP-52jmn", "Errors.ExternalIDP.IDPTypeNotImplemented") return nil, nil, zerrors.ThrowInvalidArgument(nil, "IDP-52jmn", "Errors.ExternalIDP.IDPTypeNotImplemented")
default: default:
return nil, nil, z_errs.ThrowUnimplemented(nil, "IDP-SSDg", "Errors.ExternalIDP.IDPTypeNotImplemented") return nil, nil, zerrors.ThrowUnimplemented(nil, "IDP-SSDg", "Errors.ExternalIDP.IDPTypeNotImplemented")
} }
user, err = session.FetchUser(ctx) user, err = session.FetchUser(ctx)

View File

@ -8,8 +8,8 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
z_errors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/form" "github.com/zitadel/zitadel/internal/form"
"github.com/zitadel/zitadel/internal/zerrors"
) )
func Test_redirectToSuccessURL(t *testing.T) { func Test_redirectToSuccessURL(t *testing.T) {
@ -146,7 +146,7 @@ func Test_redirectToFailureURLErr(t *testing.T) {
id: "id", id: "id",
failureURL: "https://example.com/failure", failureURL: "https://example.com/failure",
successURL: "https://example.com/success", successURL: "https://example.com/success",
err: z_errors.ThrowError(nil, "test", "testdesc"), err: zerrors.ThrowError(nil, "test", "testdesc"),
}, },
res{ res{
"https://example.com/failure?error=test&error_description=testdesc&id=id", "https://example.com/failure?error=test&error_description=testdesc&id=id",

View File

@ -10,9 +10,9 @@ import (
"github.com/zitadel/oidc/v3/pkg/op" "github.com/zitadel/oidc/v3/pkg/op"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
zerrors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/user/model" "github.com/zitadel/zitadel/internal/user/model"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type accessToken struct { type accessToken struct {

View File

@ -16,10 +16,10 @@ import (
"github.com/zitadel/zitadel/internal/api/http/middleware" "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/user/model" "github.com/zitadel/zitadel/internal/user/model"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -83,11 +83,11 @@ func (o *OPStorage) createAuthRequestLoginClient(ctx context.Context, req *oidc.
func (o *OPStorage) createAuthRequest(ctx context.Context, req *oidc.AuthRequest, userID string) (_ op.AuthRequest, err error) { func (o *OPStorage) createAuthRequest(ctx context.Context, req *oidc.AuthRequest, userID string) (_ op.AuthRequest, err error) {
userAgentID, ok := middleware.UserAgentIDFromCtx(ctx) userAgentID, ok := middleware.UserAgentIDFromCtx(ctx)
if !ok { if !ok {
return nil, errors.ThrowPreconditionFailed(nil, "OIDC-sd436", "no user agent id") return nil, zerrors.ThrowPreconditionFailed(nil, "OIDC-sd436", "no user agent id")
} }
req.Scopes, err = o.assertProjectRoleScopes(ctx, req.ClientID, req.Scopes) req.Scopes, err = o.assertProjectRoleScopes(ctx, req.ClientID, req.Scopes)
if err != nil { if err != nil {
return nil, errors.ThrowPreconditionFailed(err, "OIDC-Gqrfg", "Errors.Internal") return nil, zerrors.ThrowPreconditionFailed(err, "OIDC-Gqrfg", "Errors.Internal")
} }
authRequest := CreateAuthRequestToBusiness(ctx, req, userAgentID, userID) authRequest := CreateAuthRequestToBusiness(ctx, req, userAgentID, userID)
resp, err := o.repo.CreateAuthRequest(ctx, authRequest) resp, err := o.repo.CreateAuthRequest(ctx, authRequest)
@ -124,7 +124,7 @@ func (o *OPStorage) AuthRequestByID(ctx context.Context, id string) (_ op.AuthRe
userAgentID, ok := middleware.UserAgentIDFromCtx(ctx) userAgentID, ok := middleware.UserAgentIDFromCtx(ctx)
if !ok { if !ok {
return nil, errors.ThrowPreconditionFailed(nil, "OIDC-D3g21", "no user agent id") return nil, zerrors.ThrowPreconditionFailed(nil, "OIDC-D3g21", "no user agent id")
} }
resp, err := o.repo.AuthRequestByIDCheckLoggedIn(ctx, id, userAgentID) resp, err := o.repo.AuthRequestByIDCheckLoggedIn(ctx, id, userAgentID)
if err != nil { if err != nil {
@ -174,7 +174,7 @@ func (o *OPStorage) SaveAuthCode(ctx context.Context, id, code string) (err erro
userAgentID, ok := middleware.UserAgentIDFromCtx(ctx) userAgentID, ok := middleware.UserAgentIDFromCtx(ctx)
if !ok { if !ok {
return errors.ThrowPreconditionFailed(nil, "OIDC-Dgus2", "no user agent id") return zerrors.ThrowPreconditionFailed(nil, "OIDC-Dgus2", "no user agent id")
} }
return o.repo.SaveAuthCode(ctx, id, code, userAgentID) return o.repo.SaveAuthCode(ctx, id, code, userAgentID)
} }
@ -236,7 +236,7 @@ func (o *OPStorage) CreateAccessAndRefreshTokens(ctx context.Context, req op.Tok
userAgentID, applicationID, userOrgID, authTime, authMethodsReferences := getInfoFromRequest(req) userAgentID, applicationID, userOrgID, authTime, authMethodsReferences := getInfoFromRequest(req)
scopes, err := o.assertProjectRoleScopes(ctx, applicationID, req.GetScopes()) scopes, err := o.assertProjectRoleScopes(ctx, applicationID, req.GetScopes())
if err != nil { if err != nil {
return "", "", time.Time{}, errors.ThrowPreconditionFailed(err, "OIDC-Df2fq", "Errors.Internal") return "", "", time.Time{}, zerrors.ThrowPreconditionFailed(err, "OIDC-Df2fq", "Errors.Internal")
} }
if request, ok := req.(op.RefreshTokenRequest); ok { if request, ok := req.(op.RefreshTokenRequest); ok {
request.SetCurrentScopes(scopes) request.SetCurrentScopes(scopes)
@ -251,7 +251,7 @@ func (o *OPStorage) CreateAccessAndRefreshTokens(ctx context.Context, req op.Tok
refreshToken, req.GetAudience(), scopes, authMethodsReferences, accessTokenLifetime, refreshToken, req.GetAudience(), scopes, authMethodsReferences, accessTokenLifetime,
refreshTokenIdleExpiration, refreshTokenExpiration, authTime) //PLANNED: lifetime from client refreshTokenIdleExpiration, refreshTokenExpiration, authTime) //PLANNED: lifetime from client
if err != nil { if err != nil {
if errors.IsErrorInvalidArgument(err) { if zerrors.IsErrorInvalidArgument(err) {
err = oidc.ErrInvalidGrant().WithParent(err) err = oidc.ErrInvalidGrant().WithParent(err)
} }
return "", "", time.Time{}, err return "", "", time.Time{}, err
@ -308,7 +308,7 @@ func (o *OPStorage) TerminateSession(ctx context.Context, userID, clientID strin
userAgentID, ok := middleware.UserAgentIDFromCtx(ctx) userAgentID, ok := middleware.UserAgentIDFromCtx(ctx)
if !ok { if !ok {
logging.Error("no user agent id") logging.Error("no user agent id")
return errors.ThrowPreconditionFailed(nil, "OIDC-fso7F", "no user agent id") return zerrors.ThrowPreconditionFailed(nil, "OIDC-fso7F", "no user agent id")
} }
userIDs, err := o.repo.UserSessionUserIDsByAgentID(ctx, userAgentID) userIDs, err := o.repo.UserSessionUserIDsByAgentID(ctx, userAgentID)
if err != nil { if err != nil {
@ -366,7 +366,7 @@ func (o *OPStorage) RevokeToken(ctx context.Context, token, userID, clientID str
if err == nil { if err == nil {
return nil return nil
} }
if errors.IsPreconditionFailed(err) { if zerrors.IsPreconditionFailed(err) {
return oidc.ErrInvalidClient().WithDescription("token was not issued for this client") return oidc.ErrInvalidClient().WithDescription("token was not issued for this client")
} }
return oidc.ErrServerError().WithParent(err) return oidc.ErrServerError().WithParent(err)
@ -382,14 +382,14 @@ func (o *OPStorage) revokeTokenV1(ctx context.Context, token, userID, clientID s
return oidc.ErrInvalidClient().WithDescription("token was not issued for this client") return oidc.ErrInvalidClient().WithDescription("token was not issued for this client")
} }
_, err = o.command.RevokeRefreshToken(ctx, refreshToken.UserID, refreshToken.ResourceOwner, refreshToken.ID) _, err = o.command.RevokeRefreshToken(ctx, refreshToken.UserID, refreshToken.ResourceOwner, refreshToken.ID)
if err == nil || errors.IsNotFound(err) { if err == nil || zerrors.IsNotFound(err) {
return nil return nil
} }
return oidc.ErrServerError().WithParent(err) return oidc.ErrServerError().WithParent(err)
} }
accessToken, err := o.repo.TokenByIDs(ctx, userID, token) accessToken, err := o.repo.TokenByIDs(ctx, userID, token)
if err != nil { if err != nil {
if errors.IsNotFound(err) { if zerrors.IsNotFound(err) {
return nil return nil
} }
return oidc.ErrServerError().WithParent(err) return oidc.ErrServerError().WithParent(err)
@ -398,7 +398,7 @@ func (o *OPStorage) revokeTokenV1(ctx context.Context, token, userID, clientID s
return oidc.ErrInvalidClient().WithDescription("token was not issued for this client") return oidc.ErrInvalidClient().WithDescription("token was not issued for this client")
} }
_, err = o.command.RevokeAccessToken(ctx, userID, accessToken.ResourceOwner, accessToken.ID) _, err = o.command.RevokeAccessToken(ctx, userID, accessToken.ResourceOwner, accessToken.ID)
if err == nil || errors.IsNotFound(err) { if err == nil || zerrors.IsNotFound(err) {
return nil return nil
} }
return oidc.ErrServerError().WithParent(err) return oidc.ErrServerError().WithParent(err)
@ -434,18 +434,18 @@ func (o *OPStorage) assertProjectRoleScopes(ctx context.Context, clientID string
} }
projectID, err := o.query.ProjectIDFromOIDCClientID(ctx, clientID) projectID, err := o.query.ProjectIDFromOIDCClientID(ctx, clientID)
if err != nil { if err != nil {
return nil, errors.ThrowPreconditionFailed(nil, "OIDC-AEG4d", "Errors.Internal") return nil, zerrors.ThrowPreconditionFailed(nil, "OIDC-AEG4d", "Errors.Internal")
} }
project, err := o.query.ProjectByID(ctx, false, projectID) project, err := o.query.ProjectByID(ctx, false, projectID)
if err != nil { if err != nil {
return nil, errors.ThrowPreconditionFailed(nil, "OIDC-w4wIn", "Errors.Internal") return nil, zerrors.ThrowPreconditionFailed(nil, "OIDC-w4wIn", "Errors.Internal")
} }
if !project.ProjectRoleAssertion { if !project.ProjectRoleAssertion {
return scopes, nil return scopes, nil
} }
projectIDQuery, err := query.NewProjectRoleProjectIDSearchQuery(project.ID) projectIDQuery, err := query.NewProjectRoleProjectIDSearchQuery(project.ID)
if err != nil { if err != nil {
return nil, errors.ThrowInternal(err, "OIDC-Cyc78", "Errors.Internal") return nil, zerrors.ThrowInternal(err, "OIDC-Cyc78", "Errors.Internal")
} }
roles, err := o.query.SearchProjectRoles(ctx, true, &query.ProjectRoleSearchQueries{Queries: []query.SearchQuery{projectIDQuery}}) roles, err := o.query.SearchProjectRoles(ctx, true, &query.ProjectRoleSearchQueries{Queries: []query.SearchQuery{projectIDQuery}})
if err != nil { if err != nil {
@ -468,7 +468,7 @@ func (o *OPStorage) assertProjectRoleScopesByProject(ctx context.Context, projec
} }
projectIDQuery, err := query.NewProjectRoleProjectIDSearchQuery(project.ID) projectIDQuery, err := query.NewProjectRoleProjectIDSearchQuery(project.ID)
if err != nil { if err != nil {
return nil, errors.ThrowInternal(err, "OIDC-Cyc78", "Errors.Internal") return nil, zerrors.ThrowInternal(err, "OIDC-Cyc78", "Errors.Internal")
} }
roles, err := o.query.SearchProjectRoles(ctx, true, &query.ProjectRoleSearchQueries{Queries: []query.SearchQuery{projectIDQuery}}) roles, err := o.query.SearchProjectRoles(ctx, true, &query.ProjectRoleSearchQueries{Queries: []query.SearchQuery{projectIDQuery}})
if err != nil { if err != nil {
@ -484,7 +484,7 @@ func (o *OPStorage) assertClientScopesForPAT(ctx context.Context, token *model.T
token.Audience = append(token.Audience, clientID) token.Audience = append(token.Audience, clientID)
projectIDQuery, err := query.NewProjectRoleProjectIDSearchQuery(projectID) projectIDQuery, err := query.NewProjectRoleProjectIDSearchQuery(projectID)
if err != nil { if err != nil {
return errors.ThrowInternal(err, "OIDC-Cyc78", "Errors.Internal") return zerrors.ThrowInternal(err, "OIDC-Cyc78", "Errors.Internal")
} }
roles, err := o.query.SearchProjectRoles(ctx, true, &query.ProjectRoleSearchQueries{Queries: []query.SearchQuery{projectIDQuery}}) roles, err := o.query.SearchProjectRoles(ctx, true, &query.ProjectRoleSearchQueries{Queries: []query.SearchQuery{projectIDQuery}})
if err != nil { if err != nil {
@ -505,7 +505,7 @@ func setContextUserSystem(ctx context.Context) context.Context {
func (o *OPStorage) getOIDCSettings(ctx context.Context) (accessTokenLifetime, idTokenLifetime, refreshTokenIdleExpiration, refreshTokenExpiration time.Duration, _ error) { func (o *OPStorage) getOIDCSettings(ctx context.Context) (accessTokenLifetime, idTokenLifetime, refreshTokenIdleExpiration, refreshTokenExpiration time.Duration, _ error) {
oidcSettings, err := o.query.OIDCSettingsByAggID(ctx, authz.GetInstance(ctx).InstanceID()) oidcSettings, err := o.query.OIDCSettingsByAggID(ctx, authz.GetInstance(ctx).InstanceID())
if err != nil && !errors.IsNotFound(err) { if err != nil && !zerrors.IsNotFound(err) {
return time.Duration(0), time.Duration(0), time.Duration(0), time.Duration(0), err return time.Duration(0), time.Duration(0), time.Duration(0), time.Duration(0), err
} }

View File

@ -13,8 +13,8 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http" http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/user/model" "github.com/zitadel/zitadel/internal/user/model"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type AuthRequest struct { type AuthRequest struct {
@ -96,7 +96,7 @@ func (a *AuthRequest) oidc() *domain.AuthRequestOIDC {
func AuthRequestFromBusiness(authReq *domain.AuthRequest) (_ op.AuthRequest, err error) { func AuthRequestFromBusiness(authReq *domain.AuthRequest) (_ op.AuthRequest, err error) {
if _, ok := authReq.Request.(*domain.AuthRequestOIDC); !ok { if _, ok := authReq.Request.(*domain.AuthRequestOIDC); !ok {
return nil, errors.ThrowInvalidArgument(nil, "OIDC-Haz7A", "auth request is not of type oidc") return nil, zerrors.ThrowInvalidArgument(nil, "OIDC-Haz7A", "auth request is not of type oidc")
} }
return &AuthRequest{authReq}, nil return &AuthRequest{authReq}, nil
} }

View File

@ -21,9 +21,9 @@ import (
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -48,7 +48,7 @@ func (o *OPStorage) GetClientByClientID(ctx context.Context, id string) (_ op.Cl
return nil, err return nil, err
} }
if client.State != domain.AppStateActive { if client.State != domain.AppStateActive {
return nil, errors.ThrowPreconditionFailed(nil, "OIDC-sdaGg", "client is not active") return nil, zerrors.ThrowPreconditionFailed(nil, "OIDC-sdaGg", "client is not active")
} }
return ClientFromBusiness(client, o.defaultLoginURL, o.defaultLoginURLV2), nil return ClientFromBusiness(client, o.defaultLoginURL, o.defaultLoginURLV2), nil
} }
@ -117,7 +117,7 @@ func (o *OPStorage) SetUserinfoFromToken(ctx context.Context, userInfo *oidc.Use
token, err := o.repo.TokenByIDs(ctx, subject, tokenID) token, err := o.repo.TokenByIDs(ctx, subject, tokenID)
if err != nil { if err != nil {
return errors.ThrowPermissionDenied(nil, "OIDC-Dsfb2", "token is not valid or has expired") return zerrors.ThrowPermissionDenied(nil, "OIDC-Dsfb2", "token is not valid or has expired")
} }
if token.ApplicationID != "" { if token.ApplicationID != "" {
if err = o.isOriginAllowed(ctx, token.ApplicationID, origin); err != nil { if err = o.isOriginAllowed(ctx, token.ApplicationID, origin); err != nil {
@ -138,7 +138,7 @@ func (o *OPStorage) SetUserinfoFromScopes(ctx context.Context, userInfo *oidc.Us
if app.OIDCConfig.AssertIDTokenRole { if app.OIDCConfig.AssertIDTokenRole {
scopes, err = o.assertProjectRoleScopes(ctx, applicationID, scopes) scopes, err = o.assertProjectRoleScopes(ctx, applicationID, scopes)
if err != nil { if err != nil {
return errors.ThrowPreconditionFailed(err, "OIDC-Dfe2s", "Errors.Internal") return zerrors.ThrowPreconditionFailed(err, "OIDC-Dfe2s", "Errors.Internal")
} }
} }
} }
@ -168,7 +168,7 @@ func (o *OPStorage) SetIntrospectionFromToken(ctx context.Context, introspection
} }
projectID, err := o.query.ProjectIDFromClientID(ctx, clientID) projectID, err := o.query.ProjectIDFromClientID(ctx, clientID)
if err != nil { if err != nil {
return errors.ThrowPermissionDenied(nil, "OIDC-Adfg5", "client not found") return zerrors.ThrowPermissionDenied(nil, "OIDC-Adfg5", "client not found")
} }
return o.introspect(ctx, introspection, return o.introspect(ctx, introspection,
tokenID, token.UserID, token.ClientID, clientID, projectID, tokenID, token.UserID, token.ClientID, clientID, projectID,
@ -178,16 +178,16 @@ func (o *OPStorage) SetIntrospectionFromToken(ctx context.Context, introspection
token, err := o.repo.TokenByIDs(ctx, subject, tokenID) token, err := o.repo.TokenByIDs(ctx, subject, tokenID)
if err != nil { if err != nil {
return errors.ThrowPermissionDenied(nil, "OIDC-Dsfb2", "token is not valid or has expired") return zerrors.ThrowPermissionDenied(nil, "OIDC-Dsfb2", "token is not valid or has expired")
} }
projectID, err := o.query.ProjectIDFromClientID(ctx, clientID) projectID, err := o.query.ProjectIDFromClientID(ctx, clientID)
if err != nil { if err != nil {
return errors.ThrowPermissionDenied(nil, "OIDC-Adfg5", "client not found") return zerrors.ThrowPermissionDenied(nil, "OIDC-Adfg5", "client not found")
} }
if token.IsPAT { if token.IsPAT {
err = o.assertClientScopesForPAT(ctx, token, clientID, projectID) err = o.assertClientScopesForPAT(ctx, token, clientID, projectID)
if err != nil { if err != nil {
return errors.ThrowPreconditionFailed(err, "OIDC-AGefw", "Errors.Internal") return zerrors.ThrowPreconditionFailed(err, "OIDC-AGefw", "Errors.Internal")
} }
} }
return o.introspect(ctx, introspection, return o.introspect(ctx, introspection,
@ -216,7 +216,7 @@ func (o *OPStorage) ClientCredentialsTokenRequest(ctx context.Context, clientID
// ClientCredentials method is kept to keep the storage interface implemented. // ClientCredentials method is kept to keep the storage interface implemented.
// However, it should never be called as the VerifyClient method on the Server is overridden. // However, it should never be called as the VerifyClient method on the Server is overridden.
func (o *OPStorage) ClientCredentials(context.Context, string, string) (op.Client, error) { func (o *OPStorage) ClientCredentials(context.Context, string, string) (op.Client, error) {
return nil, errors.ThrowInternal(nil, "OIDC-Su8So", "Errors.Internal") return nil, zerrors.ThrowInternal(nil, "OIDC-Su8So", "Errors.Internal")
} }
// isOriginAllowed checks whether a call by the client to the endpoint is allowed from the provided origin // isOriginAllowed checks whether a call by the client to the endpoint is allowed from the provided origin
@ -232,7 +232,7 @@ func (o *OPStorage) isOriginAllowed(ctx context.Context, clientID, origin string
if api_http.IsOriginAllowed(app.OIDCConfig.AllowedOrigins, origin) { if api_http.IsOriginAllowed(app.OIDCConfig.AllowedOrigins, origin) {
return nil return nil
} }
return errors.ThrowPermissionDenied(nil, "OIDC-da1f3", "origin is not allowed") return zerrors.ThrowPermissionDenied(nil, "OIDC-da1f3", "origin is not allowed")
} }
func (o *OPStorage) introspect( func (o *OPStorage) introspect(
@ -265,7 +265,7 @@ func (o *OPStorage) introspect(
return nil return nil
} }
} }
return errors.ThrowPermissionDenied(nil, "OIDC-sdg3G", "token is not valid for this client") return zerrors.ThrowPermissionDenied(nil, "OIDC-sdg3G", "token is not valid for this client")
} }
func (o *OPStorage) checkOrgScopes(ctx context.Context, user *query.User, scopes []string) ([]string, error) { func (o *OPStorage) checkOrgScopes(ctx context.Context, user *query.User, scopes []string) ([]string, error) {
@ -732,7 +732,7 @@ func (o *OPStorage) assertRoles(ctx context.Context, userID, applicationID strin
} }
projectID, err := o.query.ProjectIDFromClientID(ctx, applicationID) projectID, err := o.query.ProjectIDFromClientID(ctx, applicationID)
// applicationID might contain a username (e.g. client credentials) -> ignore the not found // applicationID might contain a username (e.g. client credentials) -> ignore the not found
if err != nil && !errors.IsNotFound(err) { if err != nil && !zerrors.IsNotFound(err) {
return nil, nil, err return nil, nil, err
} }
// ensure the projectID of the requesting is part of the roleAudience // ensure the projectID of the requesting is part of the roleAudience
@ -914,7 +914,7 @@ func (s *Server) VerifyClient(ctx context.Context, r *op.Request[op.ClientCreden
return nil, err return nil, err
} }
client, err := s.query.GetOIDCClientByID(ctx, clientID, assertion) client, err := s.query.GetOIDCClientByID(ctx, clientID, assertion)
if errors.IsNotFound(err) { if zerrors.IsNotFound(err) {
return nil, oidc.ErrInvalidClient().WithParent(err).WithDescription("client not found") return nil, oidc.ErrInvalidClient().WithParent(err).WithDescription("client not found")
} }
if err != nil { if err != nil {

View File

@ -8,8 +8,8 @@ import (
"github.com/zitadel/oidc/v3/pkg/op" "github.com/zitadel/oidc/v3/pkg/op"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type clientCredentialsRequest struct { type clientCredentialsRequest struct {
@ -35,18 +35,18 @@ func (c *clientCredentialsRequest) GetScopes() []string {
func (s *Server) clientCredentialsAuth(ctx context.Context, clientID, clientSecret string) (op.Client, error) { func (s *Server) clientCredentialsAuth(ctx context.Context, clientID, clientSecret string) (op.Client, error) {
user, err := s.query.GetUserByLoginName(ctx, false, clientID) user, err := s.query.GetUserByLoginName(ctx, false, clientID)
if errors.IsNotFound(err) { if zerrors.IsNotFound(err) {
return nil, oidc.ErrInvalidClient().WithParent(err).WithDescription("client not found") return nil, oidc.ErrInvalidClient().WithParent(err).WithDescription("client not found")
} }
if err != nil { if err != nil {
return nil, err // defaults to server error return nil, err // defaults to server error
} }
if user.Machine == nil || user.Machine.Secret == nil { if user.Machine == nil || user.Machine.Secret == nil {
return nil, errors.ThrowPreconditionFailed(nil, "OIDC-pieP8", "Errors.User.Machine.Secret.NotExisting") return nil, zerrors.ThrowPreconditionFailed(nil, "OIDC-pieP8", "Errors.User.Machine.Secret.NotExisting")
} }
if err = crypto.CompareHash(user.Machine.Secret, []byte(clientSecret), s.hashAlg); err != nil { if err = crypto.CompareHash(user.Machine.Secret, []byte(clientSecret), s.hashAlg); err != nil {
s.command.MachineSecretCheckFailed(ctx, user.ID, user.ResourceOwner) s.command.MachineSecretCheckFailed(ctx, user.ID, user.ResourceOwner)
return nil, errors.ThrowInvalidArgument(err, "OIDC-VoXo6", "Errors.User.Machine.Secret.Invalid") return nil, zerrors.ThrowInvalidArgument(err, "OIDC-VoXo6", "Errors.User.Machine.Secret.Invalid")
} }
s.command.MachineSecretCheckSucceeded(ctx, user.ID, user.ResourceOwner) s.command.MachineSecretCheckSucceeded(ctx, user.ID, user.ResourceOwner)

View File

@ -10,8 +10,8 @@ import (
"github.com/zitadel/zitadel/internal/api/ui/login" "github.com/zitadel/zitadel/internal/api/ui/login"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -85,12 +85,12 @@ func (o *OPStorage) StoreDeviceAuthorization(ctx context.Context, clientID, devi
return err return err
} }
if !op.ValidateGrantType(client, oidc.GrantTypeDeviceCode) { if !op.ValidateGrantType(client, oidc.GrantTypeDeviceCode) {
return errors.ThrowPermissionDeniedf(nil, "OIDC-et1Ae", "grant type %q not allowed for client", oidc.GrantTypeDeviceCode) return zerrors.ThrowPermissionDeniedf(nil, "OIDC-et1Ae", "grant type %q not allowed for client", oidc.GrantTypeDeviceCode)
} }
scopes, err = o.assertProjectRoleScopes(ctx, clientID, scopes) scopes, err = o.assertProjectRoleScopes(ctx, clientID, scopes)
if err != nil { if err != nil {
return errors.ThrowPreconditionFailed(err, "OIDC-She4t", "Errors.Internal") return zerrors.ThrowPreconditionFailed(err, "OIDC-She4t", "Errors.Internal")
} }
aggrID, details, err := o.command.AddDeviceAuth(ctx, clientID, deviceCode, userCode, expires, scopes) aggrID, details, err := o.command.AddDeviceAuth(ctx, clientID, deviceCode, userCode, expires, scopes)
if err == nil { if err == nil {

View File

@ -11,9 +11,9 @@ import (
"github.com/zitadel/oidc/v3/pkg/op" "github.com/zitadel/oidc/v3/pkg/op"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
zerrors "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
func (s *Server) Introspect(ctx context.Context, r *op.Request[op.IntrospectionRequest]) (resp *op.Response, err error) { func (s *Server) Introspect(ctx context.Context, r *op.Request[op.IntrospectionRequest]) (resp *op.Response, err error) {

View File

@ -7,7 +7,7 @@ import (
"github.com/zitadel/oidc/v3/pkg/op" "github.com/zitadel/oidc/v3/pkg/op"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
func (o *OPStorage) JWTProfileTokenType(ctx context.Context, request op.TokenRequest) (op.AccessTokenType, error) { func (o *OPStorage) JWTProfileTokenType(ctx context.Context, request op.TokenRequest) (op.AccessTokenType, error) {
@ -18,7 +18,7 @@ func (o *OPStorage) JWTProfileTokenType(ctx context.Context, request op.TokenReq
} }
// the user should always be a machine, but let's just be sure // the user should always be a machine, but let's just be sure
if user.Machine == nil { if user.Machine == nil {
return 0, errors.ThrowInvalidArgument(nil, "OIDC-jk26S", "invalid client type") return 0, zerrors.ThrowInvalidArgument(nil, "OIDC-jk26S", "invalid client type")
} }
return accessTokenTypeToOIDC(user.Machine.AccessTokenType), nil return accessTokenTypeToOIDC(user.Machine.AccessTokenType), nil
} }

View File

@ -14,12 +14,12 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/repository/instance" "github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/keypair" "github.com/zitadel/zitadel/internal/repository/keypair"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
// keySetCache implements oidc.KeySet for Access Token verification. // keySetCache implements oidc.KeySet for Access Token verification.
@ -97,7 +97,7 @@ func (k *keySetCache) getKey(ctx context.Context, keyID string) (_ *jose.JSONWeb
if key.Expiry().After(k.clock.Now()) { if key.Expiry().After(k.clock.Now()) {
return jsonWebkey(key), nil return jsonWebkey(key), nil
} }
return nil, errors.ThrowInvalidArgument(nil, "OIDC-Zoh9E", "Errors.Key.ExpireBeforeNow") return nil, zerrors.ThrowInvalidArgument(nil, "OIDC-Zoh9E", "Errors.Key.ExpireBeforeNow")
} }
key, err = k.queryKey(ctx, keyID, k.clock.Now()) key, err = k.queryKey(ctx, keyID, k.clock.Now())
@ -114,7 +114,7 @@ func (k *keySetCache) VerifySignature(ctx context.Context, jws *jose.JSONWebSign
defer func() { span.EndWithError(err) }() defer func() { span.EndWithError(err) }()
if len(jws.Signatures) != 1 { if len(jws.Signatures) != 1 {
return nil, errors.ThrowInvalidArgument(nil, "OIDC-Gid9s", "Errors.Token.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "OIDC-Gid9s", "Errors.Token.Invalid")
} }
key, err := k.getKey(ctx, jws.Signatures[0].Header.KeyID) key, err := k.getKey(ctx, jws.Signatures[0].Header.KeyID)
if err != nil { if err != nil {
@ -152,7 +152,7 @@ func (k keySetMap) getKey(keyID string) (*jose.JSONWebKey, error) {
// VerifySignature implements the oidc.KeySet interface. // VerifySignature implements the oidc.KeySet interface.
func (k keySetMap) VerifySignature(ctx context.Context, jws *jose.JSONWebSignature) ([]byte, error) { func (k keySetMap) VerifySignature(ctx context.Context, jws *jose.JSONWebSignature) ([]byte, error) {
if len(jws.Signatures) != 1 { if len(jws.Signatures) != 1 {
return nil, errors.ThrowInvalidArgument(nil, "OIDC-Eeth6", "Errors.Token.Invalid") return nil, zerrors.ThrowInvalidArgument(nil, "OIDC-Eeth6", "Errors.Token.Invalid")
} }
key, err := k.getKey(jws.Signatures[0].Header.KeyID) key, err := k.getKey(jws.Signatures[0].Header.KeyID)
if err != nil { if err != nil {
@ -248,7 +248,7 @@ func (o *OPStorage) SigningKey(ctx context.Context) (key op.SigningKey, err erro
return err return err
} }
if key == nil { if key == nil {
return errors.ThrowInternal(nil, "test", "test") return zerrors.ThrowInternal(nil, "test", "test")
} }
return nil return nil
}) })
@ -273,13 +273,13 @@ func (o *OPStorage) getSigningKey(ctx context.Context) (op.SigningKey, error) {
func (o *OPStorage) refreshSigningKey(ctx context.Context, algorithm string, position float64) error { func (o *OPStorage) refreshSigningKey(ctx context.Context, algorithm string, position float64) error {
ok, err := o.ensureIsLatestKey(ctx, position) ok, err := o.ensureIsLatestKey(ctx, position)
if err != nil || !ok { if err != nil || !ok {
return errors.ThrowInternal(err, "OIDC-ASfh3", "cannot ensure that projection is up to date") return zerrors.ThrowInternal(err, "OIDC-ASfh3", "cannot ensure that projection is up to date")
} }
err = o.lockAndGenerateSigningKeyPair(ctx, algorithm) err = o.lockAndGenerateSigningKeyPair(ctx, algorithm)
if err != nil { if err != nil {
return errors.ThrowInternal(err, "OIDC-ADh31", "could not create signing key") return zerrors.ThrowInternal(err, "OIDC-ADh31", "could not create signing key")
} }
return errors.ThrowInternal(nil, "OIDC-Df1bh", "") return zerrors.ThrowInternal(nil, "OIDC-Df1bh", "")
} }
func (o *OPStorage) ensureIsLatestKey(ctx context.Context, position float64) (bool, error) { func (o *OPStorage) ensureIsLatestKey(ctx context.Context, position float64) (bool, error) {
@ -315,7 +315,7 @@ func (o *OPStorage) lockAndGenerateSigningKeyPair(ctx context.Context, algorithm
errs := o.locker.Lock(ctx, lockDuration, authz.GetInstance(ctx).InstanceID()) errs := o.locker.Lock(ctx, lockDuration, authz.GetInstance(ctx).InstanceID())
err, ok := <-errs err, ok := <-errs
if err != nil || !ok { if err != nil || !ok {
if errors.IsErrorAlreadyExists(err) { if zerrors.IsErrorAlreadyExists(err) {
return nil return nil
} }
logging.OnError(err).Debug("initial lock failed") logging.OnError(err).Debug("initial lock failed")

View File

@ -18,11 +18,11 @@ import (
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/database" "github.com/zitadel/zitadel/internal/database"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/handler/crdb" "github.com/zitadel/zitadel/internal/eventstore/handler/crdb"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/metrics" "github.com/zitadel/zitadel/internal/telemetry/metrics"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type Config struct { type Config struct {
@ -101,7 +101,7 @@ func NewServer(
) (*Server, error) { ) (*Server, error) {
opConfig, err := createOPConfig(config, defaultLogoutRedirectURI, cryptoKey) opConfig, err := createOPConfig(config, defaultLogoutRedirectURI, cryptoKey)
if err != nil { if err != nil {
return nil, caos_errs.ThrowInternal(err, "OIDC-EGrqd", "cannot create op config: %w") return nil, zerrors.ThrowInternal(err, "OIDC-EGrqd", "cannot create op config: %w")
} }
storage := newStorage(config, command, query, repo, encryptionAlg, es, projections, externalSecure) storage := newStorage(config, command, query, repo, encryptionAlg, es, projections, externalSecure)
var options []op.Option var options []op.Option
@ -109,7 +109,7 @@ func NewServer(
options = append(options, op.WithAllowInsecure()) options = append(options, op.WithAllowInsecure())
} }
if err != nil { if err != nil {
return nil, caos_errs.ThrowInternal(err, "OIDC-D3gq1", "cannot create options: %w") return nil, zerrors.ThrowInternal(err, "OIDC-D3gq1", "cannot create options: %w")
} }
provider, err := op.NewProvider( provider, err := op.NewProvider(
opConfig, opConfig,
@ -118,7 +118,7 @@ func NewServer(
options..., options...,
) )
if err != nil { if err != nil {
return nil, caos_errs.ThrowInternal(err, "OIDC-DAtg3", "cannot create provider") return nil, zerrors.ThrowInternal(err, "OIDC-DAtg3", "cannot create provider")
} }
server := &Server{ server := &Server{
@ -179,7 +179,7 @@ func createOPConfig(config Config, defaultLogoutRedirectURI string, cryptoKey []
DeviceAuthorization: config.DeviceAuth.toOPConfig(), DeviceAuthorization: config.DeviceAuth.toOPConfig(),
} }
if cryptoLength := len(cryptoKey); cryptoLength != 32 { if cryptoLength := len(cryptoKey); cryptoLength != 32 {
return nil, caos_errs.ThrowInternalf(nil, "OIDC-D43gf", "crypto key must be 32 bytes, but is %d", cryptoLength) return nil, zerrors.ThrowInternalf(nil, "OIDC-D43gf", "crypto key must be 32 bytes, but is %d", cryptoLength)
} }
copy(opConfig.CryptoKey[:], cryptoKey) copy(opConfig.CryptoKey[:], cryptoKey)
return opConfig, nil return opConfig, nil

View File

@ -9,7 +9,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
var _ models.AuthRequestInt = &AuthRequest{} var _ models.AuthRequestInt = &AuthRequest{}
@ -66,7 +66,7 @@ func (a *AuthRequest) GetUserName() string {
func AuthRequestFromBusiness(authReq *domain.AuthRequest) (_ models.AuthRequestInt, err error) { func AuthRequestFromBusiness(authReq *domain.AuthRequest) (_ models.AuthRequestInt, err error) {
if _, ok := authReq.Request.(*domain.AuthRequestSAML); !ok { if _, ok := authReq.Request.(*domain.AuthRequestSAML); !ok {
return nil, errors.ThrowInvalidArgument(nil, "SAML-Hbz7A", "auth request is not of type saml") return nil, zerrors.ThrowInvalidArgument(nil, "SAML-Hbz7A", "auth request is not of type saml")
} }
return &AuthRequest{authReq}, nil return &AuthRequest{authReq}, nil
} }

View File

@ -12,11 +12,11 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/repository/instance" "github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/keypair" "github.com/zitadel/zitadel/internal/repository/keypair"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -60,7 +60,7 @@ func (p *Storage) GetCertificateAndKey(ctx context.Context, usage domain.KeyUsag
return err return err
} }
if certAndKey == nil { if certAndKey == nil {
return errors.ThrowInternal(err, "SAML-8u01nks", "no certificate found") return zerrors.ThrowInternal(err, "SAML-8u01nks", "no certificate found")
} }
return nil return nil
}) })
@ -120,7 +120,7 @@ func (p *Storage) lockAndGenerateCertificateAndKey(ctx context.Context, usage do
errs := p.locker.Lock(ctx, lockDuration, authz.GetInstance(ctx).InstanceID()) errs := p.locker.Lock(ctx, lockDuration, authz.GetInstance(ctx).InstanceID())
err, ok := <-errs err, ok := <-errs
if err != nil || !ok { if err != nil || !ok {
if errors.IsErrorAlreadyExists(err) { if zerrors.IsErrorAlreadyExists(err) {
return nil return nil
} }
logging.OnError(err).Debug("initial lock failed") logging.OnError(err).Debug("initial lock failed")

View File

@ -21,11 +21,11 @@ import (
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/handler/crdb" "github.com/zitadel/zitadel/internal/eventstore/handler/crdb"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
) )
var _ provider.EntityStorage = &Storage{} var _ provider.EntityStorage = &Storage{}
@ -60,7 +60,7 @@ func (p *Storage) GetEntityByID(ctx context.Context, entityID string) (*servicep
return nil, err return nil, err
} }
if app.State != domain.AppStateActive { if app.State != domain.AppStateActive {
return nil, errors.ThrowPreconditionFailed(nil, "SAML-sdaGg", "app is not active") return nil, zerrors.ThrowPreconditionFailed(nil, "SAML-sdaGg", "app is not active")
} }
return serviceprovider.NewServiceProvider( return serviceprovider.NewServiceProvider(
app.ID, app.ID,
@ -77,7 +77,7 @@ func (p *Storage) GetEntityIDByAppID(ctx context.Context, appID string) (string,
return "", err return "", err
} }
if app.State != domain.AppStateActive { if app.State != domain.AppStateActive {
return "", errors.ThrowPreconditionFailed(nil, "SAML-sdaGg", "app is not active") return "", zerrors.ThrowPreconditionFailed(nil, "SAML-sdaGg", "app is not active")
} }
return app.SAMLConfig.EntityID, nil return app.SAMLConfig.EntityID, nil
} }
@ -103,7 +103,7 @@ func (p *Storage) CreateAuthRequest(ctx context.Context, req *samlp.AuthnRequest
defer func() { span.EndWithError(err) }() defer func() { span.EndWithError(err) }()
userAgentID, ok := middleware.UserAgentIDFromCtx(ctx) userAgentID, ok := middleware.UserAgentIDFromCtx(ctx)
if !ok { if !ok {
return nil, errors.ThrowPreconditionFailed(nil, "SAML-sd436", "no user agent id") return nil, zerrors.ThrowPreconditionFailed(nil, "SAML-sd436", "no user agent id")
} }
authRequest := CreateAuthRequestToBusiness(ctx, req, acsUrl, protocolBinding, applicationID, relayState, userAgentID) authRequest := CreateAuthRequestToBusiness(ctx, req, acsUrl, protocolBinding, applicationID, relayState, userAgentID)
@ -121,7 +121,7 @@ func (p *Storage) AuthRequestByID(ctx context.Context, id string) (_ models.Auth
defer func() { span.EndWithError(err) }() defer func() { span.EndWithError(err) }()
userAgentID, ok := middleware.UserAgentIDFromCtx(ctx) userAgentID, ok := middleware.UserAgentIDFromCtx(ctx)
if !ok { if !ok {
return nil, errors.ThrowPreconditionFailed(nil, "SAML-D3g21", "no user agent id") return nil, zerrors.ThrowPreconditionFailed(nil, "SAML-D3g21", "no user agent id")
} }
resp, err := p.repo.AuthRequestByIDCheckLoggedIn(ctx, id, userAgentID) resp, err := p.repo.AuthRequestByIDCheckLoggedIn(ctx, id, userAgentID)
if err != nil { if err != nil {

View File

@ -1,7 +1,7 @@
package login package login
import ( import (
errs "errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
@ -14,7 +14,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/http/middleware" "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -95,7 +95,7 @@ func (l *Login) handleDeviceAuthUserCode(w http.ResponseWriter, r *http.Request)
userCode := r.Form.Get("user_code") userCode := r.Form.Get("user_code")
if userCode == "" { if userCode == "" {
if prompt, _ := url.QueryUnescape(r.Form.Get("prompt")); prompt != "" { if prompt, _ := url.QueryUnescape(r.Form.Get("prompt")); prompt != "" {
err = errs.New(prompt) err = errors.New(prompt)
} }
l.renderDeviceAuthUserCode(w, r, err) l.renderDeviceAuthUserCode(w, r, err)
return return
@ -107,7 +107,7 @@ func (l *Login) handleDeviceAuthUserCode(w http.ResponseWriter, r *http.Request)
} }
userAgentID, ok := middleware.UserAgentIDFromCtx(ctx) userAgentID, ok := middleware.UserAgentIDFromCtx(ctx)
if !ok { if !ok {
l.renderDeviceAuthUserCode(w, r, errs.New("internal error: agent ID missing")) l.renderDeviceAuthUserCode(w, r, errors.New("internal error: agent ID missing"))
return return
} }
authRequest, err := l.authRepo.CreateAuthRequest(ctx, &domain.AuthRequest{ authRequest, err := l.authRepo.CreateAuthRequest(ctx, &domain.AuthRequest{
@ -151,7 +151,7 @@ func (l *Login) redirectDeviceAuthStart(w http.ResponseWriter, r *http.Request,
func (l *Login) handleDeviceAuthAction(w http.ResponseWriter, r *http.Request) { func (l *Login) handleDeviceAuthAction(w http.ResponseWriter, r *http.Request) {
authReq, err := l.getAuthRequest(r) authReq, err := l.getAuthRequest(r)
if authReq == nil { if authReq == nil {
err = errors.ThrowInvalidArgument(err, "LOGIN-OLah8", "invalid or missing auth request") err = zerrors.ThrowInvalidArgument(err, "LOGIN-OLah8", "invalid or missing auth request")
l.redirectDeviceAuthStart(w, r, err.Error()) l.redirectDeviceAuthStart(w, r, err.Error())
return return
} }

View File

@ -17,7 +17,6 @@ import (
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware" http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore/v1/models" "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/idp" "github.com/zitadel/zitadel/internal/idp"
"github.com/zitadel/zitadel/internal/idp/providers/apple" "github.com/zitadel/zitadel/internal/idp/providers/apple"
@ -32,6 +31,7 @@ import (
"github.com/zitadel/zitadel/internal/idp/providers/saml" "github.com/zitadel/zitadel/internal/idp/providers/saml"
"github.com/zitadel/zitadel/internal/idp/providers/saml/requesttracker" "github.com/zitadel/zitadel/internal/idp/providers/saml/requesttracker"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -106,7 +106,7 @@ func (l *Login) handleExternalLoginStep(w http.ResponseWriter, r *http.Request,
return return
} }
} }
l.renderLogin(w, r, authReq, errors.ThrowInvalidArgument(nil, "VIEW-Fsj7f", "Errors.User.ExternalIDP.NotAllowed")) l.renderLogin(w, r, authReq, zerrors.ThrowInvalidArgument(nil, "VIEW-Fsj7f", "Errors.User.ExternalIDP.NotAllowed"))
} }
// handleExternalLogin is called when a user selects the idp on the login page // handleExternalLogin is called when a user selects the idp on the login page
@ -179,7 +179,7 @@ func (l *Login) handleIDP(w http.ResponseWriter, r *http.Request, authReq *domai
case domain.IDPTypeUnspecified: case domain.IDPTypeUnspecified:
fallthrough fallthrough
default: default:
l.renderLogin(w, r, authReq, errors.ThrowInvalidArgument(nil, "LOGIN-AShek", "Errors.ExternalIDP.IDPTypeNotImplemented")) l.renderLogin(w, r, authReq, zerrors.ThrowInvalidArgument(nil, "LOGIN-AShek", "Errors.ExternalIDP.IDPTypeNotImplemented"))
return return
} }
if err != nil { if err != nil {
@ -330,7 +330,7 @@ func (l *Login) handleExternalLoginCallback(w http.ResponseWriter, r *http.Reque
domain.IDPTypeUnspecified: domain.IDPTypeUnspecified:
fallthrough fallthrough
default: default:
l.renderLogin(w, r, authReq, errors.ThrowInvalidArgument(nil, "LOGIN-SFefg", "Errors.ExternalIDP.IDPTypeNotImplemented")) l.renderLogin(w, r, authReq, zerrors.ThrowInvalidArgument(nil, "LOGIN-SFefg", "Errors.ExternalIDP.IDPTypeNotImplemented"))
return return
} }
@ -365,7 +365,7 @@ func (l *Login) migrateExternalUserID(r *http.Request, authReq *domain.AuthReque
// always reset to the mapped ID // always reset to the mapped ID
externalUser.ExternalUserID = externalUserID externalUser.ExternalUserID = externalUserID
// but ignore the error if the user was just not found with the previousID // but ignore the error if the user was just not found with the previousID
if errors.IsNotFound(err) { if zerrors.IsNotFound(err) {
return false, nil return false, nil
} }
return false, err return false, err
@ -395,11 +395,11 @@ func (l *Login) handleExternalUserAuthenticated(
externalUser := mapIDPUserToExternalUser(user, provider.ID) externalUser := mapIDPUserToExternalUser(user, provider.ID)
// check and fill in local linked user // check and fill in local linked user
externalErr := l.authRepo.CheckExternalUserLogin(setContext(r.Context(), ""), authReq.ID, authReq.AgentID, externalUser, domain.BrowserInfoFromRequest(r), false) externalErr := l.authRepo.CheckExternalUserLogin(setContext(r.Context(), ""), authReq.ID, authReq.AgentID, externalUser, domain.BrowserInfoFromRequest(r), false)
if externalErr != nil && !errors.IsNotFound(externalErr) { if externalErr != nil && !zerrors.IsNotFound(externalErr) {
l.renderError(w, r, authReq, externalErr) l.renderError(w, r, authReq, externalErr)
return return
} }
if externalErr != nil && errors.IsNotFound(externalErr) { if externalErr != nil && zerrors.IsNotFound(externalErr) {
previousIDMatched, err := l.tryMigrateExternalUserID(r, session, authReq, externalUser) previousIDMatched, err := l.tryMigrateExternalUserID(r, session, authReq, externalUser)
if err != nil { if err != nil {
l.renderError(w, r, authReq, err) l.renderError(w, r, authReq, err)
@ -423,7 +423,7 @@ func (l *Login) handleExternalUserAuthenticated(
return return
} }
// if action is done and no user linked then link or register // if action is done and no user linked then link or register
if errors.IsNotFound(externalErr) { if zerrors.IsNotFound(externalErr) {
l.externalUserNotExisting(w, r, authReq, provider, externalUser, externalUserChange) l.externalUserNotExisting(w, r, authReq, provider, externalUser, externalUserChange)
return return
} }
@ -489,7 +489,7 @@ func (l *Login) externalUserNotExisting(w http.ResponseWriter, r *http.Request,
// autoCreateExternalUser takes the externalUser and creates it automatically (without user interaction) // autoCreateExternalUser takes the externalUser and creates it automatically (without user interaction)
func (l *Login) autoCreateExternalUser(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest) { func (l *Login) autoCreateExternalUser(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest) {
if len(authReq.LinkingUsers) == 0 { if len(authReq.LinkingUsers) == 0 {
l.renderError(w, r, authReq, errors.ThrowPreconditionFailed(nil, "LOGIN-asfg3", "Errors.ExternalIDP.NoExternalUserData")) l.renderError(w, r, authReq, zerrors.ThrowPreconditionFailed(nil, "LOGIN-asfg3", "Errors.ExternalIDP.NoExternalUserData"))
return return
} }
@ -613,7 +613,7 @@ func (l *Login) handleExternalNotFoundOptionCheck(w http.ResponseWriter, r *http
// if the user selects the linking button // if the user selects the linking button
if data.Link { if data.Link {
if !idpTemplate.IsLinkingAllowed { if !idpTemplate.IsLinkingAllowed {
l.renderExternalNotFoundOption(w, r, authReq, nil, nil, nil, errors.ThrowPreconditionFailed(nil, "LOGIN-AS3ff", "Errors.ExternalIDP.LinkingNotAllowed")) l.renderExternalNotFoundOption(w, r, authReq, nil, nil, nil, zerrors.ThrowPreconditionFailed(nil, "LOGIN-AS3ff", "Errors.ExternalIDP.LinkingNotAllowed"))
return return
} }
l.renderLogin(w, r, authReq, nil) l.renderLogin(w, r, authReq, nil)
@ -621,7 +621,7 @@ func (l *Login) handleExternalNotFoundOptionCheck(w http.ResponseWriter, r *http
} }
// if the user selects the creation button // if the user selects the creation button
if !idpTemplate.IsCreationAllowed { if !idpTemplate.IsCreationAllowed {
l.renderExternalNotFoundOption(w, r, authReq, nil, nil, nil, errors.ThrowPreconditionFailed(nil, "LOGIN-dsfd3", "Errors.ExternalIDP.CreationNotAllowed")) l.renderExternalNotFoundOption(w, r, authReq, nil, nil, nil, zerrors.ThrowPreconditionFailed(nil, "LOGIN-dsfd3", "Errors.ExternalIDP.CreationNotAllowed"))
return return
} }
linkingUser := mapExternalNotFoundOptionFormDataToLoginUser(data) linkingUser := mapExternalNotFoundOptionFormDataToLoginUser(data)
@ -682,7 +682,7 @@ func (l *Login) updateExternalUser(ctx context.Context, authReq *domain.AuthRequ
return err return err
} }
if user.Human == nil { if user.Human == nil {
return errors.ThrowPreconditionFailed(nil, "LOGIN-WLTce", "Errors.User.NotHuman") return zerrors.ThrowPreconditionFailed(nil, "LOGIN-WLTce", "Errors.User.NotHuman")
} }
err = l.updateExternalUserEmail(ctx, user, externalUser) err = l.updateExternalUserEmail(ctx, user, externalUser)
logging.WithFields("authReq", authReq.ID, "user", authReq.UserID).OnError(err).Error("unable to update email") logging.WithFields("authReq", authReq.ID, "user", authReq.UserID).OnError(err).Error("unable to update email")

View File

@ -6,7 +6,7 @@ import (
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware" http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -64,7 +64,7 @@ func (l *Login) handleInitPasswordCheck(w http.ResponseWriter, r *http.Request)
func (l *Login) checkPWCode(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, data *initPasswordFormData) { func (l *Login) checkPWCode(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, data *initPasswordFormData) {
if data.Password != data.PasswordConfirm { if data.Password != data.PasswordConfirm {
err := errors.ThrowInvalidArgument(nil, "VIEW-KaGue", "Errors.User.Password.ConfirmationWrong") err := zerrors.ThrowInvalidArgument(nil, "VIEW-KaGue", "Errors.User.Password.ConfirmationWrong")
l.renderInitPassword(w, r, authReq, data.UserID, data.Code, err) l.renderInitPassword(w, r, authReq, data.UserID, data.Code, err)
return return
} }
@ -83,7 +83,7 @@ func (l *Login) checkPWCode(w http.ResponseWriter, r *http.Request, authReq *dom
func (l *Login) resendPasswordSet(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest) { func (l *Login) resendPasswordSet(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest) {
if authReq == nil { if authReq == nil {
l.renderError(w, r, nil, errors.ThrowInternal(nil, "LOGIN-8sn7s", "Errors.AuthRequest.NotFound")) l.renderError(w, r, nil, zerrors.ThrowInternal(nil, "LOGIN-8sn7s", "Errors.AuthRequest.NotFound"))
return return
} }
userOrg := login userOrg := login

View File

@ -6,7 +6,7 @@ import (
"strconv" "strconv"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -72,7 +72,7 @@ func (l *Login) handleInitUserCheck(w http.ResponseWriter, r *http.Request) {
func (l *Login) checkUserInitCode(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, data *initUserFormData, err error) { func (l *Login) checkUserInitCode(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, data *initUserFormData, err error) {
if data.Password != data.PasswordConfirm { if data.Password != data.PasswordConfirm {
err := caos_errs.ThrowInvalidArgument(nil, "VIEW-fsdfd", "Errors.User.Password.ConfirmationWrong") err := zerrors.ThrowInvalidArgument(nil, "VIEW-fsdfd", "Errors.User.Password.ConfirmationWrong")
l.renderInitUser(w, r, authReq, data.UserID, data.LoginName, data.Code, data.PasswordSet, err) l.renderInitUser(w, r, authReq, data.UserID, data.LoginName, data.Code, data.PasswordSet, err)
return return
} }

View File

@ -13,9 +13,9 @@ import (
http_util "github.com/zitadel/zitadel/internal/api/http" http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/idp/providers/jwt" "github.com/zitadel/zitadel/internal/idp/providers/jwt"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type jwtRequest struct { type jwtRequest struct {
@ -31,7 +31,7 @@ func (l *Login) handleJWTRequest(w http.ResponseWriter, r *http.Request) {
return return
} }
if data.AuthRequestID == "" || data.UserAgentID == "" { if data.AuthRequestID == "" || data.UserAgentID == "" {
l.renderError(w, r, nil, errors.ThrowInvalidArgument(nil, "LOGIN-adfzz", "Errors.AuthRequest.MissingParameters")) l.renderError(w, r, nil, zerrors.ThrowInvalidArgument(nil, "LOGIN-adfzz", "Errors.AuthRequest.MissingParameters"))
return return
} }
id, err := base64.RawURLEncoding.DecodeString(data.UserAgentID) id, err := base64.RawURLEncoding.DecodeString(data.UserAgentID)
@ -158,7 +158,7 @@ func getToken(r *http.Request, headerName string) (string, error) {
} }
auth := r.Header.Get(headerName) auth := r.Header.Get(headerName)
if auth == "" { if auth == "" {
return "", errors.ThrowInvalidArgument(nil, "LOGIN-adh42", "Errors.AuthRequest.TokenNotFound") return "", zerrors.ThrowInvalidArgument(nil, "LOGIN-adh42", "Errors.AuthRequest.TokenNotFound")
} }
return strings.TrimPrefix(auth, oidc.PrefixBearer), nil return strings.TrimPrefix(auth, oidc.PrefixBearer), nil
} }

View File

@ -7,7 +7,7 @@ import (
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware" http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -77,7 +77,7 @@ func (l *Login) handleLoginNameCheck(w http.ResponseWriter, r *http.Request) {
return return
} }
if authReq == nil { if authReq == nil {
l.renderLogin(w, r, nil, errors.ThrowInvalidArgument(nil, "LOGIN-adrg3", "Errors.AuthRequest.NotFound")) l.renderLogin(w, r, nil, zerrors.ThrowInvalidArgument(nil, "LOGIN-adrg3", "Errors.AuthRequest.NotFound"))
return return
} }
userAgentID, _ := http_mw.UserAgentIDFromCtx(r.Context()) userAgentID, _ := http_mw.UserAgentIDFromCtx(r.Context())

View File

@ -5,7 +5,7 @@ import (
"net/http" "net/http"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -73,6 +73,6 @@ func (l *Login) authRequestCallback(ctx context.Context, authReq *domain.AuthReq
case *domain.AuthRequestDevice: case *domain.AuthRequestDevice:
return l.deviceAuthCallbackURL(authReq.ID), nil return l.deviceAuthCallbackURL(authReq.ID), nil
default: default:
return "", caos_errs.ThrowInternal(nil, "LOGIN-rhjQF", "Errors.AuthRequest.RequestTypeNotSupported") return "", zerrors.ThrowInternal(nil, "LOGIN-rhjQF", "Errors.AuthRequest.RequestTypeNotSupported")
} }
} }

View File

@ -4,8 +4,7 @@ import (
"net/http" "net/http"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/zerrors"
caos_errs "github.com/zitadel/zitadel/internal/errors"
) )
const ( const (
@ -61,7 +60,7 @@ func (l *Login) renderMFAPrompt(w http.ResponseWriter, r *http.Request, authReq
} }
if mfaPromptData == nil { if mfaPromptData == nil {
l.renderError(w, r, authReq, caos_errs.ThrowPreconditionFailed(nil, "APP-XU0tj", "Errors.User.MFA.NoProviders")) l.renderError(w, r, authReq, zerrors.ThrowPreconditionFailed(nil, "APP-XU0tj", "Errors.User.MFA.NoProviders"))
return return
} }
@ -93,7 +92,7 @@ func (l *Login) handleMFACreation(w http.ResponseWriter, r *http.Request, authRe
l.renderRegisterU2F(w, r, authReq, nil) l.renderRegisterU2F(w, r, authReq, nil)
return return
} }
l.renderError(w, r, authReq, caos_errs.ThrowPreconditionFailed(nil, "APP-Or3HO", "Errors.User.MFA.NoProviders")) l.renderError(w, r, authReq, zerrors.ThrowPreconditionFailed(nil, "APP-Or3HO", "Errors.User.MFA.NoProviders"))
} }
func (l *Login) handleTOTPCreation(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, data *mfaVerifyData) { func (l *Login) handleTOTPCreation(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, data *mfaVerifyData) {

View File

@ -4,7 +4,7 @@ import (
"net/http" "net/http"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -19,7 +19,7 @@ func (l *Login) handlePasswordReset(w http.ResponseWriter, r *http.Request) {
} }
user, err := l.query.GetUserByLoginName(setContext(r.Context(), authReq.UserOrgID), true, authReq.LoginName) user, err := l.query.GetUserByLoginName(setContext(r.Context(), authReq.UserOrgID), true, authReq.LoginName)
if err != nil { if err != nil {
if authReq.LoginPolicy.IgnoreUnknownUsernames && errors.IsNotFound(err) { if authReq.LoginPolicy.IgnoreUnknownUsernames && zerrors.IsNotFound(err) {
err = nil err = nil
} }
l.renderPasswordResetDone(w, r, authReq, err) l.renderPasswordResetDone(w, r, authReq, err)
@ -27,7 +27,7 @@ func (l *Login) handlePasswordReset(w http.ResponseWriter, r *http.Request) {
} }
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 { if err != nil {
if authReq.LoginPolicy.IgnoreUnknownUsernames && errors.IsNotFound(err) { if authReq.LoginPolicy.IgnoreUnknownUsernames && zerrors.IsNotFound(err) {
err = nil err = nil
} }
l.renderPasswordResetDone(w, r, authReq, err) l.renderPasswordResetDone(w, r, authReq, err)

View File

@ -8,7 +8,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware" http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -57,7 +57,7 @@ func (l *Login) handleRegisterCheck(w http.ResponseWriter, r *http.Request) {
return return
} }
if data.Password != data.Password2 { if data.Password != data.Password2 {
err := caos_errs.ThrowInvalidArgument(nil, "VIEW-KaGue", "Errors.User.Password.ConfirmationWrong") err := zerrors.ThrowInvalidArgument(nil, "VIEW-KaGue", "Errors.User.Password.ConfirmationWrong")
l.renderRegister(w, r, authRequest, data, err) l.renderRegister(w, r, authRequest, data, err)
return return
} }

View File

@ -6,7 +6,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors" "github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -73,7 +73,7 @@ func (l *Login) handleRegisterOrgCheck(w http.ResponseWriter, r *http.Request) {
return return
} }
if data.Password != data.Password2 { if data.Password != data.Password2 {
err := caos_errs.ThrowInvalidArgument(nil, "VIEW-KaGue", "Errors.User.Password.ConfirmationWrong") err := zerrors.ThrowInvalidArgument(nil, "VIEW-KaGue", "Errors.User.Password.ConfirmationWrong")
l.renderRegisterOrg(w, r, authRequest, data, err) l.renderRegisterOrg(w, r, authRequest, data, err)
return return
} }

View File

@ -16,12 +16,12 @@ import (
"github.com/zitadel/zitadel/internal/api/authz" "github.com/zitadel/zitadel/internal/api/authz"
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware" http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
caos_errs "github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/i18n" "github.com/zitadel/zitadel/internal/i18n"
"github.com/zitadel/zitadel/internal/notification/templates" "github.com/zitadel/zitadel/internal/notification/templates"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/renderer" "github.com/zitadel/zitadel/internal/renderer"
"github.com/zitadel/zitadel/internal/static" "github.com/zitadel/zitadel/internal/static"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const ( const (
@ -247,7 +247,7 @@ func CreateRenderer(pathPrefix string, staticStorage static.Storage, cookieName
func (l *Login) renderNextStep(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest) { func (l *Login) renderNextStep(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest) {
if authReq == nil { if authReq == nil {
l.renderInternalError(w, r, nil, caos_errs.ThrowInvalidArgument(nil, "LOGIN-Df3f2", "Errors.AuthRequest.NotFound")) l.renderInternalError(w, r, nil, zerrors.ThrowInvalidArgument(nil, "LOGIN-Df3f2", "Errors.AuthRequest.NotFound"))
return return
} }
authReq, err := l.authRepo.AuthRequestByID(r.Context(), authReq.ID, authReq.AgentID) authReq, err := l.authRepo.AuthRequestByID(r.Context(), authReq.ID, authReq.AgentID)
@ -256,7 +256,7 @@ func (l *Login) renderNextStep(w http.ResponseWriter, r *http.Request, authReq *
return return
} }
if len(authReq.PossibleSteps) == 0 { if len(authReq.PossibleSteps) == 0 {
l.renderInternalError(w, r, authReq, caos_errs.ThrowInternal(nil, "APP-9sdp4", "no possible steps")) l.renderInternalError(w, r, authReq, zerrors.ThrowInternal(nil, "APP-9sdp4", "no possible steps"))
return return
} }
l.chooseNextStep(w, r, authReq, 0, nil) l.chooseNextStep(w, r, authReq, 0, nil)
@ -268,7 +268,7 @@ func (l *Login) renderError(w http.ResponseWriter, r *http.Request, authReq *dom
return return
} }
if authReq == nil || len(authReq.PossibleSteps) == 0 { if authReq == nil || len(authReq.PossibleSteps) == 0 {
l.renderInternalError(w, r, authReq, caos_errs.ThrowInternal(err, "APP-OVOiT", "no possible steps")) l.renderInternalError(w, r, authReq, zerrors.ThrowInternal(err, "APP-OVOiT", "no possible steps"))
return return
} }
l.chooseNextStep(w, r, authReq, 0, err) l.chooseNextStep(w, r, authReq, 0, err)
@ -323,11 +323,11 @@ func (l *Login) chooseNextStep(w http.ResponseWriter, r *http.Request, authReq *
case *domain.ExternalLoginStep: case *domain.ExternalLoginStep:
l.handleExternalLoginStep(w, r, authReq, step.SelectedIDPConfigID) l.handleExternalLoginStep(w, r, authReq, step.SelectedIDPConfigID)
case *domain.GrantRequiredStep: case *domain.GrantRequiredStep:
l.renderInternalError(w, r, authReq, caos_errs.ThrowPreconditionFailed(nil, "APP-asb43", "Errors.User.GrantRequired")) l.renderInternalError(w, r, authReq, zerrors.ThrowPreconditionFailed(nil, "APP-asb43", "Errors.User.GrantRequired"))
case *domain.ProjectRequiredStep: case *domain.ProjectRequiredStep:
l.renderInternalError(w, r, authReq, caos_errs.ThrowPreconditionFailed(nil, "APP-m92d", "Errors.User.ProjectRequired")) l.renderInternalError(w, r, authReq, zerrors.ThrowPreconditionFailed(nil, "APP-m92d", "Errors.User.ProjectRequired"))
default: default:
l.renderInternalError(w, r, authReq, caos_errs.ThrowInternal(nil, "APP-ds3QF", "step no possible")) l.renderInternalError(w, r, authReq, zerrors.ThrowInternal(nil, "APP-ds3QF", "step no possible"))
} }
} }
@ -470,7 +470,7 @@ func (l *Login) setLinksOnBaseData(baseData baseData, privacyPolicy *domain.Priv
} }
func (l *Login) getErrorMessage(r *http.Request, err error) (errID, errMsg string) { func (l *Login) getErrorMessage(r *http.Request, err error) (errID, errMsg string) {
caosErr := new(caos_errs.CaosError) caosErr := new(zerrors.ZitadelError)
if errors.As(err, &caosErr) { if errors.As(err, &caosErr) {
localized := l.renderer.LocalizeFromRequest(l.getTranslator(r.Context(), nil), r, caosErr.Message, nil) localized := l.renderer.LocalizeFromRequest(l.getTranslator(r.Context(), nil), r, caosErr.Message, nil)
return caosErr.ID, localized return caosErr.ID, localized

View File

@ -14,7 +14,6 @@ import (
"github.com/zitadel/zitadel/internal/command" "github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
es_models "github.com/zitadel/zitadel/internal/eventstore/v1/models" es_models "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/id" "github.com/zitadel/zitadel/internal/id"
@ -23,6 +22,7 @@ import (
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
user_model "github.com/zitadel/zitadel/internal/user/model" user_model "github.com/zitadel/zitadel/internal/user/model"
user_view_model "github.com/zitadel/zitadel/internal/user/repository/view/model" user_view_model "github.com/zitadel/zitadel/internal/user/repository/view/model"
"github.com/zitadel/zitadel/internal/zerrors"
) )
const unknownUserID = "UNKNOWN" const unknownUserID = "UNKNOWN"
@ -262,7 +262,7 @@ func (repo *AuthRequestRepo) CheckExternalUserLogin(ctx context.Context, authReq
return err return err
} }
err = repo.checkExternalUserLogin(ctx, request, externalUser.IDPConfigID, externalUser.ExternalUserID) err = repo.checkExternalUserLogin(ctx, request, externalUser.IDPConfigID, externalUser.ExternalUserID)
if errors.IsNotFound(err) { if zerrors.IsNotFound(err) {
// clear potential user information (e.g. when username was entered but another external user was returned) // clear potential user information (e.g. when username was entered but another external user was returned)
request.SetUserInfo("", "", "", "", "", request.UserOrgID) request.SetUserInfo("", "", "", "", "", request.UserOrgID)
// in case the check was done with an ID, that was retrieved by a session that allows migration, // in case the check was done with an ID, that was retrieved by a session that allows migration,
@ -328,7 +328,7 @@ func (repo *AuthRequestRepo) SelectUser(ctx context.Context, id, userID, userAge
return err return err
} }
if request.RequestedOrgID != "" && request.RequestedOrgID != user.ResourceOwner { if request.RequestedOrgID != "" && request.RequestedOrgID != user.ResourceOwner {
return errors.ThrowPreconditionFailed(nil, "EVENT-fJe2a", "Errors.User.NotAllowedOrg") return zerrors.ThrowPreconditionFailed(nil, "EVENT-fJe2a", "Errors.User.NotAllowedOrg")
} }
username := user.UserName username := user.UserName
if request.RequestedOrgID == "" { if request.RequestedOrgID == "" {
@ -344,7 +344,7 @@ func (repo *AuthRequestRepo) VerifyPassword(ctx context.Context, authReqID, user
request, err := repo.getAuthRequestEnsureUser(ctx, authReqID, userAgentID, userID) request, err := repo.getAuthRequestEnsureUser(ctx, authReqID, userAgentID, userID)
if err != nil { if err != nil {
if isIgnoreUserNotFoundError(err, request) { if isIgnoreUserNotFoundError(err, request) {
return errors.ThrowInvalidArgument(nil, "EVENT-SDe2f", "Errors.User.UsernameOrPassword.Invalid") return zerrors.ThrowInvalidArgument(nil, "EVENT-SDe2f", "Errors.User.UsernameOrPassword.Invalid")
} }
return err return err
} }
@ -354,17 +354,17 @@ func (repo *AuthRequestRepo) VerifyPassword(ctx context.Context, authReqID, user
} }
err = repo.Command.HumanCheckPassword(ctx, resourceOwner, userID, password, request.WithCurrentInfo(info), lockoutPolicyToDomain(policy)) err = repo.Command.HumanCheckPassword(ctx, resourceOwner, userID, password, request.WithCurrentInfo(info), lockoutPolicyToDomain(policy))
if isIgnoreUserInvalidPasswordError(err, request) { if isIgnoreUserInvalidPasswordError(err, request) {
return errors.ThrowInvalidArgument(nil, "EVENT-Jsf32", "Errors.User.UsernameOrPassword.Invalid") return zerrors.ThrowInvalidArgument(nil, "EVENT-Jsf32", "Errors.User.UsernameOrPassword.Invalid")
} }
return err return err
} }
func isIgnoreUserNotFoundError(err error, request *domain.AuthRequest) bool { func isIgnoreUserNotFoundError(err error, request *domain.AuthRequest) bool {
return request != nil && request.LoginPolicy != nil && request.LoginPolicy.IgnoreUnknownUsernames && errors.IsNotFound(err) && errors.Contains(err, "Errors.User.NotFound") return request != nil && request.LoginPolicy != nil && request.LoginPolicy.IgnoreUnknownUsernames && zerrors.IsNotFound(err) && zerrors.Contains(err, "Errors.User.NotFound")
} }
func isIgnoreUserInvalidPasswordError(err error, request *domain.AuthRequest) bool { func isIgnoreUserInvalidPasswordError(err error, request *domain.AuthRequest) bool {
return request != nil && request.LoginPolicy != nil && request.LoginPolicy.IgnoreUnknownUsernames && errors.IsErrorInvalidArgument(err) && errors.Contains(err, "Errors.User.Password.Invalid") return request != nil && request.LoginPolicy != nil && request.LoginPolicy.IgnoreUnknownUsernames && zerrors.IsErrorInvalidArgument(err) && zerrors.Contains(err, "Errors.User.Password.Invalid")
} }
func lockoutPolicyToDomain(policy *query.LockoutPolicy) *domain.LockoutPolicy { func lockoutPolicyToDomain(policy *query.LockoutPolicy) *domain.LockoutPolicy {
@ -613,7 +613,7 @@ func (repo *AuthRequestRepo) getAuthRequestEnsureUser(ctx context.Context, authR
} }
} }
if request.UserID != userID { if request.UserID != userID {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-GBH32", "Errors.User.NotMatchingUserID") return nil, zerrors.ThrowPreconditionFailed(nil, "EVENT-GBH32", "Errors.User.NotMatchingUserID")
} }
_, err = activeUserByID(ctx, repo.UserViewProvider, repo.UserEventProvider, repo.OrgViewProvider, repo.LockoutPolicyViewProvider, request.UserID, false) _, err = activeUserByID(ctx, repo.UserViewProvider, repo.UserEventProvider, repo.OrgViewProvider, repo.LockoutPolicyViewProvider, request.UserID, false)
if err != nil { if err != nil {
@ -631,7 +631,7 @@ func (repo *AuthRequestRepo) getAuthRequest(ctx context.Context, id, userAgentID
return nil, err return nil, err
} }
if request.AgentID != userAgentID { if request.AgentID != userAgentID {
return nil, errors.ThrowPermissionDenied(nil, "EVENT-adk13", "Errors.AuthRequest.UserAgentNotCorresponding") return nil, zerrors.ThrowPermissionDenied(nil, "EVENT-adk13", "Errors.AuthRequest.UserAgentNotCorresponding")
} }
err = repo.fillPolicies(ctx, request) err = repo.fillPolicies(ctx, request)
if err != nil { if err != nil {
@ -743,7 +743,7 @@ func (repo *AuthRequestRepo) checkLoginName(ctx context.Context, request *domain
user, err = repo.checkLoginNameInput(ctx, request, preferredLoginName) user, err = repo.checkLoginNameInput(ctx, request, preferredLoginName)
} }
// return any error apart from not found ones directly // return any error apart from not found ones directly
if err != nil && !errors.IsNotFound(err) { if err != nil && !zerrors.IsNotFound(err) {
return err return err
} }
// if there's an active (human) user, let's use it // if there's an active (human) user, let's use it
@ -759,11 +759,11 @@ func (repo *AuthRequestRepo) checkLoginName(ctx context.Context, request *domain
} }
// let's once again check if the user was just inactive // let's once again check if the user was just inactive
if user != nil && user.State == int32(domain.UserStateInactive) { if user != nil && user.State == int32(domain.UserStateInactive) {
return errors.ThrowPreconditionFailed(nil, "AUTH-2n8fs", "Errors.User.Inactive") return zerrors.ThrowPreconditionFailed(nil, "AUTH-2n8fs", "Errors.User.Inactive")
} }
// or locked // or locked
if user != nil && user.State == int32(domain.UserStateLocked) { if user != nil && user.State == int32(domain.UserStateLocked) {
return errors.ThrowPreconditionFailed(nil, "AUTH-SF3gb", "Errors.User.Locked") return zerrors.ThrowPreconditionFailed(nil, "AUTH-SF3gb", "Errors.User.Locked")
} }
// let's just check if unknown usernames are ignored // let's just check if unknown usernames are ignored
if request.LoginPolicy != nil && request.LoginPolicy.IgnoreUnknownUsernames { if request.LoginPolicy != nil && request.LoginPolicy.IgnoreUnknownUsernames {
@ -780,11 +780,11 @@ func (repo *AuthRequestRepo) checkLoginName(ctx context.Context, request *domain
} }
// let's check if it was a machine user // let's check if it was a machine user
if !user.MachineView.IsZero() { if !user.MachineView.IsZero() {
return errors.ThrowPreconditionFailed(nil, "AUTH-DGV4g", "Errors.User.NotHuman") return zerrors.ThrowPreconditionFailed(nil, "AUTH-DGV4g", "Errors.User.NotHuman")
} }
// everything should be handled by now // everything should be handled by now
logging.WithFields("authRequest", request.ID, "loginName", loginName).Error("unhandled state for checkLoginName") logging.WithFields("authRequest", request.ID, "loginName", loginName).Error("unhandled state for checkLoginName")
return errors.ThrowInternal(nil, "AUTH-asf3df", "Errors.Internal") return zerrors.ThrowInternal(nil, "AUTH-asf3df", "Errors.Internal")
} }
func (repo *AuthRequestRepo) checkDomainDiscovery(ctx context.Context, request *domain.AuthRequest, loginName string) (bool, error) { func (repo *AuthRequestRepo) checkDomainDiscovery(ctx context.Context, request *domain.AuthRequest, loginName string) (bool, error) {
@ -889,12 +889,12 @@ func (repo *AuthRequestRepo) checkLoginPolicyWithResourceOwner(ctx context.Conte
return err return err
} }
if len(request.LinkingUsers) != 0 && !loginPolicy.AllowExternalIDPs { if len(request.LinkingUsers) != 0 && !loginPolicy.AllowExternalIDPs {
return errors.ThrowInvalidArgument(nil, "LOGIN-s9sio", "Errors.User.NotAllowedToLink") return zerrors.ThrowInvalidArgument(nil, "LOGIN-s9sio", "Errors.User.NotAllowedToLink")
} }
if len(request.LinkingUsers) != 0 { if len(request.LinkingUsers) != 0 {
exists := linkingIDPConfigExistingInAllowedIDPs(request.LinkingUsers, idpProviders) exists := linkingIDPConfigExistingInAllowedIDPs(request.LinkingUsers, idpProviders)
if !exists { if !exists {
return errors.ThrowInvalidArgument(nil, "LOGIN-Dj89o", "Errors.User.NotAllowedToLink") return zerrors.ThrowInvalidArgument(nil, "LOGIN-Dj89o", "Errors.User.NotAllowedToLink")
} }
} }
request.LoginPolicy = queryLoginPolicyToDomain(loginPolicy) request.LoginPolicy = queryLoginPolicyToDomain(loginPolicy)
@ -941,7 +941,7 @@ func (repo *AuthRequestRepo) checkSelectedExternalIDP(request *domain.AuthReques
return nil return nil
} }
} }
return errors.ThrowNotFound(nil, "LOGIN-Nsm8r", "Errors.User.ExternalIDP.NotAllowed") return zerrors.ThrowNotFound(nil, "LOGIN-Nsm8r", "Errors.User.ExternalIDP.NotAllowed")
} }
func (repo *AuthRequestRepo) checkExternalUserLogin(ctx context.Context, request *domain.AuthRequest, idpConfigID, externalUserID string) (err error) { func (repo *AuthRequestRepo) checkExternalUserLogin(ctx context.Context, request *domain.AuthRequest, idpConfigID, externalUserID string) (err error) {
@ -968,7 +968,7 @@ func (repo *AuthRequestRepo) checkExternalUserLogin(ctx context.Context, request
return err return err
} }
if len(links.Links) != 1 { if len(links.Links) != 1 {
return errors.ThrowNotFound(nil, "AUTH-Sf8sd", "Errors.ExternalIDP.NotFound") return zerrors.ThrowNotFound(nil, "AUTH-Sf8sd", "Errors.ExternalIDP.NotFound")
} }
user, err := activeUserByID(ctx, repo.UserViewProvider, repo.UserEventProvider, repo.OrgViewProvider, repo.LockoutPolicyViewProvider, links.Links[0].UserID, false) user, err := activeUserByID(ctx, repo.UserViewProvider, repo.UserEventProvider, repo.OrgViewProvider, repo.LockoutPolicyViewProvider, links.Links[0].UserID, false)
if err != nil { if err != nil {
@ -988,7 +988,7 @@ func (repo *AuthRequestRepo) nextSteps(ctx context.Context, request *domain.Auth
defer func() { span.EndWithError(err) }() defer func() { span.EndWithError(err) }()
if request == nil { if request == nil {
return nil, errors.ThrowInvalidArgument(nil, "EVENT-ds27a", "Errors.Internal") return nil, zerrors.ThrowInvalidArgument(nil, "EVENT-ds27a", "Errors.Internal")
} }
steps = make([]domain.NextStep, 0) steps = make([]domain.NextStep, 0)
if !checkLoggedIn && domain.IsPrompt(request.Prompt, domain.PromptNone) { if !checkLoggedIn && domain.IsPrompt(request.Prompt, domain.PromptNone) {
@ -1216,7 +1216,7 @@ func (repo *AuthRequestRepo) mfaChecked(userSession *user_model.UserSessionView,
if promptRequired || !repo.mfaSkippedOrSetUp(user, request) { if promptRequired || !repo.mfaSkippedOrSetUp(user, request) {
types := user.MFATypesSetupPossible(mfaLevel, request.LoginPolicy) types := user.MFATypesSetupPossible(mfaLevel, request.LoginPolicy)
if promptRequired && len(types) == 0 { if promptRequired && len(types) == 0 {
return nil, false, errors.ThrowPreconditionFailed(nil, "LOGIN-5Hm8s", "Errors.Login.LoginPolicy.MFA.ForceAndNotConfigured") return nil, false, zerrors.ThrowPreconditionFailed(nil, "LOGIN-5Hm8s", "Errors.Login.LoginPolicy.MFA.ForceAndNotConfigured")
} }
if len(types) == 0 { if len(types) == 0 {
return nil, true, nil return nil, true, nil
@ -1265,7 +1265,7 @@ func (repo *AuthRequestRepo) mfaSkippedOrSetUp(user *user_model.UserView, reques
func (repo *AuthRequestRepo) GetPrivacyPolicy(ctx context.Context, orgID string) (*domain.PrivacyPolicy, error) { func (repo *AuthRequestRepo) GetPrivacyPolicy(ctx context.Context, orgID string) (*domain.PrivacyPolicy, error) {
policy, err := repo.PrivacyPolicyProvider.PrivacyPolicyByOrg(ctx, false, orgID, false) policy, err := repo.PrivacyPolicyProvider.PrivacyPolicyByOrg(ctx, false, orgID, false)
if errors.IsNotFound(err) { if zerrors.IsNotFound(err) {
return new(domain.PrivacyPolicy), nil return new(domain.PrivacyPolicy), nil
} }
if err != nil { if err != nil {
@ -1460,7 +1460,7 @@ func userSessionByIDs(ctx context.Context, provider userSessionViewProvider, eve
instanceID := authz.GetInstance(ctx).InstanceID() instanceID := authz.GetInstance(ctx).InstanceID()
session, err := provider.UserSessionByIDs(agentID, user.ID, instanceID) session, err := provider.UserSessionByIDs(agentID, user.ID, instanceID)
if err != nil { if err != nil {
if !errors.IsNotFound(err) { if !zerrors.IsNotFound(err) {
return nil, err return nil, err
} }
sequence, err := provider.GetLatestUserSessionSequence(ctx, instanceID) sequence, err := provider.GetLatestUserSessionSequence(ctx, instanceID)
@ -1506,7 +1506,7 @@ func userSessionByIDs(ctx context.Context, provider userSessionViewProvider, eve
continue continue
} }
case user_repo.UserRemovedType: case user_repo.UserRemovedType:
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-dG2fe", "Errors.User.NotActive") return nil, zerrors.ThrowPreconditionFailed(nil, "EVENT-dG2fe", "Errors.User.NotActive")
} }
err := sessionCopy.AppendEvent(event) err := sessionCopy.AppendEvent(event)
logging.WithFields("traceID", tracing.TraceIDFromCtx(ctx)).OnError(err).Warn("error appending event") logging.WithFields("traceID", tracing.TraceIDFromCtx(ctx)).OnError(err).Warn("error appending event")
@ -1518,7 +1518,7 @@ func activeUserByID(ctx context.Context, userViewProvider userViewProvider, user
// PLANNED: Check LockoutPolicy // PLANNED: Check LockoutPolicy
user, err = userByID(ctx, userViewProvider, userEventProvider, userID) user, err = userByID(ctx, userViewProvider, userEventProvider, userID)
if err != nil { if err != nil {
if ignoreUnknownUsernames && errors.IsNotFound(err) { if ignoreUnknownUsernames && zerrors.IsNotFound(err) {
return &user_model.UserView{ return &user_model.UserView{
ID: userID, ID: userID,
HumanView: &user_model.HumanView{}, HumanView: &user_model.HumanView{},
@ -1528,20 +1528,20 @@ func activeUserByID(ctx context.Context, userViewProvider userViewProvider, user
} }
if user.HumanView == nil { if user.HumanView == nil {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-Lm69x", "Errors.User.NotHuman") return nil, zerrors.ThrowPreconditionFailed(nil, "EVENT-Lm69x", "Errors.User.NotHuman")
} }
if user.State == user_model.UserStateLocked || user.State == user_model.UserStateSuspend { if user.State == user_model.UserStateLocked || user.State == user_model.UserStateSuspend {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-FJ262", "Errors.User.Locked") return nil, zerrors.ThrowPreconditionFailed(nil, "EVENT-FJ262", "Errors.User.Locked")
} }
if !(user.State == user_model.UserStateActive || user.State == user_model.UserStateInitial) { if !(user.State == user_model.UserStateActive || user.State == user_model.UserStateInitial) {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-FJ262", "Errors.User.NotActive") return nil, zerrors.ThrowPreconditionFailed(nil, "EVENT-FJ262", "Errors.User.NotActive")
} }
org, err := queries.OrgByID(ctx, false, user.ResourceOwner) org, err := queries.OrgByID(ctx, false, user.ResourceOwner)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if org.State != domain.OrgStateActive { if org.State != domain.OrgStateActive {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-Zws3s", "Errors.User.NotActive") return nil, zerrors.ThrowPreconditionFailed(nil, "EVENT-Zws3s", "Errors.User.NotActive")
} }
return user, nil return user, nil
} }
@ -1551,7 +1551,7 @@ func userByID(ctx context.Context, viewProvider userViewProvider, eventProvider
defer func() { span.EndWithError(err) }() defer func() { span.EndWithError(err) }()
user, viewErr := viewProvider.UserByID(userID, authz.GetInstance(ctx).InstanceID()) user, viewErr := viewProvider.UserByID(userID, authz.GetInstance(ctx).InstanceID())
if viewErr != nil && !errors.IsNotFound(viewErr) { if viewErr != nil && !zerrors.IsNotFound(viewErr) {
return nil, viewErr return nil, viewErr
} else if user == nil { } else if user == nil {
user = new(user_view_model.UserView) user = new(user_view_model.UserView)
@ -1574,7 +1574,7 @@ func userByID(ctx context.Context, viewProvider userViewProvider, eventProvider
} }
} }
if userCopy.State == int32(user_model.UserStateDeleted) { if userCopy.State == int32(user_model.UserStateDeleted) {
return nil, errors.ThrowNotFound(nil, "EVENT-3F9so", "Errors.User.NotFound") return nil, zerrors.ThrowNotFound(nil, "EVENT-3F9so", "Errors.User.NotFound")
} }
return user_view_model.UserToModel(&userCopy), nil return user_view_model.UserToModel(&userCopy), nil
} }
@ -1622,7 +1622,7 @@ func userGrantRequired(ctx context.Context, request *domain.AuthRequest, user *u
return false, err return false, err
} }
default: default:
return false, errors.ThrowPreconditionFailed(nil, "EVENT-dfrw2", "Errors.AuthRequest.RequestTypeNotSupported") return false, zerrors.ThrowPreconditionFailed(nil, "EVENT-dfrw2", "Errors.AuthRequest.RequestTypeNotSupported")
} }
if !project.ProjectRoleCheck { if !project.ProjectRoleCheck {
return false, nil return false, nil
@ -1643,7 +1643,7 @@ func projectRequired(ctx context.Context, request *domain.AuthRequest, projectPr
return false, err return false, err
} }
default: default:
return false, errors.ThrowPreconditionFailed(nil, "EVENT-ku4He", "Errors.AuthRequest.RequestTypeNotSupported") return false, zerrors.ThrowPreconditionFailed(nil, "EVENT-ku4He", "Errors.AuthRequest.RequestTypeNotSupported")
} }
// if the user and project are part of the same organisation we do not need to check if the project exists on that org // if the user and project are part of the same organisation we do not need to check if the project exists on that org
if !project.HasProjectCheck || project.ResourceOwner == request.UserOrgID { if !project.HasProjectCheck || project.ResourceOwner == request.UserOrgID {

View File

@ -14,7 +14,6 @@ import (
"github.com/zitadel/zitadel/internal/auth_request/repository/mock" "github.com/zitadel/zitadel/internal/auth_request/repository/mock"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
es_models "github.com/zitadel/zitadel/internal/eventstore/v1/models" es_models "github.com/zitadel/zitadel/internal/eventstore/v1/models"
"github.com/zitadel/zitadel/internal/query" "github.com/zitadel/zitadel/internal/query"
@ -22,6 +21,7 @@ import (
user_model "github.com/zitadel/zitadel/internal/user/model" user_model "github.com/zitadel/zitadel/internal/user/model"
user_es_model "github.com/zitadel/zitadel/internal/user/repository/eventsourcing/model" user_es_model "github.com/zitadel/zitadel/internal/user/repository/eventsourcing/model"
user_view_model "github.com/zitadel/zitadel/internal/user/repository/view/model" user_view_model "github.com/zitadel/zitadel/internal/user/repository/view/model"
"github.com/zitadel/zitadel/internal/zerrors"
) )
var ( var (
@ -31,7 +31,7 @@ var (
type mockViewNoUserSession struct{} type mockViewNoUserSession struct{}
func (m *mockViewNoUserSession) UserSessionByIDs(string, string, string) (*user_view_model.UserSessionView, error) { func (m *mockViewNoUserSession) UserSessionByIDs(string, string, string) (*user_view_model.UserSessionView, error) {
return nil, errors.ThrowNotFound(nil, "id", "user session not found") return nil, zerrors.ThrowNotFound(nil, "id", "user session not found")
} }
func (m *mockViewNoUserSession) UserSessionsByAgentID(string, string) ([]*user_view_model.UserSessionView, error) { func (m *mockViewNoUserSession) UserSessionsByAgentID(string, string) ([]*user_view_model.UserSessionView, error) {
@ -45,11 +45,11 @@ func (m *mockViewNoUserSession) GetLatestUserSessionSequence(ctx context.Context
type mockViewErrUserSession struct{} type mockViewErrUserSession struct{}
func (m *mockViewErrUserSession) UserSessionByIDs(string, string, string) (*user_view_model.UserSessionView, error) { func (m *mockViewErrUserSession) UserSessionByIDs(string, string, string) (*user_view_model.UserSessionView, error) {
return nil, errors.ThrowInternal(nil, "id", "internal error") return nil, zerrors.ThrowInternal(nil, "id", "internal error")
} }
func (m *mockViewErrUserSession) UserSessionsByAgentID(string, string) ([]*user_view_model.UserSessionView, error) { func (m *mockViewErrUserSession) UserSessionsByAgentID(string, string) ([]*user_view_model.UserSessionView, error) {
return nil, errors.ThrowInternal(nil, "id", "internal error") return nil, zerrors.ThrowInternal(nil, "id", "internal error")
} }
func (m *mockViewErrUserSession) GetLatestUserSessionSequence(ctx context.Context, instanceID string) (*query.CurrentState, error) { func (m *mockViewErrUserSession) GetLatestUserSessionSequence(ctx context.Context, instanceID string) (*query.CurrentState, error) {
@ -102,7 +102,7 @@ func (m *mockViewUserSession) GetLatestUserSessionSequence(ctx context.Context,
type mockViewNoUser struct{} type mockViewNoUser struct{}
func (m *mockViewNoUser) UserByID(string, string) (*user_view_model.UserView, error) { func (m *mockViewNoUser) UserByID(string, string) (*user_view_model.UserView, error) {
return nil, errors.ThrowNotFound(nil, "id", "user not found") return nil, zerrors.ThrowNotFound(nil, "id", "user not found")
} }
type mockEventUser struct { type mockEventUser struct {
@ -127,11 +127,11 @@ func (m *mockEventUser) BulkAddExternalIDPs(ctx context.Context, userID string,
type mockEventErrUser struct{} type mockEventErrUser struct{}
func (m *mockEventErrUser) UserEventsByID(ctx context.Context, id string, sequence uint64, types []eventstore.EventType) ([]eventstore.Event, error) { func (m *mockEventErrUser) UserEventsByID(ctx context.Context, id string, sequence uint64, types []eventstore.EventType) ([]eventstore.Event, error) {
return nil, errors.ThrowInternal(nil, "id", "internal error") return nil, zerrors.ThrowInternal(nil, "id", "internal error")
} }
func (m *mockEventErrUser) BulkAddExternalIDPs(ctx context.Context, userID string, externalIDPs []*user_model.ExternalIDP) error { func (m *mockEventErrUser) BulkAddExternalIDPs(ctx context.Context, userID string, externalIDPs []*user_model.ExternalIDP) error {
return errors.ThrowInternal(nil, "id", "internal error") return zerrors.ThrowInternal(nil, "id", "internal error")
} }
type mockViewUser struct { type mockViewUser struct {
@ -226,11 +226,11 @@ func (m *mockViewOrg) OrgByPrimaryDomain(context.Context, string) (*query.Org, e
type mockViewErrOrg struct{} type mockViewErrOrg struct{}
func (m *mockViewErrOrg) OrgByID(context.Context, bool, string) (*query.Org, error) { func (m *mockViewErrOrg) OrgByID(context.Context, bool, string) (*query.Org, error) {
return nil, errors.ThrowInternal(nil, "id", "internal error") return nil, zerrors.ThrowInternal(nil, "id", "internal error")
} }
func (m *mockViewErrOrg) OrgByPrimaryDomain(context.Context, string) (*query.Org, error) { func (m *mockViewErrOrg) OrgByPrimaryDomain(context.Context, string) (*query.Org, error) {
return nil, errors.ThrowInternal(nil, "id", "internal error") return nil, zerrors.ThrowInternal(nil, "id", "internal error")
} }
type mockUserGrants struct { type mockUserGrants struct {
@ -276,7 +276,7 @@ func (m *mockApp) AppByOIDCClientID(ctx context.Context, id string) (*query.App,
if m.app != nil { if m.app != nil {
return m.app, nil return m.app, nil
} }
return nil, errors.ThrowNotFound(nil, "ERROR", "error") return nil, zerrors.ThrowNotFound(nil, "ERROR", "error")
} }
type mockIDPUserLinks struct { type mockIDPUserLinks struct {
@ -321,7 +321,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
fields{}, fields{},
args{nil, false}, args{nil, false},
nil, nil,
errors.IsErrorInvalidArgument, zerrors.IsErrorInvalidArgument,
}, },
{ {
"prompt none and checkLoggedIn false, callback step", "prompt none and checkLoggedIn false, callback step",
@ -386,7 +386,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
}, },
args{&domain.AuthRequest{Prompt: []domain.Prompt{domain.PromptSelectAccount}}, false}, args{&domain.AuthRequest{Prompt: []domain.Prompt{domain.PromptSelectAccount}}, false},
nil, nil,
errors.IsInternal, zerrors.IsInternal,
}, },
{ {
"user not set, prompt select account, select account step", "user not set, prompt select account, select account step",
@ -666,7 +666,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
}, },
args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false}, args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false},
nil, nil,
errors.IsNotFound, zerrors.IsNotFound,
}, },
{ {
"user not active, precondition failed error", "user not active, precondition failed error",
@ -688,7 +688,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
}, },
args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false}, args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false},
nil, nil,
errors.IsPreconditionFailed, zerrors.IsPreconditionFailed,
}, },
{ {
"user locked, precondition failed error", "user locked, precondition failed error",
@ -709,7 +709,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
}, },
args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false}, args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false},
nil, nil,
errors.IsPreconditionFailed, zerrors.IsPreconditionFailed,
}, },
{ {
"org error, internal error", "org error, internal error",
@ -725,7 +725,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
}, },
args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false}, args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false},
nil, nil,
errors.IsInternal, zerrors.IsInternal,
}, },
{ {
"org not active, precondition failed error", "org not active, precondition failed error",
@ -741,7 +741,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
}, },
args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false}, args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false},
nil, nil,
errors.IsPreconditionFailed, zerrors.IsPreconditionFailed,
}, },
{ {
"usersession not found, new user session, password step", "usersession not found, new user session, password step",
@ -779,7 +779,7 @@ func TestAuthRequestRepo_nextSteps(t *testing.T) {
}, },
args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false}, args{&domain.AuthRequest{UserID: "UserID", LoginPolicy: &domain.LoginPolicy{}}, false},
nil, nil,
errors.IsInternal, zerrors.IsInternal,
}, },
{ {
"user not initialized, init user step", "user not initialized, init user step",
@ -1716,7 +1716,7 @@ func TestAuthRequestRepo_mfaChecked(t *testing.T) {
}, },
nil, nil,
false, false,
errors.IsPreconditionFailed, zerrors.IsPreconditionFailed,
}, },
{ {
"not set up, no mfas configured, no prompt and true", "not set up, no mfas configured, no prompt and true",
@ -2073,7 +2073,7 @@ func Test_userSessionByIDs(t *testing.T) {
user: &user_model.UserView{ID: "id"}, user: &user_model.UserView{ID: "id"},
}, },
nil, nil,
errors.IsInternal, zerrors.IsInternal,
}, },
{ {
"error user events, old view model state", "error user events, old view model state",
@ -2184,7 +2184,7 @@ func Test_userSessionByIDs(t *testing.T) {
}, },
}, },
nil, nil,
errors.IsPreconditionFailed, zerrors.IsPreconditionFailed,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
@ -2220,7 +2220,7 @@ func Test_userByID(t *testing.T) {
eventProvider: &mockEventUser{}, eventProvider: &mockEventUser{},
}, },
nil, nil,
errors.IsNotFound, zerrors.IsNotFound,
}, },
{ {
"error user events, old view model state", "error user events, old view model state",

View File

@ -10,12 +10,12 @@ import (
"github.com/zitadel/zitadel/internal/auth/repository/eventsourcing/view" "github.com/zitadel/zitadel/internal/auth/repository/eventsourcing/view"
"github.com/zitadel/zitadel/internal/crypto" "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain" "github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/errors"
"github.com/zitadel/zitadel/internal/eventstore" "github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/telemetry/tracing" "github.com/zitadel/zitadel/internal/telemetry/tracing"
usr_model "github.com/zitadel/zitadel/internal/user/model" usr_model "github.com/zitadel/zitadel/internal/user/model"
usr_view "github.com/zitadel/zitadel/internal/user/repository/view" usr_view "github.com/zitadel/zitadel/internal/user/repository/view"
"github.com/zitadel/zitadel/internal/user/repository/view/model" "github.com/zitadel/zitadel/internal/user/repository/view/model"
"github.com/zitadel/zitadel/internal/zerrors"
) )
type RefreshTokenRepo struct { type RefreshTokenRepo struct {
@ -35,7 +35,7 @@ func (r *RefreshTokenRepo) RefreshTokenByToken(ctx context.Context, refreshToken
return nil, err return nil, err
} }
if tokenView.Token != token { if tokenView.Token != token {
return nil, errors.ThrowNotFound(nil, "EVENT-5Bm9s", "Errors.User.RefreshToken.Invalid") return nil, zerrors.ThrowNotFound(nil, "EVENT-5Bm9s", "Errors.User.RefreshToken.Invalid")
} }
return tokenView, nil return tokenView, nil
} }
@ -43,10 +43,10 @@ func (r *RefreshTokenRepo) RefreshTokenByToken(ctx context.Context, refreshToken
func (r *RefreshTokenRepo) RefreshTokenByID(ctx context.Context, tokenID, userID string) (*usr_model.RefreshTokenView, error) { func (r *RefreshTokenRepo) RefreshTokenByID(ctx context.Context, tokenID, userID string) (*usr_model.RefreshTokenView, error) {
instanceID := authz.GetInstance(ctx).InstanceID() instanceID := authz.GetInstance(ctx).InstanceID()
tokenView, viewErr := r.View.RefreshTokenByID(tokenID, instanceID) tokenView, viewErr := r.View.RefreshTokenByID(tokenID, instanceID)
if viewErr != nil && !errors.IsNotFound(viewErr) { if viewErr != nil && !zerrors.IsNotFound(viewErr) {
return nil, viewErr return nil, viewErr
} }
if errors.IsNotFound(viewErr) { if zerrors.IsNotFound(viewErr) {
sequence, err := r.View.GetLatestRefreshTokenSequence(ctx) sequence, err := r.View.GetLatestRefreshTokenSequence(ctx)
logging.WithFields("instanceID", instanceID, "userID", userID, "tokenID", tokenID). logging.WithFields("instanceID", instanceID, "userID", userID, "tokenID", tokenID).
OnError(err). OnError(err).
@ -62,8 +62,8 @@ func (r *RefreshTokenRepo) RefreshTokenByID(ctx context.Context, tokenID, userID
} }
events, esErr := r.getUserEvents(ctx, userID, tokenView.InstanceID, tokenView.Sequence, tokenView.GetRelevantEventTypes()) events, esErr := r.getUserEvents(ctx, userID, tokenView.InstanceID, tokenView.Sequence, tokenView.GetRelevantEventTypes())
if errors.IsNotFound(viewErr) && len(events) == 0 { if zerrors.IsNotFound(viewErr) && len(events) == 0 {
return nil, errors.ThrowNotFound(nil, "EVENT-BHB52", "Errors.User.RefreshToken.Invalid") return nil, zerrors.ThrowNotFound(nil, "EVENT-BHB52", "Errors.User.RefreshToken.Invalid")
} }
if esErr != nil { if esErr != nil {
@ -78,7 +78,7 @@ func (r *RefreshTokenRepo) RefreshTokenByID(ctx context.Context, tokenID, userID
} }
} }
if !tokenView.Expiration.After(time.Now()) { if !tokenView.Expiration.After(time.Now()) {
return nil, errors.ThrowNotFound(nil, "EVENT-5Bm9s", "Errors.User.RefreshToken.Invalid") return nil, zerrors.ThrowNotFound(nil, "EVENT-5Bm9s", "Errors.User.RefreshToken.Invalid")
} }
return model.RefreshTokenViewToModel(tokenView), nil return model.RefreshTokenViewToModel(tokenView), nil
} }

Some files were not shown because too many files have changed in this diff Show More