feat(action v2): add JWT and JWE payload type options (#11196)

# Which Problems Are Solved

The payload in actions V2 is currently sent as JSON to the target
endpoint. It might get exposed to intermediary infrastructure or logging
systems.
For these scenarios there needs to be an application-layer encryption,
where the provider of the endpoint can define an key to be used for the
encryption.

# How the Problems Are Solved

- Added an additional option to the target to specify the payload type:
`JSON` (current and default), `JWT`, `JWE` (api and console)
- added endpoints to upload and manage public keys (to be used for
encryption) for a target
- updated all action v2 executions (interceptors, oidc, saml, ...) to
provide the `GetActiveSigningWebKey` from queries
- implemented jwt and jwe in the exections incl. refactoring of code and
tests
- changes to the authn_keys table:
  - added a `fingerprint` column
  - dropped not null constraint on expiration
- moved the `GetSignerOnce` into its own package to prevent circular
dependencies

# Additional Changes

None

# Additional Context

closes #11061

---------

Co-authored-by: Marco A. <[email protected]>
Co-authored-by: conblem <[email protected]>
Co-authored-by: Silvan <[email protected]>
This commit is contained in:
Livio Spring
2025-12-29 13:35:53 +00:00
committed by GitHub
co-authored by Marco A. conblem Silvan
parent 72c8f0192c
commit 791d0587aa
124 changed files with 5040 additions and 782 deletions
+1 -1
View File
@@ -207,7 +207,7 @@ func (a *API) registerConnectServer(service server.ConnectServer) {
connect_middleware.AuthorizationInterceptor(a.verifier, a.systemAuthZ, a.authConfig),
connect_middleware.TranslationHandler(),
connect_middleware.QuotaExhaustedInterceptor(a.accessInterceptor.AccessService(), system_pb.SystemService_ServiceDesc.ServiceName),
connect_middleware.ExecutionHandler(a.targetEncryptionAlgorithm),
connect_middleware.ExecutionHandler(a.targetEncryptionAlgorithm, a.queries.GetActiveSigningWebKey),
connect_middleware.ValidationHandler(),
connect_middleware.ServiceHandler(),
connect_middleware.ActivityInterceptor(),
@@ -72,8 +72,9 @@ func TestServer_ExecutionTarget(t *testing.T) {
// create target for target changes
targetCreatedName := integration.TargetName()
targetCreatedURL := "https://nonexistent"
targetCreatedPayloadType := action.PayloadType_PAYLOAD_TYPE_JSON
targetCreated := instance.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false)
targetCreated := instance.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false, targetCreatedPayloadType)
// request received by target
wantRequest := &middleware.ContextInfoRequest{
@@ -89,7 +90,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
// replace original request with different targetID
urlRequest, closeRequest, calledRequest, _ := integration.TestServerCallProto(wantRequest, 0, http.StatusOK, changedRequest)
targetRequest := waitForTarget(ctx, t, instance, urlRequest, target_domain.TargetTypeCall, false)
targetRequest := waitForTarget(ctx, t, instance, urlRequest, target_domain.TargetTypeCall, false, targetCreatedPayloadType)
waitForExecutionOnCondition(ctx, t, instance, conditionRequestFullMethod(fullMethod), []string{targetRequest.GetId()})
@@ -105,9 +106,10 @@ func TestServer_ExecutionTarget(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
PayloadType: targetCreatedPayloadType,
},
}
@@ -122,9 +124,10 @@ func TestServer_ExecutionTarget(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
PayloadType: targetCreatedPayloadType,
},
}
// content for update
@@ -138,9 +141,10 @@ func TestServer_ExecutionTarget(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
PayloadType: targetCreatedPayloadType,
}
// response received by target
@@ -157,7 +161,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
// after request with different targetID, return changed response
targetResponseURL, closeResponse, calledResponse, _ := integration.TestServerCallProto(wantResponse, 0, http.StatusOK, changedResponse)
targetResponse := waitForTarget(ctx, t, instance, targetResponseURL, target_domain.TargetTypeCall, false)
targetResponse := waitForTarget(ctx, t, instance, targetResponseURL, target_domain.TargetTypeCall, false, targetCreatedPayloadType)
waitForExecutionOnCondition(ctx, t, instance, conditionResponseFullMethod(fullMethod), []string{targetResponse.GetId()})
return func() {
closeRequest()
@@ -195,7 +199,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
wantRequest := &middleware.ContextInfoRequest{FullMethod: fullMethod, InstanceID: instance.ID(), OrgID: orgID, ProjectID: projectID, UserID: userID, Request: middleware.Message{Message: request}}
urlRequest, closeRequest, calledRequest, _ := integration.TestServerCallProto(wantRequest, 0, http.StatusInternalServerError, nil)
targetRequest := waitForTarget(ctx, t, instance, urlRequest, target_domain.TargetTypeCall, true)
targetRequest := waitForTarget(ctx, t, instance, urlRequest, target_domain.TargetTypeCall, true, action.PayloadType_PAYLOAD_TYPE_JSON)
waitForExecutionOnCondition(ctx, t, instance, conditionRequestFullMethod(fullMethod), []string{targetRequest.GetId()})
// GetTarget with used target
request.Id = targetRequest.GetId()
@@ -222,8 +226,9 @@ func TestServer_ExecutionTarget(t *testing.T) {
// create target for target changes
targetCreatedName := integration.TargetName()
targetCreatedURL := "https://nonexistent"
targetCreatedPayloadType := action.PayloadType_PAYLOAD_TYPE_JSON
targetCreated := instance.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false)
targetCreated := instance.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false, targetCreatedPayloadType)
// GetTarget with used target
request.Id = targetCreated.GetId()
@@ -240,9 +245,10 @@ func TestServer_ExecutionTarget(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
Timeout: durationpb.New(5 * time.Second),
Endpoint: targetCreatedURL,
SigningKey: targetCreated.GetSigningKey(),
PayloadType: targetCreatedPayloadType,
},
}
@@ -259,7 +265,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
// after request with different targetID, return changed response
targetResponseURL, closeResponse, calledResponse, _ := integration.TestServerCallProto(wantResponse, 0, http.StatusInternalServerError, nil)
targetResponse := waitForTarget(ctx, t, instance, targetResponseURL, target_domain.TargetTypeCall, true)
targetResponse := waitForTarget(ctx, t, instance, targetResponseURL, target_domain.TargetTypeCall, true, targetCreatedPayloadType)
waitForExecutionOnCondition(ctx, t, instance, conditionResponseFullMethod(fullMethod), []string{targetResponse.GetId()})
return func() {
closeResponse()
@@ -307,7 +313,7 @@ func TestServer_ExecutionTarget_Event(t *testing.T) {
urlRequest, closeF, calledF, resetF := integration.TestServerCall(nil, 0, http.StatusOK, nil)
defer closeF()
targetResponse := waitForTarget(isolatedIAMOwnerCTX, t, instance, urlRequest, target_domain.TargetTypeWebhook, true)
targetResponse := waitForTarget(isolatedIAMOwnerCTX, t, instance, urlRequest, target_domain.TargetTypeWebhook, true, action.PayloadType_PAYLOAD_TYPE_JSON)
waitForExecutionOnCondition(isolatedIAMOwnerCTX, t, instance, conditionEvent(event), []string{targetResponse.GetId()})
tests := []struct {
@@ -365,7 +371,7 @@ func TestServer_ExecutionTarget_Event_LongerThanTargetTimeout(t *testing.T) {
urlRequest, closeF, calledF, resetF := integration.TestServerCall(nil, 5*time.Second, http.StatusOK, nil)
defer closeF()
targetResponse := waitForTarget(isolatedIAMOwnerCTX, t, instance, urlRequest, target_domain.TargetTypeWebhook, true)
targetResponse := waitForTarget(isolatedIAMOwnerCTX, t, instance, urlRequest, target_domain.TargetTypeWebhook, true, action.PayloadType_PAYLOAD_TYPE_JSON)
waitForExecutionOnCondition(isolatedIAMOwnerCTX, t, instance, conditionEvent(event), []string{targetResponse.GetId()})
tests := []struct {
@@ -416,7 +422,7 @@ func TestServer_ExecutionTarget_Event_LongerThanTransactionTimeout(t *testing.T)
urlRequest, closeF, calledF, resetF := integration.TestServerCall(nil, 1*time.Second, http.StatusOK, nil)
defer closeF()
targetResponse := waitForTarget(isolatedIAMOwnerCTX, t, instance, urlRequest, target_domain.TargetTypeWebhook, true)
targetResponse := waitForTarget(isolatedIAMOwnerCTX, t, instance, urlRequest, target_domain.TargetTypeWebhook, true, action.PayloadType_PAYLOAD_TYPE_JSON)
waitForExecutionOnCondition(isolatedIAMOwnerCTX, t, instance, conditionEvent(event), []string{targetResponse.GetId()})
tests := []struct {
@@ -499,8 +505,8 @@ func waitForExecutionOnCondition(ctx context.Context, t *testing.T, instance *in
}, retryDuration, tick, "timeout waiting for expected execution result")
}
func waitForTarget(ctx context.Context, t *testing.T, instance *integration.Instance, endpoint string, ty target_domain.TargetType, interrupt bool) *action.CreateTargetResponse {
resp := instance.CreateTarget(ctx, t, "", endpoint, ty, interrupt)
func waitForTarget(ctx context.Context, t *testing.T, instance *integration.Instance, endpoint string, ty target_domain.TargetType, interrupt bool, payloadType action.PayloadType) *action.CreateTargetResponse {
resp := instance.CreateTarget(ctx, t, "", endpoint, ty, interrupt, payloadType)
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(ctx, time.Minute)
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
@@ -779,7 +785,7 @@ func expectPreUserinfoExecution(ctx context.Context, t *testing.T, instance *int
targetURL, closeF, _, _ := integration.TestServerCall(expectedContextInfo, 0, http.StatusOK, response)
targetResp := waitForTarget(ctx, t, instance, targetURL, target_domain.TargetTypeCall, true)
targetResp := waitForTarget(ctx, t, instance, targetURL, target_domain.TargetTypeCall, true, action.PayloadType_PAYLOAD_TYPE_JSON)
waitForExecutionOnCondition(ctx, t, instance, conditionFunction("preuserinfo"), []string{targetResp.GetId()})
return userResp.GetUserId(), closeF
}
@@ -1087,7 +1093,7 @@ func expectPreAccessTokenExecution(ctx context.Context, t *testing.T, instance *
targetURL, closeF, _, _ := integration.TestServerCall(expectedContextInfo, 0, http.StatusOK, response)
targetResp := waitForTarget(ctx, t, instance, targetURL, target_domain.TargetTypeCall, true)
targetResp := waitForTarget(ctx, t, instance, targetURL, target_domain.TargetTypeCall, true, action.PayloadType_PAYLOAD_TYPE_JSON)
waitForExecutionOnCondition(ctx, t, instance, conditionFunction("preaccesstoken"), []string{targetResp.GetId()})
return userResp.GetUserId(), closeF
}
@@ -1252,7 +1258,7 @@ func expectPreSAMLResponseExecution(ctx context.Context, t *testing.T, instance
targetURL, closeF, _, _ := integration.TestServerCall(expectedContextInfo, 0, http.StatusOK, response)
targetResp := waitForTarget(ctx, t, instance, targetURL, target_domain.TargetTypeCall, true)
targetResp := waitForTarget(ctx, t, instance, targetURL, target_domain.TargetTypeCall, true, action.PayloadType_PAYLOAD_TYPE_JSON)
waitForExecutionOnCondition(ctx, t, instance, conditionFunction("presamlresponse"), []string{targetResp.GetId()})
return userResp.GetUserId(), closeF
@@ -18,7 +18,7 @@ import (
func TestServer_SetExecution_Request(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
tests := []struct {
name string
@@ -175,7 +175,7 @@ func assertSetExecutionResponse(t *testing.T, creationDate, setDate time.Time, e
func TestServer_SetExecution_Response(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
tests := []struct {
name string
@@ -319,7 +319,7 @@ func TestServer_SetExecution_Response(t *testing.T) {
func TestServer_SetExecution_Event(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
tests := []struct {
name string
@@ -482,7 +482,7 @@ func TestServer_SetExecution_Event(t *testing.T) {
func TestServer_SetExecution_Function(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
tests := []struct {
name string
@@ -11,6 +11,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
"github.com/zitadel/zitadel/internal/integration"
@@ -54,7 +55,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -71,7 +72,8 @@ func TestServer_GetTarget(t *testing.T) {
TargetType: &action.Target_RestWebhook{
RestWebhook: &action.RESTWebhook{},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -81,7 +83,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeAsync, false)
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeAsync, false, action.PayloadType_PAYLOAD_TYPE_JSON)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -98,7 +100,8 @@ func TestServer_GetTarget(t *testing.T) {
TargetType: &action.Target_RestAsync{
RestAsync: &action.RESTAsync{},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -108,7 +111,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, true)
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, true, action.PayloadType_PAYLOAD_TYPE_JSON)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -127,7 +130,8 @@ func TestServer_GetTarget(t *testing.T) {
InterruptOnError: true,
},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -137,7 +141,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, false)
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, false, action.PayloadType_PAYLOAD_TYPE_JSON)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -156,7 +160,8 @@ func TestServer_GetTarget(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -166,7 +171,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, true)
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, true, action.PayloadType_PAYLOAD_TYPE_JSON)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -185,7 +190,8 @@ func TestServer_GetTarget(t *testing.T) {
InterruptOnError: true,
},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -261,7 +267,7 @@ func TestServer_ListTargets(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.ListTargetsRequest, response *action.ListTargetsResponse) {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
request.Filters[0].Filter = &action.TargetSearchFilter_InTargetIdsFilter{
InTargetIdsFilter: &action.InTargetIDsFilter{
TargetIds: []string{resp.GetId()},
@@ -291,7 +297,8 @@ func TestServer_ListTargets(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -301,7 +308,7 @@ func TestServer_ListTargets(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.ListTargetsRequest, response *action.ListTargetsResponse) {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
request.Filters[0].Filter = &action.TargetSearchFilter_TargetNameFilter{
TargetNameFilter: &action.TargetNameFilter{
TargetName: name,
@@ -331,7 +338,8 @@ func TestServer_ListTargets(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -344,9 +352,9 @@ func TestServer_ListTargets(t *testing.T) {
name1 := integration.TargetName()
name2 := integration.TargetName()
name3 := integration.TargetName()
resp1 := instance.CreateTarget(ctx, t, name1, "https://example.com", target_domain.TargetTypeWebhook, false)
resp2 := instance.CreateTarget(ctx, t, name2, "https://example.com", target_domain.TargetTypeCall, true)
resp3 := instance.CreateTarget(ctx, t, name3, "https://example.com", target_domain.TargetTypeAsync, false)
resp1 := instance.CreateTarget(ctx, t, name1, "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
resp2 := instance.CreateTarget(ctx, t, name2, "https://example.com", target_domain.TargetTypeCall, true, action.PayloadType_PAYLOAD_TYPE_JWT)
resp3 := instance.CreateTarget(ctx, t, name3, "https://example.com", target_domain.TargetTypeAsync, false, action.PayloadType_PAYLOAD_TYPE_JWE)
request.Filters[0].Filter = &action.TargetSearchFilter_InTargetIdsFilter{
InTargetIdsFilter: &action.InTargetIDsFilter{
TargetIds: []string{resp1.GetId(), resp2.GetId(), resp3.GetId()},
@@ -386,7 +394,8 @@ func TestServer_ListTargets(t *testing.T) {
TargetType: &action.Target_RestAsync{
RestAsync: &action.RESTAsync{},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JWE,
},
{
Endpoint: "https://example.com",
@@ -395,7 +404,8 @@ func TestServer_ListTargets(t *testing.T) {
InterruptOnError: true,
},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JWT,
},
{
Endpoint: "https://example.com",
@@ -404,7 +414,8 @@ func TestServer_ListTargets(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(5 * time.Second),
Timeout: durationpb.New(5 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
},
},
@@ -445,7 +456,7 @@ func assertPaginationResponse(t *assert.CollectT, expected *filter.PaginationRes
func TestServer_ListExecutions(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
type args struct {
ctx context.Context
@@ -523,7 +534,7 @@ func TestServer_ListExecutions(t *testing.T) {
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.ListExecutionsRequest, response *action.ListExecutionsResponse) {
target := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false)
target := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON)
// add target as Filter to the request
request.Filters[0] = &action.ExecutionSearchFilter{
Filter: &action.ExecutionSearchFilter_TargetFilter{
@@ -781,3 +792,334 @@ func TestServer_ListExecutions(t *testing.T) {
})
}
}
func TestServer_ListPublicKeys(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
activeKey, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
})
require.NoError(t, err)
changeDate, err := instance.Client.ActionV2.ActivatePublicKey(isolatedIAMOwnerCTX, &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: activeKey.GetKeyId(),
})
require.NoError(t, err)
expirationDate := timestamppb.New(time.Now().Add(24 * time.Hour))
inactiveKey, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: rsaPublicKeyBytes,
ExpirationDate: expirationDate,
})
require.NoError(t, err)
anotherKey, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: rsaPublicKeyBytes,
})
require.NoError(t, err)
type args struct {
ctx context.Context
req *action.ListPublicKeysRequest
}
tests := []struct {
name string
args args
want *action.ListPublicKeysResponse
wantErr bool
}{
{
name: "missing permission",
args: args{
ctx: instance.WithAuthorizationToken(context.Background(), integration.UserTypeOrgOwner),
req: &action.ListPublicKeysRequest{},
},
wantErr: true,
},
{
name: "invalid target id",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.ListPublicKeysRequest{
TargetId: "notfound",
},
},
want: &action.ListPublicKeysResponse{
Pagination: &filter.PaginationResponse{
AppliedLimit: 100,
},
},
},
{
name: "list all",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.ListPublicKeysRequest{
TargetId: targetID,
},
},
want: &action.ListPublicKeysResponse{
Pagination: &filter.PaginationResponse{
AppliedLimit: 100,
TotalResult: 3,
},
PublicKeys: []*action.PublicKey{
{
KeyId: anotherKey.GetKeyId(),
Active: false,
PublicKey: rsaPublicKeyBytes,
Fingerprint: rsaFingerprint,
ExpirationDate: nil,
CreationDate: anotherKey.GetCreationDate(),
ChangeDate: anotherKey.GetCreationDate(),
},
{
KeyId: inactiveKey.GetKeyId(),
Active: false,
PublicKey: rsaPublicKeyBytes,
Fingerprint: rsaFingerprint,
ExpirationDate: expirationDate,
CreationDate: inactiveKey.GetCreationDate(),
ChangeDate: inactiveKey.GetCreationDate(),
},
{
KeyId: activeKey.GetKeyId(),
Active: true,
PublicKey: publicKeyBytes,
Fingerprint: fingerprint,
ExpirationDate: nil,
CreationDate: activeKey.GetCreationDate(),
ChangeDate: changeDate.GetChangeDate(),
},
},
},
},
{
name: "list only active",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.ListPublicKeysRequest{
TargetId: targetID,
Filters: []*action.PublicKeySearchFilter{
{
Filter: &action.PublicKeySearchFilter_ActiveFilter{
ActiveFilter: true,
},
},
},
},
},
want: &action.ListPublicKeysResponse{
Pagination: &filter.PaginationResponse{
AppliedLimit: 100,
TotalResult: 1,
},
PublicKeys: []*action.PublicKey{
{
KeyId: activeKey.GetKeyId(),
Active: true,
PublicKey: publicKeyBytes,
Fingerprint: fingerprint,
ExpirationDate: nil,
CreationDate: activeKey.GetCreationDate(),
ChangeDate: changeDate.GetChangeDate(),
},
},
},
},
{
name: "list only inactive",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.ListPublicKeysRequest{
TargetId: targetID,
Filters: []*action.PublicKeySearchFilter{
{
Filter: &action.PublicKeySearchFilter_ActiveFilter{
ActiveFilter: false,
},
},
},
},
},
want: &action.ListPublicKeysResponse{
Pagination: &filter.PaginationResponse{
AppliedLimit: 100,
TotalResult: 2,
},
PublicKeys: []*action.PublicKey{
{
KeyId: anotherKey.GetKeyId(),
Active: false,
PublicKey: rsaPublicKeyBytes,
Fingerprint: rsaFingerprint,
ExpirationDate: nil,
CreationDate: anotherKey.GetCreationDate(),
ChangeDate: anotherKey.GetCreationDate(),
},
{
KeyId: inactiveKey.GetKeyId(),
Active: false,
PublicKey: rsaPublicKeyBytes,
Fingerprint: rsaFingerprint,
ExpirationDate: expirationDate,
CreationDate: inactiveKey.GetCreationDate(),
ChangeDate: inactiveKey.GetCreationDate(),
},
},
},
},
{
name: "list with expiration date filter (boefore or equals)",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.ListPublicKeysRequest{
TargetId: targetID,
Filters: []*action.PublicKeySearchFilter{
{
Filter: &action.PublicKeySearchFilter_ExpirationDateFilter{
ExpirationDateFilter: &filter.TimestampFilter{
Timestamp: expirationDate,
Method: filter.TimestampFilterMethod_TIMESTAMP_FILTER_METHOD_BEFORE_OR_EQUALS,
},
},
},
},
},
},
want: &action.ListPublicKeysResponse{
Pagination: &filter.PaginationResponse{
AppliedLimit: 100,
TotalResult: 1,
},
PublicKeys: []*action.PublicKey{
{
KeyId: inactiveKey.GetKeyId(),
Active: false,
PublicKey: rsaPublicKeyBytes,
Fingerprint: rsaFingerprint,
ExpirationDate: expirationDate,
CreationDate: inactiveKey.GetCreationDate(),
ChangeDate: inactiveKey.GetCreationDate(),
},
},
},
},
{
name: "list with expiration date filter (after incl. no expiration)",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.ListPublicKeysRequest{
TargetId: targetID,
Filters: []*action.PublicKeySearchFilter{
{
Filter: &action.PublicKeySearchFilter_ExpirationDateFilter{
ExpirationDateFilter: &filter.TimestampFilter{
Timestamp: expirationDate,
Method: filter.TimestampFilterMethod_TIMESTAMP_FILTER_METHOD_AFTER,
},
},
},
},
},
},
want: &action.ListPublicKeysResponse{
Pagination: &filter.PaginationResponse{
AppliedLimit: 100,
TotalResult: 2,
},
PublicKeys: []*action.PublicKey{
{
KeyId: anotherKey.GetKeyId(),
Active: false,
PublicKey: rsaPublicKeyBytes,
Fingerprint: rsaFingerprint,
ExpirationDate: nil,
CreationDate: anotherKey.GetCreationDate(),
ChangeDate: anotherKey.GetCreationDate(),
},
{
KeyId: activeKey.GetKeyId(),
Active: true,
PublicKey: publicKeyBytes,
Fingerprint: fingerprint,
ExpirationDate: nil,
CreationDate: activeKey.GetCreationDate(),
ChangeDate: changeDate.GetChangeDate(),
},
},
},
},
{
name: "list by key id",
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.ListPublicKeysRequest{
TargetId: targetID,
Filters: []*action.PublicKeySearchFilter{
{
Filter: &action.PublicKeySearchFilter_KeyIdsFilter{
KeyIdsFilter: &filter.InIDsFilter{
Ids: []string{activeKey.GetKeyId(), anotherKey.GetKeyId()},
},
},
},
},
SortingColumn: action.PublicKeyFieldName_PUBLIC_KEY_FIELD_NAME_CHANGE_DATE,
Pagination: &filter.PaginationRequest{
Limit: 1,
Offset: 1,
Asc: true,
},
},
},
want: &action.ListPublicKeysResponse{
Pagination: &filter.PaginationResponse{
TotalResult: 2,
AppliedLimit: 1,
},
PublicKeys: []*action.PublicKey{
{
KeyId: anotherKey.GetKeyId(),
Active: false,
PublicKey: rsaPublicKeyBytes,
Fingerprint: rsaFingerprint,
ExpirationDate: nil,
CreationDate: anotherKey.GetCreationDate(),
ChangeDate: anotherKey.GetCreationDate(),
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
retryDuration, tick := integration.WaitForAndTickWithMaxDuration(isolatedIAMOwnerCTX, 10*time.Second)
require.EventuallyWithT(t, func(ttt *assert.CollectT) {
got, err := instance.Client.ActionV2.ListPublicKeys(tt.args.ctx, tt.args.req)
if tt.wantErr {
assert.Error(ttt, err, "Error: "+err.Error())
return
}
assert.NoError(ttt, err)
assertPublicKeys(ttt, tt.want, got)
}, retryDuration, tick, "timeout waiting for expected public keys")
})
}
}
func assertPublicKeys(ttt *assert.CollectT, want *action.ListPublicKeysResponse, got *action.ListPublicKeysResponse) {
assert.EqualExportedValues(ttt, want.Pagination, got.Pagination)
assert.Len(ttt, got.PublicKeys, len(want.PublicKeys))
for i := range want.PublicKeys {
assert.Equal(ttt, want.PublicKeys[i].GetKeyId(), got.PublicKeys[i].GetKeyId())
assert.Equal(ttt, want.PublicKeys[i].GetActive(), got.PublicKeys[i].GetActive())
assert.Equal(ttt, want.PublicKeys[i].GetFingerprint(), got.PublicKeys[i].GetFingerprint())
assert.Equal(ttt, want.PublicKeys[i].GetPublicKey(), got.PublicKeys[i].GetPublicKey())
assertDateWithinRangeClockSkew(ttt, got.PublicKeys[i].GetExpirationDate().AsTime(), want.PublicKeys[i].GetExpirationDate().AsTime(), want.PublicKeys[i].GetExpirationDate().AsTime())
assertDateWithinRangeClockSkew(ttt, got.PublicKeys[i].GetCreationDate().AsTime(), want.PublicKeys[i].GetCreationDate().AsTime(), want.PublicKeys[i].GetCreationDate().AsTime())
assertDateWithinRangeClockSkew(ttt, got.PublicKeys[i].GetChangeDate().AsTime(), want.PublicKeys[i].GetChangeDate().AsTime(), want.PublicKeys[i].GetChangeDate().AsTime())
}
}
@@ -4,13 +4,25 @@ package action_test
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"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/crypto"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/pkg/grpc/action/v2"
@@ -25,7 +37,7 @@ func TestServer_CreateTarget(t *testing.T) {
signingKey bool
}
alreadyExistingTargetName := integration.TargetName()
instance.CreateTarget(isolatedIAMOwnerCTX, t, alreadyExistingTargetName, "https://example.com", target_domain.TargetTypeAsync, false)
instance.CreateTarget(isolatedIAMOwnerCTX, t, alreadyExistingTargetName, "https://example.com", target_domain.TargetTypeAsync, false, action.PayloadType_PAYLOAD_TYPE_JSON)
tests := []struct {
name string
ctx context.Context
@@ -115,7 +127,8 @@ func TestServer_CreateTarget(t *testing.T) {
TargetType: &action.CreateTargetRequest_RestAsync{
RestAsync: &action.RESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
want: want{
id: true,
@@ -134,7 +147,8 @@ func TestServer_CreateTarget(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
want: want{
id: true,
@@ -153,7 +167,8 @@ func TestServer_CreateTarget(t *testing.T) {
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
want: want{
id: true,
@@ -172,7 +187,8 @@ func TestServer_CreateTarget(t *testing.T) {
InterruptOnError: false,
},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
want: want{
id: true,
@@ -192,7 +208,8 @@ func TestServer_CreateTarget(t *testing.T) {
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
},
want: want{
id: true,
@@ -262,7 +279,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "missing permission",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -289,7 +306,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "no change, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -307,7 +324,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change name, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -325,7 +342,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "regenerate signingkey, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -343,7 +360,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change type, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -365,7 +382,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change url, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -383,7 +400,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change timeout, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -398,10 +415,28 @@ func TestServer_UpdateTarget(t *testing.T) {
signingKey: false,
},
},
{
name: "change timeout, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
ctx: isolatedIAMOwnerCTX,
req: &action.UpdateTargetRequest{
PayloadType: action.PayloadType_PAYLOAD_TYPE_JWT,
},
},
want: want{
change: true,
changeDate: true,
signingKey: false,
},
},
{
name: "change type async, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeAsync, false).GetId()
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeAsync, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
},
args: args{
@@ -497,7 +532,7 @@ func TestServer_DeleteTarget(t *testing.T) {
ctx: iamOwnerCtx,
prepare: func(request *action.DeleteTargetRequest) (time.Time, time.Time) {
creationDate := time.Now().UTC()
targetID := instance.CreateTarget(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
return creationDate, time.Time{}
},
@@ -509,7 +544,7 @@ func TestServer_DeleteTarget(t *testing.T) {
ctx: iamOwnerCtx,
prepare: func(request *action.DeleteTargetRequest) (time.Time, time.Time) {
creationDate := time.Now().UTC()
targetID := instance.CreateTarget(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTarget(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
request.Id = targetID
instance.DeleteTarget(iamOwnerCtx, t, targetID)
return creationDate, time.Now().UTC()
@@ -546,3 +581,496 @@ func assertDeleteTargetResponse(t *testing.T, creationDate, deletionDate time.Ti
assert.Nil(t, actualResp.DeletionDate)
}
}
var (
publicKey = func() *ecdsa.PublicKey {
privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
return &privateKey.PublicKey
}()
publicKeyBytes = func() []byte {
pubBytes, _ := x509.MarshalPKIXPublicKey(publicKey)
return pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: pubBytes})
}()
fingerprint = func() string {
block, _ := x509.MarshalPKIXPublicKey(publicKey)
hash := sha256.Sum256(block)
return fmt.Sprintf("SHA256:%s", base64.RawStdEncoding.EncodeToString(hash[:]))
}()
rsaPublicKey = func() *rsa.PublicKey {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
return &privateKey.PublicKey
}()
rsaPublicKeyBytes = func() []byte {
data, _ := crypto.PublicKeyToBytes(rsaPublicKey)
return data
}()
rsaFingerprint = func() string {
block, _ := x509.MarshalPKIXPublicKey(rsaPublicKey)
hash := sha256.Sum256(block)
return fmt.Sprintf("SHA256:%s", base64.RawStdEncoding.EncodeToString(hash[:]))
}()
)
func TestServer_AddPublicKey(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
type want struct {
id bool
creationDate bool
}
tests := []struct {
name string
ctx context.Context
req *action.AddPublicKeyRequest
want want
wantErr bool
}{
{
name: "missing permission",
ctx: instance.WithAuthorizationToken(context.Background(), integration.UserTypeOrgOwner),
req: &action.AddPublicKeyRequest{
TargetId: "targetID",
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
},
wantErr: true,
},
{
name: "empty target id",
ctx: isolatedIAMOwnerCTX,
req: &action.AddPublicKeyRequest{
TargetId: "",
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
},
wantErr: true,
},
{
name: "empty public key",
ctx: isolatedIAMOwnerCTX,
req: &action.AddPublicKeyRequest{
TargetId: "targetID",
PublicKey: nil,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
},
wantErr: true,
},
{
name: "invalid public key",
ctx: isolatedIAMOwnerCTX,
req: &action.AddPublicKeyRequest{
TargetId: "targetID",
PublicKey: []byte("invalid"),
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
},
wantErr: true,
},
{
name: "expiration date in the past",
ctx: isolatedIAMOwnerCTX,
req: &action.AddPublicKeyRequest{
TargetId: "targetID",
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(-1 * time.Hour)),
},
wantErr: true,
},
{
name: "target not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.AddPublicKeyRequest{
TargetId: "notexisting",
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
},
wantErr: true,
},
{
name: "add public key, ok",
ctx: isolatedIAMOwnerCTX,
req: func() *action.AddPublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
return &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
}
}(),
want: want{
id: true,
creationDate: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
start := time.Now()
got, err := instance.Client.ActionV2.AddPublicKey(tt.ctx, tt.req)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.NotEmpty(t, got.GetKeyId())
assertDateWithinRangeClockSkew(t, got.GetCreationDate().AsTime(), start, time.Now())
})
}
}
func TestServer_ActivatePublicKey(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
tests := []struct {
name string
ctx context.Context
req *action.ActivatePublicKeyRequest
wantErr bool
}{
{
name: "missing permission",
ctx: instance.WithAuthorizationToken(context.Background(), integration.UserTypeOrgOwner),
req: &action.ActivatePublicKeyRequest{
TargetId: "targetID",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "empty target id",
ctx: isolatedIAMOwnerCTX,
req: &action.ActivatePublicKeyRequest{
TargetId: "",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "empty key id",
ctx: isolatedIAMOwnerCTX,
req: &action.ActivatePublicKeyRequest{
TargetId: "targetID",
KeyId: "",
},
wantErr: true,
},
{
name: "target not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.ActivatePublicKeyRequest{
TargetId: "notexisting",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "key not existing",
ctx: isolatedIAMOwnerCTX,
req: func() *action.ActivatePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
return &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: "notexisting",
}
}(),
wantErr: true,
},
{
name: "already expired key",
ctx: isolatedIAMOwnerCTX,
req: func() *action.ActivatePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
resp, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().Add(1 * time.Second)),
})
require.NoError(t, err)
time.Sleep(2 * time.Second)
return &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
}
}(),
wantErr: true,
},
{
name: "already activated key",
ctx: isolatedIAMOwnerCTX,
req: func() *action.ActivatePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
resp, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
})
require.NoError(t, err)
_, err = instance.Client.ActionV2.ActivatePublicKey(isolatedIAMOwnerCTX, &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
})
require.NoError(t, err)
return &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
}
}(),
wantErr: false,
},
{
name: "activate key, ok",
ctx: isolatedIAMOwnerCTX,
req: func() *action.ActivatePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
resp, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
})
require.NoError(t, err)
return &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
}
}(),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
start := time.Now()
got, err := instance.Client.ActionV2.ActivatePublicKey(tt.ctx, tt.req)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assertDateWithinRangeClockSkew(t, got.GetChangeDate().AsTime(), start, time.Now())
})
}
}
func TestServer_DeactivatePublicKey(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
tests := []struct {
name string
ctx context.Context
req *action.DeactivatePublicKeyRequest
wantErr bool
}{
{
name: "missing permission",
ctx: instance.WithAuthorizationToken(context.Background(), integration.UserTypeOrgOwner),
req: &action.DeactivatePublicKeyRequest{
TargetId: "targetID",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "empty target id",
ctx: isolatedIAMOwnerCTX,
req: &action.DeactivatePublicKeyRequest{
TargetId: "",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "empty key id",
ctx: isolatedIAMOwnerCTX,
req: &action.DeactivatePublicKeyRequest{
TargetId: "targetID",
KeyId: "",
},
wantErr: true,
},
{
name: "target not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.DeactivatePublicKeyRequest{
TargetId: "notexisting",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "key not existing",
ctx: isolatedIAMOwnerCTX,
req: func() *action.DeactivatePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
return &action.DeactivatePublicKeyRequest{
TargetId: targetID,
KeyId: "notexisting",
}
}(),
wantErr: true,
},
{
name: "already deactivated key",
ctx: isolatedIAMOwnerCTX,
req: func() *action.DeactivatePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
resp, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
})
require.NoError(t, err)
return &action.DeactivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
}
}(),
wantErr: false,
},
{
name: "deactivate key, ok",
ctx: isolatedIAMOwnerCTX,
req: func() *action.DeactivatePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
resp, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
ExpirationDate: timestamppb.New(time.Now().UTC().Add(time.Hour)),
})
require.NoError(t, err)
_, err = instance.Client.ActionV2.ActivatePublicKey(isolatedIAMOwnerCTX, &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
})
require.NoError(t, err)
return &action.DeactivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
}
}(),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
start := time.Now()
got, err := instance.Client.ActionV2.DeactivatePublicKey(tt.ctx, tt.req)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assertDateWithinRangeClockSkew(t, got.GetChangeDate().AsTime(), start, time.Now())
})
}
}
func TestServer_RemovePublicKey(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
tests := []struct {
name string
ctx context.Context
req *action.RemovePublicKeyRequest
wantErr bool
}{
{
name: "missing permission",
ctx: instance.WithAuthorizationToken(context.Background(), integration.UserTypeOrgOwner),
req: &action.RemovePublicKeyRequest{
TargetId: "targetID",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "empty target id",
ctx: isolatedIAMOwnerCTX,
req: &action.RemovePublicKeyRequest{
TargetId: "",
KeyId: "keyID",
},
wantErr: true,
},
{
name: "empty key id",
ctx: isolatedIAMOwnerCTX,
req: &action.RemovePublicKeyRequest{
TargetId: "targetID",
KeyId: "",
},
wantErr: true,
},
{
name: "target not existing",
ctx: isolatedIAMOwnerCTX,
req: &action.RemovePublicKeyRequest{
TargetId: "notexisting",
KeyId: "keyID",
},
wantErr: false,
},
{
name: "key not existing",
ctx: isolatedIAMOwnerCTX,
req: func() *action.RemovePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
return &action.RemovePublicKeyRequest{
TargetId: targetID,
KeyId: "notexisting",
}
}(),
wantErr: false,
},
{
name: "remove activated key",
ctx: isolatedIAMOwnerCTX,
req: func() *action.RemovePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
resp, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
})
require.NoError(t, err)
_, err = instance.Client.ActionV2.ActivatePublicKey(isolatedIAMOwnerCTX, &action.ActivatePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
})
require.NoError(t, err)
return &action.RemovePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
}
}(),
wantErr: true,
},
{
name: "remove key, ok",
ctx: isolatedIAMOwnerCTX,
req: func() *action.RemovePublicKeyRequest {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false, action.PayloadType_PAYLOAD_TYPE_JSON).GetId()
resp, err := instance.Client.ActionV2.AddPublicKey(isolatedIAMOwnerCTX, &action.AddPublicKeyRequest{
TargetId: targetID,
PublicKey: publicKeyBytes,
})
require.NoError(t, err)
return &action.RemovePublicKeyRequest{
TargetId: targetID,
KeyId: resp.GetKeyId(),
}
}(),
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := instance.Client.ActionV2.RemovePublicKey(tt.ctx, tt.req)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
})
}
}
func assertDateWithinRangeClockSkew(t assert.TestingT, actual time.Time, start, end time.Time) {
assert.WithinRange(t, actual, start.Add(-time.Second), end.Add(time.Second))
}
+132 -5
View File
@@ -15,6 +15,7 @@ import (
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/zerrors"
"github.com/zitadel/zitadel/pkg/grpc/action/v2"
filter_pb "github.com/zitadel/zitadel/pkg/grpc/filter/v2"
)
const (
@@ -58,6 +59,21 @@ func (s *Server) ListTargets(ctx context.Context, req *connect.Request[action.Li
}), nil
}
func (s *Server) ListPublicKeys(ctx context.Context, req *connect.Request[action.ListPublicKeysRequest]) (*connect.Response[action.ListPublicKeysResponse], error) {
queries, err := s.listPublicKeysRequestToQuery(req.Msg)
if err != nil {
return nil, err
}
res, err := s.query.SearchAuthNKeys(ctx, queries, query.JoinFilterTarget, nil)
if err != nil {
return nil, err
}
return connect.NewResponse(&action.ListPublicKeysResponse{
Pagination: filter.QueryToPaginationPb(queries.SearchRequest, res.SearchResponse),
PublicKeys: publicKeysToPb(res.AuthNKeys),
}), nil
}
func (s *Server) ListExecutions(ctx context.Context, req *connect.Request[action.ListExecutionsRequest]) (*connect.Response[action.ListExecutionsResponse], error) {
queries, err := s.ListExecutionsRequestToModel(req.Msg)
if err != nil {
@@ -83,11 +99,12 @@ func targetsToPb(targets []*query.Target) []*action.Target {
func targetToPb(t *query.Target) *action.Target {
target := &action.Target{
Id: t.ID,
Name: t.Name,
Timeout: durationpb.New(t.Timeout),
Endpoint: t.Endpoint,
SigningKey: t.SigningKey,
Id: t.ID,
Name: t.Name,
Timeout: durationpb.New(t.Timeout),
Endpoint: t.Endpoint,
SigningKey: t.SigningKey,
PayloadType: payloadTypeToPb(t.PayloadType),
}
switch t.TargetType {
case target_domain.TargetTypeWebhook:
@@ -109,6 +126,21 @@ func targetToPb(t *query.Target) *action.Target {
return target
}
func payloadTypeToPb(payloadType target_domain.PayloadType) action.PayloadType {
switch payloadType {
case target_domain.PayloadTypeUnspecified:
return action.PayloadType_PAYLOAD_TYPE_UNSPECIFIED
case target_domain.PayloadTypeJSON:
return action.PayloadType_PAYLOAD_TYPE_JSON
case target_domain.PayloadTypeJWT:
return action.PayloadType_PAYLOAD_TYPE_JWT
case target_domain.PayloadTypeJWE:
return action.PayloadType_PAYLOAD_TYPE_JWE
default:
return action.PayloadType_PAYLOAD_TYPE_UNSPECIFIED
}
}
func (s *Server) ListTargetsRequestToModel(req *action.ListTargetsRequest) (*query.TargetSearchQueries, error) {
offset, limit, asc, err := filter.PaginationPbToQuery(s.systemDefaults, req.Pagination)
if err != nil {
@@ -403,3 +435,98 @@ func includeEventToCondition(id string) *action.Condition {
func includeFunctionToCondition(id string) *action.Condition {
return &action.Condition{ConditionType: &action.Condition_Function{Function: &action.FunctionExecution{Name: strings.TrimPrefix(id, "/")}}}
}
func (s *Server) listPublicKeysRequestToQuery(req *action.ListPublicKeysRequest) (*query.AuthNKeySearchQueries, error) {
offset, limit, asc, err := filter.PaginationPbToQuery(s.systemDefaults, req.Pagination)
if err != nil {
return nil, err
}
queries, err := publicKeyFiltersToQuery(req.Filters, req.GetTargetId())
if err != nil {
return nil, err
}
return &query.AuthNKeySearchQueries{
SearchRequest: query.SearchRequest{
Offset: offset,
Limit: limit,
Asc: asc,
SortingColumn: publicKeyFieldNameToSortingColumn(req.GetSortingColumn()),
},
Queries: queries,
}, nil
}
func publicKeyFiltersToQuery(filters []*action.PublicKeySearchFilter, targetID string) (_ []query.SearchQuery, err error) {
f := make([]query.SearchQuery, len(filters)+1)
for i, filter := range filters {
f[i], err = publicKeyFilterToQuery(filter)
if err != nil {
return nil, err
}
}
f[len(filters)], err = query.NewAuthNKeyIdentifyerQuery(targetID)
if err != nil {
return nil, err
}
return f, nil
}
func publicKeyFilterToQuery(filter *action.PublicKeySearchFilter) (query.SearchQuery, error) {
switch q := filter.Filter.(type) {
case *action.PublicKeySearchFilter_KeyIdsFilter:
return publicKeyKeyIDsFilterToQuery(q.KeyIdsFilter)
case *action.PublicKeySearchFilter_ActiveFilter:
return publicKeyActiveFilterToQuery(q.ActiveFilter)
case *action.PublicKeySearchFilter_ExpirationDateFilter:
return publicKeyExpirationFilterToQuery(q.ExpirationDateFilter)
default:
return nil, zerrors.ThrowInvalidArgument(nil, "GRPC-vR9nC", "List.Query.Invalid")
}
}
func publicKeyKeyIDsFilterToQuery(idsFilter *filter_pb.InIDsFilter) (query.SearchQuery, error) {
return query.NewAuthNKeyInIDsSearchQuery(idsFilter.GetIds())
}
func publicKeyActiveFilterToQuery(activeFilter bool) (query.SearchQuery, error) {
return query.NewAuthNKeyEnabledSearchQuery(activeFilter)
}
func publicKeyExpirationFilterToQuery(f *filter_pb.TimestampFilter) (query.SearchQuery, error) {
return query.NewAuthNKeyExpirationDateQuery(f.GetTimestamp().AsTime(), filter.TimestampMethodPbToQuery(f.Method))
}
func publicKeyFieldNameToSortingColumn(column action.PublicKeyFieldName) query.Column {
switch column {
case action.PublicKeyFieldName_PUBLIC_KEY_FIELD_NAME_UNSPECIFIED:
return query.AuthNKeyColumnCreationDate
case action.PublicKeyFieldName_PUBLIC_KEY_FIELD_NAME_CREATION_DATE:
return query.AuthNKeyColumnCreationDate
case action.PublicKeyFieldName_PUBLIC_KEY_FIELD_NAME_CHANGE_DATE:
return query.AuthNKeyColumnChangeDate
case action.PublicKeyFieldName_PUBLIC_KEY_FIELD_NAME_EXPIRATION_DATE:
return query.AuthNKeyColumnExpiration
default:
return query.AuthNKeyColumnCreationDate
}
}
func publicKeysToPb(keys []*query.AuthNKey) []*action.PublicKey {
pks := make([]*action.PublicKey, len(keys))
for i, key := range keys {
var expiration *timestamppb.Timestamp
if !key.Expiration.IsZero() {
expiration = timestamppb.New(key.Expiration)
}
pks[i] = &action.PublicKey{
KeyId: key.ID,
Active: key.Enabled,
PublicKey: key.PublicKey,
Fingerprint: key.Fingerprint,
ExpirationDate: expiration,
CreationDate: timestamppb.New(key.CreationDate),
ChangeDate: timestamppb.New(key.ChangeDate),
}
}
return pks
}
+73
View File
@@ -2,6 +2,8 @@ package action
import (
"context"
"strings"
"time"
"connectrpc.com/connect"
"github.com/muhlemmer/gu"
@@ -64,6 +66,60 @@ func (s *Server) DeleteTarget(ctx context.Context, req *connect.Request[action.D
}), nil
}
func (s *Server) AddPublicKey(ctx context.Context, req *connect.Request[action.AddPublicKeyRequest]) (*connect.Response[action.AddPublicKeyResponse], error) {
instanceID := authz.GetInstance(ctx).InstanceID()
var expirationDate time.Time
if req.Msg.GetExpirationDate() != nil {
expirationDate = req.Msg.GetExpirationDate().AsTime()
}
key := &command.TargetPublicKey{
TargetID: strings.TrimSpace(req.Msg.GetTargetId()),
PublicKey: req.Msg.GetPublicKey(),
Expiration: expirationDate,
}
creationDate, err := s.command.AddTargetPublicKey(ctx, key, instanceID)
if err != nil {
return nil, err
}
return connect.NewResponse(&action.AddPublicKeyResponse{
KeyId: key.KeyID,
CreationDate: timestamppb.New(creationDate),
}), nil
}
func (s *Server) ActivatePublicKey(ctx context.Context, req *connect.Request[action.ActivatePublicKeyRequest]) (*connect.Response[action.ActivatePublicKeyResponse], error) {
instanceID := authz.GetInstance(ctx).InstanceID()
changeDate, err := s.command.ActivateTargetPublicKey(ctx, strings.TrimSpace(req.Msg.GetTargetId()), strings.TrimSpace(req.Msg.GetKeyId()), instanceID)
if err != nil {
return nil, err
}
return connect.NewResponse(&action.ActivatePublicKeyResponse{
ChangeDate: timestamppb.New(changeDate),
}), nil
}
func (s *Server) DeactivatePublicKey(ctx context.Context, req *connect.Request[action.DeactivatePublicKeyRequest]) (*connect.Response[action.DeactivatePublicKeyResponse], error) {
instanceID := authz.GetInstance(ctx).InstanceID()
changeDate, err := s.command.DeactivateTargetPublicKey(ctx, strings.TrimSpace(req.Msg.GetTargetId()), strings.TrimSpace(req.Msg.GetKeyId()), instanceID)
if err != nil {
return nil, err
}
return connect.NewResponse(&action.DeactivatePublicKeyResponse{
ChangeDate: timestamppb.New(changeDate),
}), nil
}
func (s *Server) RemovePublicKey(ctx context.Context, req *connect.Request[action.RemovePublicKeyRequest]) (*connect.Response[action.RemovePublicKeyResponse], error) {
instanceID := authz.GetInstance(ctx).InstanceID()
deletionDate, err := s.command.RemoveTargetPublicKey(ctx, strings.TrimSpace(req.Msg.GetTargetId()), strings.TrimSpace(req.Msg.GetKeyId()), instanceID)
if err != nil {
return nil, err
}
return connect.NewResponse(&action.RemovePublicKeyResponse{
DeletionDate: timestamppb.New(deletionDate),
}), nil
}
func createTargetToCommand(req *action.CreateTargetRequest) *command.AddTarget {
var (
targetType target_domain.TargetType
@@ -85,6 +141,22 @@ func createTargetToCommand(req *action.CreateTargetRequest) *command.AddTarget {
Endpoint: req.GetEndpoint(),
Timeout: req.GetTimeout().AsDuration(),
InterruptOnError: interruptOnError,
PayloadType: payloadTypeToDomain(req.GetPayloadType()),
}
}
func payloadTypeToDomain(payloadType action.PayloadType) target_domain.PayloadType {
switch payloadType {
case action.PayloadType_PAYLOAD_TYPE_UNSPECIFIED:
return target_domain.PayloadTypeUnspecified
case action.PayloadType_PAYLOAD_TYPE_JSON:
return target_domain.PayloadTypeJSON
case action.PayloadType_PAYLOAD_TYPE_JWT:
return target_domain.PayloadTypeJWT
case action.PayloadType_PAYLOAD_TYPE_JWE:
return target_domain.PayloadTypeJWE
default:
return target_domain.PayloadTypeUnspecified
}
}
@@ -102,6 +174,7 @@ func updateTargetToCommand(req *action.UpdateTargetRequest) *command.ChangeTarge
Name: req.Name,
Endpoint: req.Endpoint,
ExpirationSigningKey: expirationSigningKey,
PayloadType: payloadTypeToDomain(req.GetPayloadType()),
}
if req.TargetType != nil {
switch t := req.GetTargetType().(type) {
+10 -3
View File
@@ -30,6 +30,7 @@ func Test_createTargetToCommand(t *testing.T) {
Endpoint: "",
Timeout: 0,
InterruptOnError: false,
PayloadType: target_domain.PayloadTypeUnspecified,
},
},
{
@@ -40,7 +41,8 @@ func Test_createTargetToCommand(t *testing.T) {
TargetType: &action.CreateTargetRequest_RestWebhook{
RestWebhook: &action.RESTWebhook{},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JSON,
}},
want: &command.AddTarget{
Name: "target 1",
@@ -48,6 +50,7 @@ func Test_createTargetToCommand(t *testing.T) {
Endpoint: "https://example.com/hooks/1",
Timeout: 10 * time.Second,
InterruptOnError: false,
PayloadType: target_domain.PayloadTypeJSON,
},
},
{
@@ -58,7 +61,8 @@ func Test_createTargetToCommand(t *testing.T) {
TargetType: &action.CreateTargetRequest_RestAsync{
RestAsync: &action.RESTAsync{},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JWT,
}},
want: &command.AddTarget{
Name: "target 1",
@@ -66,6 +70,7 @@ func Test_createTargetToCommand(t *testing.T) {
Endpoint: "https://example.com/hooks/1",
Timeout: 10 * time.Second,
InterruptOnError: false,
PayloadType: target_domain.PayloadTypeJWT,
},
},
{
@@ -78,7 +83,8 @@ func Test_createTargetToCommand(t *testing.T) {
InterruptOnError: true,
},
},
Timeout: durationpb.New(10 * time.Second),
Timeout: durationpb.New(10 * time.Second),
PayloadType: action.PayloadType_PAYLOAD_TYPE_JWE,
}},
want: &command.AddTarget{
Name: "target 1",
@@ -86,6 +92,7 @@ func Test_createTargetToCommand(t *testing.T) {
Endpoint: "https://example.com/hooks/1",
Timeout: 10 * time.Second,
InterruptOnError: true,
PayloadType: target_domain.PayloadTypeJWE,
},
},
}
@@ -73,7 +73,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
targetCreatedName := integration.TargetName()
targetCreatedURL := "https://nonexistent"
targetCreated := instance.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false)
targetCreated := instance.CreateTargetWithoutPayloadType(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false)
// request received by target
wantRequest := &middleware.ContextInfoRequest{
@@ -223,7 +223,7 @@ func TestServer_ExecutionTarget(t *testing.T) {
targetCreatedName := integration.TargetName()
targetCreatedURL := "https://nonexistent"
targetCreated := instance.CreateTarget(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false)
targetCreated := instance.CreateTargetWithoutPayloadType(ctx, t, targetCreatedName, targetCreatedURL, target_domain.TargetTypeCall, false)
// GetTarget with used target
request.Id = targetCreated.GetId()
@@ -18,7 +18,7 @@ import (
func TestServer_SetExecution_Request(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
tests := []struct {
name string
@@ -175,7 +175,7 @@ func assertSetExecutionResponse(t *testing.T, creationDate, setDate time.Time, e
func TestServer_SetExecution_Response(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
tests := []struct {
name string
@@ -319,7 +319,7 @@ func TestServer_SetExecution_Response(t *testing.T) {
func TestServer_SetExecution_Event(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
tests := []struct {
name string
@@ -482,7 +482,7 @@ func TestServer_SetExecution_Event(t *testing.T) {
func TestServer_SetExecution_Function(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://notexisting", target_domain.TargetTypeWebhook, false)
tests := []struct {
name string
@@ -54,7 +54,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
resp := instance.CreateTargetWithoutPayloadType(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -81,7 +81,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeAsync, false)
resp := instance.CreateTargetWithoutPayloadType(ctx, t, name, "https://example.com", target_domain.TargetTypeAsync, false)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -108,7 +108,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, true)
resp := instance.CreateTargetWithoutPayloadType(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, true)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -137,7 +137,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, false)
resp := instance.CreateTargetWithoutPayloadType(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, false)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -166,7 +166,7 @@ func TestServer_GetTarget(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.GetTargetRequest, response *action.GetTargetResponse) error {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, true)
resp := instance.CreateTargetWithoutPayloadType(ctx, t, name, "https://example.com", target_domain.TargetTypeCall, true)
request.Id = resp.GetId()
response.Target.Id = resp.GetId()
response.Target.Name = name
@@ -261,7 +261,7 @@ func TestServer_ListTargets(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.ListTargetsRequest, response *action.ListTargetsResponse) {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
resp := instance.CreateTargetWithoutPayloadType(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
request.Filters[0].Filter = &action.TargetSearchFilter_InTargetIdsFilter{
InTargetIdsFilter: &action.InTargetIDsFilter{
TargetIds: []string{resp.GetId()},
@@ -301,7 +301,7 @@ func TestServer_ListTargets(t *testing.T) {
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.ListTargetsRequest, response *action.ListTargetsResponse) {
name := integration.TargetName()
resp := instance.CreateTarget(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
resp := instance.CreateTargetWithoutPayloadType(ctx, t, name, "https://example.com", target_domain.TargetTypeWebhook, false)
request.Filters[0].Filter = &action.TargetSearchFilter_TargetNameFilter{
TargetNameFilter: &action.TargetNameFilter{
TargetName: name,
@@ -344,9 +344,9 @@ func TestServer_ListTargets(t *testing.T) {
name1 := integration.TargetName()
name2 := integration.TargetName()
name3 := integration.TargetName()
resp1 := instance.CreateTarget(ctx, t, name1, "https://example.com", target_domain.TargetTypeWebhook, false)
resp2 := instance.CreateTarget(ctx, t, name2, "https://example.com", target_domain.TargetTypeCall, true)
resp3 := instance.CreateTarget(ctx, t, name3, "https://example.com", target_domain.TargetTypeAsync, false)
resp1 := instance.CreateTargetWithoutPayloadType(ctx, t, name1, "https://example.com", target_domain.TargetTypeWebhook, false)
resp2 := instance.CreateTargetWithoutPayloadType(ctx, t, name2, "https://example.com", target_domain.TargetTypeCall, true)
resp3 := instance.CreateTargetWithoutPayloadType(ctx, t, name3, "https://example.com", target_domain.TargetTypeAsync, false)
request.Filters[0].Filter = &action.TargetSearchFilter_InTargetIdsFilter{
InTargetIdsFilter: &action.InTargetIDsFilter{
TargetIds: []string{resp1.GetId(), resp2.GetId(), resp3.GetId()},
@@ -445,7 +445,7 @@ func assertPaginationResponse(t *assert.CollectT, expected *filter.PaginationRes
func TestServer_ListExecutions(t *testing.T) {
instance := integration.NewInstance(CTX)
isolatedIAMOwnerCTX := instance.WithAuthorizationToken(CTX, integration.UserTypeIAMOwner)
targetResp := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false)
targetResp := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false)
type args struct {
ctx context.Context
@@ -523,7 +523,7 @@ func TestServer_ListExecutions(t *testing.T) {
args: args{
ctx: isolatedIAMOwnerCTX,
dep: func(ctx context.Context, request *action.ListExecutionsRequest, response *action.ListExecutionsResponse) {
target := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false)
target := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false)
// add target as Filter to the request
request.Filters[0] = &action.ExecutionSearchFilter{
Filter: &action.ExecutionSearchFilter_TargetFilter{
@@ -25,7 +25,7 @@ func TestServer_CreateTarget(t *testing.T) {
signingKey bool
}
alreadyExistingTargetName := integration.TargetName()
instance.CreateTarget(isolatedIAMOwnerCTX, t, alreadyExistingTargetName, "https://example.com", target_domain.TargetTypeAsync, false)
instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, alreadyExistingTargetName, "https://example.com", target_domain.TargetTypeAsync, false)
tests := []struct {
name string
ctx context.Context
@@ -262,7 +262,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "missing permission",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
},
args: args{
@@ -289,7 +289,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "no change, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
},
args: args{
@@ -307,7 +307,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change name, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
},
args: args{
@@ -325,7 +325,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "regenerate signingkey, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
},
args: args{
@@ -343,7 +343,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change type, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
},
args: args{
@@ -365,7 +365,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change url, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
},
args: args{
@@ -383,7 +383,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change timeout, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
},
args: args{
@@ -401,7 +401,7 @@ func TestServer_UpdateTarget(t *testing.T) {
{
name: "change type async, ok",
prepare: func(request *action.UpdateTargetRequest) {
targetID := instance.CreateTarget(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeAsync, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(isolatedIAMOwnerCTX, t, "", "https://example.com", target_domain.TargetTypeAsync, false).GetId()
request.Id = targetID
},
args: args{
@@ -497,7 +497,7 @@ func TestServer_DeleteTarget(t *testing.T) {
ctx: iamOwnerCtx,
prepare: func(request *action.DeleteTargetRequest) (time.Time, time.Time) {
creationDate := time.Now().UTC()
targetID := instance.CreateTarget(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
return creationDate, time.Time{}
},
@@ -509,7 +509,7 @@ func TestServer_DeleteTarget(t *testing.T) {
ctx: iamOwnerCtx,
prepare: func(request *action.DeleteTargetRequest) (time.Time, time.Time) {
creationDate := time.Now().UTC()
targetID := instance.CreateTarget(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
targetID := instance.CreateTargetWithoutPayloadType(iamOwnerCtx, t, "", "https://example.com", target_domain.TargetTypeWebhook, false).GetId()
request.Id = targetID
instance.DeleteTarget(iamOwnerCtx, t, targetID)
return creationDate, time.Now().UTC()
@@ -26,12 +26,12 @@ var headersToForward = map[string]bool{
strings.ToLower(http_utils.Origin): true,
}
func ExecutionHandler(alg crypto.EncryptionAlgorithm) connect.UnaryInterceptorFunc {
func ExecutionHandler(alg crypto.EncryptionAlgorithm, activeSigningKey execution.GetActiveSigningWebKey) connect.UnaryInterceptorFunc {
return func(handler connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (_ connect.AnyResponse, err error) {
requestTargets := execution.QueryExecutionTargetsForRequest(ctx, req.Spec().Procedure)
handledReq, err := executeTargetsForRequest(ctx, requestTargets, req.Spec().Procedure, req, alg)
handledReq, err := executeTargetsForRequest(ctx, requestTargets, req.Spec().Procedure, req, alg, activeSigningKey)
if err != nil {
return nil, err
}
@@ -42,12 +42,12 @@ func ExecutionHandler(alg crypto.EncryptionAlgorithm) connect.UnaryInterceptorFu
}
responseTargets := execution.QueryExecutionTargetsForResponse(ctx, req.Spec().Procedure)
return executeTargetsForResponse(ctx, responseTargets, req.Spec().Procedure, handledReq, response, alg)
return executeTargetsForResponse(ctx, responseTargets, req.Spec().Procedure, handledReq, response, alg, activeSigningKey)
}
}
}
func executeTargetsForRequest(ctx context.Context, targets []target_domain.Target, fullMethod string, req connect.AnyRequest, alg crypto.EncryptionAlgorithm) (_ connect.AnyRequest, err error) {
func executeTargetsForRequest(ctx context.Context, targets []target_domain.Target, fullMethod string, req connect.AnyRequest, alg crypto.EncryptionAlgorithm, activeSigningKey execution.GetActiveSigningWebKey) (_ connect.AnyRequest, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
@@ -67,14 +67,14 @@ func executeTargetsForRequest(ctx context.Context, targets []target_domain.Targe
Headers: SetRequestHeaders(req.Header()),
}
_, err = execution.CallTargets(ctx, targets, info, alg)
_, err = execution.CallTargets(ctx, targets, info, alg, activeSigningKey)
if err != nil {
return nil, err
}
return req, nil
}
func executeTargetsForResponse(ctx context.Context, targets []target_domain.Target, fullMethod string, req connect.AnyRequest, resp connect.AnyResponse, alg crypto.EncryptionAlgorithm) (_ connect.AnyResponse, err error) {
func executeTargetsForResponse(ctx context.Context, targets []target_domain.Target, fullMethod string, req connect.AnyRequest, resp connect.AnyResponse, alg crypto.EncryptionAlgorithm, activeSigningKey execution.GetActiveSigningWebKey) (_ connect.AnyResponse, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
@@ -95,7 +95,7 @@ func executeTargetsForResponse(ctx context.Context, targets []target_domain.Targ
Headers: SetRequestHeaders(req.Header()),
}
_, err = execution.CallTargets(ctx, targets, info, alg)
_, err = execution.CallTargets(ctx, targets, info, alg, activeSigningKey)
if err != nil {
return nil, err
}
@@ -1,25 +1,43 @@
package connect_middleware
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
"connectrpc.com/connect"
"github.com/go-jose/go-jose/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/execution"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
)
var (
privateKey = func() *rsa.PrivateKey {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
return privateKey
}()
encryptionKey = func() []byte {
data, _ := crypto.PublicKeyToBytes(&privateKey.PublicKey)
return data
}()
encryptionKeyID = "encryption-key-id"
signingAlgorithm = jose.RS256
)
func newMockContentRequest(content string) *connect.Request[structpb.Struct] {
return connect.NewRequest(&structpb.Struct{
Fields: map[string]*structpb.Value{
@@ -57,18 +75,20 @@ func newMockContextInfoResponse(fullMethod, request, response string) *ContextIn
func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
type target struct {
reqBody execution.ContextInfo
sleep time.Duration
statusCode int
respBody connect.AnyResponse
reqBody execution.ContextInfo
sleep time.Duration
statusCode int
respBody connect.AnyResponse
requestVerification func(*testing.T) func([]byte, []byte) bool
}
type args struct {
ctx context.Context
executionTargets []target_domain.Target
targets []target
fullMethod string
req connect.AnyRequest
executionTargets []target_domain.Target
targets []target
fullMethod string
req connect.AnyRequest
getActiveSigningWebKey execution.GetActiveSigningWebKey
}
type res struct {
want interface{}
@@ -139,10 +159,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -168,10 +189,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -196,10 +218,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -223,7 +246,10 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
},
targets: []target{
{reqBody: newMockContextInfoRequest("/service/method", "wrong")},
{
reqBody: newMockContextInfoRequest("/service/method", "wrong"),
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
},
@@ -247,10 +273,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -274,10 +301,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -301,10 +329,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -329,9 +358,10 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
sleep: 0,
statusCode: http.StatusInternalServerError,
reqBody: newMockContextInfoRequest("/service/method", "content"),
sleep: 0,
statusCode: http.StatusInternalServerError,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -356,10 +386,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -384,10 +415,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -427,22 +459,25 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentResponse("content2"),
sleep: 0,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentResponse("content2"),
sleep: 0,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentResponse("content3"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentResponse("content3"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -481,22 +516,25 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentResponse("content2"),
sleep: 5 * time.Second,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentResponse("content2"),
sleep: 5 * time.Second,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentResponse("content3"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentResponse("content3"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -505,6 +543,70 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
wantErr: true,
},
},
{
"payload JWT, ok",
args{
ctx: context.Background(),
fullMethod: "/service/method",
executionTargets: []target_domain.Target{
{
ExecutionID: "request./zitadel.session.v2.SessionService/SetSession",
TargetID: "target",
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Minute,
InterruptOnError: true,
PayloadType: target_domain.PayloadTypeJWT,
},
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJWTPayload,
},
},
req: newMockContentRequest("content"),
getActiveSigningWebKey: mockGetActiveSigningWebKey(),
},
res{
want: newMockContentRequest("content"),
},
},
{
"payload JWE, ok",
args{
ctx: context.Background(),
fullMethod: "/service/method",
executionTargets: []target_domain.Target{
{
ExecutionID: "request./zitadel.session.v2.SessionService/SetSession",
TargetID: "target",
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Minute,
InterruptOnError: true,
PayloadType: target_domain.PayloadTypeJWE,
EncryptionKey: encryptionKey,
EncryptionKeyID: encryptionKeyID,
},
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentResponse("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJWEPayload,
},
},
req: newMockContentRequest("content"),
getActiveSigningWebKey: mockGetActiveSigningWebKey(),
},
res{
want: newMockContentRequest("content"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -515,6 +617,7 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
target.sleep,
target.statusCode,
target.respBody,
target.requestVerification(t),
)
tt.args.executionTargets[i].Endpoint = url
@@ -527,6 +630,7 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
tt.args.fullMethod,
tt.args.req,
nil,
tt.args.getActiveSigningWebKey,
)
if tt.res.wantErr {
@@ -548,6 +652,7 @@ func testServerCall(
sleep time.Duration,
statusCode int,
respBody connect.AnyResponse,
requestVerification func(expected, sent []byte) bool,
) (string, func()) {
handler := func(w http.ResponseWriter, r *http.Request) {
data, err := json.Marshal(reqBody)
@@ -562,7 +667,7 @@ func testServerCall(
return
}
if !reflect.DeepEqual(data, sentBody) {
if !requestVerification(data, sentBody) {
http.Error(w, "error", http.StatusInternalServerError)
return
}
@@ -591,6 +696,45 @@ func testServerCall(
return server.URL, server.Close
}
func mockGetActiveSigningWebKey() func(ctx context.Context) (*jose.JSONWebKey, error) {
return func(ctx context.Context) (*jose.JSONWebKey, error) {
return &jose.JSONWebKey{
Key: privateKey,
Algorithm: string(signingAlgorithm),
Use: "sig",
}, nil
}
}
func validateJSONPayload(t *testing.T) func(expected, sent []byte) bool {
return bytes.Equal
}
func validateJWTPayload(t *testing.T) func(expected, sent []byte) bool {
return func(expected, sent []byte) bool {
jws, err := jose.ParseSigned(string(sent), []jose.SignatureAlgorithm{jose.RS256})
require.NoError(t, err)
payload, err := jws.Verify(privateKey.Public())
require.NoError(t, err)
return bytes.Equal(expected, payload)
}
}
func validateJWEPayload(t *testing.T) func(expected, sent []byte) bool {
return func(expected, sent []byte) bool {
parsedJWE, err := jose.ParseEncrypted(string(sent), []jose.KeyAlgorithm{jose.RSA_OAEP_256, jose.ECDH_ES_A256KW}, []jose.ContentEncryption{jose.A256GCM})
if err != nil {
return false
}
require.Equal(t, encryptionKeyID, parsedJWE.Header.KeyID)
require.Equal(t, "JWT", parsedJWE.Header.ExtraHeaders[jose.HeaderContentType].(string))
decryptedJWS, err := parsedJWE.Decrypt(privateKey)
require.NoError(t, err)
return validateJWTPayload(t)(expected, decryptedJWS)
}
}
func Test_executeTargetsForGRPCFullMethod_response(t *testing.T) {
type target struct {
reqBody execution.ContextInfo
@@ -710,6 +854,7 @@ func Test_executeTargetsForGRPCFullMethod_response(t *testing.T) {
target.sleep,
target.statusCode,
target.respBody,
validateJSONPayload(t),
)
tt.args.executionTargets[i].Endpoint = url
@@ -723,6 +868,7 @@ func Test_executeTargetsForGRPCFullMethod_response(t *testing.T) {
tt.args.req,
tt.args.resp,
nil,
mockGetActiveSigningWebKey(),
)
if tt.res.wantErr {
@@ -18,11 +18,11 @@ import (
"github.com/zitadel/zitadel/internal/telemetry/tracing"
)
func ExecutionHandler(alg crypto.EncryptionAlgorithm) grpc.UnaryServerInterceptor {
func ExecutionHandler(alg crypto.EncryptionAlgorithm, activeSigningKey execution.GetActiveSigningWebKey) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
requestTargets := execution.QueryExecutionTargetsForRequest(ctx, info.FullMethod)
// call targets otherwise return req
handledReq, err := executeTargetsForRequest(ctx, requestTargets, info.FullMethod, req, alg)
handledReq, err := executeTargetsForRequest(ctx, requestTargets, info.FullMethod, req, alg, activeSigningKey)
if err != nil {
return nil, err
}
@@ -33,11 +33,11 @@ func ExecutionHandler(alg crypto.EncryptionAlgorithm) grpc.UnaryServerIntercepto
}
responseTargets := execution.QueryExecutionTargetsForResponse(ctx, info.FullMethod)
return executeTargetsForResponse(ctx, responseTargets, info.FullMethod, handledReq, response, alg)
return executeTargetsForResponse(ctx, responseTargets, info.FullMethod, handledReq, response, alg, activeSigningKey)
}
}
func executeTargetsForRequest(ctx context.Context, targets []target_domain.Target, fullMethod string, req interface{}, alg crypto.EncryptionAlgorithm) (_ interface{}, err error) {
func executeTargetsForRequest(ctx context.Context, targets []target_domain.Target, fullMethod string, req interface{}, alg crypto.EncryptionAlgorithm, activeSigningKey execution.GetActiveSigningWebKey) (_ interface{}, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
@@ -58,10 +58,10 @@ func executeTargetsForRequest(ctx context.Context, targets []target_domain.Targe
Headers: connect_middleware.SetRequestHeaders(md),
}
return execution.CallTargets(ctx, targets, info, alg)
return execution.CallTargets(ctx, targets, info, alg, activeSigningKey)
}
func executeTargetsForResponse(ctx context.Context, targets []target_domain.Target, fullMethod string, req, resp interface{}, alg crypto.EncryptionAlgorithm) (_ interface{}, err error) {
func executeTargetsForResponse(ctx context.Context, targets []target_domain.Target, fullMethod string, req, resp interface{}, alg crypto.EncryptionAlgorithm, activeSigningKey execution.GetActiveSigningWebKey) (_ interface{}, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
@@ -83,7 +83,7 @@ func executeTargetsForResponse(ctx context.Context, targets []target_domain.Targ
Headers: connect_middleware.SetRequestHeaders(md),
}
return execution.CallTargets(ctx, targets, info, alg)
return execution.CallTargets(ctx, targets, info, alg, activeSigningKey)
}
var _ execution.ContextInfo = &ContextInfoRequest{}
@@ -1,24 +1,42 @@
package middleware
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/execution"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
)
var (
privateKey = func() *rsa.PrivateKey {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
return privateKey
}()
encryptionKey = func() []byte {
data, _ := crypto.PublicKeyToBytes(&privateKey.PublicKey)
return data
}()
encryptionKeyID = "encryption-key-id"
signingAlgorithm = jose.RS256
)
func newMockContentRequest(content string) proto.Message {
return &structpb.Struct{
Fields: map[string]*structpb.Value{
@@ -46,18 +64,20 @@ func newMockContextInfoResponse(fullMethod, request, response string) *ContextIn
func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
type target struct {
reqBody execution.ContextInfo
sleep time.Duration
statusCode int
respBody interface{}
reqBody execution.ContextInfo
sleep time.Duration
statusCode int
respBody interface{}
requestVerification func(*testing.T) func([]byte, []byte) bool
}
type args struct {
ctx context.Context
executionTargets []target_domain.Target
targets []target
fullMethod string
req interface{}
executionTargets []target_domain.Target
targets []target
fullMethod string
req interface{}
getActiveSigningWebKey execution.GetActiveSigningWebKey
}
type res struct {
want interface{}
@@ -128,10 +148,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -157,10 +178,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -185,10 +207,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -212,7 +235,10 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
},
targets: []target{
{reqBody: newMockContextInfoRequest("/service/method", "wrong")},
{
reqBody: newMockContextInfoRequest("/service/method", "wrong"),
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
},
@@ -236,10 +262,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -263,10 +290,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -290,10 +318,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -318,9 +347,10 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
sleep: 0,
statusCode: http.StatusInternalServerError,
reqBody: newMockContextInfoRequest("/service/method", "content"),
sleep: 0,
statusCode: http.StatusInternalServerError,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -345,10 +375,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -373,10 +404,11 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -416,22 +448,25 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentRequest("content2"),
sleep: 0,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentRequest("content2"),
sleep: 0,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentRequest("content3"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentRequest("content3"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -470,22 +505,25 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentRequest("content2"),
sleep: 5 * time.Second,
statusCode: http.StatusBadRequest,
reqBody: newMockContextInfoRequest("/service/method", "content1"),
respBody: newMockContentRequest("content2"),
sleep: 5 * time.Second,
statusCode: http.StatusBadRequest,
requestVerification: validateJSONPayload,
},
{
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentRequest("content3"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
reqBody: newMockContextInfoRequest("/service/method", "content2"),
respBody: newMockContentRequest("content3"),
sleep: 5 * time.Second,
statusCode: http.StatusOK,
requestVerification: validateJSONPayload,
},
},
req: newMockContentRequest("content"),
@@ -494,6 +532,70 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
wantErr: true,
},
},
{
"payload JWT, ok",
args{
ctx: context.Background(),
fullMethod: "/service/method",
executionTargets: []target_domain.Target{
{
ExecutionID: "request./zitadel.session.v2.SessionService/SetSession",
TargetID: "target",
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Minute,
InterruptOnError: true,
PayloadType: target_domain.PayloadTypeJWT,
},
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJWTPayload,
},
},
req: newMockContentRequest("content"),
getActiveSigningWebKey: mockGetActiveSigningWebKey(),
},
res{
want: newMockContentRequest("content"),
},
},
{
"payload JWE, ok",
args{
ctx: context.Background(),
fullMethod: "/service/method",
executionTargets: []target_domain.Target{
{
ExecutionID: "request./zitadel.session.v2.SessionService/SetSession",
TargetID: "target",
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Minute,
InterruptOnError: true,
PayloadType: target_domain.PayloadTypeJWE,
EncryptionKey: encryptionKey,
EncryptionKeyID: encryptionKeyID,
},
},
targets: []target{
{
reqBody: newMockContextInfoRequest("/service/method", "content"),
respBody: newMockContentRequest("content1"),
sleep: 0,
statusCode: http.StatusOK,
requestVerification: validateJWEPayload,
},
},
req: newMockContentRequest("content"),
getActiveSigningWebKey: mockGetActiveSigningWebKey(),
},
res{
want: newMockContentRequest("content"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -504,6 +606,7 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
target.sleep,
target.statusCode,
target.respBody,
target.requestVerification(t),
)
tt.args.executionTargets[i].Endpoint = url
@@ -516,6 +619,7 @@ func Test_executeTargetsForGRPCFullMethod_request(t *testing.T) {
tt.args.fullMethod,
tt.args.req,
nil,
tt.args.getActiveSigningWebKey,
)
if tt.res.wantErr {
@@ -537,6 +641,7 @@ func testServerCall(
sleep time.Duration,
statusCode int,
respBody interface{},
requestVerification func(expected, sent []byte) bool,
) (string, func()) {
handler := func(w http.ResponseWriter, r *http.Request) {
data, err := json.Marshal(reqBody)
@@ -551,7 +656,7 @@ func testServerCall(
return
}
if !reflect.DeepEqual(data, sentBody) {
if !requestVerification(data, sentBody) {
http.Error(w, "error", http.StatusInternalServerError)
return
}
@@ -580,6 +685,45 @@ func testServerCall(
return server.URL, server.Close
}
func mockGetActiveSigningWebKey() func(ctx context.Context) (*jose.JSONWebKey, error) {
return func(ctx context.Context) (*jose.JSONWebKey, error) {
return &jose.JSONWebKey{
Key: privateKey,
Algorithm: string(signingAlgorithm),
Use: "sig",
}, nil
}
}
func validateJSONPayload(t *testing.T) func(expected, sent []byte) bool {
return bytes.Equal
}
func validateJWTPayload(t *testing.T) func(expected, sent []byte) bool {
return func(expected, sent []byte) bool {
jws, err := jose.ParseSigned(string(sent), []jose.SignatureAlgorithm{jose.RS256})
require.NoError(t, err)
payload, err := jws.Verify(privateKey.Public())
require.NoError(t, err)
return bytes.Equal(expected, payload)
}
}
func validateJWEPayload(t *testing.T) func(expected, sent []byte) bool {
return func(expected, sent []byte) bool {
parsedJWE, err := jose.ParseEncrypted(string(sent), []jose.KeyAlgorithm{jose.RSA_OAEP_256, jose.ECDH_ES_A256KW}, []jose.ContentEncryption{jose.A256GCM})
if err != nil {
return false
}
require.Equal(t, encryptionKeyID, parsedJWE.Header.KeyID)
require.Equal(t, "JWT", parsedJWE.Header.ExtraHeaders[jose.HeaderContentType].(string))
decryptedJWS, err := parsedJWE.Decrypt(privateKey)
require.NoError(t, err)
return validateJWTPayload(t)(expected, decryptedJWS)
}
}
func Test_executeTargetsForGRPCFullMethod_response(t *testing.T) {
type target struct {
reqBody execution.ContextInfo
@@ -699,6 +843,7 @@ func Test_executeTargetsForGRPCFullMethod_response(t *testing.T) {
target.sleep,
target.statusCode,
target.respBody,
validateJSONPayload(t),
)
tt.args.executionTargets[i].Endpoint = url
@@ -712,6 +857,7 @@ func Test_executeTargetsForGRPCFullMethod_response(t *testing.T) {
tt.args.req,
tt.args.resp,
nil,
mockGetActiveSigningWebKey(),
)
if tt.res.wantErr {
+1 -1
View File
@@ -79,7 +79,7 @@ func CreateServer(
middleware.AuthorizationInterceptor(verifier, systemAuthz, authConfig),
middleware.TranslationHandler(),
middleware.QuotaExhaustedInterceptor(accessSvc, system_pb.SystemService_ServiceDesc.ServiceName),
middleware.ExecutionHandler(targetEncAlg),
middleware.ExecutionHandler(targetEncAlg, queries.GetActiveSigningWebKey),
middleware.ValidationHandler(),
middleware.ServiceHandler(),
middleware.ActivityInterceptor(),
+1 -1
View File
@@ -98,7 +98,7 @@ func authnKeyCreatedFilterToQuery(f *filter_pb.TimestampFilter) (query.SearchQue
}
func authnKeyExpirationFilterToQuery(f *filter_pb.TimestampFilter) (query.SearchQuery, error) {
return query.NewAuthNKeyExpirationDateDateQuery(f.Timestamp.AsTime(), filter.TimestampMethodPbToQuery(f.Method))
return query.NewAuthNKeyExpirationDateQuery(f.Timestamp.AsTime(), filter.TimestampMethodPbToQuery(f.Method))
}
// authnKeyFieldNameToSortingColumn defaults to the creation date because this ensures deterministic pagination
+2 -1
View File
@@ -19,6 +19,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/http/middleware"
"github.com/zitadel/zitadel/internal/api/oidc/sign"
"github.com/zitadel/zitadel/internal/api/ui/login"
"github.com/zitadel/zitadel/internal/auth/repository/eventsourcing/handler"
"github.com/zitadel/zitadel/internal/command"
@@ -300,7 +301,7 @@ func (o *OPStorage) TerminateSessionFromRequest(ctx context.Context, endSessionR
} else {
logoutURI = logoutURI.JoinPath(LogoutPath)
}
signer, _, err := GetSignerOnce(o.query.GetActiveSigningWebKey)(ctx)
signer, _, err := sign.GetSignerOnce(o.query.GetActiveSigningWebKey)(ctx)
if err != nil {
return "", err
}
+56
View File
@@ -0,0 +1,56 @@
package sign
import (
"context"
"sync"
"github.com/go-jose/go-jose/v4"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
)
// SignerFunc is a getter function that allows add-hoc retrieval of the instance's signer.
type SignerFunc func(ctx context.Context) (jose.Signer, jose.SignatureAlgorithm, error)
// GetSignerOnce returns a function which retrieves the instance's signer from the database once.
// Repeated calls of the returned function return the same results.
func GetSignerOnce(
getActiveSigningWebKey func(ctx context.Context) (*jose.JSONWebKey, error),
) SignerFunc {
var (
once sync.Once
signer jose.Signer
signAlg jose.SignatureAlgorithm
err error
)
return func(ctx context.Context) (jose.Signer, jose.SignatureAlgorithm, error) {
once.Do(func() {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
var webKey *jose.JSONWebKey
webKey, err = getActiveSigningWebKey(ctx)
if err != nil {
return
}
signer, signAlg, err = signerFromWebKey(webKey)
})
return signer, signAlg, err
}
}
func signerFromWebKey(signingKey *jose.JSONWebKey) (jose.Signer, jose.SignatureAlgorithm, error) {
signAlg := jose.SignatureAlgorithm(signingKey.Algorithm)
signer, err := jose.NewSigner(
jose.SigningKey{
Algorithm: signAlg,
Key: signingKey,
},
(&jose.SignerOptions{}).WithType("JWT"),
)
if err != nil {
return nil, "", zerrors.ThrowInternal(err, "OIDC-oaF0s", "Errors.Internal")
}
return signer, signAlg, nil
}
+5 -52
View File
@@ -4,18 +4,16 @@ import (
"context"
"encoding/base64"
"slices"
"sync"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/zitadel/oidc/v3/pkg/crypto"
"github.com/zitadel/oidc/v3/pkg/oidc"
"github.com/zitadel/oidc/v3/pkg/op"
"github.com/zitadel/zitadel/internal/api/oidc/sign"
"github.com/zitadel/zitadel/internal/command"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
)
/*
@@ -59,53 +57,8 @@ func (s *Server) accessTokenResponseFromSession(ctx context.Context, client op.C
return resp, err
}
// SignerFunc is a getter function that allows add-hoc retrieval of the instance's signer.
type SignerFunc func(ctx context.Context) (jose.Signer, jose.SignatureAlgorithm, error)
func (s *Server) getSignerOnce() SignerFunc {
return GetSignerOnce(s.query.GetActiveSigningWebKey)
}
// GetSignerOnce returns a function which retrieves the instance's signer from the database once.
// Repeated calls of the returned function return the same results.
func GetSignerOnce(
getActiveSigningWebKey func(ctx context.Context) (*jose.JSONWebKey, error),
) SignerFunc {
var (
once sync.Once
signer jose.Signer
signAlg jose.SignatureAlgorithm
err error
)
return func(ctx context.Context) (jose.Signer, jose.SignatureAlgorithm, error) {
once.Do(func() {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
var webKey *jose.JSONWebKey
webKey, err = getActiveSigningWebKey(ctx)
if err != nil {
return
}
signer, signAlg, err = signerFromWebKey(webKey)
})
return signer, signAlg, err
}
}
func signerFromWebKey(signingKey *jose.JSONWebKey) (jose.Signer, jose.SignatureAlgorithm, error) {
signAlg := jose.SignatureAlgorithm(signingKey.Algorithm)
signer, err := jose.NewSigner(
jose.SigningKey{
Algorithm: signAlg,
Key: signingKey,
},
(&jose.SignerOptions{}).WithType("JWT"),
)
if err != nil {
return nil, "", zerrors.ThrowInternal(err, "OIDC-oaF0s", "Errors.Internal")
}
return signer, signAlg, nil
func (s *Server) getSignerOnce() sign.SignerFunc {
return sign.GetSignerOnce(s.query.GetActiveSigningWebKey)
}
// userInfoFunc is a getter function that allows add-hoc retrieval of a user.
@@ -120,7 +73,7 @@ func (s *Server) getUserInfo(userID, projectID, clientID string, projectRoleAsse
}
}
func (*Server) createIDToken(ctx context.Context, client op.Client, getUserInfo userInfoFunc, roleAssertion bool, getSigningKey SignerFunc, sessionID, accessToken string, audience []string, authMethods []domain.UserAuthMethodType, authTime time.Time, nonce string, actor *domain.TokenActor) (idToken string, exp uint64, err error) {
func (*Server) createIDToken(ctx context.Context, client op.Client, getUserInfo userInfoFunc, roleAssertion bool, getSigningKey sign.SignerFunc, sessionID, accessToken string, audience []string, authMethods []domain.UserAuthMethodType, authTime time.Time, nonce string, actor *domain.TokenActor) (idToken string, exp uint64, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
@@ -164,7 +117,7 @@ func timeToOIDCExpiresIn(exp time.Time) uint64 {
return uint64(time.Until(exp) / time.Second)
}
func (s *Server) createJWT(ctx context.Context, client op.Client, session *command.OIDCSession, getUserInfo userInfoFunc, assertRoles bool, getSigner SignerFunc) (_ string, err error) {
func (s *Server) createJWT(ctx context.Context, client op.Client, session *command.OIDCSession, getUserInfo userInfoFunc, assertRoles bool, getSigner sign.SignerFunc) (_ string, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
+2 -1
View File
@@ -10,6 +10,7 @@ import (
"golang.org/x/text/language"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/api/oidc/sign"
"github.com/zitadel/zitadel/internal/domain"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
@@ -317,7 +318,7 @@ func (s *Server) createExchangeJWT(
client *Client,
getUserInfo userInfoFunc,
roleAssertion bool,
getSigner SignerFunc,
getSigner sign.SignerFunc,
userID,
resourceOwner string,
audience,
+1 -1
View File
@@ -461,7 +461,7 @@ func (s *Server) userinfoFlows(ctx context.Context, qu *query.OIDCUserInfo, user
UserGrants: qu.UserGrants,
}
resp, err := execution.CallTargets(ctx, executionTargets, info, s.targetEncryptionAlgorithm)
resp, err := execution.CallTargets(ctx, executionTargets, info, s.targetEncryptionAlgorithm, s.query.GetActiveSigningWebKey)
if err != nil {
return err
}
+1 -1
View File
@@ -401,7 +401,7 @@ func (p *Storage) getCustomAttributes(ctx context.Context, user *query.User, use
UserGrants: userGrants.UserGrants,
}
resp, err := execution.CallTargets(ctx, executionTargets, info, p.targetEncAlg)
resp, err := execution.CallTargets(ctx, executionTargets, info, p.targetEncAlg, p.query.GetActiveSigningWebKey)
if err != nil {
return nil, err
}
@@ -181,6 +181,7 @@ func TestCommands_SetExecutionRequest(t *testing.T) {
KeyID: "id",
Crypted: []byte("12345678"),
},
target_domain.PayloadTypeJSON,
),
),
),
@@ -236,6 +237,7 @@ func TestCommands_SetExecutionRequest(t *testing.T) {
KeyID: "id",
Crypted: []byte("12345678"),
},
target_domain.PayloadTypeJSON,
),
),
),
@@ -291,6 +293,7 @@ func TestCommands_SetExecutionRequest(t *testing.T) {
KeyID: "id",
Crypted: []byte("12345678"),
},
target_domain.PayloadTypeJSON,
),
),
),
@@ -863,6 +866,7 @@ func TestCommands_SetExecutionResponse(t *testing.T) {
KeyID: "id",
Crypted: []byte("12345678"),
},
target_domain.PayloadTypeJSON,
),
),
expectPushFailed(
@@ -963,6 +967,7 @@ func TestCommands_SetExecutionResponse(t *testing.T) {
KeyID: "id",
Crypted: []byte("12345678"),
},
target_domain.PayloadTypeJSON,
),
),
),
+4
View File
@@ -22,6 +22,7 @@ type AddTarget struct {
Endpoint string
Timeout time.Duration
InterruptOnError bool
PayloadType target_domain.PayloadType
SigningKey string
}
@@ -77,6 +78,7 @@ func (c *Commands) AddTarget(ctx context.Context, add *AddTarget, resourceOwner
add.Timeout,
add.InterruptOnError,
code.Crypted,
add.PayloadType,
))
if err != nil {
return time.Time{}, err
@@ -95,6 +97,7 @@ type ChangeTarget struct {
Endpoint *string
Timeout *time.Duration
InterruptOnError *bool
PayloadType target_domain.PayloadType
ExpirationSigningKey bool
SigningKey *string
@@ -153,6 +156,7 @@ func (c *Commands) ChangeTarget(ctx context.Context, change *ChangeTarget, resou
change.Timeout,
change.InterruptOnError,
changedSigningKey,
change.PayloadType,
)
if changedEvent == nil {
return existing.WriteModel.ChangeDate, nil
+190
View File
@@ -0,0 +1,190 @@
package command
import (
"context"
"crypto/ecdsa"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"time"
"github.com/zitadel/zitadel/internal/repository/target"
"github.com/zitadel/zitadel/internal/telemetry/tracing"
"github.com/zitadel/zitadel/internal/zerrors"
)
const (
ErrTargetIDMissing = "ErrTargetIDMissing"
ErrPublicKeyFormat = "ErrPublicKeyFormat"
ErrExpirationDateBeforeNow = "ErrExpirationDateBeforeNow"
ErrPublicKeyDeleteActiveKey = "ErrPublicKeyDeleteActiveKey"
ErrTargetNotFound = "ErrTargetNotFound"
ErrKeyNotFound = "ErrKeyNotFound"
ErrPublicKeyExpired = "ErrPublicKeyExpired"
)
type TargetPublicKey struct {
TargetID string
PublicKey []byte
Expiration time.Time
// KeyID is generated and returned after adding the public key
KeyID string
}
func (c *Commands) AddTargetPublicKey(ctx context.Context, key *TargetPublicKey, resourceOwner string) (_ time.Time, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if key.TargetID == "" {
return time.Time{}, zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing")
}
if !key.Expiration.IsZero() && key.Expiration.Before(time.Now()) {
return time.Time{}, zerrors.ThrowInvalidArgument(nil, ErrExpirationDateBeforeNow, "Errors.Target.InvalidExpirationDate")
}
fingerprint, err := checkPublicKeyAndComputeFingerprint(key.PublicKey)
if err != nil {
return time.Time{}, err
}
key.KeyID, err = c.idGenerator.Next()
if err != nil {
return time.Time{}, err
}
writeModel, err := c.getTargetKeyWriteModelByID(ctx, key.TargetID, key.KeyID, resourceOwner)
if err != nil {
return time.Time{}, err
}
if !writeModel.TargetExists {
return time.Time{}, zerrors.ThrowPreconditionFailed(nil, ErrTargetNotFound, "Errors.Target.NotFound")
}
err = c.pushAppendAndReduce(ctx, writeModel, target.NewKeyAddedEvent(
ctx,
TargetAggregateFromWriteModel(&writeModel.WriteModel),
key.KeyID,
key.PublicKey,
fingerprint,
key.Expiration,
))
if err != nil {
return time.Time{}, err
}
return writeModel.ChangeDate, nil
}
func (c *Commands) ActivateTargetPublicKey(ctx context.Context, targetID, keyID, resourceOwner string) (_ time.Time, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if targetID == "" || keyID == "" {
return time.Time{}, zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing")
}
writeModel, err := c.getTargetKeyWriteModelByID(ctx, targetID, keyID, resourceOwner)
if err != nil {
return time.Time{}, err
}
if !writeModel.TargetExists || !writeModel.KeyExists {
return time.Time{}, zerrors.ThrowPreconditionFailed(nil, ErrKeyNotFound, "Errors.Target.NotFound")
}
if !writeModel.ExpirationDate.IsZero() && writeModel.ExpirationDate.Before(time.Now()) {
return time.Time{}, zerrors.ThrowPreconditionFailed(nil, ErrPublicKeyExpired, "Errors.Target.PublicKeyExpired")
}
if writeModel.Active {
return writeModel.ChangeDate, nil
}
err = c.pushAppendAndReduce(ctx, writeModel, target.NewKeyActivatedEvent(
ctx,
TargetAggregateFromWriteModel(&writeModel.WriteModel),
keyID,
))
if err != nil {
return time.Time{}, err
}
return writeModel.ChangeDate, nil
}
func (c *Commands) DeactivateTargetPublicKey(ctx context.Context, targetID, keyID, resourceOwner string) (_ time.Time, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if targetID == "" || keyID == "" {
return time.Time{}, zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing")
}
writeModel, err := c.getTargetKeyWriteModelByID(ctx, targetID, keyID, resourceOwner)
if err != nil {
return time.Time{}, err
}
if !writeModel.TargetExists || !writeModel.KeyExists {
return time.Time{}, zerrors.ThrowPreconditionFailed(nil, ErrKeyNotFound, "Errors.Target.NotFound")
}
if !writeModel.Active {
return writeModel.ChangeDate, nil
}
err = c.pushAppendAndReduce(ctx, writeModel, target.NewKeyDeactivatedEvent(
ctx,
TargetAggregateFromWriteModel(&writeModel.WriteModel),
keyID,
))
if err != nil {
return time.Time{}, err
}
return writeModel.ChangeDate, nil
}
func (c *Commands) RemoveTargetPublicKey(ctx context.Context, targetID, keyID, resourceOwner string) (_ time.Time, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
if targetID == "" || keyID == "" {
return time.Time{}, zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing")
}
writeModel, err := c.getTargetKeyWriteModelByID(ctx, targetID, keyID, resourceOwner)
if err != nil {
return time.Time{}, err
}
if !writeModel.TargetExists || !writeModel.KeyExists {
return writeModel.ChangeDate, nil
}
if writeModel.Active {
return time.Time{}, zerrors.ThrowPreconditionFailed(nil, ErrPublicKeyDeleteActiveKey, "Errors.Target.PublicKeyActive")
}
err = c.pushAppendAndReduce(ctx, writeModel, target.NewKeyRemovedEvent(
ctx,
TargetAggregateFromWriteModel(&writeModel.WriteModel),
keyID,
))
if err != nil {
return time.Time{}, err
}
return writeModel.ChangeDate, nil
}
func checkPublicKeyAndComputeFingerprint(key []byte) (string, error) {
block, _ := pem.Decode(key)
if block == nil {
return "", zerrors.ThrowInvalidArgument(nil, ErrPublicKeyFormat, "Errors.Target.InvalidPublicKey")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return "", zerrors.ThrowInvalidArgument(err, ErrPublicKeyFormat, "Errors.Target.InvalidPublicKey")
}
switch pub.(type) {
case *rsa.PublicKey,
*ecdsa.PublicKey:
fingerprint := sha256.Sum256(block.Bytes)
return fmt.Sprintf("SHA256:%s", base64.RawStdEncoding.EncodeToString(fingerprint[:])), nil
default:
return "", zerrors.ThrowInvalidArgument(nil, ErrPublicKeyFormat, "Errors.Target.InvalidPublicKey")
}
}
func (c *Commands) getTargetKeyWriteModelByID(ctx context.Context, targetID, keyID string, resourceOwner string) (*TargetKeyWriteModel, error) {
wm := NewTargetKeyWriteModel(targetID, keyID, resourceOwner)
err := c.eventstore.FilterToQueryReducer(ctx, wm)
if err != nil {
return nil, err
}
return wm, nil
}
@@ -0,0 +1,94 @@
package command
import (
"time"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/repository/target"
)
type TargetKeyWriteModel struct {
eventstore.WriteModel
KeyID string
KeyExists bool
TargetExists bool
Active bool
ExpirationDate time.Time
}
func NewTargetKeyWriteModel(targetID, keyID string, resourceOwner string) *TargetKeyWriteModel {
return &TargetKeyWriteModel{
WriteModel: eventstore.WriteModel{
AggregateID: targetID,
ResourceOwner: resourceOwner,
},
KeyID: keyID,
}
}
func (wm *TargetKeyWriteModel) AppendEvents(events ...eventstore.Event) {
for _, event := range events {
switch e := event.(type) {
case *target.KeyAddedEvent:
if wm.KeyID != e.KeyID {
continue
}
wm.WriteModel.AppendEvents(e)
case *target.KeyActivatedEvent:
// don't check for KeyID, as only one key can be active at a time any activation event affects all keys
wm.WriteModel.AppendEvents(e)
case *target.KeyDeactivatedEvent:
if wm.KeyID != e.KeyID {
continue
}
wm.WriteModel.AppendEvents(e)
case *target.KeyRemovedEvent:
if wm.KeyID != e.KeyID {
continue
}
wm.WriteModel.AppendEvents(e)
case *target.AddedEvent:
wm.WriteModel.AppendEvents(e)
case *target.RemovedEvent:
wm.WriteModel.AppendEvents(e)
}
}
}
func (wm *TargetKeyWriteModel) Reduce() error {
for _, event := range wm.Events {
switch e := event.(type) {
case *target.KeyAddedEvent:
wm.KeyID = e.KeyID
wm.KeyExists = true
wm.ExpirationDate = e.ExpirationDate
case *target.KeyActivatedEvent:
wm.Active = wm.KeyID == e.KeyID
case *target.KeyDeactivatedEvent:
wm.Active = false
case *target.KeyRemovedEvent:
wm.KeyExists = false
case *target.AddedEvent:
wm.TargetExists = true
case *target.RemovedEvent:
wm.TargetExists = false
}
}
return wm.WriteModel.Reduce()
}
func (wm *TargetKeyWriteModel) Query() *eventstore.SearchQueryBuilder {
return eventstore.NewSearchQueryBuilder(eventstore.ColumnsEvent).
ResourceOwner(wm.ResourceOwner).
AddQuery().
AggregateTypes(target.AggregateType).
AggregateIDs(wm.AggregateID).
EventTypes(target.KeyAddedEventType,
target.KeyActivatedEventType,
target.KeyDeactivatedEventType,
target.KeyRemovedEventType,
target.AddedEventType,
target.RemovedEventType).
Builder()
}
@@ -0,0 +1,655 @@
package command
import (
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/id"
"github.com/zitadel/zitadel/internal/id/mock"
"github.com/zitadel/zitadel/internal/repository/target"
"github.com/zitadel/zitadel/internal/zerrors"
)
var (
rsaPublicKey = func() *rsa.PublicKey {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
return &privateKey.PublicKey
}()
rsaPublicKeyBytes = func() []byte {
data, _ := crypto.PublicKeyToBytes(rsaPublicKey)
return data
}()
rsaFingerprint = func() string {
block, _ := x509.MarshalPKIXPublicKey(rsaPublicKey)
hash := sha256.Sum256(block)
return fmt.Sprintf("SHA256:%s", base64.RawStdEncoding.EncodeToString(hash[:]))
}()
)
func TestCommands_AddTargetPublicKey(t *testing.T) {
type fields struct {
eventstore func(t *testing.T) *eventstore.Eventstore
idGenerator id.Generator
}
type args struct {
ctx context.Context
key *TargetPublicKey
resourceOwner string
}
type res struct {
err error
}
tests := []struct {
name string
fields fields
args args
res res
}{
{
name: "missing target id",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
key: &TargetPublicKey{},
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing"),
},
},
{
name: "expiration date before now",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
key: &TargetPublicKey{
TargetID: "target-1",
Expiration: testNow.Add(-time.Hour),
},
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrExpirationDateBeforeNow, "Errors.Target.InvalidExpirationDate"),
},
},
{
name: "invalid public key",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
key: &TargetPublicKey{
TargetID: "target-1",
PublicKey: []byte("invalid-key"),
},
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrPublicKeyFormat, "Errors.Target.InvalidPublicKey"),
},
},
{
name: "invalid public key format (PKCS1)",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
key: &TargetPublicKey{
TargetID: "target-1",
PublicKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(rsaPublicKey)}),
},
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrPublicKeyFormat, "Errors.Target.InvalidPublicKey"),
},
},
{
name: "invalid public key type (ed25519)",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
key: &TargetPublicKey{
TargetID: "target-1",
PublicKey: func() []byte {
publicKey, _, _ := ed25519.GenerateKey(rand.Reader)
ed25519PublicKeyBytes, _ := x509.MarshalPKIXPublicKey(publicKey)
return pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: ed25519PublicKeyBytes})
}(),
},
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrPublicKeyFormat, "Errors.Target.InvalidPublicKey"),
},
},
{
name: "target not found",
fields: fields{
eventstore: expectEventstore(
expectFilter(),
),
idGenerator: mock.ExpectID(t, "key-1"),
},
args: args{
ctx: context.Background(),
key: &TargetPublicKey{
TargetID: "target-1",
PublicKey: rsaPublicKeyBytes,
},
},
res: res{
err: zerrors.ThrowPreconditionFailed(nil, ErrTargetNotFound, "Errors.Target.NotFound"),
},
},
{
name: "success",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
),
expectPush(
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Time{},
),
),
),
),
idGenerator: mock.ExpectID(t, "key-1"),
},
args: args{
ctx: context.Background(),
key: &TargetPublicKey{
TargetID: "target-1",
PublicKey: rsaPublicKeyBytes,
},
},
res: res{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &Commands{
eventstore: tt.fields.eventstore(t),
idGenerator: tt.fields.idGenerator,
}
_, err := c.AddTargetPublicKey(tt.args.ctx, tt.args.key, tt.args.resourceOwner)
assert.ErrorIs(t, err, tt.res.err)
})
}
}
func TestCommands_ActivateTargetPublicKey(t *testing.T) {
type fields struct {
eventstore func(t *testing.T) *eventstore.Eventstore
}
type args struct {
ctx context.Context
targetID string
keyID string
resourceOwner string
}
type res struct {
err error
}
tests := []struct {
name string
fields fields
args args
res res
}{
{
name: "missing target id",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing"),
},
},
{
name: "missing key id",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing"),
},
},
{
name: "target not found",
fields: fields{
eventstore: expectEventstore(
expectFilter(),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{
err: zerrors.ThrowPreconditionFailed(nil, ErrKeyNotFound, "Errors.Target.NotFound"),
},
},
{
name: "already expired",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Now().Add(-time.Hour),
),
),
),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{
err: zerrors.ThrowPreconditionFailed(nil, ErrPublicKeyExpired, "Errors.Target.PublicKeyExpired"),
},
},
{
name: "already active",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Time{},
),
),
eventFromEventPusher(
target.NewKeyActivatedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
),
),
),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{},
},
{
name: "success",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Time{},
),
),
),
expectPush(
eventFromEventPusher(
target.NewKeyActivatedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
),
),
),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &Commands{
eventstore: tt.fields.eventstore(t),
}
_, err := c.ActivateTargetPublicKey(tt.args.ctx, tt.args.targetID, tt.args.keyID, tt.args.resourceOwner)
assert.ErrorIs(t, err, tt.res.err)
})
}
}
func TestCommands_DeactivateTargetPublicKey(t *testing.T) {
type fields struct {
eventstore func(t *testing.T) *eventstore.Eventstore
}
type args struct {
ctx context.Context
targetID string
keyID string
resourceOwner string
}
type res struct {
err error
}
tests := []struct {
name string
fields fields
args args
res res
}{
{
name: "missing target id",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing"),
},
},
{
name: "missing key id",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing"),
},
},
{
name: "target not found",
fields: fields{
eventstore: expectEventstore(
expectFilter(),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{
err: zerrors.ThrowPreconditionFailed(nil, ErrKeyNotFound, "Errors.Target.NotFound"),
},
},
{
name: "already inactive",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Time{},
),
),
),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{},
},
{
name: "success",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Time{},
),
),
eventFromEventPusher(
target.NewKeyActivatedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
),
),
),
expectPush(
eventFromEventPusher(
target.NewKeyDeactivatedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
),
),
),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &Commands{
eventstore: tt.fields.eventstore(t),
}
_, err := c.DeactivateTargetPublicKey(tt.args.ctx, tt.args.targetID, tt.args.keyID, tt.args.resourceOwner)
assert.ErrorIs(t, err, tt.res.err)
})
}
}
func TestCommands_RemoveTargetPublicKey(t *testing.T) {
type fields struct {
eventstore func(t *testing.T) *eventstore.Eventstore
}
type args struct {
ctx context.Context
targetID string
keyID string
resourceOwner string
}
type res struct {
err error
}
tests := []struct {
name string
fields fields
args args
res res
}{
{
name: "missing target id",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing"),
},
},
{
name: "missing key id",
fields: fields{
eventstore: expectEventstore(),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
},
res: res{
err: zerrors.ThrowInvalidArgument(nil, ErrTargetIDMissing, "Errors.IDMissing"),
},
},
{
name: "target not found",
fields: fields{
eventstore: expectEventstore(
expectFilter(),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{
err: nil,
},
},
{
name: "key active",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Time{},
),
),
eventFromEventPusher(
target.NewKeyActivatedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
),
),
),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{
err: zerrors.ThrowPreconditionFailed(nil, ErrPublicKeyDeleteActiveKey, "Errors.Target.PublicKeyActive"),
},
},
{
name: "success",
fields: fields{
eventstore: expectEventstore(
expectFilter(
eventFromEventPusher(
targetAddEvent("target-1", "instance1"),
),
eventFromEventPusher(
target.NewKeyAddedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
rsaPublicKeyBytes,
rsaFingerprint,
time.Time{},
),
),
),
expectPush(
eventFromEventPusher(
target.NewKeyRemovedEvent(context.Background(),
target.NewAggregate("target-1", "instance1"),
"key-1",
),
),
),
),
},
args: args{
ctx: context.Background(),
targetID: "target-1",
keyID: "key-1",
},
res: res{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &Commands{
eventstore: tt.fields.eventstore(t),
}
_, err := c.RemoveTargetPublicKey(tt.args.ctx, tt.args.targetID, tt.args.keyID, tt.args.resourceOwner)
assert.ErrorIs(t, err, tt.res.err)
})
}
}
@@ -21,6 +21,7 @@ type TargetWriteModel struct {
Timeout time.Duration
InterruptOnError bool
SigningKey *crypto.CryptoValue
PayloadType target_domain.PayloadType
State domain.TargetState
}
@@ -45,6 +46,7 @@ func (wm *TargetWriteModel) Reduce() error {
wm.Timeout = e.Timeout
wm.State = domain.TargetActive
wm.SigningKey = e.SigningKey
wm.PayloadType = e.PayloadType
case *target.ChangedEvent:
if e.Name != nil {
wm.Name = *e.Name
@@ -64,6 +66,9 @@ func (wm *TargetWriteModel) Reduce() error {
if e.SigningKey != nil {
wm.SigningKey = e.SigningKey
}
if e.PayloadType != target_domain.PayloadTypeUnspecified {
wm.PayloadType = e.PayloadType
}
case *target.RemovedEvent:
wm.State = domain.TargetRemoved
}
@@ -92,6 +97,7 @@ func (wm *TargetWriteModel) NewChangedEvent(
timeout *time.Duration,
interruptOnError *bool,
signingKey *crypto.CryptoValue,
payloadType target_domain.PayloadType,
) *target.ChangedEvent {
changes := make([]target.Changes, 0)
if name != nil && wm.Name != *name {
@@ -113,6 +119,9 @@ func (wm *TargetWriteModel) NewChangedEvent(
if signingKey != nil {
changes = append(changes, target.ChangeSigningKey(signingKey))
}
if payloadType != target_domain.PayloadTypeUnspecified && wm.PayloadType != payloadType {
changes = append(changes, target.ChangePayloadType(payloadType))
}
if len(changes) == 0 {
return nil
}
@@ -27,6 +27,7 @@ func targetAddEvent(aggID, resourceOwner string) *target.AddedEvent {
KeyID: "id",
Crypted: []byte("12345678"),
},
target_domain.PayloadTypeJSON,
)
}
+14 -8
View File
@@ -140,6 +140,7 @@ func TestCommands_AddTarget(t *testing.T) {
KeyID: "id",
Crypted: []byte("12345678"),
},
target_domain.PayloadTypeJSON,
),
),
),
@@ -150,10 +151,11 @@ func TestCommands_AddTarget(t *testing.T) {
args{
ctx: context.Background(),
add: &AddTarget{
Name: "name",
Endpoint: "https://example.com",
Timeout: time.Second,
TargetType: target_domain.TargetTypeWebhook,
Name: "name",
Endpoint: "https://example.com",
Timeout: time.Second,
TargetType: target_domain.TargetTypeWebhook,
PayloadType: target_domain.PayloadTypeJSON,
},
resourceOwner: "instance",
},
@@ -203,10 +205,11 @@ func TestCommands_AddTarget(t *testing.T) {
args{
ctx: context.Background(),
add: &AddTarget{
Name: "name",
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Second,
Endpoint: "https://example.com",
Name: "name",
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Second,
Endpoint: "https://example.com",
PayloadType: target_domain.PayloadTypeJSON,
},
resourceOwner: "instance",
},
@@ -239,6 +242,7 @@ func TestCommands_AddTarget(t *testing.T) {
Endpoint: "https://example.com",
Timeout: time.Second,
InterruptOnError: true,
PayloadType: target_domain.PayloadTypeJSON,
},
resourceOwner: "instance",
},
@@ -514,6 +518,7 @@ func TestCommands_ChangeTarget(t *testing.T) {
KeyID: "id",
Crypted: []byte("12345678"),
}),
target.ChangePayloadType(target_domain.PayloadTypeJWE),
},
),
),
@@ -533,6 +538,7 @@ func TestCommands_ChangeTarget(t *testing.T) {
Timeout: gu.Ptr(10 * time.Second),
InterruptOnError: gu.Ptr(true),
ExpirationSigningKey: true,
PayloadType: target_domain.PayloadTypeJWE,
},
resourceOwner: "instance",
},
+133 -4
View File
@@ -3,15 +3,22 @@ package execution
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"io"
"net/http"
"sync"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/zitadel/logging"
"github.com/zitadel/zitadel/internal/api/authz"
zhttp "github.com/zitadel/zitadel/internal/api/http"
"github.com/zitadel/zitadel/internal/api/oidc/sign"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/domain"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
@@ -27,20 +34,29 @@ type ContextInfo interface {
SetHTTPResponseBody([]byte) error
}
type GetActiveSigningWebKey func(ctx context.Context) (*jose.JSONWebKey, error)
// CallTargets call a list of targets in order with handling of error and responses
func CallTargets(
ctx context.Context,
targets []target_domain.Target,
info ContextInfo,
alg crypto.EncryptionAlgorithm,
activeSigningKey GetActiveSigningWebKey,
) (_ interface{}, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
// We make sure the signer and its key are only fetched once per CallTargets call.
signerOnce := sign.GetSignerOnce(activeSigningKey)
// Create a map to cache encrypters by key ID to avoid recreating them for each target.
encrypters := &sync.Map{}
for _, target := range targets {
// call the type of target
resp, err := CallTarget(ctx, target, info, alg)
resp, err := CallTarget(ctx, target, info, alg, signerOnce, encrypters)
// handle error if interrupt is set
logging.WithFields("instanceID", authz.GetInstance(ctx).InstanceID(), "target", target.GetTargetID()).OnError(err).Error("error calling target")
if err != nil && target.IsInterruptOnError() {
return nil, err
}
@@ -64,6 +80,8 @@ func CallTarget(
target target_domain.Target,
info ContextInfoRequest,
alg crypto.EncryptionAlgorithm,
signerOnce sign.SignerFunc,
encrypters *sync.Map,
) (res []byte, err error) {
ctx, span := tracing.NewSpan(ctx)
defer func() { span.EndWithError(err) }()
@@ -72,26 +90,137 @@ func CallTarget(
if err != nil {
return nil, zerrors.ThrowInternal(err, "EXEC-thiiCh5b", "Errors.Internal")
}
body, err := payload(ctx, info.GetHTTPRequestBody(), target, signerOnce, encrypters)
if err != nil {
return nil, err
}
switch target.GetTargetType() {
// get request, ignore response and return request and error for handling in list of targets
case target_domain.TargetTypeWebhook:
return nil, webhook(ctx, target.GetEndpoint(), target.GetTimeout(), info.GetHTTPRequestBody(), signingKey)
return nil, webhook(ctx, target.GetEndpoint(), target.GetTimeout(), body, signingKey)
// get request, return response and error
case target_domain.TargetTypeCall:
return Call(ctx, target.GetEndpoint(), target.GetTimeout(), info.GetHTTPRequestBody(), signingKey)
return Call(ctx, target.GetEndpoint(), target.GetTimeout(), body, signingKey)
case target_domain.TargetTypeAsync:
go func(ctx context.Context, target target_domain.Target, info []byte) {
if _, err := Call(ctx, target.GetEndpoint(), target.GetTimeout(), info, signingKey); err != nil {
logging.WithFields("target", target.GetTargetID()).OnError(err).Info(err)
}
}(context.WithoutCancel(ctx), target, info.GetHTTPRequestBody())
}(context.WithoutCancel(ctx), target, body)
return nil, nil
default:
return nil, zerrors.ThrowInternal(nil, "EXEC-auqnansr2m", "Errors.Execution.Unknown")
}
}
func payload(ctx context.Context, payload []byte, target target_domain.Target, signerOnce sign.SignerFunc, encrypters *sync.Map) ([]byte, error) {
switch target.GetPayloadType() {
case target_domain.PayloadTypeUnspecified,
target_domain.PayloadTypeJSON:
return payload, nil
case target_domain.PayloadTypeJWT:
return payloadJWT(ctx, payload, signerOnce)
case target_domain.PayloadTypeJWE:
return payloadJWE(ctx, payload, target, signerOnce, encrypters)
default:
return payload, nil
}
}
func payloadJWT(ctx context.Context, payload []byte, signerOnce sign.SignerFunc) ([]byte, error) {
signer, _, err := signerOnce(ctx)
if err != nil {
return nil, err
}
sig, err := signer.Sign(payload)
if err != nil {
return nil, err
}
data, err := sig.CompactSerialize()
if err != nil {
return nil, err
}
return []byte(data), nil
}
func loadEncrypter(target target_domain.Target, encrypters *sync.Map) (jose.Encrypter, error) {
if encrypter, ok := encrypters.Load(target.GetEncryptionKeyID()); ok {
return encrypter.(jose.Encrypter), nil
}
encryptionKey := target.GetEncryptionKey()
if len(encryptionKey) == 0 {
return nil, zerrors.ThrowInternal(nil, "EXEC-2n8fhs7g", "Errors.Execution.MissingEncryptionKey")
}
publicKey, algorithm, err := publicKeyFromBytes(encryptionKey)
if err != nil {
return nil, err
}
encrypter, err := jose.NewEncrypter(
jose.A256GCM,
jose.Recipient{
Algorithm: algorithm,
Key: publicKey,
KeyID: target.GetEncryptionKeyID(),
},
(&jose.EncrypterOptions{}).
WithType("JWT").
WithContentType("JWT"),
)
if err != nil {
return nil, err
}
encrypters.Store(target.GetEncryptionKeyID(), encrypter)
return encrypter, nil
}
func payloadJWE(
ctx context.Context,
payload []byte,
target target_domain.Target,
signerOnce sign.SignerFunc,
encrypters *sync.Map,
) ([]byte, error) {
payload, err := payloadJWT(ctx, payload, signerOnce)
if err != nil {
return nil, err
}
encrypter, err := loadEncrypter(target, encrypters)
if err != nil {
return nil, err
}
enc, err := encrypter.Encrypt(payload)
if err != nil {
return nil, err
}
crypted, err := enc.CompactSerialize()
if err != nil {
return nil, err
}
return []byte(crypted), nil
}
func publicKeyFromBytes(data []byte) (any, jose.KeyAlgorithm, error) {
block, _ := pem.Decode(data)
if block == nil {
return nil, "", zerrors.ThrowInternal(nil, "EXEC-3n8fhs7g", "Errors.Execution.InvalidPublicKey")
}
publicKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, "", err
}
switch pk := publicKey.(type) {
case *rsa.PublicKey:
return pk, jose.RSA_OAEP_256, nil
case *ecdsa.PublicKey:
return pk, jose.ECDH_ES_A256KW, nil
default:
return nil, "", zerrors.ThrowInternal(nil, "EXEC-NKJe2", "Errors.Execution.InvalidPublicKey")
}
}
// webhook call a webhook, ignore the response but return the errror
func webhook(ctx context.Context, url string, timeout time.Duration, body []byte, signingKey string) error {
_, err := Call(ctx, url, timeout, body, signingKey)
+256 -34
View File
@@ -3,20 +3,26 @@ package execution_test
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"google.golang.org/protobuf/types/known/structpb"
"github.com/zitadel/zitadel/internal/api/grpc/server/middleware"
"github.com/zitadel/zitadel/internal/api/oidc/sign"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/execution"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
@@ -111,7 +117,7 @@ func Test_Call(t *testing.T) {
respBody, err := testServer(t,
&callTestServer{
method: tt.args.method,
expectBody: tt.args.body,
expectBody: validateJSONPayload(tt.args.body),
timeout: tt.args.sleep,
statusCode: tt.args.statusCode,
respondBody: tt.args.respBody,
@@ -135,6 +141,7 @@ func Test_CallTarget(t *testing.T) {
info *middleware.ContextInfoRequest
server *callTestServer
target target_domain.Target
signer func(ctx context.Context) (jose.Signer, jose.SignatureAlgorithm, error)
}
type res struct {
body []byte
@@ -152,7 +159,7 @@ func Test_CallTarget(t *testing.T) {
info: requestContextInfo1,
server: &callTestServer{
method: http.MethodPost,
expectBody: []byte("{\"request\":{\"content\":\"request1\"}}"),
expectBody: validateJSONPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
timeout: time.Second,
statusCode: http.StatusInternalServerError,
@@ -173,7 +180,7 @@ func Test_CallTarget(t *testing.T) {
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: []byte("{\"request\":{\"content\":\"request1\"}}"),
expectBody: validateJSONPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusInternalServerError,
},
@@ -194,7 +201,7 @@ func Test_CallTarget(t *testing.T) {
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: []byte("{\"request\":{\"content\":\"request1\"}}"),
expectBody: validateJSONPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusOK,
},
@@ -215,7 +222,7 @@ func Test_CallTarget(t *testing.T) {
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: []byte("{\"request\":{\"content\":\"request1\"}}"),
expectBody: validateJSONPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusOK,
signingKey: "signingkey",
@@ -242,7 +249,7 @@ func Test_CallTarget(t *testing.T) {
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: []byte("{\"request\":{\"content\":\"request1\"}}"),
expectBody: validateJSONPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusInternalServerError,
},
@@ -263,7 +270,7 @@ func Test_CallTarget(t *testing.T) {
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: []byte("{\"request\":{\"content\":\"request1\"}}"),
expectBody: validateJSONPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusOK,
},
@@ -284,7 +291,7 @@ func Test_CallTarget(t *testing.T) {
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: []byte("{\"request\":{\"content\":\"request1\"}}"),
expectBody: validateJSONPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusOK,
signingKey: "signingkey",
@@ -303,10 +310,103 @@ func Test_CallTarget(t *testing.T) {
body: []byte("{\"content\":\"request2\"}"),
},
},
{
"webhook, JWT, ok",
args{
ctx: context.Background(),
info: requestContextInfo1,
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: validateJWTPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusOK,
signingKey: "signingkey",
},
target: target_domain.Target{
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Minute,
SigningKey: &crypto.CryptoValue{
Algorithm: "enc",
KeyID: "id",
Crypted: []byte("signingkey"),
},
PayloadType: target_domain.PayloadTypeJWT,
},
signer: mockSigner,
},
res{
body: nil,
},
},
{
"webhook, JWE, ok",
args{
ctx: context.Background(),
info: requestContextInfo1,
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: validateJWEPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusOK,
signingKey: "signingkey",
},
target: target_domain.Target{
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Minute,
SigningKey: &crypto.CryptoValue{
Algorithm: "enc",
KeyID: "id",
Crypted: []byte("signingkey"),
},
PayloadType: target_domain.PayloadTypeJWE,
EncryptionKey: encryptionKey,
EncryptionKeyID: encryptionKeyID,
},
signer: mockSigner,
},
res{
body: nil,
},
},
{
"webhook, JWE no encryption key, error",
args{
ctx: context.Background(),
info: requestContextInfo1,
server: &callTestServer{
timeout: time.Second,
method: http.MethodPost,
expectBody: validateJWEPayload([]byte("{\"request\":{\"content\":\"request1\"}}")),
respondBody: []byte("{\"content\":\"request2\"}"),
statusCode: http.StatusOK,
signingKey: "signingkey",
},
target: target_domain.Target{
TargetType: target_domain.TargetTypeWebhook,
Timeout: time.Minute,
SigningKey: &crypto.CryptoValue{
Algorithm: "enc",
KeyID: "id",
Crypted: []byte("signingkey"),
},
PayloadType: target_domain.PayloadTypeJWE,
},
signer: mockSigner,
},
res{
wantErr: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
respBody, err := testServer(t, tt.args.server, testCallTarget(tt.args.ctx, tt.args.info, tt.args.target, crypto.CreateMockEncryptionAlg(gomock.NewController(t))))
respBody, err := testServer(
t,
tt.args.server,
testCallTarget(tt.args.ctx, tt.args.info, tt.args.target, crypto.CreateMockEncryptionAlg(gomock.NewController(t)), tt.args.signer, &sync.Map{}),
)
if tt.res.wantErr {
assert.Error(t, err)
} else {
@@ -319,10 +419,11 @@ func Test_CallTarget(t *testing.T) {
func Test_CallTargets(t *testing.T) {
type args struct {
ctx context.Context
info *middleware.ContextInfoRequest
servers []*callTestServer
targets []target_domain.Target
ctx context.Context
info *middleware.ContextInfoRequest
servers []*callTestServer
targets []target_domain.Target
getActiveSigningWebKey func(*int32) execution.GetActiveSigningWebKey
}
type res struct {
ret interface{}
@@ -341,13 +442,13 @@ func Test_CallTargets(t *testing.T) {
servers: []*callTestServer{{
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusInternalServerError,
}, {
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusInternalServerError,
}},
@@ -368,13 +469,13 @@ func Test_CallTargets(t *testing.T) {
servers: []*callTestServer{{
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusInternalServerError,
}, {
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusInternalServerError,
}},
@@ -395,13 +496,13 @@ func Test_CallTargets(t *testing.T) {
servers: []*callTestServer{{
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusOK,
}, {
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: []byte("just a string, not json"),
statusCode: http.StatusOK,
}},
@@ -422,13 +523,13 @@ func Test_CallTargets(t *testing.T) {
servers: []*callTestServer{{
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusOK,
}, {
timeout: time.Second,
method: http.MethodPost,
expectBody: requestContextInfoBody1,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: []byte("just a string, not json"),
statusCode: http.StatusOK,
}},
@@ -440,12 +541,53 @@ func Test_CallTargets(t *testing.T) {
ret: requestContextInfo1.GetContent(),
},
},
{
"multiple JWT/JWE targets, ok",
args{
ctx: context.Background(),
info: requestContextInfo1,
servers: []*callTestServer{{
timeout: time.Second,
method: http.MethodPost,
expectBody: validateJWTPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusOK,
}, {
timeout: time.Second,
method: http.MethodPost,
expectBody: validateJSONPayload(requestContextInfoBody1),
respondBody: requestContextInfoBody2,
statusCode: http.StatusOK,
}},
targets: []target_domain.Target{
{
TargetType: target_domain.TargetTypeWebhook,
PayloadType: target_domain.PayloadTypeJWT,
Timeout: time.Minute,
},
{
TargetType: target_domain.TargetTypeWebhook,
PayloadType: target_domain.PayloadTypeJWE,
Timeout: time.Minute,
},
},
getActiveSigningWebKey: testActiveSingingWebKey,
},
res{
ret: requestContextInfo1.GetContent(),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var getWebKeyCalls int32
var getActiveSigningWebKey execution.GetActiveSigningWebKey
if tt.args.getActiveSigningWebKey != nil {
getActiveSigningWebKey = tt.args.getActiveSigningWebKey(&getWebKeyCalls)
}
respBody, err := testServers(t,
tt.args.servers,
testCallTargets(tt.args.ctx, tt.args.info, tt.args.targets, crypto.CreateMockEncryptionAlg(gomock.NewController(t))),
testCallTargets(tt.args.ctx, tt.args.info, tt.args.targets, crypto.CreateMockEncryptionAlg(gomock.NewController(t)), getActiveSigningWebKey),
)
if tt.res.wantErr {
assert.Error(t, err)
@@ -453,17 +595,27 @@ func Test_CallTargets(t *testing.T) {
assert.NoError(t, err)
}
assert.Equal(t, tt.res.ret, respBody)
var expectedCalls int32
if tt.args.getActiveSigningWebKey != nil {
expectedCalls = 1
}
assert.Equal(t, expectedCalls, atomic.LoadInt32(&getWebKeyCalls))
})
}
}
type callTestServer struct {
method string
expectBody []byte
expectBody func(*testing.T, []byte) bool
timeout time.Duration
statusCode int
respondBody []byte
signingKey string
called bool
}
func (s *callTestServer) Called() bool {
return s.called
}
func testServers(
@@ -473,8 +625,8 @@ func testServers(
) (interface{}, error) {
urls := make([]string, len(c))
for i := range c {
url, close := listen(t, c[i])
defer close()
url, closeF, _ := listen(t, c[i])
defer closeF()
urls[i] = url
}
return call(urls)
@@ -485,16 +637,17 @@ func testServer(
c *callTestServer,
call func(string) ([]byte, error),
) ([]byte, error) {
url, close := listen(t, c)
defer close()
url, closeF, _ := listen(t, c)
defer closeF()
return call(url)
}
func listen(
t *testing.T,
c *callTestServer,
) (url string, close func()) {
) (url string, close func(), called func() bool) {
handler := func(w http.ResponseWriter, r *http.Request) {
c.called = true
checkRequest(t, r, c.method, c.expectBody, c.signingKey)
if c.statusCode != http.StatusOK {
@@ -511,13 +664,15 @@ func listen(
}
}
server := httptest.NewServer(http.HandlerFunc(handler))
return server.URL, server.Close
return server.URL, server.Close, c.Called
}
func checkRequest(t *testing.T, sent *http.Request, method string, expectedBody []byte, signingKey string) {
func checkRequest(t *testing.T, sent *http.Request, method string, checkExpectedBody func(*testing.T, []byte) bool, signingKey string) {
sentBody, err := io.ReadAll(sent.Body)
require.NoError(t, err)
require.Equal(t, expectedBody, sentBody)
if !checkExpectedBody(t, sentBody) {
return
}
require.Equal(t, method, sent.Method)
if signingKey != "" {
require.NoError(t, actions.ValidatePayload(sentBody, sent.Header.Get(actions.SigningHeader), signingKey))
@@ -534,17 +689,20 @@ func testCallTarget(ctx context.Context,
info *middleware.ContextInfoRequest,
target target_domain.Target,
alg crypto.EncryptionAlgorithm,
signerOnce sign.SignerFunc,
encrypters *sync.Map,
) func(string) ([]byte, error) {
return func(url string) (r []byte, err error) {
target.Endpoint = url
return execution.CallTarget(ctx, target, info, alg)
return execution.CallTarget(ctx, target, info, alg, signerOnce, encrypters)
}
}
func testCallTargets(ctx context.Context,
info *middleware.ContextInfoRequest,
info execution.ContextInfo,
target []target_domain.Target,
alg crypto.EncryptionAlgorithm,
activeSigningKey execution.GetActiveSigningWebKey,
) func([]string) (interface{}, error) {
return func(urls []string) (interface{}, error) {
targets := make([]target_domain.Target, len(target))
@@ -552,7 +710,7 @@ func testCallTargets(ctx context.Context,
t.Endpoint = urls[i]
targets[i] = t
}
return execution.CallTargets(ctx, targets, info, alg)
return execution.CallTargets(ctx, targets, info, alg, activeSigningKey)
}
}
@@ -717,3 +875,67 @@ func Test_handleResponse(t *testing.T) {
}
}
var (
privateKey = func() *rsa.PrivateKey {
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
return privateKey
}()
encryptionKey = func() []byte {
data, _ := crypto.PublicKeyToBytes(&privateKey.PublicKey)
return data
}()
encryptionKeyID = "encryption-key-id"
signingAlgorithm = jose.RS256
)
func mockSigner(ctx context.Context) (jose.Signer, jose.SignatureAlgorithm, error) {
return sign.GetSignerOnce(mockGetActiveSigningWebKey)(ctx)
}
func mockGetActiveSigningWebKey(ctx context.Context) (*jose.JSONWebKey, error) {
return &jose.JSONWebKey{
Key: privateKey,
Algorithm: string(signingAlgorithm),
Use: "sig",
}, nil
}
func testActiveSingingWebKey(getWebKeyCalls *int32) execution.GetActiveSigningWebKey {
return func(ctx context.Context) (*jose.JSONWebKey, error) {
atomic.AddInt32(getWebKeyCalls, 1)
return mockGetActiveSigningWebKey(ctx)
}
}
func validateJSONPayload(expected []byte) func(*testing.T, []byte) bool {
return func(t *testing.T, actual []byte) bool {
require.Equal(t, expected, actual)
return false
}
}
func validateJWTPayload(expected []byte) func(*testing.T, []byte) bool {
return func(t *testing.T, actual []byte) bool {
jws, err := jose.ParseSigned(string(actual), []jose.SignatureAlgorithm{jose.RS256})
require.NoError(t, err)
payload, err := jws.Verify(privateKey.Public())
require.NoError(t, err)
return bytes.Equal(expected, payload)
}
}
func validateJWEPayload(expected []byte) func(*testing.T, []byte) bool {
return func(t *testing.T, actual []byte) bool {
parsedJWE, err := jose.ParseEncrypted(string(actual), []jose.KeyAlgorithm{jose.RSA_OAEP_256, jose.ECDH_ES_A256KW}, []jose.ContentEncryption{jose.A256GCM})
if err != nil {
return false
}
require.Equal(t, encryptionKeyID, parsedJWE.Header.KeyID)
require.Equal(t, "JWT", parsedJWE.Header.ExtraHeaders[jose.HeaderContentType].(string))
decryptedJWS, err := parsedJWE.Decrypt(privateKey)
require.NoError(t, err)
return validateJWTPayload(expected)(t, decryptedJWS)
}
}
+3 -1
View File
@@ -2,6 +2,7 @@ package execution
import (
"context"
"time"
"github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/eventstore/handler/v2"
@@ -16,9 +17,10 @@ func Register(
workerConfig WorkerConfig,
queue *queue.Queue,
targetEncAlg crypto.EncryptionAlgorithm,
activeSigningKey GetActiveSigningWebKey,
) {
queue.ShouldStart()
queue.AddWorkers(NewWorker(workerConfig, targetEncAlg))
queue.AddWorkers(NewWorker(workerConfig, targetEncAlg, activeSigningKey, time.Now))
}
func Start(ctx context.Context) {
+22
View File
@@ -14,6 +14,15 @@ const (
TargetTypeAsync
)
type PayloadType uint
const (
PayloadTypeUnspecified PayloadType = iota
PayloadTypeJSON
PayloadTypeJWT
PayloadTypeJWE
)
type Target struct {
ExecutionID string `json:"execution_id,omitempty"`
TargetID string `json:"target_id,omitempty"`
@@ -22,6 +31,9 @@ type Target struct {
Timeout time.Duration `json:"timeout,omitempty"`
InterruptOnError bool `json:"interrupt_on_error,omitempty"`
SigningKey *crypto.CryptoValue `json:"signing_key,omitempty"`
PayloadType PayloadType `json:"payload_type,omitempty"`
EncryptionKey []byte `json:"encryption_key,omitempty"`
EncryptionKeyID string `json:"encryption_key_id,omitempty"`
}
func (e *Target) GetExecutionID() string {
@@ -48,3 +60,13 @@ func (e *Target) GetSigningKey(alg crypto.EncryptionAlgorithm) (string, error) {
}
return crypto.DecryptString(e.SigningKey, alg)
}
func (e *Target) GetPayloadType() PayloadType {
return e.PayloadType
}
func (e *Target) GetEncryptionKey() []byte {
return e.EncryptionKey
}
func (e *Target) GetEncryptionKeyID() string {
return e.EncryptionKeyID
}
-85
View File
@@ -1,85 +0,0 @@
package execution
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"time"
)
type testServer struct {
server *httptest.Server
called bool
}
func (s *testServer) URL() string {
return s.server.URL
}
func (s *testServer) Close() {
s.server.Close()
}
func (s *testServer) Called() bool {
return s.called
}
func testServerCall(
reqBody interface{},
sleep time.Duration,
statusCode int,
respBody interface{},
) (string, func(), func() bool) {
server := &testServer{
called: false,
}
handler := func(w http.ResponseWriter, r *http.Request) {
server.called = true
if reqBody != nil {
data, err := json.Marshal(reqBody)
if err != nil {
http.Error(w, "error, marshall: "+err.Error(), http.StatusInternalServerError)
return
}
sentBody, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "error, read body: "+err.Error(), http.StatusInternalServerError)
return
}
if !reflect.DeepEqual(data, sentBody) {
http.Error(w, "error, equal:\n"+string(data)+"\nsent:\n"+string(sentBody), http.StatusInternalServerError)
return
}
}
if statusCode != http.StatusOK {
http.Error(w, "error, statusCode", statusCode)
return
}
time.Sleep(sleep)
if respBody != nil {
w.Header().Set("Content-Type", "application/json")
resp, err := json.Marshal(respBody)
if err != nil {
http.Error(w, "error", http.StatusInternalServerError)
return
}
if _, err := w.Write(resp); err != nil {
http.Error(w, "error", http.StatusInternalServerError)
return
}
} else {
if _, err := io.WriteString(w, "finished successfully"); err != nil {
http.Error(w, "error", http.StatusInternalServerError)
return
}
}
}
server.server = httptest.NewServer(http.HandlerFunc(handler))
return server.URL(), server.Close, server.Called
}
+12 -8
View File
@@ -18,9 +18,10 @@ type Worker struct {
river.WorkerDefaults[*exec_repo.Request]
config WorkerConfig
now nowFunc
now NowFunc
targetEncAlg crypto.EncryptionAlgorithm
targetEncAlg crypto.EncryptionAlgorithm
activeSigningKey GetActiveSigningWebKey
}
// Timeout implements the Timeout-function of [river.Worker].
@@ -45,7 +46,7 @@ func (w *Worker) Work(ctx context.Context, job *river.Job[*exec_repo.Request]) e
return river.JobCancel(fmt.Errorf("unable to unmarshal targets because %w", err))
}
_, err = CallTargets(ctx, targets, exec_repo.ContextInfoFromRequest(job.Args), w.targetEncAlg)
_, err = CallTargets(ctx, targets, exec_repo.ContextInfoFromRequest(job.Args), w.targetEncAlg, w.activeSigningKey)
if err != nil {
// If there is an error returned from the targets, it means that the execution was interrupted
return river.JobCancel(fmt.Errorf("interruption during call of targets because %w", err))
@@ -53,8 +54,8 @@ func (w *Worker) Work(ctx context.Context, job *river.Job[*exec_repo.Request]) e
return nil
}
// nowFunc makes [time.Now] mockable
type nowFunc func() time.Time
// NowFunc makes [time.Now] mockable
type NowFunc func() time.Time
type WorkerConfig struct {
Workers uint8
@@ -65,11 +66,14 @@ type WorkerConfig struct {
func NewWorker(
config WorkerConfig,
targetEncAlg crypto.EncryptionAlgorithm,
activeSigningKey GetActiveSigningWebKey,
now NowFunc,
) *Worker {
return &Worker{
config: config,
now: time.Now,
targetEncAlg: targetEncAlg,
config: config,
now: now,
targetEncAlg: targetEncAlg,
activeSigningKey: activeSigningKey,
}
}
+50 -27
View File
@@ -1,4 +1,4 @@
package execution
package execution_test
import (
"context"
@@ -15,6 +15,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/eventstore"
"github.com/zitadel/zitadel/internal/execution"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
"github.com/zitadel/zitadel/internal/repository/action"
exec_repo "github.com/zitadel/zitadel/internal/repository/execution"
@@ -23,26 +24,44 @@ import (
)
type fieldsWorker struct {
now nowFunc
now execution.NowFunc
}
type argsWorker struct {
job *river.Job[*exec_repo.Request]
}
type wantWorker struct {
targets []target_domain.Target
targets []target
sendStatusCode int
err assert.ErrorAssertionFunc
}
func newExecutionWorker(f fieldsWorker) *Worker {
return &Worker{
config: WorkerConfig{
type target target_domain.Target
func (t *target) validate(expectedBody []byte) func(*testing.T, []byte) bool {
switch t.PayloadType {
case target_domain.PayloadTypeUnspecified,
target_domain.PayloadTypeJSON:
return validateJSONPayload(expectedBody)
case target_domain.PayloadTypeJWT:
return validateJWTPayload(expectedBody)
case target_domain.PayloadTypeJWE:
return validateJWEPayload(expectedBody)
default:
return validateJSONPayload(expectedBody)
}
}
func newExecutionWorker(f fieldsWorker) *execution.Worker {
return execution.NewWorker(
execution.WorkerConfig{
Workers: 1,
TransactionDuration: 5 * time.Second,
MaxTtl: 5 * time.Minute,
},
now: f.now,
}
nil,
mockGetActiveSigningWebKey,
f.now,
)
}
const (
@@ -85,7 +104,7 @@ func Test_handleEventExecution(t *testing.T) {
},
},
wantWorker{
targets: mockTargets(1),
targets: mockTargets(target_domain.PayloadTypeJSON),
sendStatusCode: http.StatusOK,
err: func(tt assert.TestingT, err error, i ...interface{}) bool {
return errors.Is(err, new(river.JobCancelError))
@@ -153,7 +172,7 @@ func Test_handleEventExecution(t *testing.T) {
},
},
wantWorker{
targets: mockTargets(1),
targets: mockTargets(target_domain.PayloadTypeJSON),
sendStatusCode: http.StatusOK,
err: nil,
}
@@ -187,7 +206,7 @@ func Test_handleEventExecution(t *testing.T) {
},
},
wantWorker{
targets: mockTargets(1),
targets: mockTargets(target_domain.PayloadTypeJSON),
sendStatusCode: http.StatusBadRequest,
err: func(tt assert.TestingT, err error, i ...interface{}) bool {
return errors.Is(err, zerrors.ThrowPreconditionFailed(nil, "EXEC-dra6yamk98", "Errors.Execution.Failed"))
@@ -223,7 +242,7 @@ func Test_handleEventExecution(t *testing.T) {
},
},
wantWorker{
targets: mockTargets(3),
targets: mockTargets(target_domain.PayloadTypeJSON, target_domain.PayloadTypeJWT, target_domain.PayloadTypeJWE),
sendStatusCode: http.StatusOK,
err: nil,
}
@@ -234,15 +253,19 @@ func Test_handleEventExecution(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
f, a, w := tt.test()
body, err := json.Marshal(exec_repo.ContextInfoFromRequest(a.job.Args))
require.NoError(t, err)
closeFuncs := make([]func(), len(w.targets))
calledFuncs := make([]func() bool, len(w.targets))
for i := range w.targets {
url, closeF, calledF := testServerCall(
exec_repo.ContextInfoFromRequest(a.job.Args),
time.Second,
w.sendStatusCode,
nil,
)
url, closeF, calledF := listen(t, &callTestServer{
method: http.MethodPost,
expectBody: w.targets[i].validate(body),
timeout: time.Second,
statusCode: w.sendStatusCode,
respondBody: nil,
})
w.targets[i].Endpoint = url
closeFuncs[i] = closeF
calledFuncs[i] = calledF
@@ -273,24 +296,24 @@ func Test_handleEventExecution(t *testing.T) {
}
}
func mockTarget() target_domain.Target {
return target_domain.Target{
func mockTarget(payloadType target_domain.PayloadType) target {
return target{
ExecutionID: "executionID",
TargetID: "targetID",
TargetType: target_domain.TargetTypeWebhook,
Endpoint: "endpoint",
Timeout: time.Minute,
InterruptOnError: true,
PayloadType: payloadType,
EncryptionKey: encryptionKey,
EncryptionKeyID: encryptionKeyID,
}
}
func mockTargets(count int) []target_domain.Target {
var targets []target_domain.Target
if count > 0 {
targets = make([]target_domain.Target, count)
for i := range targets {
targets[i] = mockTarget()
}
func mockTargets(payloadTypes ...target_domain.PayloadType) []target {
targets := make([]target, len(payloadTypes))
for i, payloadType := range payloadTypes {
targets[i] = mockTarget(payloadType)
}
return targets
}
+9 -4
View File
@@ -1176,14 +1176,19 @@ func (i *Instance) DeleteProjectGrantMembership(t *testing.T, ctx context.Contex
require.NoError(t, err)
}
func (i *Instance) CreateTarget(ctx context.Context, t *testing.T, name, endpoint string, ty target_domain.TargetType, interrupt bool) *action.CreateTargetResponse {
func (i *Instance) CreateTargetWithoutPayloadType(ctx context.Context, t *testing.T, name, endpoint string, ty target_domain.TargetType, interrupt bool) *action.CreateTargetResponse {
return i.CreateTarget(ctx, t, name, endpoint, ty, interrupt, action.PayloadType_PAYLOAD_TYPE_UNSPECIFIED)
}
func (i *Instance) CreateTarget(ctx context.Context, t *testing.T, name, endpoint string, ty target_domain.TargetType, interrupt bool, payloadType action.PayloadType) *action.CreateTargetResponse {
if name == "" {
name = TargetName()
}
req := &action.CreateTargetRequest{
Name: name,
Endpoint: endpoint,
Timeout: durationpb.New(5 * time.Second),
Name: name,
Endpoint: endpoint,
Timeout: durationpb.New(5 * time.Second),
PayloadType: payloadType,
}
switch ty {
case target_domain.TargetTypeWebhook:
@@ -12,7 +12,7 @@ import (
"github.com/zitadel/zitadel/internal/api/authz"
http_utils "github.com/zitadel/zitadel/internal/api/http"
zoidc "github.com/zitadel/zitadel/internal/api/oidc"
"github.com/zitadel/zitadel/internal/api/oidc/sign"
"github.com/zitadel/zitadel/internal/command"
zcrypto "github.com/zitadel/zitadel/internal/crypto"
"github.com/zitadel/zitadel/internal/eventstore"
@@ -147,7 +147,7 @@ func (u *backChannelLogoutNotifier) terminateSession(ctx context.Context, id str
return err
}
getSigner := zoidc.GetSignerOnce(u.queries.GetActiveSigningWebKey)
getSigner := sign.GetSignerOnce(u.queries.GetActiveSigningWebKey)
var wg sync.WaitGroup
wg.Add(len(sessions.sessions))
@@ -170,7 +170,7 @@ func (u *backChannelLogoutNotifier) terminateSession(ctx context.Context, id str
return errors.Join(errs...)
}
func (u *backChannelLogoutNotifier) sendLogoutToken(ctx context.Context, oidcSession *backChannelLogoutOIDCSessions, e eventstore.Event, getSigner zoidc.SignerFunc) error {
func (u *backChannelLogoutNotifier) sendLogoutToken(ctx context.Context, oidcSession *backChannelLogoutOIDCSessions, e eventstore.Event, getSigner sign.SignerFunc) error {
token, err := u.logoutToken(ctx, oidcSession, getSigner)
if err != nil {
return err
@@ -182,7 +182,7 @@ func (u *backChannelLogoutNotifier) sendLogoutToken(ctx context.Context, oidcSes
return nil
}
func (u *backChannelLogoutNotifier) logoutToken(ctx context.Context, oidcSession *backChannelLogoutOIDCSessions, getSigner zoidc.SignerFunc) (string, error) {
func (u *backChannelLogoutNotifier) logoutToken(ctx context.Context, oidcSession *backChannelLogoutOIDCSessions, getSigner sign.SignerFunc) (string, error) {
jwtID, err := u.idGenerator.Next()
if err != nil {
return "", err
+53 -6
View File
@@ -84,6 +84,10 @@ var (
name: projection.AuthNKeyEnabledCol,
table: authNKeyTable,
}
AuthNKeyColumnFingerprint = Column{
name: projection.AuthNKeyFingerprintCol,
table: authNKeyTable,
}
)
type AuthNKeys struct {
@@ -100,8 +104,11 @@ type AuthNKey struct {
Sequence uint64
ApplicationID string
Expiration time.Time
Type domain.AuthNKeyType
Expiration time.Time
Type domain.AuthNKeyType
Enabled bool
PublicKey []byte
Fingerprint string
}
type AuthNKeysData struct {
@@ -141,6 +148,7 @@ const (
JoinFilterUnspecified JoinFilter = iota
JoinFilterApp
JoinFilterUserMachine
JoinFilterTarget
)
// SearchAuthNKeys returns machine or app keys, depending on the join filter.
@@ -173,11 +181,17 @@ func (q *Queries) searchAuthNKeys(ctx context.Context, queries *AuthNKeySearchQu
case JoinFilterUserMachine:
query = query.Join(join(MachineUserIDCol, AuthNKeyColumnIdentifier))
query = userPermissionCheckV2WithCustomColumns(ctx, query, permissionCheckV2, queries.Queries, AuthNKeyColumnResourceOwner, AuthNKeyColumnIdentifier)
case JoinFilterTarget:
query = query.Join(join(TargetColumnID, AuthNKeyColumnObjectID))
}
eq := sq.Eq{
AuthNKeyColumnEnabled.identifier(): true,
AuthNKeyColumnInstanceID.identifier(): authz.GetInstance(ctx).InstanceID(),
}
// Until now all disabled keys were just filtered out, but target keys can be explicitly disabled and
// the state needs to be returned rather than filtering them out.
if joinFilter != JoinFilterTarget {
eq[AuthNKeyColumnEnabled.identifier()] = true
}
stmt, args, err := query.Where(eq).ToSql()
if err != nil {
@@ -283,6 +297,14 @@ func NewAuthNKeyIDQuery(id string) (SearchQuery, error) {
return NewTextQuery(AuthNKeyColumnID, id, TextEquals)
}
func NewAuthNKeyInIDsSearchQuery(ids []string) (SearchQuery, error) {
return NewInTextQuery(AuthNKeyColumnID, ids)
}
func NewAuthNKeyEnabledSearchQuery(enabled bool) (SearchQuery, error) {
return NewBoolQuery(AuthNKeyColumnEnabled, enabled)
}
func NewAuthNKeyIdentifyerQuery(id string) (SearchQuery, error) {
return NewTextQuery(AuthNKeyColumnIdentifier, id, TextEquals)
}
@@ -291,8 +313,19 @@ func NewAuthNKeyCreationDateQuery(ts time.Time, compare TimestampComparison) (Se
return NewTimestampQuery(AuthNKeyColumnCreationDate, ts, compare)
}
func NewAuthNKeyExpirationDateDateQuery(ts time.Time, compare TimestampComparison) (SearchQuery, error) {
return NewTimestampQuery(AuthNKeyColumnExpiration, ts, compare)
func NewAuthNKeyExpirationDateQuery(ts time.Time, compare TimestampComparison) (SearchQuery, error) {
query, err := NewTimestampQuery(AuthNKeyColumnExpiration, ts, compare)
if err != nil {
return nil, err
}
if compare != TimestampGreater && compare != TimestampGreaterOrEquals {
return query, nil
}
noExpiration, err := NewIsNullQuery(AuthNKeyColumnExpiration)
if err != nil {
return nil, err
}
return NewOrQuery(query, noExpiration)
}
//go:embed authn_key_user.sql
@@ -344,6 +377,9 @@ func prepareAuthNKeysQuery() (sq.SelectBuilder, func(rows *sql.Rows) (*AuthNKeys
AuthNKeyColumnExpiration.identifier(),
AuthNKeyColumnType.identifier(),
AuthNKeyColumnObjectID.identifier(),
AuthNKeyColumnEnabled.identifier(),
AuthNKeyColumnPublicKey.identifier(),
AuthNKeyColumnFingerprint.identifier(),
countColumn.identifier(),
).From(authNKeyTable.identifier()).
PlaceholderFormat(sq.Dollar)
@@ -352,6 +388,8 @@ func prepareAuthNKeysQuery() (sq.SelectBuilder, func(rows *sql.Rows) (*AuthNKeys
authNKeys := make([]*AuthNKey, 0)
var count uint64
for rows.Next() {
var expiration sql.NullTime
var fingerprint sql.NullString
authNKey := new(AuthNKey)
err := rows.Scan(
&authNKey.ID,
@@ -360,14 +398,23 @@ func prepareAuthNKeysQuery() (sq.SelectBuilder, func(rows *sql.Rows) (*AuthNKeys
&authNKey.ChangeDate,
&authNKey.ResourceOwner,
&authNKey.Sequence,
&authNKey.Expiration,
&expiration,
&authNKey.Type,
&authNKey.ApplicationID,
&authNKey.Enabled,
&authNKey.PublicKey,
&fingerprint,
&count,
)
if err != nil {
return nil, err
}
if expiration.Valid {
authNKey.Expiration = expiration.Time
}
if fingerprint.Valid {
authNKey.Fingerprint = fingerprint.String
}
authNKeys = append(authNKeys, authNKey)
}
+27 -2
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"regexp"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -27,6 +28,9 @@ var (
` projections.authn_keys2.expiration,` +
` projections.authn_keys2.type,` +
` projections.authn_keys2.object_id,` +
` projections.authn_keys2.enabled,` +
` projections.authn_keys2.public_key,` +
` projections.authn_keys2.fingerprint,` +
` COUNT(*) OVER ()` +
` FROM projections.authn_keys2`
prepareAuthNKeysCols = []string{
@@ -39,6 +43,9 @@ var (
"expiration",
"type",
"object_id",
"enabled",
"public_key",
"fingerprint",
"count",
}
@@ -132,6 +139,9 @@ func Test_AuthNKeyPrepares(t *testing.T) {
testNow,
1,
"app1",
true,
[]byte("public"),
"fingerprint",
},
},
),
@@ -151,6 +161,9 @@ func Test_AuthNKeyPrepares(t *testing.T) {
Expiration: testNow,
Type: domain.AuthNKeyTypeJSON,
ApplicationID: "app1",
Enabled: true,
PublicKey: []byte("public"),
Fingerprint: "fingerprint",
},
},
},
@@ -173,6 +186,9 @@ func Test_AuthNKeyPrepares(t *testing.T) {
testNow,
1,
"app1",
true,
[]byte("public1"),
"fingerprint1",
},
{
"id-2",
@@ -181,9 +197,12 @@ func Test_AuthNKeyPrepares(t *testing.T) {
testNow,
"ro",
uint64(20211109),
testNow,
nil,
1,
"app1",
true,
[]byte("public2"),
nil,
},
},
),
@@ -203,6 +222,9 @@ func Test_AuthNKeyPrepares(t *testing.T) {
Expiration: testNow,
Type: domain.AuthNKeyTypeJSON,
ApplicationID: "app1",
Enabled: true,
PublicKey: []byte("public1"),
Fingerprint: "fingerprint1",
},
{
ID: "id-2",
@@ -211,9 +233,12 @@ func Test_AuthNKeyPrepares(t *testing.T) {
ChangeDate: testNow,
ResourceOwner: "ro",
Sequence: 20211109,
Expiration: testNow,
Expiration: time.Time{},
Type: domain.AuthNKeyTypeJSON,
ApplicationID: "app1",
Enabled: true,
PublicKey: []byte("public2"),
Fingerprint: "",
},
},
},
+9 -1
View File
@@ -35,7 +35,10 @@ with domain as (
'endpoint', t.endpoint,
'timeout', t.timeout,
'interrupt_on_error', t.interrupt_on_error,
'signing_key', t.signing_key
'signing_key', t.signing_key,
'payload_type', t.payload_type,
'encryption_key', encode(k.public_key, 'base64'),
'encryption_key_id', k.id
) as execution_targets
from domain d
join projections.executions1 e
@@ -46,6 +49,11 @@ with domain as (
join projections.targets2 t
on et.instance_id = t.instance_id
and et.target_id = t.id
left join projections.authn_keys2 k
on k.instance_id = et.instance_id
and k.object_id = t.id
and k.enabled = true
and (k.expiration IS NULL or k.expiration > now())
order by et.position asc
) as x
group by instance_id
+9 -1
View File
@@ -26,7 +26,10 @@ with features as (
'endpoint', t.endpoint,
'timeout', t.timeout,
'interrupt_on_error', t.interrupt_on_error,
'signing_key', t.signing_key
'signing_key', t.signing_key,
'payload_type', t.payload_type,
'encryption_key', encode(k.public_key, 'base64'),
'encryption_key_id', k.id
) as execution_targets
from projections.executions1 e
join projections.executions1_targets et
@@ -35,6 +38,11 @@ with features as (
join projections.targets2 t
on et.instance_id = t.instance_id
and et.target_id = t.id
left join projections.authn_keys2 k
on k.instance_id = et.instance_id
and k.object_id = t.id
and k.enabled = true
and (k.expiration IS NULL or k.expiration > now())
where e.instance_id = $1
order by et.position asc
) as x
+109 -9
View File
@@ -2,6 +2,7 @@ package projection
import (
"context"
"database/sql"
"time"
"github.com/zitadel/zitadel/internal/domain"
@@ -11,6 +12,7 @@ import (
"github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/org"
"github.com/zitadel/zitadel/internal/repository/project"
"github.com/zitadel/zitadel/internal/repository/target"
"github.com/zitadel/zitadel/internal/repository/user"
"github.com/zitadel/zitadel/internal/zerrors"
)
@@ -30,6 +32,7 @@ const (
AuthNKeyPublicKeyCol = "public_key"
AuthNKeyTypeCol = "type"
AuthNKeyEnabledCol = "enabled"
AuthNKeyFingerprintCol = "fingerprint"
)
type authNKeyProjection struct{}
@@ -53,11 +56,12 @@ func (*authNKeyProjection) Init() *old_handler.Check {
handler.NewColumn(AuthNKeyAggregateIDCol, handler.ColumnTypeText),
handler.NewColumn(AuthNKeySequenceCol, handler.ColumnTypeInt64),
handler.NewColumn(AuthNKeyObjectIDCol, handler.ColumnTypeText),
handler.NewColumn(AuthNKeyExpirationCol, handler.ColumnTypeTimestamp),
handler.NewColumn(AuthNKeyExpirationCol, handler.ColumnTypeTimestamp, handler.Nullable()),
handler.NewColumn(AuthNKeyIdentifierCol, handler.ColumnTypeText),
handler.NewColumn(AuthNKeyPublicKeyCol, handler.ColumnTypeBytes),
handler.NewColumn(AuthNKeyEnabledCol, handler.ColumnTypeBool, handler.Default(true)),
handler.NewColumn(AuthNKeyTypeCol, handler.ColumnTypeEnum, handler.Default(0)),
handler.NewColumn(AuthNKeyFingerprintCol, handler.ColumnTypeText, handler.Nullable()),
},
handler.NewPrimaryKey(AuthNKeyInstanceIDCol, AuthNKeyIDCol),
handler.WithIndex(handler.NewIndex("enabled", []string{AuthNKeyEnabledCol})),
@@ -117,6 +121,31 @@ func (p *authNKeyProjection) Reducers() []handler.AggregateReducer {
},
},
},
{
Aggregate: target.AggregateType,
EventReducers: []handler.EventReducer{
{
Event: target.KeyAddedEventType,
Reduce: p.reduceAuthNKeyAdded,
},
{
Event: target.KeyActivatedEventType,
Reduce: p.reduceTargetKeyActivated,
},
{
Event: target.KeyDeactivatedEventType,
Reduce: p.reduceTargetKeyDeactivated,
},
{
Event: target.KeyRemovedEventType,
Reduce: p.reduceAuthNKeyRemoved,
},
{
Event: target.RemovedEventType,
Reduce: p.reduceAuthNKeyRemoved,
},
},
},
{
Aggregate: org.AggregateType,
EventReducers: []handler.EventReducer{
@@ -141,30 +170,43 @@ func (p *authNKeyProjection) Reducers() []handler.AggregateReducer {
func (p *authNKeyProjection) reduceAuthNKeyAdded(event eventstore.Event) (*handler.Statement, error) {
var authNKeyEvent struct {
eventstore.BaseEvent
keyID string
objectID string
expiration time.Time
identifier string
publicKey []byte
keyType domain.AuthNKeyType
keyID string
objectID string
expiration sql.NullTime
identifier string
publicKey []byte
keyType domain.AuthNKeyType
fingerprint sql.NullString
enabled bool
}
switch e := event.(type) {
case *project.ApplicationKeyAddedEvent:
authNKeyEvent.BaseEvent = e.BaseEvent
authNKeyEvent.keyID = e.KeyID
authNKeyEvent.objectID = e.AppID
authNKeyEvent.expiration = e.ExpirationDate
authNKeyEvent.expiration = sql.NullTime{Time: e.ExpirationDate, Valid: true}
authNKeyEvent.identifier = e.ClientID
authNKeyEvent.publicKey = e.PublicKey
authNKeyEvent.keyType = e.KeyType
authNKeyEvent.enabled = true
case *user.MachineKeyAddedEvent:
authNKeyEvent.BaseEvent = e.BaseEvent
authNKeyEvent.keyID = e.KeyID
authNKeyEvent.objectID = e.Aggregate().ID
authNKeyEvent.expiration = e.ExpirationDate
authNKeyEvent.expiration = sql.NullTime{Time: e.ExpirationDate, Valid: true}
authNKeyEvent.identifier = e.Aggregate().ID
authNKeyEvent.publicKey = e.PublicKey
authNKeyEvent.keyType = e.KeyType
authNKeyEvent.enabled = true
case *target.KeyAddedEvent:
authNKeyEvent.BaseEvent = e.BaseEvent
authNKeyEvent.keyID = e.KeyID
authNKeyEvent.objectID = e.Aggregate().ID
authNKeyEvent.expiration = sql.NullTime{Time: e.ExpirationDate, Valid: !e.ExpirationDate.IsZero()}
authNKeyEvent.identifier = e.Aggregate().ID
authNKeyEvent.publicKey = e.PublicKey
authNKeyEvent.fingerprint = sql.NullString{String: e.Fingerprint, Valid: true}
authNKeyEvent.enabled = false
default:
return nil, zerrors.ThrowInvalidArgumentf(nil, "PROJE-Dgb32", "reduce.wrong.event.type %v", []eventstore.EventType{project.ApplicationKeyAddedEventType, user.MachineKeyAddedEventType})
}
@@ -183,6 +225,8 @@ func (p *authNKeyProjection) reduceAuthNKeyAdded(event eventstore.Event) (*handl
handler.NewCol(AuthNKeyIdentifierCol, authNKeyEvent.identifier),
handler.NewCol(AuthNKeyPublicKeyCol, authNKeyEvent.publicKey),
handler.NewCol(AuthNKeyTypeCol, authNKeyEvent.keyType),
handler.NewCol(AuthNKeyFingerprintCol, authNKeyEvent.fingerprint),
handler.NewCol(AuthNKeyEnabledCol, authNKeyEvent.enabled),
},
), nil
}
@@ -239,6 +283,10 @@ func (p *authNKeyProjection) reduceAuthNKeyRemoved(event eventstore.Event) (*han
condition = handler.NewCond(AuthNKeyIDCol, e.KeyID)
case *user.UserRemovedEvent:
condition = handler.NewCond(AuthNKeyAggregateIDCol, e.Aggregate().ID)
case *target.KeyRemovedEvent:
condition = handler.NewCond(AuthNKeyIDCol, e.KeyID)
case *target.RemovedEvent:
condition = handler.NewCond(AuthNKeyAggregateIDCol, e.Aggregate().ID)
default:
return nil, zerrors.ThrowInvalidArgumentf(nil, "PROJE-BGge42", "reduce.wrong.event.type %v", []eventstore.EventType{project.ApplicationKeyRemovedEventType, project.ApplicationRemovedType, project.ProjectRemovedType, user.MachineKeyRemovedEventType, user.UserRemovedType})
}
@@ -265,3 +313,55 @@ func (p *authNKeyProjection) reduceOwnerRemoved(event eventstore.Event) (*handle
},
), nil
}
func (p *authNKeyProjection) reduceTargetKeyActivated(event eventstore.Event) (*handler.Statement, error) {
e, err := assertEvent[*target.KeyActivatedEvent](event)
if err != nil {
return nil, err
}
return handler.NewMultiStatement(
e,
handler.AddUpdateStatement(
[]handler.Column{
handler.NewCol(AuthNKeyEnabledCol, false),
handler.NewCol(AuthNKeyChangeDateCol, e.CreationDate()),
handler.NewCol(AuthNKeySequenceCol, e.Sequence()),
},
[]handler.Condition{
handler.NewCond(AuthNKeyInstanceIDCol, e.Aggregate().InstanceID),
handler.NewCond(AuthNKeyAggregateIDCol, e.Aggregate().ID),
handler.NewCond(AuthNKeyEnabledCol, true),
},
),
handler.AddUpdateStatement(
[]handler.Column{
handler.NewCol(AuthNKeyEnabledCol, true),
handler.NewCol(AuthNKeyChangeDateCol, e.CreationDate()),
handler.NewCol(AuthNKeySequenceCol, e.Sequence()),
},
[]handler.Condition{
handler.NewCond(AuthNKeyIDCol, e.KeyID),
handler.NewCond(AuthNKeyInstanceIDCol, e.Aggregate().InstanceID),
},
),
), nil
}
func (p *authNKeyProjection) reduceTargetKeyDeactivated(event eventstore.Event) (*handler.Statement, error) {
e, err := assertEvent[*target.KeyDeactivatedEvent](event)
if err != nil {
return nil, err
}
return handler.NewUpdateStatement(
e,
[]handler.Column{
handler.NewCol(AuthNKeyEnabledCol, false),
handler.NewCol(AuthNKeyChangeDateCol, e.CreationDate()),
handler.NewCol(AuthNKeySequenceCol, e.Sequence()),
},
[]handler.Condition{
handler.NewCond(AuthNKeyIDCol, e.KeyID),
handler.NewCond(AuthNKeyInstanceIDCol, e.Aggregate().InstanceID),
},
), nil
}
+172 -2
View File
@@ -1,6 +1,7 @@
package projection
import (
"database/sql"
"testing"
"github.com/zitadel/zitadel/internal/domain"
@@ -9,6 +10,7 @@ import (
"github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/org"
"github.com/zitadel/zitadel/internal/repository/project"
"github.com/zitadel/zitadel/internal/repository/target"
"github.com/zitadel/zitadel/internal/repository/user"
"github.com/zitadel/zitadel/internal/zerrors"
)
@@ -40,7 +42,7 @@ func TestAuthNKeyProjection_reduces(t *testing.T) {
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO projections.authn_keys2 (id, creation_date, change_date, resource_owner, instance_id, aggregate_id, sequence, object_id, expiration, identifier, public_key, type) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
expectedStmt: "INSERT INTO projections.authn_keys2 (id, creation_date, change_date, resource_owner, instance_id, aggregate_id, sequence, object_id, expiration, identifier, public_key, type, fingerprint, enabled) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
expectedArgs: []interface{}{
"keyId",
anyArg{},
@@ -54,6 +56,8 @@ func TestAuthNKeyProjection_reduces(t *testing.T) {
"clientId",
[]byte("publicKey"),
domain.AuthNKeyTypeJSON,
sql.NullString{}, // fingerprint is not set for apps
true, // apps keys are enabled by default
},
},
},
@@ -77,7 +81,7 @@ func TestAuthNKeyProjection_reduces(t *testing.T) {
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO projections.authn_keys2 (id, creation_date, change_date, resource_owner, instance_id, aggregate_id, sequence, object_id, expiration, identifier, public_key, type) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
expectedStmt: "INSERT INTO projections.authn_keys2 (id, creation_date, change_date, resource_owner, instance_id, aggregate_id, sequence, object_id, expiration, identifier, public_key, type, fingerprint, enabled) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
expectedArgs: []interface{}{
"keyId",
anyArg{},
@@ -91,6 +95,47 @@ func TestAuthNKeyProjection_reduces(t *testing.T) {
"agg-id",
[]byte("publicKey"),
domain.AuthNKeyTypeJSON,
sql.NullString{}, // fingerprint is not set for users
true, // user keys are enabled by default
},
},
},
},
},
},
{
name: "reduceAuthNKeyAdded target",
args: args{
event: getEvent(
testEvent(
target.KeyAddedEventType,
target.AggregateType,
[]byte(`{"keyId": "keyId", "expirationDate": "2021-11-30T15:00:00Z", "publicKey": "cHVibGljS2V5", "fingerprint": "fingerprint"}`),
), eventstore.GenericEventMapper[target.KeyAddedEvent]),
},
reduce: (&authNKeyProjection{}).reduceAuthNKeyAdded,
want: wantReduce{
aggregateType: eventstore.AggregateType("target"),
sequence: 15,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO projections.authn_keys2 (id, creation_date, change_date, resource_owner, instance_id, aggregate_id, sequence, object_id, expiration, identifier, public_key, type, fingerprint, enabled) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)",
expectedArgs: []interface{}{
"keyId",
anyArg{},
anyArg{},
"ro-id",
"instance-id",
"agg-id",
uint64(15),
"agg-id",
anyArg{},
"agg-id",
[]byte("publicKey"),
domain.AuthNKeyTypeNONE,
sql.NullString{String: "fingerprint", Valid: true},
false, // target keys are disabled by default
},
},
},
@@ -470,6 +515,60 @@ func TestAuthNKeyProjection_reduces(t *testing.T) {
},
},
},
{
name: "reduceAuthNKeyRemoved target key removed",
args: args{
event: getEvent(
testEvent(
target.KeyRemovedEventType,
target.AggregateType,
[]byte(`{"keyId": "keyId"}`),
), eventstore.GenericEventMapper[target.KeyRemovedEvent]),
},
reduce: (&authNKeyProjection{}).reduceAuthNKeyRemoved,
want: wantReduce{
aggregateType: eventstore.AggregateType("target"),
sequence: 15,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM projections.authn_keys2 WHERE (id = $1) AND (instance_id = $2)",
expectedArgs: []interface{}{
"keyId",
"instance-id",
},
},
},
},
},
},
{
name: "reduceAuthNKeyRemoved target removed",
args: args{
event: getEvent(
testEvent(
target.RemovedEventType,
target.AggregateType,
[]byte(`{"keyId": "keyId"}`),
), eventstore.GenericEventMapper[target.RemovedEvent]),
},
reduce: (&authNKeyProjection{}).reduceAuthNKeyRemoved,
want: wantReduce{
aggregateType: eventstore.AggregateType("target"),
sequence: 15,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "DELETE FROM projections.authn_keys2 WHERE (aggregate_id = $1) AND (instance_id = $2)",
expectedArgs: []interface{}{
"agg-id",
"instance-id",
},
},
},
},
},
},
{
name: "reduceOwnerRemoved",
args: args{
@@ -497,6 +596,77 @@ func TestAuthNKeyProjection_reduces(t *testing.T) {
},
},
},
{
name: "reduceTargetKeyActivated",
args: args{
event: getEvent(
testEvent(
target.KeyActivatedEventType,
target.AggregateType,
[]byte(`{"keyId": "keyId"}`),
), eventstore.GenericEventMapper[target.KeyActivatedEvent]),
},
reduce: (&authNKeyProjection{}).reduceTargetKeyActivated,
want: wantReduce{
aggregateType: eventstore.AggregateType("target"),
sequence: 15,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE projections.authn_keys2 SET (enabled, change_date, sequence) = ($1, $2, $3) WHERE (instance_id = $4) AND (aggregate_id = $5) AND (enabled = $6)",
expectedArgs: []interface{}{
false,
anyArg{},
uint64(15),
"instance-id",
"agg-id",
true,
},
},
{
expectedStmt: "UPDATE projections.authn_keys2 SET (enabled, change_date, sequence) = ($1, $2, $3) WHERE (id = $4) AND (instance_id = $5)",
expectedArgs: []interface{}{
true,
anyArg{},
uint64(15),
"keyId",
"instance-id",
},
},
},
},
},
},
{
name: "reduceTargetKeyDeactivated",
args: args{
event: getEvent(
testEvent(
target.KeyDeactivatedEventType,
target.AggregateType,
[]byte(`{"keyId": "keyId"}`),
), eventstore.GenericEventMapper[target.KeyDeactivatedEvent]),
},
reduce: (&authNKeyProjection{}).reduceTargetKeyDeactivated,
want: wantReduce{
aggregateType: eventstore.AggregateType("target"),
sequence: 15,
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE projections.authn_keys2 SET (enabled, change_date, sequence) = ($1, $2, $3) WHERE (id = $4) AND (instance_id = $5)",
expectedArgs: []interface{}{
false,
anyArg{},
uint64(15),
"keyId",
"instance-id",
},
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
+7
View File
@@ -6,6 +6,7 @@ import (
"github.com/zitadel/zitadel/internal/eventstore"
old_handler "github.com/zitadel/zitadel/internal/eventstore/handler"
"github.com/zitadel/zitadel/internal/eventstore/handler/v2"
target_domain "github.com/zitadel/zitadel/internal/execution/target"
"github.com/zitadel/zitadel/internal/repository/instance"
"github.com/zitadel/zitadel/internal/repository/target"
)
@@ -24,6 +25,7 @@ const (
TargetTimeoutCol = "timeout"
TargetInterruptOnErrorCol = "interrupt_on_error"
TargetSigningKey = "signing_key"
TargetPayloadType = "payload_type"
)
type targetProjection struct{}
@@ -51,6 +53,7 @@ func (*targetProjection) Init() *old_handler.Check {
handler.NewColumn(TargetTimeoutCol, handler.ColumnTypeInt64),
handler.NewColumn(TargetInterruptOnErrorCol, handler.ColumnTypeBool),
handler.NewColumn(TargetSigningKey, handler.ColumnTypeJSONB, handler.Nullable()),
handler.NewColumn(TargetPayloadType, handler.ColumnTypeEnum, handler.Default(target_domain.PayloadTypeUnspecified)),
},
handler.NewPrimaryKey(TargetInstanceIDCol, TargetIDCol),
),
@@ -108,6 +111,7 @@ func (p *targetProjection) reduceTargetAdded(event eventstore.Event) (*handler.S
handler.NewCol(TargetTimeoutCol, e.Timeout),
handler.NewCol(TargetInterruptOnErrorCol, e.InterruptOnError),
handler.NewCol(TargetSigningKey, e.SigningKey),
handler.NewCol(TargetPayloadType, e.PayloadType),
},
), nil
}
@@ -140,6 +144,9 @@ func (p *targetProjection) reduceTargetChanged(event eventstore.Event) (*handler
if e.SigningKey != nil {
values = append(values, handler.NewCol(TargetSigningKey, e.SigningKey))
}
if e.PayloadType != target_domain.PayloadTypeUnspecified {
values = append(values, handler.NewCol(TargetPayloadType, e.PayloadType))
}
return handler.NewUpdateStatement(
e,
values,
+6 -4
View File
@@ -29,7 +29,7 @@ func TestTargetProjection_reduces(t *testing.T) {
testEvent(
target.AddedEventType,
target.AggregateType,
[]byte(`{"name": "name", "targetType":0, "endpoint":"https://example.com", "timeout": 3000000000, "async": true, "interruptOnError": true, "signingKey": { "cryptoType": 0, "algorithm": "RSA-265", "keyId": "key-id" }}`),
[]byte(`{"name": "name", "targetType":0, "endpoint":"https://example.com", "timeout": 3000000000, "async": true, "interruptOnError": true, "signingKey": { "cryptoType": 0, "algorithm": "RSA-265", "keyId": "key-id" }, "payloadType": 1}`),
),
eventstore.GenericEventMapper[target.AddedEvent],
),
@@ -41,7 +41,7 @@ func TestTargetProjection_reduces(t *testing.T) {
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "INSERT INTO projections.targets2 (instance_id, resource_owner, id, creation_date, change_date, sequence, name, endpoint, target_type, timeout, interrupt_on_error, signing_key) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
expectedStmt: "INSERT INTO projections.targets2 (instance_id, resource_owner, id, creation_date, change_date, sequence, name, endpoint, target_type, timeout, interrupt_on_error, signing_key, payload_type) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
expectedArgs: []interface{}{
"instance-id",
"ro-id",
@@ -55,6 +55,7 @@ func TestTargetProjection_reduces(t *testing.T) {
3 * time.Second,
true,
anyArg{},
target_domain.PayloadTypeJSON,
},
},
},
@@ -68,7 +69,7 @@ func TestTargetProjection_reduces(t *testing.T) {
testEvent(
target.ChangedEventType,
target.AggregateType,
[]byte(`{"name": "name2", "targetType":0, "endpoint":"https://example.com", "timeout": 3000000000, "async": true, "interruptOnError": true, "signingKey": { "cryptoType": 0, "algorithm": "RSA-265", "keyId": "key-id" }}`),
[]byte(`{"name": "name2", "targetType":0, "endpoint":"https://example.com", "timeout": 3000000000, "async": true, "interruptOnError": true, "signingKey": { "cryptoType": 0, "algorithm": "RSA-265", "keyId": "key-id" }, "payloadType": 1}`),
),
eventstore.GenericEventMapper[target.ChangedEvent],
),
@@ -80,7 +81,7 @@ func TestTargetProjection_reduces(t *testing.T) {
executer: &testExecuter{
executions: []execution{
{
expectedStmt: "UPDATE projections.targets2 SET (change_date, sequence, resource_owner, name, target_type, endpoint, timeout, interrupt_on_error, signing_key) = ($1, $2, $3, $4, $5, $6, $7, $8, $9) WHERE (instance_id = $10) AND (id = $11)",
expectedStmt: "UPDATE projections.targets2 SET (change_date, sequence, resource_owner, name, target_type, endpoint, timeout, interrupt_on_error, signing_key, payload_type) = ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) WHERE (instance_id = $11) AND (id = $12)",
expectedArgs: []interface{}{
anyArg{},
uint64(15),
@@ -91,6 +92,7 @@ func TestTargetProjection_reduces(t *testing.T) {
3 * time.Second,
true,
anyArg{},
target_domain.PayloadTypeJSON,
"instance-id",
"agg-id",
},
+9
View File
@@ -65,6 +65,10 @@ var (
name: projection.TargetSigningKey,
table: targetTable,
}
TargetColumnPayloadType = Column{
name: projection.TargetPayloadType,
table: targetTable,
}
)
type Targets struct {
@@ -86,6 +90,7 @@ type Target struct {
InterruptOnError bool
signingKey *crypto.CryptoValue
SigningKey string
PayloadType target_domain.PayloadType
}
func (t *Target) decryptSigningKey(alg crypto.EncryptionAlgorithm) error {
@@ -166,6 +171,7 @@ func prepareTargetsQuery() (sq.SelectBuilder, func(rows *sql.Rows) (*Targets, er
TargetColumnURL.identifier(),
TargetColumnInterruptOnError.identifier(),
TargetColumnSigningKey.identifier(),
TargetColumnPayloadType.identifier(),
countColumn.identifier(),
).From(targetTable.identifier()).
PlaceholderFormat(sq.Dollar),
@@ -185,6 +191,7 @@ func prepareTargetsQuery() (sq.SelectBuilder, func(rows *sql.Rows) (*Targets, er
&target.Endpoint,
&target.InterruptOnError,
&target.signingKey,
&target.PayloadType,
&count,
)
if err != nil {
@@ -218,6 +225,7 @@ func prepareTargetQuery() (sq.SelectBuilder, func(row *sql.Row) (*Target, error)
TargetColumnURL.identifier(),
TargetColumnInterruptOnError.identifier(),
TargetColumnSigningKey.identifier(),
TargetColumnPayloadType.identifier(),
).From(targetTable.identifier()).
PlaceholderFormat(sq.Dollar),
func(row *sql.Row) (*Target, error) {
@@ -233,6 +241,7 @@ func prepareTargetQuery() (sq.SelectBuilder, func(row *sql.Row) (*Target, error)
&target.Endpoint,
&target.InterruptOnError,
&target.signingKey,
&target.PayloadType,
)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
+15 -1
View File
@@ -26,6 +26,7 @@ var (
` projections.targets2.endpoint,` +
` projections.targets2.interrupt_on_error,` +
` projections.targets2.signing_key,` +
` projections.targets2.payload_type,` +
` COUNT(*) OVER ()` +
` FROM projections.targets2`
prepareTargetsCols = []string{
@@ -39,6 +40,7 @@ var (
"endpoint",
"interrupt_on_error",
"signing_key",
"payload_type",
"count",
}
@@ -51,7 +53,8 @@ var (
` projections.targets2.timeout,` +
` projections.targets2.endpoint,` +
` projections.targets2.interrupt_on_error,` +
` projections.targets2.signing_key` +
` projections.targets2.signing_key,` +
` projections.targets2.payload_type` +
` FROM projections.targets2`
prepareTargetCols = []string{
"id",
@@ -64,6 +67,7 @@ var (
"endpoint",
"interrupt_on_error",
"signing_key",
"payload_type",
}
)
@@ -114,6 +118,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
target_domain.PayloadTypeJSON,
},
},
),
@@ -141,6 +146,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
PayloadType: target_domain.PayloadTypeJSON,
},
},
},
@@ -169,6 +175,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
target_domain.PayloadTypeJSON,
},
{
"id-2",
@@ -186,6 +193,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
target_domain.PayloadTypeJWT,
},
{
"id-3",
@@ -203,6 +211,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
target_domain.PayloadTypeJWE,
},
},
),
@@ -230,6 +239,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
PayloadType: target_domain.PayloadTypeJSON,
},
{
ObjectDetails: domain.ObjectDetails{
@@ -249,6 +259,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
PayloadType: target_domain.PayloadTypeJWT,
},
{
ObjectDetails: domain.ObjectDetails{
@@ -268,6 +279,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
PayloadType: target_domain.PayloadTypeJWE,
},
},
},
@@ -330,6 +342,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
target_domain.PayloadTypeJSON,
},
),
},
@@ -351,6 +364,7 @@ func Test_TargetPrepares(t *testing.T) {
KeyID: "encKey",
Crypted: []byte("crypted"),
},
PayloadType: target_domain.PayloadTypeJSON,
},
},
{
+4
View File
@@ -6,4 +6,8 @@ func init() {
eventstore.RegisterFilterEventMapper(AggregateType, AddedEventType, eventstore.GenericEventMapper[AddedEvent])
eventstore.RegisterFilterEventMapper(AggregateType, ChangedEventType, eventstore.GenericEventMapper[ChangedEvent])
eventstore.RegisterFilterEventMapper(AggregateType, RemovedEventType, eventstore.GenericEventMapper[RemovedEvent])
eventstore.RegisterFilterEventMapper(AggregateType, KeyAddedEventType, eventstore.GenericEventMapper[KeyAddedEvent])
eventstore.RegisterFilterEventMapper(AggregateType, KeyActivatedEventType, eventstore.GenericEventMapper[KeyActivatedEvent])
eventstore.RegisterFilterEventMapper(AggregateType, KeyDeactivatedEventType, eventstore.GenericEventMapper[KeyDeactivatedEvent])
eventstore.RegisterFilterEventMapper(AggregateType, KeyRemovedEventType, eventstore.GenericEventMapper[KeyRemovedEvent])
}
+122
View File
@@ -0,0 +1,122 @@
package target
import (
"context"
"time"
"github.com/zitadel/zitadel/internal/eventstore"
)
const (
keyEventTypePrefix eventstore.EventType = "target.key."
KeyAddedEventType = keyEventTypePrefix + "added"
KeyActivatedEventType = keyEventTypePrefix + "activated"
KeyDeactivatedEventType = keyEventTypePrefix + "deactivated"
KeyRemovedEventType = keyEventTypePrefix + "removed"
)
type KeyAddedEvent struct {
eventstore.BaseEvent `json:"-"`
KeyID string `json:"keyId,omitempty"`
PublicKey []byte `json:"publicKey,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
ExpirationDate time.Time `json:"expirationDate,omitzero"`
}
func (e *KeyAddedEvent) SetBaseEvent(b *eventstore.BaseEvent) {
e.BaseEvent = *b
}
func (e *KeyAddedEvent) Payload() any {
return e
}
func (e *KeyAddedEvent) UniqueConstraints() []*eventstore.UniqueConstraint {
return nil
}
func NewKeyAddedEvent(
ctx context.Context,
aggregate *eventstore.Aggregate,
keyID string,
publicKey []byte,
fingerprint string,
expiration time.Time,
) *KeyAddedEvent {
return &KeyAddedEvent{
BaseEvent: *eventstore.NewBaseEventForPush(
ctx, aggregate, KeyAddedEventType,
),
KeyID: keyID,
PublicKey: publicKey,
Fingerprint: fingerprint,
ExpirationDate: expiration,
}
}
type KeyActivatedEvent struct {
eventstore.BaseEvent `json:"-"`
KeyID string `json:"keyId,omitempty"`
}
func (e *KeyActivatedEvent) SetBaseEvent(b *eventstore.BaseEvent) {
e.BaseEvent = *b
}
func (e *KeyActivatedEvent) Payload() any {
return e
}
func (e *KeyActivatedEvent) UniqueConstraints() []*eventstore.UniqueConstraint {
return nil
}
func NewKeyActivatedEvent(ctx context.Context, aggregate *eventstore.Aggregate, id string) *KeyActivatedEvent {
return &KeyActivatedEvent{*eventstore.NewBaseEventForPush(ctx, aggregate, KeyActivatedEventType), id}
}
type KeyDeactivatedEvent struct {
eventstore.BaseEvent `json:"-"`
KeyID string `json:"keyId,omitempty"`
}
func (e *KeyDeactivatedEvent) SetBaseEvent(b *eventstore.BaseEvent) {
e.BaseEvent = *b
}
func (e *KeyDeactivatedEvent) Payload() any {
return e
}
func (e *KeyDeactivatedEvent) UniqueConstraints() []*eventstore.UniqueConstraint {
return nil
}
func NewKeyDeactivatedEvent(ctx context.Context, aggregate *eventstore.Aggregate, id string) *KeyDeactivatedEvent {
return &KeyDeactivatedEvent{*eventstore.NewBaseEventForPush(ctx, aggregate, KeyDeactivatedEventType), id}
}
type KeyRemovedEvent struct {
eventstore.BaseEvent `json:"-"`
KeyID string `json:"keyId,omitempty"`
}
func (e *KeyRemovedEvent) SetBaseEvent(b *eventstore.BaseEvent) {
e.BaseEvent = *b
}
func (e *KeyRemovedEvent) Payload() any {
return e
}
func (e *KeyRemovedEvent) UniqueConstraints() []*eventstore.UniqueConstraint {
return nil
}
func NewKeyRemovedEvent(ctx context.Context, aggregate *eventstore.Aggregate, id string) *KeyRemovedEvent {
return &KeyRemovedEvent{*eventstore.NewBaseEventForPush(ctx, aggregate, KeyRemovedEventType), id}
}
+23 -7
View File
@@ -19,12 +19,13 @@ const (
type AddedEvent struct {
eventstore.BaseEvent `json:"-"`
Name string `json:"name"`
TargetType target_domain.TargetType `json:"targetType"`
Endpoint string `json:"endpoint"`
Timeout time.Duration `json:"timeout"`
InterruptOnError bool `json:"interruptOnError"`
SigningKey *crypto.CryptoValue `json:"signingKey"`
Name string `json:"name"`
TargetType target_domain.TargetType `json:"targetType"`
Endpoint string `json:"endpoint"`
Timeout time.Duration `json:"timeout"`
InterruptOnError bool `json:"interruptOnError"`
SigningKey *crypto.CryptoValue `json:"signingKey"`
PayloadType target_domain.PayloadType `json:"payloadType"`
}
func (e *AddedEvent) SetBaseEvent(b *eventstore.BaseEvent) {
@@ -48,12 +49,20 @@ func NewAddedEvent(
timeout time.Duration,
interruptOnError bool,
signingKey *crypto.CryptoValue,
payloadType target_domain.PayloadType,
) *AddedEvent {
return &AddedEvent{
*eventstore.NewBaseEventForPush(
ctx, aggregate, AddedEventType,
),
name, targetType, endpoint, timeout, interruptOnError, signingKey}
name,
targetType,
endpoint,
timeout,
interruptOnError,
signingKey,
payloadType,
}
}
type ChangedEvent struct {
@@ -65,6 +74,7 @@ type ChangedEvent struct {
Timeout *time.Duration `json:"timeout,omitempty"`
InterruptOnError *bool `json:"interruptOnError,omitempty"`
SigningKey *crypto.CryptoValue `json:"signingKey,omitempty"`
PayloadType target_domain.PayloadType `json:"payloadType,omitempty"`
oldName string
}
@@ -144,6 +154,12 @@ func ChangeSigningKey(signingKey *crypto.CryptoValue) func(event *ChangedEvent)
}
}
func ChangePayloadType(payloadType target_domain.PayloadType) func(event *ChangedEvent) {
return func(e *ChangedEvent) {
e.PayloadType = payloadType
}
}
type RemovedEvent struct {
eventstore.BaseEvent `json:"-"`
+5
View File
@@ -593,6 +593,10 @@ Errors:
NoTimeout: Целта няма време за изчакване
InvalidURL: Целта има невалиден URL адрес
NotFound: Целта не е намерена
InvalidExpirationDate: Срокът за изтичане на ключа трябва да бъде в бъдещето
PublicKeyExpired: Публичният ключ на целта е изтекъл
PublicKeyActive: Не може да се изтрие активен публичен ключ на целта
InvalidPublicKey: Публичният ключ е невалиден. Трябва да е PEM-кодиран RSA или ECDSA публичен ключ в PKCS#8 формат
Execution:
ConditionInvalid: Условието за изпълнение е невалидно
Invalid: Изпълнението е невалидно
@@ -601,6 +605,7 @@ Errors:
NoTargets: Няма определени цели
Failed: неуспешно изпълнение
ResponseIsNotValidJSON: Отговорът не е валиден JSON
MissingEncryptionKey: Липсващ ключ за шифроване
UserSchema:
NotEnabled: Функцията „Потребителска схема“ не е активирана
Type:
+5
View File
@@ -573,6 +573,10 @@ Errors:
NoTimeout: Cíl nemá časový limit
InvalidURL: Cíl má neplatnou adresu URL
NotFound: Cíl nenalezen
InvalidExpirationDate: Datum vypršení platnosti klíče musí být v budoucnosti
PublicKeyExpired: Veřejný klíč cíle vypršel
PublicKeyActive: Nelze odstranit aktivní veřejný klíč cíle
InvalidPublicKey: Veřejný klíč je neplatný. Musí být PEM kódovaný RSA nebo ECDSA veřejný klíč ve formátu PKCS#8
Execution:
ConditionInvalid: Podmínka provedení je neplatná
Invalid: Provedení je neplatné
@@ -581,6 +585,7 @@ Errors:
NoTargets: Nejsou definovány žádné cíle
Failed: Provedení se nezdařilo
ResponseIsNotValidJSON: Odpověď není platný JSON
MissingEncryptionKey: Chybí klíč pro šifrování
UserSchema:
NotEnabled: Funkce "Uživatelské schéma" není povolena
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: Ziel hat keinen Timeout
InvalidURL: Ziel hat eine ungültige URL
NotFound: Ziel nicht gefunden
InvalidExpirationDate: Ablaufdatum des Schlüssels muss in der Zukunft liegen
PublicKeyExpired: Öffentlicher Schlüssel des Ziels ist abgelaufen
PublicKeyActive: Aktiven öffentlichen Zielschlüssel kann nicht gelöscht werden
InvalidPublicKey: Der öffentliche Schlüssel ist ungültig. Muss ein PEM-kodierter RSA- oder ECDSA-öffentlicher Schlüssel im PKCS#8-Format sein
Execution:
ConditionInvalid: Die Ausführungsbedingung ist ungültig
Invalid: Die Ausführung ist ungültig
@@ -583,6 +587,7 @@ Errors:
NoTargets: Keine Ziele definiert
Failed: Ausführung fehlgeschlagen
ResponseIsNotValidJSON: Antwort ist kein gültiges JSON
MissingEncryptionKey: Fehlender Verschlüsselungsschlüssel für die Ausführung
UserSchema:
NotEnabled: Funktion Benutzerschema ist nicht aktiviert
Type:
+5
View File
@@ -576,6 +576,10 @@ Errors:
NoTimeout: Target has no timeout
InvalidURL: Target has an invalid URL
NotFound: Target not found
InvalidExpirationDate: Key expiration date must be in the future
PublicKeyExpired: Target public key is expired
PublicKeyActive: Cannot delete active target public key
InvalidPublicKey: The public key is invalid. Must be a PEM encoded RSA or ECDSA public key in PKCS#8 format
Execution:
ConditionInvalid: Execution condition is invalid
Invalid: Execution is invalid
@@ -584,6 +588,7 @@ Errors:
NoTargets: No targets defined
Failed: Execution failed
ResponseIsNotValidJSON: Response is not valid JSON
MissingEncryptionKey: No encryption key found for target
UserSchema:
NotEnabled: Feature "User Schema" is not enabled
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: El objetivo no tiene tiempo de espera
InvalidURL: El objetivo tiene una URL no válida
NotFound: El objetivo no encontrado
InvalidExpirationDate: La fecha de expiración de la clave debe estar en el futuro
PublicKeyExpired: La clave pública del destino ha expirado
PublicKeyActive: No se puede eliminar una clave pública activa del destino
InvalidPublicKey: La clave pública no es válida. Debe ser una clave pública RSA o ECDSA codificada en PEM en formato PKCS#8
Execution:
ConditionInvalid: La condición de ejecución no es válida
Invalid: La ejecución no es válida
@@ -583,6 +587,7 @@ Errors:
NoTargets: No hay objetivos definidos
Failed: Ejecución fallida
ResponseIsNotValidJSON: La respuesta no es un JSON válido
MissingEncryptionKey: Falta la clave de cifrado para la ejecución
UserSchema:
NotEnabled: La función "Esquema de usuario" no está habilitada
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: La cible n'a pas de délai d'attente
InvalidURL: La cible a une URL non valide
NotFound: La cible introuvable
InvalidExpirationDate: La date d'expiration de la clé doit être dans le futur
PublicKeyExpired: La clé publique de la cible a expiré
PublicKeyActive: Impossible de supprimer une clé publique active de la cible
InvalidPublicKey: La clé publique est invalide. Elle doit être une clé publique RSA ou ECDSA encodée PEM au format PKCS#8
Execution:
ConditionInvalid: La condition d'exécution n'est pas valide
Invalid: L'exécution est invalide
@@ -583,6 +587,7 @@ Errors:
NoTargets: Aucune cible définie
Failed: Exécution échouée
ResponseIsNotValidJSON: La réponse n'est pas un JSON valide
MissingEncryptionKey: Clé de chiffrement manquante pour l'exécution
UserSchema:
NotEnabled: La fonctionnalité "Schéma utilisateur" n'est pas activée
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: A célnak nincs időkorlátja
InvalidURL: A cél érvénytelen URL-t tartalmaz
NotFound: Cél nem található
InvalidExpirationDate: A kulcs lejárati dátumának a jövőben kell lennie
PublicKeyExpired: A cél nyilvános kulcsa lejárt
PublicKeyActive: Nem törölhető az aktív cél nyilvános kulcs
InvalidPublicKey: A nyilvános kulcs érvénytelen. PEM-kódolt RSA vagy ECDSA nyilvános kulcsnak kell lennie PKCS#8 formátumban
Execution:
ConditionInvalid: Végrehajtási feltétel érvénytelen
Invalid: A végrehajtás érvénytelen
@@ -583,6 +587,7 @@ Errors:
NoTargets: Nincsenek célok meghatározva
Failed: Végrehajtás sikertelen
ResponseIsNotValidJSON: Az válasz nem érvényes JSON
MissingEncryptionKey: Hiányzik a titkosítási kulcs
UserSchema:
NotEnabled: A "User Schema" funkció nincs engedélyezve
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: Target tidak memiliki batas waktu
InvalidURL: Target memiliki URL yang tidak valid
NotFound: Sasaran tidak ditemukan
InvalidExpirationDate: Tanggal kadaluwarsa kunci harus di masa depan
PublicKeyExpired: Kunci publik target telah kedaluwarsa
PublicKeyActive: Tidak dapat menghapus kunci publik target yang aktif
InvalidPublicKey: Kunci publik tidak valid. Harus merupakan kunci publik RSA atau ECDSA yang dikodekan PEM dalam format PKCS#8
Execution:
ConditionInvalid: Kondisi eksekusi tidak valid
Invalid: Eksekusi tidak valid
@@ -583,6 +587,7 @@ Errors:
NoTargets: Tidak ada target yang ditentukan
Failed: Eksekusi gagal
ResponseIsNotValidJSON: Responsnya bukan JSON yang valid
MissingEncryptionKey: Kunci enkripsi hilang
UserSchema:
NotEnabled: Fitur "Skema Pengguna" tidak diaktifkan
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: Il target non ha timeout
InvalidURL: La destinazione ha un URL non valido
NotFound: Obiettivo non trovato
InvalidExpirationDate: La data di scadenza della chiave deve essere nel futuro
PublicKeyExpired: La chiave pubblica dell'obiettivo è scaduta
PublicKeyActive: Impossibile eliminare la chiave pubblica dell'obiettivo attivo
InvalidPublicKey: La chiave pubblica non è valida. Deve essere una chiave pubblica RSA o ECDSA codificata PEM in formato PKCS#8
Execution:
ConditionInvalid: La condizione di esecuzione non è valida
Invalid: L'esecuzione non è valida
@@ -583,6 +587,7 @@ Errors:
NoTargets: Nessun obiettivo definito
Failed: Esecuzione fallita
ResponseIsNotValidJSON: La risposta non è un JSON valido
MissingEncryptionKey: Chiave di crittografia mancante per l'esecuzione
UserSchema:
NotEnabled: La funzionalità "Schema utente" non è abilitata
Type:
+5
View File
@@ -576,6 +576,10 @@ Errors:
NoTimeout: ターゲットにはタイムアウトがありません
InvalidURL: ターゲットに無効な URL があります
NotFound: ターゲットが見つかりません
InvalidExpirationDate: キーの有効期限は将来の日付でなければなりません
PublicKeyExpired: 対象の公開鍵は期限切れです
PublicKeyActive: アクティブな対象の公開鍵は削除できません
InvalidPublicKey: 公開鍵が無効です。PKCS#8形式のPEMエンコードされたRSAまたはECDSA公開鍵である必要があります
Execution:
ConditionInvalid: 実行条件が不正です
Invalid: 実行は無効です
@@ -584,6 +588,7 @@ Errors:
NoTargets: ターゲットが定義されていません
Failed: 実行に失敗しました
ResponseIsNotValidJSON: 応答は有効な JSON ではありません
MissingEncryptionKey: 暗号化キーがありません
UserSchema:
NotEnabled: 機能「ユーザースキーマ」が有効になっていません
Type:
+5
View File
@@ -576,6 +576,10 @@ Errors:
NoTimeout: 대상에 타임아웃이 없습니다
InvalidURL: 대상 URL이 유효하지 않습니다
NotFound: 대상을 찾을 수 없습니다
InvalidExpirationDate: 키 만료 날짜는 미래여야 합니다
PublicKeyExpired: 대상 공개키가 만료되었습니다
PublicKeyActive: 활성 대상 공개키는 삭제할 수 없습니다
InvalidPublicKey: 공개키가 유효하지 않습니다. PKCS#8 형식의 PEM 인코딩된 RSA 또는 ECDSA 공개키여야 합니다
Execution:
ConditionInvalid: 실행 조건이 유효하지 않습니다
Invalid: 실행이 유효하지 않습니다
@@ -584,6 +588,7 @@ Errors:
NoTargets: 정의된 대상이 없습니다
Failed: 실행 실패
ResponseIsNotValidJSON: 응답이 유효한 JSON이 아닙니다
MissingEncryptionKey: 암호화 키가 누락되었습니다
UserSchema:
NotEnabled: "\"사용자 스키마\" 기능이 활성화되지 않았습니다"
Type:
+5
View File
@@ -574,6 +574,10 @@ Errors:
NoTimeout: Целта нема тајмаут
InvalidURL: Целта има неважечка URL-адреса
NotFound: Целта не е пронајдена
InvalidExpirationDate: Датумот на истекување на клучот мора да е во иднината
PublicKeyExpired: Јавниот клуч на целта е истечен
PublicKeyActive: Не може да се избрише активниот јавен клуч на целта
InvalidPublicKey: Јавниот клуч е неважечок. Мора да биде PEM-кодиран RSA или ECDSA јавен клуч во PKCS#8 формат
Execution:
ConditionInvalid: Условот за извршување е неважечки
Invalid: Извршувањето е неважечко
@@ -582,6 +586,7 @@ Errors:
NoTargets: Не се дефинирани цели
Failed: Извршувањето не успеа
ResponseIsNotValidJSON: Одговорот не е валиден JSON
MissingEncryptionKey: Недостасува клуч за шифрирање
UserSchema:
NotEnabled: Функцијата „Корисничка шема“ не е овозможена
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: Doel heeft geen time-out
InvalidURL: Doel heeft een ongeldige URL
NotFound: Doel niet gevonden
InvalidExpirationDate: De vervaldatum van de sleutel moet in de toekomst liggen
PublicKeyExpired: Doelpublieke sleutel is verlopen
PublicKeyActive: Actieve doelpublieke sleutel kan niet worden verwijderd
InvalidPublicKey: De openbare sleutel is ongeldig. Moet een PEM-gecodeerde RSA- of ECDSA\-openbare sleutel in PKCS#8\-formaat zijn
Execution:
ConditionInvalid: Uitvoeringsvoorwaarde is ongeldig
Invalid: Uitvoering is ongeldig
@@ -583,6 +587,7 @@ Errors:
NoTargets: Geen doelstellingen gedefinieerd
Failed: Uitvoering mislukt
ResponseIsNotValidJSON: Reactie is geen geldige JSON
MissingEncryptionKey: Ontbrekende encryptiesleutel voor uitvoering
UserSchema:
NotEnabled: Functie "Gebruikersschema" is niet ingeschakeld
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: Cel nie ma limitu czasu
InvalidURL: Cel ma nieprawidłowy adres URL
NotFound: Nie znaleziono celu
InvalidExpirationDate: Data wygaśnięcia klucza musi być w przyszłości
PublicKeyExpired: Publiczny klucz docelowy wygasł
PublicKeyActive: Nie można usunąć aktywnego publicznego klucza docelowego
InvalidPublicKey: Klucz publiczny jest nieprawidłowy. Musi być to klucz publiczny RSA lub ECDSA zakodowany w PEM w formacie PKCS#8
Execution:
ConditionInvalid: Warunek wykonania jest nieprawidłowy
Invalid: Wykonanie jest nieprawidłowe
@@ -583,6 +587,7 @@ Errors:
NoTargets: Nie zdefiniowano celów
Failed: Wykonanie nie powiodło się
ResponseIsNotValidJSON: Odpowiedź nie jest prawidłowym JSON-em
MissingEncryptionKey: Brak klucza szyfrowania dla wykonania
UserSchema:
NotEnabled: Funkcja „Schemat użytkownika” nie jest włączona
Type:
+5
View File
@@ -574,6 +574,10 @@ Errors:
NoTimeout: O destino não tem tempo limite
InvalidURL: O destino tem um URL inválido
NotFound: Destino não encontrado
InvalidExpirationDate: A data de expiração da chave deve estar no futuro
PublicKeyExpired: A chave pública do destino expirou
PublicKeyActive: Não é possível apagar a chave pública ativa do destino
InvalidPublicKey: A chave pública é inválida. Deve ser uma chave pública RSA ou ECDSA codificada em PEM no formato PKCS#8
Execution:
ConditionInvalid: A condição de execução é inválida
Invalid: A execução é inválida
@@ -582,6 +586,7 @@ Errors:
NoTargets: Nenhuma meta definida
Failed: Falha na execução
ResponseIsNotValidJSON: A resposta não é um JSON válido
MissingEncryptionKey: Chave de criptografia ausente
UserSchema:
NotEnabled: O recurso "Esquema do usuário" não está habilitado
Type:
+5
View File
@@ -571,6 +571,10 @@ Errors:
NoTimeout: Ținta nu are timp de așteptare
InvalidURL: Ținta are un URL invalid
NotFound: Ținta nu a fost găsită
InvalidExpirationDate: Data de expirare a cheii trebuie să fie în viitor
PublicKeyExpired: Cheia publică a destinației a expirat
PublicKeyActive: Nu se poate șterge cheia publică activă a destinației
InvalidPublicKey: Cheia publică este invalidă. Trebuie să fie o cheie publică RSA sau ECDSA codificată PEM în format PKCS#8
Execution:
ConditionInvalid: Condiția de execuție este invalidă
Invalid: Execuția este invalidă
@@ -579,6 +583,7 @@ Errors:
NoTargets: Nu sunt definite ținte
Failed: Execuția a eșuat
ResponseIsNotValidJSON: Răspunsul nu este un JSON valid
MissingEncryptionKey: Lipsește cheia de criptare pentru execuție
UserSchema:
NotEnabled: Caracteristica "Schema de utilizator" nu este activată
Type:
+5
View File
@@ -564,6 +564,10 @@ Errors:
NoTimeout: У цели нет тайм-аута
InvalidURL: Цель имеет неверный URL-адрес
NotFound: Цель не найдена
InvalidExpirationDate: Дата истечения срока действия ключа должна быть в будущем
PublicKeyExpired: Публичный ключ цели просрочен
PublicKeyActive: Невозможно удалить активный публичный ключ цели
InvalidPublicKey: Публичный ключ недействителен. Должен быть PEM-кодированный RSA или ECDSA публичный ключ в формате PKCS#8
Execution:
ConditionInvalid: Недопустимое условие выполнения
Invalid: Исполнение недействительно
@@ -572,6 +576,7 @@ Errors:
NoTargets: Цели не определены
Failed: Выполнение не удалось
ResponseIsNotValidJSON: Ответ не является допустимым JSON
MissingEncryptionKey: Отсутствует ключ шифрования
UserSchema:
NotEnabled: Функция «Пользовательская схема» не включена
Type:
+5
View File
@@ -575,6 +575,10 @@ Errors:
NoTimeout: Målet har ingen timeout
InvalidURL: Målet har en ogiltig URL
NotFound: Målet hittades inte
InvalidExpirationDate: Nyckelns utgångsdatum måste vara i framtiden
PublicKeyExpired: Målets publika nyckel har gått ut
PublicKeyActive: Kan inte ta bort en aktiv publik nyckel för målet
InvalidPublicKey: Den publika nyckeln är ogiltig. Måste vara en PEM-kodad RSA- eller ECDSA-publik nyckel i PKCS#8-format
Execution:
ConditionInvalid: Exekveringsvillkoret är ogiltigt
Invalid: Exekveringen är ogiltig
@@ -583,6 +587,7 @@ Errors:
NoTargets: Inga mål definierade
Failed: Utförande misslyckades
ResponseIsNotValidJSON: Svaret är inte giltigt JSON
MissingEncryptionKey: Krypteringsnyckel saknas för exekvering
UserSchema:
NotEnabled: Funktionen "Användarschema" är inte aktiverad
Type:
+5
View File
@@ -576,6 +576,10 @@ Errors:
NoTimeout: Hedefin zaman aşımı yok
InvalidURL: Hedefin geçersiz URL'si var
NotFound: Hedef bulunamadı
InvalidExpirationDate: Anahtarın sona erme tarihi gelecekte olmalıdır
PublicKeyExpired: Hedefin açık anahtarı süresi doldu
PublicKeyActive: Etkin hedef açık anahtarı silinemez
InvalidPublicKey: Açık anahtar geçersiz. PEM kodlu PKCS#8 formatında RSA veya ECDSA açık anahtarı olmalıdır
Execution:
ConditionInvalid: Yürütme koşulu geçersiz
Invalid: Yürütme geçersiz
@@ -584,6 +588,7 @@ Errors:
NoTargets: Hedef tanımlanmamış
Failed: Yürütme başarısız
ResponseIsNotValidJSON: Yanıt geçerli JSON değil
MissingEncryptionKey: Şifreleme anahtarı eksik
UserSchema:
NotEnabled: '"User Schema" özelliği etkin değil'
Type:
+5
View File
@@ -570,6 +570,10 @@ Errors:
NoTimeout: Ціль не має часу очікування
InvalidURL: Ціль має недійсний URL
NotFound: Ціль не знайдена
InvalidExpirationDate: Дата закінчення терміну дії ключа має бути в майбутньому
PublicKeyExpired: Публічний ключ цілі прострочено
PublicKeyActive: Неможливо видалити активний публічний ключ цілі
InvalidPublicKey: Публічний ключ недійсний. Має бути PEM-кодований RSA або ECDSA публічний ключ у форматі PKCS#8
Execution:
ConditionInvalid: Умова виконання недійсна
Invalid: Виконання недійсне
@@ -578,6 +582,7 @@ Errors:
NoTargets: Не визначено цілей
Failed: Виконання не вдалося
ResponseIsNotValidJSON: Відповідь не є дійсним JSON
MissingEncryptionKey: Відсутній ключ шифрування для виконання
UserSchema:
NotEnabled: Функція "Схема користувача" не увімкнена
Type:
+5
View File
@@ -576,6 +576,10 @@ Errors:
NoTimeout: 目标没有超时
InvalidURL: 目标的 URL 无效
NotFound: 未找到目标
InvalidExpirationDate: 密钥的到期日期必须是将来的时间
PublicKeyExpired: 目标公钥已过期
PublicKeyActive: 无法删除处于活动状态的目标公钥
InvalidPublicKey: 公钥无效。必须是 PEM 编码的 RSA 或 ECDSA 公钥,格式为 PKCS#8
Execution:
ConditionInvalid: 执行条件无效
Invalid: 执行无效
@@ -584,6 +588,7 @@ Errors:
NoTargets: 没有定义目标
Failed: 执行失败
ResponseIsNotValidJSON: 响应不是有效的 JSON
MissingEncryptionKey: 缺少加密密钥
UserSchema:
NotEnabled: 未启用“用户架构”功能
Type: