Merge branch 'refs/heads/main' into next

# Conflicts:
#	cmd/start/start.go
#	docs/sidebars.js
#	internal/api/grpc/action/v3alpha/execution_integration_test.go
#	internal/api/grpc/action/v3alpha/query_integration_test.go
#	internal/api/grpc/action/v3alpha/target_integration_test.go
#	internal/api/grpc/feature/v2beta/converter.go
#	internal/api/grpc/feature/v2beta/converter_test.go
#	internal/api/grpc/oidc/v2beta/oidc.go
#	internal/api/grpc/resources/action/v3alpha/server_integration_test.go
#	internal/api/grpc/settings/v2beta/server.go
#	internal/api/grpc/user/v2/query_integration_test.go
#	internal/api/grpc/user/v2beta/query.go
#	internal/api/grpc/user/v2beta/query_integration_test.go
#	internal/auth/repository/eventsourcing/eventstore/auth_request_test.go
#	internal/command/user_idp_link_test.go
#	internal/crypto/crypto.go
#	internal/integration/assert.go
#	internal/integration/client.go
#	proto/zitadel/action/v3alpha/target.proto
#	proto/zitadel/feature/v2/instance.proto
#	proto/zitadel/org/v2/org_service.proto
#	proto/zitadel/resources/action/v3alpha/action_service.proto
#	proto/zitadel/resources/action/v3alpha/execution.proto
#	proto/zitadel/resources/action/v3alpha/query.proto
#	proto/zitadel/user/v2/user_service.proto
This commit is contained in:
Livio Spring
2024-08-19 16:55:55 +02:00
442 changed files with 18479 additions and 9385 deletions

View File

@@ -61,7 +61,7 @@ func Trigger(ctx context.Context, orgID, userID string, trigger TriggerMethod, r
authz.GetInstance(ctx).InstanceID(),
orgID,
userID,
http_utils.ComposedOrigin(ctx),
http_utils.DomainContext(ctx).Origin(), // TODO: origin?
trigger,
ai.Method,
ai.Path,
@@ -78,7 +78,7 @@ func TriggerGRPCWithContext(ctx context.Context, trigger TriggerMethod) {
authz.GetInstance(ctx).InstanceID(),
authz.GetCtxData(ctx).OrgID,
authz.GetCtxData(ctx).UserID,
http_utils.ComposedOrigin(ctx),
http_utils.DomainContext(ctx).Origin(), // TODO: origin?
trigger,
ai.Method,
ai.Path,

View File

@@ -32,7 +32,7 @@ type API struct {
verifier internal_authz.APITokenVerifier
health healthCheck
router *mux.Router
http1HostName string
hostHeaders []string
grpcGateway *server.Gateway
healthServer *health.Server
accessInterceptor *http_mw.AccessInterceptor
@@ -75,7 +75,8 @@ func New(
verifier internal_authz.APITokenVerifier,
authZ internal_authz.Config,
tlsConfig *tls.Config,
http2HostName, http1HostName, externalDomain string,
externalDomain string,
hostHeaders []string,
accessInterceptor *http_mw.AccessInterceptor,
) (_ *API, err error) {
api := &API{
@@ -83,13 +84,13 @@ func New(
verifier: verifier,
health: queries,
router: router,
http1HostName: http1HostName,
queries: queries,
accessInterceptor: accessInterceptor,
hostHeaders: hostHeaders,
}
api.grpcServer = server.CreateServer(api.verifier, authZ, queries, http2HostName, externalDomain, tlsConfig, accessInterceptor.AccessService())
api.grpcGateway, err = server.CreateGateway(ctx, port, http1HostName, accessInterceptor, tlsConfig)
api.grpcServer = server.CreateServer(api.verifier, authZ, queries, externalDomain, tlsConfig, accessInterceptor.AccessService())
api.grpcGateway, err = server.CreateGateway(ctx, port, hostHeaders, accessInterceptor, tlsConfig)
if err != nil {
return nil, err
}
@@ -112,9 +113,8 @@ func (a *API) RegisterServer(ctx context.Context, grpcServer server.WithGatewayP
ctx,
grpcServer,
a.port,
a.http1HostName,
a.hostHeaders,
a.accessInterceptor,
a.queries,
tlsConfig,
)
if err != nil {

View File

@@ -55,9 +55,9 @@ func (h *Handler) Storage() static.Storage {
return h.storage
}
func AssetAPI(externalSecure bool) func(context.Context) string {
func AssetAPI() func(context.Context) string {
return func(ctx context.Context) string {
return http_util.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + HandlerPrefix
return http_util.DomainContext(ctx).Origin() + HandlerPrefix
}
}

View File

@@ -18,8 +18,6 @@ type Instance interface {
ProjectID() string
ConsoleClientID() string
ConsoleApplicationID() string
RequestedDomain() string
RequestedHost() string
DefaultLanguage() language.Tag
DefaultOrganisationID() string
SecurityPolicyAllowedOrigins() []string
@@ -30,8 +28,8 @@ type Instance interface {
}
type InstanceVerifier interface {
InstanceByHost(ctx context.Context, host string) (Instance, error)
InstanceByID(ctx context.Context) (Instance, error)
InstanceByHost(ctx context.Context, host, publicDomain string) (Instance, error)
InstanceByID(ctx context.Context, id string) (Instance, error)
}
type instance struct {
@@ -68,14 +66,6 @@ func (i *instance) ConsoleApplicationID() string {
return i.appID
}
func (i *instance) RequestedDomain() string {
return i.domain
}
func (i *instance) RequestedHost() string {
return i.domain
}
func (i *instance) DefaultLanguage() language.Tag {
return language.Und
}
@@ -116,16 +106,6 @@ func WithInstanceID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, instanceKey, &instance{id: id})
}
func WithRequestedDomain(ctx context.Context, domain string) context.Context {
i, ok := ctx.Value(instanceKey).(*instance)
if !ok {
i = new(instance)
}
i.domain = domain
return context.WithValue(ctx, instanceKey, i)
}
func WithConsole(ctx context.Context, projectID, appID string) context.Context {
i, ok := ctx.Value(instanceKey).(*instance)
if !ok {

View File

@@ -118,14 +118,6 @@ func (m *mockInstance) DefaultOrganisationID() string {
return "orgID"
}
func (m *mockInstance) RequestedDomain() string {
return "zitadel.cloud"
}
func (m *mockInstance) RequestedHost() string {
return "zitadel.cloud:443"
}
func (m *mockInstance) SecurityPolicyAllowedOrigins() []string {
return nil
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,877 +0,0 @@
//go:build integration
package action_test
import (
"context"
"fmt"
"reflect"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/integration"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
"github.com/zitadel/zitadel/pkg/grpc/object/v2"
)
func TestServer_GetTargetByID(t *testing.T) {
ensureFeatureEnabled(t)
type args struct {
ctx context.Context
dep func(context.Context, *action.GetTargetByIDRequest, *action.GetTargetByIDResponse) error
req *action.GetTargetByIDRequest
}
tests := []struct {
name string
args args
want *action.GetTargetByIDResponse
wantErr bool
}{
{
name: "missing permission",
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.GetTargetByIDRequest{},
},
wantErr: true,
},
{
name: "not found",
args: args{
ctx: CTX,
req: &action.GetTargetByIDRequest{TargetId: "notexisting"},
},
wantErr: true,
},
{
name: "get, ok",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, false)
request.TargetId = resp.GetId()
response.Target.TargetId = resp.GetId()
response.Target.Name = name
response.Target.Details.ResourceOwner = resp.GetDetails().GetResourceOwner()
response.Target.Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Target.Details.Sequence = resp.GetDetails().GetSequence()
return nil
},
req: &action.GetTargetByIDRequest{},
},
want: &action.GetTargetByIDResponse{
Target: &action.Target{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
{
name: "get, async, ok",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeAsync, false)
request.TargetId = resp.GetId()
response.Target.TargetId = resp.GetId()
response.Target.Name = name
response.Target.Details.ResourceOwner = resp.GetDetails().GetResourceOwner()
response.Target.Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Target.Details.Sequence = resp.GetDetails().GetSequence()
return nil
},
req: &action.GetTargetByIDRequest{},
},
want: &action.GetTargetByIDResponse{
Target: &action.Target{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
{
name: "get, webhook interruptOnError, ok",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, true)
request.TargetId = resp.GetId()
response.Target.TargetId = resp.GetId()
response.Target.Name = name
response.Target.Details.ResourceOwner = resp.GetDetails().GetResourceOwner()
response.Target.Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Target.Details.Sequence = resp.GetDetails().GetSequence()
return nil
},
req: &action.GetTargetByIDRequest{},
},
want: &action.GetTargetByIDResponse{
Target: &action.Target{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
{
name: "get, call, ok",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeCall, false)
request.TargetId = resp.GetId()
response.Target.TargetId = resp.GetId()
response.Target.Name = name
response.Target.Details.ResourceOwner = resp.GetDetails().GetResourceOwner()
response.Target.Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Target.Details.Sequence = resp.GetDetails().GetSequence()
return nil
},
req: &action.GetTargetByIDRequest{},
},
want: &action.GetTargetByIDResponse{
Target: &action.Target{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
{
name: "get, call interruptOnError, ok",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeCall, true)
request.TargetId = resp.GetId()
response.Target.TargetId = resp.GetId()
response.Target.Name = name
response.Target.Details.ResourceOwner = resp.GetDetails().GetResourceOwner()
response.Target.Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Target.Details.Sequence = resp.GetDetails().GetSequence()
return nil
},
req: &action.GetTargetByIDRequest{},
},
want: &action.GetTargetByIDResponse{
Target: &action.Target{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.dep != nil {
err := tt.args.dep(tt.args.ctx, tt.args.req, tt.want)
require.NoError(t, err)
}
retryDuration := 5 * time.Second
if ctxDeadline, ok := CTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, getErr := Client.GetTargetByID(tt.args.ctx, tt.args.req)
if tt.wantErr {
assert.Error(ttt, getErr, "Error: "+getErr.Error())
} else {
assert.NoError(ttt, getErr)
integration.AssertDetails(t, tt.want.GetTarget(), got.GetTarget())
assert.Equal(t, tt.want.Target, got.Target)
}
}, retryDuration, time.Millisecond*100, "timeout waiting for expected execution result")
})
}
}
func TestServer_ListTargets(t *testing.T) {
ensureFeatureEnabled(t)
type args struct {
ctx context.Context
dep func(context.Context, *action.ListTargetsRequest, *action.ListTargetsResponse) error
req *action.ListTargetsRequest
}
tests := []struct {
name string
args args
want *action.ListTargetsResponse
wantErr bool
}{
{
name: "missing permission",
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.ListTargetsRequest{},
},
wantErr: true,
},
{
name: "list, not found",
args: args{
ctx: CTX,
req: &action.ListTargetsRequest{
Queries: []*action.TargetSearchQuery{
{Query: &action.TargetSearchQuery_InTargetIdsQuery{
InTargetIdsQuery: &action.InTargetIDsQuery{
TargetIds: []string{"notfound"},
},
},
},
},
},
},
want: &action.ListTargetsResponse{
Details: &object.ListDetails{
TotalResult: 0,
},
Result: []*action.Target{},
},
},
{
name: "list single id",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListTargetsRequest, response *action.ListTargetsResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, false)
request.Queries[0].Query = &action.TargetSearchQuery_InTargetIdsQuery{
InTargetIdsQuery: &action.InTargetIDsQuery{
TargetIds: []string{resp.GetId()},
},
}
response.Details.Timestamp = resp.GetDetails().GetChangeDate()
//response.Details.ProcessedSequence = resp.GetDetails().GetSequence()
response.Result[0].Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Result[0].Details.Sequence = resp.GetDetails().GetSequence()
response.Result[0].TargetId = resp.GetId()
response.Result[0].Name = name
return nil
},
req: &action.ListTargetsRequest{
Queries: []*action.TargetSearchQuery{{}},
},
},
want: &action.ListTargetsResponse{
Details: &object.ListDetails{
TotalResult: 1,
},
Result: []*action.Target{
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
}, {
name: "list single name",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListTargetsRequest, response *action.ListTargetsResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, false)
request.Queries[0].Query = &action.TargetSearchQuery_TargetNameQuery{
TargetNameQuery: &action.TargetNameQuery{
TargetName: name,
},
}
response.Details.Timestamp = resp.GetDetails().GetChangeDate()
response.Details.ProcessedSequence = resp.GetDetails().GetSequence()
response.Result[0].Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Result[0].Details.Sequence = resp.GetDetails().GetSequence()
response.Result[0].TargetId = resp.GetId()
response.Result[0].Name = name
return nil
},
req: &action.ListTargetsRequest{
Queries: []*action.TargetSearchQuery{{}},
},
},
want: &action.ListTargetsResponse{
Details: &object.ListDetails{
TotalResult: 1,
},
Result: []*action.Target{
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
{
name: "list multiple id",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListTargetsRequest, response *action.ListTargetsResponse) error {
name1 := fmt.Sprint(time.Now().UnixNano() + 1)
name2 := fmt.Sprint(time.Now().UnixNano() + 3)
name3 := fmt.Sprint(time.Now().UnixNano() + 5)
resp1 := Tester.CreateTarget(ctx, t, name1, "https://example.com", domain.TargetTypeWebhook, false)
resp2 := Tester.CreateTarget(ctx, t, name2, "https://example.com", domain.TargetTypeCall, true)
resp3 := Tester.CreateTarget(ctx, t, name3, "https://example.com", domain.TargetTypeAsync, false)
request.Queries[0].Query = &action.TargetSearchQuery_InTargetIdsQuery{
InTargetIdsQuery: &action.InTargetIDsQuery{
TargetIds: []string{resp1.GetId(), resp2.GetId(), resp3.GetId()},
},
}
response.Details.Timestamp = resp3.GetDetails().GetChangeDate()
response.Details.ProcessedSequence = resp3.GetDetails().GetSequence()
response.Result[0].Details.ChangeDate = resp1.GetDetails().GetChangeDate()
response.Result[0].Details.Sequence = resp1.GetDetails().GetSequence()
response.Result[0].TargetId = resp1.GetId()
response.Result[0].Name = name1
response.Result[1].Details.ChangeDate = resp2.GetDetails().GetChangeDate()
response.Result[1].Details.Sequence = resp2.GetDetails().GetSequence()
response.Result[1].TargetId = resp2.GetId()
response.Result[1].Name = name2
response.Result[2].Details.ChangeDate = resp3.GetDetails().GetChangeDate()
response.Result[2].Details.Sequence = resp3.GetDetails().GetSequence()
response.Result[2].TargetId = resp3.GetId()
response.Result[2].Name = name3
return nil
},
req: &action.ListTargetsRequest{
Queries: []*action.TargetSearchQuery{{}},
},
},
want: &action.ListTargetsResponse{
Details: &object.ListDetails{
TotalResult: 3,
},
Result: []*action.Target{
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Endpoint: "https://example.com",
TargetType: &action.Target_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.dep != nil {
err := tt.args.dep(tt.args.ctx, tt.args.req, tt.want)
require.NoError(t, err)
}
retryDuration := 5 * time.Second
if ctxDeadline, ok := CTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, listErr := Client.ListTargets(tt.args.ctx, tt.args.req)
if tt.wantErr {
assert.Error(ttt, listErr, "Error: "+listErr.Error())
} else {
assert.NoError(ttt, listErr)
}
if listErr != nil {
return
}
// always first check length, otherwise its failed anyway
assert.Len(ttt, got.Result, len(tt.want.Result))
for i := range tt.want.Result {
assert.Contains(ttt, got.Result, tt.want.Result[i])
}
integration.AssertListDetails(t, tt.want, got)
}, retryDuration, time.Millisecond*100, "timeout waiting for expected execution result")
})
}
}
func TestServer_ListExecutions(t *testing.T) {
ensureFeatureEnabled(t)
targetResp := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false)
type args struct {
ctx context.Context
dep func(context.Context, *action.ListExecutionsRequest, *action.ListExecutionsResponse) error
req *action.ListExecutionsRequest
}
tests := []struct {
name string
args args
want *action.ListExecutionsResponse
wantErr bool
}{
{
name: "missing permission",
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.ListExecutionsRequest{},
},
wantErr: true,
},
{
name: "list request single condition",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListExecutionsRequest, response *action.ListExecutionsResponse) error {
cond := request.Queries[0].GetInConditionsQuery().GetConditions()[0]
resp := Tester.SetExecution(ctx, t, cond, executionTargetsSingleTarget(targetResp.GetId()))
response.Details.Timestamp = resp.GetDetails().GetChangeDate()
// response.Details.ProcessedSequence = resp.GetDetails().GetSequence()
// Set expected response with used values for SetExecution
response.Result[0].Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Result[0].Details.Sequence = resp.GetDetails().GetSequence()
response.Result[0].Condition = cond
return nil
},
req: &action.ListExecutionsRequest{
Queries: []*action.SearchQuery{{
Query: &action.SearchQuery_InConditionsQuery{
InConditionsQuery: &action.InConditionsQuery{
Conditions: []*action.Condition{{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/GetSession",
},
},
},
}},
},
},
}},
},
},
want: &action.ListExecutionsResponse{
Details: &object.ListDetails{
TotalResult: 1,
},
Result: []*action.Execution{
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/GetSession",
},
},
},
},
Targets: executionTargetsSingleTarget(targetResp.GetId()),
},
},
},
},
{
name: "list request single target",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListExecutionsRequest, response *action.ListExecutionsResponse) error {
target := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false)
// add target as query to the request
request.Queries[0] = &action.SearchQuery{
Query: &action.SearchQuery_TargetQuery{
TargetQuery: &action.TargetQuery{
TargetId: target.GetId(),
},
},
}
cond := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.management.v1.ManagementService/UpdateAction",
},
},
},
}
targets := executionTargetsSingleTarget(target.GetId())
resp := Tester.SetExecution(ctx, t, cond, targets)
response.Details.Timestamp = resp.GetDetails().GetChangeDate()
response.Details.ProcessedSequence = resp.GetDetails().GetSequence()
response.Result[0].Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Result[0].Details.Sequence = resp.GetDetails().GetSequence()
response.Result[0].Condition = cond
response.Result[0].Targets = targets
return nil
},
req: &action.ListExecutionsRequest{
Queries: []*action.SearchQuery{{}},
},
},
want: &action.ListExecutionsResponse{
Details: &object.ListDetails{
TotalResult: 1,
},
Result: []*action.Execution{
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
Condition: &action.Condition{},
Targets: executionTargetsSingleTarget(""),
},
},
},
}, {
name: "list request single include",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListExecutionsRequest, response *action.ListExecutionsResponse) error {
cond := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.management.v1.ManagementService/GetAction",
},
},
},
}
Tester.SetExecution(ctx, t, cond, executionTargetsSingleTarget(targetResp.GetId()))
request.Queries[0].GetIncludeQuery().Include = cond
includeCond := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.management.v1.ManagementService/ListActions",
},
},
},
}
includeTargets := executionTargetsSingleInclude(cond)
resp2 := Tester.SetExecution(ctx, t, includeCond, includeTargets)
response.Details.Timestamp = resp2.GetDetails().GetChangeDate()
response.Details.ProcessedSequence = resp2.GetDetails().GetSequence()
response.Result[0].Details.ChangeDate = resp2.GetDetails().GetChangeDate()
response.Result[0].Details.Sequence = resp2.GetDetails().GetSequence()
response.Result[0].Condition = includeCond
response.Result[0].Targets = includeTargets
return nil
},
req: &action.ListExecutionsRequest{
Queries: []*action.SearchQuery{{
Query: &action.SearchQuery_IncludeQuery{
IncludeQuery: &action.IncludeQuery{},
},
}},
},
},
want: &action.ListExecutionsResponse{
Details: &object.ListDetails{
TotalResult: 1,
},
Result: []*action.Execution{
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
},
},
{
name: "list multiple conditions",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListExecutionsRequest, response *action.ListExecutionsResponse) error {
cond1 := request.Queries[0].GetInConditionsQuery().GetConditions()[0]
targets1 := executionTargetsSingleTarget(targetResp.GetId())
resp1 := Tester.SetExecution(ctx, t, cond1, targets1)
response.Result[0].Details.ChangeDate = resp1.GetDetails().GetChangeDate()
response.Result[0].Details.Sequence = resp1.GetDetails().GetSequence()
response.Result[0].Condition = cond1
response.Result[0].Targets = targets1
cond2 := request.Queries[0].GetInConditionsQuery().GetConditions()[1]
targets2 := executionTargetsSingleTarget(targetResp.GetId())
resp2 := Tester.SetExecution(ctx, t, cond2, targets2)
response.Result[1].Details.ChangeDate = resp2.GetDetails().GetChangeDate()
response.Result[1].Details.Sequence = resp2.GetDetails().GetSequence()
response.Result[1].Condition = cond2
response.Result[1].Targets = targets2
cond3 := request.Queries[0].GetInConditionsQuery().GetConditions()[2]
targets3 := executionTargetsSingleTarget(targetResp.GetId())
resp3 := Tester.SetExecution(ctx, t, cond3, targets3)
response.Result[2].Details.ChangeDate = resp3.GetDetails().GetChangeDate()
response.Result[2].Details.Sequence = resp3.GetDetails().GetSequence()
response.Result[2].Condition = cond3
response.Result[2].Targets = targets3
response.Details.Timestamp = resp3.GetDetails().GetChangeDate()
response.Details.ProcessedSequence = resp3.GetDetails().GetSequence()
return nil
},
req: &action.ListExecutionsRequest{
Queries: []*action.SearchQuery{{
Query: &action.SearchQuery_InConditionsQuery{
InConditionsQuery: &action.InConditionsQuery{
Conditions: []*action.Condition{
{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/GetSession",
},
},
},
},
{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/CreateSession",
},
},
},
},
{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/SetSession",
},
},
},
},
},
},
},
}},
},
},
want: &action.ListExecutionsResponse{
Details: &object.ListDetails{
TotalResult: 3,
},
Result: []*action.Execution{
{
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
}, {
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
}, {
Details: &object.Details{
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
},
},
{
name: "list multiple conditions all types",
args: args{
ctx: CTX,
dep: func(ctx context.Context, request *action.ListExecutionsRequest, response *action.ListExecutionsResponse) error {
targets := executionTargetsSingleTarget(targetResp.GetId())
for i, cond := range request.Queries[0].GetInConditionsQuery().GetConditions() {
resp := Tester.SetExecution(ctx, t, cond, targets)
response.Result[i].Details.ChangeDate = resp.GetDetails().GetChangeDate()
response.Result[i].Details.Sequence = resp.GetDetails().GetSequence()
response.Result[i].Condition = cond
response.Result[i].Targets = targets
// filled with info of last sequence
response.Details.Timestamp = resp.GetDetails().GetChangeDate()
response.Details.ProcessedSequence = resp.GetDetails().GetSequence()
}
return nil
},
req: &action.ListExecutionsRequest{
Queries: []*action.SearchQuery{{
Query: &action.SearchQuery_InConditionsQuery{
InConditionsQuery: &action.InConditionsQuery{
Conditions: []*action.Condition{
{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_Method{Method: "/zitadel.session.v2.SessionService/GetSession"}}}},
{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_Service{Service: "zitadel.session.v2.SessionService"}}}},
{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_All{All: true}}}},
{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_Method{Method: "/zitadel.session.v2.SessionService/GetSession"}}}},
{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_Service{Service: "zitadel.session.v2.SessionService"}}}},
{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_All{All: true}}}},
{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_Event{Event: "user.added"}}}},
{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_Group{Group: "user"}}}},
{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_All{All: true}}}},
{ConditionType: &action.Condition_Function{Function: &action.FunctionExecution{Name: "Action.Flow.Type.ExternalAuthentication.Action.TriggerType.PostAuthentication"}}},
},
},
},
}},
},
},
want: &action.ListExecutionsResponse{
Details: &object.ListDetails{
TotalResult: 10,
},
Result: []*action.Execution{
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
{Details: &object.Details{ResourceOwner: Tester.Instance.InstanceID()}},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.dep != nil {
err := tt.args.dep(tt.args.ctx, tt.args.req, tt.want)
require.NoError(t, err)
}
retryDuration := 5 * time.Second
if ctxDeadline, ok := CTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, listErr := Client.ListExecutions(tt.args.ctx, tt.args.req)
if tt.wantErr {
assert.Error(t, listErr, "Error: "+listErr.Error())
} else {
assert.NoError(t, listErr)
}
if listErr != nil {
return
}
// always first check length, otherwise its failed anyway
assert.Len(t, got.Result, len(tt.want.Result))
for i := range tt.want.Result {
// as not sorted, all elements have to be checked
// workaround as oneof elements can only be checked with assert.EqualExportedValues()
if j, found := containExecution(got.Result, tt.want.Result[i]); found {
assert.EqualExportedValues(t, tt.want.Result[i], got.Result[j])
}
}
integration.AssertListDetails(t, tt.want, got)
}, retryDuration, time.Millisecond*100, "timeout waiting for expected execution result")
})
}
}
func containExecution(executionList []*action.Execution, execution *action.Execution) (int, bool) {
for i, exec := range executionList {
if reflect.DeepEqual(exec.Details, execution.Details) {
return i, true
}
}
return 0, false
}

View File

@@ -1,112 +0,0 @@
package action
import (
"context"
"github.com/muhlemmer/gu"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/eventstore/v1/models"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
)
func (s *Server) CreateTarget(ctx context.Context, req *action.CreateTargetRequest) (*action.CreateTargetResponse, error) {
if err := checkExecutionEnabled(ctx); err != nil {
return nil, err
}
add := createTargetToCommand(req)
details, err := s.command.AddTarget(ctx, add, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
return &action.CreateTargetResponse{
Id: add.AggregateID,
Details: object.DomainToDetailsPb(details),
}, nil
}
func (s *Server) UpdateTarget(ctx context.Context, req *action.UpdateTargetRequest) (*action.UpdateTargetResponse, error) {
if err := checkExecutionEnabled(ctx); err != nil {
return nil, err
}
details, err := s.command.ChangeTarget(ctx, updateTargetToCommand(req), authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
return &action.UpdateTargetResponse{
Details: object.DomainToDetailsPb(details),
}, nil
}
func (s *Server) DeleteTarget(ctx context.Context, req *action.DeleteTargetRequest) (*action.DeleteTargetResponse, error) {
if err := checkExecutionEnabled(ctx); err != nil {
return nil, err
}
details, err := s.command.DeleteTarget(ctx, req.GetTargetId(), authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
return &action.DeleteTargetResponse{
Details: object.DomainToDetailsPb(details),
}, nil
}
func createTargetToCommand(req *action.CreateTargetRequest) *command.AddTarget {
var (
targetType domain.TargetType
interruptOnError bool
)
switch t := req.GetTargetType().(type) {
case *action.CreateTargetRequest_RestWebhook:
targetType = domain.TargetTypeWebhook
interruptOnError = t.RestWebhook.InterruptOnError
case *action.CreateTargetRequest_RestCall:
targetType = domain.TargetTypeCall
interruptOnError = t.RestCall.InterruptOnError
case *action.CreateTargetRequest_RestAsync:
targetType = domain.TargetTypeAsync
}
return &command.AddTarget{
Name: req.GetName(),
TargetType: targetType,
Endpoint: req.GetEndpoint(),
Timeout: req.GetTimeout().AsDuration(),
InterruptOnError: interruptOnError,
}
}
func updateTargetToCommand(req *action.UpdateTargetRequest) *command.ChangeTarget {
if req == nil {
return nil
}
target := &command.ChangeTarget{
ObjectRoot: models.ObjectRoot{
AggregateID: req.GetTargetId(),
},
Name: req.Name,
Endpoint: req.Endpoint,
}
if req.TargetType != nil {
switch t := req.GetTargetType().(type) {
case *action.UpdateTargetRequest_RestWebhook:
target.TargetType = gu.Ptr(domain.TargetTypeWebhook)
target.InterruptOnError = gu.Ptr(t.RestWebhook.InterruptOnError)
case *action.UpdateTargetRequest_RestCall:
target.TargetType = gu.Ptr(domain.TargetTypeCall)
target.InterruptOnError = gu.Ptr(t.RestCall.InterruptOnError)
case *action.UpdateTargetRequest_RestAsync:
target.TargetType = gu.Ptr(domain.TargetTypeAsync)
target.InterruptOnError = gu.Ptr(false)
}
}
if req.Timeout != nil {
target.Timeout = gu.Ptr(req.GetTimeout().AsDuration())
}
return target
}

View File

@@ -1,423 +0,0 @@
//go:build integration
package action_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/muhlemmer/gu"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/integration"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
"github.com/zitadel/zitadel/pkg/grpc/object/v2"
)
func TestServer_CreateTarget(t *testing.T) {
ensureFeatureEnabled(t)
tests := []struct {
name string
ctx context.Context
req *action.CreateTargetRequest
want *action.CreateTargetResponse
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
},
wantErr: true,
},
{
name: "empty name",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: "",
},
wantErr: true,
},
{
name: "empty type",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
TargetType: nil,
},
wantErr: true,
},
{
name: "empty webhook url",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
TargetType: &action.CreateTargetRequest_RestWebhook{
RestWebhook: &action.SetRESTWebhook{},
},
},
wantErr: true,
},
{
name: "empty request response url",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
TargetType: &action.CreateTargetRequest_RestCall{
RestCall: &action.SetRESTCall{},
},
},
wantErr: true,
},
{
name: "empty timeout",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.CreateTargetRequest_RestWebhook{
RestWebhook: &action.SetRESTWebhook{},
},
Timeout: nil,
},
wantErr: true,
},
{
name: "async, ok",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.CreateTargetRequest_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &action.CreateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "webhook, ok",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.CreateTargetRequest_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &action.CreateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "webhook, interrupt on error, ok",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.CreateTargetRequest_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &action.CreateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "call, ok",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.CreateTargetRequest_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &action.CreateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "call, interruptOnError, ok",
ctx: CTX,
req: &action.CreateTargetRequest{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.CreateTargetRequest_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &action.CreateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Client.CreateTarget(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertDetails(t, tt.want, got)
assert.NotEmpty(t, got.GetId())
})
}
}
func TestServer_UpdateTarget(t *testing.T) {
ensureFeatureEnabled(t)
type args struct {
ctx context.Context
req *action.UpdateTargetRequest
}
tests := []struct {
name string
prepare func(request *action.UpdateTargetRequest) error
args args
want *action.UpdateTargetResponse
wantErr bool
}{
{
name: "missing permission",
prepare: func(request *action.UpdateTargetRequest) error {
targetID := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetId()
request.TargetId = targetID
return nil
},
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.UpdateTargetRequest{
Name: gu.Ptr(fmt.Sprint(time.Now().UnixNano() + 1)),
},
},
wantErr: true,
},
{
name: "not existing",
prepare: func(request *action.UpdateTargetRequest) error {
request.TargetId = "notexisting"
return nil
},
args: args{
ctx: CTX,
req: &action.UpdateTargetRequest{
Name: gu.Ptr(fmt.Sprint(time.Now().UnixNano() + 1)),
},
},
wantErr: true,
},
{
name: "change name, ok",
prepare: func(request *action.UpdateTargetRequest) error {
targetID := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetId()
request.TargetId = targetID
return nil
},
args: args{
ctx: CTX,
req: &action.UpdateTargetRequest{
Name: gu.Ptr(fmt.Sprint(time.Now().UnixNano() + 1)),
},
},
want: &action.UpdateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "change type, ok",
prepare: func(request *action.UpdateTargetRequest) error {
targetID := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetId()
request.TargetId = targetID
return nil
},
args: args{
ctx: CTX,
req: &action.UpdateTargetRequest{
TargetType: &action.UpdateTargetRequest_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
},
},
want: &action.UpdateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "change url, ok",
prepare: func(request *action.UpdateTargetRequest) error {
targetID := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetId()
request.TargetId = targetID
return nil
},
args: args{
ctx: CTX,
req: &action.UpdateTargetRequest{
Endpoint: gu.Ptr("https://example.com/hooks/new"),
},
},
want: &action.UpdateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "change timeout, ok",
prepare: func(request *action.UpdateTargetRequest) error {
targetID := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetId()
request.TargetId = targetID
return nil
},
args: args{
ctx: CTX,
req: &action.UpdateTargetRequest{
Timeout: durationpb.New(20 * time.Second),
},
},
want: &action.UpdateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
{
name: "change type async, ok",
prepare: func(request *action.UpdateTargetRequest) error {
targetID := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeAsync, false).GetId()
request.TargetId = targetID
return nil
},
args: args{
ctx: CTX,
req: &action.UpdateTargetRequest{
TargetType: &action.UpdateTargetRequest_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
},
},
want: &action.UpdateTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.prepare(tt.args.req)
require.NoError(t, err)
got, err := Client.UpdateTarget(tt.args.ctx, tt.args.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertDetails(t, tt.want, got)
})
}
}
func TestServer_DeleteTarget(t *testing.T) {
ensureFeatureEnabled(t)
target := Tester.CreateTarget(CTX, t, "", "https://example.com", domain.TargetTypeWebhook, false)
tests := []struct {
name string
ctx context.Context
req *action.DeleteTargetRequest
want *action.DeleteTargetResponse
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.DeleteTargetRequest{
TargetId: target.GetId(),
},
wantErr: true,
},
{
name: "empty id",
ctx: CTX,
req: &action.DeleteTargetRequest{
TargetId: "",
},
wantErr: true,
},
{
name: "delete target",
ctx: CTX,
req: &action.DeleteTargetRequest{
TargetId: target.GetId(),
},
want: &action.DeleteTargetResponse{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
ResourceOwner: Tester.Instance.InstanceID(),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Client.DeleteTarget(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertDetails(t, tt.want, got)
})
}
}

View File

@@ -36,7 +36,7 @@ func (s *Server) ExportData(ctx context.Context, req *admin_pb.ExportDataRequest
}
orgSearchQuery.Queries = []query.SearchQuery{orgIDsSearchQuery}
}
queriedOrgs, err := s.query.SearchOrgs(ctx, orgSearchQuery)
queriedOrgs, err := s.query.SearchOrgs(ctx, orgSearchQuery, nil)
if err != nil {
return nil, err
}
@@ -554,7 +554,7 @@ func (s *Server) getUsers(ctx context.Context, org string, withPasswords bool, w
if err != nil {
return nil, nil, nil, nil, err
}
users, err := s.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: []query.SearchQuery{orgSearch}})
users, err := s.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: []query.SearchQuery{orgSearch}}, nil)
if err != nil {
return nil, nil, nil, nil, err
}

View File

@@ -157,7 +157,7 @@ func (s *Server) GetProviderByID(ctx context.Context, req *admin_pb.GetProviderB
if err != nil {
return nil, err
}
idp, err := s.query.IDPTemplateByID(ctx, true, req.Id, false, instanceIDQuery)
idp, err := s.query.IDPTemplateByID(ctx, true, req.Id, false, nil, instanceIDQuery)
if err != nil {
return nil, err
}

View File

@@ -37,3 +37,42 @@ func (s *Server) ListInstanceDomains(ctx context.Context, req *admin_pb.ListInst
),
}, nil
}
func (s *Server) ListInstanceTrustedDomains(ctx context.Context, req *admin_pb.ListInstanceTrustedDomainsRequest) (*admin_pb.ListInstanceTrustedDomainsResponse, error) {
queries, err := ListInstanceTrustedDomainsRequestToModel(req)
if err != nil {
return nil, err
}
domains, err := s.query.SearchInstanceTrustedDomains(ctx, queries)
if err != nil {
return nil, err
}
return &admin_pb.ListInstanceTrustedDomainsResponse{
Result: instance_grpc.TrustedDomainsToPb(domains.Domains),
Details: object.ToListDetails(
domains.Count,
domains.Sequence,
domains.LastRun,
),
}, nil
}
func (s *Server) AddInstanceTrustedDomain(ctx context.Context, req *admin_pb.AddInstanceTrustedDomainRequest) (*admin_pb.AddInstanceTrustedDomainResponse, error) {
details, err := s.command.AddTrustedDomain(ctx, req.Domain)
if err != nil {
return nil, err
}
return &admin_pb.AddInstanceTrustedDomainResponse{
Details: object.DomainToAddDetailsPb(details),
}, nil
}
func (s *Server) RemoveInstanceTrustedDomain(ctx context.Context, req *admin_pb.RemoveInstanceTrustedDomainRequest) (*admin_pb.RemoveInstanceTrustedDomainResponse, error) {
details, err := s.command.RemoveTrustedDomain(ctx, req.Domain)
if err != nil {
return nil, err
}
return &admin_pb.RemoveInstanceTrustedDomainResponse{
Details: object.DomainToChangeDetailsPb(details),
}, nil
}

View File

@@ -39,3 +39,20 @@ func fieldNameToInstanceDomainColumn(fieldName instance.DomainFieldName) query.C
return query.Column{}
}
}
func ListInstanceTrustedDomainsRequestToModel(req *admin_pb.ListInstanceTrustedDomainsRequest) (*query.InstanceTrustedDomainSearchQueries, error) {
offset, limit, asc := object.ListQueryToModel(req.Query)
queries, err := instance_grpc.TrustedDomainQueriesToModel(req.Queries)
if err != nil {
return nil, err
}
return &query.InstanceTrustedDomainSearchQueries{
SearchRequest: query.SearchRequest{
Offset: offset,
Limit: limit,
Asc: asc,
SortingColumn: fieldNameToInstanceDomainColumn(req.SortingColumn),
},
Queries: queries,
}, nil
}

View File

@@ -6,6 +6,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object"
org_grpc "github.com/zitadel/zitadel/internal/api/grpc/org"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
@@ -58,7 +59,7 @@ func (s *Server) ListOrgs(ctx context.Context, req *admin_pb.ListOrgsRequest) (*
if err != nil {
return nil, err
}
orgs, err := s.query.SearchOrgs(ctx, queries)
orgs, err := s.query.SearchOrgs(ctx, queries, nil)
if err != nil {
return nil, err
}
@@ -69,7 +70,7 @@ func (s *Server) ListOrgs(ctx context.Context, req *admin_pb.ListOrgsRequest) (*
}
func (s *Server) SetUpOrg(ctx context.Context, req *admin_pb.SetUpOrgRequest) (*admin_pb.SetUpOrgResponse, error) {
orgDomain, err := domain.NewIAMDomainName(req.Org.Name, authz.GetInstance(ctx).RequestedDomain())
orgDomain, err := domain.NewIAMDomainName(req.Org.Name, http_utils.DomainContext(ctx).RequestedDomain())
if err != nil {
return nil, err
}
@@ -107,7 +108,7 @@ func (s *Server) getClaimedUserIDsOfOrgDomain(ctx context.Context, orgDomain str
if err != nil {
return nil, err
}
users, err := s.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: []query.SearchQuery{loginName}})
users, err := s.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: []query.SearchQuery{loginName}}, nil)
if err != nil {
return nil, err
}

View File

@@ -90,7 +90,7 @@ func TestServer_Restrictions_AllowedLanguages(t *testing.T) {
awaitDiscoveryEndpoint(tt, domain, []string{defaultAndAllowedLanguage.String()}, []string{disallowedLanguage.String()})
})
t.Run("the login ui is rendered in the default language", func(tt *testing.T) {
awaitLoginUILanguage(tt, domain, disallowedLanguage, defaultAndAllowedLanguage, "Allgemeine Geschäftsbedingungen und Datenschutz")
awaitLoginUILanguage(tt, domain, disallowedLanguage, defaultAndAllowedLanguage, "Passwort")
})
t.Run("preferred languages are not restricted by the supported languages", func(tt *testing.T) {
tt.Run("change user profile", func(ttt *testing.T) {
@@ -151,7 +151,7 @@ func TestServer_Restrictions_AllowedLanguages(t *testing.T) {
awaitDiscoveryEndpoint(ttt, domain, []string{disallowedLanguage.String()}, nil)
})
tt.Run("the login ui is rendered in the previously disallowed language", func(ttt *testing.T) {
awaitLoginUILanguage(ttt, domain, disallowedLanguage, disallowedLanguage, "Términos y condiciones")
awaitLoginUILanguage(ttt, domain, disallowedLanguage, disallowedLanguage, "Contraseña")
})
})
}

View File

@@ -11,7 +11,6 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/server"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/config/systemdefaults"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/pkg/grpc/admin"
@@ -41,8 +40,6 @@ func CreateServer(
database string,
command *command.Commands,
query *query.Queries,
sd systemdefaults.SystemDefaults,
externalSecure bool,
userCodeAlg crypto.EncryptionAlgorithm,
auditLogRetention time.Duration,
) *Server {
@@ -50,7 +47,7 @@ func CreateServer(
database: database,
command: command,
query: query,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
userCodeAlg: userCodeAlg,
auditLogRetention: auditLogRetention,
}

View File

@@ -67,10 +67,9 @@ func (s *Server) AddMyPasswordlessLink(ctx context.Context, _ *auth_pb.AddMyPass
if err != nil {
return nil, err
}
origin := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
return &auth_pb.AddMyPasswordlessLinkResponse{
Details: object.AddToDetailsPb(initCode.Sequence, initCode.ChangeDate, initCode.ResourceOwner),
Link: initCode.Link(origin + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Link: initCode.Link(http.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Expiration: durationpb.New(initCode.Expiration),
}, nil
}

View File

@@ -31,7 +31,6 @@ type Server struct {
defaults systemdefaults.SystemDefaults
assetsAPIDomain func(context.Context) string
userCodeAlg crypto.EncryptionAlgorithm
externalSecure bool
}
type Config struct {
@@ -43,16 +42,14 @@ func CreateServer(command *command.Commands,
authRepo repository.Repository,
defaults systemdefaults.SystemDefaults,
userCodeAlg crypto.EncryptionAlgorithm,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
repo: authRepo,
defaults: defaults,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
userCodeAlg: userCodeAlg,
externalSecure: externalSecure,
}
}

View File

@@ -220,7 +220,7 @@ func (s *Server) ListMyProjectOrgs(ctx context.Context, req *auth_pb.ListMyProje
}
}
orgs, err := s.query.SearchOrgs(ctx, queries)
orgs, err := s.query.SearchOrgs(ctx, queries, nil)
if err != nil {
return nil, err
}

View File

@@ -42,6 +42,7 @@ func instanceFeaturesToCommand(req *feature_pb.SetInstanceFeaturesRequest) *comm
TokenExchange: req.OidcTokenExchange,
Actions: req.Actions,
ImprovedPerformance: improvedPerformanceListToDomain(req.ImprovedPerformance),
WebKey: req.WebKey,
}
}
@@ -55,6 +56,7 @@ func instanceFeaturesToPb(f *query.InstanceFeatures) *feature_pb.GetInstanceFeat
OidcTokenExchange: featureSourceToFlagPb(&f.TokenExchange),
Actions: featureSourceToFlagPb(&f.Actions),
ImprovedPerformance: featureSourceToImprovedPerformanceFlagPb(&f.ImprovedPerformance),
WebKey: featureSourceToFlagPb(&f.WebKey),
}
}

View File

@@ -123,6 +123,7 @@ func Test_instanceFeaturesToCommand(t *testing.T) {
OidcTokenExchange: gu.Ptr(true),
Actions: gu.Ptr(true),
ImprovedPerformance: nil,
WebKey: gu.Ptr(true),
}
want := &command.InstanceFeatures{
LoginDefaultOrg: gu.Ptr(true),
@@ -132,6 +133,7 @@ func Test_instanceFeaturesToCommand(t *testing.T) {
TokenExchange: gu.Ptr(true),
Actions: gu.Ptr(true),
ImprovedPerformance: nil,
WebKey: gu.Ptr(true),
}
got := instanceFeaturesToCommand(arg)
assert.Equal(t, want, got)
@@ -172,6 +174,10 @@ func Test_instanceFeaturesToPb(t *testing.T) {
Level: feature.LevelSystem,
Value: []feature.ImprovedPerformanceType{feature.ImprovedPerformanceTypeOrgByID},
},
WebKey: query.FeatureSource[bool]{
Level: feature.LevelInstance,
Value: true,
},
}
want := &feature_pb.GetInstanceFeaturesResponse{
Details: &object.Details{
@@ -207,6 +213,10 @@ func Test_instanceFeaturesToPb(t *testing.T) {
ExecutionPaths: []feature_pb.ImprovedPerformance{feature_pb.ImprovedPerformance_IMPROVED_PERFORMANCE_ORG_BY_ID},
Source: feature_pb.Source_SOURCE_SYSTEM,
},
WebKey: &feature_pb.FeatureFlag{
Enabled: true,
Source: feature_pb.Source_SOURCE_INSTANCE,
},
}
got := instanceFeaturesToPb(arg)
assert.Equal(t, want, got)

View File

@@ -42,6 +42,7 @@ func instanceFeaturesToCommand(req *feature_pb.SetInstanceFeaturesRequest) *comm
TokenExchange: req.OidcTokenExchange,
Actions: req.Actions,
ImprovedPerformance: improvedPerformanceListToDomain(req.ImprovedPerformance),
WebKey: req.WebKey,
}
}
@@ -55,6 +56,7 @@ func instanceFeaturesToPb(f *query.InstanceFeatures) *feature_pb.GetInstanceFeat
OidcTokenExchange: featureSourceToFlagPb(&f.TokenExchange),
Actions: featureSourceToFlagPb(&f.Actions),
ImprovedPerformance: featureSourceToImprovedPerformanceFlagPb(&f.ImprovedPerformance),
WebKey: featureSourceToFlagPb(&f.WebKey),
}
}

View File

@@ -123,6 +123,7 @@ func Test_instanceFeaturesToCommand(t *testing.T) {
OidcTokenExchange: gu.Ptr(true),
Actions: gu.Ptr(true),
ImprovedPerformance: nil,
WebKey: gu.Ptr(true),
}
want := &command.InstanceFeatures{
LoginDefaultOrg: gu.Ptr(true),
@@ -132,6 +133,7 @@ func Test_instanceFeaturesToCommand(t *testing.T) {
TokenExchange: gu.Ptr(true),
Actions: gu.Ptr(true),
ImprovedPerformance: nil,
WebKey: gu.Ptr(true),
}
got := instanceFeaturesToCommand(arg)
assert.Equal(t, want, got)
@@ -172,6 +174,10 @@ func Test_instanceFeaturesToPb(t *testing.T) {
Level: feature.LevelSystem,
Value: []feature.ImprovedPerformanceType{feature.ImprovedPerformanceTypeOrgByID},
},
WebKey: query.FeatureSource[bool]{
Level: feature.LevelInstance,
Value: true,
},
}
want := &feature_pb.GetInstanceFeaturesResponse{
Details: &object.Details{
@@ -207,6 +213,10 @@ func Test_instanceFeaturesToPb(t *testing.T) {
ExecutionPaths: []feature_pb.ImprovedPerformance{feature_pb.ImprovedPerformance_IMPROVED_PERFORMANCE_ORG_BY_ID},
Source: feature_pb.Source_SOURCE_SYSTEM,
},
WebKey: &feature_pb.FeatureFlag{
Enabled: true,
Source: feature_pb.Source_SOURCE_INSTANCE,
},
}
got := instanceFeaturesToPb(arg)
assert.Equal(t, want, got)

View File

@@ -0,0 +1,369 @@
package idp
import (
"context"
"github.com/crewjam/saml"
"github.com/muhlemmer/gu"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/idp/providers/azuread"
"github.com/zitadel/zitadel/internal/query"
idp_rp "github.com/zitadel/zitadel/internal/repository/idp"
idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp/v2"
)
func (s *Server) GetIDPByID(ctx context.Context, req *idp_pb.GetIDPByIDRequest) (*idp_pb.GetIDPByIDResponse, error) {
idp, err := s.query.IDPTemplateByID(ctx, true, req.Id, false, s.checkPermission)
if err != nil {
return nil, err
}
return &idp_pb.GetIDPByIDResponse{Idp: idpToPb(idp)}, nil
}
func idpToPb(idp *query.IDPTemplate) *idp_pb.IDP {
return &idp_pb.IDP{
Id: idp.ID,
Details: object.DomainToDetailsPb(
&domain.ObjectDetails{
Sequence: idp.Sequence,
EventDate: idp.ChangeDate,
ResourceOwner: idp.ResourceOwner,
}),
State: idpStateToPb(idp.State),
Name: idp.Name,
Type: idpTypeToPb(idp.Type),
Config: configToPb(idp),
}
}
func idpStateToPb(state domain.IDPState) idp_pb.IDPState {
switch state {
case domain.IDPStateActive:
return idp_pb.IDPState_IDP_STATE_ACTIVE
case domain.IDPStateInactive:
return idp_pb.IDPState_IDP_STATE_INACTIVE
case domain.IDPStateUnspecified:
return idp_pb.IDPState_IDP_STATE_UNSPECIFIED
case domain.IDPStateMigrated:
return idp_pb.IDPState_IDP_STATE_MIGRATED
case domain.IDPStateRemoved:
return idp_pb.IDPState_IDP_STATE_REMOVED
default:
return idp_pb.IDPState_IDP_STATE_UNSPECIFIED
}
}
func idpTypeToPb(idpType domain.IDPType) idp_pb.IDPType {
switch idpType {
case domain.IDPTypeOIDC:
return idp_pb.IDPType_IDP_TYPE_OIDC
case domain.IDPTypeJWT:
return idp_pb.IDPType_IDP_TYPE_JWT
case domain.IDPTypeOAuth:
return idp_pb.IDPType_IDP_TYPE_OAUTH
case domain.IDPTypeLDAP:
return idp_pb.IDPType_IDP_TYPE_LDAP
case domain.IDPTypeAzureAD:
return idp_pb.IDPType_IDP_TYPE_AZURE_AD
case domain.IDPTypeGitHub:
return idp_pb.IDPType_IDP_TYPE_GITHUB
case domain.IDPTypeGitHubEnterprise:
return idp_pb.IDPType_IDP_TYPE_GITHUB_ES
case domain.IDPTypeGitLab:
return idp_pb.IDPType_IDP_TYPE_GITLAB
case domain.IDPTypeGitLabSelfHosted:
return idp_pb.IDPType_IDP_TYPE_GITLAB_SELF_HOSTED
case domain.IDPTypeGoogle:
return idp_pb.IDPType_IDP_TYPE_GOOGLE
case domain.IDPTypeApple:
return idp_pb.IDPType_IDP_TYPE_APPLE
case domain.IDPTypeSAML:
return idp_pb.IDPType_IDP_TYPE_SAML
case domain.IDPTypeUnspecified:
return idp_pb.IDPType_IDP_TYPE_UNSPECIFIED
default:
return idp_pb.IDPType_IDP_TYPE_UNSPECIFIED
}
}
func configToPb(config *query.IDPTemplate) *idp_pb.IDPConfig {
idpConfig := &idp_pb.IDPConfig{
Options: &idp_pb.Options{
IsLinkingAllowed: config.IsLinkingAllowed,
IsCreationAllowed: config.IsCreationAllowed,
IsAutoCreation: config.IsAutoCreation,
IsAutoUpdate: config.IsAutoUpdate,
AutoLinking: autoLinkingOptionToPb(config.AutoLinking),
},
}
if config.OAuthIDPTemplate != nil {
oauthConfigToPb(idpConfig, config.OAuthIDPTemplate)
return idpConfig
}
if config.OIDCIDPTemplate != nil {
oidcConfigToPb(idpConfig, config.OIDCIDPTemplate)
return idpConfig
}
if config.JWTIDPTemplate != nil {
jwtConfigToPb(idpConfig, config.JWTIDPTemplate)
return idpConfig
}
if config.AzureADIDPTemplate != nil {
azureConfigToPb(idpConfig, config.AzureADIDPTemplate)
return idpConfig
}
if config.GitHubIDPTemplate != nil {
githubConfigToPb(idpConfig, config.GitHubIDPTemplate)
return idpConfig
}
if config.GitHubEnterpriseIDPTemplate != nil {
githubEnterpriseConfigToPb(idpConfig, config.GitHubEnterpriseIDPTemplate)
return idpConfig
}
if config.GitLabIDPTemplate != nil {
gitlabConfigToPb(idpConfig, config.GitLabIDPTemplate)
return idpConfig
}
if config.GitLabSelfHostedIDPTemplate != nil {
gitlabSelfHostedConfigToPb(idpConfig, config.GitLabSelfHostedIDPTemplate)
return idpConfig
}
if config.GoogleIDPTemplate != nil {
googleConfigToPb(idpConfig, config.GoogleIDPTemplate)
return idpConfig
}
if config.LDAPIDPTemplate != nil {
ldapConfigToPb(idpConfig, config.LDAPIDPTemplate)
return idpConfig
}
if config.AppleIDPTemplate != nil {
appleConfigToPb(idpConfig, config.AppleIDPTemplate)
return idpConfig
}
if config.SAMLIDPTemplate != nil {
samlConfigToPb(idpConfig, config.SAMLIDPTemplate)
return idpConfig
}
return idpConfig
}
func autoLinkingOptionToPb(linking domain.AutoLinkingOption) idp_pb.AutoLinkingOption {
switch linking {
case domain.AutoLinkingOptionUnspecified:
return idp_pb.AutoLinkingOption_AUTO_LINKING_OPTION_UNSPECIFIED
case domain.AutoLinkingOptionUsername:
return idp_pb.AutoLinkingOption_AUTO_LINKING_OPTION_USERNAME
case domain.AutoLinkingOptionEmail:
return idp_pb.AutoLinkingOption_AUTO_LINKING_OPTION_EMAIL
default:
return idp_pb.AutoLinkingOption_AUTO_LINKING_OPTION_UNSPECIFIED
}
}
func oauthConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.OAuthIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_Oauth{
Oauth: &idp_pb.OAuthConfig{
ClientId: template.ClientID,
AuthorizationEndpoint: template.AuthorizationEndpoint,
TokenEndpoint: template.TokenEndpoint,
UserEndpoint: template.UserEndpoint,
Scopes: template.Scopes,
IdAttribute: template.IDAttribute,
},
}
}
func oidcConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.OIDCIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_Oidc{
Oidc: &idp_pb.GenericOIDCConfig{
ClientId: template.ClientID,
Issuer: template.Issuer,
Scopes: template.Scopes,
IsIdTokenMapping: template.IsIDTokenMapping,
},
}
}
func jwtConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.JWTIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_Jwt{
Jwt: &idp_pb.JWTConfig{
JwtEndpoint: template.Endpoint,
Issuer: template.Issuer,
KeysEndpoint: template.KeysEndpoint,
HeaderName: template.HeaderName,
},
}
}
func azureConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.AzureADIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_AzureAd{
AzureAd: &idp_pb.AzureADConfig{
ClientId: template.ClientID,
Tenant: azureTenantToPb(template.Tenant),
EmailVerified: template.IsEmailVerified,
Scopes: template.Scopes,
},
}
}
func azureTenantToPb(tenant string) *idp_pb.AzureADTenant {
var tenantType idp_pb.IsAzureADTenantType
switch azuread.TenantType(tenant) {
case azuread.CommonTenant:
tenantType = &idp_pb.AzureADTenant_TenantType{TenantType: idp_pb.AzureADTenantType_AZURE_AD_TENANT_TYPE_COMMON}
case azuread.OrganizationsTenant:
tenantType = &idp_pb.AzureADTenant_TenantType{TenantType: idp_pb.AzureADTenantType_AZURE_AD_TENANT_TYPE_ORGANISATIONS}
case azuread.ConsumersTenant:
tenantType = &idp_pb.AzureADTenant_TenantType{TenantType: idp_pb.AzureADTenantType_AZURE_AD_TENANT_TYPE_CONSUMERS}
default:
tenantType = &idp_pb.AzureADTenant_TenantId{TenantId: tenant}
}
return &idp_pb.AzureADTenant{Type: tenantType}
}
func githubConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.GitHubIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_Github{
Github: &idp_pb.GitHubConfig{
ClientId: template.ClientID,
Scopes: template.Scopes,
},
}
}
func githubEnterpriseConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.GitHubEnterpriseIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_GithubEs{
GithubEs: &idp_pb.GitHubEnterpriseServerConfig{
ClientId: template.ClientID,
AuthorizationEndpoint: template.AuthorizationEndpoint,
TokenEndpoint: template.TokenEndpoint,
UserEndpoint: template.UserEndpoint,
Scopes: template.Scopes,
},
}
}
func gitlabConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.GitLabIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_Gitlab{
Gitlab: &idp_pb.GitLabConfig{
ClientId: template.ClientID,
Scopes: template.Scopes,
},
}
}
func gitlabSelfHostedConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.GitLabSelfHostedIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_GitlabSelfHosted{
GitlabSelfHosted: &idp_pb.GitLabSelfHostedConfig{
ClientId: template.ClientID,
Issuer: template.Issuer,
Scopes: template.Scopes,
},
}
}
func googleConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.GoogleIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_Google{
Google: &idp_pb.GoogleConfig{
ClientId: template.ClientID,
Scopes: template.Scopes,
},
}
}
func ldapConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.LDAPIDPTemplate) {
var timeout *durationpb.Duration
if template.Timeout != 0 {
timeout = durationpb.New(template.Timeout)
}
idpConfig.Config = &idp_pb.IDPConfig_Ldap{
Ldap: &idp_pb.LDAPConfig{
Servers: template.Servers,
StartTls: template.StartTLS,
BaseDn: template.BaseDN,
BindDn: template.BindDN,
UserBase: template.UserBase,
UserObjectClasses: template.UserObjectClasses,
UserFilters: template.UserFilters,
Timeout: timeout,
Attributes: ldapAttributesToPb(template.LDAPAttributes),
},
}
}
func ldapAttributesToPb(attributes idp_rp.LDAPAttributes) *idp_pb.LDAPAttributes {
return &idp_pb.LDAPAttributes{
IdAttribute: attributes.IDAttribute,
FirstNameAttribute: attributes.FirstNameAttribute,
LastNameAttribute: attributes.LastNameAttribute,
DisplayNameAttribute: attributes.DisplayNameAttribute,
NickNameAttribute: attributes.NickNameAttribute,
PreferredUsernameAttribute: attributes.PreferredUsernameAttribute,
EmailAttribute: attributes.EmailAttribute,
EmailVerifiedAttribute: attributes.EmailVerifiedAttribute,
PhoneAttribute: attributes.PhoneAttribute,
PhoneVerifiedAttribute: attributes.PhoneVerifiedAttribute,
PreferredLanguageAttribute: attributes.PreferredLanguageAttribute,
AvatarUrlAttribute: attributes.AvatarURLAttribute,
ProfileAttribute: attributes.ProfileAttribute,
}
}
func appleConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.AppleIDPTemplate) {
idpConfig.Config = &idp_pb.IDPConfig_Apple{
Apple: &idp_pb.AppleConfig{
ClientId: template.ClientID,
TeamId: template.TeamID,
KeyId: template.KeyID,
Scopes: template.Scopes,
},
}
}
func samlConfigToPb(idpConfig *idp_pb.IDPConfig, template *query.SAMLIDPTemplate) {
nameIDFormat := idp_pb.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_PERSISTENT
if template.NameIDFormat.Valid {
nameIDFormat = nameIDToPb(template.NameIDFormat.V)
}
idpConfig.Config = &idp_pb.IDPConfig_Saml{
Saml: &idp_pb.SAMLConfig{
MetadataXml: template.Metadata,
Binding: bindingToPb(template.Binding),
WithSignedRequest: template.WithSignedRequest,
NameIdFormat: nameIDFormat,
TransientMappingAttributeName: gu.Ptr(template.TransientMappingAttributeName),
},
}
}
func bindingToPb(binding string) idp_pb.SAMLBinding {
switch binding {
case "":
return idp_pb.SAMLBinding_SAML_BINDING_UNSPECIFIED
case saml.HTTPPostBinding:
return idp_pb.SAMLBinding_SAML_BINDING_POST
case saml.HTTPRedirectBinding:
return idp_pb.SAMLBinding_SAML_BINDING_REDIRECT
case saml.HTTPArtifactBinding:
return idp_pb.SAMLBinding_SAML_BINDING_ARTIFACT
default:
return idp_pb.SAMLBinding_SAML_BINDING_UNSPECIFIED
}
}
func nameIDToPb(format domain.SAMLNameIDFormat) idp_pb.SAMLNameIDFormat {
switch format {
case domain.SAMLNameIDFormatUnspecified:
return idp_pb.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_UNSPECIFIED
case domain.SAMLNameIDFormatEmailAddress:
return idp_pb.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_EMAIL_ADDRESS
case domain.SAMLNameIDFormatPersistent:
return idp_pb.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_PERSISTENT
case domain.SAMLNameIDFormatTransient:
return idp_pb.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_TRANSIENT
default:
return idp_pb.SAMLNameIDFormat_SAML_NAME_ID_FORMAT_UNSPECIFIED
}
}

View File

@@ -0,0 +1,235 @@
//go:build integration
package idp_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/pkg/grpc/idp/v2"
"github.com/zitadel/zitadel/pkg/grpc/object/v2"
)
type idpAttr struct {
ID string
Name string
Details *object.Details
}
func TestServer_GetIDPByID(t *testing.T) {
type args struct {
ctx context.Context
req *idp.GetIDPByIDRequest
dep func(ctx context.Context, request *idp.GetIDPByIDRequest) *idpAttr
}
tests := []struct {
name string
args args
want *idp.GetIDPByIDResponse
wantErr bool
}{
{
name: "idp by ID, no id provided",
args: args{
IamCTX,
&idp.GetIDPByIDRequest{
Id: "",
},
func(ctx context.Context, request *idp.GetIDPByIDRequest) *idpAttr {
return nil
},
},
wantErr: true,
},
{
name: "idp by ID, not found",
args: args{
IamCTX,
&idp.GetIDPByIDRequest{
Id: "unknown",
},
func(ctx context.Context, request *idp.GetIDPByIDRequest) *idpAttr {
return nil
},
},
wantErr: true,
},
{
name: "idp by ID, instance, ok",
args: args{
IamCTX,
&idp.GetIDPByIDRequest{},
func(ctx context.Context, request *idp.GetIDPByIDRequest) *idpAttr {
name := fmt.Sprintf("GetIDPByID%d", time.Now().UnixNano())
resp := Tester.AddGenericOAuthIDP(ctx, name)
request.Id = resp.Id
return &idpAttr{
resp.GetId(),
name,
&object.Details{
Sequence: resp.Details.Sequence,
ChangeDate: resp.Details.ChangeDate,
ResourceOwner: resp.Details.ResourceOwner,
}}
},
},
want: &idp.GetIDPByIDResponse{
Idp: &idp.IDP{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
},
State: idp.IDPState_IDP_STATE_ACTIVE,
Type: idp.IDPType_IDP_TYPE_OAUTH,
Config: &idp.IDPConfig{
Config: &idp.IDPConfig_Oauth{
Oauth: &idp.OAuthConfig{
ClientId: "clientID",
AuthorizationEndpoint: "https://example.com/oauth/v2/authorize",
TokenEndpoint: "https://example.com/oauth/v2/token",
UserEndpoint: "https://api.example.com/user",
Scopes: []string{"openid", "profile", "email"},
IdAttribute: "id",
},
},
Options: &idp.Options{
IsLinkingAllowed: true,
IsCreationAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_USERNAME,
},
},
},
},
},
{
name: "idp by ID, instance, no permission",
args: args{
UserCTX,
&idp.GetIDPByIDRequest{},
func(ctx context.Context, request *idp.GetIDPByIDRequest) *idpAttr {
name := fmt.Sprintf("GetIDPByID%d", time.Now().UnixNano())
resp := Tester.AddGenericOAuthIDP(IamCTX, name)
request.Id = resp.Id
return &idpAttr{
resp.GetId(),
name,
&object.Details{
Sequence: resp.Details.Sequence,
ChangeDate: resp.Details.ChangeDate,
ResourceOwner: resp.Details.ResourceOwner,
}}
},
},
wantErr: true,
},
{
name: "idp by ID, org, ok",
args: args{
CTX,
&idp.GetIDPByIDRequest{},
func(ctx context.Context, request *idp.GetIDPByIDRequest) *idpAttr {
name := fmt.Sprintf("GetIDPByID%d", time.Now().UnixNano())
resp := Tester.AddOrgGenericOAuthIDP(ctx, name)
request.Id = resp.Id
return &idpAttr{
resp.GetId(),
name,
&object.Details{
Sequence: resp.Details.Sequence,
ChangeDate: resp.Details.ChangeDate,
ResourceOwner: resp.Details.ResourceOwner,
}}
},
},
want: &idp.GetIDPByIDResponse{
Idp: &idp.IDP{
Details: &object.Details{
ChangeDate: timestamppb.Now(),
},
State: idp.IDPState_IDP_STATE_ACTIVE,
Type: idp.IDPType_IDP_TYPE_OAUTH,
Config: &idp.IDPConfig{
Config: &idp.IDPConfig_Oauth{
Oauth: &idp.OAuthConfig{
ClientId: "clientID",
AuthorizationEndpoint: "https://example.com/oauth/v2/authorize",
TokenEndpoint: "https://example.com/oauth/v2/token",
UserEndpoint: "https://api.example.com/user",
Scopes: []string{"openid", "profile", "email"},
IdAttribute: "id",
},
},
Options: &idp.Options{
IsLinkingAllowed: true,
IsCreationAllowed: true,
IsAutoCreation: true,
IsAutoUpdate: true,
AutoLinking: idp.AutoLinkingOption_AUTO_LINKING_OPTION_USERNAME,
},
},
},
},
},
{
name: "idp by ID, org, no permission",
args: args{
UserCTX,
&idp.GetIDPByIDRequest{},
func(ctx context.Context, request *idp.GetIDPByIDRequest) *idpAttr {
name := fmt.Sprintf("GetIDPByID%d", time.Now().UnixNano())
resp := Tester.AddOrgGenericOAuthIDP(CTX, name)
request.Id = resp.Id
return &idpAttr{
resp.GetId(),
name,
&object.Details{
Sequence: resp.Details.Sequence,
ChangeDate: resp.Details.ChangeDate,
ResourceOwner: resp.Details.ResourceOwner,
}}
},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
idpAttr := tt.args.dep(tt.args.ctx, tt.args.req)
retryDuration := time.Minute
if ctxDeadline, ok := CTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, getErr := Client.GetIDPByID(tt.args.ctx, tt.args.req)
assertErr := assert.NoError
if tt.wantErr {
assertErr = assert.Error
}
assertErr(ttt, getErr)
if getErr != nil {
return
}
// set provided info from creation
tt.want.Idp.Details = idpAttr.Details
tt.want.Idp.Name = idpAttr.Name
tt.want.Idp.Id = idpAttr.ID
// first check for details, mgmt and admin api don't fill the details correctly
integration.AssertDetails(t, tt.want.Idp, got.Idp)
// then set details
tt.want.Idp.Details = got.Idp.Details
// to check the rest of the content
assert.Equal(ttt, tt.want.Idp, got.Idp)
}, retryDuration, time.Second)
})
}
}

View File

@@ -0,0 +1,56 @@
package idp
import (
"google.golang.org/grpc"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/server"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/pkg/grpc/idp/v2"
)
var _ idp.IdentityProviderServiceServer = (*Server)(nil)
type Server struct {
idp.UnimplementedIdentityProviderServiceServer
command *command.Commands
query *query.Queries
checkPermission domain.PermissionCheck
}
type Config struct{}
func CreateServer(
command *command.Commands,
query *query.Queries,
checkPermission domain.PermissionCheck,
) *Server {
return &Server{
command: command,
query: query,
checkPermission: checkPermission,
}
}
func (s *Server) RegisterServer(grpcServer *grpc.Server) {
idp.RegisterIdentityProviderServiceServer(grpcServer, s)
}
func (s *Server) AppName() string {
return idp.IdentityProviderService_ServiceDesc.ServiceName
}
func (s *Server) MethodPrefix() string {
return idp.IdentityProviderService_ServiceDesc.ServiceName
}
func (s *Server) AuthMethods() authz.MethodMapping {
return idp.IdentityProviderService_AuthMethods
}
func (s *Server) RegisterGateway() server.RegisterGatewayFunc {
return idp.RegisterIdentityProviderServiceHandler
}

View File

@@ -0,0 +1,40 @@
//go:build integration
package idp_test
import (
"context"
"os"
"testing"
"time"
"github.com/zitadel/zitadel/internal/integration"
idp_pb "github.com/zitadel/zitadel/pkg/grpc/idp/v2"
)
var (
CTX context.Context
IamCTX context.Context
UserCTX context.Context
SystemCTX context.Context
ErrCTX context.Context
Tester *integration.Tester
Client idp_pb.IdentityProviderServiceClient
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, errCtx, cancel := integration.Contexts(time.Hour)
defer cancel()
Tester = integration.NewTester(ctx)
defer Tester.Done()
UserCTX = Tester.WithAuthorization(ctx, integration.Login)
IamCTX = Tester.WithAuthorization(ctx, integration.IAMOwner)
SystemCTX = Tester.WithAuthorization(ctx, integration.SystemUser)
CTX, ErrCTX = Tester.WithAuthorization(ctx, integration.OrgOwner), errCtx
Client = Tester.Client.IDPv2
return m.Run()
}())
}

View File

@@ -115,3 +115,43 @@ func DomainToPb(d *query.InstanceDomain) *instance_pb.Domain {
),
}
}
func TrustedDomainQueriesToModel(queries []*instance_pb.TrustedDomainSearchQuery) (_ []query.SearchQuery, err error) {
q := make([]query.SearchQuery, len(queries))
for i, query := range queries {
q[i], err = TrustedDomainQueryToModel(query)
if err != nil {
return nil, err
}
}
return q, nil
}
func TrustedDomainQueryToModel(searchQuery *instance_pb.TrustedDomainSearchQuery) (query.SearchQuery, error) {
switch q := searchQuery.Query.(type) {
case *instance_pb.TrustedDomainSearchQuery_DomainQuery:
return query.NewInstanceTrustedDomainDomainSearchQuery(object.TextMethodToQuery(q.DomainQuery.Method), q.DomainQuery.Domain)
default:
return nil, zerrors.ThrowInvalidArgument(nil, "INST-Ags42", "List.Query.Invalid")
}
}
func TrustedDomainsToPb(domains []*query.InstanceTrustedDomain) []*instance_pb.TrustedDomain {
d := make([]*instance_pb.TrustedDomain, len(domains))
for i, domain := range domains {
d[i] = TrustedDomainToPb(domain)
}
return d
}
func TrustedDomainToPb(d *query.InstanceTrustedDomain) *instance_pb.TrustedDomain {
return &instance_pb.TrustedDomain{
Domain: d.Domain,
Details: object.ToViewDetailsPb(
d.Sequence,
d.CreationDate,
d.ChangeDate,
d.InstanceID,
),
}
}

View File

@@ -149,7 +149,7 @@ func (s *Server) GetProviderByID(ctx context.Context, req *mgmt_pb.GetProviderBy
if err != nil {
return nil, err
}
idp, err := s.query.IDPTemplateByID(ctx, true, req.Id, false, orgIDQuery)
idp, err := s.query.IDPTemplateByID(ctx, true, req.Id, false, nil, orgIDQuery)
if err != nil {
return nil, err
}

View File

@@ -5,7 +5,6 @@ import (
"github.com/zitadel/oidc/v3/pkg/oidc"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/http"
mgmt_pb "github.com/zitadel/zitadel/pkg/grpc/management"
)
@@ -15,7 +14,7 @@ func (s *Server) Healthz(context.Context, *mgmt_pb.HealthzRequest) (*mgmt_pb.Hea
}
func (s *Server) GetOIDCInformation(ctx context.Context, _ *mgmt_pb.GetOIDCInformationRequest) (*mgmt_pb.GetOIDCInformationResponse, error) {
issuer := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
issuer := http.DomainContext(ctx).Origin()
return &mgmt_pb.GetOIDCInformationResponse{
Issuer: issuer,
DiscoveryEndpoint: issuer + oidc.DiscoveryEndpoint,

View File

@@ -11,6 +11,7 @@ import (
obj_grpc "github.com/zitadel/zitadel/internal/api/grpc/object"
org_grpc "github.com/zitadel/zitadel/internal/api/grpc/org"
policy_grpc "github.com/zitadel/zitadel/internal/api/grpc/policy"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/eventstore/v1/models"
@@ -73,7 +74,7 @@ func (s *Server) ListOrgChanges(ctx context.Context, req *mgmt_pb.ListOrgChanges
}
func (s *Server) AddOrg(ctx context.Context, req *mgmt_pb.AddOrgRequest) (*mgmt_pb.AddOrgResponse, error) {
orgDomain, err := domain.NewIAMDomainName(req.Name, authz.GetInstance(ctx).RequestedDomain())
orgDomain, err := domain.NewIAMDomainName(req.Name, http_utils.DomainContext(ctx).RequestedDomain())
if err != nil {
return nil, err
}
@@ -329,7 +330,7 @@ func (s *Server) getClaimedUserIDsOfOrgDomain(ctx context.Context, orgDomain, or
}
queries = append(queries, owner)
}
users, err := s.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: queries})
users, err := s.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: queries}, nil)
if err != nil {
return nil, err
}

View File

@@ -28,7 +28,6 @@ type Server struct {
systemDefaults systemdefaults.SystemDefaults
assetAPIPrefix func(context.Context) string
userCodeAlg crypto.EncryptionAlgorithm
externalSecure bool
}
func CreateServer(
@@ -36,15 +35,13 @@ func CreateServer(
query *query.Queries,
sd systemdefaults.SystemDefaults,
userCodeAlg crypto.EncryptionAlgorithm,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
systemDefaults: sd,
assetAPIPrefix: assets.AssetAPI(externalSecure),
assetAPIPrefix: assets.AssetAPI(),
userCodeAlg: userCodeAlg,
externalSecure: externalSecure,
}
}

View File

@@ -68,7 +68,7 @@ func (s *Server) ListUsers(ctx context.Context, req *mgmt_pb.ListUsersRequest) (
if err != nil {
return nil, err
}
res, err := s.query.SearchUsers(ctx, queries)
res, err := s.query.SearchUsers(ctx, queries, nil)
if err != nil {
return nil, err
}
@@ -286,9 +286,8 @@ func (s *Server) ImportHumanUser(ctx context.Context, req *mgmt_pb.ImportHumanUs
),
}
if code != nil {
origin := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
resp.PasswordlessRegistration = &mgmt_pb.ImportHumanUserResponse_PasswordlessRegistration{
Link: code.Link(origin + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Link: code.Link(http.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Lifetime: durationpb.New(code.Expiration),
Expiration: durationpb.New(code.Expiration),
}
@@ -691,10 +690,9 @@ func (s *Server) AddPasswordlessRegistration(ctx context.Context, req *mgmt_pb.A
if err != nil {
return nil, err
}
origin := http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure)
return &mgmt_pb.AddPasswordlessRegistrationResponse{
Details: obj_grpc.AddToDetailsPb(initCode.Sequence, initCode.ChangeDate, initCode.ResourceOwner),
Link: initCode.Link(origin + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Link: initCode.Link(http.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointPasswordlessRegistration),
Expiration: durationpb.New(initCode.Expiration),
}, nil
}

View File

@@ -8,7 +8,6 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/oidc"
@@ -107,7 +106,7 @@ func (s *Server) linkSessionToAuthRequest(ctx context.Context, authRequestID str
return nil, err
}
authReq := &oidc.AuthRequestV2{CurrentAuthRequest: aar}
ctx = op.ContextWithIssuer(ctx, http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure))
ctx = op.ContextWithIssuer(ctx, http.DomainContext(ctx).Origin())
var callback string
if aar.ResponseType == domain.OIDCResponseTypeCode {
callback, err = oidc.CreateCodeCallbackURL(ctx, authReq, s.op.Provider())

View File

@@ -8,7 +8,6 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/api/authz"
object "github.com/zitadel/zitadel/internal/api/grpc/object/v2beta"
"github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/oidc"
@@ -107,7 +106,7 @@ func (s *Server) linkSessionToAuthRequest(ctx context.Context, authRequestID str
return nil, err
}
authReq := &oidc.AuthRequestV2{CurrentAuthRequest: aar}
ctx = op.ContextWithIssuer(ctx, http.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), s.externalSecure))
ctx = op.ContextWithIssuer(ctx, http.DomainContext(ctx).Origin())
var callback string
if aar.ResponseType == domain.OIDCResponseTypeCode {
callback, err = oidc.CreateCodeCallbackURL(ctx, authReq, s.op.Provider())

View File

@@ -19,22 +19,26 @@ import (
)
var (
CTX context.Context
Tester *integration.Tester
Client org.OrganizationServiceClient
User *user.AddHumanUserResponse
CTX context.Context
OwnerCTX context.Context
UserCTX context.Context
Tester *integration.Tester
Client org.OrganizationServiceClient
User *user.AddHumanUserResponse
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, errCtx, cancel := integration.Contexts(5 * time.Minute)
ctx, _, cancel := integration.Contexts(5 * time.Minute)
defer cancel()
Tester = integration.NewTester(ctx)
defer Tester.Done()
Client = Tester.Client.OrgV2
CTX, _ = Tester.WithAuthorization(ctx, integration.IAMOwner), errCtx
CTX = Tester.WithAuthorization(ctx, integration.IAMOwner)
OwnerCTX = Tester.WithAuthorization(ctx, integration.OrgOwner)
UserCTX = Tester.WithAuthorization(ctx, integration.Login)
User = Tester.CreateHumanUser(CTX)
return m.Run()
}())

View File

@@ -0,0 +1,132 @@
package org
import (
"context"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
"github.com/zitadel/zitadel/pkg/grpc/org/v2"
)
func (s *Server) ListOrganizations(ctx context.Context, req *org.ListOrganizationsRequest) (*org.ListOrganizationsResponse, error) {
queries, err := listOrgRequestToModel(req)
if err != nil {
return nil, err
}
orgs, err := s.query.SearchOrgs(ctx, queries, s.checkPermission)
if err != nil {
return nil, err
}
return &org.ListOrganizationsResponse{
Result: organizationsToPb(orgs.Orgs),
Details: object.ToListDetails(orgs.SearchResponse),
}, nil
}
func listOrgRequestToModel(req *org.ListOrganizationsRequest) (*query.OrgSearchQueries, error) {
offset, limit, asc := object.ListQueryToQuery(req.Query)
queries, err := orgQueriesToQuery(req.Queries)
if err != nil {
return nil, err
}
return &query.OrgSearchQueries{
SearchRequest: query.SearchRequest{
Offset: offset,
Limit: limit,
SortingColumn: fieldNameToOrganizationColumn(req.SortingColumn),
Asc: asc,
},
Queries: queries,
}, nil
}
func orgQueriesToQuery(queries []*org.SearchQuery) (_ []query.SearchQuery, err error) {
q := make([]query.SearchQuery, len(queries))
for i, query := range queries {
q[i], err = orgQueryToQuery(query)
if err != nil {
return nil, err
}
}
return q, nil
}
func orgQueryToQuery(orgQuery *org.SearchQuery) (query.SearchQuery, error) {
switch q := orgQuery.Query.(type) {
case *org.SearchQuery_DomainQuery:
return query.NewOrgDomainSearchQuery(object.TextMethodToQuery(q.DomainQuery.Method), q.DomainQuery.Domain)
case *org.SearchQuery_NameQuery:
return query.NewOrgNameSearchQuery(object.TextMethodToQuery(q.NameQuery.Method), q.NameQuery.Name)
case *org.SearchQuery_StateQuery:
return query.NewOrgStateSearchQuery(orgStateToDomain(q.StateQuery.State))
case *org.SearchQuery_IdQuery:
return query.NewOrgIDSearchQuery(q.IdQuery.Id)
default:
return nil, zerrors.ThrowInvalidArgument(nil, "ORG-vR9nC", "List.Query.Invalid")
}
}
func orgStateToPb(state domain.OrgState) org.OrganizationState {
switch state {
case domain.OrgStateActive:
return org.OrganizationState_ORGANIZATION_STATE_ACTIVE
case domain.OrgStateInactive:
return org.OrganizationState_ORGANIZATION_STATE_INACTIVE
case domain.OrgStateRemoved:
return org.OrganizationState_ORGANIZATION_STATE_REMOVED
case domain.OrgStateUnspecified:
fallthrough
default:
return org.OrganizationState_ORGANIZATION_STATE_UNSPECIFIED
}
}
func orgStateToDomain(state org.OrganizationState) domain.OrgState {
switch state {
case org.OrganizationState_ORGANIZATION_STATE_ACTIVE:
return domain.OrgStateActive
case org.OrganizationState_ORGANIZATION_STATE_INACTIVE:
return domain.OrgStateInactive
case org.OrganizationState_ORGANIZATION_STATE_REMOVED:
return domain.OrgStateRemoved
case org.OrganizationState_ORGANIZATION_STATE_UNSPECIFIED:
fallthrough
default:
return domain.OrgStateUnspecified
}
}
func fieldNameToOrganizationColumn(fieldName org.OrganizationFieldName) query.Column {
switch fieldName {
case org.OrganizationFieldName_ORGANIZATION_FIELD_NAME_NAME:
return query.OrgColumnName
case org.OrganizationFieldName_ORGANIZATION_FIELD_NAME_UNSPECIFIED:
return query.Column{}
default:
return query.Column{}
}
}
func organizationsToPb(orgs []*query.Org) []*org.Organization {
o := make([]*org.Organization, len(orgs))
for i, org := range orgs {
o[i] = organizationToPb(org)
}
return o
}
func organizationToPb(organization *query.Org) *org.Organization {
return &org.Organization{
Id: organization.ID,
Name: organization.Name,
PrimaryDomain: organization.Domain,
Details: object.DomainToDetailsPb(&domain.ObjectDetails{
Sequence: organization.Sequence,
EventDate: organization.ChangeDate,
ResourceOwner: organization.ResourceOwner,
}),
State: orgStateToPb(organization.State),
}
}

View File

@@ -0,0 +1,443 @@
//go:build integration
package org_test
import (
"context"
"fmt"
"strconv"
"testing"
"time"
"github.com/brianvoe/gofakeit/v6"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/pkg/grpc/object/v2"
"github.com/zitadel/zitadel/pkg/grpc/org/v2"
)
type orgAttr struct {
ID string
Name string
Details *object.Details
}
func TestServer_ListOrganizations(t *testing.T) {
type args struct {
ctx context.Context
req *org.ListOrganizationsRequest
dep func(ctx context.Context, request *org.ListOrganizationsRequest) ([]orgAttr, error)
}
tests := []struct {
name string
args args
want *org.ListOrganizationsResponse
wantErr bool
}{
{
name: "list org by id, ok, multiple",
args: args{
CTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationIdQuery(Tester.Organisation.ID),
},
},
func(ctx context.Context, request *org.ListOrganizationsRequest) ([]orgAttr, error) {
count := 3
orgs := make([]orgAttr, count)
prefix := fmt.Sprintf("ListOrgs%d", time.Now().UnixNano())
for i := 0; i < count; i++ {
name := prefix + strconv.Itoa(i)
orgResp := Tester.CreateOrganization(ctx, name, fmt.Sprintf("%d@mouse.com", time.Now().UnixNano()))
orgs[i] = orgAttr{
ID: orgResp.GetOrganizationId(),
Name: name,
Details: orgResp.GetDetails(),
}
}
request.Queries = []*org.SearchQuery{
OrganizationNamePrefixQuery(prefix),
}
return orgs, nil
},
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 3,
Timestamp: timestamppb.Now(),
},
SortingColumn: 0,
Result: []*org.Organization{
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
},
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
},
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
},
},
},
},
{
name: "list org by id, ok",
args: args{
CTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationIdQuery(Tester.Organisation.ID),
},
},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 1,
Timestamp: timestamppb.Now(),
},
SortingColumn: 0,
Result: []*org.Organization{
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
Name: Tester.Organisation.Name,
Details: &object.Details{
Sequence: Tester.Organisation.Sequence,
ChangeDate: timestamppb.New(Tester.Organisation.ChangeDate),
ResourceOwner: Tester.Organisation.ResourceOwner,
},
Id: Tester.Organisation.ID,
PrimaryDomain: Tester.Organisation.Domain,
},
},
},
},
{
name: "list org by name, ok",
args: args{
CTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationNameQuery(Tester.Organisation.Name),
},
},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 1,
Timestamp: timestamppb.Now(),
},
SortingColumn: 0,
Result: []*org.Organization{
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
Name: Tester.Organisation.Name,
Details: &object.Details{
Sequence: Tester.Organisation.Sequence,
ChangeDate: timestamppb.New(Tester.Organisation.ChangeDate),
ResourceOwner: Tester.Organisation.ResourceOwner,
},
Id: Tester.Organisation.ID,
PrimaryDomain: Tester.Organisation.Domain,
},
},
},
},
{
name: "list org by domain, ok",
args: args{
CTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationDomainQuery(Tester.Organisation.Domain),
},
},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 1,
Timestamp: timestamppb.Now(),
},
SortingColumn: 0,
Result: []*org.Organization{
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
Name: Tester.Organisation.Name,
Details: &object.Details{
Sequence: Tester.Organisation.Sequence,
ChangeDate: timestamppb.New(Tester.Organisation.ChangeDate),
ResourceOwner: Tester.Organisation.ResourceOwner,
},
Id: Tester.Organisation.ID,
PrimaryDomain: Tester.Organisation.Domain,
},
},
},
},
{
name: "list org by inactive state, ok",
args: args{
CTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{},
},
func(ctx context.Context, request *org.ListOrganizationsRequest) ([]orgAttr, error) {
name := gofakeit.Name()
orgResp := Tester.CreateOrganization(ctx, name, gofakeit.Email())
deactivateOrgResp := Tester.DeactivateOrganization(ctx, orgResp.GetOrganizationId())
request.Queries = []*org.SearchQuery{
OrganizationIdQuery(orgResp.GetOrganizationId()),
OrganizationStateQuery(org.OrganizationState_ORGANIZATION_STATE_INACTIVE),
}
return []orgAttr{{
ID: orgResp.GetOrganizationId(),
Name: name,
Details: &object.Details{
ResourceOwner: deactivateOrgResp.GetDetails().GetResourceOwner(),
Sequence: deactivateOrgResp.GetDetails().GetSequence(),
ChangeDate: deactivateOrgResp.GetDetails().GetChangeDate(),
},
}}, nil
},
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 1,
Timestamp: timestamppb.Now(),
},
SortingColumn: 0,
Result: []*org.Organization{
{
State: org.OrganizationState_ORGANIZATION_STATE_INACTIVE,
Details: &object.Details{},
},
},
},
},
{
name: "list org by domain, ok, sorted",
args: args{
CTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationDomainQuery(Tester.Organisation.Domain),
},
SortingColumn: org.OrganizationFieldName_ORGANIZATION_FIELD_NAME_NAME,
},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 1,
Timestamp: timestamppb.Now(),
},
SortingColumn: 1,
Result: []*org.Organization{
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
Name: Tester.Organisation.Name,
Details: &object.Details{
Sequence: Tester.Organisation.Sequence,
ChangeDate: timestamppb.New(Tester.Organisation.ChangeDate),
ResourceOwner: Tester.Organisation.ResourceOwner,
},
Id: Tester.Organisation.ID,
PrimaryDomain: Tester.Organisation.Domain,
},
},
},
},
{
name: "list org, no result",
args: args{
CTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationDomainQuery("notexisting"),
},
},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 0,
Timestamp: timestamppb.Now(),
},
SortingColumn: 0,
Result: []*org.Organization{},
},
},
{
name: "list org, no login",
args: args{
context.Background(),
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationDomainQuery("nopermission"),
},
},
nil,
},
wantErr: true,
},
{
name: "list org, no permission",
args: args{
UserCTX,
&org.ListOrganizationsRequest{},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 0,
Timestamp: timestamppb.Now(),
},
SortingColumn: 1,
Result: []*org.Organization{},
},
},
{
name: "list org, no permission org owner",
args: args{
OwnerCTX,
&org.ListOrganizationsRequest{
Queries: []*org.SearchQuery{
OrganizationDomainQuery("nopermission"),
},
},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 0,
Timestamp: timestamppb.Now(),
},
SortingColumn: 1,
Result: []*org.Organization{},
},
},
{
name: "list org, org owner",
args: args{
OwnerCTX,
&org.ListOrganizationsRequest{},
nil,
},
want: &org.ListOrganizationsResponse{
Details: &object.ListDetails{
TotalResult: 1,
Timestamp: timestamppb.Now(),
},
SortingColumn: 1,
Result: []*org.Organization{
{
State: org.OrganizationState_ORGANIZATION_STATE_ACTIVE,
Name: Tester.Organisation.Name,
Details: &object.Details{
Sequence: Tester.Organisation.Sequence,
ChangeDate: timestamppb.New(Tester.Organisation.ChangeDate),
ResourceOwner: Tester.Organisation.ResourceOwner,
},
Id: Tester.Organisation.ID,
PrimaryDomain: Tester.Organisation.Domain,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.dep != nil {
orgs, err := tt.args.dep(tt.args.ctx, tt.args.req)
require.NoError(t, err)
if len(orgs) > 0 {
for i, org := range orgs {
tt.want.Result[i].Name = org.Name
tt.want.Result[i].Id = org.ID
tt.want.Result[i].Details = org.Details
}
}
}
retryDuration := time.Minute
if ctxDeadline, ok := CTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, listErr := Client.ListOrganizations(tt.args.ctx, tt.args.req)
assertErr := assert.NoError
if tt.wantErr {
assertErr = assert.Error
}
assertErr(ttt, listErr)
if listErr != nil {
return
}
// totalResult is unrelated to the tests here so gets carried over, can vary from the count of results due to permissions
tt.want.Details.TotalResult = got.Details.TotalResult
// always first check length, otherwise its failed anyway
assert.Len(ttt, got.Result, len(tt.want.Result))
for i := range tt.want.Result {
// domain from result, as it is generated though the create
tt.want.Result[i].PrimaryDomain = got.Result[i].PrimaryDomain
// sequence from result, as it can be with different sequence from create
tt.want.Result[i].Details.Sequence = got.Result[i].Details.Sequence
}
for i := range tt.want.Result {
assert.Contains(ttt, got.Result, tt.want.Result[i])
}
integration.AssertListDetails(t, tt.want, got)
}, retryDuration, time.Millisecond*100, "timeout waiting for expected user result")
})
}
}
func OrganizationIdQuery(resourceowner string) *org.SearchQuery {
return &org.SearchQuery{Query: &org.SearchQuery_IdQuery{
IdQuery: &org.OrganizationIDQuery{
Id: resourceowner,
},
}}
}
func OrganizationNameQuery(name string) *org.SearchQuery {
return &org.SearchQuery{Query: &org.SearchQuery_NameQuery{
NameQuery: &org.OrganizationNameQuery{
Name: name,
},
}}
}
func OrganizationNamePrefixQuery(name string) *org.SearchQuery {
return &org.SearchQuery{Query: &org.SearchQuery_NameQuery{
NameQuery: &org.OrganizationNameQuery{
Name: name,
Method: object.TextQueryMethod_TEXT_QUERY_METHOD_STARTS_WITH,
},
}}
}
func OrganizationDomainQuery(domain string) *org.SearchQuery {
return &org.SearchQuery{Query: &org.SearchQuery_DomainQuery{
DomainQuery: &org.OrganizationDomainQuery{
Domain: domain,
},
}}
}
func OrganizationStateQuery(state org.OrganizationState) *org.SearchQuery {
return &org.SearchQuery{Query: &org.SearchQuery_StateQuery{
StateQuery: &org.OrganizationStateQuery{
State: state,
},
}}
}

View File

@@ -4,38 +4,22 @@ import (
"context"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
resource_object "github.com/zitadel/zitadel/internal/api/grpc/resources/object/v3alpha"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/repository/execution"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
"github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
)
func (s *Server) ListExecutionFunctions(_ context.Context, _ *action.ListExecutionFunctionsRequest) (*action.ListExecutionFunctionsResponse, error) {
return &action.ListExecutionFunctionsResponse{
Functions: s.ListActionFunctions(),
}, nil
}
func (s *Server) ListExecutionMethods(_ context.Context, _ *action.ListExecutionMethodsRequest) (*action.ListExecutionMethodsResponse, error) {
return &action.ListExecutionMethodsResponse{
Methods: s.ListGRPCMethods(),
}, nil
}
func (s *Server) ListExecutionServices(_ context.Context, _ *action.ListExecutionServicesRequest) (*action.ListExecutionServicesResponse, error) {
return &action.ListExecutionServicesResponse{
Services: s.ListGRPCServices(),
}, nil
}
func (s *Server) SetExecution(ctx context.Context, req *action.SetExecutionRequest) (*action.SetExecutionResponse, error) {
if err := checkExecutionEnabled(ctx); err != nil {
if err := checkActionsEnabled(ctx); err != nil {
return nil, err
}
targets := make([]*execution.Target, len(req.Targets))
for i, target := range req.Targets {
reqTargets := req.GetExecution().GetTargets()
targets := make([]*execution.Target, len(reqTargets))
for i, target := range reqTargets {
switch t := target.GetType().(type) {
case *action.ExecutionTargetType_Include:
include, err := conditionToInclude(t.Include)
@@ -50,36 +34,29 @@ func (s *Server) SetExecution(ctx context.Context, req *action.SetExecutionReque
set := &command.SetExecution{
Targets: targets,
}
var err error
var details *domain.ObjectDetails
instanceID := authz.GetInstance(ctx).InstanceID()
switch t := req.GetCondition().GetConditionType().(type) {
case *action.Condition_Request:
cond := executionConditionFromRequest(t.Request)
details, err = s.command.SetExecutionRequest(ctx, cond, set, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
details, err = s.command.SetExecutionRequest(ctx, cond, set, instanceID)
case *action.Condition_Response:
cond := executionConditionFromResponse(t.Response)
details, err = s.command.SetExecutionResponse(ctx, cond, set, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
details, err = s.command.SetExecutionResponse(ctx, cond, set, instanceID)
case *action.Condition_Event:
cond := executionConditionFromEvent(t.Event)
details, err = s.command.SetExecutionEvent(ctx, cond, set, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
details, err = s.command.SetExecutionEvent(ctx, cond, set, instanceID)
case *action.Condition_Function:
details, err = s.command.SetExecutionFunction(ctx, command.ExecutionFunctionCondition(t.Function.GetName()), set, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
details, err = s.command.SetExecutionFunction(ctx, command.ExecutionFunctionCondition(t.Function.GetName()), set, instanceID)
default:
err = zerrors.ThrowInvalidArgument(nil, "ACTION-5r5Ju", "Errors.Execution.ConditionInvalid")
}
if err != nil {
return nil, err
}
return &action.SetExecutionResponse{
Details: object.DomainToDetailsPb(details),
Details: resource_object.DomainToDetailsPb(details, object.OwnerType_OWNER_TYPE_INSTANCE, instanceID),
}, nil
}
@@ -109,44 +86,26 @@ func conditionToInclude(cond *action.Condition) (string, error) {
return "", err
}
return cond.ID(), nil
default:
return "", zerrors.ThrowInvalidArgument(nil, "ACTION-9BBob", "Errors.Execution.ConditionInvalid")
}
return "", nil
}
func (s *Server) DeleteExecution(ctx context.Context, req *action.DeleteExecutionRequest) (*action.DeleteExecutionResponse, error) {
if err := checkExecutionEnabled(ctx); err != nil {
return nil, err
}
func (s *Server) ListExecutionFunctions(_ context.Context, _ *action.ListExecutionFunctionsRequest) (*action.ListExecutionFunctionsResponse, error) {
return &action.ListExecutionFunctionsResponse{
Functions: s.ListActionFunctions(),
}, nil
}
var err error
var details *domain.ObjectDetails
switch t := req.GetCondition().GetConditionType().(type) {
case *action.Condition_Request:
cond := executionConditionFromRequest(t.Request)
details, err = s.command.DeleteExecutionRequest(ctx, cond, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
case *action.Condition_Response:
cond := executionConditionFromResponse(t.Response)
details, err = s.command.DeleteExecutionResponse(ctx, cond, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
case *action.Condition_Event:
cond := executionConditionFromEvent(t.Event)
details, err = s.command.DeleteExecutionEvent(ctx, cond, authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
case *action.Condition_Function:
details, err = s.command.DeleteExecutionFunction(ctx, command.ExecutionFunctionCondition(t.Function.GetName()), authz.GetInstance(ctx).InstanceID())
if err != nil {
return nil, err
}
}
return &action.DeleteExecutionResponse{
Details: object.DomainToDetailsPb(details),
func (s *Server) ListExecutionMethods(_ context.Context, _ *action.ListExecutionMethodsRequest) (*action.ListExecutionMethodsResponse, error) {
return &action.ListExecutionMethodsResponse{
Methods: s.ListGRPCMethods(),
}, nil
}
func (s *Server) ListExecutionServices(_ context.Context, _ *action.ListExecutionServicesRequest) (*action.ListExecutionServicesResponse, error) {
return &action.ListExecutionServicesResponse{
Services: s.ListGRPCServices(),
}, nil
}

View File

@@ -0,0 +1,808 @@
//go:build integration
package action_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/integration"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
resource_object "github.com/zitadel/zitadel/pkg/grpc/resources/object/v3alpha"
)
func executionTargetsSingleTarget(id string) []*action.ExecutionTargetType {
return []*action.ExecutionTargetType{{Type: &action.ExecutionTargetType_Target{Target: id}}}
}
func executionTargetsSingleInclude(include *action.Condition) []*action.ExecutionTargetType {
return []*action.ExecutionTargetType{{Type: &action.ExecutionTargetType_Include{Include: include}}}
}
func TestServer_SetExecution_Request(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
targetResp := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", domain.TargetTypeWebhook, false)
tests := []struct {
name string
ctx context.Context
req *action.SetExecutionRequest
want *action.SetExecutionResponse
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_All{All: true},
},
},
},
},
wantErr: true,
},
{
name: "no condition, error",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "method, not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2beta.NotExistingService/List",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "method, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2beta.SessionService/ListSessions",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
{
name: "service, not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Service{
Service: "NotExistingService",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "service, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Service{
Service: "zitadel.session.v2beta.SessionService",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
{
name: "all, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_All{
All: true,
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// We want to have the same response no matter how often we call the function
Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
got, err := Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want.Details, got.Details)
// cleanup to not impact other requests
Tester.DeleteExecution(tt.ctx, t, tt.req.GetCondition())
})
}
}
func TestServer_SetExecution_Request_Include(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
targetResp := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", domain.TargetTypeWebhook, false)
executionCond := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_All{
All: true,
},
},
},
}
Tester.SetExecution(isolatedIAMOwnerCTX, t,
executionCond,
executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
)
circularExecutionService := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Service{
Service: "zitadel.session.v2beta.SessionService",
},
},
},
}
Tester.SetExecution(isolatedIAMOwnerCTX, t,
circularExecutionService,
executionTargetsSingleInclude(executionCond),
)
circularExecutionMethod := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2beta.SessionService/ListSessions",
},
},
},
}
Tester.SetExecution(isolatedIAMOwnerCTX, t,
circularExecutionMethod,
executionTargetsSingleInclude(circularExecutionService),
)
tests := []struct {
name string
ctx context.Context
req *action.SetExecutionRequest
want *action.SetExecutionResponse
wantErr bool
}{
{
name: "method, circular error",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: circularExecutionService,
Execution: &action.Execution{
Targets: executionTargetsSingleInclude(circularExecutionMethod),
},
},
wantErr: true,
},
{
name: "method, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2beta.SessionService/ListSessions",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleInclude(executionCond),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
{
name: "service, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Service{
Service: "zitadel.session.v2beta.SessionService",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleInclude(executionCond),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// We want to have the same response no matter how often we call the function
Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
got, err := Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want.Details, got.Details)
// cleanup to not impact other requests
Tester.DeleteExecution(tt.ctx, t, tt.req.GetCondition())
})
}
}
func TestServer_SetExecution_Response(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
targetResp := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", domain.TargetTypeWebhook, false)
tests := []struct {
name string
ctx context.Context
req *action.SetExecutionRequest
want *action.SetExecutionResponse
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{
Condition: &action.ResponseExecution_All{All: true},
},
},
},
},
wantErr: true,
},
{
name: "no condition, error",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "method, not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{
Condition: &action.ResponseExecution_Method{
Method: "/zitadel.session.v2beta.NotExistingService/List",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "method, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{
Condition: &action.ResponseExecution_Method{
Method: "/zitadel.session.v2beta.SessionService/ListSessions",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
{
name: "service, not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{
Condition: &action.ResponseExecution_Service{
Service: "NotExistingService",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "service, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{
Condition: &action.ResponseExecution_Service{
Service: "zitadel.session.v2beta.SessionService",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
{
name: "all, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{
Condition: &action.ResponseExecution_All{
All: true,
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// We want to have the same response no matter how often we call the function
Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
got, err := Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want.Details, got.Details)
// cleanup to not impact other requests
Tester.DeleteExecution(tt.ctx, t, tt.req.GetCondition())
})
}
}
func TestServer_SetExecution_Event(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
targetResp := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", domain.TargetTypeWebhook, false)
tests := []struct {
name string
ctx context.Context
req *action.SetExecutionRequest
want *action.SetExecutionResponse
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Event{
Event: &action.EventExecution{
Condition: &action.EventExecution_All{
All: true,
},
},
},
},
},
wantErr: true,
},
{
name: "no condition, error",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Event{
Event: &action.EventExecution{},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
/*
//TODO event existing check
{
name: "event, not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Event{
Event: &action.EventExecution{
Condition: &action.EventExecution_Event{
Event: "xxx",
},
},
},
},
Targets: []string{targetResp.GetId()},
},
wantErr: true,
},
*/
{
name: "event, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Event{
Event: &action.EventExecution{
Condition: &action.EventExecution_Event{
Event: "xxx",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
/*
// TODO:
{
name: "group, not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Event{
Event: &action.EventExecution{
Condition: &action.EventExecution_Group{
Group: "xxx",
},
},
},
},
Targets: []string{targetResp.GetId()},
},
wantErr: true,
},
*/
{
name: "group, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Event{
Event: &action.EventExecution{
Condition: &action.EventExecution_Group{
Group: "xxx",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
{
name: "all, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Event{
Event: &action.EventExecution{
Condition: &action.EventExecution_All{
All: true,
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// We want to have the same response no matter how often we call the function
Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
got, err := Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want.Details, got.Details)
// cleanup to not impact other requests
Tester.DeleteExecution(tt.ctx, t, tt.req.GetCondition())
})
}
}
func TestServer_SetExecution_Function(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
targetResp := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", domain.TargetTypeWebhook, false)
tests := []struct {
name string
ctx context.Context
req *action.SetExecutionRequest
want *action.SetExecutionResponse
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{
Condition: &action.ResponseExecution_All{All: true},
},
},
},
},
wantErr: true,
},
{
name: "no condition, error",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Response{
Response: &action.ResponseExecution{},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "function, not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Function{
Function: &action.FunctionExecution{Name: "xxx"},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
wantErr: true,
},
{
name: "function, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.SetExecutionRequest{
Condition: &action.Condition{
ConditionType: &action.Condition_Function{
Function: &action.FunctionExecution{Name: "Action.Flow.Type.ExternalAuthentication.Action.TriggerType.PostAuthentication"},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
want: &action.SetExecutionResponse{
Details: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// We want to have the same response no matter how often we call the function
Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
got, err := Tester.Client.ActionV3Alpha.SetExecution(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want.Details, got.Details)
// cleanup to not impact other requests
Tester.DeleteExecution(tt.ctx, t, tt.req.GetCondition())
})
}
}

View File

@@ -13,92 +13,94 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/zitadel/zitadel/internal/api/grpc/server/middleware"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/integration"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
resource_object "github.com/zitadel/zitadel/pkg/grpc/resources/object/v3alpha"
)
func TestServer_ExecutionTarget(t *testing.T) {
ensureFeatureEnabled(t)
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
fullMethod := "/zitadel.action.v3alpha.ActionService/GetTargetByID"
fullMethod := "/zitadel.resources.action.v3alpha.ZITADELActions/GetTarget"
tests := []struct {
name string
ctx context.Context
dep func(context.Context, *action.GetTargetByIDRequest, *action.GetTargetByIDResponse) (func(), error)
dep func(context.Context, *action.GetTargetRequest, *action.GetTargetResponse) (func(), error)
clean func(context.Context)
req *action.GetTargetByIDRequest
want *action.GetTargetByIDResponse
req *action.GetTargetRequest
want *action.GetTargetResponse
wantErr bool
}{
{
name: "GetTargetByID, request and response, ok",
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) (func(), error) {
name: "GetTarget, request and response, ok",
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) (func(), error) {
instanceID := Tester.Instance.InstanceID()
orgID := Tester.Organisation.ID
projectID := ""
userID := Tester.Users.Get(integration.FirstInstanceUsersKey, integration.IAMOwner).ID
userID := Tester.Users.Get(instanceID, integration.IAMOwner).ID
// create target for target changes
targetCreatedName := fmt.Sprint("GetTargetByID", time.Now().UnixNano()+1)
targetCreatedName := fmt.Sprint("GetTarget", time.Now().UnixNano()+1)
targetCreatedURL := "https://nonexistent"
targetCreated := Tester.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, domain.TargetTypeCall, false)
// request received by target
wantRequest := &middleware.ContextInfoRequest{FullMethod: fullMethod, InstanceID: instanceID, OrgID: orgID, ProjectID: projectID, UserID: userID, Request: request}
changedRequest := &action.GetTargetByIDRequest{TargetId: targetCreated.GetId()}
changedRequest := &action.GetTargetRequest{Id: targetCreated.GetDetails().GetId()}
// replace original request with different targetID
urlRequest, closeRequest := testServerCall(wantRequest, 0, http.StatusOK, changedRequest)
targetRequest := Tester.CreateTarget(ctx, t, "", urlRequest, domain.TargetTypeCall, false)
Tester.SetExecution(ctx, t, conditionRequestFullMethod(fullMethod), executionTargetsSingleTarget(targetRequest.GetId()))
// GetTargetByID with used target
request.TargetId = targetRequest.GetId()
Tester.SetExecution(ctx, t, conditionRequestFullMethod(fullMethod), executionTargetsSingleTarget(targetRequest.GetDetails().GetId()))
// expected response from the GetTargetByID
expectedResponse := &action.GetTargetByIDResponse{
Target: &action.Target{
TargetId: targetCreated.GetId(),
Details: targetCreated.GetDetails(),
Name: targetCreatedName,
Endpoint: targetCreatedURL,
// expected response from the GetTarget
expectedResponse := &action.GetTargetResponse{
Target: &action.GetTarget{
Config: &action.Target{
Name: targetCreatedName,
Endpoint: targetCreatedURL,
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
Details: targetCreated.GetDetails(),
},
}
// has to be set separately because of the pointers
response.Target = &action.GetTarget{
Details: targetCreated.GetDetails(),
Config: &action.Target{
Name: targetCreatedName,
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
Endpoint: targetCreatedURL,
},
}
// has to be set separately because of the pointers
response.Target = &action.Target{
TargetId: targetCreated.GetId(),
Details: targetCreated.GetDetails(),
Name: targetCreatedName,
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
}
// content for partial update
changedResponse := &action.GetTargetByIDResponse{
Target: &action.Target{
TargetId: "changed",
changedResponse := &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Id: targetCreated.GetDetails().GetId(),
},
},
}
// change partial updated content on returned response
response.Target.TargetId = changedResponse.Target.TargetId
// response received by target
wantResponse := &middleware.ContextInfoResponse{
@@ -113,7 +115,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
// after request with different targetID, return changed response
targetResponseURL, closeResponse := testServerCall(wantResponse, 0, http.StatusOK, changedResponse)
targetResponse := Tester.CreateTarget(ctx, t, "", targetResponseURL, domain.TargetTypeCall, false)
Tester.SetExecution(ctx, t, conditionResponseFullMethod(fullMethod), executionTargetsSingleTarget(targetResponse.GetId()))
Tester.SetExecution(ctx, t, conditionResponseFullMethod(fullMethod), executionTargetsSingleTarget(targetResponse.GetDetails().GetId()))
return func() {
closeRequest()
@@ -124,28 +126,39 @@ func TestServer_ExecutionTarget(t *testing.T) {
Tester.DeleteExecution(ctx, t, conditionRequestFullMethod(fullMethod))
Tester.DeleteExecution(ctx, t, conditionResponseFullMethod(fullMethod))
},
req: &action.GetTargetByIDRequest{},
want: &action.GetTargetByIDResponse{},
req: &action.GetTargetRequest{
Id: "something",
},
want: &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Id: "changed",
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
},
},
/*{
name: "GetTargetByID, request, interrupt",
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) (func(), error) {
{
name: "GetTarget, request, interrupt",
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) (func(), error) {
fullMethod := "/zitadel.action.v3alpha.ActionService/GetTargetByID"
instanceID := Tester.Instance.InstanceID()
fullMethod := "/zitadel.resources.action.v3alpha.ZITADELActions/GetTarget"
orgID := Tester.Organisation.ID
projectID := ""
userID := Tester.Users.Get(integration.FirstInstanceUsersKey, integration.IAMOwner).ID
userID := Tester.Users.Get(instanceID, integration.IAMOwner).ID
// request received by target
wantRequest := &middleware.ContextInfoRequest{FullMethod: fullMethod, InstanceID: instanceID, OrgID: orgID, ProjectID: projectID, UserID: userID, Request: request}
urlRequest, closeRequest := testServerCall(wantRequest, 0, http.StatusInternalServerError, &action.GetTargetByIDRequest{TargetId: "notchanged"})
urlRequest, closeRequest := testServerCall(wantRequest, 0, http.StatusInternalServerError, &action.GetTargetRequest{Id: "notchanged"})
targetRequest := Tester.CreateTarget(ctx, t, "", urlRequest, domain.TargetTypeCall, true)
Tester.SetExecution(ctx, t, conditionRequestFullMethod(fullMethod), executionTargetsSingleTarget(targetRequest.GetId()))
// GetTargetByID with used target
request.TargetId = targetRequest.GetId()
Tester.SetExecution(ctx, t, conditionRequestFullMethod(fullMethod), executionTargetsSingleTarget(targetRequest.GetDetails().GetId()))
// GetTarget with used target
request.Id = targetRequest.GetDetails().GetId()
return func() {
closeRequest()
@@ -154,49 +167,50 @@ func TestServer_ExecutionTarget(t *testing.T) {
clean: func(ctx context.Context) {
Tester.DeleteExecution(ctx, t, conditionRequestFullMethod(fullMethod))
},
req: &action.GetTargetByIDRequest{},
req: &action.GetTargetRequest{},
wantErr: true,
},
{
name: "GetTargetByID, response, interrupt",
ctx: CTX,
dep: func(ctx context.Context, request *action.GetTargetByIDRequest, response *action.GetTargetByIDResponse) (func(), error) {
name: "GetTarget, response, interrupt",
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) (func(), error) {
fullMethod := "/zitadel.action.v3alpha.ActionService/GetTargetByID"
instanceID := Tester.Instance.InstanceID()
fullMethod := "/zitadel.resources.action.v3alpha.ZITADELActions/GetTarget"
orgID := Tester.Organisation.ID
projectID := ""
userID := Tester.Users.Get(integration.FirstInstanceUsersKey, integration.IAMOwner).ID
userID := Tester.Users.Get(instanceID, integration.IAMOwner).ID
// create target for target changes
targetCreatedName := fmt.Sprint("GetTargetByID", time.Now().UnixNano()+1)
targetCreatedName := fmt.Sprint("GetTarget", time.Now().UnixNano()+1)
targetCreatedURL := "https://nonexistent"
targetCreated := Tester.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, domain.TargetTypeCall, false)
// GetTargetByID with used target
request.TargetId = targetCreated.GetId()
// GetTarget with used target
request.Id = targetCreated.GetDetails().GetId()
// expected response from the GetTargetByID
expectedResponse := &action.GetTargetByIDResponse{
Target: &action.Target{
TargetId: targetCreated.GetId(),
Details: targetCreated.GetDetails(),
Name: targetCreatedName,
Endpoint: targetCreatedURL,
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
// expected response from the GetTarget
expectedResponse := &action.GetTargetResponse{
Target: &action.GetTarget{
Details: targetCreated.GetDetails(),
Config: &action.Target{
Name: targetCreatedName,
Endpoint: targetCreatedURL,
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
Timeout: durationpb.New(10 * time.Second),
},
}
// content for partial update
changedResponse := &action.GetTargetByIDResponse{
Target: &action.Target{
TargetId: "changed",
changedResponse := &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Id: "changed",
},
},
}
@@ -213,7 +227,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
// after request with different targetID, return changed response
targetResponseURL, closeResponse := testServerCall(wantResponse, 0, http.StatusInternalServerError, changedResponse)
targetResponse := Tester.CreateTarget(ctx, t, "", targetResponseURL, domain.TargetTypeCall, true)
Tester.SetExecution(ctx, t, conditionResponseFullMethod(fullMethod), executionTargetsSingleTarget(targetResponse.GetId()))
Tester.SetExecution(ctx, t, conditionResponseFullMethod(fullMethod), executionTargetsSingleTarget(targetResponse.GetDetails().GetId()))
return func() {
closeResponse()
@@ -222,9 +236,9 @@ func TestServer_ExecutionTarget(t *testing.T) {
clean: func(ctx context.Context) {
Tester.DeleteExecution(ctx, t, conditionResponseFullMethod(fullMethod))
},
req: &action.GetTargetByIDRequest{},
req: &action.GetTargetRequest{},
wantErr: true,
},*/
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -234,17 +248,15 @@ func TestServer_ExecutionTarget(t *testing.T) {
defer close()
}
got, err := Client.GetTargetByID(tt.ctx, tt.req)
got, err := Tester.Client.ActionV3Alpha.GetTarget(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertDetails(t, tt.want.GetTarget(), got.GetTarget())
assert.Equal(t, tt.want.Target.TargetId, got.Target.TargetId)
integration.AssertResourceDetails(t, tt.want.GetTarget().GetDetails(), got.GetTarget().GetDetails())
require.Equal(t, tt.want.GetTarget().GetConfig(), got.GetTarget().GetConfig())
if tt.clean != nil {
tt.clean(tt.ctx)
}

View File

@@ -6,20 +6,50 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
"github.com/zitadel/zitadel/internal/api/grpc/object/v2"
resource_object "github.com/zitadel/zitadel/internal/api/grpc/resources/object/v3alpha"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
)
func (s *Server) ListTargets(ctx context.Context, req *action.ListTargetsRequest) (*action.ListTargetsResponse, error) {
if err := checkExecutionEnabled(ctx); err != nil {
const (
conditionIDAllSegmentCount = 0
conditionIDRequestResponseServiceSegmentCount = 1
conditionIDRequestResponseMethodSegmentCount = 2
conditionIDEventGroupSegmentCount = 1
)
func (s *Server) GetTarget(ctx context.Context, req *action.GetTargetRequest) (*action.GetTargetResponse, error) {
if err := checkActionsEnabled(ctx); err != nil {
return nil, err
}
queries, err := listTargetsRequestToModel(req)
resp, err := s.query.GetTargetByID(ctx, req.GetId())
if err != nil {
return nil, err
}
return &action.GetTargetResponse{
Target: targetToPb(resp),
}, nil
}
type InstanceContext interface {
GetInstanceId() string
GetInstanceDomain() string
}
type Context interface {
GetOwner() InstanceContext
}
func (s *Server) SearchTargets(ctx context.Context, req *action.SearchTargetsRequest) (*action.SearchTargetsResponse, error) {
if err := checkActionsEnabled(ctx); err != nil {
return nil, err
}
queries, err := s.searchTargetsRequestToModel(req)
if err != nil {
return nil, err
}
@@ -27,15 +57,66 @@ func (s *Server) ListTargets(ctx context.Context, req *action.ListTargetsRequest
if err != nil {
return nil, err
}
return &action.ListTargetsResponse{
return &action.SearchTargetsResponse{
Result: targetsToPb(resp.Targets),
Details: object.ToListDetails(resp.SearchResponse),
Details: resource_object.ToSearchDetailsPb(queries.SearchRequest, resp.SearchResponse),
}, nil
}
func listTargetsRequestToModel(req *action.ListTargetsRequest) (*query.TargetSearchQueries, error) {
offset, limit, asc := object.ListQueryToQuery(req.Query)
queries, err := targetQueriesToQuery(req.Queries)
func (s *Server) SearchExecutions(ctx context.Context, req *action.SearchExecutionsRequest) (*action.SearchExecutionsResponse, error) {
if err := checkActionsEnabled(ctx); err != nil {
return nil, err
}
queries, err := s.searchExecutionsRequestToModel(req)
if err != nil {
return nil, err
}
resp, err := s.query.SearchExecutions(ctx, queries)
if err != nil {
return nil, err
}
return &action.SearchExecutionsResponse{
Result: executionsToPb(resp.Executions),
Details: resource_object.ToSearchDetailsPb(queries.SearchRequest, resp.SearchResponse),
}, nil
}
func targetsToPb(targets []*query.Target) []*action.GetTarget {
t := make([]*action.GetTarget, len(targets))
for i, target := range targets {
t[i] = targetToPb(target)
}
return t
}
func targetToPb(t *query.Target) *action.GetTarget {
target := &action.GetTarget{
Details: resource_object.DomainToDetailsPb(&t.ObjectDetails, object.OwnerType_OWNER_TYPE_INSTANCE, t.ResourceOwner),
Config: &action.Target{
Name: t.Name,
Timeout: durationpb.New(t.Timeout),
Endpoint: t.Endpoint,
},
}
switch t.TargetType {
case domain.TargetTypeWebhook:
target.Config.TargetType = &action.Target_RestWebhook{RestWebhook: &action.SetRESTWebhook{InterruptOnError: t.InterruptOnError}}
case domain.TargetTypeCall:
target.Config.TargetType = &action.Target_RestCall{RestCall: &action.SetRESTCall{InterruptOnError: t.InterruptOnError}}
case domain.TargetTypeAsync:
target.Config.TargetType = &action.Target_RestAsync{RestAsync: &action.SetRESTAsync{}}
default:
target.Config.TargetType = nil
}
return target
}
func (s *Server) searchTargetsRequestToModel(req *action.SearchTargetsRequest) (*query.TargetSearchQueries, error) {
offset, limit, asc, err := resource_object.SearchQueryPbToQuery(s.systemDefaults, req.Query)
if err != nil {
return nil, err
}
queries, err := targetQueriesToQuery(req.Filters)
if err != nil {
return nil, err
}
@@ -50,35 +131,10 @@ func listTargetsRequestToModel(req *action.ListTargetsRequest) (*query.TargetSea
}, nil
}
func targetFieldNameToSortingColumn(field action.TargetFieldName) query.Column {
switch field {
case action.TargetFieldName_FIELD_NAME_UNSPECIFIED:
return query.TargetColumnID
case action.TargetFieldName_FIELD_NAME_ID:
return query.TargetColumnID
case action.TargetFieldName_FIELD_NAME_CREATION_DATE:
return query.TargetColumnCreationDate
case action.TargetFieldName_FIELD_NAME_CHANGE_DATE:
return query.TargetColumnChangeDate
case action.TargetFieldName_FIELD_NAME_NAME:
return query.TargetColumnName
case action.TargetFieldName_FIELD_NAME_TARGET_TYPE:
return query.TargetColumnTargetType
case action.TargetFieldName_FIELD_NAME_URL:
return query.TargetColumnURL
case action.TargetFieldName_FIELD_NAME_TIMEOUT:
return query.TargetColumnTimeout
case action.TargetFieldName_FIELD_NAME_INTERRUPT_ON_ERROR:
return query.TargetColumnInterruptOnError
default:
return query.TargetColumnID
}
}
func targetQueriesToQuery(queries []*action.TargetSearchQuery) (_ []query.SearchQuery, err error) {
func targetQueriesToQuery(queries []*action.TargetSearchFilter) (_ []query.SearchQuery, err error) {
q := make([]query.SearchQuery, len(queries))
for i, query := range queries {
q[i], err = targetQueryToQuery(query)
for i, qry := range queries {
q[i], err = targetQueryToQuery(qry)
if err != nil {
return nil, err
}
@@ -86,105 +142,94 @@ func targetQueriesToQuery(queries []*action.TargetSearchQuery) (_ []query.Search
return q, nil
}
func targetQueryToQuery(query *action.TargetSearchQuery) (query.SearchQuery, error) {
switch q := query.Query.(type) {
case *action.TargetSearchQuery_TargetNameQuery:
return targetNameQueryToQuery(q.TargetNameQuery)
case *action.TargetSearchQuery_InTargetIdsQuery:
return targetInTargetIdsQueryToQuery(q.InTargetIdsQuery)
func targetQueryToQuery(filter *action.TargetSearchFilter) (query.SearchQuery, error) {
switch q := filter.Filter.(type) {
case *action.TargetSearchFilter_TargetNameFilter:
return targetNameQueryToQuery(q.TargetNameFilter)
case *action.TargetSearchFilter_InTargetIdsFilter:
return targetInTargetIdsQueryToQuery(q.InTargetIdsFilter)
default:
return nil, zerrors.ThrowInvalidArgument(nil, "GRPC-vR9nC", "List.Query.Invalid")
}
}
func targetNameQueryToQuery(q *action.TargetNameQuery) (query.SearchQuery, error) {
return query.NewTargetNameSearchQuery(object.TextMethodToQuery(q.Method), q.GetTargetName())
func targetNameQueryToQuery(q *action.TargetNameFilter) (query.SearchQuery, error) {
return query.NewTargetNameSearchQuery(resource_object.TextMethodPbToQuery(q.Method), q.GetTargetName())
}
func targetInTargetIdsQueryToQuery(q *action.InTargetIDsQuery) (query.SearchQuery, error) {
func targetInTargetIdsQueryToQuery(q *action.InTargetIDsFilter) (query.SearchQuery, error) {
return query.NewTargetInIDsSearchQuery(q.GetTargetIds())
}
func (s *Server) GetTargetByID(ctx context.Context, req *action.GetTargetByIDRequest) (_ *action.GetTargetByIDResponse, err error) {
if err := checkExecutionEnabled(ctx); err != nil {
return nil, err
// targetFieldNameToSortingColumn defaults to the creation date because this ensures deterministic pagination
func targetFieldNameToSortingColumn(field *action.TargetFieldName) query.Column {
if field == nil {
return query.TargetColumnCreationDate
}
resp, err := s.query.GetTargetByID(ctx, req.GetTargetId())
if err != nil {
return nil, err
}
return &action.GetTargetByIDResponse{
Target: targetToPb(resp),
}, nil
}
func targetsToPb(targets []*query.Target) []*action.Target {
t := make([]*action.Target, len(targets))
for i, target := range targets {
t[i] = targetToPb(target)
}
return t
}
func targetToPb(t *query.Target) *action.Target {
target := &action.Target{
Details: object.DomainToDetailsPb(&t.ObjectDetails),
TargetId: t.ID,
Name: t.Name,
Timeout: durationpb.New(t.Timeout),
Endpoint: t.Endpoint,
}
switch t.TargetType {
case domain.TargetTypeWebhook:
target.TargetType = &action.Target_RestWebhook{RestWebhook: &action.SetRESTWebhook{InterruptOnError: t.InterruptOnError}}
case domain.TargetTypeCall:
target.TargetType = &action.Target_RestCall{RestCall: &action.SetRESTCall{InterruptOnError: t.InterruptOnError}}
case domain.TargetTypeAsync:
target.TargetType = &action.Target_RestAsync{RestAsync: &action.SetRESTAsync{}}
switch *field {
case action.TargetFieldName_TARGET_FIELD_NAME_UNSPECIFIED:
return query.TargetColumnID
case action.TargetFieldName_TARGET_FIELD_NAME_ID:
return query.TargetColumnID
case action.TargetFieldName_TARGET_FIELD_NAME_CREATED_DATE:
return query.TargetColumnCreationDate
case action.TargetFieldName_TARGET_FIELD_NAME_CHANGED_DATE:
return query.TargetColumnChangeDate
case action.TargetFieldName_TARGET_FIELD_NAME_NAME:
return query.TargetColumnName
case action.TargetFieldName_TARGET_FIELD_NAME_TARGET_TYPE:
return query.TargetColumnTargetType
case action.TargetFieldName_TARGET_FIELD_NAME_URL:
return query.TargetColumnURL
case action.TargetFieldName_TARGET_FIELD_NAME_TIMEOUT:
return query.TargetColumnTimeout
case action.TargetFieldName_TARGET_FIELD_NAME_INTERRUPT_ON_ERROR:
return query.TargetColumnInterruptOnError
default:
target.TargetType = nil
return query.TargetColumnCreationDate
}
return target
}
func (s *Server) ListExecutions(ctx context.Context, req *action.ListExecutionsRequest) (*action.ListExecutionsResponse, error) {
if err := checkExecutionEnabled(ctx); err != nil {
return nil, err
// executionFieldNameToSortingColumn defaults to the creation date because this ensures deterministic pagination
func executionFieldNameToSortingColumn(field *action.ExecutionFieldName) query.Column {
if field == nil {
return query.ExecutionColumnCreationDate
}
switch *field {
case action.ExecutionFieldName_EXECUTION_FIELD_NAME_UNSPECIFIED:
return query.ExecutionColumnID
case action.ExecutionFieldName_EXECUTION_FIELD_NAME_ID:
return query.ExecutionColumnID
case action.ExecutionFieldName_EXECUTION_FIELD_NAME_CREATED_DATE:
return query.ExecutionColumnCreationDate
case action.ExecutionFieldName_EXECUTION_FIELD_NAME_CHANGED_DATE:
return query.ExecutionColumnChangeDate
default:
return query.ExecutionColumnCreationDate
}
}
queries, err := listExecutionsRequestToModel(req)
func (s *Server) searchExecutionsRequestToModel(req *action.SearchExecutionsRequest) (*query.ExecutionSearchQueries, error) {
offset, limit, asc, err := resource_object.SearchQueryPbToQuery(s.systemDefaults, req.Query)
if err != nil {
return nil, err
}
resp, err := s.query.SearchExecutions(ctx, queries)
if err != nil {
return nil, err
}
return &action.ListExecutionsResponse{
Result: executionsToPb(resp.Executions),
Details: object.ToListDetails(resp.SearchResponse),
}, nil
}
func listExecutionsRequestToModel(req *action.ListExecutionsRequest) (*query.ExecutionSearchQueries, error) {
offset, limit, asc := object.ListQueryToQuery(req.Query)
queries, err := executionQueriesToQuery(req.Queries)
queries, err := executionQueriesToQuery(req.Filters)
if err != nil {
return nil, err
}
return &query.ExecutionSearchQueries{
SearchRequest: query.SearchRequest{
Offset: offset,
Limit: limit,
Asc: asc,
Offset: offset,
Limit: limit,
Asc: asc,
SortingColumn: executionFieldNameToSortingColumn(req.SortingColumn),
},
Queries: queries,
}, nil
}
func executionQueriesToQuery(queries []*action.SearchQuery) (_ []query.SearchQuery, err error) {
func executionQueriesToQuery(queries []*action.ExecutionSearchFilter) (_ []query.SearchQuery, err error) {
q := make([]query.SearchQuery, len(queries))
for i, query := range queries {
q[i], err = executionQueryToQuery(query)
@@ -195,26 +240,26 @@ func executionQueriesToQuery(queries []*action.SearchQuery) (_ []query.SearchQue
return q, nil
}
func executionQueryToQuery(searchQuery *action.SearchQuery) (query.SearchQuery, error) {
switch q := searchQuery.Query.(type) {
case *action.SearchQuery_InConditionsQuery:
return inConditionsQueryToQuery(q.InConditionsQuery)
case *action.SearchQuery_ExecutionTypeQuery:
return executionTypeToQuery(q.ExecutionTypeQuery)
case *action.SearchQuery_IncludeQuery:
include, err := conditionToInclude(q.IncludeQuery.GetInclude())
func executionQueryToQuery(searchQuery *action.ExecutionSearchFilter) (query.SearchQuery, error) {
switch q := searchQuery.Filter.(type) {
case *action.ExecutionSearchFilter_InConditionsFilter:
return inConditionsQueryToQuery(q.InConditionsFilter)
case *action.ExecutionSearchFilter_ExecutionTypeFilter:
return executionTypeToQuery(q.ExecutionTypeFilter)
case *action.ExecutionSearchFilter_IncludeFilter:
include, err := conditionToInclude(q.IncludeFilter.GetInclude())
if err != nil {
return nil, err
}
return query.NewIncludeSearchQuery(include)
case *action.SearchQuery_TargetQuery:
return query.NewTargetSearchQuery(q.TargetQuery.GetTargetId())
case *action.ExecutionSearchFilter_TargetFilter:
return query.NewTargetSearchQuery(q.TargetFilter.GetTargetId())
default:
return nil, zerrors.ThrowInvalidArgument(nil, "GRPC-vR9nC", "List.Query.Invalid")
}
}
func executionTypeToQuery(q *action.ExecutionTypeQuery) (query.SearchQuery, error) {
func executionTypeToQuery(q *action.ExecutionTypeFilter) (query.SearchQuery, error) {
switch q.ExecutionType {
case action.ExecutionType_EXECUTION_TYPE_UNSPECIFIED:
return query.NewExecutionTypeSearchQuery(domain.ExecutionTypeUnspecified)
@@ -231,7 +276,7 @@ func executionTypeToQuery(q *action.ExecutionTypeQuery) (query.SearchQuery, erro
}
}
func inConditionsQueryToQuery(q *action.InConditionsQuery) (query.SearchQuery, error) {
func inConditionsQueryToQuery(q *action.InConditionsFilter) (query.SearchQuery, error) {
values := make([]string, len(q.GetConditions()))
for i, condition := range q.GetConditions() {
id, err := conditionToID(condition)
@@ -273,15 +318,15 @@ func conditionToID(q *action.Condition) (string, error) {
}
}
func executionsToPb(executions []*query.Execution) []*action.Execution {
e := make([]*action.Execution, len(executions))
func executionsToPb(executions []*query.Execution) []*action.GetExecution {
e := make([]*action.GetExecution, len(executions))
for i, execution := range executions {
e[i] = executionToPb(execution)
}
return e
}
func executionToPb(e *query.Execution) *action.Execution {
func executionToPb(e *query.Execution) *action.GetExecution {
targets := make([]*action.ExecutionTargetType, len(e.Targets))
for i := range e.Targets {
switch e.Targets[i].Type {
@@ -296,10 +341,11 @@ func executionToPb(e *query.Execution) *action.Execution {
}
}
return &action.Execution{
Details: object.DomainToDetailsPb(&e.ObjectDetails),
Condition: executionIDToCondition(e.ID),
Targets: targets,
return &action.GetExecution{
Details: resource_object.DomainToDetailsPb(&e.ObjectDetails, object.OwnerType_OWNER_TYPE_INSTANCE, e.ResourceOwner),
Execution: &action.Execution{
Targets: targets,
},
}
}
@@ -321,11 +367,11 @@ func executionIDToCondition(include string) *action.Condition {
func includeRequestToCondition(id string) *action.Condition {
switch strings.Count(id, "/") {
case 2:
case conditionIDRequestResponseMethodSegmentCount:
return &action.Condition{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_Method{Method: id}}}}
case 1:
case conditionIDRequestResponseServiceSegmentCount:
return &action.Condition{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_Service{Service: strings.TrimPrefix(id, "/")}}}}
case 0:
case conditionIDAllSegmentCount:
return &action.Condition{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_All{All: true}}}}
default:
return nil
@@ -333,11 +379,11 @@ func includeRequestToCondition(id string) *action.Condition {
}
func includeResponseToCondition(id string) *action.Condition {
switch strings.Count(id, "/") {
case 2:
case conditionIDRequestResponseMethodSegmentCount:
return &action.Condition{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_Method{Method: id}}}}
case 1:
case conditionIDRequestResponseServiceSegmentCount:
return &action.Condition{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_Service{Service: strings.TrimPrefix(id, "/")}}}}
case 0:
case conditionIDAllSegmentCount:
return &action.Condition{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_All{All: true}}}}
default:
return nil
@@ -346,13 +392,13 @@ func includeResponseToCondition(id string) *action.Condition {
func includeEventToCondition(id string) *action.Condition {
switch strings.Count(id, "/") {
case 1:
case conditionIDEventGroupSegmentCount:
if strings.HasSuffix(id, command.EventGroupSuffix) {
return &action.Condition{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_Group{Group: strings.TrimSuffix(strings.TrimPrefix(id, "/"), command.EventGroupSuffix)}}}}
} else {
return &action.Condition{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_Event{Event: strings.TrimPrefix(id, "/")}}}}
}
case 0:
case conditionIDAllSegmentCount:
return &action.Condition{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_All{All: true}}}}
default:
return nil

View File

@@ -0,0 +1,898 @@
//go:build integration
package action_test
import (
"context"
"fmt"
"reflect"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/integration"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
resource_object "github.com/zitadel/zitadel/pkg/grpc/resources/object/v3alpha"
)
func TestServer_GetTarget(t *testing.T) {
_, _, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
type args struct {
ctx context.Context
dep func(context.Context, *action.GetTargetRequest, *action.GetTargetResponse) error
req *action.GetTargetRequest
}
tests := []struct {
name string
args args
want *action.GetTargetResponse
wantErr bool
}{
{
name: "missing permission",
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.GetTargetRequest{},
},
wantErr: true,
},
{
name: "not found",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.GetTargetRequest{Id: "notexisting"},
},
wantErr: true,
},
{
name: "get, ok",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, false)
request.Id = resp.GetDetails().GetId()
response.Target.Config.Name = name
response.Target.Details = resp.GetDetails()
return nil
},
req: &action.GetTargetRequest{},
},
want: &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
{
name: "get, async, ok",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeAsync, false)
request.Id = resp.GetDetails().GetId()
response.Target.Config.Name = name
response.Target.Details = resp.GetDetails()
return nil
},
req: &action.GetTargetRequest{},
},
want: &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
{
name: "get, webhook interruptOnError, ok",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, true)
request.Id = resp.GetDetails().GetId()
response.Target.Config.Name = name
response.Target.Details = resp.GetDetails()
return nil
},
req: &action.GetTargetRequest{},
},
want: &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
{
name: "get, call, ok",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeCall, false)
request.Id = resp.GetDetails().GetId()
response.Target.Config.Name = name
response.Target.Details = resp.GetDetails()
return nil
},
req: &action.GetTargetRequest{},
},
want: &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
{
name: "get, call interruptOnError, ok",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeCall, true)
request.Id = resp.GetDetails().GetId()
response.Target.Config.Name = name
response.Target.Details = resp.GetDetails()
return nil
},
req: &action.GetTargetRequest{},
},
want: &action.GetTargetResponse{
Target: &action.GetTarget{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.dep != nil {
err := tt.args.dep(tt.args.ctx, tt.args.req, tt.want)
require.NoError(t, err)
}
got, getErr := Tester.Client.ActionV3Alpha.GetTarget(tt.args.ctx, tt.args.req)
if tt.wantErr {
assert.Error(t, getErr, "Error: "+getErr.Error())
} else {
assert.NoError(t, getErr)
wantTarget := tt.want.GetTarget()
gotTarget := got.GetTarget()
integration.AssertResourceDetails(t, wantTarget.GetDetails(), gotTarget.GetDetails())
assert.Equal(t, wantTarget.GetConfig(), gotTarget.GetConfig())
}
})
}
}
func TestServer_ListTargets(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
type args struct {
ctx context.Context
dep func(context.Context, *action.SearchTargetsRequest, *action.SearchTargetsResponse) error
req *action.SearchTargetsRequest
}
tests := []struct {
name string
args args
want *action.SearchTargetsResponse
wantErr bool
}{
{
name: "missing permission",
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.SearchTargetsRequest{},
},
wantErr: true,
},
{
name: "list, not found",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.SearchTargetsRequest{
Filters: []*action.TargetSearchFilter{
{Filter: &action.TargetSearchFilter_InTargetIdsFilter{
InTargetIdsFilter: &action.InTargetIDsFilter{
TargetIds: []string{"notfound"},
},
},
},
},
},
},
want: &action.SearchTargetsResponse{
Details: &resource_object.ListDetails{
TotalResult: 0,
AppliedLimit: 100,
},
Result: []*action.GetTarget{},
},
},
{
name: "list single id",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchTargetsRequest, response *action.SearchTargetsResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, false)
request.Filters[0].Filter = &action.TargetSearchFilter_InTargetIdsFilter{
InTargetIdsFilter: &action.InTargetIDsFilter{
TargetIds: []string{resp.GetDetails().GetId()},
},
}
response.Details.Timestamp = resp.GetDetails().GetChanged()
response.Result[0].Details = resp.GetDetails()
response.Result[0].Config.Name = name
return nil
},
req: &action.SearchTargetsRequest{
Filters: []*action.TargetSearchFilter{{}},
},
},
want: &action.SearchTargetsResponse{
Details: &resource_object.ListDetails{
TotalResult: 1,
AppliedLimit: 100,
},
Result: []*action.GetTarget{
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
}, {
name: "list single name",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchTargetsRequest, response *action.SearchTargetsResponse) error {
name := fmt.Sprint(time.Now().UnixNano() + 1)
resp := Tester.CreateTarget(ctx, t, name, "https://example.com", domain.TargetTypeWebhook, false)
request.Filters[0].Filter = &action.TargetSearchFilter_TargetNameFilter{
TargetNameFilter: &action.TargetNameFilter{
TargetName: name,
},
}
response.Details.Timestamp = resp.GetDetails().GetChanged()
response.Result[0].Details = resp.GetDetails()
response.Result[0].Config.Name = name
return nil
},
req: &action.SearchTargetsRequest{
Filters: []*action.TargetSearchFilter{{}},
},
},
want: &action.SearchTargetsResponse{
Details: &resource_object.ListDetails{
TotalResult: 1,
AppliedLimit: 100,
},
Result: []*action.GetTarget{
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
},
{
name: "list multiple id",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchTargetsRequest, response *action.SearchTargetsResponse) error {
name1 := fmt.Sprint(time.Now().UnixNano() + 1)
name2 := fmt.Sprint(time.Now().UnixNano() + 3)
name3 := fmt.Sprint(time.Now().UnixNano() + 5)
resp1 := Tester.CreateTarget(ctx, t, name1, "https://example.com", domain.TargetTypeWebhook, false)
resp2 := Tester.CreateTarget(ctx, t, name2, "https://example.com", domain.TargetTypeCall, true)
resp3 := Tester.CreateTarget(ctx, t, name3, "https://example.com", domain.TargetTypeAsync, false)
request.Filters[0].Filter = &action.TargetSearchFilter_InTargetIdsFilter{
InTargetIdsFilter: &action.InTargetIDsFilter{
TargetIds: []string{resp1.GetDetails().GetId(), resp2.GetDetails().GetId(), resp3.GetDetails().GetId()},
},
}
response.Details.Timestamp = resp3.GetDetails().GetChanged()
response.Result[0].Details = resp1.GetDetails()
response.Result[0].Config.Name = name1
response.Result[1].Details = resp2.GetDetails()
response.Result[1].Config.Name = name2
response.Result[2].Details = resp3.GetDetails()
response.Result[2].Config.Name = name3
return nil
},
req: &action.SearchTargetsRequest{
Filters: []*action.TargetSearchFilter{{}},
},
},
want: &action.SearchTargetsResponse{
Details: &resource_object.ListDetails{
TotalResult: 3,
AppliedLimit: 100,
},
Result: []*action.GetTarget{
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
},
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
Config: &action.Target{
Endpoint: "https://example.com",
TargetType: &action.Target_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.dep != nil {
err := tt.args.dep(tt.args.ctx, tt.args.req, tt.want)
require.NoError(t, err)
}
retryDuration := 5 * time.Second
if ctxDeadline, ok := isolatedIAMOwnerCTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, listErr := Tester.Client.ActionV3Alpha.SearchTargets(tt.args.ctx, tt.args.req)
if tt.wantErr {
assert.Error(ttt, listErr, "Error: "+listErr.Error())
} else {
assert.NoError(ttt, listErr)
}
if listErr != nil {
return
}
// always first check length, otherwise its failed anyway
assert.Len(ttt, got.Result, len(tt.want.Result))
for i := range tt.want.Result {
integration.AssertResourceDetails(t, tt.want.Result[i].GetDetails(), got.Result[i].GetDetails())
assert.Equal(ttt, tt.want.Result[i].GetConfig(), got.Result[i].GetConfig())
}
integration.AssertResourceListDetails(t, tt.want, got)
}, retryDuration, time.Millisecond*100, "timeout waiting for expected execution result")
})
}
}
func TestServer_SearchExecutions(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
targetResp := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false)
type args struct {
ctx context.Context
dep func(context.Context, *action.SearchExecutionsRequest, *action.SearchExecutionsResponse) error
req *action.SearchExecutionsRequest
}
tests := []struct {
name string
args args
want *action.SearchExecutionsResponse
wantErr bool
}{
{
name: "missing permission",
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.SearchExecutionsRequest{},
},
wantErr: true,
},
{
name: "list request single condition",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchExecutionsRequest, response *action.SearchExecutionsResponse) error {
cond := request.Filters[0].GetInConditionsFilter().GetConditions()[0]
resp := Tester.SetExecution(ctx, t, cond, executionTargetsSingleTarget(targetResp.GetDetails().GetId()))
response.Details.Timestamp = resp.GetDetails().GetChanged()
// Set expected response with used values for SetExecution
response.Result[0].Details = resp.GetDetails()
response.Result[0].Condition = cond
return nil
},
req: &action.SearchExecutionsRequest{
Filters: []*action.ExecutionSearchFilter{{
Filter: &action.ExecutionSearchFilter_InConditionsFilter{
InConditionsFilter: &action.InConditionsFilter{
Conditions: []*action.Condition{{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/GetSession",
},
},
},
}},
},
},
}},
},
},
want: &action.SearchExecutionsResponse{
Details: &resource_object.ListDetails{
TotalResult: 1,
AppliedLimit: 100,
},
Result: []*action.GetExecution{
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Condition: &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/GetSession",
},
},
},
},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(targetResp.GetDetails().GetId()),
},
},
},
},
},
{
name: "list request single target",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchExecutionsRequest, response *action.SearchExecutionsResponse) error {
target := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false)
// add target as Filter to the request
request.Filters[0] = &action.ExecutionSearchFilter{
Filter: &action.ExecutionSearchFilter_TargetFilter{
TargetFilter: &action.TargetFilter{
TargetId: target.GetDetails().GetId(),
},
},
}
cond := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.management.v1.ManagementService/UpdateAction",
},
},
},
}
targets := executionTargetsSingleTarget(target.GetDetails().GetId())
resp := Tester.SetExecution(ctx, t, cond, targets)
response.Details.Timestamp = resp.GetDetails().GetChanged()
response.Result[0].Details = resp.GetDetails()
response.Result[0].Condition = cond
response.Result[0].Execution.Targets = targets
return nil
},
req: &action.SearchExecutionsRequest{
Filters: []*action.ExecutionSearchFilter{{}},
},
},
want: &action.SearchExecutionsResponse{
Details: &resource_object.ListDetails{
TotalResult: 1,
AppliedLimit: 100,
},
Result: []*action.GetExecution{
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
Condition: &action.Condition{},
Execution: &action.Execution{
Targets: executionTargetsSingleTarget(""),
},
},
},
},
}, {
name: "list request single include",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchExecutionsRequest, response *action.SearchExecutionsResponse) error {
cond := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.management.v1.ManagementService/GetAction",
},
},
},
}
Tester.SetExecution(ctx, t, cond, executionTargetsSingleTarget(targetResp.GetDetails().GetId()))
request.Filters[0].GetIncludeFilter().Include = cond
includeCond := &action.Condition{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.management.v1.ManagementService/ListActions",
},
},
},
}
includeTargets := executionTargetsSingleInclude(cond)
resp2 := Tester.SetExecution(ctx, t, includeCond, includeTargets)
response.Details.Timestamp = resp2.GetDetails().GetChanged()
response.Result[0].Details = resp2.GetDetails()
response.Result[0].Condition = includeCond
response.Result[0].Execution = &action.Execution{
Targets: includeTargets,
}
return nil
},
req: &action.SearchExecutionsRequest{
Filters: []*action.ExecutionSearchFilter{{
Filter: &action.ExecutionSearchFilter_IncludeFilter{
IncludeFilter: &action.IncludeFilter{},
},
}},
},
},
want: &action.SearchExecutionsResponse{
Details: &resource_object.ListDetails{
TotalResult: 1,
AppliedLimit: 100,
},
Result: []*action.GetExecution{
{
Details: &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
},
},
},
},
},
{
name: "list multiple conditions",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchExecutionsRequest, response *action.SearchExecutionsResponse) error {
cond1 := request.Filters[0].GetInConditionsFilter().GetConditions()[0]
targets1 := executionTargetsSingleTarget(targetResp.GetDetails().GetId())
resp1 := Tester.SetExecution(ctx, t, cond1, targets1)
response.Result[0].Details = resp1.GetDetails()
response.Result[0].Condition = cond1
response.Result[0].Execution = &action.Execution{
Targets: targets1,
}
cond2 := request.Filters[0].GetInConditionsFilter().GetConditions()[1]
targets2 := executionTargetsSingleTarget(targetResp.GetDetails().GetId())
resp2 := Tester.SetExecution(ctx, t, cond2, targets2)
response.Result[1].Details = resp2.GetDetails()
response.Result[1].Condition = cond2
response.Result[1].Execution = &action.Execution{
Targets: targets2,
}
cond3 := request.Filters[0].GetInConditionsFilter().GetConditions()[2]
targets3 := executionTargetsSingleTarget(targetResp.GetDetails().GetId())
resp3 := Tester.SetExecution(ctx, t, cond3, targets3)
response.Result[2].Details = resp3.GetDetails()
response.Result[2].Condition = cond3
response.Result[2].Execution = &action.Execution{
Targets: targets3,
}
response.Details.Timestamp = resp3.GetDetails().GetChanged()
return nil
},
req: &action.SearchExecutionsRequest{
Filters: []*action.ExecutionSearchFilter{{
Filter: &action.ExecutionSearchFilter_InConditionsFilter{
InConditionsFilter: &action.InConditionsFilter{
Conditions: []*action.Condition{
{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/GetSession",
},
},
},
},
{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/CreateSession",
},
},
},
},
{
ConditionType: &action.Condition_Request{
Request: &action.RequestExecution{
Condition: &action.RequestExecution_Method{
Method: "/zitadel.session.v2.SessionService/SetSession",
},
},
},
},
},
},
},
}},
},
},
want: &action.SearchExecutionsResponse{
Details: &resource_object.ListDetails{
TotalResult: 3,
AppliedLimit: 100,
},
Result: []*action.GetExecution{
{
Details: &resource_object.Details{
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
}, {
Details: &resource_object.Details{
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
}, {
Details: &resource_object.Details{
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
},
},
},
},
{
name: "list multiple conditions all types",
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.SearchExecutionsRequest, response *action.SearchExecutionsResponse) error {
targets := executionTargetsSingleTarget(targetResp.GetDetails().GetId())
for i, cond := range request.Filters[0].GetInConditionsFilter().GetConditions() {
resp := Tester.SetExecution(ctx, t, cond, targets)
response.Result[i].Details = resp.GetDetails()
response.Result[i].Condition = cond
response.Result[i].Execution = &action.Execution{
Targets: targets,
}
// filled with info of last sequence
response.Details.Timestamp = resp.GetDetails().GetChanged()
}
return nil
},
req: &action.SearchExecutionsRequest{
Filters: []*action.ExecutionSearchFilter{{
Filter: &action.ExecutionSearchFilter_InConditionsFilter{
InConditionsFilter: &action.InConditionsFilter{
Conditions: []*action.Condition{
{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_Method{Method: "/zitadel.session.v2.SessionService/GetSession"}}}},
{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_Service{Service: "zitadel.session.v2.SessionService"}}}},
{ConditionType: &action.Condition_Request{Request: &action.RequestExecution{Condition: &action.RequestExecution_All{All: true}}}},
{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_Method{Method: "/zitadel.session.v2.SessionService/GetSession"}}}},
{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_Service{Service: "zitadel.session.v2.SessionService"}}}},
{ConditionType: &action.Condition_Response{Response: &action.ResponseExecution{Condition: &action.ResponseExecution_All{All: true}}}},
{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_Event{Event: "user.added"}}}},
{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_Group{Group: "user"}}}},
{ConditionType: &action.Condition_Event{Event: &action.EventExecution{Condition: &action.EventExecution_All{All: true}}}},
{ConditionType: &action.Condition_Function{Function: &action.FunctionExecution{Name: "Action.Flow.Type.ExternalAuthentication.Action.TriggerType.PostAuthentication"}}},
},
},
},
}},
},
},
want: &action.SearchExecutionsResponse{
Details: &resource_object.ListDetails{
TotalResult: 10,
AppliedLimit: 100,
},
Result: []*action.GetExecution{
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
{Details: &resource_object.Details{Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID}}},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.args.dep != nil {
err := tt.args.dep(tt.args.ctx, tt.args.req, tt.want)
require.NoError(t, err)
}
retryDuration := 5 * time.Second
if ctxDeadline, ok := isolatedIAMOwnerCTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, listErr := Tester.Client.ActionV3Alpha.SearchExecutions(tt.args.ctx, tt.args.req)
if tt.wantErr {
assert.Error(t, listErr, "Error: "+listErr.Error())
} else {
assert.NoError(t, listErr)
}
if listErr != nil {
return
}
// always first check length, otherwise its failed anyway
assert.Len(t, got.Result, len(tt.want.Result))
for i := range tt.want.Result {
// as not sorted, all elements have to be checked
// workaround as oneof elements can only be checked with assert.EqualExportedValues()
if j, found := containExecution(got.Result, tt.want.Result[i]); found {
assert.EqualExportedValues(t, tt.want.Result[i], got.Result[j])
}
}
integration.AssertResourceListDetails(t, tt.want, got)
}, retryDuration, time.Millisecond*100, "timeout waiting for expected execution result")
})
}
}
func containExecution(executionList []*action.GetExecution, execution *action.GetExecution) (int, bool) {
for i, exec := range executionList {
if reflect.DeepEqual(exec.Details, execution.Details) {
return i, true
}
}
return 0, false
}

View File

@@ -8,15 +8,17 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/server"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/config/systemdefaults"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
)
var _ action.ActionServiceServer = (*Server)(nil)
var _ action.ZITADELActionsServer = (*Server)(nil)
type Server struct {
action.UnimplementedActionServiceServer
action.UnimplementedZITADELActionsServer
systemDefaults systemdefaults.SystemDefaults
command *command.Commands
query *query.Queries
ListActionFunctions func() []string
@@ -27,6 +29,7 @@ type Server struct {
type Config struct{}
func CreateServer(
systemDefaults systemdefaults.SystemDefaults,
command *command.Commands,
query *query.Queries,
listActionFunctions func() []string,
@@ -34,6 +37,7 @@ func CreateServer(
listGRPCServices func() []string,
) *Server {
return &Server{
systemDefaults: systemDefaults,
command: command,
query: query,
ListActionFunctions: listActionFunctions,
@@ -43,26 +47,26 @@ func CreateServer(
}
func (s *Server) RegisterServer(grpcServer *grpc.Server) {
action.RegisterActionServiceServer(grpcServer, s)
action.RegisterZITADELActionsServer(grpcServer, s)
}
func (s *Server) AppName() string {
return action.ActionService_ServiceDesc.ServiceName
return action.ZITADELActions_ServiceDesc.ServiceName
}
func (s *Server) MethodPrefix() string {
return action.ActionService_ServiceDesc.ServiceName
return action.ZITADELActions_ServiceDesc.ServiceName
}
func (s *Server) AuthMethods() authz.MethodMapping {
return action.ActionService_AuthMethods
return action.ZITADELActions_AuthMethods
}
func (s *Server) RegisterGateway() server.RegisterGatewayFunc {
return action.RegisterActionServiceHandler
return action.RegisterZITADELActionsHandler
}
func checkExecutionEnabled(ctx context.Context) error {
func checkActionsEnabled(ctx context.Context) error {
if authz.GetInstance(ctx).Features().Actions {
return nil
}

View File

@@ -13,49 +13,48 @@ import (
"github.com/stretchr/testify/require"
"github.com/zitadel/zitadel/internal/integration"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
"github.com/zitadel/zitadel/pkg/grpc/feature/v2"
)
var (
CTX context.Context
Tester *integration.Tester
Client action.ActionServiceClient
IAMOwnerCTX, SystemCTX context.Context
Tester *integration.Tester
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, errCtx, cancel := integration.Contexts(5 * time.Minute)
ctx, _, cancel := integration.Contexts(5 * time.Minute)
defer cancel()
Tester = integration.NewTester(ctx)
defer Tester.Done()
Client = Tester.Client.ActionV3
CTX, _ = Tester.WithAuthorization(ctx, integration.IAMOwner), errCtx
IAMOwnerCTX = Tester.WithAuthorization(ctx, integration.IAMOwner)
SystemCTX = Tester.WithAuthorization(ctx, integration.SystemUser)
return m.Run()
}())
}
func ensureFeatureEnabled(t *testing.T) {
f, err := Tester.Client.FeatureV2.GetInstanceFeatures(CTX, &feature.GetInstanceFeaturesRequest{
func ensureFeatureEnabled(t *testing.T, iamOwnerCTX context.Context) {
f, err := Tester.Client.FeatureV2.GetInstanceFeatures(iamOwnerCTX, &feature.GetInstanceFeaturesRequest{
Inheritance: true,
})
require.NoError(t, err)
if f.Actions.GetEnabled() {
return
}
_, err = Tester.Client.FeatureV2.SetInstanceFeatures(CTX, &feature.SetInstanceFeaturesRequest{
_, err = Tester.Client.FeatureV2.SetInstanceFeatures(iamOwnerCTX, &feature.SetInstanceFeaturesRequest{
Actions: gu.Ptr(true),
})
require.NoError(t, err)
retryDuration := time.Minute
if ctxDeadline, ok := CTX.Deadline(); ok {
if ctxDeadline, ok := iamOwnerCTX.Deadline(); ok {
retryDuration = time.Until(ctxDeadline)
}
require.EventuallyWithT(t,
func(ttt *assert.CollectT) {
f, err := Tester.Client.FeatureV2.GetInstanceFeatures(CTX, &feature.GetInstanceFeaturesRequest{
f, err := Tester.Client.FeatureV2.GetInstanceFeatures(iamOwnerCTX, &feature.GetInstanceFeaturesRequest{
Inheritance: true,
})
require.NoError(ttt, err)

View File

@@ -0,0 +1,114 @@
package action
import (
"context"
"github.com/muhlemmer/gu"
"github.com/zitadel/zitadel/internal/api/authz"
resource_object "github.com/zitadel/zitadel/internal/api/grpc/resources/object/v3alpha"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/eventstore/v1/models"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
)
func (s *Server) CreateTarget(ctx context.Context, req *action.CreateTargetRequest) (*action.CreateTargetResponse, error) {
if err := checkActionsEnabled(ctx); err != nil {
return nil, err
}
add := createTargetToCommand(req)
instanceID := authz.GetInstance(ctx).InstanceID()
details, err := s.command.AddTarget(ctx, add, instanceID)
if err != nil {
return nil, err
}
return &action.CreateTargetResponse{
Details: resource_object.DomainToDetailsPb(details, object.OwnerType_OWNER_TYPE_INSTANCE, instanceID),
}, nil
}
func (s *Server) PatchTarget(ctx context.Context, req *action.PatchTargetRequest) (*action.PatchTargetResponse, error) {
if err := checkActionsEnabled(ctx); err != nil {
return nil, err
}
instanceID := authz.GetInstance(ctx).InstanceID()
details, err := s.command.ChangeTarget(ctx, patchTargetToCommand(req), instanceID)
if err != nil {
return nil, err
}
return &action.PatchTargetResponse{
Details: resource_object.DomainToDetailsPb(details, object.OwnerType_OWNER_TYPE_INSTANCE, instanceID),
}, nil
}
func (s *Server) DeleteTarget(ctx context.Context, req *action.DeleteTargetRequest) (*action.DeleteTargetResponse, error) {
if err := checkActionsEnabled(ctx); err != nil {
return nil, err
}
instanceID := authz.GetInstance(ctx).InstanceID()
details, err := s.command.DeleteTarget(ctx, req.GetId(), instanceID)
if err != nil {
return nil, err
}
return &action.DeleteTargetResponse{
Details: resource_object.DomainToDetailsPb(details, object.OwnerType_OWNER_TYPE_INSTANCE, instanceID),
}, nil
}
func createTargetToCommand(req *action.CreateTargetRequest) *command.AddTarget {
reqTarget := req.GetTarget()
var (
targetType domain.TargetType
interruptOnError bool
)
switch t := reqTarget.GetTargetType().(type) {
case *action.Target_RestWebhook:
targetType = domain.TargetTypeWebhook
interruptOnError = t.RestWebhook.InterruptOnError
case *action.Target_RestCall:
targetType = domain.TargetTypeCall
interruptOnError = t.RestCall.InterruptOnError
case *action.Target_RestAsync:
targetType = domain.TargetTypeAsync
}
return &command.AddTarget{
Name: reqTarget.GetName(),
TargetType: targetType,
Endpoint: reqTarget.GetEndpoint(),
Timeout: reqTarget.GetTimeout().AsDuration(),
InterruptOnError: interruptOnError,
}
}
func patchTargetToCommand(req *action.PatchTargetRequest) *command.ChangeTarget {
reqTarget := req.GetTarget()
if reqTarget == nil {
return nil
}
target := &command.ChangeTarget{
ObjectRoot: models.ObjectRoot{
AggregateID: req.GetId(),
},
Name: reqTarget.Name,
Endpoint: reqTarget.Endpoint,
}
if reqTarget.TargetType != nil {
switch t := reqTarget.GetTargetType().(type) {
case *action.PatchTarget_RestWebhook:
target.TargetType = gu.Ptr(domain.TargetTypeWebhook)
target.InterruptOnError = gu.Ptr(t.RestWebhook.InterruptOnError)
case *action.PatchTarget_RestCall:
target.TargetType = gu.Ptr(domain.TargetTypeCall)
target.InterruptOnError = gu.Ptr(t.RestCall.InterruptOnError)
case *action.PatchTarget_RestAsync:
target.TargetType = gu.Ptr(domain.TargetTypeAsync)
target.InterruptOnError = gu.Ptr(false)
}
}
if reqTarget.Timeout != nil {
target.Timeout = gu.Ptr(reqTarget.GetTimeout().AsDuration())
}
return target
}

View File

@@ -0,0 +1,450 @@
//go:build integration
package action_test
import (
"context"
"fmt"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
"testing"
"time"
"github.com/muhlemmer/gu"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/integration"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
resource_object "github.com/zitadel/zitadel/pkg/grpc/resources/object/v3alpha"
)
func TestServer_CreateTarget(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
tests := []struct {
name string
ctx context.Context
req *action.Target
want *resource_object.Details
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
},
wantErr: true,
},
{
name: "empty name",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: "",
},
wantErr: true,
},
{
name: "empty type",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
TargetType: nil,
},
wantErr: true,
},
{
name: "empty webhook url",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{},
},
},
wantErr: true,
},
{
name: "empty request response url",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{},
},
},
wantErr: true,
},
{
name: "empty timeout",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{},
},
Timeout: nil,
},
wantErr: true,
},
{
name: "async, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.Target_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "webhook, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "webhook, interrupt on error, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "call, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "call, interruptOnError, ok",
ctx: isolatedIAMOwnerCTX,
req: &action.Target{
Name: fmt.Sprint(time.Now().UnixNano() + 1),
Endpoint: "https://example.com",
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Tester.Client.ActionV3Alpha.CreateTarget(tt.ctx, &action.CreateTargetRequest{Target: tt.req})
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want, got.Details)
})
}
}
func TestServer_PatchTarget(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
type args struct {
ctx context.Context
req *action.PatchTargetRequest
}
tests := []struct {
name string
prepare func(request *action.PatchTargetRequest) error
args args
want *resource_object.Details
wantErr bool
}{
{
name: "missing permission",
prepare: func(request *action.PatchTargetRequest) error {
targetID := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetDetails().GetId()
request.Id = targetID
return nil
},
args: args{
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.PatchTargetRequest{
Target: &action.PatchTarget{
Name: gu.Ptr(fmt.Sprint(time.Now().UnixNano() + 1)),
},
},
},
wantErr: true,
},
{
name: "not existing",
prepare: func(request *action.PatchTargetRequest) error {
request.Id = "notexisting"
return nil
},
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.PatchTargetRequest{
Target: &action.PatchTarget{
Name: gu.Ptr(fmt.Sprint(time.Now().UnixNano() + 1)),
},
},
},
wantErr: true,
},
{
name: "change name, ok",
prepare: func(request *action.PatchTargetRequest) error {
targetID := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetDetails().GetId()
request.Id = targetID
return nil
},
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.PatchTargetRequest{
Target: &action.PatchTarget{
Name: gu.Ptr(fmt.Sprint(time.Now().UnixNano() + 1)),
},
},
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "change type, ok",
prepare: func(request *action.PatchTargetRequest) error {
targetID := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetDetails().GetId()
request.Id = targetID
return nil
},
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.PatchTargetRequest{
Target: &action.PatchTarget{
TargetType: &action.PatchTarget_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
},
},
},
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "change url, ok",
prepare: func(request *action.PatchTargetRequest) error {
targetID := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetDetails().GetId()
request.Id = targetID
return nil
},
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.PatchTargetRequest{
Target: &action.PatchTarget{
Endpoint: gu.Ptr("https://example.com/hooks/new"),
},
},
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "change timeout, ok",
prepare: func(request *action.PatchTargetRequest) error {
targetID := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false).GetDetails().GetId()
request.Id = targetID
return nil
},
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.PatchTargetRequest{
Target: &action.PatchTarget{
Timeout: durationpb.New(20 * time.Second),
},
},
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
{
name: "change type async, ok",
prepare: func(request *action.PatchTargetRequest) error {
targetID := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeAsync, false).GetDetails().GetId()
request.Id = targetID
return nil
},
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.PatchTargetRequest{
Target: &action.PatchTarget{
TargetType: &action.PatchTarget_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
},
},
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.prepare(tt.args.req)
require.NoError(t, err)
// We want to have the same response no matter how often we call the function
Tester.Client.ActionV3Alpha.PatchTarget(tt.args.ctx, tt.args.req)
got, err := Tester.Client.ActionV3Alpha.PatchTarget(tt.args.ctx, tt.args.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want, got.Details)
})
}
}
func TestServer_DeleteTarget(t *testing.T) {
_, instanceID, _, isolatedIAMOwnerCTX := Tester.UseIsolatedInstance(t, IAMOwnerCTX, SystemCTX)
ensureFeatureEnabled(t, isolatedIAMOwnerCTX)
target := Tester.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", domain.TargetTypeWebhook, false)
tests := []struct {
name string
ctx context.Context
req *action.DeleteTargetRequest
want *resource_object.Details
wantErr bool
}{
{
name: "missing permission",
ctx: Tester.WithAuthorization(context.Background(), integration.OrgOwner),
req: &action.DeleteTargetRequest{
Id: target.GetDetails().GetId(),
},
wantErr: true,
},
{
name: "empty id",
ctx: isolatedIAMOwnerCTX,
req: &action.DeleteTargetRequest{
Id: "",
},
wantErr: true,
},
{
name: "delete target",
ctx: isolatedIAMOwnerCTX,
req: &action.DeleteTargetRequest{
Id: target.GetDetails().GetId(),
},
want: &resource_object.Details{
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: instanceID,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Tester.Client.ActionV3Alpha.DeleteTarget(tt.ctx, tt.req)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
integration.AssertResourceDetails(t, tt.want, got.Details)
})
}
}

View File

@@ -10,12 +10,12 @@ import (
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
action "github.com/zitadel/zitadel/pkg/grpc/action/v3alpha"
action "github.com/zitadel/zitadel/pkg/grpc/resources/action/v3alpha"
)
func Test_createTargetToCommand(t *testing.T) {
type args struct {
req *action.CreateTargetRequest
req *action.Target
}
tests := []struct {
name string
@@ -34,10 +34,10 @@ func Test_createTargetToCommand(t *testing.T) {
},
{
name: "all fields (webhook)",
args: args{&action.CreateTargetRequest{
args: args{&action.Target{
Name: "target 1",
Endpoint: "https://example.com/hooks/1",
TargetType: &action.CreateTargetRequest_RestWebhook{
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.SetRESTWebhook{},
},
Timeout: durationpb.New(10 * time.Second),
@@ -52,10 +52,10 @@ func Test_createTargetToCommand(t *testing.T) {
},
{
name: "all fields (async)",
args: args{&action.CreateTargetRequest{
args: args{&action.Target{
Name: "target 1",
Endpoint: "https://example.com/hooks/1",
TargetType: &action.CreateTargetRequest_RestAsync{
TargetType: &action.Target_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
@@ -70,10 +70,10 @@ func Test_createTargetToCommand(t *testing.T) {
},
{
name: "all fields (interrupting response)",
args: args{&action.CreateTargetRequest{
args: args{&action.Target{
Name: "target 1",
Endpoint: "https://example.com/hooks/1",
TargetType: &action.CreateTargetRequest_RestCall{
TargetType: &action.Target_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
@@ -91,7 +91,7 @@ func Test_createTargetToCommand(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := createTargetToCommand(tt.args.req)
got := createTargetToCommand(&action.CreateTargetRequest{Target: tt.args.req})
assert.Equal(t, tt.want, got)
})
}
@@ -99,7 +99,7 @@ func Test_createTargetToCommand(t *testing.T) {
func Test_updateTargetToCommand(t *testing.T) {
type args struct {
req *action.UpdateTargetRequest
req *action.PatchTarget
}
tests := []struct {
name string
@@ -113,7 +113,7 @@ func Test_updateTargetToCommand(t *testing.T) {
},
{
name: "all fields nil",
args: args{&action.UpdateTargetRequest{
args: args{&action.PatchTarget{
Name: nil,
TargetType: nil,
Timeout: nil,
@@ -128,7 +128,7 @@ func Test_updateTargetToCommand(t *testing.T) {
},
{
name: "all fields empty",
args: args{&action.UpdateTargetRequest{
args: args{&action.PatchTarget{
Name: gu.Ptr(""),
TargetType: nil,
Timeout: durationpb.New(0),
@@ -143,10 +143,10 @@ func Test_updateTargetToCommand(t *testing.T) {
},
{
name: "all fields (webhook)",
args: args{&action.UpdateTargetRequest{
args: args{&action.PatchTarget{
Name: gu.Ptr("target 1"),
Endpoint: gu.Ptr("https://example.com/hooks/1"),
TargetType: &action.UpdateTargetRequest_RestWebhook{
TargetType: &action.PatchTarget_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: false,
},
@@ -163,10 +163,10 @@ func Test_updateTargetToCommand(t *testing.T) {
},
{
name: "all fields (webhook interrupt)",
args: args{&action.UpdateTargetRequest{
args: args{&action.PatchTarget{
Name: gu.Ptr("target 1"),
Endpoint: gu.Ptr("https://example.com/hooks/1"),
TargetType: &action.UpdateTargetRequest_RestWebhook{
TargetType: &action.PatchTarget_RestWebhook{
RestWebhook: &action.SetRESTWebhook{
InterruptOnError: true,
},
@@ -183,10 +183,10 @@ func Test_updateTargetToCommand(t *testing.T) {
},
{
name: "all fields (async)",
args: args{&action.UpdateTargetRequest{
args: args{&action.PatchTarget{
Name: gu.Ptr("target 1"),
Endpoint: gu.Ptr("https://example.com/hooks/1"),
TargetType: &action.UpdateTargetRequest_RestAsync{
TargetType: &action.PatchTarget_RestAsync{
RestAsync: &action.SetRESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
@@ -201,10 +201,10 @@ func Test_updateTargetToCommand(t *testing.T) {
},
{
name: "all fields (interrupting response)",
args: args{&action.UpdateTargetRequest{
args: args{&action.PatchTarget{
Name: gu.Ptr("target 1"),
Endpoint: gu.Ptr("https://example.com/hooks/1"),
TargetType: &action.UpdateTargetRequest_RestCall{
TargetType: &action.PatchTarget_RestCall{
RestCall: &action.SetRESTCall{
InterruptOnError: true,
},
@@ -222,7 +222,7 @@ func Test_updateTargetToCommand(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := updateTargetToCommand(tt.args.req)
got := patchTargetToCommand(&action.PatchTargetRequest{Target: tt.args.req})
assert.Equal(t, tt.want, got)
})
}

View File

@@ -0,0 +1,77 @@
package object
import (
"fmt"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/config/systemdefaults"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
resource_object "github.com/zitadel/zitadel/pkg/grpc/resources/object/v3alpha"
)
func DomainToDetailsPb(objectDetail *domain.ObjectDetails, ownerType object.OwnerType, ownerId string) *resource_object.Details {
details := &resource_object.Details{
Id: objectDetail.ID,
Owner: &object.Owner{
Type: ownerType,
Id: ownerId,
},
}
if !objectDetail.EventDate.IsZero() {
details.Changed = timestamppb.New(objectDetail.EventDate)
}
if !objectDetail.CreationDate.IsZero() {
details.Created = timestamppb.New(objectDetail.CreationDate)
}
return details
}
func ToSearchDetailsPb(request query.SearchRequest, response query.SearchResponse) *resource_object.ListDetails {
details := &resource_object.ListDetails{
AppliedLimit: request.Limit,
TotalResult: response.Count,
Timestamp: timestamppb.New(response.EventCreatedAt),
}
return details
}
func TextMethodPbToQuery(method resource_object.TextFilterMethod) query.TextComparison {
switch method {
case resource_object.TextFilterMethod_TEXT_FILTER_METHOD_EQUALS:
return query.TextEquals
case resource_object.TextFilterMethod_TEXT_FILTER_METHOD_EQUALS_IGNORE_CASE:
return query.TextEqualsIgnoreCase
case resource_object.TextFilterMethod_TEXT_FILTER_METHOD_STARTS_WITH:
return query.TextStartsWith
case resource_object.TextFilterMethod_TEXT_FILTER_METHOD_STARTS_WITH_IGNORE_CASE:
return query.TextStartsWithIgnoreCase
case resource_object.TextFilterMethod_TEXT_FILTER_METHOD_CONTAINS:
return query.TextContains
default:
return -1
}
}
func SearchQueryPbToQuery(defaults systemdefaults.SystemDefaults, query *resource_object.SearchQuery) (offset, limit uint64, asc bool, err error) {
limit = defaults.DefaultQueryLimit
asc = true
if query == nil {
return 0, limit, asc, nil
}
offset = query.Offset
if query.Desc {
asc = false
}
if defaults.MaxQueryLimit > 0 && uint64(query.Limit) > defaults.MaxQueryLimit {
return 0, 0, false, zerrors.ThrowInvalidArgumentf(fmt.Errorf("given: %d, allowed: %d", query.Limit, defaults.MaxQueryLimit), "QUERY-4M0fs", "Errors.Query.LimitExceeded")
}
if query.Limit > 0 {
limit = uint64(query.Limit)
}
return offset, limit, asc, nil
}

View File

@@ -0,0 +1,47 @@
package webkey
import (
"google.golang.org/grpc"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/grpc/server"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/query"
webkey "github.com/zitadel/zitadel/pkg/grpc/resources/webkey/v3alpha"
)
type Server struct {
webkey.UnimplementedZITADELWebKeysServer
command *command.Commands
query *query.Queries
}
func CreateServer(
command *command.Commands,
query *query.Queries,
) *Server {
return &Server{
command: command,
query: query,
}
}
func (s *Server) RegisterServer(grpcServer *grpc.Server) {
webkey.RegisterZITADELWebKeysServer(grpcServer, s)
}
func (s *Server) AppName() string {
return webkey.ZITADELWebKeys_ServiceDesc.ServiceName
}
func (s *Server) MethodPrefix() string {
return webkey.ZITADELWebKeys_ServiceDesc.ServiceName
}
func (s *Server) AuthMethods() authz.MethodMapping {
return webkey.ZITADELWebKeys_AuthMethods
}
func (s *Server) RegisterGateway() server.RegisterGatewayFunc {
return webkey.RegisterZITADELWebKeysHandler
}

View File

@@ -0,0 +1,87 @@
package webkey
import (
"context"
"github.com/zitadel/zitadel/internal/api/authz"
resource_object "github.com/zitadel/zitadel/internal/api/grpc/resources/object/v3alpha"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
webkey "github.com/zitadel/zitadel/pkg/grpc/resources/webkey/v3alpha"
)
func (s *Server) CreateWebKey(ctx context.Context, req *webkey.CreateWebKeyRequest) (_ *webkey.CreateWebKeyResponse, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if err = checkWebKeyFeature(ctx); err != nil {
return nil, err
}
webKey, err := s.command.CreateWebKey(ctx, createWebKeyRequestToConfig(req))
if err != nil {
return nil, err
}
return &webkey.CreateWebKeyResponse{
Details: resource_object.DomainToDetailsPb(webKey.ObjectDetails, object.OwnerType_OWNER_TYPE_INSTANCE, authz.GetInstance(ctx).InstanceID()),
}, nil
}
func (s *Server) ActivateWebKey(ctx context.Context, req *webkey.ActivateWebKeyRequest) (_ *webkey.ActivateWebKeyResponse, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if err = checkWebKeyFeature(ctx); err != nil {
return nil, err
}
details, err := s.command.ActivateWebKey(ctx, req.GetId())
if err != nil {
return nil, err
}
return &webkey.ActivateWebKeyResponse{
Details: resource_object.DomainToDetailsPb(details, object.OwnerType_OWNER_TYPE_INSTANCE, authz.GetInstance(ctx).InstanceID()),
}, nil
}
func (s *Server) DeleteWebKey(ctx context.Context, req *webkey.DeleteWebKeyRequest) (_ *webkey.DeleteWebKeyResponse, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if err = checkWebKeyFeature(ctx); err != nil {
return nil, err
}
details, err := s.command.DeleteWebKey(ctx, req.GetId())
if err != nil {
return nil, err
}
return &webkey.DeleteWebKeyResponse{
Details: resource_object.DomainToDetailsPb(details, object.OwnerType_OWNER_TYPE_INSTANCE, authz.GetInstance(ctx).InstanceID()),
}, nil
}
func (s *Server) ListWebKeys(ctx context.Context, _ *webkey.ListWebKeysRequest) (_ *webkey.ListWebKeysResponse, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if err = checkWebKeyFeature(ctx); err != nil {
return nil, err
}
list, err := s.query.ListWebKeys(ctx)
if err != nil {
return nil, err
}
return &webkey.ListWebKeysResponse{
WebKeys: webKeyDetailsListToPb(list, authz.GetInstance(ctx).InstanceID()),
}, nil
}
func checkWebKeyFeature(ctx context.Context) error {
if !authz.GetFeatures(ctx).WebKey {
return zerrors.ThrowPreconditionFailed(nil, "WEBKEY-Ohx6E", "Errors.WebKey.FeatureDisabled")
}
return nil
}

View File

@@ -0,0 +1,173 @@
package webkey
import (
resource_object "github.com/zitadel/zitadel/internal/api/grpc/resources/object/v3alpha"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
webkey "github.com/zitadel/zitadel/pkg/grpc/resources/webkey/v3alpha"
)
func createWebKeyRequestToConfig(req *webkey.CreateWebKeyRequest) crypto.WebKeyConfig {
switch config := req.GetKey().GetConfig().(type) {
case *webkey.WebKey_Rsa:
return webKeyRSAConfigToCrypto(config.Rsa)
case *webkey.WebKey_Ecdsa:
return webKeyECDSAConfigToCrypto(config.Ecdsa)
case *webkey.WebKey_Ed25519:
return new(crypto.WebKeyED25519Config)
default:
return webKeyRSAConfigToCrypto(nil)
}
}
func webKeyRSAConfigToCrypto(config *webkey.WebKeyRSAConfig) *crypto.WebKeyRSAConfig {
out := new(crypto.WebKeyRSAConfig)
switch config.GetBits() {
case webkey.WebKeyRSAConfig_RSA_BITS_UNSPECIFIED:
out.Bits = crypto.RSABits2048
case webkey.WebKeyRSAConfig_RSA_BITS_2048:
out.Bits = crypto.RSABits2048
case webkey.WebKeyRSAConfig_RSA_BITS_3072:
out.Bits = crypto.RSABits3072
case webkey.WebKeyRSAConfig_RSA_BITS_4096:
out.Bits = crypto.RSABits4096
default:
out.Bits = crypto.RSABits2048
}
switch config.GetHasher() {
case webkey.WebKeyRSAConfig_RSA_HASHER_UNSPECIFIED:
out.Hasher = crypto.RSAHasherSHA256
case webkey.WebKeyRSAConfig_RSA_HASHER_SHA256:
out.Hasher = crypto.RSAHasherSHA256
case webkey.WebKeyRSAConfig_RSA_HASHER_SHA384:
out.Hasher = crypto.RSAHasherSHA384
case webkey.WebKeyRSAConfig_RSA_HASHER_SHA512:
out.Hasher = crypto.RSAHasherSHA512
default:
out.Hasher = crypto.RSAHasherSHA256
}
return out
}
func webKeyECDSAConfigToCrypto(config *webkey.WebKeyECDSAConfig) *crypto.WebKeyECDSAConfig {
out := new(crypto.WebKeyECDSAConfig)
switch config.GetCurve() {
case webkey.WebKeyECDSAConfig_ECDSA_CURVE_UNSPECIFIED:
out.Curve = crypto.EllipticCurveP256
case webkey.WebKeyECDSAConfig_ECDSA_CURVE_P256:
out.Curve = crypto.EllipticCurveP256
case webkey.WebKeyECDSAConfig_ECDSA_CURVE_P384:
out.Curve = crypto.EllipticCurveP384
case webkey.WebKeyECDSAConfig_ECDSA_CURVE_P512:
out.Curve = crypto.EllipticCurveP512
default:
out.Curve = crypto.EllipticCurveP256
}
return out
}
func webKeyDetailsListToPb(list []query.WebKeyDetails, instanceID string) []*webkey.GetWebKey {
out := make([]*webkey.GetWebKey, len(list))
for i := range list {
out[i] = webKeyDetailsToPb(&list[i], instanceID)
}
return out
}
func webKeyDetailsToPb(details *query.WebKeyDetails, instanceID string) *webkey.GetWebKey {
out := &webkey.GetWebKey{
Details: resource_object.DomainToDetailsPb(&domain.ObjectDetails{
ID: details.KeyID,
CreationDate: details.CreationDate,
EventDate: details.ChangeDate,
}, object.OwnerType_OWNER_TYPE_INSTANCE, instanceID),
State: webKeyStateToPb(details.State),
Config: &webkey.WebKey{},
}
switch config := details.Config.(type) {
case *crypto.WebKeyRSAConfig:
out.Config.Config = &webkey.WebKey_Rsa{
Rsa: webKeyRSAConfigToPb(config),
}
case *crypto.WebKeyECDSAConfig:
out.Config.Config = &webkey.WebKey_Ecdsa{
Ecdsa: webKeyECDSAConfigToPb(config),
}
case *crypto.WebKeyED25519Config:
out.Config.Config = &webkey.WebKey_Ed25519{
Ed25519: new(webkey.WebKeyED25519Config),
}
}
return out
}
func webKeyStateToPb(state domain.WebKeyState) webkey.WebKeyState {
switch state {
case domain.WebKeyStateUnspecified:
return webkey.WebKeyState_STATE_UNSPECIFIED
case domain.WebKeyStateInitial:
return webkey.WebKeyState_STATE_INITIAL
case domain.WebKeyStateActive:
return webkey.WebKeyState_STATE_ACTIVE
case domain.WebKeyStateInactive:
return webkey.WebKeyState_STATE_INACTIVE
case domain.WebKeyStateRemoved:
return webkey.WebKeyState_STATE_REMOVED
default:
return webkey.WebKeyState_STATE_UNSPECIFIED
}
}
func webKeyRSAConfigToPb(config *crypto.WebKeyRSAConfig) *webkey.WebKeyRSAConfig {
out := new(webkey.WebKeyRSAConfig)
switch config.Bits {
case crypto.RSABitsUnspecified:
out.Bits = webkey.WebKeyRSAConfig_RSA_BITS_UNSPECIFIED
case crypto.RSABits2048:
out.Bits = webkey.WebKeyRSAConfig_RSA_BITS_2048
case crypto.RSABits3072:
out.Bits = webkey.WebKeyRSAConfig_RSA_BITS_3072
case crypto.RSABits4096:
out.Bits = webkey.WebKeyRSAConfig_RSA_BITS_4096
}
switch config.Hasher {
case crypto.RSAHasherUnspecified:
out.Hasher = webkey.WebKeyRSAConfig_RSA_HASHER_UNSPECIFIED
case crypto.RSAHasherSHA256:
out.Hasher = webkey.WebKeyRSAConfig_RSA_HASHER_SHA256
case crypto.RSAHasherSHA384:
out.Hasher = webkey.WebKeyRSAConfig_RSA_HASHER_SHA384
case crypto.RSAHasherSHA512:
out.Hasher = webkey.WebKeyRSAConfig_RSA_HASHER_SHA512
}
return out
}
func webKeyECDSAConfigToPb(config *crypto.WebKeyECDSAConfig) *webkey.WebKeyECDSAConfig {
out := new(webkey.WebKeyECDSAConfig)
switch config.Curve {
case crypto.EllipticCurveUnspecified:
out.Curve = webkey.WebKeyECDSAConfig_ECDSA_CURVE_UNSPECIFIED
case crypto.EllipticCurveP256:
out.Curve = webkey.WebKeyECDSAConfig_ECDSA_CURVE_P256
case crypto.EllipticCurveP384:
out.Curve = webkey.WebKeyECDSAConfig_ECDSA_CURVE_P384
case crypto.EllipticCurveP512:
out.Curve = webkey.WebKeyECDSAConfig_ECDSA_CURVE_P512
}
return out
}

View File

@@ -0,0 +1,529 @@
package webkey
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/query"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
resource_object "github.com/zitadel/zitadel/pkg/grpc/resources/object/v3alpha"
webkey "github.com/zitadel/zitadel/pkg/grpc/resources/webkey/v3alpha"
)
func Test_createWebKeyRequestToConfig(t *testing.T) {
type args struct {
req *webkey.CreateWebKeyRequest
}
tests := []struct {
name string
args args
want crypto.WebKeyConfig
}{
{
name: "RSA",
args: args{&webkey.CreateWebKeyRequest{
Key: &webkey.WebKey{
Config: &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_3072,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA384,
},
},
},
}},
want: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits3072,
Hasher: crypto.RSAHasherSHA384,
},
},
{
name: "ECDSA",
args: args{&webkey.CreateWebKeyRequest{
Key: &webkey.WebKey{
Config: &webkey.WebKey_Ecdsa{
Ecdsa: &webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P384,
},
},
},
}},
want: &crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP384,
},
},
{
name: "ED25519",
args: args{&webkey.CreateWebKeyRequest{
Key: &webkey.WebKey{
Config: &webkey.WebKey_Ed25519{
Ed25519: &webkey.WebKeyED25519Config{},
},
},
}},
want: &crypto.WebKeyED25519Config{},
},
{
name: "default",
args: args{&webkey.CreateWebKeyRequest{}},
want: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits2048,
Hasher: crypto.RSAHasherSHA256,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := createWebKeyRequestToConfig(tt.args.req)
assert.Equal(t, tt.want, got)
})
}
}
func Test_webKeyRSAConfigToCrypto(t *testing.T) {
type args struct {
config *webkey.WebKeyRSAConfig
}
tests := []struct {
name string
args args
want *crypto.WebKeyRSAConfig
}{
{
name: "unspecified",
args: args{&webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_UNSPECIFIED,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_UNSPECIFIED,
}},
want: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits2048,
Hasher: crypto.RSAHasherSHA256,
},
},
{
name: "2048, RSA256",
args: args{&webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
}},
want: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits2048,
Hasher: crypto.RSAHasherSHA256,
},
},
{
name: "3072, RSA384",
args: args{&webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_3072,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA384,
}},
want: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits3072,
Hasher: crypto.RSAHasherSHA384,
},
},
{
name: "4096, RSA512",
args: args{&webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_4096,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA512,
}},
want: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits4096,
Hasher: crypto.RSAHasherSHA512,
},
},
{
name: "invalid",
args: args{&webkey.WebKeyRSAConfig{
Bits: 99,
Hasher: 99,
}},
want: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits2048,
Hasher: crypto.RSAHasherSHA256,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := webKeyRSAConfigToCrypto(tt.args.config)
assert.Equal(t, tt.want, got)
})
}
}
func Test_webKeyECDSAConfigToCrypto(t *testing.T) {
type args struct {
config *webkey.WebKeyECDSAConfig
}
tests := []struct {
name string
args args
want *crypto.WebKeyECDSAConfig
}{
{
name: "unspecified",
args: args{&webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_UNSPECIFIED,
}},
want: &crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP256,
},
},
{
name: "P256",
args: args{&webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P256,
}},
want: &crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP256,
},
},
{
name: "P384",
args: args{&webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P384,
}},
want: &crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP384,
},
},
{
name: "P512",
args: args{&webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P512,
}},
want: &crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP512,
},
},
{
name: "invalid",
args: args{&webkey.WebKeyECDSAConfig{
Curve: 99,
}},
want: &crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP256,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := webKeyECDSAConfigToCrypto(tt.args.config)
assert.Equal(t, tt.want, got)
})
}
}
func Test_webKeyDetailsListToPb(t *testing.T) {
instanceID := "ownerid"
list := []query.WebKeyDetails{
{
KeyID: "key1",
CreationDate: time.Unix(123, 456),
ChangeDate: time.Unix(789, 0),
Sequence: 123,
State: domain.WebKeyStateActive,
Config: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits3072,
Hasher: crypto.RSAHasherSHA384,
},
},
{
KeyID: "key2",
CreationDate: time.Unix(123, 456),
ChangeDate: time.Unix(789, 0),
Sequence: 123,
State: domain.WebKeyStateActive,
Config: &crypto.WebKeyED25519Config{},
},
}
want := []*webkey.GetWebKey{
{
Details: &resource_object.Details{
Id: "key1",
Created: &timestamppb.Timestamp{Seconds: 123, Nanos: 456},
Changed: &timestamppb.Timestamp{Seconds: 789, Nanos: 0},
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
State: webkey.WebKeyState_STATE_ACTIVE,
Config: &webkey.WebKey{
Config: &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_3072,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA384,
},
},
},
},
{
Details: &resource_object.Details{
Id: "key2",
Created: &timestamppb.Timestamp{Seconds: 123, Nanos: 456},
Changed: &timestamppb.Timestamp{Seconds: 789, Nanos: 0},
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
State: webkey.WebKeyState_STATE_ACTIVE,
Config: &webkey.WebKey{
Config: &webkey.WebKey_Ed25519{
Ed25519: &webkey.WebKeyED25519Config{},
},
},
},
}
got := webKeyDetailsListToPb(list, instanceID)
assert.Equal(t, want, got)
}
func Test_webKeyDetailsToPb(t *testing.T) {
instanceID := "ownerid"
type args struct {
details *query.WebKeyDetails
}
tests := []struct {
name string
args args
want *webkey.GetWebKey
}{
{
name: "RSA",
args: args{&query.WebKeyDetails{
KeyID: "keyID",
CreationDate: time.Unix(123, 456),
ChangeDate: time.Unix(789, 0),
Sequence: 123,
State: domain.WebKeyStateActive,
Config: &crypto.WebKeyRSAConfig{
Bits: crypto.RSABits3072,
Hasher: crypto.RSAHasherSHA384,
},
}},
want: &webkey.GetWebKey{
Details: &resource_object.Details{
Id: "keyID",
Created: &timestamppb.Timestamp{Seconds: 123, Nanos: 456},
Changed: &timestamppb.Timestamp{Seconds: 789, Nanos: 0},
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
State: webkey.WebKeyState_STATE_ACTIVE,
Config: &webkey.WebKey{
Config: &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_3072,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA384,
},
},
},
},
},
{
name: "ECDSA",
args: args{&query.WebKeyDetails{
KeyID: "keyID",
CreationDate: time.Unix(123, 456),
ChangeDate: time.Unix(789, 0),
Sequence: 123,
State: domain.WebKeyStateActive,
Config: &crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP384,
},
}},
want: &webkey.GetWebKey{
Details: &resource_object.Details{
Id: "keyID",
Created: &timestamppb.Timestamp{Seconds: 123, Nanos: 456},
Changed: &timestamppb.Timestamp{Seconds: 789, Nanos: 0},
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
State: webkey.WebKeyState_STATE_ACTIVE,
Config: &webkey.WebKey{
Config: &webkey.WebKey_Ecdsa{
Ecdsa: &webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P384,
},
},
},
},
},
{
name: "ED25519",
args: args{&query.WebKeyDetails{
KeyID: "keyID",
CreationDate: time.Unix(123, 456),
ChangeDate: time.Unix(789, 0),
Sequence: 123,
State: domain.WebKeyStateActive,
Config: &crypto.WebKeyED25519Config{},
}},
want: &webkey.GetWebKey{
Details: &resource_object.Details{
Id: "keyID",
Created: &timestamppb.Timestamp{Seconds: 123, Nanos: 456},
Changed: &timestamppb.Timestamp{Seconds: 789, Nanos: 0},
Owner: &object.Owner{Type: object.OwnerType_OWNER_TYPE_INSTANCE, Id: instanceID},
},
State: webkey.WebKeyState_STATE_ACTIVE,
Config: &webkey.WebKey{
Config: &webkey.WebKey_Ed25519{
Ed25519: &webkey.WebKeyED25519Config{},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := webKeyDetailsToPb(tt.args.details, instanceID)
assert.Equal(t, tt.want, got)
})
}
}
func Test_webKeyStateToPb(t *testing.T) {
type args struct {
state domain.WebKeyState
}
tests := []struct {
name string
args args
want webkey.WebKeyState
}{
{
name: "unspecified",
args: args{domain.WebKeyStateUnspecified},
want: webkey.WebKeyState_STATE_UNSPECIFIED,
},
{
name: "initial",
args: args{domain.WebKeyStateInitial},
want: webkey.WebKeyState_STATE_INITIAL,
},
{
name: "active",
args: args{domain.WebKeyStateActive},
want: webkey.WebKeyState_STATE_ACTIVE,
},
{
name: "inactive",
args: args{domain.WebKeyStateInactive},
want: webkey.WebKeyState_STATE_INACTIVE,
},
{
name: "removed",
args: args{domain.WebKeyStateRemoved},
want: webkey.WebKeyState_STATE_REMOVED,
},
{
name: "invalid",
args: args{99},
want: webkey.WebKeyState_STATE_UNSPECIFIED,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := webKeyStateToPb(tt.args.state)
assert.Equal(t, tt.want, got)
})
}
}
func Test_webKeyRSAConfigToPb(t *testing.T) {
type args struct {
config *crypto.WebKeyRSAConfig
}
tests := []struct {
name string
args args
want *webkey.WebKeyRSAConfig
}{
{
name: "2048, RSA256",
args: args{&crypto.WebKeyRSAConfig{
Bits: crypto.RSABits2048,
Hasher: crypto.RSAHasherSHA256,
}},
want: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
},
{
name: "3072, RSA384",
args: args{&crypto.WebKeyRSAConfig{
Bits: crypto.RSABits3072,
Hasher: crypto.RSAHasherSHA384,
}},
want: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_3072,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA384,
},
},
{
name: "4096, RSA512",
args: args{&crypto.WebKeyRSAConfig{
Bits: crypto.RSABits4096,
Hasher: crypto.RSAHasherSHA512,
}},
want: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_4096,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA512,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := webKeyRSAConfigToPb(tt.args.config)
assert.Equal(t, tt.want, got)
})
}
}
func Test_webKeyECDSAConfigToPb(t *testing.T) {
type args struct {
config *crypto.WebKeyECDSAConfig
}
tests := []struct {
name string
args args
want *webkey.WebKeyECDSAConfig
}{
{
name: "P256",
args: args{&crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP256,
}},
want: &webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P256,
},
},
{
name: "P384",
args: args{&crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP384,
}},
want: &webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P384,
},
},
{
name: "P512",
args: args{&crypto.WebKeyECDSAConfig{
Curve: crypto.EllipticCurveP512,
}},
want: &webkey.WebKeyECDSAConfig{
Curve: webkey.WebKeyECDSAConfig_ECDSA_CURVE_P512,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := webKeyECDSAConfigToPb(tt.args.config)
assert.Equal(t, tt.want, got)
})
}
}

View File

@@ -0,0 +1,245 @@
//go:build integration
package webkey_test
import (
"context"
"net"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/pkg/grpc/feature/v2"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
resource_object "github.com/zitadel/zitadel/pkg/grpc/resources/object/v3alpha"
webkey "github.com/zitadel/zitadel/pkg/grpc/resources/webkey/v3alpha"
)
var (
CTX context.Context
SystemCTX context.Context
Tester *integration.Tester
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, _, cancel := integration.Contexts(time.Hour)
defer cancel()
Tester = integration.NewTester(ctx)
defer Tester.Done()
SystemCTX = Tester.WithAuthorization(ctx, integration.SystemUser)
CTX = Tester.WithAuthorization(ctx, integration.IAMOwner)
return m.Run()
}())
}
func TestServer_Feature_Disabled(t *testing.T) {
client, iamCTX := createInstanceAndClients(t, false)
t.Run("CreateWebKey", func(t *testing.T) {
_, err := client.CreateWebKey(iamCTX, &webkey.CreateWebKeyRequest{})
assertFeatureDisabledError(t, err)
})
t.Run("ActivateWebKey", func(t *testing.T) {
_, err := client.ActivateWebKey(iamCTX, &webkey.ActivateWebKeyRequest{
Id: "1",
})
assertFeatureDisabledError(t, err)
})
t.Run("DeleteWebKey", func(t *testing.T) {
_, err := client.DeleteWebKey(iamCTX, &webkey.DeleteWebKeyRequest{
Id: "1",
})
assertFeatureDisabledError(t, err)
})
t.Run("ListWebKeys", func(t *testing.T) {
_, err := client.ListWebKeys(iamCTX, &webkey.ListWebKeysRequest{})
assertFeatureDisabledError(t, err)
})
}
func TestServer_ListWebKeys(t *testing.T) {
client, iamCtx := createInstanceAndClients(t, true)
// After the feature is first enabled, we can expect 2 generated keys with the default config.
checkWebKeyListState(iamCtx, t, client, 2, "", &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
})
}
func TestServer_CreateWebKey(t *testing.T) {
client, iamCtx := createInstanceAndClients(t, true)
_, err := client.CreateWebKey(iamCtx, &webkey.CreateWebKeyRequest{
Key: &webkey.WebKey{
Config: &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
},
},
})
require.NoError(t, err)
checkWebKeyListState(iamCtx, t, client, 3, "", &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
})
}
func TestServer_ActivateWebKey(t *testing.T) {
client, iamCtx := createInstanceAndClients(t, true)
resp, err := client.CreateWebKey(iamCtx, &webkey.CreateWebKeyRequest{
Key: &webkey.WebKey{
Config: &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
},
},
})
require.NoError(t, err)
_, err = client.ActivateWebKey(iamCtx, &webkey.ActivateWebKeyRequest{
Id: resp.GetDetails().GetId(),
})
require.NoError(t, err)
checkWebKeyListState(iamCtx, t, client, 3, resp.GetDetails().GetId(), &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
})
}
func TestServer_DeleteWebKey(t *testing.T) {
client, iamCtx := createInstanceAndClients(t, true)
keyIDs := make([]string, 2)
for i := 0; i < 2; i++ {
resp, err := client.CreateWebKey(iamCtx, &webkey.CreateWebKeyRequest{
Key: &webkey.WebKey{
Config: &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
},
},
})
require.NoError(t, err)
keyIDs[i] = resp.GetDetails().GetId()
}
_, err := client.ActivateWebKey(iamCtx, &webkey.ActivateWebKeyRequest{
Id: keyIDs[0],
})
require.NoError(t, err)
ok := t.Run("cannot delete active key", func(t *testing.T) {
_, err := client.DeleteWebKey(iamCtx, &webkey.DeleteWebKeyRequest{
Id: keyIDs[0],
})
require.Error(t, err)
s := status.Convert(err)
assert.Equal(t, codes.FailedPrecondition, s.Code())
assert.Contains(t, s.Message(), "COMMAND-Chai1")
})
if !ok {
return
}
ok = t.Run("delete inactive key", func(t *testing.T) {
_, err := client.DeleteWebKey(iamCtx, &webkey.DeleteWebKeyRequest{
Id: keyIDs[1],
})
require.NoError(t, err)
})
if !ok {
return
}
// There are 2 keys from feature setup, +2 created, -1 deleted = 3
checkWebKeyListState(iamCtx, t, client, 3, keyIDs[0], &webkey.WebKey_Rsa{
Rsa: &webkey.WebKeyRSAConfig{
Bits: webkey.WebKeyRSAConfig_RSA_BITS_2048,
Hasher: webkey.WebKeyRSAConfig_RSA_HASHER_SHA256,
},
})
}
func createInstanceAndClients(t *testing.T, enableFeature bool) (webkey.ZITADELWebKeysClient, context.Context) {
domain, _, _, iamCTX := Tester.UseIsolatedInstance(t, CTX, SystemCTX)
cc, err := grpc.NewClient(
net.JoinHostPort(domain, "8080"),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
require.NoError(t, err)
if enableFeature {
features := feature.NewFeatureServiceClient(cc)
_, err = features.SetInstanceFeatures(iamCTX, &feature.SetInstanceFeaturesRequest{
WebKey: proto.Bool(true),
})
require.NoError(t, err)
time.Sleep(time.Second)
}
return webkey.NewZITADELWebKeysClient(cc), iamCTX
}
func assertFeatureDisabledError(t *testing.T, err error) {
t.Helper()
require.Error(t, err)
s := status.Convert(err)
assert.Equal(t, codes.FailedPrecondition, s.Code())
assert.Contains(t, s.Message(), "WEBKEY-Ohx6E")
}
func checkWebKeyListState(ctx context.Context, t *testing.T, client webkey.ZITADELWebKeysClient, nKeys int, expectActiveKeyID string, config any) {
resp, err := client.ListWebKeys(ctx, &webkey.ListWebKeysRequest{})
require.NoError(t, err)
list := resp.GetWebKeys()
require.Len(t, list, nKeys)
now := time.Now()
var gotActiveKeyID string
for _, key := range list {
integration.AssertResourceDetails(t, &resource_object.Details{
Created: timestamppb.Now(),
Changed: timestamppb.Now(),
Owner: &object.Owner{
Type: object.OwnerType_OWNER_TYPE_INSTANCE,
Id: Tester.Instance.InstanceID(),
},
}, key.GetDetails())
assert.WithinRange(t, key.GetDetails().GetChanged().AsTime(), now.Add(-time.Minute), now.Add(time.Minute))
assert.NotEqual(t, webkey.WebKeyState_STATE_UNSPECIFIED, key.GetState())
assert.NotEqual(t, webkey.WebKeyState_STATE_REMOVED, key.GetState())
assert.Equal(t, config, key.GetConfig().GetConfig())
if key.GetState() == webkey.WebKeyState_STATE_ACTIVE {
gotActiveKeyID = key.GetDetails().GetId()
}
}
assert.NotEmpty(t, gotActiveKeyID)
if expectActiveKeyID != "" {
assert.Equal(t, expectActiveKeyID, gotActiveKeyID)
}
}

View File

@@ -5,6 +5,7 @@ import (
"crypto/tls"
"fmt"
"net/http"
"slices"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
@@ -19,10 +20,8 @@ import (
"google.golang.org/protobuf/proto"
client_middleware "github.com/zitadel/zitadel/internal/api/grpc/client/middleware"
"github.com/zitadel/zitadel/internal/api/grpc/server/middleware"
http_utils "github.com/zitadel/zitadel/internal/api/http"
http_mw "github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/telemetry/metrics"
)
@@ -57,26 +56,29 @@ var (
},
)
serveMuxOptions = []runtime.ServeMuxOption{
runtime.WithMarshalerOption(jsonMarshaler.ContentType(nil), jsonMarshaler),
runtime.WithMarshalerOption(mimeWildcard, jsonMarshaler),
runtime.WithMarshalerOption(runtime.MIMEWildcard, jsonMarshaler),
runtime.WithIncomingHeaderMatcher(headerMatcher),
runtime.WithOutgoingHeaderMatcher(runtime.DefaultHeaderMatcher),
runtime.WithForwardResponseOption(responseForwarder),
runtime.WithRoutingErrorHandler(httpErrorHandler),
serveMuxOptions = func(hostHeaders []string) []runtime.ServeMuxOption {
return []runtime.ServeMuxOption{
runtime.WithMarshalerOption(jsonMarshaler.ContentType(nil), jsonMarshaler),
runtime.WithMarshalerOption(mimeWildcard, jsonMarshaler),
runtime.WithMarshalerOption(runtime.MIMEWildcard, jsonMarshaler),
runtime.WithIncomingHeaderMatcher(headerMatcher(hostHeaders)),
runtime.WithOutgoingHeaderMatcher(runtime.DefaultHeaderMatcher),
runtime.WithForwardResponseOption(responseForwarder),
runtime.WithRoutingErrorHandler(httpErrorHandler),
}
}
headerMatcher = runtime.HeaderMatcherFunc(
func(header string) (string, bool) {
headerMatcher = func(hostHeaders []string) runtime.HeaderMatcherFunc {
customHeaders = slices.Compact(append(customHeaders, hostHeaders...))
return func(header string) (string, bool) {
for _, customHeader := range customHeaders {
if strings.HasPrefix(strings.ToLower(header), customHeader) {
return header, true
}
}
return runtime.DefaultHeaderMatcher(header)
},
)
}
}
responseForwarder = func(ctx context.Context, w http.ResponseWriter, resp proto.Message) error {
t, ok := resp.(CustomHTTPResponse)
@@ -90,14 +92,12 @@ var (
type Gateway struct {
mux *runtime.ServeMux
http1HostName string
connection *grpc.ClientConn
accessInterceptor *http_mw.AccessInterceptor
queries *query.Queries
}
func (g *Gateway) Handler() http.Handler {
return addInterceptors(g.mux, g.http1HostName, g.accessInterceptor, g.queries)
return addInterceptors(g.mux, g.accessInterceptor)
}
type CustomHTTPResponse interface {
@@ -110,12 +110,11 @@ func CreateGatewayWithPrefix(
ctx context.Context,
g WithGatewayPrefix,
port uint16,
http1HostName string,
hostHeaders []string,
accessInterceptor *http_mw.AccessInterceptor,
queries *query.Queries,
tlsConfig *tls.Config,
) (http.Handler, string, error) {
runtimeMux := runtime.NewServeMux(serveMuxOptions...)
runtimeMux := runtime.NewServeMux(serveMuxOptions(hostHeaders)...)
opts := []grpc.DialOption{
grpc.WithTransportCredentials(grpcCredentials(tlsConfig)),
grpc.WithChainUnaryInterceptor(
@@ -131,13 +130,13 @@ func CreateGatewayWithPrefix(
if err != nil {
return nil, "", fmt.Errorf("failed to register grpc gateway: %w", err)
}
return addInterceptors(runtimeMux, http1HostName, accessInterceptor, queries), g.GatewayPathPrefix(), nil
return addInterceptors(runtimeMux, accessInterceptor), g.GatewayPathPrefix(), nil
}
func CreateGateway(
ctx context.Context,
port uint16,
http1HostName string,
hostHeaders []string,
accessInterceptor *http_mw.AccessInterceptor,
tlsConfig *tls.Config,
) (*Gateway, error) {
@@ -153,10 +152,9 @@ func CreateGateway(
if err != nil {
return nil, err
}
runtimeMux := runtime.NewServeMux(append(serveMuxOptions, runtime.WithHealthzEndpoint(healthpb.NewHealthClient(connection)))...)
runtimeMux := runtime.NewServeMux(append(serveMuxOptions(hostHeaders), runtime.WithHealthzEndpoint(healthpb.NewHealthClient(connection)))...)
return &Gateway{
mux: runtimeMux,
http1HostName: http1HostName,
connection: connection,
accessInterceptor: accessInterceptor,
}, nil
@@ -195,12 +193,9 @@ func dial(ctx context.Context, port uint16, opts []grpc.DialOption) (*grpc.Clien
func addInterceptors(
handler http.Handler,
http1HostName string,
accessInterceptor *http_mw.AccessInterceptor,
queries *query.Queries,
) http.Handler {
handler = http_mw.CallDurationHandler(handler)
handler = http1Host(handler, http1HostName)
handler = http_mw.CORSInterceptor(handler)
handler = http_mw.RobotsTagHandler(handler)
handler = http_mw.DefaultTelemetryHandler(handler)
@@ -215,18 +210,6 @@ func addInterceptors(
return handler
}
func http1Host(next http.Handler, http1HostName string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host, err := http_mw.HostFromRequest(r, http1HostName)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
r.Header.Set(middleware.HTTP1Host, host)
next.ServeHTTP(w, r)
})
}
func exhaustedCookieInterceptor(
next http.Handler,
accessInterceptor *http_mw.AccessInterceptor,

View File

@@ -9,6 +9,7 @@ import (
"google.golang.org/grpc/status"
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/logstore"
"github.com/zitadel/zitadel/internal/logstore/record"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
@@ -35,6 +36,7 @@ func AccessStorageInterceptor(svc *logstore.Service[*record.AccessLog]) grpc.Una
resMd, _ := metadata.FromOutgoingContext(ctx)
instance := authz.GetInstance(ctx)
domainCtx := http_util.DomainContext(ctx)
r := &record.AccessLog{
LogDate: time.Now(),
@@ -45,8 +47,8 @@ func AccessStorageInterceptor(svc *logstore.Service[*record.AccessLog]) grpc.Una
ResponseHeaders: resMd,
InstanceID: instance.InstanceID(),
ProjectID: instance.ProjectID(),
RequestedDomain: instance.RequestedDomain(),
RequestedHost: instance.RequestedHost(),
RequestedDomain: domainCtx.RequestedDomain(),
RequestedHost: domainCtx.RequestedHost(),
}
svc.Handle(interceptorCtx, r)

View File

@@ -14,6 +14,7 @@ import (
"github.com/zitadel/zitadel/internal/query"
exec_repo "github.com/zitadel/zitadel/internal/repository/execution"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
)
func ExecutionHandler(queries *query.Queries) grpc.UnaryServerInterceptor {
@@ -143,6 +144,9 @@ func (c *ContextInfoRequest) GetHTTPRequestBody() []byte {
}
func (c *ContextInfoRequest) SetHTTPResponseBody(resp []byte) error {
if !json.Valid(resp) {
return zerrors.ThrowPreconditionFailed(nil, "ACTION-4m9s2", "Errors.Execution.ResponseIsNotValidJSON")
}
return json.Unmarshal(resp, c.Request)
}

View File

@@ -10,7 +10,6 @@ import (
"golang.org/x/text/language"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/zitadel/zitadel/internal/api/authz"
@@ -18,52 +17,88 @@ import (
"github.com/zitadel/zitadel/internal/i18n"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
object_v3 "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
)
const (
HTTP1Host = "x-zitadel-http1-host"
)
func InstanceInterceptor(verifier authz.InstanceVerifier, headerName, externalDomain string, explicitInstanceIdServices ...string) grpc.UnaryServerInterceptor {
func InstanceInterceptor(verifier authz.InstanceVerifier, externalDomain string, explicitInstanceIdServices ...string) grpc.UnaryServerInterceptor {
translator, err := i18n.NewZitadelTranslator(language.English)
logging.OnError(err).Panic("unable to get translator")
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return setInstance(ctx, req, info, handler, verifier, headerName, externalDomain, translator, explicitInstanceIdServices...)
return setInstance(ctx, req, info, handler, verifier, externalDomain, translator, explicitInstanceIdServices...)
}
}
func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, verifier authz.InstanceVerifier, headerName, externalDomain string, translator *i18n.Translator, idFromRequestsServices ...string) (_ interface{}, err error) {
func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, verifier authz.InstanceVerifier, externalDomain string, translator *i18n.Translator, idFromRequestsServices ...string) (_ interface{}, err error) {
interceptorCtx, span := tracing.NewServerInterceptorSpan(ctx)
defer func() { span.EndWithError(err) }()
for _, service := range idFromRequestsServices {
if !strings.HasPrefix(service, "/") {
service = "/" + service
}
if strings.HasPrefix(info.FullMethod, service) {
withInstanceIDProperty, ok := req.(interface{ GetInstanceId() string })
withInstanceIDProperty, ok := req.(interface {
GetInstanceId() string
})
if !ok {
return handler(ctx, req)
}
ctx = authz.WithInstanceID(ctx, withInstanceIDProperty.GetInstanceId())
instance, err := verifier.InstanceByID(ctx)
if err != nil {
notFoundErr := new(zerrors.NotFoundError)
if errors.As(err, &notFoundErr) {
notFoundErr.Message = translator.LocalizeFromCtx(ctx, notFoundErr.GetMessage(), nil)
}
return nil, status.Error(codes.NotFound, err.Error())
}
return handler(authz.WithInstance(ctx, instance), req)
return addInstanceByID(interceptorCtx, req, handler, verifier, translator, withInstanceIDProperty.GetInstanceId())
}
}
host, err := hostFromContext(interceptorCtx, headerName)
if err != nil {
return nil, status.Error(codes.NotFound, err.Error())
explicitInstanceRequest, ok := req.(interface {
GetInstance() *object_v3.Instance
})
if ok {
instance := explicitInstanceRequest.GetInstance()
if id := instance.GetId(); id != "" {
return addInstanceByID(interceptorCtx, req, handler, verifier, translator, id)
}
if domain := instance.GetDomain(); domain != "" {
return addInstanceByDomain(interceptorCtx, req, handler, verifier, translator, domain)
}
}
instance, err := verifier.InstanceByHost(interceptorCtx, host)
return addInstanceByRequestedHost(interceptorCtx, req, handler, verifier, translator, externalDomain)
}
func addInstanceByID(ctx context.Context, req interface{}, handler grpc.UnaryHandler, verifier authz.InstanceVerifier, translator *i18n.Translator, id string) (interface{}, error) {
instance, err := verifier.InstanceByID(ctx, id)
if err != nil {
origin := zitadel_http.ComposedOrigin(ctx)
logging.WithFields("origin", origin, "externalDomain", externalDomain).WithError(err).Error("unable to set instance")
notFoundErr := new(zerrors.ZitadelError)
if errors.As(err, &notFoundErr) {
notFoundErr.Message = translator.LocalizeFromCtx(ctx, notFoundErr.GetMessage(), nil)
}
return nil, status.Error(codes.NotFound, fmt.Errorf("unable to set instance using id %s: %w", id, notFoundErr).Error())
}
return handler(authz.WithInstance(ctx, instance), req)
}
func addInstanceByDomain(ctx context.Context, req interface{}, handler grpc.UnaryHandler, verifier authz.InstanceVerifier, translator *i18n.Translator, domain string) (interface{}, error) {
instance, err := verifier.InstanceByHost(ctx, domain, "")
if err != nil {
notFoundErr := new(zerrors.NotFoundError)
if errors.As(err, &notFoundErr) {
notFoundErr.Message = translator.LocalizeFromCtx(ctx, notFoundErr.GetMessage(), nil)
}
return nil, status.Error(codes.NotFound, fmt.Errorf("unable to set instance using domain %s: %w", domain, notFoundErr).Error())
}
return handler(authz.WithInstance(ctx, instance), req)
}
func addInstanceByRequestedHost(ctx context.Context, req interface{}, handler grpc.UnaryHandler, verifier authz.InstanceVerifier, translator *i18n.Translator, externalDomain string) (interface{}, error) {
requestContext := zitadel_http.DomainContext(ctx)
if requestContext.InstanceHost == "" {
logging.WithFields("origin", requestContext.Origin(), "externalDomain", externalDomain).Error("unable to set instance")
return nil, status.Error(codes.NotFound, "no instanceHost specified")
}
instance, err := verifier.InstanceByHost(ctx, requestContext.InstanceHost, requestContext.PublicHost)
if err != nil {
origin := zitadel_http.DomainContext(ctx)
logging.WithFields("origin", requestContext.Origin(), "externalDomain", externalDomain).WithError(err).Error("unable to set instance")
zErr := new(zerrors.ZitadelError)
if errors.As(err, &zErr) {
zErr.SetMessage(translator.LocalizeFromCtx(ctx, zErr.GetMessage(), nil))
@@ -72,36 +107,5 @@ func setInstance(ctx context.Context, req interface{}, info *grpc.UnaryServerInf
}
return nil, status.Error(codes.NotFound, fmt.Sprintf("unable to set instance using origin %s (ExternalDomain is %s)", origin, externalDomain))
}
span.End()
return handler(authz.WithInstance(ctx, instance), req)
}
func hostFromContext(ctx context.Context, headerName string) (string, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", fmt.Errorf("cannot read metadata")
}
host, ok := md[HTTP1Host]
if ok && len(host) == 1 {
if !isAllowedToSendHTTP1Header(md) {
return "", fmt.Errorf("no valid host header")
}
return host[0], nil
}
host, ok = md[headerName]
if !ok {
return "", fmt.Errorf("cannot find header: %v", headerName)
}
if len(host) != 1 {
return "", fmt.Errorf("invalid host header: %v", host)
}
return host[0], nil
}
// isAllowedToSendHTTP1Header check if the gRPC call was sent to `localhost`
// this is only possible when calling the server directly running on localhost
// or through the gRPC gateway
func isAllowedToSendHTTP1Header(md metadata.MD) bool {
authority, ok := md[":authority"]
return ok && len(authority) == 1 && strings.Split(authority[0], ":")[0] == "localhost"
}

View File

@@ -9,82 +9,20 @@ import (
"golang.org/x/text/language"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/feature"
object_v3 "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
)
func Test_hostNameFromContext(t *testing.T) {
type args struct {
ctx context.Context
headerName string
}
type res struct {
want string
err bool
}
tests := []struct {
name string
args args
res res
}{
{
"empty context, error",
args{
ctx: context.Background(),
headerName: "header",
},
res{
want: "",
err: true,
},
},
{
"header not found",
args{
ctx: metadata.NewIncomingContext(context.Background(), nil),
headerName: "header",
},
res{
want: "",
err: true,
},
},
{
"header not found",
args{
ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs("header", "value")),
headerName: "header",
},
res{
want: "value",
err: false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := hostFromContext(tt.args.ctx, tt.args.headerName)
if (err != nil) != tt.res.err {
t.Errorf("hostFromContext() error = %v, wantErr %v", err, tt.res.err)
return
}
if got != tt.res.want {
t.Errorf("hostFromContext() got = %v, want %v", got, tt.res.want)
}
})
}
}
func Test_setInstance(t *testing.T) {
type args struct {
ctx context.Context
req interface{}
info *grpc.UnaryServerInfo
handler grpc.UnaryHandler
verifier authz.InstanceVerifier
headerName string
ctx context.Context
req interface{}
info *grpc.UnaryServerInfo
handler grpc.UnaryHandler
verifier authz.InstanceVerifier
}
type res struct {
want interface{}
@@ -108,10 +46,9 @@ func Test_setInstance(t *testing.T) {
{
"invalid host, error",
args{
ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs("header", "host2")),
req: &mockRequest{},
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
ctx: http_util.WithDomainContext(context.Background(), &http_util.DomainCtx{InstanceHost: "host2"}),
req: &mockRequest{},
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
res{
want: nil,
@@ -121,10 +58,9 @@ func Test_setInstance(t *testing.T) {
{
"valid host",
args{
ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs("header", "host")),
req: &mockRequest{},
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
ctx: http_util.WithDomainContext(context.Background(), &http_util.DomainCtx{InstanceHost: "host"}),
req: &mockRequest{},
verifier: &mockInstanceVerifier{instanceHost: "host"},
handler: func(ctx context.Context, req interface{}) (interface{}, error) {
return req, nil
},
@@ -134,10 +70,139 @@ func Test_setInstance(t *testing.T) {
err: false,
},
},
{
"explicit instance unset, hostname not found, error",
args{
ctx: http_util.WithDomainContext(context.Background(), &http_util.DomainCtx{InstanceHost: "host2"}),
req: &mockRequestWithExplicitInstance{},
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
res{
want: nil,
err: true,
},
},
{
"explicit instance unset, invalid host, error",
args{
ctx: http_util.WithDomainContext(context.Background(), &http_util.DomainCtx{InstanceHost: "host2"}),
req: &mockRequestWithExplicitInstance{},
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
res{
want: nil,
err: true,
},
},
{
"explicit instance unset, valid host",
args{
ctx: http_util.WithDomainContext(context.Background(), &http_util.DomainCtx{InstanceHost: "host"}),
req: &mockRequestWithExplicitInstance{},
verifier: &mockInstanceVerifier{instanceHost: "host"},
handler: func(ctx context.Context, req interface{}) (interface{}, error) {
return req, nil
},
},
res{
want: &mockRequestWithExplicitInstance{},
err: false,
},
},
{
name: "explicit instance set, id not found, error",
args: args{
ctx: context.Background(),
req: &mockRequestWithExplicitInstance{
instance: object_v3.Instance{
Property: &object_v3.Instance_Id{
Id: "not existing instance id",
},
},
},
verifier: &mockInstanceVerifier{id: "existing instance id"},
},
res: res{
want: nil,
err: true,
},
},
{
name: "explicit instance set, id found, ok",
args: args{
ctx: context.Background(),
req: &mockRequestWithExplicitInstance{
instance: object_v3.Instance{
Property: &object_v3.Instance_Id{
Id: "existing instance id",
},
},
},
verifier: &mockInstanceVerifier{id: "existing instance id"},
handler: func(ctx context.Context, req interface{}) (interface{}, error) {
return req, nil
},
},
res: res{
want: &mockRequestWithExplicitInstance{
instance: object_v3.Instance{
Property: &object_v3.Instance_Id{
Id: "existing instance id",
},
},
},
err: false,
},
},
{
name: "explicit instance set, domain not found, error",
args: args{
ctx: context.Background(),
req: &mockRequestWithExplicitInstance{
instance: object_v3.Instance{
Property: &object_v3.Instance_Domain{
Domain: "not existing instance domain",
},
},
},
verifier: &mockInstanceVerifier{instanceHost: "existing instance domain"},
},
res: res{
want: nil,
err: true,
},
},
{
name: "explicit instance set, domain found, ok",
args: args{
ctx: context.Background(),
req: &mockRequestWithExplicitInstance{
instance: object_v3.Instance{
Property: &object_v3.Instance_Domain{
Domain: "existing instance domain",
},
},
},
verifier: &mockInstanceVerifier{instanceHost: "existing instance domain"},
handler: func(ctx context.Context, req interface{}) (interface{}, error) {
return req, nil
},
},
res: res{
want: &mockRequestWithExplicitInstance{
instance: object_v3.Instance{
Property: &object_v3.Instance_Domain{
Domain: "existing instance domain",
},
},
},
err: false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := setInstance(tt.args.ctx, tt.args.req, tt.args.info, tt.args.handler, tt.args.verifier, tt.args.headerName, "", nil)
got, err := setInstance(tt.args.ctx, tt.args.req, tt.args.info, tt.args.handler, tt.args.verifier, "", nil)
if (err != nil) != tt.res.err {
t.Errorf("setInstance() error = %v, wantErr %v", err, tt.res.err)
return
@@ -151,18 +216,39 @@ func Test_setInstance(t *testing.T) {
type mockRequest struct{}
type mockInstanceVerifier struct {
host string
type mockRequestWithExplicitInstance struct {
instance object_v3.Instance
}
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, host string) (authz.Instance, error) {
if host != m.host {
func (m *mockRequestWithExplicitInstance) GetInstance() *object_v3.Instance {
return &m.instance
}
type mockInstanceVerifier struct {
id string
instanceHost string
publicHost string
}
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, instanceHost, publicHost string) (authz.Instance, error) {
if instanceHost != m.instanceHost {
return nil, fmt.Errorf("invalid host")
}
if publicHost == "" {
return &mockInstance{}, nil
}
if publicHost != instanceHost && publicHost != m.publicHost {
return nil, fmt.Errorf("invalid host")
}
return &mockInstance{}, nil
}
func (m *mockInstanceVerifier) InstanceByID(context.Context) (authz.Instance, error) { return nil, nil }
func (m *mockInstanceVerifier) InstanceByID(_ context.Context, id string) (authz.Instance, error) {
if id != m.id {
return nil, fmt.Errorf("not found")
}
return &mockInstance{}, nil
}
type mockInstance struct{}
@@ -198,14 +284,6 @@ func (m *mockInstance) DefaultOrganisationID() string {
return "orgID"
}
func (m *mockInstance) RequestedDomain() string {
return "localhost"
}
func (m *mockInstance) RequestedHost() string {
return "localhost:8080"
}
func (m *mockInstance) SecurityPolicyAllowedOrigins() []string {
return nil
}

View File

@@ -2,7 +2,6 @@ package server
import (
"crypto/tls"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
@@ -38,7 +37,6 @@ func CreateServer(
verifier authz.APITokenVerifier,
authConfig authz.Config,
queries *query.Queries,
hostHeaderName string,
externalDomain string,
tlsConfig *tls.Config,
accessSvc *logstore.Service[*record.AccessLog],
@@ -51,7 +49,7 @@ func CreateServer(
middleware.DefaultTracingServer(),
middleware.MetricsHandler(metricTypes, grpc_api.Probes...),
middleware.NoCacheInterceptor(),
middleware.InstanceInterceptor(queries, hostHeaderName, externalDomain, system_pb.SystemService_ServiceDesc.ServiceName, healthpb.Health_ServiceDesc.ServiceName),
middleware.InstanceInterceptor(queries, externalDomain, system_pb.SystemService_ServiceDesc.ServiceName, healthpb.Health_ServiceDesc.ServiceName),
middleware.AccessStorageInterceptor(accessSvc),
middleware.ErrorHandler(),
middleware.LimitsInterceptor(system_pb.SystemService_ServiceDesc.ServiceName),

View File

@@ -0,0 +1,20 @@
package object
import (
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/domain"
object "github.com/zitadel/zitadel/pkg/grpc/object/v3alpha"
settings_object "github.com/zitadel/zitadel/pkg/grpc/settings/object/v3alpha"
)
func DomainToDetailsPb(objectDetail *domain.ObjectDetails, owner *object.Owner) *settings_object.Details {
details := &settings_object.Details{
Sequence: objectDetail.Sequence,
Owner: owner,
}
if !objectDetail.EventDate.IsZero() {
details.ChangeDate = timestamppb.New(objectDetail.EventDate)
}
return details
}

View File

@@ -27,12 +27,11 @@ type Config struct{}
func CreateServer(
command *command.Commands,
query *query.Queries,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
}
}

View File

@@ -27,12 +27,11 @@ type Config struct{}
func CreateServer(
command *command.Commands,
query *query.Queries,
externalSecure bool,
) *Server {
return &Server{
command: command,
query: query,
assetsAPIDomain: assets.AssetAPI(externalSecure),
assetsAPIDomain: assets.AssetAPI(),
}
}

View File

@@ -3,7 +3,6 @@ package system
import (
"context"
"github.com/zitadel/zitadel/internal/api/authz"
instance_grpc "github.com/zitadel/zitadel/internal/api/grpc/instance"
"github.com/zitadel/zitadel/internal/api/grpc/member"
"github.com/zitadel/zitadel/internal/api/grpc/object"
@@ -151,12 +150,6 @@ func (s *Server) ListDomains(ctx context.Context, req *system_pb.ListDomainsRequ
}
func (s *Server) AddDomain(ctx context.Context, req *system_pb.AddDomainRequest) (*system_pb.AddDomainResponse, error) {
instance, err := s.query.InstanceByID(ctx)
if err != nil {
return nil, err
}
ctx = authz.WithInstance(ctx, instance)
details, err := s.command.AddInstanceDomain(ctx, req.Domain)
if err != nil {
return nil, err

View File

@@ -263,7 +263,7 @@ func TestServer_RemovePhone(t *testing.T) {
req *user.RemovePhoneRequest
want *user.RemovePhoneResponse
wantErr bool
dep func(ctx context.Context, userID string) (*user.RemovePhoneResponse, error)
dep func(ctx context.Context, userID string) (*user.RemovePhoneResponse, error)
}{
{
name: "remove phone",
@@ -303,7 +303,7 @@ func TestServer_RemovePhone(t *testing.T) {
dep: func(ctx context.Context, userID string) (*user.RemovePhoneResponse, error) {
return Client.RemovePhone(ctx, &user.RemovePhoneRequest{
UserId: doubleRemoveUser.GetUserId(),
});
})
},
},
{

View File

@@ -39,11 +39,10 @@ func (s *Server) ListUsers(ctx context.Context, req *user.ListUsersRequest) (*us
if err != nil {
return nil, err
}
res, err := s.query.SearchUsers(ctx, queries)
res, err := s.query.SearchUsers(ctx, queries, s.checkPermission)
if err != nil {
return nil, err
}
res.RemoveNoPermission(ctx, s.checkPermission)
return &user.ListUsersResponse{
Result: UsersToPb(res.Users, s.assetAPIPrefix(ctx)),
Details: object.ToListDetails(res.SearchResponse),

View File

@@ -13,8 +13,8 @@ import (
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
object "github.com/zitadel/zitadel/pkg/grpc/object/v2"
user "github.com/zitadel/zitadel/pkg/grpc/user/v2"
"github.com/zitadel/zitadel/pkg/grpc/object/v2"
"github.com/zitadel/zitadel/pkg/grpc/user/v2"
"github.com/zitadel/zitadel/internal/integration"
)
@@ -914,6 +914,10 @@ func TestServer_ListUsers(t *testing.T) {
assert.Len(ttt, tt.want.Result, len(infos))
// always first check length, otherwise its failed anyway
assert.Len(ttt, got.Result, len(tt.want.Result))
// totalResult is unrelated to the tests here so gets carried over, can vary from the count of results due to permissions
tt.want.Details.TotalResult = got.Details.TotalResult
// fill in userid and username as it is generated
for i := range infos {
tt.want.Result[i].UserId = infos[i].UserID

View File

@@ -39,11 +39,10 @@ func (s *Server) ListUsers(ctx context.Context, req *user.ListUsersRequest) (*us
if err != nil {
return nil, err
}
res, err := s.query.SearchUsers(ctx, queries)
res, err := s.query.SearchUsers(ctx, queries, s.checkPermission)
if err != nil {
return nil, err
}
res.RemoveNoPermission(ctx, s.checkPermission)
return &user.ListUsersResponse{
Result: UsersToPb(res.Users, s.assetAPIPrefix(ctx)),
Details: object.ToListDetails(res.SearchResponse),

View File

@@ -923,6 +923,10 @@ func TestServer_ListUsers(t *testing.T) {
// always first check length, otherwise its failed anyway
assert.Len(ttt, got.Result, len(tt.want.Result))
// fill in userid and username as it is generated
// totalResult is unrelated to the tests here so gets carried over, can vary from the count of results due to permissions
tt.want.Details.TotalResult = got.Details.TotalResult
for i := range infos {
tt.want.Result[i].UserId = infos[i].UserID
tt.want.Result[i].Username = infos[i].Username

View File

@@ -45,3 +45,36 @@ func ZitadelErrorToHTTPStatusCode(err error) (statusCode int, ok bool) {
return http.StatusInternalServerError, false
}
}
func HTTPStatusCodeToZitadelError(parent error, statusCode int, id string, message string) error {
if statusCode == http.StatusOK {
return nil
}
var errorFunc func(parent error, id, message string) error
switch statusCode {
case http.StatusConflict:
errorFunc = zerrors.ThrowAlreadyExists
case http.StatusGatewayTimeout:
errorFunc = zerrors.ThrowDeadlineExceeded
case http.StatusInternalServerError:
errorFunc = zerrors.ThrowInternal
case http.StatusBadRequest:
errorFunc = zerrors.ThrowInvalidArgument
case http.StatusNotFound:
errorFunc = zerrors.ThrowNotFound
case http.StatusForbidden:
errorFunc = zerrors.ThrowPermissionDenied
case http.StatusUnauthorized:
errorFunc = zerrors.ThrowUnauthenticated
case http.StatusServiceUnavailable:
errorFunc = zerrors.ThrowUnavailable
case http.StatusNotImplemented:
errorFunc = zerrors.ThrowUnimplemented
case http.StatusTooManyRequests:
errorFunc = zerrors.ThrowResourceExhausted
default:
errorFunc = zerrors.ThrowUnknown
}
return errorFunc(parent, id, message)
}

View File

@@ -6,6 +6,8 @@ import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zitadel/zitadel/internal/zerrors"
)
@@ -136,3 +138,152 @@ func TestZitadelErrorToHTTPStatusCode(t *testing.T) {
})
}
}
func TestHTTPStatusCodeToZitadelError(t *testing.T) {
type args struct {
statusCode int
id string
message string
parent error
}
tests := []struct {
name string
args args
wantErr error
}{
{
name: "StatusOK",
args: args{
statusCode: http.StatusOK,
},
wantErr: nil,
},
{
name: "StatusConflict",
args: args{
statusCode: http.StatusConflict,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowAlreadyExists(nil, "id", "message"),
},
{
name: "StatusGatewayTimeout",
args: args{
statusCode: http.StatusGatewayTimeout,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowDeadlineExceeded(nil, "id", "message"),
},
{
name: "StatusInternalServerError",
args: args{
statusCode: http.StatusInternalServerError,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowInternal(nil, "id", "message"),
},
{
name: "StatusBadRequest",
args: args{
statusCode: http.StatusBadRequest,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowInvalidArgument(nil, "id", "message"),
},
{
name: "StatusNotFound",
args: args{
statusCode: http.StatusNotFound,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowNotFound(nil, "id", "message"),
},
{
name: "StatusForbidden",
args: args{
statusCode: http.StatusForbidden,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowPermissionDenied(nil, "id", "message"),
},
{
name: "StatusUnauthorized",
args: args{
statusCode: http.StatusUnauthorized,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowUnauthenticated(nil, "id", "message"),
},
{
name: "StatusServiceUnavailable",
args: args{
statusCode: http.StatusServiceUnavailable,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowUnavailable(nil, "id", "message"),
},
{
name: "StatusNotImplemented",
args: args{
statusCode: http.StatusNotImplemented,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowUnimplemented(nil, "id", "message"),
},
{
name: "StatusTooManyRequests",
args: args{
statusCode: http.StatusTooManyRequests,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowResourceExhausted(nil, "id", "message"),
},
{
name: "Unknown",
args: args{
statusCode: 1000,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowUnknown(nil, "id", "message"),
},
{
name: "Unknown, test for statuscode",
args: args{
statusCode: 1000,
id: "id",
message: "message",
},
wantErr: zerrors.ThrowError(nil, "id", "message"),
},
{
name: "Unknown with parent",
args: args{
statusCode: 1000,
id: "id",
message: "message",
parent: errors.New("parent error"),
},
wantErr: zerrors.ThrowUnknown(nil, "id", "message"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := HTTPStatusCodeToZitadelError(tt.args.parent, tt.args.statusCode, tt.args.id, tt.args.message)
assert.ErrorIs(t, err, tt.wantErr)
if tt.args.parent != nil {
assert.ErrorIs(t, err, tt.args.parent)
}
})
}
}

View File

@@ -20,6 +20,9 @@ const (
Pragma = "pragma"
UserAgentHeader = "user-agent"
ForwardedFor = "x-forwarded-for"
ForwardedHost = "x-forwarded-host"
ForwardedProto = "x-forwarded-proto"
Forwarded = "forwarded"
XUserAgent = "x-user-agent"
XGrpcWeb = "x-grpc-web"
XRequestedWith = "x-requested-with"
@@ -45,7 +48,7 @@ type key int
const (
httpHeaders key = iota
remoteAddr
origin
domainCtx
)
func CopyHeadersToContext(h http.Handler) http.Handler {
@@ -70,18 +73,6 @@ func OriginHeader(ctx context.Context) string {
return headers.Get(Origin)
}
func ComposedOrigin(ctx context.Context) string {
o, ok := ctx.Value(origin).(string)
if !ok {
return ""
}
return o
}
func WithComposedOrigin(ctx context.Context, composed string) context.Context {
return context.WithValue(ctx, origin, composed)
}
func RemoteIPFromCtx(ctx context.Context) string {
ctxHeaders, ok := HeadersFromCtx(ctx)
if !ok {

View File

@@ -163,6 +163,7 @@ func (a *AccessInterceptor) writeLog(ctx context.Context, wrappedWriter *statusR
logging.WithError(err).WithField("url", requestURL).Warning("failed to unescape request url")
}
instance := authz.GetInstance(ctx)
domainCtx := http_utils.DomainContext(ctx)
a.logstoreSvc.Handle(ctx, &record.AccessLog{
LogDate: time.Now(),
Protocol: record.HTTP,
@@ -172,8 +173,8 @@ func (a *AccessInterceptor) writeLog(ctx context.Context, wrappedWriter *statusR
ResponseHeaders: writer.Header(),
InstanceID: instance.InstanceID(),
ProjectID: instance.ProjectID(),
RequestedDomain: instance.RequestedDomain(),
RequestedHost: instance.RequestedHost(),
RequestedDomain: domainCtx.RequestedDomain(),
RequestedHost: domainCtx.RequestedHost(),
NotCountable: notCountable,
})
}

View File

@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/zitadel/logging"
@@ -19,16 +18,15 @@ import (
)
type instanceInterceptor struct {
verifier authz.InstanceVerifier
headerName, externalDomain string
ignoredPrefixes []string
translator *i18n.Translator
verifier authz.InstanceVerifier
externalDomain string
ignoredPrefixes []string
translator *i18n.Translator
}
func InstanceInterceptor(verifier authz.InstanceVerifier, headerName, externalDomain string, ignoredPrefixes ...string) *instanceInterceptor {
func InstanceInterceptor(verifier authz.InstanceVerifier, externalDomain string, ignoredPrefixes ...string) *instanceInterceptor {
return &instanceInterceptor{
verifier: verifier,
headerName: headerName,
externalDomain: externalDomain,
ignoredPrefixes: ignoredPrefixes,
translator: newZitadelTranslator(),
@@ -54,10 +52,10 @@ func (a *instanceInterceptor) handleInstance(w http.ResponseWriter, r *http.Requ
return
}
}
ctx, err := setInstance(r, a.verifier, a.headerName)
ctx, err := setInstance(r, a.verifier)
if err != nil {
origin := zitadel_http.ComposedOrigin(r.Context())
logging.WithFields("origin", origin, "externalDomain", a.externalDomain).WithError(err).Error("unable to set instance")
origin := zitadel_http.DomainContext(r.Context())
logging.WithFields("origin", origin.Origin(), "externalDomain", a.externalDomain).WithError(err).Error("unable to set instance")
zErr := new(zerrors.ZitadelError)
if errors.As(err, &zErr) {
zErr.SetMessage(a.translator.LocalizeFromRequest(r, zErr.GetMessage(), nil))
@@ -71,18 +69,16 @@ func (a *instanceInterceptor) handleInstance(w http.ResponseWriter, r *http.Requ
next.ServeHTTP(w, r)
}
func setInstance(r *http.Request, verifier authz.InstanceVerifier, headerName string) (_ context.Context, err error) {
func setInstance(r *http.Request, verifier authz.InstanceVerifier) (_ context.Context, err error) {
ctx := r.Context()
authCtx, span := tracing.NewServerInterceptorSpan(ctx)
defer func() { span.EndWithError(err) }()
host, err := HostFromRequest(r, headerName)
if err != nil {
requestContext := zitadel_http.DomainContext(ctx)
if requestContext.InstanceHost == "" {
return nil, zerrors.ThrowNotFound(err, "INST-zWq7X", "Errors.IAM.NotFound")
}
instance, err := verifier.InstanceByHost(authCtx, host)
instance, err := verifier.InstanceByHost(authCtx, requestContext.InstanceHost, requestContext.PublicHost)
if err != nil {
return nil, err
}
@@ -90,39 +86,6 @@ func setInstance(r *http.Request, verifier authz.InstanceVerifier, headerName st
return authz.WithInstance(ctx, instance), nil
}
func HostFromRequest(r *http.Request, headerName string) (host string, err error) {
if headerName != "host" {
return hostFromSpecialHeader(r, headerName)
}
return hostFromOrigin(r.Context())
}
func hostFromSpecialHeader(r *http.Request, headerName string) (host string, err error) {
host = r.Header.Get(headerName)
if host == "" {
return "", fmt.Errorf("host header `%s` not found", headerName)
}
return host, nil
}
func hostFromOrigin(ctx context.Context) (host string, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("invalid origin: %w", err)
}
}()
origin := zitadel_http.ComposedOrigin(ctx)
u, err := url.Parse(origin)
if err != nil {
return "", err
}
host = u.Host
if host == "" {
err = errors.New("empty host")
}
return host, err
}
func newZitadelTranslator() *i18n.Translator {
translator, err := i18n.NewZitadelTranslator(language.English)
logging.OnError(err).Panic("unable to get translator")

View File

@@ -19,8 +19,7 @@ import (
func Test_instanceInterceptor_Handler(t *testing.T) {
type fields struct {
verifier authz.InstanceVerifier
headerName string
verifier authz.InstanceVerifier
}
type args struct {
request *http.Request
@@ -38,8 +37,7 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
{
"setInstance error",
fields{
verifier: &mockInstanceVerifier{},
headerName: "header",
verifier: &mockInstanceVerifier{},
},
args{
request: httptest.NewRequest("", "/url", nil),
@@ -52,19 +50,18 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
{
"setInstance ok",
fields{
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
args{
request: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host")
r = r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "host"}))
return r
}(),
},
res{
statusCode: 200,
context: authz.WithInstance(context.Background(), &mockInstance{}),
context: authz.WithInstance(zitadel_http.WithDomainContext(context.Background(), &zitadel_http.DomainCtx{InstanceHost: "host"}), &mockInstance{}),
},
},
}
@@ -72,7 +69,6 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
a := &instanceInterceptor{
verifier: tt.fields.verifier,
headerName: tt.fields.headerName,
translator: newZitadelTranslator(),
}
next := &testHandler{}
@@ -87,8 +83,7 @@ func Test_instanceInterceptor_Handler(t *testing.T) {
func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
type fields struct {
verifier authz.InstanceVerifier
headerName string
verifier authz.InstanceVerifier
}
type args struct {
request *http.Request
@@ -106,8 +101,7 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
{
"setInstance error",
fields{
verifier: &mockInstanceVerifier{},
headerName: "header",
verifier: &mockInstanceVerifier{},
},
args{
request: httptest.NewRequest("", "/url", nil),
@@ -120,19 +114,18 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
{
"setInstance ok",
fields{
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
args{
request: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host")
r = r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "host"}))
return r
}(),
},
res{
statusCode: 200,
context: authz.WithInstance(context.Background(), &mockInstance{}),
context: authz.WithInstance(zitadel_http.WithDomainContext(context.Background(), &zitadel_http.DomainCtx{InstanceHost: "host"}), &mockInstance{}),
},
},
}
@@ -140,7 +133,6 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
a := &instanceInterceptor{
verifier: tt.fields.verifier,
headerName: tt.fields.headerName,
translator: newZitadelTranslator(),
}
next := &testHandler{}
@@ -155,9 +147,8 @@ func Test_instanceInterceptor_HandlerFunc(t *testing.T) {
func Test_setInstance(t *testing.T) {
type args struct {
r *http.Request
verifier authz.InstanceVerifier
headerName string
r *http.Request
verifier authz.InstanceVerifier
}
type res struct {
want context.Context
@@ -169,14 +160,13 @@ func Test_setInstance(t *testing.T) {
res res
}{
{
"special host header not found, error",
"no domain context, not found error",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
return r
}(),
verifier: &mockInstanceVerifier{},
headerName: "",
verifier: &mockInstanceVerifier{},
},
res{
want: nil,
@@ -184,77 +174,27 @@ func Test_setInstance(t *testing.T) {
},
},
{
"special host header invalid, error",
"instanceHost found, ok",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host2")
return r
return r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "host", Protocol: "https"}))
}(),
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
verifier: &mockInstanceVerifier{instanceHost: "host"},
},
res{
want: nil,
err: true,
},
},
{
"special host header valid, ok",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("header", "host")
return r
}(),
verifier: &mockInstanceVerifier{"host"},
headerName: "header",
},
res{
want: authz.WithInstance(context.Background(), &mockInstance{}),
want: authz.WithInstance(zitadel_http.WithDomainContext(context.Background(), &zitadel_http.DomainCtx{InstanceHost: "host", Protocol: "https"}), &mockInstance{}),
err: false,
},
},
{
"host from origin if header is not special, ok",
"instanceHost not found, error",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
r.Header.Set("host", "fromrequest")
return r.WithContext(zitadel_http.WithComposedOrigin(r.Context(), "https://fromorigin:9999"))
return r.WithContext(zitadel_http.WithDomainContext(r.Context(), &zitadel_http.DomainCtx{InstanceHost: "fromorigin:9999", Protocol: "https"}))
}(),
verifier: &mockInstanceVerifier{"fromorigin:9999"},
headerName: "host",
},
res{
want: authz.WithInstance(zitadel_http.WithComposedOrigin(context.Background(), "https://fromorigin:9999"), &mockInstance{}),
err: false,
},
},
{
"host from origin, instance not found",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
return r.WithContext(zitadel_http.WithComposedOrigin(r.Context(), "https://fromorigin:9999"))
}(),
verifier: &mockInstanceVerifier{"unknowndomain"},
headerName: "host",
},
res{
want: nil,
err: true,
},
},
{
"host from origin invalid, err",
args{
r: func() *http.Request {
r := httptest.NewRequest("", "/url", nil)
return r.WithContext(zitadel_http.WithComposedOrigin(r.Context(), "https://from origin:9999"))
}(),
verifier: &mockInstanceVerifier{"from origin"},
headerName: "host",
verifier: &mockInstanceVerifier{instanceHost: "unknowndomain"},
},
res{
want: nil,
@@ -264,7 +204,7 @@ func Test_setInstance(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := setInstance(tt.args.r, tt.args.verifier, tt.args.headerName)
got, err := setInstance(tt.args.r, tt.args.verifier)
if (err != nil) != tt.res.err {
t.Errorf("setInstance() error = %v, wantErr %v", err, tt.res.err)
return
@@ -285,17 +225,24 @@ func (t *testHandler) ServeHTTP(_ http.ResponseWriter, r *http.Request) {
}
type mockInstanceVerifier struct {
host string
instanceHost string
publicHost string
}
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, host string) (authz.Instance, error) {
if host != m.host {
func (m *mockInstanceVerifier) InstanceByHost(_ context.Context, instanceHost, publicHost string) (authz.Instance, error) {
if instanceHost != m.instanceHost {
return nil, fmt.Errorf("invalid host")
}
if publicHost == "" {
return &mockInstance{}, nil
}
if publicHost != instanceHost && publicHost != m.publicHost {
return nil, fmt.Errorf("invalid host")
}
return &mockInstance{}, nil
}
func (m *mockInstanceVerifier) InstanceByID(context.Context) (authz.Instance, error) {
func (m *mockInstanceVerifier) InstanceByID(context.Context, string) (authz.Instance, error) {
return nil, nil
}
@@ -333,14 +280,6 @@ func (m *mockInstance) DefaultOrganisationID() string {
return "orgID"
}
func (m *mockInstance) RequestedDomain() string {
return "zitadel.cloud"
}
func (m *mockInstance) RequestedHost() string {
return "zitadel.cloud:443"
}
func (m *mockInstance) SecurityPolicyAllowedOrigins() []string {
return nil
}

View File

@@ -1,53 +1,82 @@
package middleware
import (
"fmt"
"net/http"
"slices"
"github.com/gorilla/mux"
"github.com/muhlemmer/httpforwarded"
"github.com/zitadel/logging"
http_util "github.com/zitadel/zitadel/internal/api/http"
)
func WithOrigin(fallBackToHttps bool) mux.MiddlewareFunc {
func WithOrigin(fallBackToHttps bool, http1Header, http2Header string, instanceHostHeaders, publicDomainHeaders []string) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := composeOrigin(r, fallBackToHttps)
if !http_util.IsOrigin(origin) {
logging.Debugf("extracted origin is not valid: %s", origin)
next.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r.WithContext(http_util.WithComposedOrigin(r.Context(), origin)))
origin := composeDomainContext(
r,
fallBackToHttps,
// to make sure we don't break existing configurations we append the existing checked headers as well
slices.Compact(append(instanceHostHeaders, http1Header, http2Header, http_util.Forwarded, http_util.ForwardedFor, http_util.ForwardedHost, http_util.ForwardedProto)),
publicDomainHeaders,
)
next.ServeHTTP(w, r.WithContext(http_util.WithDomainContext(r.Context(), origin)))
})
}
}
func composeOrigin(r *http.Request, fallBackToHttps bool) string {
var proto, host string
fwd, fwdErr := httpforwarded.ParseFromRequest(r)
if fwdErr == nil {
proto = oldestForwardedValue(fwd, "proto")
host = oldestForwardedValue(fwd, "host")
func composeDomainContext(r *http.Request, fallBackToHttps bool, instanceDomainHeaders, publicDomainHeaders []string) *http_util.DomainCtx {
instanceHost, instanceProto := hostFromRequest(r, instanceDomainHeaders)
publicHost, publicProto := hostFromRequest(r, publicDomainHeaders)
if publicProto == "" {
publicProto = instanceProto
}
if proto == "" {
proto = r.Header.Get("X-Forwarded-Proto")
}
if host == "" {
host = r.Header.Get("X-Forwarded-Host")
}
if proto == "" {
proto = "http"
if publicProto == "" {
publicProto = "http"
if fallBackToHttps {
proto = "https"
publicProto = "https"
}
}
if host == "" {
host = r.Host
if instanceHost == "" {
instanceHost = r.Host
}
return fmt.Sprintf("%s://%s", proto, host)
return &http_util.DomainCtx{
InstanceHost: instanceHost,
Protocol: publicProto,
PublicHost: publicHost,
}
}
func hostFromRequest(r *http.Request, headers []string) (host, proto string) {
var hostFromHeader, protoFromHeader string
for _, header := range headers {
switch http.CanonicalHeaderKey(header) {
case http.CanonicalHeaderKey(http_util.Forwarded),
http.CanonicalHeaderKey(http_util.ForwardedFor):
hostFromHeader, protoFromHeader = hostFromForwarded(r.Header.Values(header))
case http.CanonicalHeaderKey(http_util.ForwardedHost):
hostFromHeader = r.Header.Get(header)
case http.CanonicalHeaderKey(http_util.ForwardedProto):
protoFromHeader = r.Header.Get(header)
default:
hostFromHeader = r.Header.Get(header)
}
if host == "" {
host = hostFromHeader
}
if proto == "" {
proto = protoFromHeader
}
}
return host, proto
}
func hostFromForwarded(values []string) (string, string) {
fwd, fwdErr := httpforwarded.Parse(values)
if fwdErr == nil {
return oldestForwardedValue(fwd, "host"), oldestForwardedValue(fwd, "proto")
}
return "", ""
}
func oldestForwardedValue(forwarded map[string][]string, key string) string {

View File

@@ -5,6 +5,8 @@ import (
"testing"
"github.com/stretchr/testify/assert"
http_util "github.com/zitadel/zitadel/internal/api/http"
)
func Test_composeOrigin(t *testing.T) {
@@ -15,10 +17,13 @@ func Test_composeOrigin(t *testing.T) {
tests := []struct {
name string
args args
want string
want *http_util.DomainCtx
}{{
name: "no proxy headers",
want: "http://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "http",
},
}, {
name: "forwarded proto",
args: args{
@@ -27,7 +32,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "https",
},
}, {
name: "forwarded host",
args: args{
@@ -36,7 +44,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "http://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "http",
},
}, {
name: "forwarded proto and host",
args: args{
@@ -45,7 +56,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded proto and host with multiple complete entries",
args: args{
@@ -54,7 +68,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded proto and host with multiple incomplete entries",
args: args{
@@ -63,7 +80,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded proto and host with incomplete entries in different values",
args: args{
@@ -72,7 +92,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: true,
},
want: "http://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "http",
},
}, {
name: "x-forwarded-proto https",
args: args{
@@ -81,7 +104,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "https",
},
}, {
name: "x-forwarded-proto http",
args: args{
@@ -90,19 +116,28 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: true,
},
want: "http://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "http",
},
}, {
name: "fallback to http",
args: args{
fallBackToHttps: false,
},
want: "http://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "http",
},
}, {
name: "fallback to https",
args: args{
fallBackToHttps: true,
},
want: "https://host.header",
want: &http_util.DomainCtx{
InstanceHost: "host.header",
Protocol: "https",
},
}, {
name: "x-forwarded-host",
args: args{
@@ -111,7 +146,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "http://x-forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "x-forwarded.host",
Protocol: "http",
},
}, {
name: "x-forwarded-proto and x-forwarded-host",
args: args{
@@ -121,7 +159,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://x-forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "x-forwarded.host",
Protocol: "https",
},
}, {
name: "forwarded host and x-forwarded-host",
args: args{
@@ -131,7 +172,10 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "http://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "http",
},
}, {
name: "forwarded host and x-forwarded-proto",
args: args{
@@ -141,17 +185,22 @@ func Test_composeOrigin(t *testing.T) {
},
fallBackToHttps: false,
},
want: "https://forwarded.host",
want: &http_util.DomainCtx{
InstanceHost: "forwarded.host",
Protocol: "https",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, composeOrigin(
assert.Equalf(t, tt.want, composeDomainContext(
&http.Request{
Host: "host.header",
Header: tt.args.h,
},
tt.args.fallBackToHttps,
[]string{http_util.Forwarded, http_util.ForwardedFor, http_util.ForwardedHost, http_util.ForwardedProto},
[]string{"x-zitadel-public-host"},
), "headers: %+v, fallBackToHttps: %t", tt.args.h, tt.args.fallBackToHttps)
})
}

View File

@@ -0,0 +1,60 @@
package http
import (
"context"
"fmt"
"strings"
)
type DomainCtx struct {
InstanceHost string
PublicHost string
Protocol string
}
// RequestedHost returns the host (hostname[:port]) for which the request was handled.
// The instance host is returned if not public host was set.
func (r *DomainCtx) RequestedHost() string {
if r.PublicHost != "" {
return r.PublicHost
}
return r.InstanceHost
}
// RequestedDomain returns the domain (hostname) for which the request was handled.
// The instance domain is returned if not public host / domain was set.
func (r *DomainCtx) RequestedDomain() string {
return strings.Split(r.RequestedHost(), ":")[0]
}
// Origin returns the origin (protocol://hostname[:port]) for which the request was handled.
// The instance host is used if not public host was set.
func (r *DomainCtx) Origin() string {
host := r.PublicHost
if host == "" {
host = r.InstanceHost
}
return fmt.Sprintf("%s://%s", r.Protocol, host)
}
func DomainContext(ctx context.Context) *DomainCtx {
o, ok := ctx.Value(domainCtx).(*DomainCtx)
if !ok {
return &DomainCtx{}
}
return o
}
func WithDomainContext(ctx context.Context, domainContext *DomainCtx) context.Context {
return context.WithValue(ctx, domainCtx, domainContext)
}
func WithRequestedHost(ctx context.Context, host string) context.Context {
i, ok := ctx.Value(domainCtx).(*DomainCtx)
if !ok {
i = new(DomainCtx)
}
i.PublicHost = host
return context.WithValue(ctx, domainCtx, i)
}

View File

@@ -13,7 +13,6 @@ import (
"github.com/gorilla/mux"
"github.com/zitadel/logging"
"github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/ui/login"
"github.com/zitadel/zitadel/internal/command"
@@ -79,21 +78,21 @@ type externalSAMLIDPCallbackData struct {
}
// CallbackURL generates the instance specific URL to the IDP callback handler
func CallbackURL(externalSecure bool) func(ctx context.Context) string {
func CallbackURL() func(ctx context.Context) string {
return func(ctx context.Context) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + HandlerPrefix + callbackPath
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix + callbackPath
}
}
func SAMLRootURL(externalSecure bool) func(ctx context.Context, idpID string) string {
func SAMLRootURL() func(ctx context.Context, idpID string) string {
return func(ctx context.Context, idpID string) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + HandlerPrefix + "/" + idpID + "/"
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix + "/" + idpID + "/"
}
}
func LoginSAMLRootURL(externalSecure bool) func(ctx context.Context) string {
func LoginSAMLRootURL() func(ctx context.Context) string {
return func(ctx context.Context) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), externalSecure) + login.HandlerPrefix + login.EndpointSAMLACS
return http_utils.DomainContext(ctx).Origin() + login.HandlerPrefix + login.EndpointSAMLACS
}
}
@@ -101,7 +100,6 @@ func NewHandler(
commands *command.Commands,
queries *query.Queries,
encryptionAlgorithm crypto.EncryptionAlgorithm,
externalSecure bool,
instanceInterceptor func(next http.Handler) http.Handler,
) http.Handler {
h := &Handler{
@@ -109,9 +107,9 @@ func NewHandler(
queries: queries,
parser: form.NewParser(),
encryptionAlgorithm: encryptionAlgorithm,
callbackURL: CallbackURL(externalSecure),
samlRootURL: SAMLRootURL(externalSecure),
loginSAMLRootURL: LoginSAMLRootURL(externalSecure),
callbackURL: CallbackURL(),
samlRootURL: SAMLRootURL(),
loginSAMLRootURL: LoginSAMLRootURL(),
}
router := mux.NewRouter()

View File

@@ -60,7 +60,7 @@ func (c *DeviceAuthorizationConfig) toOPConfig() op.DeviceAuthorizationConfig {
out.UserCode.CharAmount = c.UserCode.CharAmount
}
if c.UserCode.DashInterval != 0 {
out.UserCode.DashInterval = c.UserCode.CharAmount
out.UserCode.DashInterval = c.UserCode.DashInterval
}
return out
}

View File

@@ -14,7 +14,6 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/repository/instance"
@@ -208,7 +207,7 @@ func (k keySetMap) getKey(keyID string) (*jose.JSONWebKey, error) {
return &jose.JSONWebKey{
Key: pubKey,
KeyID: keyID,
Use: domain.KeyUsageSigning.String(),
Use: crypto.KeyUsageSigning.String(),
}, nil
}

View File

@@ -12,14 +12,14 @@ import (
"github.com/stretchr/testify/require"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/query"
)
type publicKey struct {
id string
alg string
use domain.KeyUsage
use crypto.KeyUsage
seq uint64
expiry time.Time
key any
@@ -33,7 +33,7 @@ func (k *publicKey) Algorithm() string {
return k.alg
}
func (k *publicKey) Use() domain.KeyUsage {
func (k *publicKey) Use() crypto.KeyUsage {
return k.use
}
@@ -55,21 +55,21 @@ var (
"key1": {
id: "key1",
alg: "alg",
use: domain.KeyUsageSigning,
use: crypto.KeyUsageSigning,
seq: 1,
expiry: clock.Now().Add(time.Minute),
},
"key2": {
id: "key2",
alg: "alg",
use: domain.KeyUsageSigning,
use: crypto.KeyUsageSigning,
seq: 3,
expiry: clock.Now().Add(10 * time.Hour),
},
"exp1": {
id: "key2",
alg: "alg",
use: domain.KeyUsageSigning,
use: crypto.KeyUsageSigning,
seq: 4,
expiry: clock.Now().Add(-time.Hour),
},

View File

@@ -100,7 +100,7 @@ func NewServer(
if err != nil {
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)
keyCache := newPublicKeyCache(ctx, config.PublicKeyCacheMaxAge, query.GetPublicKeyByID)
accessTokenKeySet := newOidcKeySet(keyCache, withKeyExpiryCheck(true))
idTokenHintKeySet := newOidcKeySet(keyCache)
@@ -115,7 +115,7 @@ func NewServer(
provider, err := op.NewProvider(
opConfig,
storage,
op.IssuerFromForwardedOrHost("", op.WithIssuerFromCustomHeaders("forwarded", "x-zitadel-forwarded")),
IssuerFromContext,
options...,
)
if err != nil {
@@ -142,7 +142,7 @@ func NewServer(
signingKeyAlgorithm: config.SigningKeyAlgorithm,
encAlg: encryptionAlg,
opCrypto: op.NewAESCrypto(opConfig.CryptoKey),
assetAPIPrefix: assets.AssetAPI(externalSecure),
assetAPIPrefix: assets.AssetAPI(),
}
metricTypes := []metrics.MetricType{metrics.MetricTypeRequestCount, metrics.MetricTypeStatusCode, metrics.MetricTypeTotalCount}
server.Handler = op.RegisterLegacyServer(server,
@@ -162,6 +162,12 @@ func NewServer(
return server, nil
}
func IssuerFromContext(_ bool) (op.IssuerFromRequest, error) {
return func(r *http.Request) string {
return http_utils.DomainContext(r.Context()).Origin()
}, nil
}
func publicAuthPathPrefixes(endpoints *EndpointConfig) []string {
authURL := op.DefaultEndpoints.Authorization.Relative()
keysURL := op.DefaultEndpoints.JwksURI.Relative()
@@ -194,7 +200,7 @@ func createOPConfig(config Config, defaultLogoutRedirectURI string, cryptoKey []
return opConfig, nil
}
func newStorage(config Config, command *command.Commands, query *query.Queries, repo repository.Repository, encAlg crypto.EncryptionAlgorithm, es *eventstore.Eventstore, db *database.DB, externalSecure bool) *OPStorage {
func newStorage(config Config, command *command.Commands, query *query.Queries, repo repository.Repository, encAlg crypto.EncryptionAlgorithm, es *eventstore.Eventstore, db *database.DB) *OPStorage {
return &OPStorage{
repo: repo,
command: command,
@@ -210,7 +216,7 @@ func newStorage(config Config, command *command.Commands, query *query.Queries,
defaultRefreshTokenExpiration: config.DefaultRefreshTokenExpiration,
encAlg: encAlg,
locker: crdb.NewLocker(db.DB, locksTable, signingKey),
assetAPIPrefix: assets.AssetAPI(externalSecure),
assetAPIPrefix: assets.AssetAPI(),
}
}

View File

@@ -11,7 +11,6 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/repository/instance"
@@ -53,7 +52,7 @@ func (c *CertificateAndKey) ID() string {
return c.id
}
func (p *Storage) GetCertificateAndKey(ctx context.Context, usage domain.KeyUsage) (certAndKey *key.CertificateAndKey, err error) {
func (p *Storage) GetCertificateAndKey(ctx context.Context, usage crypto.KeyUsage) (certAndKey *key.CertificateAndKey, err error) {
err = retry(func() error {
certAndKey, err = p.getCertificateAndKey(ctx, usage)
if err != nil {
@@ -67,7 +66,7 @@ func (p *Storage) GetCertificateAndKey(ctx context.Context, usage domain.KeyUsag
return certAndKey, err
}
func (p *Storage) getCertificateAndKey(ctx context.Context, usage domain.KeyUsage) (*key.CertificateAndKey, error) {
func (p *Storage) getCertificateAndKey(ctx context.Context, usage crypto.KeyUsage) (*key.CertificateAndKey, error) {
certs, err := p.query.ActiveCertificates(ctx, time.Now().Add(gracefulPeriod), usage)
if err != nil {
return nil, err
@@ -87,7 +86,7 @@ func (p *Storage) getCertificateAndKey(ctx context.Context, usage domain.KeyUsag
func (p *Storage) refreshCertificate(
ctx context.Context,
usage domain.KeyUsage,
usage crypto.KeyUsage,
position float64,
) error {
ok, err := p.ensureIsLatestCertificate(ctx, position)
@@ -112,7 +111,7 @@ func (p *Storage) ensureIsLatestCertificate(ctx context.Context, position float6
return position >= maxSequence, nil
}
func (p *Storage) lockAndGenerateCertificateAndKey(ctx context.Context, usage domain.KeyUsage) error {
func (p *Storage) lockAndGenerateCertificateAndKey(ctx context.Context, usage crypto.KeyUsage) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx = setSAMLCtx(ctx)
@@ -128,8 +127,8 @@ func (p *Storage) lockAndGenerateCertificateAndKey(ctx context.Context, usage do
}
switch usage {
case domain.KeyUsageSAMLMetadataSigning, domain.KeyUsageSAMLResponseSinging:
certAndKey, err := p.GetCertificateAndKey(ctx, domain.KeyUsageSAMLCA)
case crypto.KeyUsageSAMLMetadataSigning, crypto.KeyUsageSAMLResponseSinging:
certAndKey, err := p.GetCertificateAndKey(ctx, crypto.KeyUsageSAMLCA)
if err != nil {
return fmt.Errorf("error while reading ca certificate: %w", err)
}
@@ -138,14 +137,14 @@ func (p *Storage) lockAndGenerateCertificateAndKey(ctx context.Context, usage do
}
switch usage {
case domain.KeyUsageSAMLMetadataSigning:
case crypto.KeyUsageSAMLMetadataSigning:
return p.command.GenerateSAMLMetadataCertificate(setSAMLCtx(ctx), p.certificateAlgorithm, certAndKey.Key, certAndKey.Certificate)
case domain.KeyUsageSAMLResponseSinging:
case crypto.KeyUsageSAMLResponseSinging:
return p.command.GenerateSAMLResponseCertificate(setSAMLCtx(ctx), p.certificateAlgorithm, certAndKey.Key, certAndKey.Certificate)
default:
return fmt.Errorf("unknown usage")
}
case domain.KeyUsageSAMLCA:
case crypto.KeyUsageSAMLCA:
return p.command.GenerateSAMLCACertificate(setSAMLCtx(ctx), p.certificateAlgorithm)
default:
return fmt.Errorf("unknown certificate usage")

View File

@@ -87,15 +87,15 @@ func (p *Storage) Health(context.Context) error {
}
func (p *Storage) GetCA(ctx context.Context) (*key.CertificateAndKey, error) {
return p.GetCertificateAndKey(ctx, domain.KeyUsageSAMLCA)
return p.GetCertificateAndKey(ctx, crypto.KeyUsageSAMLCA)
}
func (p *Storage) GetMetadataSigningKey(ctx context.Context) (*key.CertificateAndKey, error) {
return p.GetCertificateAndKey(ctx, domain.KeyUsageSAMLMetadataSigning)
return p.GetCertificateAndKey(ctx, crypto.KeyUsageSAMLMetadataSigning)
}
func (p *Storage) GetResponseSigningKey(ctx context.Context) (*key.CertificateAndKey, error) {
return p.GetCertificateAndKey(ctx, domain.KeyUsageSAMLResponseSinging)
return p.GetCertificateAndKey(ctx, crypto.KeyUsageSAMLResponseSinging)
}
func (p *Storage) CreateAuthRequest(ctx context.Context, req *samlp.AuthnRequestType, acsUrl, protocolBinding, relayState, applicationID string) (_ models.AuthRequestInt, err error) {

View File

@@ -21,6 +21,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/http/middleware"
console_path "github.com/zitadel/zitadel/internal/api/ui/console/path"
)
type Config struct {
@@ -40,7 +41,6 @@ var (
const (
envRequestPath = "/assets/environment.json"
HandlerPrefix = "/ui/console"
)
var (
@@ -56,7 +56,7 @@ var (
)
func LoginHintLink(origin, username string) string {
return origin + HandlerPrefix + "?login_hint=" + username
return origin + console_path.HandlerPrefix + "?login_hint=" + username
}
func (i *spaHandler) Open(name string) (http.File, error) {

View File

@@ -0,0 +1,7 @@
package path
const (
HandlerPrefix = "/ui/console"
RedirectPath = HandlerPrefix + "/auth/callback"
PostLogoutPath = HandlerPrefix + "/signedout"
)

View File

@@ -533,9 +533,10 @@ func (l *Login) externalUserNotExisting(w http.ResponseWriter, r *http.Request,
}
}
// if auto creation or creation itself is disabled, send the user to the notFoundOption
if !provider.IsCreationAllowed || !provider.IsAutoCreation {
l.renderExternalNotFoundOption(w, r, authReq, orgIAMPolicy, human, idpLink, err)
// if auto creation is disabled, send the user to the notFoundOption
// where they can either link or create an account (based on the available options)
if !provider.IsAutoCreation {
l.renderExternalNotFoundOption(w, r, authReq, orgIAMPolicy, human, idpLink, nil)
return
}
@@ -614,6 +615,10 @@ func (l *Login) renderExternalNotFoundOption(w http.ResponseWriter, r *http.Requ
l.renderError(w, r, authReq, err)
return
}
if !idpTemplate.IsCreationAllowed && !idpTemplate.IsLinkingAllowed {
l.renderError(w, r, authReq, zerrors.ThrowPreconditionFailed(nil, "LOGIN-3kl44", "Errors.User.ExternalIDP.NoOptionAllowed"))
return
}
translator := l.getTranslator(r.Context(), authReq)
data := externalNotFoundOptionData{
@@ -1042,7 +1047,7 @@ func (l *Login) samlProvider(ctx context.Context, identityProvider *query.IDPTem
opts = append(opts, saml.WithTransientMappingAttributeName(identityProvider.SAMLIDPTemplate.TransientMappingAttributeName))
}
opts = append(opts,
saml.WithEntityID(http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), l.externalSecure)+"/idps/"+identityProvider.ID+"/saml/metadata"),
saml.WithEntityID(http_utils.DomainContext(ctx).Origin()+"/idps/"+identityProvider.ID+"/saml/metadata"),
saml.WithCustomRequestTracker(
requesttracker.New(
func(ctx context.Context, authRequestID, samlRequestID string) error {

View File

@@ -19,6 +19,9 @@ func (l *Login) linkUsers(w http.ResponseWriter, r *http.Request, authReq *domai
func (l *Login) renderLinkUsersDone(w http.ResponseWriter, r *http.Request, authReq *domain.AuthRequest, err error) {
var errType, errMessage string
if err != nil {
errType, errMessage = l.getErrorMessage(r, err)
}
translator := l.getTranslator(r.Context(), authReq)
data := l.getUserData(r, authReq, translator, "LinkingUsersDone.Title", "LinkingUsersDone.Description", errType, errMessage)
l.renderer.RenderTemplate(w, r, translator, l.renderer.Templates[tmplLinkUsersDone], data, nil)

View File

@@ -129,7 +129,7 @@ func createCSRFInterceptor(cookieName string, csrfCookieKey []byte, externalSecu
sameSiteMode = csrf.SameSiteNoneMode
// ... and since SameSite none requires the secure flag, we'll set it for TLS and for localhost
// (regardless of the TLS / externalSecure settings)
secureOnly = externalSecure || instance.RequestedDomain() == "localhost"
secureOnly = externalSecure || http_utils.DomainContext(r.Context()).RequestedDomain() == "localhost"
}
csrf.Protect(csrfCookieKey,
csrf.Secure(secureOnly),
@@ -163,7 +163,7 @@ func (l *Login) Handler() http.Handler {
}
func (l *Login) getClaimedUserIDsOfOrgDomain(ctx context.Context, orgName string) ([]string, error) {
orgDomain, err := domain.NewIAMDomainName(orgName, authz.GetInstance(ctx).RequestedDomain())
orgDomain, err := domain.NewIAMDomainName(orgName, http_utils.DomainContext(ctx).RequestedDomain())
if err != nil {
return nil, err
}
@@ -171,7 +171,7 @@ func (l *Login) getClaimedUserIDsOfOrgDomain(ctx context.Context, orgName string
if err != nil {
return nil, err
}
users, err := l.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: []query.SearchQuery{loginName}})
users, err := l.query.SearchUsers(ctx, &query.UserSearchQueries{Queries: []query.SearchQuery{loginName}}, nil)
if err != nil {
return nil, err
}
@@ -199,5 +199,5 @@ func setUserContext(ctx context.Context, userID, resourceOwner string) context.C
}
func (l *Login) baseURL(ctx context.Context) string {
return http_utils.BuildOrigin(authz.GetInstance(ctx).RequestedHost(), l.externalSecure) + HandlerPrefix
return http_utils.DomainContext(ctx).Origin() + HandlerPrefix
}

View File

@@ -18,7 +18,7 @@ func (l *Login) getOrgDomainPolicy(r *http.Request, orgID string) (*query.Domain
}
func (l *Login) getIDPByID(r *http.Request, id string) (*query.IDPTemplate, error) {
return l.query.IDPTemplateByID(r.Context(), false, id, false)
return l.query.IDPTemplateByID(r.Context(), false, id, false, nil)
}
func (l *Login) getLoginPolicy(r *http.Request, orgID string) (*query.LoginPolicy, error) {

View File

@@ -3,7 +3,7 @@ package login
import (
"net/http"
"github.com/zitadel/zitadel/internal/api/authz"
http_util "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/zerrors"
@@ -128,7 +128,7 @@ func (l *Login) renderRegisterOrg(w http.ResponseWriter, r *http.Request, authRe
orgPolicy, _ := l.getDefaultDomainPolicy(r)
if orgPolicy != nil {
data.UserLoginMustBeDomain = orgPolicy.UserLoginMustBeDomain
data.IamDomain = authz.GetInstance(r.Context()).RequestedDomain()
data.IamDomain = http_util.DomainContext(r.Context()).RequestedDomain()
}
if authRequest == nil {

View File

@@ -475,6 +475,7 @@ Errors:
NoExternalUserData: Не са получени външни потребителски данни
CreationNotAllowed: Създаването на нов потребител не е разрешено на този доставчик
LinkingNotAllowed: Свързването на потребител не е разрешено на този доставчик
NoOptionAllowed: Нито създаване, нито свързване е разрешено за този доставчик. Моля, свържете се с администратора.
GrantRequired: 'Влизането не е възможно. '
ProjectRequired: 'Влизането не е възможно. '
IdentityProvider:

View File

@@ -486,6 +486,7 @@ Errors:
NoExternalUserData: Nebyla přijata žádná externí uživatelská data
CreationNotAllowed: Vytvoření nového uživatele není na tomto poskytovateli povoleno
LinkingNotAllowed: Propojení uživatele není na tomto poskytovateli povoleno
NoOptionAllowed: Ani vytvoření, ani propojení není povoleno pro tohoto poskytovatele. Obraťte se na svého správce.
GrantRequired: Přihlášení není možné. Uživatel musí mít alespoň jeden oprávnění na aplikaci. Prosím, kontaktujte svého správce.
ProjectRequired: Přihlášení není možné. Organizace uživatele musí být přidělena k projektu. Prosím, kontaktujte svého správce.
IdentityProvider:

View File

@@ -485,6 +485,7 @@ Errors:
NoExternalUserData: Keine externen User-Daten erhalten
CreationNotAllowed: Erstellen eines neuen Benutzers mit diesem Provider ist nicht erlaubt
LinkingNotAllowed: Verknüpfen eines Benutzers mit diesem Provider ist nicht erlaubt
NoOptionAllowed: Weder Erstellung noch Verknüpfung ist für diesen Provider erlaubt. Bitte wenden Sie sich an Ihren Administrator.
GrantRequired: Die Anmeldung an diese Applikation ist nicht möglich. Der Benutzer benötigt mindestens eine Berechtigung an der Applikation. Bitte wende dich an deinen Administrator.
ProjectRequired: Die Anmeldung an dieser Applikation ist nicht möglich. Die Organisation des Benutzer benötigt Berechtigung auf das Projekt. Bitte wende dich an deinen Administrator.
IdentityProvider:

View File

@@ -484,8 +484,9 @@ Errors:
ExternalUserIDEmpty: External User ID is empty
UserDisplayNameEmpty: User Display Name is empty
NoExternalUserData: No external User Data received
CreationNotAllowed: Creation of a new user is not allowed on this Provider
LinkingNotAllowed: Linking of a user is not allowed on this Provider
CreationNotAllowed: Creation of a new user is not allowed on this provider
LinkingNotAllowed: Linking of a user is not allowed on this provider
NoOptionAllowed: Neither creation of linking is allowed on this provider. Please contact your administrator.
GrantRequired: Login not possible. The user is required to have at least one grant on the application. Please contact your administrator.
ProjectRequired: Login not possible. The organization of the user must be granted to the project. Please contact your administrator.
IdentityProvider:

View File

@@ -469,6 +469,7 @@ Errors:
NoExternalUserData: No se recibieron datos del usuario externo
CreationNotAllowed: La creación de un nuevo usuario no está permitida para este proveedor
LinkingNotAllowed: La vinculación de un usuario no está permitida para este proveedor
NoOptionAllowed: Ni la creación ni la vinculación están permitidas en este proveedor. Póngase en contacto con su administrador.
GrantRequired: El inicio de sesión no es posible. Se requiere que el usuario tenga al menos una concesión sobre la aplicación. Por favor contacta con tu administrador.
ProjectRequired: El inicio de sesión no es posible. La organización del usuario debe tener el acceso concedido para el proyecto. Por favor contacta con tu administrador.
IdentityProvider:

View File

@@ -487,6 +487,7 @@ Errors:
NoExternalUserData: Aucune donnée d'utilisateur externe reçue
CreationNotAllowed: La création d'un nouvel utilisateur n'est pas autorisée sur ce fournisseur.
LinkingNotAllowed: La création d'un lien vers un utilisateur n'est pas autorisée pour ce fournisseur.
NoOptionAllowed: Ni la création ni la liaison sont autorisées pour ce fournisseur. Veuillez contacter votre administrateur.
GrantRequired: Connexion impossible. L'utilisateur doit avoir au moins une subvention sur l'application. Veuillez contacter votre administrateur.
ProjectRequired: Connexion impossible. L'organisation de l'utilisateur doit être accordée au projet. Veuillez contacter votre administrateur.
IdentityProvider:

View File

@@ -487,6 +487,7 @@ Errors:
NoExternalUserData: Nessun dato utente esterno ricevuto
CreationNotAllowed: La creazione di un nuovo utente non è consentita su questo provider.
LinkingNotAllowed: Il collegamento di un utente non è consentito su questo provider.
NoOptionAllowed: Né la creazione né il collegamento sono consentiti per questo provider. Contattare l'amministratore.
GrantRequired: Accesso non possibile. L'utente deve avere almeno una sovvenzione sull'applicazione. Contatta il tuo amministratore.
ProjectRequired: Accesso non possibile. L'organizzazione dell'utente deve essere concessa al progetto. Contatta il tuo amministratore.
IdentityProvider:

View File

@@ -450,6 +450,7 @@ Errors:
NoExternalUserData: 外部ユーザー情報を取得できません
CreationNotAllowed: このプロバイダーでは、新しいユーザーの作成は許可されていません
LinkingNotAllowed: このプロバイダーでは、ユーザーのリンクが許可されていません
NoOptionAllowed: このプロバイダーでは作成もリンクも許可されていません。 管理者にお問い合わせください。
GrantRequired: ログインできません。このユーザーは、アプリケーションに少なくとも1つの権限を付与されていることが必要です。管理者にお問い合わせください。
ProjectRequired: ログインできません。ユーザーの組織がプロジェクトに権限を付与されている必要があります。管理者にお問い合わせください。
IdentityProvider:

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