code
stringlengths 0
56.1M
| repo_name
stringclasses 515
values | path
stringlengths 2
147
| language
stringclasses 447
values | license
stringclasses 7
values | size
int64 0
56.8M
|
---|---|---|---|---|---|
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sqlite
import (
"fmt"
"time"
"github.com/microsoft/durabletask-go/backend/sqlite"
kitmd "github.com/dapr/kit/metadata"
)
type sqliteMetadata struct {
sqlite.SqliteOptions
}
func (m *sqliteMetadata) Parse(meta map[string]string) error {
// Reset to default values
m.reset()
err := kitmd.DecodeMetadata(meta, &m.SqliteOptions)
if err != nil {
return fmt.Errorf("failed to decode metadata: %w", err)
}
return nil
}
func (m *sqliteMetadata) reset() {
m.FilePath = ""
m.OrchestrationLockTimeout = 2 * time.Minute
m.ActivityLockTimeout = 2 * time.Minute
}
|
mikeee/dapr
|
pkg/runtime/wfengine/backends/sqlite/metadata.go
|
GO
|
mit
| 1,143 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package wfengine
import (
"context"
"errors"
"fmt"
"time"
"github.com/microsoft/durabletask-go/api"
"github.com/microsoft/durabletask-go/backend"
"github.com/dapr/components-contrib/workflows"
"github.com/dapr/kit/logger"
)
// Status values are defined at: https://github.com/microsoft/durabletask-go/blob/119b361079c45e368f83b223888d56a436ac59b9/internal/protos/orchestrator_service.pb.go#L42-L64
var statusMap = map[int32]string{
0: "RUNNING",
1: "COMPLETED",
2: "CONTINUED_AS_NEW",
3: "FAILED",
4: "CANCELED",
5: "TERMINATED",
6: "PENDING",
7: "SUSPENDED",
}
func BuiltinWorkflowFactory(engine *WorkflowEngine) func(logger.Logger) workflows.Workflow {
return func(logger logger.Logger) workflows.Workflow {
return &workflowEngineComponent{
logger: logger,
client: backend.NewTaskHubClient(engine.Backend),
}
}
}
type workflowEngineComponent struct {
logger logger.Logger
client backend.TaskHubClient
}
func (c *workflowEngineComponent) Init(metadata workflows.Metadata) error {
c.logger.Info("Initializing Dapr workflow component")
return nil
}
func (c *workflowEngineComponent) Start(ctx context.Context, req *workflows.StartRequest) (*workflows.StartResponse, error) {
if req.WorkflowName == "" {
return nil, errors.New("a workflow name is required")
}
// Init with capacity of 3 as worst-case scenario
opts := make([]api.NewOrchestrationOptions, 0, 3)
// Specifying the ID is optional - if not specified, a random ID will be generated by the client.
if req.InstanceID != "" {
opts = append(opts, api.WithInstanceID(api.InstanceID(req.InstanceID)))
}
// Input is also optional. However, inputs are expected to be unprocessed string values (e.g. JSON text)
if len(req.WorkflowInput) > 0 {
opts = append(opts, api.WithRawInput(string(req.WorkflowInput)))
}
// Start time is also optional and must be in the RFC3339 format (e.g. 2009-11-10T23:00:00Z).
if req.Options != nil {
if startTimeRFC3339, ok := req.Options["dapr.workflow.start_time"]; ok {
if startTime, err := time.Parse(time.RFC3339, startTimeRFC3339); err != nil {
return nil, errors.New(`start times must be in RFC3339 format (e.g. "2009-11-10T23:00:00Z")`)
} else {
opts = append(opts, api.WithStartTime(startTime))
}
}
}
workflowID, err := c.client.ScheduleNewOrchestration(ctx, req.WorkflowName, opts...)
if err != nil {
return nil, fmt.Errorf("unable to start workflow: %w", err)
}
c.logger.Debugf("Created new workflow '%s' instance with ID '%s'", req.WorkflowName, workflowID)
res := &workflows.StartResponse{
InstanceID: string(workflowID),
}
return res, nil
}
func (c *workflowEngineComponent) Terminate(ctx context.Context, req *workflows.TerminateRequest) error {
if req.InstanceID == "" {
return errors.New("a workflow instance ID is required")
}
if err := c.client.TerminateOrchestration(ctx, api.InstanceID(req.InstanceID), api.WithRecursiveTerminate(req.Recursive)); err != nil {
if errors.Is(err, api.ErrInstanceNotFound) {
c.logger.Infof("No such instance exists: '%s'", req.InstanceID)
return err
}
return fmt.Errorf("failed to terminate workflow %s: %w", req.InstanceID, err)
}
c.logger.Debugf("Scheduled termination for workflow instance '%s'", req.InstanceID)
return nil
}
func (c *workflowEngineComponent) Purge(ctx context.Context, req *workflows.PurgeRequest) error {
if req.InstanceID == "" {
return errors.New("a workflow instance ID is required")
}
if err := c.client.PurgeOrchestrationState(ctx, api.InstanceID(req.InstanceID), api.WithRecursivePurge(req.Recursive)); err != nil {
if errors.Is(err, api.ErrInstanceNotFound) {
c.logger.Warnf("Unable to purge the instance: '%s', no such instance exists", req.InstanceID)
return err
}
return fmt.Errorf("failed to Purge workflow %s: %w", req.InstanceID, err)
}
c.logger.Debugf("Purging workflow instance '%s'", req.InstanceID)
return nil
}
func (c *workflowEngineComponent) RaiseEvent(ctx context.Context, req *workflows.RaiseEventRequest) error {
if req.InstanceID == "" {
return errors.New("a workflow instance ID is required")
}
if req.EventName == "" {
return errors.New("an event name is required")
}
// Input is also optional. However, inputs are expected to be unprocessed string values (e.g. JSON text)
var opts []api.RaiseEventOptions
if len(req.EventData) > 0 {
opts = append(opts, api.WithRawEventData(string(req.EventData)))
}
if err := c.client.RaiseEvent(ctx, api.InstanceID(req.InstanceID), req.EventName, opts...); err != nil {
return fmt.Errorf("failed to raise event %s on workflow %s: %w", req.EventName, req.InstanceID, err)
}
c.logger.Debugf("Raised event %s on workflow instance '%s'", req.EventName, req.InstanceID)
return nil
}
func (c *workflowEngineComponent) Get(ctx context.Context, req *workflows.GetRequest) (*workflows.StateResponse, error) {
if req.InstanceID == "" {
return nil, errors.New("a workflow instance ID is required")
}
metadata, err := c.client.FetchOrchestrationMetadata(ctx, api.InstanceID(req.InstanceID))
if err != nil {
if errors.Is(err, api.ErrInstanceNotFound) {
c.logger.Errorf("Unable to get data on the instance: %s, no such instance exists", req.InstanceID)
return nil, err
}
return nil, fmt.Errorf("failed to get workflow metadata for '%s': %w", req.InstanceID, err)
}
res := &workflows.StateResponse{
Workflow: &workflows.WorkflowState{
InstanceID: req.InstanceID,
WorkflowName: metadata.Name,
CreatedAt: metadata.CreatedAt,
LastUpdatedAt: metadata.LastUpdatedAt,
RuntimeStatus: getStatusString(int32(metadata.RuntimeStatus)),
Properties: map[string]string{
"dapr.workflow.input": metadata.SerializedInput,
"dapr.workflow.custom_status": metadata.SerializedCustomStatus,
},
},
}
// Status-specific fields
if metadata.FailureDetails != nil {
res.Workflow.Properties["dapr.workflow.failure.error_type"] = metadata.FailureDetails.GetErrorType()
res.Workflow.Properties["dapr.workflow.failure.error_message"] = metadata.FailureDetails.GetErrorMessage()
} else if metadata.IsComplete() {
res.Workflow.Properties["dapr.workflow.output"] = metadata.SerializedOutput
}
return res, nil
}
func (c *workflowEngineComponent) Pause(ctx context.Context, req *workflows.PauseRequest) error {
if req.InstanceID == "" {
return errors.New("a workflow instance ID is required")
}
if err := c.client.SuspendOrchestration(ctx, api.InstanceID(req.InstanceID), ""); err != nil {
return fmt.Errorf("failed to pause workflow %s: %w", req.InstanceID, err)
}
c.logger.Debugf("Pausing workflow instance '%s'", req.InstanceID)
return nil
}
func (c *workflowEngineComponent) Resume(ctx context.Context, req *workflows.ResumeRequest) error {
if req.InstanceID == "" {
return errors.New("a workflow instance ID is required")
}
if err := c.client.ResumeOrchestration(ctx, api.InstanceID(req.InstanceID), ""); err != nil {
return fmt.Errorf("failed to resume workflow %s: %w", req.InstanceID, err)
}
c.logger.Debugf("Resuming workflow instance '%s'", req.InstanceID)
return nil
}
func (c *workflowEngineComponent) PurgeWorkflow(ctx context.Context, req *workflows.PurgeRequest) error {
if req.InstanceID == "" {
return errors.New("a workflow instance ID is required")
}
if err := c.client.PurgeOrchestrationState(ctx, api.InstanceID(req.InstanceID)); err != nil {
if errors.Is(err, api.ErrInstanceNotFound) {
c.logger.Warnf("The requested instance: '%s' does not exist or has already been purged", req.InstanceID)
return err
}
return fmt.Errorf("failed to purge workflow %s: %w", req.InstanceID, err)
}
c.logger.Debugf("Purging workflow instance '%s'", req.InstanceID)
return nil
}
func getStatusString(status int32) string {
if statusStr, ok := statusMap[status]; ok {
return statusStr
}
return "UNKNOWN"
}
|
mikeee/dapr
|
pkg/runtime/wfengine/component.go
|
GO
|
mit
| 8,439 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package wfengine
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/microsoft/durabletask-go/backend"
"google.golang.org/grpc"
"github.com/dapr/dapr/pkg/components/wfbackend"
"github.com/dapr/dapr/pkg/config"
"github.com/dapr/dapr/pkg/runtime/processor"
actorsbe "github.com/dapr/dapr/pkg/runtime/wfengine/backends/actors"
"github.com/dapr/kit/logger"
)
type WorkflowEngine struct {
IsRunning bool
Backend backend.Backend
executor backend.Executor
worker backend.TaskHubWorker
registerGrpcServerFn func(grpcServer grpc.ServiceRegistrar)
startMutex sync.Mutex
disconnectChan chan any
spec config.WorkflowSpec
wfEngineReady atomic.Bool
wfEngineReadyCh chan struct{}
}
var (
wfLogger = logger.NewLogger("dapr.runtime.wfengine")
wfBackendLogger = logger.NewLogger("wfengine.durabletask.backend")
)
func IsWorkflowRequest(path string) bool {
return backend.IsDurableTaskGrpcRequest(path)
}
func NewWorkflowEngine(appID string, spec config.WorkflowSpec, backendManager processor.WorkflowBackendManager) *WorkflowEngine {
engine := &WorkflowEngine{
spec: spec,
wfEngineReadyCh: make(chan struct{}),
}
var ok bool
if backendManager != nil {
engine.Backend, ok = backendManager.Backend()
}
if !ok {
// If no backend was initialized by the manager, create a backend backed by actors
var err error
engine.Backend, err = actorsbe.NewActorBackend(wfbackend.Metadata{
AppID: appID,
}, nil)
if err != nil {
// Should never happen
wfLogger.Errorf("Failed to initialize actors backend for workflow: %v", err)
}
}
return engine
}
func (wfe *WorkflowEngine) RegisterGrpcServer(grpcServer *grpc.Server) {
wfe.registerGrpcServerFn(grpcServer)
}
func (wfe *WorkflowEngine) ConfigureGrpcExecutor() {
// Enable lazy auto-starting the worker only when a workflow app connects to fetch work items.
autoStartCallback := backend.WithOnGetWorkItemsConnectionCallback(func(ctx context.Context) error {
// NOTE: We don't propagate the context here because that would cause the engine to shut
// down when the client disconnects and cancels the passed-in context. Once it starts
// up, we want to keep the engine running until the runtime shuts down.
if err := wfe.Start(context.Background()); err != nil {
// This can happen if the workflow app connects before the sidecar has finished initializing.
// The client app is expected to continuously retry until successful.
return fmt.Errorf("failed to auto-start the workflow engine: %w", err)
}
return nil
})
// Create a channel that can be used to disconnect the remote client during shutdown.
wfe.disconnectChan = make(chan any, 1)
disconnectHelper := backend.WithStreamShutdownChannel(wfe.disconnectChan)
wfe.executor, wfe.registerGrpcServerFn = backend.NewGrpcExecutor(wfe.Backend, wfLogger, autoStartCallback, disconnectHelper)
}
// SetExecutor sets the executor property. This is primarily used for testing.
func (wfe *WorkflowEngine) SetExecutor(fn func(be backend.Backend) backend.Executor) {
wfe.executor = fn(wfe.Backend)
}
// SetLogLevel sets the logging level for the workflow engine.
// This function is only intended to be used for testing.
func SetLogLevel(level logger.LogLevel) {
wfLogger.SetOutputLevel(level)
wfBackendLogger.SetOutputLevel(level)
}
func (wfe *WorkflowEngine) Start(ctx context.Context) (err error) {
// Start could theoretically get called by multiple goroutines concurrently
wfe.startMutex.Lock()
defer wfe.startMutex.Unlock()
if wfe.IsRunning {
return nil
}
if wfe.executor == nil {
return errors.New("gRPC executor is not yet configured")
}
// Register actor backend if backend is actor
abe, ok := wfe.Backend.(*actorsbe.ActorBackend)
if ok {
abe.WaitForActorsReady(ctx)
abe.RegisterActor(ctx)
}
// There are separate "workers" for executing orchestrations (workflows) and activities
orchestrationWorker := backend.NewOrchestrationWorker(
wfe.Backend,
wfe.executor,
wfBackendLogger,
backend.WithMaxParallelism(wfe.spec.GetMaxConcurrentWorkflowInvocations()))
activityWorker := backend.NewActivityTaskWorker(
wfe.Backend,
wfe.executor,
wfBackendLogger,
backend.WithMaxParallelism(wfe.spec.GetMaxConcurrentActivityInvocations()))
wfe.worker = backend.NewTaskHubWorker(wfe.Backend, orchestrationWorker, activityWorker, wfBackendLogger)
// Start the Durable Task worker, which will allow workflows to be scheduled and execute.
if err := wfe.worker.Start(ctx); err != nil {
return fmt.Errorf("failed to start workflow engine: %w", err)
}
wfe.IsRunning = true
wfLogger.Info("Workflow engine started")
wfe.SetWorkflowEngineReadyDone()
return nil
}
func (wfe *WorkflowEngine) Close(ctx context.Context) error {
wfe.startMutex.Lock()
defer wfe.startMutex.Unlock()
if !wfe.IsRunning {
return nil
}
if wfe.worker != nil {
if wfe.disconnectChan != nil {
// Signals to the durabletask-go gRPC service to disconnect the app client.
// This is important to complete the graceful shutdown sequence in a timely manner.
close(wfe.disconnectChan)
}
if err := wfe.worker.Shutdown(ctx); err != nil {
return fmt.Errorf("failed to shutdown the workflow worker: %w", err)
}
wfe.IsRunning = false
wfLogger.Info("Workflow engine stopped")
}
return nil
}
// WaitForWorkflowEngineReady waits for the workflow engine to be ready.
func (wfe *WorkflowEngine) WaitForWorkflowEngineReady(ctx context.Context) {
// Quick check to avoid allocating a timer if the workflow engine is ready
if wfe.wfEngineReady.Load() {
return
}
waitCtx, waitCancel := context.WithTimeout(ctx, 10*time.Second)
defer waitCancel()
select {
case <-waitCtx.Done():
case <-wfe.wfEngineReadyCh:
}
}
func (wfe *WorkflowEngine) SetWorkflowEngineReadyDone() {
if wfe.wfEngineReady.CompareAndSwap(false, true) {
close(wfe.wfEngineReadyCh)
}
}
|
mikeee/dapr
|
pkg/runtime/wfengine/wfengine.go
|
GO
|
mit
| 6,527 |
//go:build unit
// +build unit
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// wfengine_test is a suite of integration tests that verify workflow
// engine behavior using only exported APIs.
package wfengine_test
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/microsoft/durabletask-go/api"
"github.com/microsoft/durabletask-go/backend"
"github.com/microsoft/durabletask-go/task"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"github.com/dapr/components-contrib/state"
"github.com/dapr/dapr/pkg/actors"
"github.com/dapr/dapr/pkg/config"
"github.com/dapr/dapr/pkg/resiliency"
"github.com/dapr/dapr/pkg/runtime/compstore"
"github.com/dapr/dapr/pkg/runtime/processor"
"github.com/dapr/dapr/pkg/runtime/registry"
"github.com/dapr/dapr/pkg/runtime/wfengine"
actorsbe "github.com/dapr/dapr/pkg/runtime/wfengine/backends/actors"
daprt "github.com/dapr/dapr/pkg/testing"
"github.com/dapr/kit/logger"
)
const (
testAppID = "wf-app"
workflowActorType = "dapr.internal.default.wf-app.workflow"
activityActorType = "dapr.internal.default.wf-app.activity"
)
func fakeStore() state.Store {
return daprt.NewFakeStateStore()
}
func init() {
wfengine.SetLogLevel(logger.DebugLevel)
}
// TestStartWorkflowEngine validates that starting the workflow engine returns no errors.
func TestStartWorkflowEngine(t *testing.T) {
ctx := context.Background()
engine := getEngine(t, ctx)
engine.ConfigureGrpcExecutor()
grpcServer := grpc.NewServer()
engine.RegisterGrpcServer(grpcServer)
err := engine.Start(ctx)
require.NoError(t, err)
}
// GetTestOptions returns an array of functions for configuring the workflow engine. Each
// string returned by each function can be used as the name of the test configuration.
func GetTestOptions() []func(wfe *wfengine.WorkflowEngine) string {
return []func(wfe *wfengine.WorkflowEngine) string{
func(wfe *wfengine.WorkflowEngine) string {
// caching enabled, etc.
return "default options"
},
func(wfe *wfengine.WorkflowEngine) string {
// disable caching to test recovery from failure
if abe, ok := wfe.Backend.(*actorsbe.ActorBackend); ok {
abe.DisableActorCaching(true)
return "caching disabled"
}
return ""
},
}
}
// TestEmptyWorkflow executes a no-op workflow end-to-end and verifies all workflow metadata is correctly initialized.
func TestEmptyWorkflow(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("EmptyWorkflow", func(*task.OrchestrationContext) (any, error) {
return nil, nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
preStartTime := time.Now().UTC()
id, err := client.ScheduleNewOrchestration(ctx, "EmptyWorkflow")
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.Equal(t, id, metadata.InstanceID)
assert.True(t, metadata.IsComplete())
assert.GreaterOrEqual(t, metadata.CreatedAt, preStartTime)
assert.GreaterOrEqual(t, metadata.LastUpdatedAt, metadata.CreatedAt)
assert.Empty(t, metadata.SerializedInput)
assert.Empty(t, metadata.SerializedOutput)
assert.Empty(t, metadata.SerializedCustomStatus)
assert.Nil(t, metadata.FailureDetails)
})
}
}
// TestSingleTimerWorkflow executes a workflow schedules a timer and completes, verifying that timers
// can be used to resume a workflow. This test does not attempt to verify delay accuracy.
func TestSingleTimerWorkflow(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("SingleTimer", func(ctx *task.OrchestrationContext) (any, error) {
err := ctx.CreateTimer(time.Duration(0)).Await(nil)
return nil, err
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "SingleTimer")
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.GreaterOrEqual(t, metadata.LastUpdatedAt, metadata.CreatedAt)
})
}
}
// TestSingleActivityWorkflow_ReuseInstanceIDIgnore executes a workflow twice.
// The workflow calls a single activity with orchestraion ID reuse policy.
// The reuse ID policy contains action IGNORE and target status ['RUNNING', 'COMPLETED', 'PENDING']
// The second call to create a workflow with same instance ID is expected to be ignored
// if first workflow instance is in above statuses
func TestSingleActivityWorkflow_ReuseInstanceIDIgnore(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("SingleActivity", func(ctx *task.OrchestrationContext) (any, error) {
var input string
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var output string
err := ctx.CallActivity("SayHello", task.WithActivityInput(input)).Await(&output)
return output, err
})
r.AddActivityN("SayHello", func(ctx task.ActivityContext) (any, error) {
var name string
if err := ctx.GetInput(&name); err != nil {
return nil, err
}
return fmt.Sprintf("Hello, %s!", name), nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
suffix := opt(engine)
t.Run(suffix, func(t *testing.T) {
instanceID := api.InstanceID("IGNORE_IF_RUNNING_OR_COMPLETED_" + suffix)
reuseIDPolicy := &api.OrchestrationIdReusePolicy{
Action: api.REUSE_ID_ACTION_IGNORE,
OperationStatus: []api.OrchestrationStatus{api.RUNTIME_STATUS_RUNNING, api.RUNTIME_STATUS_COMPLETED, api.RUNTIME_STATUS_PENDING},
}
// Run the orchestration
id, err := client.ScheduleNewOrchestration(ctx, "SingleActivity", api.WithInput("世界"), api.WithInstanceID(instanceID))
require.NoError(t, err)
// wait orchestration to start
client.WaitForOrchestrationStart(ctx, id)
pivotTime := time.Now()
// schedule again, it should ignore creating the new orchestration
id, err = client.ScheduleNewOrchestration(ctx, "SingleActivity", api.WithInput("World"), api.WithInstanceID(id), api.WithOrchestrationIdReusePolicy(reuseIDPolicy))
require.NoError(t, err)
timeoutCtx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)
defer cancelTimeout()
metadata, err := client.WaitForOrchestrationCompletion(timeoutCtx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
// the first orchestration should complete as the second one is ignored
assert.Equal(t, `"Hello, 世界!"`, metadata.SerializedOutput)
// assert the orchestration created timestamp
assert.True(t, pivotTime.After(metadata.CreatedAt))
})
}
}
// TestSingleActivityWorkflow_ReuseInstanceIDIgnore executes a workflow twice.
// The workflow calls a single activity with orchestraion ID reuse policy.
// The reuse ID policy contains action TERMINATE and target status ['RUNNING', 'COMPLETED', 'PENDING']
// The second call to create a workflow with same instance ID is expected to terminate
// the first workflow instance and create a new workflow instance if it's status is in target statuses
func TestSingleActivityWorkflow_ReuseInstanceIDTerminate(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("SingleActivity", func(ctx *task.OrchestrationContext) (any, error) {
var input string
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var output string
err := ctx.CallActivity("SayHello", task.WithActivityInput(input)).Await(&output)
return output, err
})
r.AddActivityN("SayHello", func(ctx task.ActivityContext) (any, error) {
var name string
if err := ctx.GetInput(&name); err != nil {
return nil, err
}
return fmt.Sprintf("Hello, %s!", name), nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
suffix := opt(engine)
t.Run(suffix, func(t *testing.T) {
instanceID := api.InstanceID("IGNORE_IF_RUNNING_OR_COMPLETED_" + suffix)
reuseIDPolicy := &api.OrchestrationIdReusePolicy{
Action: api.REUSE_ID_ACTION_TERMINATE,
OperationStatus: []api.OrchestrationStatus{api.RUNTIME_STATUS_RUNNING, api.RUNTIME_STATUS_COMPLETED, api.RUNTIME_STATUS_PENDING},
}
// Run the orchestration
id, err := client.ScheduleNewOrchestration(ctx, "SingleActivity", api.WithInput("世界"), api.WithInstanceID(instanceID))
require.NoError(t, err)
// wait orchestration to start
client.WaitForOrchestrationStart(ctx, id)
pivotTime := time.Now()
// schedule again, it should ignore creating the new orchestration
id, err = client.ScheduleNewOrchestration(ctx, "SingleActivity", api.WithInput("World"), api.WithInstanceID(id), api.WithOrchestrationIdReusePolicy(reuseIDPolicy))
require.NoError(t, err)
timeoutCtx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)
defer cancelTimeout()
metadata, err := client.WaitForOrchestrationCompletion(timeoutCtx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
// the first orchestration should complete as the second one is ignored
assert.Equal(t, `"Hello, World!"`, metadata.SerializedOutput)
// assert the orchestration created timestamp
assert.False(t, pivotTime.After(metadata.CreatedAt))
})
}
}
// TestSingleActivityWorkflow_ReuseInstanceIDIgnore executes a workflow twice.
// The workflow calls a single activity with orchestraion ID reuse policy.
// The reuse ID policy contains default action Error and empty target status
// The second call to create a workflow with same instance ID is expected to error out
// the first workflow instance is not completed.
func TestSingleActivityWorkflow_ReuseInstanceIDError(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("SingleActivity", func(ctx *task.OrchestrationContext) (any, error) {
var input string
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var output string
err := ctx.CallActivity("SayHello", task.WithActivityInput(input)).Await(&output)
return output, err
})
r.AddActivityN("SayHello", func(ctx task.ActivityContext) (any, error) {
var name string
if err := ctx.GetInput(&name); err != nil {
return nil, err
}
return fmt.Sprintf("Hello, %s!", name), nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
suffix := opt(engine)
t.Run(suffix, func(t *testing.T) {
instanceID := api.InstanceID("IGNORE_IF_RUNNING_OR_COMPLETED_" + suffix)
id, err := client.ScheduleNewOrchestration(ctx, "SingleActivity", api.WithInput("世界"), api.WithInstanceID(instanceID))
require.NoError(t, err)
_, err = client.ScheduleNewOrchestration(ctx, "SingleActivity", api.WithInput("World"), api.WithInstanceID(id))
require.Error(t, err)
assert.Contains(t, err.Error(), "already exists")
})
}
}
// TestActivityChainingWorkflow verifies that a workflow can call multiple activities in a sequence,
// passing the output of the previous activity as the input of the next activity.
func TestActivityChainingWorkflow(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("ActivityChain", func(ctx *task.OrchestrationContext) (any, error) {
val := 0
for i := 0; i < 10; i++ {
if err := ctx.CallActivity("PlusOne", task.WithActivityInput(val)).Await(&val); err != nil {
return nil, err
}
}
return val, nil
})
r.AddActivityN("PlusOne", func(ctx task.ActivityContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
return input + 1, nil
})
ctx := context.Background()
client, engine, _ := startEngineAndGetStore(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "ActivityChain")
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `10`, metadata.SerializedOutput)
})
}
}
// TestConcurrentActivityExecution verifies that a workflow can execute multiple activities in parallel
// and wait for all of them to complete before completing itself.
func TestConcurrentActivityExecution(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("ActivityFanOut", func(ctx *task.OrchestrationContext) (any, error) {
tasks := []task.Task{}
for i := 0; i < 10; i++ {
tasks = append(tasks, ctx.CallActivity("ToString", task.WithActivityInput(i)))
}
results := []string{}
for _, t := range tasks {
var result string
if err := t.Await(&result); err != nil {
return nil, err
}
results = append(results, result)
}
sort.Sort(sort.Reverse(sort.StringSlice(results)))
return results, nil
})
r.AddActivityN("ToString", func(ctx task.ActivityContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
// Sleep for 1 second to ensure that the test passes only if all activities execute in parallel.
time.Sleep(1 * time.Second)
return strconv.Itoa(input), nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "ActivityFanOut")
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `["9","8","7","6","5","4","3","2","1","0"]`, metadata.SerializedOutput)
// Because all the activities run in parallel, they should complete very quickly
assert.Less(t, metadata.LastUpdatedAt.Sub(metadata.CreatedAt), 3*time.Second)
})
}
}
// TestChildWorkflow creates a workflow that calls a child workflow and verifies that the child workflow
// completes successfully.
func TestChildWorkflow(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("root", func(ctx *task.OrchestrationContext) (any, error) {
var input string
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var output string
err := ctx.CallSubOrchestrator("child", task.WithSubOrchestratorInput(input)).Await(&output)
return output, err
})
r.AddOrchestratorN("child", func(ctx *task.OrchestrationContext) (any, error) {
var name string
if err := ctx.GetInput(&name); err != nil {
return nil, err
}
return fmt.Sprintf("Hello, %s!", name), nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
// Run the root orchestration
id, err := client.ScheduleNewOrchestration(ctx, "root", api.WithInput("世界"))
require.NoError(t, err)
timeoutCtx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)
defer cancelTimeout()
metadata, err := client.WaitForOrchestrationCompletion(timeoutCtx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `"Hello, 世界!"`, metadata.SerializedOutput)
})
}
}
// TestContinueAsNewWorkflow verifies that a workflow can "continue-as-new" to restart itself with a new input.
func TestContinueAsNewWorkflow(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("ContinueAsNewTest", func(ctx *task.OrchestrationContext) (any, error) {
var input int32
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
if input < 10 {
if err := ctx.CreateTimer(0).Await(nil); err != nil {
return nil, err
}
var nextInput int32
if err := ctx.CallActivity("PlusOne", task.WithActivityInput(input)).Await(&nextInput); err != nil {
return nil, err
}
ctx.ContinueAsNew(nextInput)
}
return input, nil
})
r.AddActivityN("PlusOne", func(ctx task.ActivityContext) (any, error) {
var input int32
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
return input + 1, nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "ContinueAsNewTest", api.WithInput(0))
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `10`, metadata.SerializedOutput)
})
}
}
// TestRecreateCompletedWorkflow verifies that completed workflows can be restarted with new inputs externally.
func TestRecreateCompletedWorkflow(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("EchoWorkflow", func(ctx *task.OrchestrationContext) (any, error) {
var input any
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
return input, nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
// First workflow
var metadata *api.OrchestrationMetadata
id, err := client.ScheduleNewOrchestration(ctx, "EchoWorkflow", api.WithInput("echo!"))
require.NoError(t, err)
metadata, err = client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `"echo!"`, metadata.SerializedOutput)
// Second workflow, using the same ID as the first but a different input
_, err = client.ScheduleNewOrchestration(ctx, "EchoWorkflow", api.WithInstanceID(id), api.WithInput(42))
require.NoError(t, err)
metadata, err = client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `42`, metadata.SerializedOutput)
})
}
}
func TestInternalActorsSetupForWF(t *testing.T) {
ctx := context.Background()
_, engine := startEngine(ctx, t, task.NewTaskRegistry())
abe, ok := engine.Backend.(*actorsbe.ActorBackend)
assert.True(t, ok, "engine.Backend is of type ActorBackend")
assert.Len(t, abe.GetInternalActorsMap(), 2)
assert.Contains(t, abe.GetInternalActorsMap(), workflowActorType)
assert.Contains(t, abe.GetInternalActorsMap(), activityActorType)
}
// TestRecreateRunningWorkflowFails verifies that a workflow can't be recreated if it's in a running state.
func TestRecreateRunningWorkflowFails(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("SleepyWorkflow", func(ctx *task.OrchestrationContext) (any, error) {
err := ctx.CreateTimer(24 * time.Hour).Await(nil)
return nil, err
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
// Start the first workflow, which will not complete
var metadata *api.OrchestrationMetadata
id, err := client.ScheduleNewOrchestration(ctx, "SleepyWorkflow")
require.NoError(t, err)
metadata, err = client.WaitForOrchestrationStart(ctx, id)
require.NoError(t, err)
assert.False(t, metadata.IsComplete())
// Attempting to start a second workflow with the same ID should fail
_, err = client.ScheduleNewOrchestration(ctx, "SleepyWorkflow", api.WithInstanceID(id))
require.Error(t, err)
// We expect that the workflow instance ID is included in the error message
assert.Contains(t, err.Error(), id)
})
}
}
// TestRetryWorkflowOnTimeout verifies that workflow operations are retried when they fail to complete.
func TestRetryWorkflowOnTimeout(t *testing.T) {
const expectedCallCount = 3
actualCallCount := atomic.Int32{}
r := task.NewTaskRegistry()
r.AddOrchestratorN("FlakyWorkflow", func(ctx *task.OrchestrationContext) (any, error) {
// update this global counter each time the workflow gets invoked
acc := actualCallCount.Add(1)
if acc < expectedCallCount {
// simulate a hang for the first two calls
time.Sleep(5 * time.Minute)
}
return acc, nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
abe, _ := engine.Backend.(*actorsbe.ActorBackend)
// Set a really short timeout to override the default workflow timeout so that we can exercise the timeout
// handling codepath in a short period of time.
abe.SetWorkflowTimeout(1 * time.Second)
// Set a really short reminder interval to retry workflows immediately after they time out.
abe.SetActorReminderInterval(1 * time.Millisecond)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
actualCallCount.Store(0)
id, err := client.ScheduleNewOrchestration(ctx, "FlakyWorkflow")
require.NoError(t, err)
// Add a 5 second timeout so that the test doesn't take forever if something isn't working
timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
metadata, err := client.WaitForOrchestrationCompletion(timeoutCtx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, strconv.Itoa(expectedCallCount), metadata.SerializedOutput)
})
}
}
// TestRetryActivityOnTimeout verifies that activity operations are retried when they fail to complete.
func TestRetryActivityOnTimeout(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("FlakyWorkflow", func(ctx *task.OrchestrationContext) (any, error) {
var output int
err := ctx.CallActivity("FlakyActivity").Await(&output)
return output, err
})
const expectedCallCount = 3
actualCallCount := atomic.Int32{}
r.AddActivityN("FlakyActivity", func(ctx task.ActivityContext) (any, error) {
// update this global counter each time the activity gets invoked
acc := actualCallCount.Add(1)
if acc < expectedCallCount {
// simulate a hang for the first two calls
time.Sleep(5 * time.Minute)
}
return acc, nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
abe, _ := engine.Backend.(*actorsbe.ActorBackend)
// Set a really short timeout to override the default activity timeout (1 hour at the time of writing)
// so that we can exercise the timeout handling codepath in a short period of time.
abe.SetActivityTimeout(1 * time.Second)
// Set a really short reminder interval to retry activities immediately after they time out.
abe.SetActorReminderInterval(1 * time.Millisecond)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
actualCallCount.Store(0)
id, err := client.ScheduleNewOrchestration(ctx, "FlakyWorkflow")
require.NoError(t, err)
// Add a 5 second timeout so that the test doesn't take forever if something isn't working
timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
metadata, err := client.WaitForOrchestrationCompletion(timeoutCtx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, strconv.Itoa(expectedCallCount), metadata.SerializedOutput)
})
}
}
func TestConcurrentTimerExecution(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("TimerFanOut", func(ctx *task.OrchestrationContext) (any, error) {
tasks := []task.Task{}
for i := 0; i < 2; i++ {
tasks = append(tasks, ctx.CreateTimer(1*time.Second))
}
for _, t := range tasks {
if err := t.Await(nil); err != nil {
return nil, err
}
}
return nil, nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "TimerFanOut")
require.NoError(t, err)
// Add a 5 second timeout so that the test doesn't take forever if something isn't working
timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
metadata, err := client.WaitForOrchestrationCompletion(timeoutCtx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
// Because all the timers run in parallel, they should complete very quickly
assert.Less(t, metadata.LastUpdatedAt.Sub(metadata.CreatedAt), 3*time.Second)
})
}
}
// TestRaiseEvent verifies that a workflow can have an event raised against it to trigger specific functionality.
func TestRaiseEvent(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("WorkflowForRaiseEvent", func(ctx *task.OrchestrationContext) (any, error) {
var nameInput string
if err := ctx.WaitForSingleEvent("NameOfEventBeingRaised", 30*time.Second).Await(&nameInput); err != nil {
// Timeout expired
return nil, err
}
return fmt.Sprintf("Hello, %s!", nameInput), nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "WorkflowForRaiseEvent")
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationStart(ctx, id)
require.NoError(t, err)
assert.Equal(t, id, metadata.InstanceID)
client.RaiseEvent(ctx, id, "NameOfEventBeingRaised", api.WithEventPayload("NameOfInput"))
metadata, _ = client.WaitForOrchestrationCompletion(ctx, id)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `"Hello, NameOfInput!"`, metadata.SerializedOutput)
assert.Nil(t, metadata.FailureDetails)
})
}
}
// TestContinueAsNew_WithEvents verifies that a workflow can continue as new and process any received events
// in subsequent iterations.
func TestContinueAsNew_WithEvents(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("ContinueAsNewTest", func(ctx *task.OrchestrationContext) (any, error) {
var input int32
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
var complete bool
if err := ctx.WaitForSingleEvent("MyEvent", -1).Await(&complete); err != nil {
return nil, err
}
if complete {
return input, nil
}
ctx.ContinueAsNew(input+1, task.WithKeepUnprocessedEvents())
return nil, nil
})
// Initialization
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
// Run the orchestration
id, err := client.ScheduleNewOrchestration(ctx, "ContinueAsNewTest", api.WithInput(0))
require.NoError(t, err)
for i := 0; i < 10; i++ {
require.NoError(t, client.RaiseEvent(ctx, id, "MyEvent", api.WithEventPayload(false)))
}
require.NoError(t, client.RaiseEvent(ctx, id, "MyEvent", api.WithEventPayload(true)))
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `10`, metadata.SerializedOutput)
})
}
}
// TestPurge verifies that a workflow can have a series of activities created and then
// verifies that all the metadata for those activities can be deleted from the statestore
func TestPurge(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("ActivityChainToPurge", func(ctx *task.OrchestrationContext) (any, error) {
val := 0
for i := 0; i < 10; i++ {
if err := ctx.CallActivity("PlusOne", task.WithActivityInput(val)).Await(&val); err != nil {
return nil, err
}
}
return val, nil
})
r.AddActivityN("PlusOne", func(ctx task.ActivityContext) (any, error) {
var input int
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
return input + 1, nil
})
ctx := context.Background()
client, engine, stateStore := startEngineAndGetStore(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "ActivityChainToPurge")
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.Equal(t, id, metadata.InstanceID)
// Get the number of keys that were stored from the activity and ensure that at least some keys were stored
keyCounter := atomic.Int64{}
for key := range stateStore.GetItems() {
if strings.Contains(key, string(id)) {
keyCounter.Add(1)
}
}
assert.Greater(t, keyCounter.Load(), int64(10))
err = client.PurgeOrchestrationState(ctx, id)
require.NoError(t, err)
// Check that no key from the statestore containing the actor id is still present in the statestore
keysPostPurge := []string{}
for key := range stateStore.GetItems() {
keysPostPurge = append(keysPostPurge, key)
}
for _, item := range keysPostPurge {
if strings.Contains(item, string(id)) {
assert.Truef(t, false, "Found key post-purge that should not have existed: %v", item)
}
}
})
}
}
func TestPurgeContinueAsNew(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("ContinueAsNewTest", func(ctx *task.OrchestrationContext) (any, error) {
var input int32
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
if input < 10 {
if err := ctx.CreateTimer(0).Await(nil); err != nil {
return nil, err
}
var nextInput int32
if err := ctx.CallActivity("PlusOne", task.WithActivityInput(input)).Await(&nextInput); err != nil {
return nil, err
}
ctx.ContinueAsNew(nextInput)
}
return input, nil
})
r.AddActivityN("PlusOne", func(ctx task.ActivityContext) (any, error) {
var input int32
if err := ctx.GetInput(&input); err != nil {
return nil, err
}
return input + 1, nil
})
ctx := context.Background()
client, engine, stateStore := startEngineAndGetStore(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "ContinueAsNewTest", api.WithInput(0))
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationCompletion(ctx, id)
require.NoError(t, err)
assert.True(t, metadata.IsComplete())
assert.Equal(t, `10`, metadata.SerializedOutput)
// Purging
// Get the number of keys that were stored from the activity and ensure that at least some keys were stored
keyCounter := atomic.Int64{}
for key := range stateStore.GetItems() {
if strings.Contains(key, string(id)) {
keyCounter.Add(1)
}
}
assert.Greater(t, keyCounter.Load(), int64(2))
err = client.PurgeOrchestrationState(ctx, id)
require.NoError(t, err)
// Check that no key from the statestore containing the actor id is still present in the statestore
keysPostPurge := []string{}
for key := range stateStore.GetItems() {
keysPostPurge = append(keysPostPurge, key)
}
for _, item := range keysPostPurge {
if strings.Contains(item, string(id)) {
assert.True(t, false)
}
}
})
}
}
func TestPauseResumeWorkflow(t *testing.T) {
r := task.NewTaskRegistry()
r.AddOrchestratorN("PauseWorkflow", func(ctx *task.OrchestrationContext) (any, error) {
if err := ctx.WaitForSingleEvent("WaitForThisEvent", 30*time.Second).Await(nil); err != nil {
// Timeout expired
return nil, err
}
return nil, nil
})
ctx := context.Background()
client, engine := startEngine(ctx, t, r)
for _, opt := range GetTestOptions() {
t.Run(opt(engine), func(t *testing.T) {
id, err := client.ScheduleNewOrchestration(ctx, "PauseWorkflow")
require.NoError(t, err)
metadata, err := client.WaitForOrchestrationStart(ctx, id)
require.NoError(t, err)
assert.Equal(t, id, metadata.InstanceID)
client.SuspendOrchestration(ctx, id, "PauseWFReasonTest")
client.RaiseEvent(ctx, id, "WaitForThisEvent")
assert.True(t, metadata.IsRunning())
client.ResumeOrchestration(ctx, id, "ResumeWFReasonTest")
metadata, _ = client.WaitForOrchestrationCompletion(ctx, id)
assert.True(t, metadata.IsComplete())
assert.Nil(t, metadata.FailureDetails)
})
}
}
func startEngine(ctx context.Context, t *testing.T, r *task.TaskRegistry) (backend.TaskHubClient, *wfengine.WorkflowEngine) {
client, engine, _ := startEngineAndGetStore(ctx, t, r)
return client, engine
}
func startEngineAndGetStore(ctx context.Context, t *testing.T, r *task.TaskRegistry) (backend.TaskHubClient, *wfengine.WorkflowEngine, *daprt.FakeStateStore) {
var client backend.TaskHubClient
engine, store := getEngineAndStateStore(t, ctx)
engine.SetExecutor(func(be backend.Backend) backend.Executor {
client = backend.NewTaskHubClient(be)
return task.NewTaskExecutor(r)
})
require.NoError(t, engine.Start(ctx))
return client, engine, store
}
func getEngine(t *testing.T, ctx context.Context) *wfengine.WorkflowEngine {
spec := config.WorkflowSpec{MaxConcurrentWorkflowInvocations: 100, MaxConcurrentActivityInvocations: 100}
processor := processor.New(processor.Options{
Registry: registry.New(registry.NewOptions()),
GlobalConfig: new(config.Configuration),
})
engine := wfengine.NewWorkflowEngine(testAppID, spec, processor.WorkflowBackend())
store := fakeStore()
cfg := actors.NewConfig(actors.ConfigOpts{
AppID: testAppID,
ActorsService: "placement:placement:5050",
AppConfig: config.ApplicationConfig{},
})
compStore := compstore.New()
compStore.AddStateStore("workflowStore", store)
actors, err := actors.NewActors(actors.ActorsOpts{
CompStore: compStore,
Config: cfg,
StateStoreName: "workflowStore",
MockPlacement: actors.NewMockPlacement(testAppID),
Resiliency: resiliency.New(logger.NewLogger("test")),
})
require.NoError(t, err)
if err := actors.Init(context.Background()); err != nil {
require.NoError(t, err)
}
abe, _ := engine.Backend.(*actorsbe.ActorBackend)
abe.SetActorRuntime(ctx, actors)
return engine
}
func getEngineAndStateStore(t *testing.T, ctx context.Context) (*wfengine.WorkflowEngine, *daprt.FakeStateStore) {
spec := config.WorkflowSpec{MaxConcurrentWorkflowInvocations: 100, MaxConcurrentActivityInvocations: 100}
processor := processor.New(processor.Options{
Registry: registry.New(registry.NewOptions()),
GlobalConfig: new(config.Configuration),
})
engine := wfengine.NewWorkflowEngine(testAppID, spec, processor.WorkflowBackend())
store := fakeStore().(*daprt.FakeStateStore)
cfg := actors.NewConfig(actors.ConfigOpts{
AppID: testAppID,
ActorsService: "placement:placement:5050",
AppConfig: config.ApplicationConfig{},
HostAddress: "localhost",
Port: 5000, // port for unit tests to pass IsLocalActor
})
compStore := compstore.New()
compStore.AddStateStore("workflowStore", store)
actors, err := actors.NewActors(actors.ActorsOpts{
CompStore: compStore,
Config: cfg,
StateStoreName: "workflowStore",
MockPlacement: actors.NewMockPlacement(testAppID),
Resiliency: resiliency.New(logger.NewLogger("test")),
})
require.NoError(t, err)
require.NoError(t, actors.Init(context.Background()))
abe, _ := engine.Backend.(*actorsbe.ActorBackend)
abe.SetActorRuntime(ctx, actors)
return engine, store
}
|
mikeee/dapr
|
pkg/runtime/wfengine/wfengine_test.go
|
GO
|
mit
| 35,481 |
package scopes
import (
"strings"
)
const (
SubscriptionScopes = "subscriptionScopes"
PublishingScopes = "publishingScopes"
AllowedTopics = "allowedTopics"
ProtectedTopics = "protectedTopics"
appsSeparator = ";"
appSeparator = "="
topicSeparator = ","
)
func findParamInMetadata(param string, metadata map[string]string) (string, bool) {
param = strings.ToLower(param)
for name, val := range metadata {
name = strings.ToLower(name)
if param == name {
return val, true
}
}
return "", false
}
// GetScopedTopics returns a list of scoped topics for a given application from a Pub/Sub
// Component properties.
func GetScopedTopics(scope, appID string, metadata map[string]string) []string {
var (
existM = map[string]struct{}{}
topics = []string{}
)
if val, ok := findParamInMetadata(scope, metadata); ok && val != "" {
val = strings.ReplaceAll(val, " ", "")
apps := strings.Split(val, appsSeparator)
for _, a := range apps {
appTopics := strings.Split(a, appSeparator)
if len(appTopics) < 2 {
continue
}
app := appTopics[0]
if app != appID {
continue
}
tempTopics := strings.Split(appTopics[1], topicSeparator)
for _, tempTopic := range tempTopics {
if _, ok = existM[tempTopic]; !ok {
existM[tempTopic] = struct{}{}
topics = append(topics, tempTopic)
}
}
}
}
return topics
}
func getParamTopics(param string, metadata map[string]string) []string {
var (
existM = map[string]struct{}{}
topics = []string{}
)
if val, ok := findParamInMetadata(param, metadata); ok && val != "" {
val = strings.ReplaceAll(val, " ", "")
tempTopics := strings.Split(val, topicSeparator)
for _, tempTopic := range tempTopics {
if _, ok = existM[tempTopic]; !ok {
existM[tempTopic] = struct{}{}
topics = append(topics, tempTopic)
}
}
}
return topics
}
// GetAllowedTopics return the all topics list of params allowedTopics.
func GetAllowedTopics(metadata map[string]string) []string {
return getParamTopics(AllowedTopics, metadata)
}
// GetProtectedTopics returns all topics of param protectedTopics.
func GetProtectedTopics(metadata map[string]string) []string {
return getParamTopics(ProtectedTopics, metadata)
}
|
mikeee/dapr
|
pkg/scopes/scopes.go
|
GO
|
mit
| 2,253 |
package scopes
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetAllowedTopics(t *testing.T) {
allowedTests := []struct {
Metadata map[string]string
Target []string
Msg string
}{
{
Metadata: nil,
Target: []string{},
Msg: "pass",
},
{
Metadata: map[string]string{
"allowedTopics": "topic1,topic2,topic3",
},
Target: []string{"topic1", "topic2", "topic3"},
Msg: "pass",
},
{
Metadata: map[string]string{
"allowedTopics": "topic1, topic2, topic3",
},
Target: []string{"topic1", "topic2", "topic3"},
Msg: "pass, include whitespace",
},
{
Metadata: map[string]string{
"allowedTopics": "",
},
Target: []string{},
Msg: "pass",
},
{
Metadata: map[string]string{
"allowedTopics": "topic1, topic1, topic1", //nolint:dupword
},
Target: []string{"topic1"},
Msg: "pass, include whitespace and repeated topic",
},
{
Metadata: map[string]string{
"Allowedtopics": "topic1",
},
Target: []string{"topic1"},
Msg: "pass, case-insensitive match",
},
}
for _, item := range allowedTests {
assert.Equal(t, GetAllowedTopics(item.Metadata), item.Target)
}
}
func TestGetProtectedTopics(t *testing.T) {
protectedTests := []struct {
Metadata map[string]string
Target []string
Msg string
}{
{
Metadata: nil,
Target: []string{},
Msg: "pass",
},
{
Metadata: map[string]string{},
Target: []string{},
Msg: "pass",
},
{
Metadata: map[string]string{
"protectedTopics": "",
},
Target: []string{},
Msg: "pass",
},
{
Metadata: map[string]string{
"protectedTopics": "topic1,topic2,topic3",
},
Target: []string{"topic1", "topic2", "topic3"},
Msg: "pass",
},
{
Metadata: map[string]string{
"protectedTopics": "topic1, topic2, topic3",
},
Target: []string{"topic1", "topic2", "topic3"},
Msg: "pass, include whitespace",
},
{
Metadata: map[string]string{
"protectedTopics": "topic1, topic1, topic1", //nolint:dupword
},
Target: []string{"topic1"},
Msg: "pass, include whitespace and repeated topic",
},
{
Metadata: map[string]string{
"protectedTOPICS": "topic1",
},
Target: []string{"topic1"},
Msg: "pass, case-insensitive match",
},
}
for _, item := range protectedTests {
assert.Equal(t, GetProtectedTopics(item.Metadata), item.Target)
}
}
func TestGetScopedTopics(t *testing.T) {
scopedTests := []struct {
Scope string
AppID string
Metadata map[string]string
Target []string
Msg string
}{
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{},
Target: []string{},
Msg: "pass",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid2=topic1",
},
Target: []string{},
Msg: "pass",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid1=topic1",
},
Target: []string{"topic1"},
Msg: "pass",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid1=topic1, topic2",
},
Target: []string{"topic1", "topic2"},
Msg: "pass, include whitespace",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid1=topic1;appid1=topic2",
},
Target: []string{"topic1", "topic2"},
Msg: "pass, include repeated appid",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid1=topic1;appid1=topic1",
},
Target: []string{"topic1"},
Msg: "pass, include repeated appid and topic",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid1",
},
Target: []string{},
Msg: "pass",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid2",
},
Target: []string{},
Msg: "pass",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid1;appid2=topic2",
},
Target: []string{},
Msg: "pass",
},
{
Scope: "subscriptionScopes",
AppID: "appid1",
Metadata: map[string]string{
"subscriptionScopes": "appid1=topic1;appid2",
},
Target: []string{"topic1"},
Msg: "pass",
},
{
Scope: "subscriptionSCOPES",
AppID: "appid1",
Metadata: map[string]string{
"Subscriptionscopes": "appid1=topic1;appid2",
},
Target: []string{"topic1"},
Msg: "pass, case-insensitive match",
},
}
for _, item := range scopedTests {
assert.Equal(t,
GetScopedTopics(item.Scope, item.AppID, item.Metadata),
item.Target)
}
}
|
mikeee/dapr
|
pkg/scopes/scopes_test.go
|
GO
|
mit
| 4,969 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package consts
const (
// APITokenEnvVar is the environment variable for the API token.
//nolint:gosec
APITokenEnvVar = "DAPR_API_TOKEN"
// AppAPITokenEnvVar is the environment variable for the app API token.
//nolint:gosec
AppAPITokenEnvVar = "APP_API_TOKEN"
// APITokenHeader is header name for HTTP/gRPC calls to hold the token.
//nolint:gosec
APITokenHeader = "dapr-api-token"
// TrustBundleK8sSecretName is the name of the kubernetes secret that holds the trust bundle.
TrustBundleK8sSecretName = "dapr-trust-bundle" /* #nosec */
// TrustAnchorsEnvVar is the environment variable name for the trust anchors in the sidecar.
TrustAnchorsEnvVar = "DAPR_TRUST_ANCHORS"
// EnvKeysEnvVar is the variable injected in the daprd container with the list of injected env vars.
EnvKeysEnvVar = "DAPR_ENV_KEYS"
// SentryTokenFileEnvVar is the environment variable for the Sentry token file.
//nolint:gosec
SentryTokenFileEnvVar = "DAPR_SENTRY_TOKEN_FILE"
// AnnotationKeyControlPlane is the annotation to mark a control plane
// component. The value is the name of the control plane service.
AnnotationKeyControlPlane = "dapr.io/control-plane"
// ControlPlaneAddressEnvVar is the daprd environment variable for
// configuring the control plane namespace.
ControlPlaneNamespaceEnvVar = "DAPR_CONTROLPLANE_NAMESPACE"
// ControlPlaneAddressEnvVar is the daprd environment variable for
// configuring the control plane trust domain.
ControlPlaneTrustDomainEnvVar = "DAPR_CONTROLPLANE_TRUST_DOMAIN"
// ControlPlaneDefaultTrustAnchorsPath is the default path where the trust anchors are placed for control plane services.
ControlPlaneDefaultTrustAnchorsPath = "/var/run/secrets/dapr.io/tls/ca.crt"
)
|
mikeee/dapr
|
pkg/security/consts/consts.go
|
GO
|
mit
| 2,285 |
//go:build unit
// +build unit
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
"crypto/tls"
"net"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/dapr/dapr/pkg/security"
)
type Fake struct {
controlPlaneTrustDomainFn func() spiffeid.TrustDomain
controlPlaneNamespaceFn func() string
currentTrustAnchorsFn func(context.Context) ([]byte, error)
watchTrustAnchorsFn func(context.Context, chan<- []byte)
mtls bool
tlsServerConfigMTLSFn func(spiffeid.TrustDomain) (*tls.Config, error)
tlsServerConfigNoClientAuthFn func() *tls.Config
tlsServerConfigNoClientAuthOptionFn func(*tls.Config)
netListenerIDFn func(net.Listener, spiffeid.ID) net.Listener
netDialerIDFn func(context.Context, spiffeid.ID, time.Duration) func(network, addr string) (net.Conn, error)
grpcDialOptionFn func(spiffeid.ID) grpc.DialOption
grpcDialOptionUnknownTrustDomainFn func(ns, appID string) grpc.DialOption
grpcServerOptionMTLSFn func() grpc.ServerOption
grpcServerOptionNoClientAuthFn func() grpc.ServerOption
}
func New() *Fake {
return &Fake{
controlPlaneTrustDomainFn: func() spiffeid.TrustDomain {
return spiffeid.RequireTrustDomainFromString("example.org")
},
controlPlaneNamespaceFn: func() string {
return "dapr-test"
},
tlsServerConfigMTLSFn: func(spiffeid.TrustDomain) (*tls.Config, error) {
return new(tls.Config), nil
},
tlsServerConfigNoClientAuthFn: func() *tls.Config {
return new(tls.Config)
},
tlsServerConfigNoClientAuthOptionFn: func(*tls.Config) {},
grpcDialOptionFn: func(spiffeid.ID) grpc.DialOption {
return grpc.WithTransportCredentials(insecure.NewCredentials())
},
grpcDialOptionUnknownTrustDomainFn: func(ns, appID string) grpc.DialOption {
return grpc.WithTransportCredentials(insecure.NewCredentials())
},
grpcServerOptionMTLSFn: func() grpc.ServerOption {
return grpc.Creds(nil)
},
grpcServerOptionNoClientAuthFn: func() grpc.ServerOption {
return grpc.Creds(nil)
},
currentTrustAnchorsFn: func(context.Context) ([]byte, error) {
return []byte{}, nil
},
watchTrustAnchorsFn: func(context.Context, chan<- []byte) {
return
},
netListenerIDFn: func(l net.Listener, _ spiffeid.ID) net.Listener {
return l
},
netDialerIDFn: func(context.Context, spiffeid.ID, time.Duration) func(network, addr string) (net.Conn, error) {
return net.Dial
},
mtls: false,
}
}
func (f *Fake) WithControlPlaneTrustDomainFn(fn func() spiffeid.TrustDomain) *Fake {
f.controlPlaneTrustDomainFn = fn
return f
}
func (f *Fake) WithControlPlaneNamespaceFn(fn func() string) *Fake {
f.controlPlaneNamespaceFn = fn
return f
}
func (f *Fake) WithTLSServerConfigMTLSFn(fn func(spiffeid.TrustDomain) (*tls.Config, error)) *Fake {
f.tlsServerConfigMTLSFn = fn
return f
}
func (f *Fake) WithTLSServerConfigNoClientAuthFn(fn func() *tls.Config) *Fake {
f.tlsServerConfigNoClientAuthFn = fn
return f
}
func (f *Fake) WithTLSServerConfigNoClientAuthOptionFn(fn func(*tls.Config)) *Fake {
f.tlsServerConfigNoClientAuthOptionFn = fn
return f
}
func (f *Fake) WithGRPCDialOptionMTLSFn(fn func(spiffeid.ID) grpc.DialOption) *Fake {
f.grpcDialOptionFn = fn
return f
}
func (f *Fake) WithGRPCDialOptionMTLSUnknownTrustDomainFn(fn func(ns, appID string) grpc.DialOption) *Fake {
f.grpcDialOptionUnknownTrustDomainFn = fn
return f
}
func (f *Fake) WithGRPCServerOptionMTLSFn(fn func() grpc.ServerOption) *Fake {
f.grpcServerOptionMTLSFn = fn
return f
}
func (f *Fake) WithGRPCServerOptionNoClientAuthFn(fn func() grpc.ServerOption) *Fake {
f.grpcServerOptionNoClientAuthFn = fn
return f
}
func (f *Fake) WithMTLSEnabled(mtls bool) *Fake {
f.mtls = mtls
return f
}
func (f *Fake) ControlPlaneTrustDomain() spiffeid.TrustDomain {
return f.controlPlaneTrustDomainFn()
}
func (f *Fake) ControlPlaneNamespace() string {
return f.controlPlaneNamespaceFn()
}
func (f *Fake) TLSServerConfigMTLS(td spiffeid.TrustDomain) (*tls.Config, error) {
return f.tlsServerConfigMTLSFn(td)
}
func (f *Fake) TLSServerConfigNoClientAuth() *tls.Config {
return f.tlsServerConfigNoClientAuthFn()
}
func (f *Fake) TLSServerConfigNoClientAuthOption(cfg *tls.Config) {
f.tlsServerConfigNoClientAuthOptionFn(cfg)
}
func (f *Fake) GRPCDialOptionMTLS(id spiffeid.ID) grpc.DialOption {
return f.grpcDialOptionFn(id)
}
func (f *Fake) GRPCDialOptionMTLSUnknownTrustDomain(ns, appID string) grpc.DialOption {
return f.grpcDialOptionUnknownTrustDomainFn(ns, appID)
}
func (f *Fake) GRPCServerOptionMTLS() grpc.ServerOption {
return f.grpcServerOptionMTLSFn()
}
func (f *Fake) WithCurrentTrustAnchorsFn(fn func(context.Context) ([]byte, error)) *Fake {
f.currentTrustAnchorsFn = fn
return f
}
func (f *Fake) WithWatchTrustAnchorsFn(fn func(context.Context, chan<- []byte)) *Fake {
f.watchTrustAnchorsFn = fn
return f
}
func (f *Fake) WithGRPCDialOptionFn(fn func(spiffeid.ID) grpc.DialOption) *Fake {
f.grpcDialOptionFn = fn
return f
}
func (f *Fake) WithNetListenerIDFn(fn func(net.Listener, spiffeid.ID) net.Listener) *Fake {
f.netListenerIDFn = fn
return f
}
func (f *Fake) WithNetDialerIDFn(fn func(context.Context, spiffeid.ID, time.Duration) func(network, addr string) (net.Conn, error)) *Fake {
f.netDialerIDFn = fn
return f
}
func (f *Fake) GRPCServerOptionNoClientAuth() grpc.ServerOption {
return f.grpcServerOptionNoClientAuthFn()
}
func (f *Fake) CurrentTrustAnchors(ctx context.Context) ([]byte, error) {
return f.currentTrustAnchorsFn(ctx)
}
func (f *Fake) WatchTrustAnchors(ctx context.Context, ch chan<- []byte) {
f.watchTrustAnchorsFn(ctx, ch)
}
func (f *Fake) WithSVIDContext(ctx context.Context) context.Context {
return ctx
}
func (f *Fake) GRPCDialOption(id spiffeid.ID) grpc.DialOption {
return f.grpcDialOptionFn(id)
}
func (f *Fake) NetListenerID(l net.Listener, id spiffeid.ID) net.Listener {
return f.netListenerIDFn(l, id)
}
func (f *Fake) NetDialerID(ctx context.Context, id spiffeid.ID, timeout time.Duration) func(network, addr string) (net.Conn, error) {
return f.netDialerIDFn(ctx, id, timeout)
}
func (f *Fake) MTLSEnabled() bool {
return f.mtls
}
func (f *Fake) Run(ctx context.Context) error {
<-ctx.Done()
return nil
}
func (f *Fake) Handler(context.Context) (security.Handler, error) {
return f, nil
}
|
mikeee/dapr
|
pkg/security/fake/fake.go
|
GO
|
mit
| 7,014 |
//go:build unit
// +build unit
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"testing"
"github.com/dapr/dapr/pkg/security"
)
func TestFake(t *testing.T) {
var _ security.Handler = New()
var _ security.Provider = New()
}
|
mikeee/dapr
|
pkg/security/fake/fake_test.go
|
GO
|
mit
| 765 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package security
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"os"
"sync/atomic"
"time"
"github.com/spiffe/go-spiffe/v2/spiffegrpc/grpccredentials"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/dapr/dapr/pkg/diagnostics"
"github.com/dapr/dapr/pkg/modes"
"github.com/dapr/kit/concurrency"
"github.com/dapr/kit/crypto/spiffe"
spiffecontext "github.com/dapr/kit/crypto/spiffe/context"
"github.com/dapr/kit/crypto/spiffe/trustanchors"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.runtime.security")
// Handler implements middleware for client and server connection security.
//
//nolint:interfacebloat
type Handler interface {
GRPCServerOptionMTLS() grpc.ServerOption
GRPCServerOptionNoClientAuth() grpc.ServerOption
GRPCDialOptionMTLSUnknownTrustDomain(ns, appID string) grpc.DialOption
GRPCDialOptionMTLS(spiffeid.ID) grpc.DialOption
TLSServerConfigNoClientAuth() *tls.Config
NetListenerID(net.Listener, spiffeid.ID) net.Listener
NetDialerID(context.Context, spiffeid.ID, time.Duration) func(network, addr string) (net.Conn, error)
ControlPlaneTrustDomain() spiffeid.TrustDomain
ControlPlaneNamespace() string
CurrentTrustAnchors(context.Context) ([]byte, error)
WithSVIDContext(context.Context) context.Context
MTLSEnabled() bool
WatchTrustAnchors(context.Context, chan<- []byte)
}
// Provider is the security provider.
type Provider interface {
Run(context.Context) error
Handler(context.Context) (Handler, error)
}
// Options are the options for the security authenticator.
type Options struct {
// SentryAddress is the network address of the sentry server.
SentryAddress string
// ControlPlaneTrustDomain is the trust domain of the control plane
// components.
ControlPlaneTrustDomain string
// ControlPlaneNamespace is the dapr namespace of the control plane
// components.
ControlPlaneNamespace string
// TrustAnchors is the X.509 PEM encoded CA certificates for this Dapr
// installation. Cannot be used with TrustAnchorsFile. TrustAnchorsFile is
// preferred so changes to the file are automatically picked up.
TrustAnchors []byte
// TrustAnchorsFile is the path to the X.509 PEM encoded CA certificates for
// this Dapr installation. Prefer this over TrustAnchors so changes to the
// file are automatically picked up. Cannot be used with TrustAnchors.
TrustAnchorsFile *string
// AppID is the application ID of this workload.
AppID string
// MTLS is true if mTLS is enabled.
MTLSEnabled bool
// OverrideCertRequestFn is used to override where certificates are requested
// from. Default to an implementation requesting from Sentry.
OverrideCertRequestFn spiffe.RequestSVIDFn
// Mode is the operation mode of this security instance (self-hosted or
// Kubernetes).
Mode modes.DaprMode
// SentryTokenFile is an optional file containing the token to authenticate
// to sentry.
SentryTokenFile *string
}
type provider struct {
sec *security
running atomic.Bool
readyCh chan struct{}
}
// security implements the Security interface.
type security struct {
controlPlaneTrustDomain spiffeid.TrustDomain
controlPlaneNamespace string
trustAnchors trustanchors.Interface
spiffe *spiffe.SPIFFE
mtls bool
}
func New(ctx context.Context, opts Options) (Provider, error) {
if len(opts.ControlPlaneTrustDomain) == 0 {
return nil, errors.New("control plane trust domain is required")
}
cptd, err := spiffeid.TrustDomainFromString(opts.ControlPlaneTrustDomain)
if err != nil {
return nil, fmt.Errorf("invalid control plane trust domain: %w", err)
}
// Always request certificates from Sentry if mTLS is enabled or running in
// Kubernetes. In Kubernetes, Daprd always communicates mTLS with the control
// plane.
var spf *spiffe.SPIFFE
var trustAnchors trustanchors.Interface
if opts.MTLSEnabled || opts.Mode == modes.KubernetesMode {
if len(opts.TrustAnchors) > 0 && opts.TrustAnchorsFile != nil {
return nil, errors.New("trust anchors cannot be specified in both TrustAnchors and TrustAnchorsFile")
}
if len(opts.TrustAnchors) == 0 && opts.TrustAnchorsFile == nil {
return nil, errors.New("trust anchors are required")
}
switch {
case len(opts.TrustAnchors) > 0:
trustAnchors, err = trustanchors.FromStatic(opts.TrustAnchors)
if err != nil {
return nil, err
}
case opts.TrustAnchorsFile != nil:
trustAnchors = trustanchors.FromFile(trustanchors.OptionsFile{
Log: log,
Path: *opts.TrustAnchorsFile,
})
}
var reqFn spiffe.RequestSVIDFn
if opts.OverrideCertRequestFn != nil {
reqFn = opts.OverrideCertRequestFn
} else {
reqFn, err = newRequestFn(opts, trustAnchors, cptd)
if err != nil {
return nil, err
}
}
spf = spiffe.New(spiffe.Options{Log: log, RequestSVIDFn: reqFn})
} else {
log.Warn("mTLS is disabled. Skipping certificate request and tls validation")
}
return &provider{
readyCh: make(chan struct{}),
sec: &security{
trustAnchors: trustAnchors,
spiffe: spf,
mtls: opts.MTLSEnabled,
controlPlaneTrustDomain: cptd,
controlPlaneNamespace: opts.ControlPlaneNamespace,
},
}, nil
}
// Run is a blocking function which starts the security provider, handling
// rotation of credentials.
func (p *provider) Run(ctx context.Context) error {
if !p.running.CompareAndSwap(false, true) {
return errors.New("security provider already started")
}
// If spiffe has not been initialized, then just wait to exit.
if p.sec.spiffe == nil {
close(p.readyCh)
<-ctx.Done()
return nil
}
return concurrency.NewRunnerManager(
p.sec.spiffe.Run,
p.sec.trustAnchors.Run,
func(ctx context.Context) error {
if err := p.sec.spiffe.Ready(ctx); err != nil {
return err
}
close(p.readyCh)
diagnostics.DefaultMonitoring.MTLSInitCompleted()
<-ctx.Done()
return nil
},
).Run(ctx)
}
// Handler returns a ready handler from the security provider. Blocks until
// the provider is ready.
func (p *provider) Handler(ctx context.Context) (Handler, error) {
select {
case <-p.readyCh:
return p.sec, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// GRPCDialOptionMTLS returns a gRPC dial option which instruments client
// authentication using the current signed client certificate.
func (s *security) GRPCDialOptionMTLS(appID spiffeid.ID) grpc.DialOption {
// If source has not been initialized, then just return an insecure dial
// option. We don't check on `mtls` here as we still want to use mTLS with
// control plane peers when running in Kubernetes mode even if mTLS is
// disabled.
if s.spiffe == nil {
return grpc.WithTransportCredentials(insecure.NewCredentials())
}
return grpc.WithTransportCredentials(
grpccredentials.MTLSClientCredentials(s.spiffe.SVIDSource(), s.trustAnchors, tlsconfig.AuthorizeID(appID)),
)
}
// GRPCServerOptionMTLS returns a gRPC server option which instruments
// authentication of clients using the current trust anchors.
func (s *security) GRPCServerOptionMTLS() grpc.ServerOption {
if !s.mtls {
return grpc.Creds(insecure.NewCredentials())
}
return grpc.Creds(
// TODO: It would be better if we could give a subset of trust domains in
// which this server authorizes.
grpccredentials.MTLSServerCredentials(s.spiffe.SVIDSource(), s.trustAnchors, tlsconfig.AuthorizeAny()),
)
}
// GRPCServerOptionNoClientAuth returns a gRPC server option which instruments
// authentication of clients using the current trust anchors. Doesn't require
// clients to present a certificate.
func (s *security) GRPCServerOptionNoClientAuth() grpc.ServerOption {
return grpc.Creds(grpccredentials.TLSServerCredentials(s.spiffe.SVIDSource()))
}
// GRPCDialOptionMTLSUnknownTrustDomain returns a gRPC dial option which
// instruments client authentication using the current signed client
// certificate. Doesn't verify the servers trust domain, but does authorize the
// SPIFFE ID path.
// Used for clients which don't know the servers Trust Domain.
func (s *security) GRPCDialOptionMTLSUnknownTrustDomain(ns, appID string) grpc.DialOption {
if !s.mtls {
return grpc.WithTransportCredentials(insecure.NewCredentials())
}
expID := "/ns/" + ns + "/" + appID
matcher := func(actual spiffeid.ID) error {
if actual.Path() != expID {
return fmt.Errorf("unexpected SPIFFE ID: %q", actual)
}
return nil
}
return grpc.WithTransportCredentials(
grpccredentials.MTLSClientCredentials(s.spiffe.SVIDSource(), s.trustAnchors, tlsconfig.AdaptMatcher(matcher)),
)
}
// CurrentTrustAnchors returns the current trust anchors for this Dapr
// installation.
func (s *security) CurrentTrustAnchors(ctx context.Context) ([]byte, error) {
if s.spiffe == nil {
return nil, nil
}
return s.trustAnchors.CurrentTrustAnchors(ctx)
}
// WatchTrustAnchors watches for changes to the trust domains and returns the
// PEM encoded trust domain roots.
// Returns when the given context is canceled.
func (s *security) WatchTrustAnchors(ctx context.Context, trustAnchors chan<- []byte) {
s.trustAnchors.Watch(ctx, trustAnchors)
}
// ControlPlaneTrustDomain returns the trust domain of the control plane.
func (s *security) ControlPlaneTrustDomain() spiffeid.TrustDomain {
return s.controlPlaneTrustDomain
}
// ControlPlaneNamespace returns the dapr namespace of the control plane.
func (s *security) ControlPlaneNamespace() string {
return s.controlPlaneNamespace
}
// TLSServerConfigNoClientAuth returns a TLS server config which instruments
// using the current signed server certificate. Authorizes client certificate
// chains against the trust anchors.
func (s *security) TLSServerConfigNoClientAuth() *tls.Config {
return tlsconfig.TLSServerConfig(s.spiffe.SVIDSource())
}
// NetListenerID returns a mTLS net listener which instruments using the
// current signed server certificate. Authorizes client matches against the
// given SPIFFE ID.
func (s *security) NetListenerID(lis net.Listener, id spiffeid.ID) net.Listener {
if !s.mtls {
return lis
}
return tls.NewListener(lis,
tlsconfig.MTLSServerConfig(s.spiffe.SVIDSource(), s.trustAnchors, tlsconfig.AuthorizeID(id)),
)
}
// NetDialerID returns a mTLS net dialer which instruments using the current
// signed client certificate. Authorizes server matches against the given
// SPIFFE ID.
func (s *security) NetDialerID(ctx context.Context, spiffeID spiffeid.ID, timeout time.Duration) func(string, string) (net.Conn, error) {
if !s.mtls {
return (&net.Dialer{Timeout: timeout, Cancel: ctx.Done()}).Dial
}
return (&tls.Dialer{
NetDialer: (&net.Dialer{Timeout: timeout, Cancel: ctx.Done()}),
Config: tlsconfig.MTLSClientConfig(s.spiffe.SVIDSource(), s.trustAnchors, tlsconfig.AuthorizeID(spiffeID)),
}).Dial
}
// MTLSEnabled returns true if mTLS is enabled.
func (s *security) MTLSEnabled() bool {
return s.mtls
}
// CurrentNamespace returns the namespace of this workload.
func CurrentNamespace() string {
namespace, ok := os.LookupEnv("NAMESPACE")
if !ok {
return "default"
}
return namespace
}
// CurrentNamespaceOrError returns the namespace of this workload. If current
// Namespace is not found, error.
func CurrentNamespaceOrError() (string, error) {
namespace, ok := os.LookupEnv("NAMESPACE")
if !ok {
return "", errors.New("'NAMESPACE' environment variable not set")
}
if len(namespace) == 0 {
return "", errors.New("'NAMESPACE' environment variable is empty")
}
return namespace, nil
}
// SentryID returns the SPIFFE ID of the sentry server.
func SentryID(sentryTrustDomain spiffeid.TrustDomain, sentryNamespace string) (spiffeid.ID, error) {
sentryID, err := spiffeid.FromSegments(sentryTrustDomain, "ns", sentryNamespace, "dapr-sentry")
if err != nil {
return spiffeid.ID{}, fmt.Errorf("failed to parse sentry SPIFFE ID: %w", err)
}
return sentryID, nil
}
func (s *security) WithSVIDContext(ctx context.Context) context.Context {
if s.spiffe == nil {
return ctx
}
return spiffecontext.With(ctx, s.spiffe)
}
|
mikeee/dapr
|
pkg/security/security.go
|
GO
|
mit
| 12,703 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package security
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"math/big"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_Start(t *testing.T) {
t.Run("trust bundle should be updated when it is changed on file", func(t *testing.T) {
genRootCA := func() ([]byte, *x509.Certificate) {
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
require.NoError(t, err)
tmpl := x509.Certificate{
SerialNumber: serialNumber,
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Minute),
KeyUsage: x509.KeyUsageDigitalSignature,
SignatureAlgorithm: x509.ECDSAWithSHA256,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true,
}
certDER, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &pk.PublicKey, pk)
require.NoError(t, err)
wrkloadPK, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
serialNumber, err = rand.Int(rand.Reader, serialNumberLimit)
require.NoError(t, err)
spiffeID := spiffeid.RequireFromPath(spiffeid.RequireTrustDomainFromString("test.example.com"), "/ns/foo/bar")
tmpl = x509.Certificate{
SerialNumber: serialNumber,
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Minute),
KeyUsage: x509.KeyUsageDigitalSignature,
SignatureAlgorithm: x509.ECDSAWithSHA256,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
URIs: []*url.URL{spiffeID.URL()},
BasicConstraintsValid: true,
}
workloadCertDER, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, &wrkloadPK.PublicKey, pk)
require.NoError(t, err)
workloadCert, err := x509.ParseCertificate(workloadCertDER)
require.NoError(t, err)
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}), workloadCert
}
root1, workloadCert := genRootCA()
root2, _ := genRootCA()
tdFile := filepath.Join(t.TempDir(), "root.pem")
require.NoError(t, os.WriteFile(tdFile, root1, 0o600))
p, err := New(context.Background(), Options{
TrustAnchorsFile: &tdFile,
AppID: "test",
ControlPlaneTrustDomain: "test.example.com",
ControlPlaneNamespace: "default",
MTLSEnabled: true,
OverrideCertRequestFn: func(context.Context, []byte) ([]*x509.Certificate, error) {
return []*x509.Certificate{workloadCert}, nil
},
})
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
providerStopped := make(chan struct{})
go func() {
defer close(providerStopped)
require.NoError(t, p.Run(ctx))
}()
prov := p.(*provider)
select {
case <-prov.readyCh:
case <-time.After(time.Second):
require.FailNow(t, "provider is not ready")
}
sec, err := p.Handler(ctx)
require.NoError(t, err)
td, err := sec.CurrentTrustAnchors(ctx)
require.NoError(t, err)
assert.Equal(t, root1, td)
caBundleCh := make(chan []byte, 2)
watcherStopped := make(chan struct{})
go func() {
defer close(watcherStopped)
sec.WatchTrustAnchors(ctx, caBundleCh)
}()
assert.EventuallyWithT(t, func(c *assert.CollectT) {
curr, err := prov.sec.trustAnchors.CurrentTrustAnchors(ctx)
require.NoError(t, err)
assert.Equal(c, root1, curr)
}, time.Second, time.Millisecond)
assert.Eventually(t, func() bool {
// We put the write file inside this assert loop since we have to wait
// for the fsnotify go rountine to warm up.
require.NoError(t, os.WriteFile(tdFile, root2, 0o600))
curr, err := prov.sec.trustAnchors.CurrentTrustAnchors(ctx)
require.NoError(t, err)
return bytes.Equal(root2, curr)
}, time.Second*5, time.Millisecond*750)
t.Run("should expect that the trust bundle watch is updated", func(t *testing.T) {
select {
case got := <-caBundleCh:
assert.Equal(t, root2, got)
case <-time.After(time.Second * 3):
require.FailNow(t, "trust bundle watch is not updated in time")
}
})
cancel()
select {
case <-providerStopped:
case <-time.After(time.Second):
require.FailNow(t, "provider is not stopped")
}
})
}
func TestCurrentNamespace(t *testing.T) {
t.Run("error is namespace is not set", func(t *testing.T) {
osns, ok := os.LookupEnv("NAMESPACE")
os.Unsetenv("NAMESPACE")
t.Cleanup(func() {
if ok {
os.Setenv("NAMESPACE", osns)
}
})
ns, err := CurrentNamespaceOrError()
require.Error(t, err)
assert.Empty(t, ns)
})
t.Run("error if namespace is set but empty", func(t *testing.T) {
t.Setenv("NAMESPACE", "")
ns, err := CurrentNamespaceOrError()
require.Error(t, err)
assert.Empty(t, ns)
})
t.Run("returns namespace if set", func(t *testing.T) {
t.Setenv("NAMESPACE", "foo")
ns, err := CurrentNamespaceOrError()
require.NoError(t, err)
assert.Equal(t, "foo", ns)
})
}
func Test_isControlPlaneService(t *testing.T) {
tests := map[string]struct {
name string
exp bool
}{
"operator should be control plane service": {
name: "dapr-operator",
exp: true,
},
"sentry should be control plane service": {
name: "dapr-sentry",
exp: true,
},
"placement should be control plane service": {
name: "dapr-placement",
exp: true,
},
"sidecar injector should be control plane service": {
name: "dapr-injector",
exp: true,
},
"not a control plane service": {
name: "my-app",
exp: false,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert.Equal(t, test.exp, isControlPlaneService(test.name))
})
}
}
|
mikeee/dapr
|
pkg/security/security_test.go
|
GO
|
mit
| 6,573 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package security
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"time"
middleware "github.com/grpc-ecosystem/go-grpc-middleware"
retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"github.com/spiffe/go-spiffe/v2/spiffegrpc/grpccredentials"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"
"google.golang.org/grpc"
"github.com/dapr/dapr/pkg/diagnostics"
"github.com/dapr/dapr/pkg/modes"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
sentryToken "github.com/dapr/dapr/pkg/security/token"
cryptopem "github.com/dapr/kit/crypto/pem"
"github.com/dapr/kit/crypto/spiffe"
"github.com/dapr/kit/crypto/spiffe/trustanchors"
)
const (
sentrySignTimeout = time.Second * 3
sentryMaxRetries = 5
)
func newRequestFn(opts Options, trustAnchors trustanchors.Interface, cptd spiffeid.TrustDomain) (spiffe.RequestSVIDFn, error) {
sentryID, err := SentryID(cptd, opts.ControlPlaneNamespace)
if err != nil {
return nil, err
}
var trustDomain *string
ns := CurrentNamespace()
// If the service is a control plane service, set the trust domain to the
// control plane trust domain.
if isControlPlaneService(opts.AppID) && opts.ControlPlaneNamespace == ns {
trustDomain = &opts.ControlPlaneTrustDomain
}
// return injected identity, default id if not present
sentryIdentifier := os.Getenv("SENTRY_LOCAL_IDENTITY")
if sentryIdentifier == "" {
sentryIdentifier = opts.AppID
}
sentryAddress := opts.SentryAddress
sentryTokenFile := opts.SentryTokenFile
kubernetesMode := opts.Mode == modes.KubernetesMode
fn := func(ctx context.Context, csrDER []byte) ([]*x509.Certificate, error) {
unaryClientInterceptor := retry.UnaryClientInterceptor(
retry.WithMax(sentryMaxRetries),
retry.WithPerRetryTimeout(sentrySignTimeout),
)
if diagnostics.DefaultGRPCMonitoring.IsEnabled() {
unaryClientInterceptor = middleware.ChainUnaryClient(
unaryClientInterceptor,
diagnostics.DefaultGRPCMonitoring.UnaryClientInterceptor(),
)
}
conn, err := grpc.DialContext(ctx,
sentryAddress,
grpc.WithTransportCredentials(
grpccredentials.TLSClientCredentials(trustAnchors, tlsconfig.AuthorizeID(sentryID)),
),
grpc.WithUnaryInterceptor(unaryClientInterceptor),
grpc.WithReturnConnectionError(),
)
if err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sentry_conn")
return nil, fmt.Errorf("error establishing connection to sentry: %w", err)
}
defer conn.Close()
var token string
var tokenValidator sentryv1pb.SignCertificateRequest_TokenValidator
if sentryTokenFile != nil {
token, tokenValidator, err = sentryToken.GetSentryTokenFromFile(*sentryTokenFile)
} else {
token, tokenValidator, err = sentryToken.GetSentryToken(kubernetesMode)
}
if err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sentry_token")
return nil, fmt.Errorf("error obtaining token: %w", err)
}
req := &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE REQUEST", Bytes: csrDER,
}),
Id: sentryIdentifier,
Token: token,
Namespace: ns,
TokenValidator: tokenValidator,
}
if trustDomain != nil {
req.TrustDomain = *trustDomain
}
resp, err := sentryv1pb.NewCAClient(conn).SignCertificate(ctx, req)
if err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("sign")
return nil, fmt.Errorf("error from sentry SignCertificate: %w", err)
}
if err = resp.GetValidUntil().CheckValid(); err != nil {
diagnostics.DefaultMonitoring.MTLSWorkLoadCertRotationFailed("invalid_ts")
return nil, fmt.Errorf("error parsing ValidUntil: %w", err)
}
workloadcert, err := cryptopem.DecodePEMCertificates(resp.GetWorkloadCertificate())
if err != nil {
return nil, fmt.Errorf("error parsing newly signed certificate: %w", err)
}
return workloadcert, nil
}
return fn, nil
}
// isControlPlaneService returns true if the app ID corresponds to a Dapr
// control plane service.
func isControlPlaneService(id string) bool {
switch id {
case "dapr-operator",
"dapr-placement",
"dapr-injector",
"dapr-sentry":
return true
default:
return false
}
}
|
mikeee/dapr
|
pkg/security/sentry.go
|
GO
|
mit
| 4,855 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package spiffe
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"github.com/spiffe/go-spiffe/v2/spiffegrpc/grpccredentials"
"github.com/spiffe/go-spiffe/v2/spiffeid"
)
// Parsed is a parsed SPIFFE ID according to the Dapr SPIFFE ID path format.
type Parsed struct {
id spiffeid.ID
namespace string
appID string
}
// FromGRPCContext parses a SPIFFE ID from a gRPC context.
func FromGRPCContext(ctx context.Context) (*Parsed, bool, error) {
// Apply access control list filter
id, ok := grpccredentials.PeerIDFromContext(ctx)
if !ok {
return nil, false, nil
}
split := strings.Split(id.Path(), "/")
// Don't force match of 4 segments, since we may want to add more identifiers
// to the path in future which would otherwise break backwards compat.
if len(split) < 4 || split[0] != "" || split[1] != "ns" {
return nil, false, fmt.Errorf("malformed SPIFFE ID: %s", id.String())
}
return &Parsed{
id: id,
namespace: split[2],
appID: split[3],
}, true, nil
}
// FromStrings builds a Dapr SPIFFE ID with the given namespace and app ID in
// the given Trust Domain.
func FromStrings(td spiffeid.TrustDomain, namespace, appID string) (*Parsed, error) {
if len(td.String()) == 0 || len(namespace) == 0 || len(appID) == 0 {
return nil, errors.New("malformed SPIFFE ID")
}
id, err := spiffeid.FromSegments(td, "ns", namespace, appID)
if err != nil {
return nil, err
}
return &Parsed{
id: id,
namespace: namespace,
appID: appID,
}, nil
}
func (p *Parsed) TrustDomain() spiffeid.TrustDomain {
if p == nil {
return spiffeid.TrustDomain{}
}
return p.id.TrustDomain()
}
func (p *Parsed) AppID() string {
if p == nil {
return ""
}
return p.appID
}
func (p *Parsed) Namespace() string {
if p == nil {
return ""
}
return p.namespace
}
func (p *Parsed) URL() *url.URL {
if p == nil {
return new(url.URL)
}
return p.id.URL()
}
|
mikeee/dapr
|
pkg/security/spiffe/spiffe.go
|
GO
|
mit
| 2,479 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package spiffe
import (
"errors"
"testing"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
)
func TestFromStrings(t *testing.T) {
tests := map[string]struct {
td spiffeid.TrustDomain
appID string
ns string
expErr error
expID *Parsed
}{
"valid SPIFFE ID": {
td: spiffeid.RequireTrustDomainFromString("example.org"),
ns: "test",
appID: "app",
expID: &Parsed{
id: spiffeid.RequireFromString("spiffe://example.org/ns/test/app"),
namespace: "test",
appID: "app",
},
},
"SPIFFE ID: no namespace": {
td: spiffeid.RequireTrustDomainFromString("example.org"),
ns: "",
appID: "app",
expErr: errors.New("malformed SPIFFE ID"),
expID: nil,
},
"SPIFFE ID: no app ID": {
td: spiffeid.RequireTrustDomainFromString("example.org"),
ns: "test",
appID: "",
expErr: errors.New("malformed SPIFFE ID"),
expID: nil,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
id, err := FromStrings(test.td, test.ns, test.appID)
assert.Equal(t, test.expErr, err)
assert.Equal(t, test.expID, id)
})
}
}
|
mikeee/dapr
|
pkg/security/spiffe/spiffe_test.go
|
GO
|
mit
| 1,733 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package security
import (
"os"
"path/filepath"
"github.com/dapr/dapr/pkg/security/consts"
)
const (
kubeTknPath = "/var/run/secrets/dapr.io/sentrytoken/token"
)
// used for testing.
var rootFS = "/"
// GetAPIToken returns the value of the api token from an environment variable.
func GetAPIToken() string {
return os.Getenv(consts.APITokenEnvVar)
}
// GetAppToken returns the value of the app api token from an environment variable.
func GetAppToken() string {
return os.Getenv(consts.AppAPITokenEnvVar)
}
// getKubernetesIdentityToken returns the value of the Kubernetes identity
// token.
func getKubernetesIdentityToken() (string, error) {
b, err := os.ReadFile(filepath.Join(rootFS, kubeTknPath))
if err != nil {
return "", err
}
return string(b), err
}
|
mikeee/dapr
|
pkg/security/token.go
|
GO
|
mit
| 1,339 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package token
import (
"errors"
"fmt"
"os"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
securityConsts "github.com/dapr/dapr/pkg/security/consts"
"github.com/dapr/kit/logger"
)
const (
kubeTknPath = "/var/run/secrets/dapr.io/sentrytoken/token"
legacyKubeTknPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
)
var log = logger.NewLogger("dapr.security.token")
func GetSentryTokenFromFile(path string) (token string, validator sentryv1pb.SignCertificateRequest_TokenValidator, err error) {
b, err := os.ReadFile(path)
if err != nil {
log.Warnf("Failed to read token at path '%s': %v", path, err)
return "", sentryv1pb.SignCertificateRequest_UNKNOWN, fmt.Errorf("failed to read token at path '%s': %w", path, err)
}
if len(b) == 0 {
log.Warnf("Token at path '%s' is empty", path)
return "", sentryv1pb.SignCertificateRequest_UNKNOWN, fmt.Errorf("token at path '%s' is empty", path)
}
log.Debugf("Loaded token from path '%s' specified in the DAPR_SENTRY_TOKEN_FILE environmental variable", path)
return string(b), sentryv1pb.SignCertificateRequest_JWKS, nil
}
// GetSentryToken returns the token for authenticating with Sentry.
func GetSentryToken(allowKubernetes bool) (token string, validator sentryv1pb.SignCertificateRequest_TokenValidator, err error) {
// Check if we have a token file in the DAPR_SENTRY_TOKEN_FILE env var (for the JWKS validator)
if path, ok := os.LookupEnv(securityConsts.SentryTokenFileEnvVar); ok {
if path == "" {
return "", sentryv1pb.SignCertificateRequest_UNKNOWN, errors.New("environmental variable DAPR_SENTRY_TOKEN_FILE is set with an empty value")
}
return GetSentryTokenFromFile(path)
}
if allowKubernetes {
// Try to read a token from Kubernetes (for the Kubernetes validator)
b, err := os.ReadFile(kubeTknPath)
if err != nil && os.IsNotExist(err) {
// Attempt to use the legacy token if that exists
b, _ = os.ReadFile(legacyKubeTknPath)
if len(b) > 0 {
log.Warn("⚠️ daprd is initializing using the legacy service account token with access to Kubernetes APIs, which is discouraged. This usually happens when daprd is running against an older version of the Dapr control plane.")
}
}
if len(b) > 0 {
return string(b), sentryv1pb.SignCertificateRequest_KUBERNETES, nil
}
}
return "", sentryv1pb.SignCertificateRequest_UNKNOWN, nil
}
// HasKubernetesToken returns true if a Kubernetes token exists.
func HasKubernetesToken() bool {
_, err := os.Stat(kubeTknPath)
if err != nil {
_, err = os.Stat(legacyKubeTknPath)
if err != nil {
return false
}
}
return true
}
|
mikeee/dapr
|
pkg/security/token/token.go
|
GO
|
mit
| 3,174 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package security
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/pkg/security/consts"
"github.com/dapr/kit/ptr"
)
func TestAPIToken(t *testing.T) {
t.Run("existing token", func(t *testing.T) {
/* #nosec */
token := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1OTA1NTQ1NzMsImV4cCI6MTYyMjA5MDU3MywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.QLFl8ZqC48DOsT7SmXA794nivmqGgylzjrUu6JhXPW4"
t.Setenv(consts.APITokenEnvVar, token)
apitoken := GetAPIToken()
assert.Equal(t, token, apitoken)
})
t.Run("non-existent token", func(t *testing.T) {
token := GetAPIToken()
assert.Equal(t, "", token)
})
}
func TestAppToken(t *testing.T) {
t.Run("existing token", func(t *testing.T) {
/* #nosec */
token := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1OTA1NTQ1NzMsImV4cCI6MTYyMjA5MDU3MywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.QLFl8ZqC48DOsT7SmXA794nivmqGgylzjrUu6JhXPW4"
t.Setenv(consts.AppAPITokenEnvVar, token)
apitoken := GetAppToken()
assert.Equal(t, token, apitoken)
})
t.Run("non-existent token", func(t *testing.T) {
token := GetAppToken()
assert.Equal(t, "", token)
})
}
func TestGetKubernetesIdentityToken(t *testing.T) {
tests := map[string]struct {
kubeToken *string
boundToken *string
exp string
expErr bool
}{
"if neither token is present, expect an error": {
kubeToken: nil,
boundToken: nil,
exp: "",
expErr: true,
},
"if only kube token is present, expect error": {
kubeToken: ptr.Of("kube-token"),
boundToken: nil,
exp: "",
expErr: true,
},
"if only boundToken, expect bound token": {
kubeToken: nil,
boundToken: ptr.Of("bound-token"),
exp: "bound-token",
expErr: false,
},
"if both tokens are present, expect bound token": {
kubeToken: ptr.Of("kube-token"),
boundToken: ptr.Of("bound-token"),
exp: "bound-token",
expErr: false,
},
}
origFS := rootFS
t.Cleanup(func() {
rootFS = origFS
})
for name, test := range tests {
t.Run(name, func(t *testing.T) {
rootFS = t.TempDir()
for _, tt := range []struct {
path string
token *string
}{
{path: "/var/run/secrets/kubernetes.io/serviceaccount/token", token: test.kubeToken},
{path: "/var/run/secrets/dapr.io/sentrytoken/token", token: test.boundToken},
} {
if tt.token != nil {
path := filepath.Join(rootFS, tt.path)
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700))
require.NoError(t, os.WriteFile(path, []byte(*tt.token), 0o600))
}
}
got, err := getKubernetesIdentityToken()
assert.Equal(t, test.expErr, err != nil, err)
assert.Equal(t, test.exp, got)
})
}
}
|
mikeee/dapr
|
pkg/security/token_test.go
|
GO
|
mit
| 3,770 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package config
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
scheme "github.com/dapr/dapr/pkg/client/clientset/versioned"
daprGlobalConfig "github.com/dapr/dapr/pkg/config"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/dapr/utils"
)
const (
kubernetesServiceHostEnvVar = "KUBERNETES_SERVICE_HOST"
kubernetesConfig = "kubernetes"
selfHostedConfig = "selfhosted"
defaultWorkloadCertTTL = time.Hour * 24
defaultAllowedClockSkew = time.Minute * 15
defaultTrustDomain = "cluster.local"
// defaultDaprSystemConfigName is the default resource object name for Dapr System Config.
defaultDaprSystemConfigName = "daprsystem"
DefaultPort = 50001
// Default RootCertFilename is the filename that holds the root certificate.
DefaultRootCertFilename = "ca.crt"
// DefaultIssuerCertFilename is the filename that holds the issuer certificate.
DefaultIssuerCertFilename = "issuer.crt"
// DefaultIssuerKeyFilename is the filename that holds the issuer key.
DefaultIssuerKeyFilename = "issuer.key"
)
// Config holds the configuration for the Certificate Authority.
type Config struct {
Port int
ListenAddress string
TrustDomain string
CAStore string
WorkloadCertTTL time.Duration
AllowedClockSkew time.Duration
RootCertPath string
IssuerCertPath string
IssuerKeyPath string
Validators map[sentryv1pb.SignCertificateRequest_TokenValidator]map[string]string
DefaultValidator sentryv1pb.SignCertificateRequest_TokenValidator
Features []daprGlobalConfig.FeatureSpec
}
// FromConfigName returns a Sentry configuration based on a configuration spec.
// A default configuration is loaded in case of an error.
func FromConfigName(configName string) (conf Config, err error) {
if IsKubernetesHosted() {
conf, err = getKubernetesConfig(configName)
} else {
conf, err = getSelfhostedConfig(configName)
}
if err != nil {
err = fmt.Errorf("loading default config. couldn't find config name %q: %w", configName, err)
conf = getDefaultConfig()
}
return conf, err
}
func IsKubernetesHosted() bool {
return os.Getenv(kubernetesServiceHostEnvVar) != ""
}
func getDefaultConfig() Config {
return Config{
Port: DefaultPort,
ListenAddress: "0.0.0.0",
WorkloadCertTTL: defaultWorkloadCertTTL,
AllowedClockSkew: defaultAllowedClockSkew,
TrustDomain: defaultTrustDomain,
}
}
func getKubernetesConfig(configName string) (Config, error) {
defaultConfig := getDefaultConfig()
kubeConf := utils.GetConfig()
daprClient, err := scheme.NewForConfig(kubeConf)
if err != nil {
return defaultConfig, err
}
namespace, err := security.CurrentNamespaceOrError()
if err != nil {
return defaultConfig, err
}
if configName == "" {
configName = defaultDaprSystemConfigName
}
cfg, err := daprClient.ConfigurationV1alpha1().Configurations(namespace).Get(configName, metaV1.GetOptions{})
if apierrors.IsNotFound(err) {
return defaultConfig, errors.New("config CRD not found")
}
if err != nil {
return defaultConfig, err
}
spec, err := json.Marshal(cfg.Spec)
if err != nil {
return defaultConfig, err
}
var configSpec daprGlobalConfig.ConfigurationSpec
if err := json.Unmarshal(spec, &configSpec); err != nil {
return defaultConfig, err
}
return parseConfiguration(defaultConfig, &daprGlobalConfig.Configuration{
Spec: configSpec,
})
}
func getSelfhostedConfig(configName string) (Config, error) {
defaultConfig := getDefaultConfig()
daprConfig, err := daprGlobalConfig.LoadStandaloneConfiguration(configName)
if err != nil {
return defaultConfig, err
}
if daprConfig != nil {
return parseConfiguration(defaultConfig, daprConfig)
}
return defaultConfig, nil
}
func parseConfiguration(conf Config, daprConfig *daprGlobalConfig.Configuration) (Config, error) {
mtlsSpec := daprConfig.Spec.MTLSSpec
if mtlsSpec != nil && mtlsSpec.WorkloadCertTTL != "" {
d, err := time.ParseDuration(daprConfig.Spec.MTLSSpec.WorkloadCertTTL)
if err != nil {
return conf, fmt.Errorf("error parsing WorkloadCertTTL duration: %w", err)
}
conf.WorkloadCertTTL = d
}
if mtlsSpec != nil && mtlsSpec.AllowedClockSkew != "" {
d, err := time.ParseDuration(mtlsSpec.AllowedClockSkew)
if err != nil {
return conf, fmt.Errorf("error parsing AllowedClockSkew duration: %w", err)
}
conf.AllowedClockSkew = d
}
if daprConfig.Spec.MTLSSpec != nil && len(daprConfig.Spec.MTLSSpec.ControlPlaneTrustDomain) > 0 {
conf.TrustDomain = daprConfig.Spec.MTLSSpec.ControlPlaneTrustDomain
}
conf.Features = daprConfig.Spec.Features
// Get token validators
// In Kubernetes mode, we always allow the built-in "kubernetes" validator
// In self-hosted mode, the built-in "insecure" validator is enabled only if no other validator is configured
conf.Validators = map[sentryv1pb.SignCertificateRequest_TokenValidator]map[string]string{}
if IsKubernetesHosted() {
conf.DefaultValidator = sentryv1pb.SignCertificateRequest_KUBERNETES
conf.Validators[sentryv1pb.SignCertificateRequest_KUBERNETES] = map[string]string{}
}
if daprConfig.Spec.MTLSSpec != nil && len(daprConfig.Spec.MTLSSpec.TokenValidators) > 0 {
for _, v := range daprConfig.Spec.MTLSSpec.TokenValidators {
// Check if the name is a valid one
// We do not allow re-configuring the built-in validators
val, ok := sentryv1pb.SignCertificateRequest_TokenValidator_value[strings.ToUpper(v.Name)]
if !ok {
return conf, fmt.Errorf("invalid token validator name: '%s'; supported values: 'jwks'", v.Name)
}
switch val {
case int32(sentryv1pb.SignCertificateRequest_JWKS):
// All good - nop
case int32(sentryv1pb.SignCertificateRequest_KUBERNETES), int32(sentryv1pb.SignCertificateRequest_INSECURE):
return conf, fmt.Errorf("invalid token validator: the built-in 'kubernetes' and 'insecure' validators cannot be configured manually")
default:
return conf, fmt.Errorf("invalid token validator name: '%s'; supported values: 'jwks'", v.Name)
}
conf.Validators[sentryv1pb.SignCertificateRequest_TokenValidator(val)] = v.OptionsMap()
}
} else if !IsKubernetesHosted() {
conf.DefaultValidator = sentryv1pb.SignCertificateRequest_INSECURE
conf.Validators[sentryv1pb.SignCertificateRequest_INSECURE] = map[string]string{}
}
return conf, nil
}
|
mikeee/dapr
|
pkg/sentry/config/config.go
|
GO
|
mit
| 7,072 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package config
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
daprDaprConfig "github.com/dapr/dapr/pkg/config"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
func TestConfig(t *testing.T) {
t.Run("valid FromConfig, empty config name", func(t *testing.T) {
defaultConfig := getDefaultConfig()
c, _ := FromConfigName("")
assert.Equal(t, defaultConfig, c)
})
t.Run("valid default config, self hosted", func(t *testing.T) {
defaultConfig := getDefaultConfig()
c, _ := getSelfhostedConfig("")
assert.Equal(t, defaultConfig, c)
})
t.Run("parse configuration", func(t *testing.T) {
daprConfig := daprDaprConfig.Configuration{
Spec: daprDaprConfig.ConfigurationSpec{
MTLSSpec: &daprDaprConfig.MTLSSpec{
Enabled: true,
WorkloadCertTTL: "5s",
AllowedClockSkew: "1h",
},
},
}
defaultConfig := getDefaultConfig()
conf, err := parseConfiguration(defaultConfig, &daprConfig)
require.NoError(t, err)
assert.Equal(t, "5s", conf.WorkloadCertTTL.String())
assert.Equal(t, "1h0m0s", conf.AllowedClockSkew.String())
})
t.Run("set validators", func(t *testing.T) {
daprConfig := daprDaprConfig.Configuration{
Spec: daprDaprConfig.ConfigurationSpec{
MTLSSpec: &daprDaprConfig.MTLSSpec{
Enabled: true,
WorkloadCertTTL: "5s",
AllowedClockSkew: "1h",
},
},
}
defaultConfig := getDefaultConfig()
t.Run("kubernetes mode", func(t *testing.T) {
// Setting this env var makes Sentry think we're running on Kubernetes
t.Setenv(kubernetesServiceHostEnvVar, "TEST")
t.Run("no additional validators", func(t *testing.T) {
daprConfig.Spec.MTLSSpec.TokenValidators = nil
conf, err := parseConfiguration(defaultConfig, &daprConfig)
require.NoError(t, err)
require.Len(t, conf.Validators, 1)
require.NotNil(t, conf.Validators[sentryv1pb.SignCertificateRequest_KUBERNETES])
require.Equal(t, sentryv1pb.SignCertificateRequest_KUBERNETES, conf.DefaultValidator)
})
t.Run("additional validators", func(t *testing.T) {
daprConfig.Spec.MTLSSpec.TokenValidators = []daprDaprConfig.ValidatorSpec{
{Name: sentryv1pb.SignCertificateRequest_JWKS.String(), Options: map[any]any{"foo": "bar"}},
}
conf, err := parseConfiguration(defaultConfig, &daprConfig)
require.NoError(t, err)
require.Len(t, conf.Validators, 2)
require.NotNil(t, conf.Validators[sentryv1pb.SignCertificateRequest_KUBERNETES])
require.NotNil(t, conf.Validators[sentryv1pb.SignCertificateRequest_JWKS])
require.Equal(t, map[string]string{"foo": "bar"}, conf.Validators[sentryv1pb.SignCertificateRequest_JWKS])
require.Equal(t, sentryv1pb.SignCertificateRequest_KUBERNETES, conf.DefaultValidator)
})
})
t.Run("self-hosted mode", func(t *testing.T) {
// Deleting this env var to empty makes Sentry think we're running on self-hosted mode
t.Setenv(kubernetesServiceHostEnvVar, "")
t.Run("no additional validators", func(t *testing.T) {
daprConfig.Spec.MTLSSpec.TokenValidators = nil
conf, err := parseConfiguration(defaultConfig, &daprConfig)
require.NoError(t, err)
require.Len(t, conf.Validators, 1)
require.NotNil(t, conf.Validators[sentryv1pb.SignCertificateRequest_INSECURE])
require.Equal(t, sentryv1pb.SignCertificateRequest_INSECURE, conf.DefaultValidator)
})
t.Run("additional validators", func(t *testing.T) {
daprConfig.Spec.MTLSSpec.TokenValidators = []daprDaprConfig.ValidatorSpec{
{Name: sentryv1pb.SignCertificateRequest_JWKS.String(), Options: map[any]any{"foo": "bar"}},
}
conf, err := parseConfiguration(defaultConfig, &daprConfig)
require.NoError(t, err)
require.Len(t, conf.Validators, 1)
require.NotNil(t, conf.Validators[sentryv1pb.SignCertificateRequest_JWKS])
require.Equal(t, map[string]string{"foo": "bar"}, conf.Validators[sentryv1pb.SignCertificateRequest_JWKS])
require.Equal(t, 0, int(conf.DefaultValidator))
})
})
})
}
|
mikeee/dapr
|
pkg/sentry/config/config_test.go
|
GO
|
mit
| 4,599 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package monitoring
import (
"context"
"time"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
diagUtils "github.com/dapr/dapr/pkg/diagnostics/utils"
)
var (
// Metrics definitions.
csrReceivedTotal = stats.Int64(
"sentry/cert/sign/request_received_total",
"The number of CSRs received.",
stats.UnitDimensionless)
certSignSuccessTotal = stats.Int64(
"sentry/cert/sign/success_total",
"The number of certificates issuances that have succeeded.",
stats.UnitDimensionless)
certSignFailedTotal = stats.Int64(
"sentry/cert/sign/failure_total",
"The number of errors occurred when signing the CSR.",
stats.UnitDimensionless)
serverTLSCertIssueFailedTotal = stats.Int64(
"sentry/servercert/issue_failed_total",
"The number of server TLS certificate issuance failures.",
stats.UnitDimensionless)
issuerCertChangedTotal = stats.Int64(
"sentry/issuercert/changed_total",
"The number of issuer cert updates, when issuer cert or key is changed",
stats.UnitDimensionless)
issuerCertExpiryTimestamp = stats.Int64(
"sentry/issuercert/expiry_timestamp",
"The unix timestamp, in seconds, when issuer/root cert will expire.",
stats.UnitDimensionless)
// Metrics Tags.
failedReasonKey = tag.MustNewKey("reason")
noKeys = []tag.Key{}
)
// CertSignRequestReceived counts when CSR received.
func CertSignRequestReceived() {
stats.Record(context.Background(), csrReceivedTotal.M(1))
}
// CertSignSucceed counts succeeded cert issuance.
func CertSignSucceed() {
stats.Record(context.Background(), certSignSuccessTotal.M(1))
}
// CertSignFailed counts succeeded cert issuance.
func CertSignFailed(reason string) {
stats.RecordWithTags(
context.Background(),
diagUtils.WithTags(certSignFailedTotal.Name(), failedReasonKey, reason),
certSignFailedTotal.M(1))
}
// ServerCertIssueFailed records server cert issue failure.
func ServerCertIssueFailed(reason string) {
stats.Record(context.Background(), serverTLSCertIssueFailedTotal.M(1))
}
// IssuerCertExpiry records root cert expiry.
func IssuerCertExpiry(expiry time.Time) {
stats.Record(context.Background(), issuerCertExpiryTimestamp.M(expiry.Unix()))
}
// IssuerCertChanged records issuer credential change.
func IssuerCertChanged() {
stats.Record(context.Background(), issuerCertChangedTotal.M(1))
}
// InitMetrics initializes metrics.
func InitMetrics() error {
return view.Register(
diagUtils.NewMeasureView(csrReceivedTotal, noKeys, view.Count()),
diagUtils.NewMeasureView(certSignSuccessTotal, noKeys, view.Count()),
diagUtils.NewMeasureView(certSignFailedTotal, []tag.Key{failedReasonKey}, view.Count()),
diagUtils.NewMeasureView(serverTLSCertIssueFailedTotal, []tag.Key{failedReasonKey}, view.Count()),
diagUtils.NewMeasureView(issuerCertChangedTotal, noKeys, view.Count()),
diagUtils.NewMeasureView(issuerCertExpiryTimestamp, noKeys, view.LastValue()),
)
}
|
mikeee/dapr
|
pkg/sentry/monitoring/metrics.go
|
GO
|
mit
| 3,480 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sentry
import (
"encoding/json"
"errors"
"reflect"
"strconv"
"time"
"github.com/mitchellh/mapstructure"
)
func decodeOptions(dest any, opts map[string]string) error {
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
Result: dest,
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(
toTimeDurationHookFunc(),
),
})
if err != nil {
return err
}
return decoder.Decode(opts)
}
type Duration struct {
time.Duration
}
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
func (d *Duration) UnmarshalJSON(b []byte) error {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case float64:
d.Duration = time.Duration(value)
return nil
case string:
var err error
d.Duration, err = time.ParseDuration(value)
if err != nil {
return err
}
return nil
default:
return errors.New("invalid duration")
}
}
// This helper function is used to decode durations within a map[string]interface{} into a struct.
// It must be used in conjunction with mapstructure's DecodeHook.
// This is used in utils.DecodeMetadata to decode durations in metadata.
//
// mapstructure.NewDecoder(&mapstructure.DecoderConfig{
// DecodeHook: mapstructure.ComposeDecodeHookFunc(
// toTimeDurationHookFunc()),
// Metadata: nil,
// Result: result,
// })
func toTimeDurationHookFunc() mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
if t != reflect.TypeOf(Duration{}) && t != reflect.TypeOf(time.Duration(0)) {
return data, nil
}
switch f.Kind() {
case reflect.TypeOf(time.Duration(0)).Kind():
return data.(time.Duration), nil
case reflect.String:
var val time.Duration
if data.(string) != "" {
var err error
val, err = time.ParseDuration(data.(string))
if err != nil {
// If we can't parse the duration, try parsing it as int64 seconds
seconds, errParse := strconv.ParseInt(data.(string), 10, 0)
if errParse != nil {
return nil, errors.Join(err, errParse)
}
val = time.Duration(seconds * int64(time.Second))
}
}
if t != reflect.TypeOf(Duration{}) {
return val, nil
}
return Duration{Duration: val}, nil
case reflect.Float64:
val := time.Duration(data.(float64))
if t != reflect.TypeOf(Duration{}) {
return val, nil
}
return Duration{Duration: val}, nil
case reflect.Int64:
val := time.Duration(data.(int64))
if t != reflect.TypeOf(Duration{}) {
return val, nil
}
return Duration{Duration: val}, nil
default:
return data, nil
}
}
}
|
mikeee/dapr
|
pkg/sentry/options.go
|
GO
|
mit
| 3,276 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sentry
import (
"context"
"crypto"
"crypto/x509"
"errors"
"fmt"
"strings"
"sync/atomic"
"github.com/spiffe/go-spiffe/v2/spiffeid"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/dapr/pkg/sentry/config"
"github.com/dapr/dapr/pkg/sentry/monitoring"
"github.com/dapr/dapr/pkg/sentry/server"
"github.com/dapr/dapr/pkg/sentry/server/ca"
"github.com/dapr/dapr/pkg/sentry/server/validator"
validatorInsecure "github.com/dapr/dapr/pkg/sentry/server/validator/insecure"
validatorJWKS "github.com/dapr/dapr/pkg/sentry/server/validator/jwks"
validatorKube "github.com/dapr/dapr/pkg/sentry/server/validator/kubernetes"
"github.com/dapr/dapr/utils"
"github.com/dapr/kit/concurrency"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.sentry")
// CertificateAuthority is the interface for the Sentry Certificate Authority.
// Starts the Sentry gRPC server and signs workload certificates.
type CertificateAuthority interface {
Start(context.Context) error
}
type sentry struct {
conf config.Config
running atomic.Bool
}
// New returns a new Sentry Certificate Authority instance.
func New(conf config.Config) CertificateAuthority {
return &sentry{
conf: conf,
}
}
// Start the server in background.
func (s *sentry) Start(parentCtx context.Context) error {
ctx, cancel := context.WithCancel(parentCtx)
defer cancel()
// If the server is already running, return an error
if !s.running.CompareAndSwap(false, true) {
return errors.New("CertificateAuthority server is already running")
}
ns := security.CurrentNamespace()
camngr, err := ca.New(ctx, s.conf)
if err != nil {
return fmt.Errorf("error creating CA: %w", err)
}
log.Info("CA certificate key pair ready")
provider, err := security.New(ctx, security.Options{
ControlPlaneTrustDomain: s.conf.TrustDomain,
ControlPlaneNamespace: ns,
AppID: "dapr-sentry",
TrustAnchors: camngr.TrustAnchors(),
MTLSEnabled: true,
// Override the request source to our in memory CA since _we_ are sentry!
OverrideCertRequestFn: func(ctx context.Context, csrDER []byte) ([]*x509.Certificate, error) {
csr, csrErr := x509.ParseCertificateRequest(csrDER)
if csrErr != nil {
monitoring.ServerCertIssueFailed("invalid_csr")
return nil, csrErr
}
certs, csrErr := camngr.SignIdentity(ctx, &ca.SignRequest{
PublicKey: csr.PublicKey.(crypto.PublicKey),
SignatureAlgorithm: csr.SignatureAlgorithm,
TrustDomain: s.conf.TrustDomain,
Namespace: ns,
AppID: "dapr-sentry",
})
if csrErr != nil {
monitoring.ServerCertIssueFailed("ca_error")
return nil, csrErr
}
return certs, nil
},
})
if err != nil {
return fmt.Errorf("error creating security: %s", err)
}
vals, err := s.getValidators(ctx)
if err != nil {
return err
}
// Start all background processes
runners := concurrency.NewRunnerManager(
provider.Run,
func(ctx context.Context) error {
sec, secErr := provider.Handler(ctx)
if secErr != nil {
return secErr
}
return server.Start(ctx, server.Options{
Port: s.conf.Port,
Security: sec,
Validators: vals,
DefaultValidator: s.conf.DefaultValidator,
CA: camngr,
})
},
)
for name, val := range vals {
log.Infof("Using validator '%s'", strings.ToLower(name.String()))
runners.Add(val.Start)
}
err = runners.Run(ctx)
if err != nil {
log.Fatalf("Error running Sentry: %v", err)
}
return nil
}
func (s *sentry) getValidators(ctx context.Context) (map[sentryv1pb.SignCertificateRequest_TokenValidator]validator.Validator, error) {
validators := make(map[sentryv1pb.SignCertificateRequest_TokenValidator]validator.Validator, len(s.conf.Validators))
for validatorID, opts := range s.conf.Validators {
switch validatorID {
case sentryv1pb.SignCertificateRequest_KUBERNETES:
td, err := spiffeid.TrustDomainFromString(s.conf.TrustDomain)
if err != nil {
return nil, err
}
sentryID, err := security.SentryID(td, security.CurrentNamespace())
if err != nil {
return nil, err
}
val, err := validatorKube.New(ctx, validatorKube.Options{
RestConfig: utils.GetConfig(),
SentryID: sentryID,
ControlPlaneNS: security.CurrentNamespace(),
})
if err != nil {
return nil, err
}
log.Info("Adding validator 'kubernetes' with Sentry ID: " + sentryID.String())
validators[validatorID] = val
case sentryv1pb.SignCertificateRequest_INSECURE:
log.Info("Adding validator 'insecure'")
validators[validatorID] = validatorInsecure.New()
case sentryv1pb.SignCertificateRequest_JWKS:
td, err := spiffeid.TrustDomainFromString(s.conf.TrustDomain)
if err != nil {
return nil, err
}
sentryID, err := security.SentryID(td, security.CurrentNamespace())
if err != nil {
return nil, err
}
obj := validatorJWKS.Options{
SentryID: sentryID,
}
err = decodeOptions(&obj, opts)
if err != nil {
return nil, fmt.Errorf("failed to decode validator options: %w", err)
}
val, err := validatorJWKS.New(ctx, obj)
if err != nil {
return nil, err
}
log.Info("Adding validator 'jwks' with Sentry ID: " + sentryID.String())
validators[validatorID] = val
}
}
if len(validators) == 0 {
// Should never hit this, as the config is already sanitized
return nil, errors.New("invalid validators")
}
return validators, nil
}
|
mikeee/dapr
|
pkg/sentry/sentry.go
|
GO
|
mit
| 6,103 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"time"
)
// Bundle is the bundle of certificates and keys used by the CA.
type Bundle struct {
TrustAnchors []byte
IssChainPEM []byte
IssKeyPEM []byte
IssChain []*x509.Certificate
IssKey any
}
func GenerateBundle(rootKey crypto.Signer, trustDomain string, allowedClockSkew time.Duration, overrideCATTL *time.Duration) (Bundle, error) {
rootCert, err := generateRootCert(trustDomain, allowedClockSkew, overrideCATTL)
if err != nil {
return Bundle{}, fmt.Errorf("failed to generate root cert: %w", err)
}
rootCertDER, err := x509.CreateCertificate(rand.Reader, rootCert, rootCert, rootKey.Public(), rootKey)
if err != nil {
return Bundle{}, fmt.Errorf("failed to sign root certificate: %w", err)
}
trustAnchors := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootCertDER})
issKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return Bundle{}, err
}
issKeyDer, err := x509.MarshalPKCS8PrivateKey(issKey)
if err != nil {
return Bundle{}, err
}
issKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: issKeyDer})
issCert, err := generateIssuerCert(trustDomain, allowedClockSkew, overrideCATTL)
if err != nil {
return Bundle{}, fmt.Errorf("failed to generate issuer cert: %w", err)
}
issCertDER, err := x509.CreateCertificate(rand.Reader, issCert, rootCert, &issKey.PublicKey, rootKey)
if err != nil {
return Bundle{}, fmt.Errorf("failed to sign issuer cert: %w", err)
}
issCertPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: issCertDER})
issCert, err = x509.ParseCertificate(issCertDER)
if err != nil {
return Bundle{}, err
}
return Bundle{
TrustAnchors: trustAnchors,
IssChainPEM: issCertPEM,
IssKeyPEM: issKeyPEM,
IssChain: []*x509.Certificate{issCert},
IssKey: issKey,
}, nil
}
|
mikeee/dapr
|
pkg/sentry/server/ca/bundle.go
|
GO
|
mit
| 2,518 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"k8s.io/client-go/kubernetes"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/dapr/pkg/security/spiffe"
"github.com/dapr/dapr/pkg/sentry/config"
"github.com/dapr/dapr/pkg/sentry/monitoring"
"github.com/dapr/dapr/utils"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.sentry.ca")
// SignRequest signs a certificate request with the issuer certificate.
type SignRequest struct {
// Public key of the certificate request.
PublicKey crypto.PublicKey
// Signature of the certificate request.
SignatureAlgorithm x509.SignatureAlgorithm
// TrustDomain is the trust domain of the client.
TrustDomain string
// Namespace is the namespace of the client.
Namespace string
// AppID is the app id of the client.
AppID string
// Optional DNS names to add to the certificate.
DNS []string
}
// Signer is the interface for the CA.
type Signer interface {
// SignIdentity signs a certificate request with the issuer certificate. Note
// that this does not include the trust anchors, and does not perform _any_
// kind of validation on the request; authz should already have happened
// before this point.
// If given true, then the certificate duration will be given the largest
// possible according to the signing certificate.
SignIdentity(context.Context, *SignRequest) ([]*x509.Certificate, error)
// TrustAnchors returns the trust anchors for the CA in PEM format.
TrustAnchors() []byte
}
// store is the interface for the trust bundle backend store.
type store interface {
store(context.Context, Bundle) error
get(context.Context) (Bundle, bool, error)
}
// ca is the implementation of the CA Signer.
type ca struct {
bundle Bundle
config config.Config
}
func New(ctx context.Context, conf config.Config) (Signer, error) {
var castore store
if config.IsKubernetesHosted() {
log.Info("Using kubernetes secret store for trust bundle storage")
client, err := kubernetes.NewForConfig(utils.GetConfig())
if err != nil {
return nil, err
}
castore = &kube{
config: conf,
namespace: security.CurrentNamespace(),
client: client,
}
} else {
log.Info("Using local file system for trust bundle storage")
castore = &selfhosted{config: conf}
}
bundle, ok, err := castore.get(ctx)
if err != nil {
return nil, err
}
if !ok {
log.Info("Root and issuer certs not found: generating self signed CA")
rootKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
bundle, err = GenerateBundle(rootKey, conf.TrustDomain, conf.AllowedClockSkew, nil)
if err != nil {
return nil, err
}
log.Info("Root and issuer certs generated")
if err := castore.store(ctx, bundle); err != nil {
return nil, err
}
log.Info("Self-signed certs generated and persisted successfully")
monitoring.IssuerCertChanged()
} else {
log.Info("Root and issuer certs found: using existing certs")
}
monitoring.IssuerCertExpiry(bundle.IssChain[0].NotAfter)
return &ca{
bundle: bundle,
config: conf,
}, nil
}
func (c *ca) SignIdentity(ctx context.Context, req *SignRequest) ([]*x509.Certificate, error) {
td, err := spiffeid.TrustDomainFromString(req.TrustDomain)
if err != nil {
return nil, err
}
spiffeID, err := spiffe.FromStrings(td, req.Namespace, req.AppID)
if err != nil {
return nil, err
}
tmpl, err := generateWorkloadCert(req.SignatureAlgorithm, c.config.WorkloadCertTTL, c.config.AllowedClockSkew, spiffeID)
if err != nil {
return nil, err
}
tmpl.DNSNames = append(tmpl.DNSNames, req.DNS...)
certDER, err := x509.CreateCertificate(rand.Reader, tmpl, c.bundle.IssChain[0], req.PublicKey, c.bundle.IssKey)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
return nil, err
}
return append([]*x509.Certificate{cert}, c.bundle.IssChain...), nil
}
// TODO: Remove this method in v1.12 since it is not used any more.
func (c *ca) TrustAnchors() []byte {
return c.bundle.TrustAnchors
}
|
mikeee/dapr
|
pkg/sentry/server/ca/ca.go
|
GO
|
mit
| 4,712 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/pkg/sentry/config"
"github.com/dapr/kit/crypto/pem"
)
func TestNew(t *testing.T) {
t.Run("if no existing bundle exist, new should generate a new bundle", func(t *testing.T) {
os.Setenv("NAMESPACE", "dapr-test")
t.Cleanup(func() {
os.Unsetenv("NAMESPACE")
})
dir := t.TempDir()
rootCertPath := filepath.Join(dir, "root.cert")
issuerCertPath := filepath.Join(dir, "issuer.cert")
issuerKeyPath := filepath.Join(dir, "issuer.key")
config := config.Config{
RootCertPath: rootCertPath,
IssuerCertPath: issuerCertPath,
IssuerKeyPath: issuerKeyPath,
TrustDomain: "test.example.com",
}
_, err := New(context.Background(), config)
require.NoError(t, err)
require.FileExists(t, rootCertPath)
require.FileExists(t, issuerCertPath)
require.FileExists(t, issuerKeyPath)
rootCert, err := os.ReadFile(rootCertPath)
require.NoError(t, err)
issuerCert, err := os.ReadFile(issuerCertPath)
require.NoError(t, err)
issuerKey, err := os.ReadFile(issuerKeyPath)
require.NoError(t, err)
rootCertX509, err := pem.DecodePEMCertificates(rootCert)
require.NoError(t, err)
require.Len(t, rootCertX509, 1)
assert.Equal(t, []string{"test.example.com"}, rootCertX509[0].Subject.Organization)
issuerCertX509, err := pem.DecodePEMCertificates(issuerCert)
require.NoError(t, err)
require.Len(t, issuerCertX509, 1)
assert.Equal(t, []string{"spiffe://test.example.com/ns/dapr-test/dapr-sentry"}, issuerCertX509[0].Subject.Organization)
issuerKeyPK, err := pem.DecodePEMPrivateKey(issuerKey)
require.NoError(t, err)
require.NoError(t, issuerCertX509[0].CheckSignatureFrom(rootCertX509[0]))
ok, err := pem.PublicKeysEqual(issuerCertX509[0].PublicKey, issuerKeyPK.Public())
require.NoError(t, err)
assert.True(t, ok)
})
t.Run("if existing pool exists, new should load the existing pool", func(t *testing.T) {
dir := t.TempDir()
rootCertPath := filepath.Join(dir, "root.cert")
issuerCertPath := filepath.Join(dir, "issuer.cert")
issuerKeyPath := filepath.Join(dir, "issuer.key")
config := config.Config{
RootCertPath: rootCertPath,
IssuerCertPath: issuerCertPath,
IssuerKeyPath: issuerKeyPath,
}
rootPEM, rootCrt, _, rootPK := genCrt(t, "root", nil, nil)
rootPEM2, _, _, _ := genCrt(t, "root2", nil, nil)
int1PEM, int1Crt, _, int1PK := genCrt(t, "int1", rootCrt, rootPK)
int2PEM, int2Crt, int2PKPEM, int2PK := genCrt(t, "int2", int1Crt, int1PK)
//nolint:gocritic
rootFileContents := append(rootPEM, rootPEM2...)
//nolint:gocritic
issuerFileContents := append(int2PEM, int1PEM...)
issuerKeyFileContents := int2PKPEM
require.NoError(t, os.WriteFile(rootCertPath, rootFileContents, 0o600))
require.NoError(t, os.WriteFile(issuerCertPath, issuerFileContents, 0o600))
require.NoError(t, os.WriteFile(issuerKeyPath, issuerKeyFileContents, 0o600))
caImp, err := New(context.Background(), config)
require.NoError(t, err)
rootCert, err := os.ReadFile(rootCertPath)
require.NoError(t, err)
issuerCert, err := os.ReadFile(issuerCertPath)
require.NoError(t, err)
issuerKey, err := os.ReadFile(issuerKeyPath)
require.NoError(t, err)
assert.Equal(t, rootFileContents, rootCert)
assert.Equal(t, issuerFileContents, issuerCert)
assert.Equal(t, issuerKeyFileContents, issuerKey)
assert.Equal(t, Bundle{
TrustAnchors: rootFileContents,
IssChainPEM: issuerFileContents,
IssKeyPEM: issuerKeyFileContents,
IssChain: []*x509.Certificate{int2Crt, int1Crt},
IssKey: int2PK,
}, caImp.(*ca).bundle)
})
}
func TestSignIdentity(t *testing.T) {
t.Run("singing identity should return a signed certificate with chain", func(t *testing.T) {
dir := t.TempDir()
rootCertPath := filepath.Join(dir, "root.cert")
issuerCertPath := filepath.Join(dir, "issuer.cert")
issuerKeyPath := filepath.Join(dir, "issuer.key")
config := config.Config{
RootCertPath: rootCertPath,
IssuerCertPath: issuerCertPath,
IssuerKeyPath: issuerKeyPath,
}
rootPEM, rootCrt, _, rootPK := genCrt(t, "root", nil, nil)
rootPEM2, _, _, _ := genCrt(t, "root2", nil, nil)
int1PEM, int1Crt, _, int1PK := genCrt(t, "int1", rootCrt, rootPK)
int2PEM, int2Crt, int2PKPEM, _ := genCrt(t, "int2", int1Crt, int1PK)
//nolint:gocritic
rootFileContents := append(rootPEM, rootPEM2...)
//nolint:gocritic
issuerFileContents := append(int2PEM, int1PEM...)
issuerKeyFileContents := int2PKPEM
require.NoError(t, os.WriteFile(rootCertPath, rootFileContents, 0o600))
require.NoError(t, os.WriteFile(issuerCertPath, issuerFileContents, 0o600))
require.NoError(t, os.WriteFile(issuerKeyPath, issuerKeyFileContents, 0o600))
ca, err := New(context.Background(), config)
require.NoError(t, err)
clientPK, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
clientCert, err := ca.SignIdentity(context.Background(), &SignRequest{
PublicKey: clientPK.Public(),
SignatureAlgorithm: x509.ECDSAWithSHA256,
TrustDomain: "example.test.dapr.io",
Namespace: "my-test-namespace",
AppID: "my-app-id",
DNS: []string{"my-app-id.my-test-namespace.svc.cluster.local", "example.com"},
})
require.NoError(t, err)
require.Len(t, clientCert, 3)
assert.Equal(t, clientCert[1], int2Crt)
assert.Equal(t, clientCert[2], int1Crt)
assert.Len(t, clientCert[0].DNSNames, 2)
assert.ElementsMatch(t, clientCert[0].DNSNames, []string{"my-app-id.my-test-namespace.svc.cluster.local", "example.com"})
require.Len(t, clientCert[0].URIs, 1)
assert.Equal(t, "spiffe://example.test.dapr.io/ns/my-test-namespace/my-app-id", clientCert[0].URIs[0].String())
require.NoError(t, clientCert[0].CheckSignatureFrom(int2Crt))
})
}
|
mikeee/dapr
|
pkg/sentry/server/ca/ca_test.go
|
GO
|
mit
| 6,550 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"math/big"
"net/url"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/dapr/pkg/security/spiffe"
)
const (
// defaultCATTL is the default CA certificate TTL.
defaultCATTL = 365 * 24 * time.Hour
)
// serialNumber returns the serial number of the certificate.
func serialNumber() (*big.Int, error) {
serialNumLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNum, err := rand.Int(rand.Reader, serialNumLimit)
if err != nil {
return nil, fmt.Errorf("error generating serial number: %w", err)
}
return serialNum, nil
}
// generateBaseCert returns a base non-CA cert that can be made a workload or CA cert
// By adding subjects, key usage and additional properties.
func generateBaseCert(ttl, skew time.Duration) (*x509.Certificate, error) {
serNum, err := serialNumber()
if err != nil {
return nil, err
}
now := time.Now().UTC()
// Allow for clock skew with the NotBefore validity bound.
notBefore := now.Add(-1 * skew)
notAfter := now.Add(ttl)
return &x509.Certificate{
SerialNumber: serNum,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
}, nil
}
// generateRootCert returns a CA root x509 Certificate.
func generateRootCert(trustDomain string, skew time.Duration, overrideTTL *time.Duration) (*x509.Certificate, error) {
ttl := defaultCATTL
if overrideTTL != nil {
ttl = *overrideTTL
}
cert, err := generateBaseCert(ttl, skew)
if err != nil {
return nil, err
}
cert.KeyUsage |= x509.KeyUsageCertSign
cert.Subject = pkix.Name{Organization: []string{trustDomain}}
cert.IsCA = true
cert.BasicConstraintsValid = true
cert.SignatureAlgorithm = x509.ECDSAWithSHA256
return cert, nil
}
// generateIssuerCert returns a CA issuing x509 Certificate.
func generateIssuerCert(trustDomain string, skew time.Duration, overrideTTL *time.Duration) (*x509.Certificate, error) {
ttl := defaultCATTL
if overrideTTL != nil {
ttl = *overrideTTL
}
cert, err := generateBaseCert(ttl, skew)
if err != nil {
return nil, err
}
td, err := spiffeid.TrustDomainFromString(trustDomain)
if err != nil {
return nil, err
}
sentryID, err := spiffe.FromStrings(td, security.CurrentNamespace(), "dapr-sentry")
if err != nil {
return nil, fmt.Errorf("failed to generate sentry ID: %w", err)
}
cert.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign
cert.Subject = pkix.Name{Organization: []string{sentryID.URL().String()}}
cert.IsCA = true
cert.BasicConstraintsValid = true
cert.SignatureAlgorithm = x509.ECDSAWithSHA256
return cert, nil
}
// generateWorkloadCert returns a CA issuing x509 Certificate.
func generateWorkloadCert(sig x509.SignatureAlgorithm, ttl, skew time.Duration, id *spiffe.Parsed) (*x509.Certificate, error) {
cert, err := generateBaseCert(ttl, skew)
if err != nil {
return nil, err
}
cert.ExtKeyUsage = append(cert.ExtKeyUsage, x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth)
cert.SignatureAlgorithm = sig
cert.URIs = []*url.URL{id.URL()}
return cert, nil
}
|
mikeee/dapr
|
pkg/sentry/server/ca/cert.go
|
GO
|
mit
| 3,729 |
//go:build unit
// +build unit
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
"crypto/x509"
"github.com/dapr/dapr/pkg/sentry/server/ca"
)
type Fake struct {
signIdentityFn func(context.Context, *ca.SignRequest) ([]*x509.Certificate, error)
trustAnchorsFn func() []byte
}
func New() *Fake {
return &Fake{
signIdentityFn: func(context.Context, *ca.SignRequest) ([]*x509.Certificate, error) {
return nil, nil
},
trustAnchorsFn: func() []byte {
return nil
},
}
}
func (f *Fake) WithSignIdentity(fn func(context.Context, *ca.SignRequest) ([]*x509.Certificate, error)) *Fake {
f.signIdentityFn = fn
return f
}
func (f *Fake) WithTrustAnchors(fn func() []byte) *Fake {
f.trustAnchorsFn = fn
return f
}
func (f *Fake) SignIdentity(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
return f.signIdentityFn(ctx, req)
}
func (f *Fake) TrustAnchors() []byte {
return f.trustAnchorsFn()
}
|
mikeee/dapr
|
pkg/sentry/server/ca/fake/fake.go
|
GO
|
mit
| 1,481 |
//go:build unit
// +build unit
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"testing"
"github.com/dapr/dapr/pkg/sentry/server/ca"
)
func TestNew(t *testing.T) {
var _ ca.Signer = New()
}
|
mikeee/dapr
|
pkg/sentry/server/ca/fake/fake_test.go
|
GO
|
mit
| 732 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"context"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"github.com/dapr/dapr/pkg/sentry/config"
)
const (
// TrustBundleK8sName is the name of the kubernetes secret that holds the
// issuer certificate key pair and trust anchors, and configmap that holds
// the trust anchors.
TrustBundleK8sName = "dapr-trust-bundle" /* #nosec */
)
// kube is a store that uses Kubernetes as the secret store.
type kube struct {
config config.Config
namespace string
client kubernetes.Interface
}
func (k *kube) get(ctx context.Context) (Bundle, bool, error) {
s, err := k.client.CoreV1().Secrets(k.namespace).Get(ctx, TrustBundleK8sName, metav1.GetOptions{})
if err != nil {
return Bundle{}, false, err
}
trustAnchors, ok := s.Data[filepath.Base(k.config.RootCertPath)]
if !ok {
return Bundle{}, false, nil
}
issChainPEM, ok := s.Data[filepath.Base(k.config.IssuerCertPath)]
if !ok {
return Bundle{}, false, nil
}
issKeyPEM, ok := s.Data[filepath.Base(k.config.IssuerKeyPath)]
if !ok {
return Bundle{}, false, nil
}
// Ensure ConfigMap is up to date also.
cm, err := k.client.CoreV1().ConfigMaps(k.namespace).Get(ctx, TrustBundleK8sName, metav1.GetOptions{})
if err != nil {
return Bundle{}, false, err
}
if cm.Data[filepath.Base(k.config.RootCertPath)] != string(trustAnchors) {
return Bundle{}, false, nil
}
bundle, err := verifyBundle(trustAnchors, issChainPEM, issKeyPEM)
if err != nil {
return Bundle{}, false, err
}
return bundle, true, nil
}
func (k *kube) store(ctx context.Context, bundle Bundle) error {
s, err := k.client.CoreV1().Secrets(k.namespace).Get(ctx, TrustBundleK8sName, metav1.GetOptions{})
if err != nil {
return err
}
s.Data = map[string][]byte{
filepath.Base(k.config.RootCertPath): bundle.TrustAnchors,
filepath.Base(k.config.IssuerCertPath): bundle.IssChainPEM,
filepath.Base(k.config.IssuerKeyPath): bundle.IssKeyPEM,
}
_, err = k.client.CoreV1().Secrets(k.namespace).Update(ctx, s, metav1.UpdateOptions{})
if err != nil {
return err
}
cm, err := k.client.CoreV1().ConfigMaps(k.namespace).Get(ctx, TrustBundleK8sName, metav1.GetOptions{})
if err != nil {
return err
}
cm.Data = map[string]string{
filepath.Base(k.config.RootCertPath): string(bundle.TrustAnchors),
}
_, err = k.client.CoreV1().ConfigMaps(k.namespace).Update(ctx, cm, metav1.UpdateOptions{})
if err != nil {
return err
}
return nil
}
|
mikeee/dapr
|
pkg/sentry/server/ca/kube.go
|
GO
|
mit
| 3,049 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"context"
"crypto/x509"
"testing"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/fake"
"github.com/dapr/dapr/pkg/sentry/config"
)
func TestKube_get(t *testing.T) {
rootPEM, rootCrt, _, rootPK := genCrt(t, "root", nil, nil)
//nolint:dogsled
rootPEM2, _, _, _ := genCrt(t, "root2", nil, nil)
intPEM, intCrt, intPKPEM, intPK := genCrt(t, "int", rootCrt, rootPK)
tests := map[string]struct {
sec *corev1.Secret
cm *corev1.ConfigMap
expBundle Bundle
expOK bool
expErr bool
}{
"if secret doesn't exist, expect error": {
sec: nil,
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{"ca.crt": string(rootPEM)},
},
expBundle: Bundle{},
expOK: false,
expErr: true,
},
"if configmap doesn't exist, expect error": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"ca.crt": rootPEM,
"tls.key": intPKPEM,
"tls.crt": intPEM,
},
},
cm: nil,
expBundle: Bundle{},
expOK: false,
expErr: true,
},
"if secret doesn't include ca.crt, expect not ok": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"tls.key": intPKPEM,
"tls.crt": intPEM,
},
},
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{"ca.crt": string(rootPEM)},
},
expBundle: Bundle{},
expOK: false,
expErr: false,
},
"if secret doesn't include tls.crt, expect not ok": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"ca.crt": rootPEM,
"tls.key": intPKPEM,
},
},
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{"ca.crt": string(rootPEM)},
},
expBundle: Bundle{},
expOK: false,
expErr: false,
},
"if secret doesn't include tls.key, expect not ok": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"ca.crt": rootPEM,
"tls.crt": intPEM,
},
},
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{"ca.crt": string(rootPEM)},
},
expBundle: Bundle{},
expOK: false,
expErr: false,
},
"if configmap doesn't include ca.crt, expect not ok": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"ca.crt": rootPEM,
"tls.crt": intPEM,
"tls.key": intPKPEM,
},
},
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{},
},
expBundle: Bundle{},
expOK: false,
expErr: false,
},
"if trust anchors do not match, expect not ok": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"ca.crt": rootPEM,
"tls.crt": intPEM,
"tls.key": intPKPEM,
},
},
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{"ca.crt": string(rootPEM) + "\n" + string(rootPEM2)},
},
expBundle: Bundle{},
expOK: false,
expErr: false,
},
"if bundle fails to verify, expect error": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"ca.crt": rootPEM2,
"tls.crt": intPEM,
"tls.key": intPKPEM,
},
},
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{"ca.crt": string(rootPEM2)},
},
expBundle: Bundle{},
expOK: false,
expErr: true,
},
"if bundle is valid, expect ok and return bundle": {
sec: &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string][]byte{
"ca.crt": rootPEM,
"tls.crt": intPEM,
"tls.key": intPKPEM,
},
},
cm: &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-trust-bundle",
Namespace: "dapr-system-test",
},
Data: map[string]string{"ca.crt": string(rootPEM)},
},
expBundle: Bundle{
TrustAnchors: rootPEM,
IssChainPEM: intPEM,
IssKeyPEM: intPKPEM,
IssChain: []*x509.Certificate{intCrt},
IssKey: intPK,
},
expOK: true,
expErr: false,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
var intObj []runtime.Object
if test.sec != nil {
intObj = append(intObj, test.sec)
}
if test.cm != nil {
intObj = append(intObj, test.cm)
}
fakeclient := fake.NewSimpleClientset(intObj...)
k := &kube{
client: fakeclient,
config: config.Config{
RootCertPath: "ca.crt",
IssuerCertPath: "tls.crt",
IssuerKeyPath: "tls.key",
},
namespace: "dapr-system-test",
}
bundle, ok, err := k.get(context.Background())
assert.Equal(t, test.expErr, err != nil, "%v", err)
assert.Equal(t, test.expOK, ok, "ok")
assert.Equal(t, test.expBundle, bundle)
})
}
}
|
mikeee/dapr
|
pkg/sentry/server/ca/kube_test.go
|
GO
|
mit
| 6,816 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"context"
"fmt"
"os"
"github.com/dapr/dapr/pkg/sentry/config"
)
// selfSigned is a store that uses the file system as the secret store.
type selfhosted struct {
config config.Config
}
func (s *selfhosted) store(_ context.Context, bundle Bundle) error {
for _, f := range []struct {
name string
data []byte
}{
{s.config.RootCertPath, bundle.TrustAnchors},
{s.config.IssuerCertPath, bundle.IssChainPEM},
{s.config.IssuerKeyPath, bundle.IssKeyPEM},
} {
if err := os.WriteFile(f.name, f.data, 0o600); err != nil {
return err
}
}
return nil
}
func (s *selfhosted) get(_ context.Context) (Bundle, bool, error) {
trustAnchors, err := os.ReadFile(s.config.RootCertPath)
if os.IsNotExist(err) {
return Bundle{}, false, nil
}
if err != nil {
return Bundle{}, false, err
}
issChainPEM, err := os.ReadFile(s.config.IssuerCertPath)
if os.IsNotExist(err) {
return Bundle{}, false, nil
}
if err != nil {
return Bundle{}, false, err
}
issKeyPEM, err := os.ReadFile(s.config.IssuerKeyPath)
if os.IsNotExist(err) {
return Bundle{}, false, nil
}
if err != nil {
return Bundle{}, false, err
}
bundle, err := verifyBundle(trustAnchors, issChainPEM, issKeyPEM)
if err != nil {
return Bundle{}, false, fmt.Errorf("failed to verify CA bundle: %w", err)
}
return bundle, true, nil
}
|
mikeee/dapr
|
pkg/sentry/server/ca/selfhosted.go
|
GO
|
mit
| 1,909 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"context"
"crypto/x509"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dapr/dapr/pkg/sentry/config"
)
var writePerm os.FileMode
func init() {
writePerm = 0o600
if runtime.GOOS == "windows" {
writePerm = 0o666
}
}
func TestSelhosted_store(t *testing.T) {
t.Run("storing file should write to disk with correct permissions", func(t *testing.T) {
rootFile := filepath.Join(t.TempDir(), "root.pem")
issuerFile := filepath.Join(t.TempDir(), "issuer.pem")
keyFile := filepath.Join(t.TempDir(), "key.pem")
s := &selfhosted{
config: config.Config{
RootCertPath: rootFile,
IssuerCertPath: issuerFile,
IssuerKeyPath: keyFile,
},
}
require.NoError(t, s.store(context.Background(), Bundle{
TrustAnchors: []byte("root"),
IssChainPEM: []byte("issuer"),
IssKeyPEM: []byte("key"),
}))
require.FileExists(t, rootFile)
require.FileExists(t, issuerFile)
require.FileExists(t, keyFile)
info, err := os.Stat(rootFile)
require.NoError(t, err)
assert.Equal(t, writePerm, info.Mode().Perm())
info, err = os.Stat(issuerFile)
require.NoError(t, err)
assert.Equal(t, writePerm, info.Mode().Perm())
info, err = os.Stat(keyFile)
require.NoError(t, err)
assert.Equal(t, writePerm, info.Mode().Perm())
b, err := os.ReadFile(rootFile)
require.NoError(t, err)
assert.Equal(t, "root", string(b))
b, err = os.ReadFile(issuerFile)
require.NoError(t, err)
assert.Equal(t, "issuer", string(b))
b, err = os.ReadFile(keyFile)
require.NoError(t, err)
assert.Equal(t, "key", string(b))
})
}
func TestSelfhosted_get(t *testing.T) {
rootPEM, rootCrt, _, rootPK := genCrt(t, "root", nil, nil)
intPEM, intCrt, intPKPEM, intPK := genCrt(t, "int", rootCrt, rootPK)
tests := map[string]struct {
rootFile *[]byte
issuer *[]byte
key *[]byte
expBundle Bundle
expOk bool
expErr bool
}{
"if no files exist, return not ok": {
rootFile: nil,
issuer: nil,
key: nil,
expBundle: Bundle{},
expOk: false,
expErr: false,
},
"if root file doesn't exist, return not ok": {
rootFile: nil,
issuer: &intPEM,
key: &intPKPEM,
expBundle: Bundle{},
expOk: false,
expErr: false,
},
"if issuer file doesn't exist, return not ok": {
rootFile: &rootPEM,
issuer: nil,
key: &intPKPEM,
expBundle: Bundle{},
expOk: false,
expErr: false,
},
"if issuer key file doesn't exist, return not ok": {
rootFile: &rootPEM,
issuer: &intPEM,
key: nil,
expBundle: Bundle{},
expOk: false,
expErr: false,
},
"if failed to verify CA bundle, return error": {
rootFile: &intPEM,
issuer: &intPEM,
key: &intPKPEM,
expBundle: Bundle{},
expOk: false,
expErr: true,
},
"if all files exist, return certs": {
rootFile: &rootPEM,
issuer: &intPEM,
key: &intPKPEM,
expBundle: Bundle{
TrustAnchors: rootPEM,
IssChainPEM: intPEM,
IssKeyPEM: intPKPEM,
IssChain: []*x509.Certificate{intCrt},
IssKey: intPK,
},
expOk: true,
expErr: false,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
dir := t.TempDir()
rootFile := filepath.Join(dir, "root.pem")
issuerFile := filepath.Join(dir, "issuer.pem")
keyFile := filepath.Join(dir, "key.pem")
s := &selfhosted{
config: config.Config{
RootCertPath: rootFile,
IssuerCertPath: issuerFile,
IssuerKeyPath: keyFile,
},
}
if test.rootFile != nil {
require.NoError(t, os.WriteFile(rootFile, *test.rootFile, writePerm))
}
if test.issuer != nil {
require.NoError(t, os.WriteFile(issuerFile, *test.issuer, writePerm))
}
if test.key != nil {
require.NoError(t, os.WriteFile(keyFile, *test.key, writePerm))
}
got, ok, err := s.get(context.Background())
assert.Equal(t, test.expBundle, got)
assert.Equal(t, test.expOk, ok)
assert.Equal(t, test.expErr, err != nil, "%v", err)
})
}
}
|
mikeee/dapr
|
pkg/sentry/server/ca/selfhosted_test.go
|
GO
|
mit
| 4,697 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"crypto/x509"
"errors"
"fmt"
"github.com/dapr/kit/crypto/pem"
)
// verifyBundle verifies issuer certificate key pair, and trust anchor set.
// Returns error if any of the verification fails.
// Returned CA bundle is ready for sentry.
func verifyBundle(trustAnchors, issChainPEM, issKeyPEM []byte) (Bundle, error) {
trustAnchorsX509, err := pem.DecodePEMCertificates(trustAnchors)
if err != nil {
return Bundle{}, fmt.Errorf("failed to decode trust anchors: %w", err)
}
for _, cert := range trustAnchorsX509 {
if err = cert.CheckSignatureFrom(cert); err != nil {
return Bundle{}, fmt.Errorf("certificate in trust anchor is not self-signed: %w", err)
}
}
// Strip comments from anchor certificates.
trustAnchors = nil
for _, cert := range trustAnchorsX509 {
var trustAnchor []byte
trustAnchor, err = pem.EncodeX509(cert)
if err != nil {
return Bundle{}, fmt.Errorf("failed to re-encode trust anchor: %w", err)
}
trustAnchors = append(trustAnchors, trustAnchor...)
}
issChain, err := pem.DecodePEMCertificatesChain(issChainPEM)
if err != nil {
return Bundle{}, err
}
// If we are using an intermediate certificate for signing, ensure we do not
// add the root CA to the issuer chain.
if len(issChain) > 1 {
lastCert := issChain[len(issChain)-1]
if err = lastCert.CheckSignatureFrom(lastCert); err == nil {
issChain = issChain[:len(issChain)-1]
}
}
// Ensure intermediate certificate is valid for signing.
if !issChain[0].IsCA && !issChain[0].BasicConstraintsValid &&
issChain[0].KeyUsage&x509.KeyUsageCertSign == 0 {
return Bundle{}, errors.New("intermediate certificate is not valid for signing")
}
// Re-encode the issuer chain to ensure it contains only the issuer chain,
// and strip out PEM comments since we don't want to send them to the client.
issChainPEM, err = pem.EncodeX509Chain(issChain)
if err != nil {
return Bundle{}, err
}
issKey, err := pem.DecodePEMPrivateKey(issKeyPEM)
if err != nil {
return Bundle{}, err
}
issKeyPEM, err = pem.EncodePrivateKey(issKey)
if err != nil {
return Bundle{}, err
}
// Ensure issuer key matches the issuer certificate.
ok, err := pem.PublicKeysEqual(issKey.Public(), issChain[0].PublicKey)
if err != nil {
return Bundle{}, err
}
if !ok {
return Bundle{}, errors.New("issuer key does not match issuer certificate")
}
// Ensure issuer chain belongs to one of the trust anchors.
trustAnchorPool := x509.NewCertPool()
for _, cert := range trustAnchorsX509 {
trustAnchorPool.AddCert(cert)
}
intPool := x509.NewCertPool()
for _, cert := range issChain[1:] {
intPool.AddCert(cert)
}
if _, err := issChain[0].Verify(x509.VerifyOptions{
Roots: trustAnchorPool,
Intermediates: intPool,
}); err != nil {
return Bundle{}, fmt.Errorf("issuer chain does not belong to trust anchors: %w", err)
}
return Bundle{
TrustAnchors: trustAnchors,
IssChainPEM: issChainPEM,
IssChain: issChain,
IssKeyPEM: issKeyPEM,
IssKey: issKey,
}, nil
}
|
mikeee/dapr
|
pkg/sentry/server/ca/validate.go
|
GO
|
mit
| 3,601 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func genCrt(t *testing.T,
name string,
signCrt *x509.Certificate,
signKey crypto.Signer,
) ([]byte, *x509.Certificate, []byte, crypto.Signer) {
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
require.NoError(t, err)
tmpl := x509.Certificate{
Subject: pkix.Name{Organization: []string{name}},
SerialNumber: serialNumber,
IsCA: true,
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour),
}
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
if signCrt == nil {
signCrt = &tmpl
}
if signKey == nil {
signKey = pk
}
crtDER, err := x509.CreateCertificate(rand.Reader, &tmpl, signCrt, pk.Public(), signKey)
require.NoError(t, err)
crt, err := x509.ParseCertificate(crtDER)
require.NoError(t, err)
crtPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: crtDER})
pkDER, err := x509.MarshalPKCS8PrivateKey(pk)
require.NoError(t, err)
pkPEM := pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY", Bytes: pkDER,
})
return crtPEM, crt, pkPEM, pk
}
func joinPEM(crts ...[]byte) []byte {
var b []byte
for _, crt := range crts {
b = append(b, crt...)
}
return b
}
func TestVerifyBundle(t *testing.T) {
rootPEM, rootCrt, _, rootPK := genCrt(t, "root", nil, nil)
//nolint:dogsled
rootBPEM, _, _, _ := genCrt(t, "rootB", nil, nil)
int1PEM, int1Crt, int1PKPEM, int1PK := genCrt(t, "int1", rootCrt, rootPK)
int2PEM, int2Crt, int2PKPEM, int2PK := genCrt(t, "int2", int1Crt, int1PK)
tests := map[string]struct {
issChainPEM []byte
issKeyPEM []byte
trustBundle []byte
expErr bool
expBundle Bundle
}{
"if issuer chain pem empty, expect error": {
issChainPEM: nil,
issKeyPEM: int1PKPEM,
trustBundle: rootPEM,
expErr: true,
expBundle: Bundle{},
},
"if issuer key pem empty, expect error": {
issChainPEM: int1PEM,
issKeyPEM: nil,
trustBundle: rootPEM,
expErr: true,
expBundle: Bundle{},
},
"if issuer trust bundle pem empty, expect error": {
issChainPEM: int1PEM,
issKeyPEM: int1PKPEM,
trustBundle: nil,
expErr: true,
expBundle: Bundle{},
},
"invalid issuer chain PEM should error": {
issChainPEM: []byte("invalid"),
issKeyPEM: int1PKPEM,
trustBundle: rootPEM,
expErr: true,
expBundle: Bundle{},
},
"invalid issuer key PEM should error": {
issChainPEM: int1PEM,
issKeyPEM: []byte("invalid"),
trustBundle: rootPEM,
expErr: true,
expBundle: Bundle{},
},
"invalid trust bundle PEM should error": {
issChainPEM: int1PEM,
issKeyPEM: int1PKPEM,
trustBundle: []byte("invalid"),
expErr: true,
expBundle: Bundle{},
},
"if issuer chain is in wrong order, expect error": {
issChainPEM: joinPEM(int1PEM, int2PEM),
issKeyPEM: int2PKPEM,
trustBundle: joinPEM(rootPEM, rootBPEM),
expErr: true,
expBundle: Bundle{},
},
"if issuer key does not belong to issuer certificate, expect error": {
issChainPEM: joinPEM(int2PEM, int1PEM),
issKeyPEM: int1PKPEM,
trustBundle: joinPEM(rootPEM, rootBPEM),
expErr: true,
expBundle: Bundle{},
},
"if trust anchors contains non root certificates, exp error": {
issChainPEM: joinPEM(int2PEM, int1PEM),
issKeyPEM: int2PKPEM,
trustBundle: joinPEM(rootPEM, rootBPEM, int1PEM),
expErr: true,
expBundle: Bundle{},
},
"if issuer chain doesn't belong to trust anchors, expect error": {
issChainPEM: joinPEM(int2PEM, int1PEM),
issKeyPEM: int2PKPEM,
trustBundle: joinPEM(rootBPEM),
expErr: true,
expBundle: Bundle{},
},
"valid chain should not error": {
issChainPEM: int1PEM,
issKeyPEM: int1PKPEM,
trustBundle: rootPEM,
expErr: false,
expBundle: Bundle{
TrustAnchors: rootPEM,
IssChainPEM: joinPEM(int1PEM),
IssKeyPEM: int1PKPEM,
IssChain: []*x509.Certificate{int1Crt},
IssKey: int1PK,
},
},
"valid long chain should not error": {
issChainPEM: joinPEM(int2PEM, int1PEM),
issKeyPEM: int2PKPEM,
trustBundle: joinPEM(rootPEM, rootBPEM),
expErr: false,
expBundle: Bundle{
TrustAnchors: joinPEM(rootPEM, rootBPEM),
IssChainPEM: joinPEM(int2PEM, int1PEM),
IssKeyPEM: int2PKPEM,
IssChain: []*x509.Certificate{int2Crt, int1Crt},
IssKey: int2PK,
},
},
"is root certificate in chain, expect to be removed": {
issChainPEM: joinPEM(int2PEM, int1PEM, rootPEM),
issKeyPEM: int2PKPEM,
trustBundle: joinPEM(rootPEM, rootBPEM),
expErr: false,
expBundle: Bundle{
TrustAnchors: joinPEM(rootPEM, rootBPEM),
IssChainPEM: joinPEM(int2PEM, int1PEM),
IssKeyPEM: int2PKPEM,
IssChain: []*x509.Certificate{int2Crt, int1Crt},
IssKey: int2PK,
},
},
"comments are removed from parsed issuer chain, private key and trust anchors": {
issChainPEM: joinPEM(
[]byte("# this is a comment\n"),
int2PEM,
[]byte("# this is a comment\n"),
int1PEM,
[]byte("# this is a comment\n"),
),
issKeyPEM: joinPEM(
[]byte("# this is a comment\n"),
int2PKPEM,
[]byte("# this is a comment\n"),
),
trustBundle: joinPEM(
[]byte("# this is a comment\n"),
rootPEM,
[]byte("# this is a comment\n"),
rootBPEM,
[]byte("# this is a comment\n"),
),
expErr: false,
expBundle: Bundle{
TrustAnchors: joinPEM(rootPEM, rootBPEM),
IssChainPEM: joinPEM(int2PEM, int1PEM),
IssKeyPEM: int2PKPEM,
IssChain: []*x509.Certificate{int2Crt, int1Crt},
IssKey: int2PK,
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
Bundle, err := verifyBundle(test.trustBundle, test.issChainPEM, test.issKeyPEM)
assert.Equal(t, test.expErr, err != nil, "%v", err)
require.Equal(t, test.expBundle, Bundle)
})
}
}
|
mikeee/dapr
|
pkg/sentry/server/ca/validate_test.go
|
GO
|
mit
| 6,840 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"net"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/security"
"github.com/dapr/dapr/pkg/sentry/monitoring"
"github.com/dapr/dapr/pkg/sentry/server/ca"
"github.com/dapr/dapr/pkg/sentry/server/validator"
secpem "github.com/dapr/kit/crypto/pem"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.sentry.server")
// Options is the configuration for the server.
type Options struct {
// Port is the port that the server will listen on.
Port int
// ListenAddress is the address that the server will listen on.
ListenAddress string
// Security is the security handler for the server.
Security security.Handler
// Validator are the client authentication validator.
Validators map[sentryv1pb.SignCertificateRequest_TokenValidator]validator.Validator
// Name of the default validator to use if the request doesn't specify one.
DefaultValidator sentryv1pb.SignCertificateRequest_TokenValidator
// CA is the certificate authority which signs client certificates.
CA ca.Signer
}
// server is the gRPC server for the Sentry service.
type server struct {
vals map[sentryv1pb.SignCertificateRequest_TokenValidator]validator.Validator
defaultValidator sentryv1pb.SignCertificateRequest_TokenValidator
ca ca.Signer
}
// Start starts the server. Blocks until the context is cancelled.
func Start(ctx context.Context, opts Options) error {
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", opts.ListenAddress, opts.Port))
if err != nil {
return fmt.Errorf("could not listen on port %d: %w", opts.Port, err)
}
// No client auth because we auth based on the client SignCertificateRequest.
srv := grpc.NewServer(opts.Security.GRPCServerOptionNoClientAuth())
s := &server{
vals: opts.Validators,
defaultValidator: opts.DefaultValidator,
ca: opts.CA,
}
sentryv1pb.RegisterCAServer(srv, s)
errCh := make(chan error, 1)
go func() {
log.Infof("Running gRPC server on port %d", opts.Port)
if err := srv.Serve(lis); err != nil {
errCh <- fmt.Errorf("failed to serve: %w", err)
return
}
errCh <- nil
}()
<-ctx.Done()
log.Info("Shutting down gRPC server")
srv.GracefulStop()
return <-errCh
}
// SignCertificate implements the SignCertificate gRPC method.
func (s *server) SignCertificate(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error) {
monitoring.CertSignRequestReceived()
resp, err := s.signCertificate(ctx, req)
if err != nil {
monitoring.CertSignFailed("sign")
return nil, err
}
monitoring.CertSignSucceed()
return resp, nil
}
func (s *server) signCertificate(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (*sentryv1pb.SignCertificateResponse, error) {
validator := s.defaultValidator
if req.GetTokenValidator() != sentryv1pb.SignCertificateRequest_UNKNOWN && req.GetTokenValidator().String() != "" {
validator = req.GetTokenValidator()
}
namespace := req.GetNamespace()
if validator == sentryv1pb.SignCertificateRequest_UNKNOWN {
log.Debugf("Validator '%s' is not known for %s/%s", validator.String(), namespace, req.GetId())
return nil, status.Error(codes.InvalidArgument, "a validator name must be specified in this environment")
}
if _, ok := s.vals[validator]; !ok {
log.Debugf("Validator '%s' is not enabled for %s/%s", validator.String(), namespace, req.GetId())
return nil, status.Error(codes.InvalidArgument, "the requested validator is not enabled")
}
log.Debugf("Processing SignCertificate request for %s/%s (validator: %s)", namespace, req.GetId(), validator.String())
trustDomain, err := s.vals[validator].Validate(ctx, req)
if err != nil {
log.Debugf("Failed to validate request for %s/%s: %s", namespace, req.GetId(), err)
return nil, status.Error(codes.PermissionDenied, err.Error())
}
der, _ := pem.Decode(req.GetCertificateSigningRequest())
if der == nil {
log.Debugf("Invalid CSR: PEM block is nil for %s/%s", namespace, req.GetId())
return nil, status.Error(codes.InvalidArgument, "invalid certificate signing request")
}
// TODO: @joshvanl: Before v1.12, daprd was sending CSRs with the PEM block type "CERTIFICATE"
// After 1.14, allow only "CERTIFICATE REQUEST"
if der.Type != "CERTIFICATE REQUEST" && der.Type != "CERTIFICATE" {
log.Debugf("Invalid CSR: PEM block type is invalid for %s/%s: %s", namespace, req.GetId(), der.Type)
return nil, status.Error(codes.InvalidArgument, "invalid certificate signing request")
}
csr, err := x509.ParseCertificateRequest(der.Bytes)
if err != nil {
log.Debugf("Failed to parse CSR for %s/%s: %v", namespace, req.GetId(), err)
return nil, status.Errorf(codes.InvalidArgument, "failed to parse certificate signing request: %v", err)
}
if csr.CheckSignature() != nil {
log.Debugf("Invalid CSR: invalid signature for %s/%s", namespace, req.GetId())
return nil, status.Error(codes.InvalidArgument, "invalid signature")
}
var dns []string
switch {
case req.GetNamespace() == security.CurrentNamespace() && req.GetId() == "dapr-injector":
dns = []string{fmt.Sprintf("dapr-sidecar-injector.%s.svc", req.GetNamespace())}
case req.GetNamespace() == security.CurrentNamespace() && req.GetId() == "dapr-operator":
dns = []string{fmt.Sprintf("dapr-webhook.%s.svc", req.GetNamespace())}
}
chain, err := s.ca.SignIdentity(ctx, &ca.SignRequest{
PublicKey: csr.PublicKey,
SignatureAlgorithm: csr.SignatureAlgorithm,
TrustDomain: trustDomain.String(),
Namespace: namespace,
AppID: req.GetId(),
DNS: dns,
})
if err != nil {
log.Errorf("Error signing identity: %v", err)
return nil, status.Error(codes.Internal, "failed to sign certificate")
}
chainPEM, err := secpem.EncodeX509Chain(chain)
if err != nil {
log.Errorf("Error encoding certificate chain: %v", err)
return nil, status.Error(codes.Internal, "failed to encode certificate chain")
}
log.Debugf("Successfully signed certificate for %s/%s", namespace, req.GetId())
return &sentryv1pb.SignCertificateResponse{
WorkloadCertificate: chainPEM,
// We only populate the trust chain and valid until for clients pre-1.12.
// TODO: Remove fields in 1.14.
TrustChainCertificates: [][]byte{s.ca.TrustAnchors()},
ValidUntil: timestamppb.New(chain[0].NotAfter),
}, nil
}
|
mikeee/dapr
|
pkg/sentry/server/server.go
|
GO
|
mit
| 7,151 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package server
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"testing"
"time"
"github.com/phayes/freeport"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/security"
securityfake "github.com/dapr/dapr/pkg/security/fake"
"github.com/dapr/dapr/pkg/sentry/server/ca"
cafake "github.com/dapr/dapr/pkg/sentry/server/ca/fake"
"github.com/dapr/dapr/pkg/sentry/server/validator"
validatorfake "github.com/dapr/dapr/pkg/sentry/server/validator/fake"
)
func TestRun(t *testing.T) {
pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{}, pk)
require.NoError(t, err)
csrPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csr})
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
require.NoError(t, err)
tmpl := &x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{Organization: []string{"test"}},
NotBefore: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
NotAfter: time.Date(2023, 1, 1, 1, 1, 1, 0, time.UTC),
}
crt, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pk.Public(), pk)
require.NoError(t, err)
crtX509, err := x509.ParseCertificate(crt)
require.NoError(t, err)
crtPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: crt})
tests := map[string]struct {
sec security.Handler
val validator.Validator
ca ca.Signer
req *sentryv1pb.SignCertificateRequest
expResp *sentryv1pb.SignCertificateResponse
expErr bool
expCode codes.Code
}{
"request where signing returns bad certificate chain should error": {
sec: securityfake.New().WithGRPCServerOptionNoClientAuthFn(func() grpc.ServerOption {
return grpc.Creds(insecure.NewCredentials())
}),
val: validatorfake.New().WithValidateFn(func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.RequireTrustDomainFromString("test"), nil
}),
ca: cafake.New().WithSignIdentity(func(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
return []*x509.Certificate{}, nil
}).WithTrustAnchors(func() []byte {
return []byte("my-trust-anchors")
}),
req: &sentryv1pb.SignCertificateRequest{
Id: "my-id",
Token: "my-token",
TrustDomain: "my-trust-domain",
Namespace: "my-namespace",
CertificateSigningRequest: csrPEM,
TokenValidator: sentryv1pb.SignCertificateRequest_TokenValidator(-1),
},
expResp: nil,
expErr: true,
expCode: codes.Internal,
},
"request which signing cert should error": {
sec: securityfake.New().WithGRPCServerOptionNoClientAuthFn(func() grpc.ServerOption {
return grpc.Creds(insecure.NewCredentials())
}),
val: validatorfake.New().WithValidateFn(func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.RequireTrustDomainFromString("test"), nil
}),
ca: cafake.New().WithSignIdentity(func(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
return nil, fmt.Errorf("signing error")
}).WithTrustAnchors(func() []byte {
return []byte("my-trust-anchors")
}),
req: &sentryv1pb.SignCertificateRequest{
Id: "my-id",
Token: "my-token",
TrustDomain: "my-trust-domain",
Namespace: "my-namespace",
CertificateSigningRequest: csrPEM,
TokenValidator: sentryv1pb.SignCertificateRequest_TokenValidator(-1),
},
expResp: nil,
expErr: true,
expCode: codes.Internal,
},
"request with a bad csr should fail": {
sec: securityfake.New().WithGRPCServerOptionNoClientAuthFn(func() grpc.ServerOption {
return grpc.Creds(insecure.NewCredentials())
}),
val: validatorfake.New().WithValidateFn(func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.RequireTrustDomainFromString("my-trust-domain"), nil
}),
ca: cafake.New().WithSignIdentity(func(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
return []*x509.Certificate{crtX509}, nil
}).WithTrustAnchors(func() []byte {
return []byte("my-trust-anchors")
}),
req: &sentryv1pb.SignCertificateRequest{
Id: "my-id",
Token: "my-token",
TrustDomain: "my-trust-domain",
Namespace: "my-namespace",
CertificateSigningRequest: []byte("bad csr"),
TokenValidator: sentryv1pb.SignCertificateRequest_TokenValidator(-1),
},
expResp: nil,
expErr: true,
expCode: codes.InvalidArgument,
},
"request which fails validation should return error": {
sec: securityfake.New().WithGRPCServerOptionNoClientAuthFn(func() grpc.ServerOption {
return grpc.Creds(insecure.NewCredentials())
}),
val: validatorfake.New().WithValidateFn(func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.TrustDomain{}, fmt.Errorf("validation error")
}),
ca: cafake.New().WithSignIdentity(func(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
return []*x509.Certificate{crtX509}, nil
}).WithTrustAnchors(func() []byte {
return []byte("my-trust-anchors")
}),
req: &sentryv1pb.SignCertificateRequest{
Id: "my-id",
Token: "my-token",
TrustDomain: "my-trust-domain",
Namespace: "my-namespace",
CertificateSigningRequest: csrPEM,
TokenValidator: sentryv1pb.SignCertificateRequest_TokenValidator(-1),
},
expResp: nil,
expErr: true,
expCode: codes.PermissionDenied,
},
"valid request should return valid response": {
sec: securityfake.New().WithGRPCServerOptionNoClientAuthFn(func() grpc.ServerOption {
return grpc.Creds(insecure.NewCredentials())
}),
val: validatorfake.New().WithValidateFn(func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.RequireTrustDomainFromString("my-trust-domain"), nil
}),
ca: cafake.New().WithSignIdentity(func(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
return []*x509.Certificate{crtX509}, nil
}).WithTrustAnchors(func() []byte {
return []byte("my-trust-anchors")
}),
req: &sentryv1pb.SignCertificateRequest{
Id: "my-id",
Token: "my-token",
TrustDomain: "my-trust-domain",
Namespace: "my-namespace",
CertificateSigningRequest: csrPEM,
TokenValidator: sentryv1pb.SignCertificateRequest_TokenValidator(-1),
},
expResp: &sentryv1pb.SignCertificateResponse{
WorkloadCertificate: crtPEM,
TrustChainCertificates: [][]byte{[]byte("my-trust-anchors")},
ValidUntil: timestamppb.New(time.Date(2023, 1, 1, 1, 1, 1, 0, time.UTC)),
},
expErr: false,
expCode: codes.OK,
},
"if request is for injector, expect injector dns name": {
sec: securityfake.New().WithGRPCServerOptionNoClientAuthFn(func() grpc.ServerOption {
return grpc.Creds(insecure.NewCredentials())
}),
val: validatorfake.New().WithValidateFn(func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.RequireTrustDomainFromString("my-trust-domain"), nil
}),
ca: cafake.New().WithSignIdentity(func(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
assert.Equal(t, []string{"dapr-sidecar-injector.default.svc"}, req.DNS)
return []*x509.Certificate{crtX509}, nil
}).WithTrustAnchors(func() []byte {
return []byte("my-trust-anchors")
}),
req: &sentryv1pb.SignCertificateRequest{
Id: "dapr-injector",
Token: "my-token",
TrustDomain: "my-trust-domain",
Namespace: "default",
CertificateSigningRequest: csrPEM,
TokenValidator: sentryv1pb.SignCertificateRequest_TokenValidator(-1),
},
expResp: &sentryv1pb.SignCertificateResponse{
WorkloadCertificate: crtPEM,
TrustChainCertificates: [][]byte{[]byte("my-trust-anchors")},
ValidUntil: timestamppb.New(time.Date(2023, 1, 1, 1, 1, 1, 0, time.UTC)),
},
expErr: false,
expCode: codes.OK,
},
"if request is for operator, expect operator dns name": {
sec: securityfake.New().WithGRPCServerOptionNoClientAuthFn(func() grpc.ServerOption {
return grpc.Creds(insecure.NewCredentials())
}),
val: validatorfake.New().WithValidateFn(func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.RequireTrustDomainFromString("my-trust-domain"), nil
}),
ca: cafake.New().WithSignIdentity(func(ctx context.Context, req *ca.SignRequest) ([]*x509.Certificate, error) {
assert.Equal(t, []string{"dapr-webhook.default.svc"}, req.DNS)
return []*x509.Certificate{crtX509}, nil
}).WithTrustAnchors(func() []byte {
return []byte("my-trust-anchors")
}),
req: &sentryv1pb.SignCertificateRequest{
Id: "dapr-operator",
Token: "my-token",
TrustDomain: "my-trust-domain",
Namespace: "default",
CertificateSigningRequest: csrPEM,
TokenValidator: sentryv1pb.SignCertificateRequest_TokenValidator(-1),
},
expResp: &sentryv1pb.SignCertificateResponse{
WorkloadCertificate: crtPEM,
TrustChainCertificates: [][]byte{[]byte("my-trust-anchors")},
ValidUntil: timestamppb.New(time.Date(2023, 1, 1, 1, 1, 1, 0, time.UTC)),
},
expErr: false,
expCode: codes.OK,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
port, err := freeport.GetFreePort()
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
opts := Options{
Port: port,
Security: test.sec,
Validators: map[sentryv1pb.SignCertificateRequest_TokenValidator]validator.Validator{
// This is an invalid validator that is just used for tests
-1: test.val,
},
CA: test.ca,
}
serverClosed := make(chan struct{})
t.Cleanup(func() {
cancel()
select {
case <-serverClosed:
case <-time.After(3 * time.Second):
assert.Fail(t, "server did not close in time")
}
})
go func() {
defer close(serverClosed)
require.NoError(t, Start(ctx, opts))
}()
require.Eventually(t, func() bool {
var conn net.Conn
conn, err = net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err == nil {
conn.Close()
}
return err == nil
}, time.Second, 10*time.Millisecond)
conn, err := grpc.DialContext(ctx, fmt.Sprintf("127.0.0.1:%d", port), grpc.WithTransportCredentials(insecure.NewCredentials()))
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, conn.Close())
})
client := sentryv1pb.NewCAClient(conn)
resp, err := client.SignCertificate(ctx, test.req)
assert.Equal(t, test.expErr, err != nil, "%v", err)
assert.Equalf(t, test.expCode, status.Code(err), "unexpected error code: %v", err)
require.Equalf(t, test.expResp == nil, resp == nil, "expected response to be nil: %v", resp)
if test.expResp != nil {
assert.Equal(t, test.expResp.GetTrustChainCertificates(), resp.GetTrustChainCertificates())
assert.Equal(t, test.expResp.GetValidUntil(), resp.GetValidUntil())
assert.Equal(t, test.expResp.GetWorkloadCertificate(), resp.GetWorkloadCertificate())
}
})
}
}
|
mikeee/dapr
|
pkg/sentry/server/server_test.go
|
GO
|
mit
| 12,895 |
//go:build unit
// +build unit
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
"github.com/spiffe/go-spiffe/v2/spiffeid"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
// Fake implements the validator.Interface. It is used in tests.
type Fake struct {
validateFn func(context.Context, *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error)
startFn func(context.Context) error
}
func New() *Fake {
return &Fake{
startFn: func(context.Context) error {
return nil
},
validateFn: func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return spiffeid.TrustDomain{}, nil
},
}
}
func (f *Fake) WithValidateFn(fn func(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error)) *Fake {
f.validateFn = fn
return f
}
func (f *Fake) WithStartFn(fn func(ctx context.Context) error) *Fake {
f.startFn = fn
return f
}
func (f *Fake) Validate(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return f.validateFn(ctx, req)
}
func (f *Fake) Start(ctx context.Context) error {
return f.startFn(ctx)
}
|
mikeee/dapr
|
pkg/sentry/server/validator/fake/fake.go
|
GO
|
mit
| 1,708 |
//go:build unit
// +build unit
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"testing"
"github.com/dapr/dapr/pkg/sentry/server/validator"
)
func TestNew(t *testing.T) {
var _ validator.Validator = New()
}
|
mikeee/dapr
|
pkg/sentry/server/validator/fake/fake_test.go
|
GO
|
mit
| 749 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package insecure
import (
"context"
"github.com/spiffe/go-spiffe/v2/spiffeid"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/sentry/server/validator"
"github.com/dapr/dapr/pkg/sentry/server/validator/internal"
)
// insecure implements the validator.Interface. It doesn't perform any authentication on requests.
// It is meant to be used in self-hosted scenarios where Dapr is running on a trusted environment.
type insecure struct{}
func New() validator.Validator {
return new(insecure)
}
func (s *insecure) Start(ctx context.Context) error {
<-ctx.Done()
return nil
}
func (s *insecure) Validate(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
return internal.Validate(ctx, req)
}
|
mikeee/dapr
|
pkg/sentry/server/validator/insecure/insecure.go
|
GO
|
mit
| 1,337 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package insecure
import (
"testing"
"github.com/dapr/dapr/pkg/sentry/server/validator"
)
func TestInsecure(t *testing.T) {
var _ validator.Validator = New()
}
|
mikeee/dapr
|
pkg/sentry/server/validator/insecure/insecure_test.go
|
GO
|
mit
| 726 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package internal
import (
"context"
"errors"
"fmt"
"github.com/spiffe/go-spiffe/v2/spiffeid"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/validation"
)
// Validate validates the common rules for all requests.
func Validate(_ context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
err := errors.Join(
validation.ValidateSelfHostedAppID(req.GetId()),
appIDLessOrEqualTo64Characters(req.GetId()),
csrIsRequired(req.GetCertificateSigningRequest()),
namespaceIsRequired(req.GetNamespace()),
)
if err != nil {
return spiffeid.TrustDomain{}, fmt.Errorf("invalid request: %w", err)
}
var td spiffeid.TrustDomain
if req.GetTrustDomain() == "" {
// Default to public trust domain if not specified.
td, err = spiffeid.TrustDomainFromString("public")
return td, err
}
td, err = spiffeid.TrustDomainFromString(req.GetTrustDomain())
return td, err
}
func appIDLessOrEqualTo64Characters(appID string) error {
if len(appID) > 64 {
return errors.New("app ID must be 64 characters or less")
}
return nil
}
func csrIsRequired(csr []byte) error {
if len(csr) == 0 {
return errors.New("CSR is required")
}
return nil
}
func namespaceIsRequired(namespace string) error {
if namespace == "" {
return errors.New("namespace is required")
}
return nil
}
|
mikeee/dapr
|
pkg/sentry/server/validator/internal/common.go
|
GO
|
mit
| 1,913 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package internal
import (
"context"
"errors"
"fmt"
"testing"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
func TestValidate(t *testing.T) {
tests := map[string]struct {
req *sentryv1pb.SignCertificateRequest
expTD spiffeid.TrustDomain
expErr error
}{
"if all errors with app ID empty, return errors": {
req: &sentryv1pb.SignCertificateRequest{
Id: "",
Namespace: "",
CertificateSigningRequest: nil,
},
expTD: spiffeid.TrustDomain{},
expErr: fmt.Errorf("invalid request: %w",
errors.Join(
errors.New("parameter app-id cannot be empty"),
errors.New("CSR is required"),
errors.New("namespace is required"),
)),
},
"if all errors with app ID over 64 chars long, return errors": {
req: &sentryv1pb.SignCertificateRequest{
Id: "12345678901234567890123456789012345678901234567890123456789012345",
Namespace: "",
CertificateSigningRequest: nil,
},
expTD: spiffeid.TrustDomain{},
expErr: fmt.Errorf("invalid request: %w",
errors.Join(
errors.New("app ID must be 64 characters or less"),
errors.New("CSR is required"),
errors.New("namespace is required"),
)),
},
"if no errors with trust domain empty, return default trust domain": {
req: &sentryv1pb.SignCertificateRequest{
Id: "my-app-id",
CertificateSigningRequest: []byte("csr"),
Namespace: "my-namespace",
TrustDomain: "",
},
expTD: spiffeid.RequireTrustDomainFromString("public"),
expErr: nil,
},
"if no errors with trust domain not empty, return trust domain": {
req: &sentryv1pb.SignCertificateRequest{
Id: "my-app-id",
CertificateSigningRequest: []byte("csr"),
Namespace: "my-namespace",
TrustDomain: "example.com",
},
expTD: spiffeid.RequireTrustDomainFromString("example.com"),
expErr: nil,
},
"if no errors with trust domain which is invalid, return error": {
req: &sentryv1pb.SignCertificateRequest{
Id: "my-app-id",
CertificateSigningRequest: []byte("csr"),
Namespace: "my-namespace",
TrustDomain: "example com",
},
expTD: spiffeid.TrustDomain{},
expErr: errors.New("trust domain characters are limited to lowercase letters, numbers, dots, dashes, and underscores"),
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
td, err := Validate(context.Background(), test.req)
assert.Equal(t, test.expTD, td)
assert.Equal(t, test.expErr, err)
})
}
}
|
mikeee/dapr
|
pkg/sentry/server/validator/internal/common_test.go
|
GO
|
mit
| 3,345 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jwks
import (
"context"
"errors"
"fmt"
"time"
"github.com/lestrrat-go/jwx/v2/jws"
"github.com/lestrrat-go/jwx/v2/jwt"
"github.com/spiffe/go-spiffe/v2/spiffeid"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/sentry/server/validator"
"github.com/dapr/dapr/pkg/sentry/server/validator/internal"
"github.com/dapr/kit/jwkscache"
"github.com/dapr/kit/logger"
)
var log = logger.NewLogger("dapr.sentry.identity.jwks")
type Options struct {
// SPIFFE ID of Sentry.
SentryID spiffeid.ID `mapstructure:"-"`
// Location of the JWKS: a URL, path on local file, or the actual JWKS (optionally base64-encoded)
Source string `mapstructure:"source"`
// Optional CA certificate to trust. Can be a path to a local file or an actual, PEM-encoded certificate
CACertificate string `mapstructure:"caCertificate"`
// Minimum interval before the JWKS can be refrehsed if fetched from a HTTP(S) endpoint.
MinRefreshInterval time.Duration `mapstructure:"minRefreshInterval"`
// Timeout for network requests.
RequestTimeout time.Duration `mapstructure:"requestTimeout"`
}
// jwks implements the validator.Interface.
// It validates the request by reviewing a JWT signed by a key included in a JWKS.
// The JWT must be signed by a key included in the JWKS and must contain the following claims:
// - aud: must include the audience of Sentry (SPIFFE ID)
// - sub: must include the SPIFFE ID of the requestor
type jwks struct {
sentryAudience string
cache *jwkscache.JWKSCache
}
func New(ctx context.Context, opts Options) (validator.Validator, error) {
cache := jwkscache.NewJWKSCache(opts.Source, log)
// Set options
if opts.MinRefreshInterval > time.Second {
cache.SetMinRefreshInterval(opts.MinRefreshInterval)
}
if opts.RequestTimeout > time.Millisecond {
cache.SetRequestTimeout(opts.RequestTimeout)
}
if opts.CACertificate != "" {
cache.SetCACertificate(opts.CACertificate)
}
return &jwks{
sentryAudience: opts.SentryID.String(),
cache: cache,
}, nil
}
func (j *jwks) Start(ctx context.Context) error {
// Start the cache. Note this is a blocking call
err := j.cache.Start(ctx)
if err != nil {
return err
}
return nil
}
func (j *jwks) Validate(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
if req.GetToken() == "" {
return spiffeid.TrustDomain{}, errors.New("the request does not contain a token")
}
if err := j.cache.WaitForCacheReady(ctx); err != nil {
return spiffeid.TrustDomain{}, errors.New("jwks validator not ready")
}
// Validate the internal request
// This also returns the trust domain.
td, err := internal.Validate(ctx, req)
if err != nil {
return spiffeid.TrustDomain{}, err
}
// Construct the expected value for the subject, which is the SPIFFE ID of the requestor
sub, err := spiffeid.FromSegments(td, "ns", req.GetNamespace(), req.GetId())
if err != nil {
return spiffeid.TrustDomain{}, fmt.Errorf("failed to construct SPIFFE ID for requestor: %w", err)
}
// Validate the authorization token
_, err = jwt.Parse([]byte(req.GetToken()),
jwt.WithKeySet(j.cache.KeySet(), jws.WithInferAlgorithmFromKey(true)),
jwt.WithAcceptableSkew(5*time.Minute),
jwt.WithContext(ctx),
jwt.WithAudience(j.sentryAudience),
// TODO: @joshvanl: extract the trust domain from the subject.
jwt.WithSubject(sub.String()),
)
if err != nil {
return spiffeid.TrustDomain{}, fmt.Errorf("token validation failed: %w", err)
}
return td, nil
}
|
mikeee/dapr
|
pkg/sentry/server/validator/jwks/jwks.go
|
GO
|
mit
| 4,082 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"errors"
"fmt"
"strings"
"github.com/lestrrat-go/jwx/v2/jwt"
"github.com/spiffe/go-spiffe/v2/spiffeid"
kauthapi "k8s.io/api/authentication/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
cl "k8s.io/client-go/kubernetes"
clauthv1 "k8s.io/client-go/kubernetes/typed/authentication/v1"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
configv1alpha1 "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
"github.com/dapr/dapr/pkg/injector/annotations"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
"github.com/dapr/dapr/pkg/security/consts"
"github.com/dapr/dapr/pkg/sentry/server/validator"
"github.com/dapr/dapr/pkg/sentry/server/validator/internal"
"github.com/dapr/kit/logger"
)
var (
log = logger.NewLogger("dapr.sentry.identity.kubernetes")
errMissingPodClaim = errors.New("kubernetes.io/pod/name claim is missing from Kubernetes token")
)
const (
// TODO: @joshvanl: Before 1.12, dapr would use this generic audience. After
// 1.13, clients use the sentry SPIFFE ID as the audience. Remove this
// constant in 1.14.
LegacyServiceAccountAudience = "dapr.io/sentry"
)
type Options struct {
RestConfig *rest.Config
SentryID spiffeid.ID
ControlPlaneNS string
}
// kubernetes implements the validator.Interface. It validates the request by
// doing a Kubernetes token review.
type kubernetes struct {
auth clauthv1.AuthenticationV1Interface
client client.Reader
ready func(context.Context) bool
sentryAudience string
controlPlaneNS string
controlPlaneTD spiffeid.TrustDomain
}
func New(ctx context.Context, opts Options) (validator.Validator, error) {
kubeClient, err := cl.NewForConfig(opts.RestConfig)
if err != nil {
return nil, err
}
scheme := runtime.NewScheme()
if err = configv1alpha1.AddToScheme(scheme); err != nil {
return nil, err
}
if err = corev1.AddToScheme(scheme); err != nil {
return nil, err
}
cache, err := cache.New(opts.RestConfig, cache.Options{Scheme: scheme})
if err != nil {
return nil, err
}
for _, obj := range []client.Object{
&metav1.PartialObjectMetadata{TypeMeta: metav1.TypeMeta{Kind: "Pod", APIVersion: "v1"}},
&configv1alpha1.Configuration{},
} {
if _, err := cache.GetInformer(ctx, obj); err != nil {
return nil, err
}
}
return &kubernetes{
auth: kubeClient.AuthenticationV1(),
client: cache,
ready: cache.WaitForCacheSync,
sentryAudience: opts.SentryID.String(),
controlPlaneNS: opts.ControlPlaneNS,
controlPlaneTD: opts.SentryID.TrustDomain(),
}, nil
}
func (k *kubernetes) Start(ctx context.Context) error {
if err := k.client.(cache.Cache).Start(ctx); err != nil {
return err
}
<-ctx.Done()
return nil
}
func (k *kubernetes) Validate(ctx context.Context, req *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error) {
if !k.ready(ctx) {
return spiffeid.TrustDomain{}, errors.New("validator not ready")
}
// The TrustDomain field is ignored by the Kubernetes validator.
if _, err := internal.Validate(ctx, req); err != nil {
return spiffeid.TrustDomain{}, err
}
prts, err := k.executeTokenReview(ctx, req.GetToken(), LegacyServiceAccountAudience, k.sentryAudience)
if err != nil {
return spiffeid.TrustDomain{}, err
}
if len(prts) != 4 || prts[0] != "system" {
return spiffeid.TrustDomain{}, errors.New("provided token is not a properly structured service account token")
}
saNamespace := prts[2]
// We have already validated to the token against Kubernetes API server, so
// we do not need to supply a key.
ptoken, err := jwt.ParseInsecure([]byte(req.GetToken()), jwt.WithTypedClaim("kubernetes.io", new(k8sClaims)))
if err != nil {
return spiffeid.TrustDomain{}, fmt.Errorf("failed to parse Kubernetes token: %s", err)
}
claimsT, ok := ptoken.Get("kubernetes.io")
if !ok {
return spiffeid.TrustDomain{}, errMissingPodClaim
}
claims, ok := claimsT.(*k8sClaims)
if !ok || len(claims.Pod.Name) == 0 {
return spiffeid.TrustDomain{}, errMissingPodClaim
}
var pod corev1.Pod
err = k.client.Get(ctx, types.NamespacedName{Namespace: saNamespace, Name: claims.Pod.Name}, &pod)
if err != nil {
log.Errorf("Failed to get pod %s/%s for requested identity: %s", saNamespace, claims.Pod.Name, err)
return spiffeid.TrustDomain{}, errors.New("failed to get pod of identity")
}
if saNamespace != req.GetNamespace() {
return spiffeid.TrustDomain{}, fmt.Errorf("namespace mismatch; received namespace: %s", req.GetNamespace())
}
if pod.Spec.ServiceAccountName != prts[3] {
log.Errorf("Service account on pod %s/%s does not match token", req.GetNamespace(), claims.Pod.Name)
return spiffeid.TrustDomain{}, errors.New("pod service account mismatch")
}
expID, isControlPlane, err := k.expectedID(&pod)
if err != nil {
log.Errorf("Failed to get expected ID for pod %s/%s: %s", req.GetNamespace(), claims.Pod.Name, err)
return spiffeid.TrustDomain{}, err
}
if expID != req.GetId() {
return spiffeid.TrustDomain{}, fmt.Errorf("app-id mismatch. expected: %s, received: %s", expID, req.GetId())
}
if isControlPlane {
return k.controlPlaneTD, nil
}
configName, ok := pod.GetAnnotations()[annotations.KeyConfig]
if !ok {
// Return early with default trust domain if no config annotation is found.
return spiffeid.RequireTrustDomainFromString("public"), nil
}
var config configv1alpha1.Configuration
err = k.client.Get(ctx, types.NamespacedName{Namespace: req.GetNamespace(), Name: configName}, &config)
if err != nil {
log.Errorf("Failed to get configuration %q: %v", configName, err)
return spiffeid.TrustDomain{}, errors.New("failed to get configuration")
}
if config.Spec.AccessControlSpec == nil || len(config.Spec.AccessControlSpec.TrustDomain) == 0 {
return spiffeid.RequireTrustDomainFromString("public"), nil
}
return spiffeid.TrustDomainFromString(config.Spec.AccessControlSpec.TrustDomain)
}
// expectedID returns the expected ID for the pod. If the pod is a control
// plane service (has the dapr.io/control-plane annotation), the ID will be the
// control plane service name prefixed with "dapr-". Otherwise, the ID will be
// `dapr.io/app-id` annotation or the pod name.
func (k *kubernetes) expectedID(pod *corev1.Pod) (string, bool, error) {
ctrlPlane, ctrlOK := pod.Annotations[consts.AnnotationKeyControlPlane]
appID, appOK := pod.Annotations[annotations.KeyAppID]
if ctrlOK {
if pod.Namespace != k.controlPlaneNS {
return "", false, fmt.Errorf("control plane service in namespace '%s' is not allowed", pod.Namespace)
}
if !isControlPlaneService(ctrlPlane) {
return "", false, fmt.Errorf("unknown control plane service '%s'", pod.Name)
}
if appOK {
return "", false, fmt.Errorf("control plane service '%s' cannot have annotation '%s'", pod.Name, annotations.KeyAppID)
}
return "dapr-" + ctrlPlane, true, nil
}
if !appOK {
return pod.Name, false, nil
}
return appID, false, nil
}
// Executes a tokenReview, returning an error if the token is invalid or if
// there's a failure.
// If successful, returns the username of the token, split by the Kubernetes
// ':' separator.
func (k *kubernetes) executeTokenReview(ctx context.Context, token string, audiences ...string) ([]string, error) {
review, err := k.auth.TokenReviews().Create(ctx, &kauthapi.TokenReview{
Spec: kauthapi.TokenReviewSpec{Token: token, Audiences: audiences},
}, metav1.CreateOptions{})
if err != nil {
return nil, fmt.Errorf("token review failed: %w", err)
}
if len(review.Status.Error) > 0 {
return nil, fmt.Errorf("invalid token: %s", review.Status.Error)
}
if !review.Status.Authenticated {
return nil, errors.New("authentication failed")
}
return strings.Split(review.Status.User.Username, ":"), nil
}
// k8sClaims is a subset of the claims in a Kubernetes service account token
// containing the name of the Pod that the token was issued for.
type k8sClaims struct {
Pod struct {
Name string `json:"name"`
} `json:"pod"`
}
// IsControlPlaneService returns true if the app ID corresponds to a Dapr control plane service.
// Note: callers must additionally validate the namespace to ensure it matches the one of the Dapr control plane.
func isControlPlaneService(id string) bool {
switch id {
case "operator",
"placement",
"injector",
"sentry":
return true
default:
return false
}
}
|
mikeee/dapr
|
pkg/sentry/server/validator/kubernetes/kubernetes.go
|
GO
|
mit
| 9,112 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubernetes
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/lestrrat-go/jwx/v2/jwt"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
kauthapi "k8s.io/api/authentication/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
kubefake "k8s.io/client-go/kubernetes/fake"
core "k8s.io/client-go/testing"
clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
configapi "github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
func TestValidate(t *testing.T) {
newToken := func(t *testing.T, ns, name string) string {
token, err := jwt.NewBuilder().Claim("kubernetes.io", map[string]any{
"pod": map[string]any{
"namespace": ns,
"name": name,
},
}).Build()
require.NoError(t, err)
tokenB, err := json.Marshal(token)
require.NoError(t, err)
return string(tokenB)
}
sentryID := spiffeid.RequireFromPath(spiffeid.RequireTrustDomainFromString("cluster.local"), "/ns/dapr-test/dapr-sentry")
tests := map[string]struct {
reactor func(t *testing.T) core.ReactionFunc
req *sentryv1pb.SignCertificateRequest
pod *corev1.Pod
config *configapi.Configuration
sentryAudience string
expTD spiffeid.TrustDomain
expErr bool
}{
"if pod in different namespace, expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "not-my-ns", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "not-my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if config in different namespace, expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "not-my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"is missing app-id and app-id is the same as the pod name, expect no error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "my-ns", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-pod",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "",
},
},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("public"),
},
"if missing app-id annotation and app-id doesn't match pod name, expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if target configuration doesn't exist, expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: nil,
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"is service account on pod does not match token, expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "not-my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if username namespace doesn't match request namespace, reject": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "not-my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if token returns an error, expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
Error: "this is an error",
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if token auth failed, expect failed": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: false,
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if pod name is empty in kube token, expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", ""),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"valid authentication, no config annotation should be default trust domain": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "my-ns", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("public"),
},
"valid authentication, config annotation, return the trust domain from config": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "my-ns", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("example.test.dapr.io"),
},
"valid authentication, config annotation, config empty, return the default trust domain": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "my-ns", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-app-id",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "",
},
},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("public"),
},
"valid authentication, if sentry return trust domain of control-plane": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:dapr-sentry",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "dapr-sentry"),
TrustDomain: "example.test.dapr.io",
Id: "dapr-sentry",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-sentry",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "sentry",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "dapr-sentry"},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("cluster.local"),
},
"valid authentication, if operator return trust domain of control-plane": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:dapr-operator",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "dapr-operator"),
TrustDomain: "example.test.dapr.io",
Id: "dapr-operator",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-operator",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "operator",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "dapr-operator"},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("cluster.local"),
},
"valid authentication, if injector return trust domain of control-plane": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:dapr-injector",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "dapr-injector"),
TrustDomain: "example.test.dapr.io",
Id: "dapr-injector",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-injector",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "injector",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "dapr-injector"},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("cluster.local"),
},
"valid authentication, if placement return trust domain of control-plane": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:dapr-placement",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "dapr-placement"),
TrustDomain: "example.test.dapr.io",
Id: "dapr-placement",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "dapr-placement",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "placement",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "dapr-placement"},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("cluster.local"),
},
"if both app-id and control-plane annotation present, should error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "dapr-test:my-sa",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/app-id": "my-app-id",
"dapr.io/control-plane": "placement",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "dapr-test",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if control plane component not in control plane namespace, error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-ns:my-sa",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/control-plane": "placement",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"should error if the control plane component is not known": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "dapr-test:my-sa",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "foo",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "dapr-test",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"should always use the control plane trust domain even in config is configured": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "dapr-placement",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "placement",
"dapr.io/config": "my-config",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "dapr-test",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("cluster.local"),
},
"injector is not able to request for whatever identity it wants (name)": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "dapr-test",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "bar",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "injector",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"injector is not able to request for whatever identity it wants (namespace)": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "foo",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-pod",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "injector",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"injector is not able to request for whatever identity it wants (namespace + name)": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "foo",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "bar",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "dapr-test",
Annotations: map[string]string{
"dapr.io/control-plane": "injector",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"injector is not able to request for whatever identity it wants if not in control plane namespace": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:dapr-test:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "foo",
Token: newToken(t, "bar", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "bar",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "bar",
Annotations: map[string]string{
"dapr.io/control-plane": "injector",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if app ID is 64 characters long don't error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: strings.Repeat("a", 64),
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": strings.Repeat("a", 64),
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: false,
expTD: spiffeid.RequireTrustDomainFromString("public"),
},
"if app ID is 65 characters long expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: strings.Repeat("a", 65),
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": strings.Repeat("a", 65),
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if app ID is 0 characters long expect error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:my-sa",
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "",
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
Annotations: map[string]string{
"dapr.io/app-id": "",
},
},
Spec: corev1.PodSpec{ServiceAccountName: "my-sa"},
},
config: &configapi.Configuration{
ObjectMeta: metav1.ObjectMeta{
Name: "my-config",
Namespace: "my-ns",
},
Spec: configapi.ConfigurationSpec{
AccessControlSpec: &configapi.AccessControlSpec{
TrustDomain: "example.test.dapr.io",
},
},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
"if requester is using the legacy request ID, and namespace+service account name is over 64 characters, error": {
sentryAudience: "spiffe://cluster.local/ns/dapr-test/dapr-sentry",
reactor: func(t *testing.T) core.ReactionFunc {
return func(action core.Action) (bool, runtime.Object, error) {
obj := action.(core.CreateAction).GetObject().(*kauthapi.TokenReview)
assert.Equal(t, []string{"dapr.io/sentry", "spiffe://cluster.local/ns/dapr-test/dapr-sentry"}, obj.Spec.Audiences)
return true, &kauthapi.TokenReview{Status: kauthapi.TokenReviewStatus{
Authenticated: true,
User: kauthapi.UserInfo{
Username: "system:serviceaccount:my-ns:" + strings.Repeat("a", 65),
},
}}, nil
}
},
req: &sentryv1pb.SignCertificateRequest{
CertificateSigningRequest: []byte("csr"),
Namespace: "my-ns",
Token: newToken(t, "dapr-test", "my-pod"),
TrustDomain: "example.test.dapr.io",
Id: "my-ns:" + strings.Repeat("a", 65),
},
pod: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "my-pod",
Namespace: "my-ns",
},
Spec: corev1.PodSpec{ServiceAccountName: strings.Repeat("a", 65)},
},
expErr: true,
expTD: spiffeid.TrustDomain{},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
var kobjs []runtime.Object
if test.pod != nil {
kobjs = append(kobjs, test.pod)
}
kubeCl := kubefake.NewSimpleClientset(kobjs...)
kubeCl.Fake.PrependReactor("create", "tokenreviews", test.reactor(t))
scheme := runtime.NewScheme()
require.NoError(t, configapi.AddToScheme(scheme))
require.NoError(t, corev1.AddToScheme(scheme))
client := clientfake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(kobjs...).Build()
if test.config != nil {
require.NoError(t, client.Create(context.Background(), test.config))
}
k := &kubernetes{
auth: kubeCl.AuthenticationV1(),
client: client,
controlPlaneNS: "dapr-test",
controlPlaneTD: sentryID.TrustDomain(),
sentryAudience: test.sentryAudience,
ready: func(_ context.Context) bool { return true },
}
td, err := k.Validate(context.Background(), test.req)
assert.Equal(t, test.expErr, err != nil, "%v", err)
assert.Equal(t, test.expTD, td)
})
}
}
func Test_isControlPlaneService(t *testing.T) {
tests := map[string]struct {
name string
exp bool
}{
"operator should be control plane service": {
name: "operator",
exp: true,
},
"sentry should be control plane service": {
name: "sentry",
exp: true,
},
"placement should be control plane service": {
name: "placement",
exp: true,
},
"sidecar injector should be control plane service": {
name: "injector",
exp: true,
},
"not a control plane service": {
name: "my-app",
exp: false,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert.Equal(t, test.exp, isControlPlaneService(test.name))
})
}
}
|
mikeee/dapr
|
pkg/sentry/server/validator/kubernetes/kubernetes_test.go
|
GO
|
mit
| 46,113 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package validator
import (
"context"
"github.com/spiffe/go-spiffe/v2/spiffeid"
sentryv1pb "github.com/dapr/dapr/pkg/proto/sentry/v1"
)
// Validator is used to validate the identity of a certificate requester by
// using an ID and token.
// Returns the trust domain of the certificate requester.
type Validator interface {
// Start starts the validator.
Start(context.Context) error
// Validate validates the identity of a certificate request.
// Returns the Trust Domain of the certificate requester, and whether the
// signed certificates duration should be overridden to the maximum time
// permitted by the singing certificate.
Validate(context.Context, *sentryv1pb.SignCertificateRequest) (spiffeid.TrustDomain, error)
}
|
mikeee/dapr
|
pkg/sentry/server/validator/validator.go
|
GO
|
mit
| 1,301 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"context"
"google.golang.org/protobuf/types/known/anypb"
"github.com/dapr/dapr/pkg/apphealth"
"github.com/dapr/dapr/pkg/config"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
)
type FailingAppChannel struct {
Failure Failure
KeyFunc func(req *invokev1.InvokeMethodRequest) string
}
func (f *FailingAppChannel) GetAppConfig(_ context.Context, appID string) (*config.ApplicationConfig, error) {
return nil, nil
}
func (f *FailingAppChannel) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest, appID string) (*invokev1.InvokeMethodResponse, error) {
err := f.Failure.PerformFailure(f.KeyFunc(req))
if err != nil {
return invokev1.NewInvokeMethodResponse(500, "Failure!", []*anypb.Any{}), err
}
return invokev1.NewInvokeMethodResponse(200, "Success", []*anypb.Any{}), nil
}
func (f *FailingAppChannel) HealthProbe(ctx context.Context) (bool, error) {
return true, nil
}
func (f *FailingAppChannel) SetAppHealth(ah *apphealth.AppHealth) {
// Do nothing
}
|
mikeee/dapr
|
pkg/testing/app_channel_mock.go
|
GO
|
mit
| 1,580 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//nolint:forbidigo
package testing
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"time"
)
// KeyValState is a key value struct for state.
type KeyValState struct {
Key string `json:"key"`
Value interface{} `json:"value"`
}
// Event is an app response event.
type Event struct {
EventName string `json:"eventName,omitempty"`
To []string `json:"to,omitempty"`
Concurrency string `json:"concurrency,omitempty"`
CreatedAt time.Time `json:"createdAt,omitempty"`
State []KeyValState `json:"state,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// MockApp is a mock for an app.
type MockApp struct {
returnBody bool
messageCount int
count int
noprint bool
}
// NewMockApp returns a new mocked app.
func NewMockApp(returnBody bool, messageCount int, noprint bool) *MockApp {
ret := new(MockApp)
ret.returnBody = returnBody
ret.messageCount = messageCount
ret.count = 0
ret.noprint = noprint
return ret
}
// Run opens a test HTTP server and echo endpoint on the mock object.
func (a *MockApp) Run(port int) {
mux := http.NewServeMux()
mux.HandleFunc("/httptest", a.handler)
mux.HandleFunc("/echo", a.echoHandler)
//nolint:gosec
server := http.Server{Addr: ":" + strconv.Itoa(port), Handler: mux}
go func() {
server.ListenAndServe()
}()
fmt.Println("App is running")
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
<-stop
ctx, cF := context.WithTimeout(context.Background(), 5*time.Second)
cF()
server.Shutdown(ctx)
}
func (a *MockApp) echoHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
var buffer bytes.Buffer
for k, p := range r.URL.Query() {
buffer.WriteString(k + "=" + p[0] + ";")
}
w.Write(buffer.Bytes())
}
func (a *MockApp) handler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
w.Write(nil)
return
}
defer r.Body.Close()
body, _ := io.ReadAll(r.Body)
var msg Event
if err := json.Unmarshal(body, &msg); err != nil {
log.Fatal(err)
}
str, _ := json.Marshal(msg.Data)
if !a.noprint {
fmt.Println(string(str) + "#" + time.Now().UTC().Format(time.RFC3339))
}
w.WriteHeader(http.StatusOK)
if a.returnBody {
w.Write(body)
} else {
w.Write(nil)
}
a.count++
if a.messageCount > 0 && a.count >= a.messageCount {
os.Exit(0)
}
}
|
mikeee/dapr
|
pkg/testing/app_mock.go
|
GO
|
mit
| 3,014 |
package testing
import (
"context"
mock "github.com/stretchr/testify/mock"
"github.com/dapr/components-contrib/bindings"
)
// MockBinding is a mock input/output component object.
type MockBinding struct {
mock.Mock
readCloseCh chan struct{}
}
// Init is a mock initialization method.
func (m *MockBinding) Init(ctx context.Context, metadata bindings.Metadata) error {
return nil
}
// Read is a mock read method.
func (m *MockBinding) Read(ctx context.Context, handler bindings.Handler) error {
args := m.Called(ctx, handler)
if err := args.Error(0); err != nil {
return err
}
if ctx != nil && m.readCloseCh != nil {
go func() {
<-ctx.Done()
m.readCloseCh <- struct{}{}
}()
}
return nil
}
// Invoke is a mock invoke method.
func (m *MockBinding) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
args := m.Called(req)
return nil, args.Error(0)
}
// Operations is a mock operations method.
func (m *MockBinding) Operations() []bindings.OperationKind {
return []bindings.OperationKind{bindings.CreateOperation}
}
func (m *MockBinding) Close() error {
return nil
}
func (m *MockBinding) SetOnReadCloseCh(ch chan struct{}) {
m.readCloseCh = ch
}
type FailingBinding struct {
Failure Failure
}
// Init is a mock initialization method.
func (m *FailingBinding) Init(ctx context.Context, metadata bindings.Metadata) error {
return nil
}
// Invoke is a mock invoke method.
func (m *FailingBinding) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
key := string(req.Data)
return nil, m.Failure.PerformFailure(key)
}
// Operations is a mock operations method.
func (m *FailingBinding) Operations() []bindings.OperationKind {
return []bindings.OperationKind{bindings.CreateOperation}
}
func (m *FailingBinding) Close() error {
return nil
}
|
mikeee/dapr
|
pkg/testing/bindings_mock.go
|
GO
|
mit
| 1,868 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"fmt"
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
commonapi "github.com/dapr/dapr/pkg/apis/common"
"github.com/dapr/dapr/pkg/scopes"
)
const (
TestRuntimeConfigID = "consumer0"
)
func GetFakeProperties() map[string]string {
return map[string]string{
"host": "localhost",
"password": "fakePassword",
"consumerID": TestRuntimeConfigID,
scopes.SubscriptionScopes: fmt.Sprintf("%s=topic0,topic1,topic10,topic11", TestRuntimeConfigID),
scopes.PublishingScopes: fmt.Sprintf("%s=topic0,topic1,topic10,topic11", TestRuntimeConfigID),
scopes.ProtectedTopics: "topic10,topic11,topic12",
}
}
func GetFakeMetadataItems() []commonapi.NameValuePair {
return []commonapi.NameValuePair{
{
Name: "host",
Value: commonapi.DynamicValue{
JSON: v1.JSON{
Raw: []byte("localhost"),
},
},
},
{
Name: "password",
Value: commonapi.DynamicValue{
JSON: v1.JSON{
Raw: []byte("fakePassword"),
},
},
},
{
Name: "consumerID",
Value: commonapi.DynamicValue{
JSON: v1.JSON{
Raw: []byte(TestRuntimeConfigID),
},
},
},
{
Name: scopes.SubscriptionScopes,
Value: commonapi.DynamicValue{
JSON: v1.JSON{
Raw: []byte(fmt.Sprintf("%s=topic0,topic1,topic10,topic11", TestRuntimeConfigID)),
},
},
},
{
Name: scopes.PublishingScopes,
Value: commonapi.DynamicValue{
JSON: v1.JSON{
Raw: []byte(fmt.Sprintf("%s=topic0,topic1,topic10,topic11", TestRuntimeConfigID)),
},
},
},
{
Name: scopes.ProtectedTopics,
Value: commonapi.DynamicValue{
JSON: v1.JSON{
Raw: []byte("topic10,topic11,topic12"),
},
},
},
}
}
|
mikeee/dapr
|
pkg/testing/component.go
|
GO
|
mit
| 2,297 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import "context"
func MatchContextInterface(v any) bool {
_, ok := v.(context.Context)
return ok
}
|
mikeee/dapr
|
pkg/testing/context.go
|
GO
|
mit
| 680 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"context"
"net/http"
mock "github.com/stretchr/testify/mock"
"github.com/dapr/dapr/pkg/channel"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
)
// MockDirectMessaging is a semi-autogenerated mock type for the MockDirectMessaging type.
// Note: This file is created by copy/pasting values and renaming to use MockDirectMessaging instead of DirectMessaging.
// You run "mockery --name directMessaging" in "pkg/messaging" and modify the corresponding values here.
type MockDirectMessaging struct {
mock.Mock
}
// Invoke provides a mock function with given fields: ctx, targetAppID, req
func (_m *MockDirectMessaging) Invoke(ctx context.Context, targetAppID string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
ret := _m.Called(ctx, targetAppID, req)
var r0 *invokev1.InvokeMethodResponse
var r1 error
if rf, ok := ret.Get(0).(func(context.Context, string, *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error)); ok {
return rf(ctx, targetAppID, req)
}
if rf, ok := ret.Get(0).(func(context.Context, string, *invokev1.InvokeMethodRequest) *invokev1.InvokeMethodResponse); ok {
r0 = rf(ctx, targetAppID, req)
} else if ret.Get(0) != nil {
r0 = ret.Get(0).(*invokev1.InvokeMethodResponse)
}
if rf, ok := ret.Get(1).(func(context.Context, string, *invokev1.InvokeMethodRequest) error); ok {
r1 = rf(ctx, targetAppID, req)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
func (_m *MockDirectMessaging) SetAppChannel(appChannel channel.AppChannel) {
// nop
}
// SetHTTPEndpointsAppChannel provides a mock function with given fields: appChannel
func (_m *MockDirectMessaging) SetHTTPEndpointsAppChannels(nonResourceChannel channel.HTTPEndpointAppChannel, resourceChannels map[string]channel.HTTPEndpointAppChannel) {
// nop
}
func (_m *MockDirectMessaging) Close() error {
return nil
}
type FailingDirectMessaging struct {
Failure Failure
SuccessStatusCode int
}
func (_m *FailingDirectMessaging) Invoke(ctx context.Context, targetAppID string, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
r, err := req.ProtoWithData()
if err != nil {
return &invokev1.InvokeMethodResponse{}, err
}
err = _m.Failure.PerformFailure(string(r.GetMessage().GetData().GetValue()))
if err != nil {
return &invokev1.InvokeMethodResponse{}, err
}
statusCode := _m.SuccessStatusCode
if statusCode == 0 {
statusCode = http.StatusOK
}
// Setting up the headers passed in request
md := r.GetMetadata()
headers := make(map[string][]string)
for k, v := range md {
headers[k] = v.GetValues()
}
contentType := r.GetMessage().GetContentType()
resp := invokev1.
NewInvokeMethodResponse(int32(statusCode), http.StatusText(statusCode), nil).
WithRawDataBytes(r.GetMessage().GetData().GetValue()).
WithHTTPHeaders(headers).
WithContentType(contentType)
return resp, nil
}
func (_m *FailingDirectMessaging) SetAppChannel(appChannel channel.AppChannel) {
// nop
}
// SetHTTPEndpointsAppChannel provides a mock function with given fields: appChannel
func (_m *FailingDirectMessaging) SetHTTPEndpointsAppChannels(nonResourceChannel channel.HTTPEndpointAppChannel, resourceChannels map[string]channel.HTTPEndpointAppChannel) {
// nop
}
|
mikeee/dapr
|
pkg/testing/directmessaging_mock.go
|
GO
|
mit
| 3,844 |
// This file contains stream utils that are only used in tests
//go:build unit
// +build unit
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"io"
)
// ErrorReader implements an io.Reader that returns an error after reading a few bytes.
type ErrorReader struct{}
func (r ErrorReader) Read(p []byte) (n int, err error) {
data := []byte("non ti scordar di me")
l := copy(p, data)
return l, io.ErrClosedPipe
}
|
mikeee/dapr
|
pkg/testing/error_reader.go
|
GO
|
mit
| 953 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"errors"
"sync"
"time"
"k8s.io/utils/clock"
)
func NewFailure(fails map[string]int, timeouts map[string]time.Duration, callCount map[string]int) Failure {
return newFailureWithClock(fails, timeouts, callCount, &clock.RealClock{})
}
func newFailureWithClock(fails map[string]int, timeouts map[string]time.Duration, callCount map[string]int, clock clock.Clock) Failure {
return Failure{
fails: fails,
timeouts: timeouts,
callCount: callCount,
lock: &sync.RWMutex{},
clock: clock,
}
}
type Failure struct {
fails map[string]int
timeouts map[string]time.Duration
callCount map[string]int
lock *sync.RWMutex
clock clock.Clock
}
func (f *Failure) PerformFailure(key string) error {
f.lock.Lock()
f.callCount[key]++
if v, ok := f.fails[key]; ok {
if v > 0 {
f.fails[key]--
f.lock.Unlock()
return errors.New("forced failure")
}
delete(f.fails, key)
f.lock.Unlock()
return nil
}
f.lock.Unlock()
if val, ok := f.timeouts[key]; ok {
f.clock.Sleep(val)
}
return nil
}
func (f *Failure) CallCount(key string) int {
f.lock.RLock()
defer f.lock.RUnlock()
return f.callCount[key]
}
|
mikeee/dapr
|
pkg/testing/failure_mock.go
|
GO
|
mit
| 1,744 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"context"
"encoding/json"
"fmt"
"sync"
"sync/atomic"
"github.com/google/uuid"
"golang.org/x/exp/maps"
state "github.com/dapr/components-contrib/state"
)
type FakeStateStoreItem struct {
data []byte
etag *string
}
type FakeStateStore struct {
MaxOperations int
NoLock bool
items map[string]*FakeStateStoreItem
lock sync.RWMutex
callCount map[string]*atomic.Uint64
}
func NewFakeStateStore() *FakeStateStore {
return &FakeStateStore{
items: map[string]*FakeStateStoreItem{},
callCount: map[string]*atomic.Uint64{
"Delete": {},
"BulkDelete": {},
"Get": {},
"BulkGet": {},
"Set": {},
"BulkSet": {},
"Multi": {},
},
}
}
func (f *FakeStateStore) NewItem(data []byte) *FakeStateStoreItem {
etag, _ := uuid.NewRandom()
etagString := etag.String()
return &FakeStateStoreItem{
data: data,
etag: &etagString,
}
}
func (f *FakeStateStore) Init(ctx context.Context, metadata state.Metadata) error {
return nil
}
func (f *FakeStateStore) Ping() error {
return nil
}
func (f *FakeStateStore) Features() []state.Feature {
return []state.Feature{state.FeatureETag, state.FeatureTransactional}
}
func (f *FakeStateStore) Delete(ctx context.Context, req *state.DeleteRequest) error {
f.callCount["Delete"].Add(1)
if !f.NoLock {
f.lock.Lock()
defer f.lock.Unlock()
}
delete(f.items, req.Key)
return nil
}
func (f *FakeStateStore) BulkDelete(ctx context.Context, req []state.DeleteRequest, opts state.BulkStoreOpts) error {
f.callCount["BulkDelete"].Add(1)
return nil
}
func (f *FakeStateStore) Get(ctx context.Context, req *state.GetRequest) (*state.GetResponse, error) {
f.callCount["Get"].Add(1)
if !f.NoLock {
f.lock.RLock()
defer f.lock.RUnlock()
}
item := f.items[req.Key]
if item == nil {
return &state.GetResponse{Data: nil, ETag: nil}, nil
}
return &state.GetResponse{Data: item.data, ETag: item.etag}, nil
}
func (f *FakeStateStore) BulkGet(ctx context.Context, req []state.GetRequest, opts state.BulkGetOpts) ([]state.BulkGetResponse, error) {
f.callCount["BulkGet"].Add(1)
res := make([]state.BulkGetResponse, len(req))
for i, oneRequest := range req {
oneResponse, err := f.Get(ctx, &state.GetRequest{
Key: oneRequest.Key,
Metadata: oneRequest.Metadata,
Options: oneRequest.Options,
})
if err != nil {
return nil, err
}
res[i] = state.BulkGetResponse{
Key: oneRequest.Key,
Data: oneResponse.Data,
ETag: oneResponse.ETag,
}
}
return res, nil
}
func (f *FakeStateStore) Set(ctx context.Context, req *state.SetRequest) error {
f.callCount["Set"].Add(1)
if !f.NoLock {
f.lock.Lock()
defer f.lock.Unlock()
}
b, _ := marshal(&req.Value)
f.items[req.Key] = f.NewItem(b)
return nil
}
func (f *FakeStateStore) BulkSet(ctx context.Context, req []state.SetRequest, opts state.BulkStoreOpts) error {
f.callCount["BulkSet"].Add(1)
return nil
}
func (f *FakeStateStore) Multi(ctx context.Context, request *state.TransactionalStateRequest) error {
f.callCount["Multi"].Add(1)
if !f.NoLock {
f.lock.Lock()
defer f.lock.Unlock()
}
// First we check all eTags
for _, o := range request.Operations {
var eTag *string
key := ""
switch req := o.(type) {
case state.SetRequest:
key = req.Key
eTag = req.ETag
case state.DeleteRequest:
key = req.Key
eTag = req.ETag
}
item := f.items[key]
if eTag != nil && item != nil {
if *eTag != *item.etag {
return fmt.Errorf("etag does not match for key %v", key)
}
}
if eTag != nil && item == nil {
return fmt.Errorf("etag does not match for key not found %v", key)
}
}
// Now we can perform the operation.
for _, o := range request.Operations {
switch req := o.(type) {
case state.SetRequest:
b, _ := marshal(req.Value)
f.items[req.Key] = f.NewItem(b)
case state.DeleteRequest:
delete(f.items, req.Key)
}
}
return nil
}
func (f *FakeStateStore) GetItems() map[string]*FakeStateStoreItem {
if !f.NoLock {
f.lock.Lock()
defer f.lock.Unlock()
}
return maps.Clone(f.items)
}
func (f *FakeStateStore) CallCount(op string) uint64 {
if f.callCount[op] == nil {
return 0
}
return f.callCount[op].Load()
}
func (f *FakeStateStore) MultiMaxSize() int {
return f.MaxOperations
}
// Adapted from https://github.com/dapr/components-contrib/blob/a4b27ae49b7c99820c6e921d3891f03334692714/state/utils/utils.go#L16
func marshal(val interface{}) ([]byte, error) {
var err error = nil
bt, ok := val.([]byte)
if !ok {
bt, err = json.Marshal(val)
}
return bt, err
}
|
mikeee/dapr
|
pkg/testing/fake_state_store.go
|
GO
|
mit
| 5,165 |
/*
Copyright 2022 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package grpc
import (
"context"
"fmt"
"net"
"testing"
"time"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/test/bufconn"
runtimev1pb "github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/kit/logger"
)
const (
bufSize = 1024 * 1024
MaxGRPCServerUptime = 200 * time.Millisecond
)
// TestServerFor returns a grpcServer factory that bootstraps a grpcserver backed by a buf connection (in memory), and returns the given clientFactory instance to communicate with it.
// it also provides cleanup function for close the grpcserver and client connection.
//
// usage,
//
// serverFactory := testingGrpc.TestServerFor(testLogger, func(s *grpc.Server, svc *your_service_goes_here) {
// proto.RegisterMyService(s, svc) // your service
// }, proto.NewMyServiceClient)
//
// client, cleanup, err := serverFactory(&your_service{})
// require.NoError(t, err)
// defer cleanup()
func TestServerFor[TServer any, TClient any](logger logger.Logger, registersvc func(*grpc.Server, TServer), clientFactory func(grpc.ClientConnInterface) TClient) func(svc TServer) (client TClient, cleanup func(), err error) {
return func(srv TServer) (client TClient, cleanup func(), err error) {
lis := bufconn.Listen(bufSize)
s := grpc.NewServer()
registersvc(s, srv)
go func() {
if serveErr := s.Serve(lis); serveErr != nil {
logger.Debugf("Server exited with error: %v", serveErr)
}
}()
ctx := context.Background()
conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) {
return lis.Dial()
}), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
var zero TClient
return zero, nil, err
}
return clientFactory(conn), func() {
lis.Close()
conn.Close()
}, nil
}
}
// TestServerWithDialer returns a grpcServer factory that bootstraps a grpcserver backed by a buf connection (in memory), and returns a connection dialer to communicate with it.
// it also provides cleanup function for close the grpcserver but the client connection should be handled by the caller.
func TestServerWithDialer[TServer any](logger logger.Logger, registersvc func(*grpc.Server, TServer)) func(svc TServer) (dialer func(ctx context.Context, opts ...grpc.DialOption) (*grpc.ClientConn, error), cleanup func(), err error) {
return func(srv TServer) (dialer func(ctx context.Context, opts ...grpc.DialOption) (*grpc.ClientConn, error), cleanup func(), err error) {
lis := bufconn.Listen(bufSize)
s := grpc.NewServer()
registersvc(s, srv)
go func() {
if serveErr := s.Serve(lis); serveErr != nil {
logger.Debugf("Server exited with error: %v", serveErr)
}
}()
return func(ctx context.Context, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
opts = append(opts, grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) {
return lis.Dial()
}), grpc.WithTransportCredentials(insecure.NewCredentials()))
return grpc.DialContext(ctx, "bufnet", opts...)
}, func() {
lis.Close()
}, nil
}
}
func StartTestAppCallbackGRPCServer(t *testing.T, port int, mockServer runtimev1pb.AppCallbackServer) *grpc.Server {
lis, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
require.NoError(t, err)
grpcServer := grpc.NewServer()
go func() {
runtimev1pb.RegisterAppCallbackServer(grpcServer, mockServer)
if err := grpcServer.Serve(lis); err != nil {
panic(err)
}
}()
// wait until server starts
time.Sleep(MaxGRPCServerUptime)
return grpcServer
}
|
mikeee/dapr
|
pkg/testing/grpc/server.go
|
GO
|
mit
| 4,193 |
// Package testing is a generated GoMock package.
package testing
import (
"context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
lock "github.com/dapr/components-contrib/lock"
)
// MockStore is a mock of Store interface.
type MockStore struct {
ctrl *gomock.Controller
recorder *MockStoreMockRecorder
}
// MockStoreMockRecorder is the mock recorder for MockStore.
type MockStoreMockRecorder struct {
mock *MockStore
}
// NewMockStore creates a new mock instance.
func NewMockStore(ctrl *gomock.Controller) *MockStore {
mock := &MockStore{ctrl: ctrl}
mock.recorder = &MockStoreMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockStore) EXPECT() *MockStoreMockRecorder {
return m.recorder
}
// InitLockStore mocks base method.
func (m *MockStore) InitLockStore(ctx context.Context, metadata lock.Metadata) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "InitLockStore", metadata)
ret0, _ := ret[0].(error)
return ret0
}
// InitLockStore indicates an expected call of InitLockStore.
func (mr *MockStoreMockRecorder) InitLockStore(ctx context.Context, metadata interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitLockStore", reflect.TypeOf((*MockStore)(nil).InitLockStore), metadata)
}
// TryLock mocks base method.
func (m *MockStore) TryLock(ctx context.Context, req *lock.TryLockRequest) (*lock.TryLockResponse, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "TryLock", ctx, req)
ret0, _ := ret[0].(*lock.TryLockResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// TryLock indicates an expected call of TryLock.
func (mr *MockStoreMockRecorder) TryLock(ctx context.Context, req interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TryLock", reflect.TypeOf((*MockStore)(nil).TryLock), ctx, req)
}
// Unlock mocks base method.
func (m *MockStore) Unlock(ctx context.Context, req *lock.UnlockRequest) (*lock.UnlockResponse, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Unlock", ctx, req)
ret0, _ := ret[0].(*lock.UnlockResponse)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Unlock indicates an expected call of Unlock.
func (mr *MockStoreMockRecorder) Unlock(ctx context.Context, req interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unlock", reflect.TypeOf((*MockStore)(nil).Unlock), ctx, req)
}
|
mikeee/dapr
|
pkg/testing/lock_mock.go
|
GO
|
mit
| 2,513 |
package logging
import "github.com/go-logr/logr"
// NullLogSink is a logr.LogSink that does nothing.
type NullLogSink struct{}
func (NullLogSink) Init(_ logr.RuntimeInfo) {
// Do nothing.
}
func (NullLogSink) Enabled(_ int) bool {
return false
}
func (NullLogSink) Info(_ int, _ string, _ ...interface{}) {
// Do nothing.
}
func (NullLogSink) Error(_ error, _ string, _ ...interface{}) {
// Do nothing.
}
func (log NullLogSink) WithValues(_ ...interface{}) logr.LogSink {
return log
}
func (log NullLogSink) WithName(name string) logr.LogSink {
return log
}
|
mikeee/dapr
|
pkg/testing/logging/null.go
|
GO
|
mit
| 572 |
package testing
import (
"context"
"net/http"
"reflect"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/record"
"github.com/dapr/dapr/pkg/testing/logging"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/config"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/webhook"
)
func NewMockManager() *MockManager {
mgr := &MockManager{
sc: runtime.NewScheme(),
log: logr.New(logging.NullLogSink{}),
runnables: []manager.Runnable{},
indexer: &MockFieldIndexer{
typeMap: map[reflect.Type]client.IndexerFunc{},
},
}
return mgr
}
type MockManager struct {
sc *runtime.Scheme
log logr.Logger
runnables []manager.Runnable
indexer *MockFieldIndexer
}
type MockFieldIndexer struct {
typeMap map[reflect.Type]client.IndexerFunc
}
func (m *MockManager) GetRunnables() []manager.Runnable {
return m.runnables
}
func (m *MockManager) Add(runnable manager.Runnable) error {
m.runnables = append(m.runnables, runnable)
return nil
}
func (m *MockManager) Elected() <-chan struct{} {
return nil
}
func (m *MockManager) SetFields(interface{}) error {
return nil
}
func (m *MockManager) AddMetricsExtraHandler(path string, handler http.Handler) error {
return nil
}
func (m *MockManager) AddHealthzCheck(name string, check healthz.Checker) error {
return nil
}
func (m *MockManager) AddReadyzCheck(name string, check healthz.Checker) error {
return nil
}
func (m *MockManager) Start(ctx context.Context) error {
return nil
}
func (m *MockManager) GetConfig() *rest.Config {
return nil
}
func (m *MockManager) GetControllerOptions() config.Controller {
return config.Controller{}
}
func (m *MockManager) GetScheme() *runtime.Scheme {
return m.sc
}
func (m *MockManager) GetClient() client.Client {
return nil
}
func (m *MockManager) GetFieldIndexer() client.FieldIndexer {
return m.indexer
}
func (m *MockManager) GetCache() cache.Cache {
return nil
}
func (m *MockManager) GetEventRecorderFor(name string) record.EventRecorder {
return nil
}
func (m *MockManager) GetRESTMapper() meta.RESTMapper {
return nil
}
func (m *MockManager) GetAPIReader() client.Reader {
return nil
}
func (m *MockManager) GetWebhookServer() webhook.Server {
return nil
}
func (m *MockManager) GetLogger() logr.Logger {
return m.log
}
func (m *MockManager) GetHTTPClient() *http.Client {
return http.DefaultClient
}
func (t *MockFieldIndexer) IndexField(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error {
t.typeMap[reflect.TypeOf(obj)] = extractValue
return nil
}
func (m *MockManager) GetIndexerFunc(obj client.Object) client.IndexerFunc {
return m.indexer.typeMap[reflect.TypeOf(obj)]
}
|
mikeee/dapr
|
pkg/testing/manager_mock.go
|
GO
|
mit
| 2,949 |
package testing
import (
"context"
mock "github.com/stretchr/testify/mock"
nr "github.com/dapr/components-contrib/nameresolution"
)
// MockResolver is a mock nameresolution component object.
type MockResolver struct {
mock.Mock
}
// Init is a mock initialization method.
func (m *MockResolver) Init(_ context.Context, metadata nr.Metadata) error {
args := m.Called(metadata)
return args.Error(0)
}
// ResolveID is a mock resolve method.
func (m *MockResolver) ResolveID(_ context.Context, req nr.ResolveRequest) (string, error) {
args := m.Called(req)
return args.String(0), args.Error(1)
}
|
mikeee/dapr
|
pkg/testing/nameresolution_mock.go
|
GO
|
mit
| 605 |
package testing
import (
"net"
"testing"
"time"
)
// WaitForListeningAddress waits for `addresses` to be listening for up to `timeout`.
func WaitForListeningAddress(t *testing.T, timeout time.Duration, addresses ...string) {
start := time.Now().UTC()
for _, address := range addresses {
t.Logf("Waiting for address %q", address)
check:
for {
d := timeout - time.Since(start)
if d <= 0 {
t.Log("Waiting for addresses timed out")
t.FailNow()
}
conn, _ := net.DialTimeout("tcp", address, d)
if conn != nil {
conn.Close()
break check
}
time.Sleep(time.Millisecond * 500)
}
t.Logf("Address %q is ready", address)
}
}
// GetFreePorts asks the kernel for `num` free open ports that are ready to use.
// This code is retrofitted from freeport.GetFreePort().
func GetFreePorts(num uint) ([]int, error) {
ports := make([]int, num)
for i := uint(0); i < num; i++ {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return nil, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return nil, err
}
defer l.Close()
ports[i] = l.Addr().(*net.TCPAddr).Port
}
return ports, nil
}
|
mikeee/dapr
|
pkg/testing/network.go
|
GO
|
mit
| 1,179 |
package testing
import (
"context"
"sync"
mock "github.com/stretchr/testify/mock"
"github.com/dapr/components-contrib/pubsub"
)
// MockPubSub is a mock pub-sub component object.
type MockPubSub struct {
mock.Mock
}
// Init is a mock initialization method.
func (m *MockPubSub) Init(ctx context.Context, metadata pubsub.Metadata) error {
args := m.Called(metadata)
return args.Error(0)
}
// Publish is a mock publish method.
func (m *MockPubSub) Publish(ctx context.Context, req *pubsub.PublishRequest) error {
args := m.Called(req)
return args.Error(0)
}
// BulkPublish is a mock bulk publish method.
func (m *MockPubSub) BulkPublish(ctx context.Context, req *pubsub.BulkPublishRequest) (pubsub.BulkPublishResponse, error) {
args := m.Called(req)
return pubsub.BulkPublishResponse{}, args.Error(0)
}
// BulkSubscribe is a mock bulk subscribe method.
func (m *MockPubSub) BulkSubscribe(rctx context.Context, req pubsub.SubscribeRequest, handler pubsub.BulkHandler) (pubsub.BulkSubscribeResponse, error) {
args := m.Called(req)
return pubsub.BulkSubscribeResponse{}, args.Error(0)
}
// Subscribe is a mock subscribe method.
func (m *MockPubSub) Subscribe(_ context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error {
args := m.Called(req, handler)
return args.Error(0)
}
// Close is a mock close method.
func (m *MockPubSub) Close() error {
return nil
}
func (m *MockPubSub) Features() []pubsub.Feature {
args := m.Called()
return args.Get(0).([]pubsub.Feature)
}
// FailingPubsub is a mock pubsub component object that simulates failures.
type FailingPubsub struct {
Failure Failure
}
func (f *FailingPubsub) Init(ctx context.Context, metadata pubsub.Metadata) error {
return nil
}
func (f *FailingPubsub) Publish(ctx context.Context, req *pubsub.PublishRequest) error {
return f.Failure.PerformFailure(req.Topic)
}
func (f *FailingPubsub) BulkPublish(ctx context.Context, req *pubsub.BulkPublishRequest) (pubsub.BulkPublishResponse, error) {
return pubsub.BulkPublishResponse{}, f.Failure.PerformFailure(req.Topic)
}
func (f *FailingPubsub) BulkSubscribe(ctx context.Context, req pubsub.SubscribeRequest, handler pubsub.BulkHandler) (pubsub.BulkSubscribeResponse, error) {
return pubsub.BulkSubscribeResponse{}, f.Failure.PerformFailure(req.Topic)
}
func (f *FailingPubsub) Subscribe(_ context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error {
err := f.Failure.PerformFailure(req.Topic)
if err != nil {
return err
}
// This handler can also be calling into things that'll fail
return handler(context.Background(), &pubsub.NewMessage{
Topic: req.Topic,
Metadata: map[string]string{
"pubsubName": "failPubsub",
},
Data: []byte(req.Topic),
})
}
func (f *FailingPubsub) Close() error {
return nil
}
func (f *FailingPubsub) Features() []pubsub.Feature {
return nil
}
// InMemoryPubsub is a mock pub-sub component object that works with in-memory handlers
type InMemoryPubsub struct {
mock.Mock
subscribedTopics map[string]subscription
topicsCb func([]string)
bulkHandler func(topic string, msg *pubsub.BulkMessage)
handler func(topic string, msg *pubsub.NewMessage)
lock *sync.Mutex
}
type subscription struct {
cancel context.CancelFunc
send chan *pubsub.NewMessage
sendBatch chan *pubsub.BulkMessage
}
// Init is a mock initialization method.
func (m *InMemoryPubsub) Init(ctx context.Context, metadata pubsub.Metadata) error {
m.lock = &sync.Mutex{}
args := m.Called(metadata)
return args.Error(0)
}
// Publish is a mock publish method.
func (m *InMemoryPubsub) Publish(ctx context.Context, req *pubsub.PublishRequest) error {
m.lock.Lock()
defer m.lock.Unlock()
var send chan *pubsub.NewMessage
t, ok := m.subscribedTopics[req.Topic]
if ok && t.send != nil {
send = t.send
}
if send != nil {
send <- &pubsub.NewMessage{
Data: req.Data,
Topic: req.Topic,
Metadata: req.Metadata,
ContentType: req.ContentType,
}
}
return nil
}
func (m *InMemoryPubsub) BulkPublish(req *pubsub.BulkPublishRequest) (pubsub.BulkPublishResponse, error) {
var sendBatch chan *pubsub.BulkMessage
bulkMessage := pubsub.BulkMessage{}
if req != nil {
m.lock.Lock()
t, ok := m.subscribedTopics[req.Topic]
if ok && t.sendBatch != nil {
sendBatch = t.sendBatch
}
m.lock.Unlock()
bulkMessage.Entries = make([]pubsub.BulkMessageEntry, len(req.Entries))
for i, datum := range req.Entries {
bulkMessage.Entries[i] = datum
}
}
bulkMessage.Metadata = req.Metadata
bulkMessage.Topic = req.Topic
if sendBatch != nil {
sendBatch <- &bulkMessage
}
return pubsub.BulkPublishResponse{}, nil
}
func (m *InMemoryPubsub) BulkSubscribe(parentCtx context.Context, req pubsub.SubscribeRequest, handler pubsub.BulkHandler) (pubsub.BulkSubscribeResponse, error) {
ctx, cancel := context.WithCancel(parentCtx)
ch := make(chan *pubsub.BulkMessage, 10)
m.lock.Lock()
if m.subscribedTopics == nil {
m.subscribedTopics = map[string]subscription{}
}
m.subscribedTopics[req.Topic] = subscription{
cancel: cancel,
sendBatch: ch,
}
m.onSubscribedTopicsChanged()
m.lock.Unlock()
go func() {
for {
select {
case msg := <-ch:
if m.bulkHandler != nil && msg != nil {
go m.bulkHandler(req.Topic, msg)
}
case <-ctx.Done():
close(ch)
m.lock.Lock()
delete(m.subscribedTopics, req.Topic)
m.onSubscribedTopicsChanged()
m.lock.Unlock()
m.MethodCalled("unsubscribed", req.Topic)
return
}
}
}()
args := m.Called(req, handler)
return pubsub.BulkSubscribeResponse{}, args.Error(0)
}
// Subscribe is a mock subscribe method.
func (m *InMemoryPubsub) Subscribe(parentCtx context.Context, req pubsub.SubscribeRequest, handler pubsub.Handler) error {
ctx, cancel := context.WithCancel(parentCtx)
ch := make(chan *pubsub.NewMessage, 10)
m.lock.Lock()
if m.subscribedTopics == nil {
m.subscribedTopics = map[string]subscription{}
}
m.subscribedTopics[req.Topic] = subscription{
cancel: cancel,
send: ch,
}
m.onSubscribedTopicsChanged()
m.lock.Unlock()
go func() {
for {
select {
case msg := <-ch:
if m.handler != nil && msg != nil {
go m.handler(req.Topic, msg)
}
case <-ctx.Done():
m.lock.Lock()
close(ch)
delete(m.subscribedTopics, req.Topic)
m.onSubscribedTopicsChanged()
m.MethodCalled("unsubscribed", req.Topic)
m.lock.Unlock()
return
}
}
}()
args := m.Called(req, handler)
return args.Error(0)
}
// Close is a mock close method.
func (m *InMemoryPubsub) Close() error {
m.lock.Lock()
if len(m.subscribedTopics) > 0 {
for _, f := range m.subscribedTopics {
f.cancel()
}
}
m.lock.Unlock()
return nil
}
func (m *InMemoryPubsub) Features() []pubsub.Feature {
return nil
}
func (m *InMemoryPubsub) SetHandler(h func(topic string, msg *pubsub.NewMessage)) {
m.handler = h
}
func (m *InMemoryPubsub) SetBulkHandler(h func(topic string, msg *pubsub.BulkMessage)) {
m.bulkHandler = h
}
func (m *InMemoryPubsub) SetOnSubscribedTopicsChanged(f func([]string)) {
m.topicsCb = f
}
func (m *InMemoryPubsub) onSubscribedTopicsChanged() {
if m.topicsCb != nil {
topics := make([]string, len(m.subscribedTopics))
i := 0
for k := range m.subscribedTopics {
topics[i] = k
i++
}
m.topicsCb(topics)
}
}
|
mikeee/dapr
|
pkg/testing/pubsub_mock.go
|
GO
|
mit
| 7,352 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by mockery v1.0.0.
package testing
import (
"context"
"github.com/dapr/components-contrib/pubsub"
)
// MockPubSubAdapter is mock for PubSubAdapter
type MockPubSubAdapter struct {
PublishFn func(ctx context.Context, req *pubsub.PublishRequest) error
BulkPublishFn func(ctx context.Context, req *pubsub.BulkPublishRequest) (pubsub.BulkPublishResponse, error)
}
// Publish is an adapter method for the runtime to pre-validate publish requests
// And then forward them to the Pub/Sub component.
// This method is used by the HTTP and gRPC APIs.
func (a *MockPubSubAdapter) Publish(ctx context.Context, req *pubsub.PublishRequest) error {
return a.PublishFn(ctx, req)
}
// Publish is an adapter method for the runtime to pre-validate publish requests
// And then forward them to the Pub/Sub component.
// This method is used by the HTTP and gRPC APIs.
func (a *MockPubSubAdapter) BulkPublish(ctx context.Context, req *pubsub.BulkPublishRequest) (pubsub.BulkPublishResponse, error) {
return a.BulkPublishFn(ctx, req)
}
|
mikeee/dapr
|
pkg/testing/pubsubadapter_mock.go
|
GO
|
mit
| 1,608 |
// Code generated by mockery v2.9.4. DO NOT EDIT.
package testing
import (
"context"
state "github.com/dapr/components-contrib/state"
mock "github.com/stretchr/testify/mock"
)
// MockQuerier is an autogenerated mock type for the Querier type
type MockQuerier struct {
mock.Mock
}
// Query provides a mock function with given fields: req
func (_m *MockQuerier) Query(ctx context.Context, req *state.QueryRequest) (*state.QueryResponse, error) {
ret := _m.Called(ctx, req)
var r0 *state.QueryResponse
if rf, ok := ret.Get(0).(func(context.Context, *state.QueryRequest) *state.QueryResponse); ok {
r0 = rf(ctx, req)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(*state.QueryResponse)
}
}
var r1 error
if rf, ok := ret.Get(1).(func(*state.QueryRequest) error); ok {
r1 = rf(req)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
func (f *FailingStatestore) Query(ctx context.Context, req *state.QueryRequest) (*state.QueryResponse, error) {
key := req.Metadata["key"]
err := f.Failure.PerformFailure(key)
if err != nil {
return nil, err
}
return &state.QueryResponse{}, nil
}
|
mikeee/dapr
|
pkg/testing/querier_mock.go
|
GO
|
mit
| 1,115 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"github.com/dapr/dapr/pkg/apis/resiliency/v1alpha1"
"github.com/dapr/kit/ptr"
)
var TestResiliency = &v1alpha1.Resiliency{
Spec: v1alpha1.ResiliencySpec{
Policies: v1alpha1.Policies{
Retries: map[string]v1alpha1.Retry{
"singleRetry": {
MaxRetries: ptr.Of(1),
MaxInterval: "100ms",
Policy: "constant",
Duration: "10ms",
},
},
Timeouts: map[string]string{
"fast": "100ms",
},
},
Targets: v1alpha1.Targets{
Components: map[string]v1alpha1.ComponentPolicyNames{
"failOutput": {
Outbound: v1alpha1.PolicyNames{
Retry: "singleRetry",
Timeout: "fast",
},
},
"failPubsub": {
Outbound: v1alpha1.PolicyNames{
Retry: "singleRetry",
Timeout: "fast",
},
Inbound: v1alpha1.PolicyNames{
Retry: "singleRetry",
Timeout: "fast",
},
},
"failingInputBinding": {
Inbound: v1alpha1.PolicyNames{
Retry: "singleRetry",
Timeout: "fast",
},
},
},
},
},
}
|
mikeee/dapr
|
pkg/testing/resiliency.go
|
GO
|
mit
| 1,608 |
{
"kid": "rsa-public",
"kty": "RSA",
"alg": "RSA-OAEP",
"e": "AQAB",
"n": "3I2mdIK4mRRu-ywMrYjUZzBxt0NlAVLrMhGlaJsby7PWTMiLpZVip4SBD9GwnCU0TGFD7k2-7tfs0y9U6WV7MwgCjc9m_DUUGbE-kKjEU7JYkLzYlndys-6xuhD4Jf1hu9AZVdfXftpWSy_NNg6fVwTH4nckOAbOSL1hXToOYWQcDDW95Rhw3U4z04PqssEpRKn5KGBuTahNNNiZcWns99pChpLTxgdm93LjMBI1KCGBpOaz7fcQJ9V3c6rSwMKyY3IPm1LwS6PIs7xb2ZJ0Eb8A6MtCkGhgNsodpkxhqKbqtxI-KqTuZy9g4jb8WKjJq9lB9q-HPHoQqIEDom6P8w"
}
|
mikeee/dapr
|
pkg/testing/rsa-pub.json
|
JSON
|
mit
| 441 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"context"
"errors"
"github.com/dapr/components-contrib/secretstores"
)
type FakeSecretStore struct{}
func (c FakeSecretStore) GetSecret(ctx context.Context, req secretstores.GetSecretRequest) (secretstores.GetSecretResponse, error) {
if req.Name == "good-key" {
return secretstores.GetSecretResponse{
Data: map[string]string{"good-key": "life is good"},
}, nil
}
if req.Name == "error-key" {
return secretstores.GetSecretResponse{}, errors.New("error occurs with error-key")
}
return secretstores.GetSecretResponse{}, nil
}
func (c FakeSecretStore) BulkGetSecret(ctx context.Context, req secretstores.BulkGetSecretRequest) (secretstores.BulkGetSecretResponse, error) {
response := map[string]map[string]string{}
response["good-key"] = map[string]string{"good-key": "life is good"}
return secretstores.BulkGetSecretResponse{
Data: response,
}, nil
}
func (c FakeSecretStore) Init(ctx context.Context, metadata secretstores.Metadata) error {
return nil
}
func (c FakeSecretStore) Close() error {
return nil
}
func (c FakeSecretStore) Features() []secretstores.Feature {
return []secretstores.Feature{secretstores.FeatureMultipleKeyValuesPerSecret}
}
type FailingSecretStore struct {
Failure Failure
}
func (c FailingSecretStore) GetSecret(ctx context.Context, req secretstores.GetSecretRequest) (secretstores.GetSecretResponse, error) {
err := c.Failure.PerformFailure(req.Name)
if err != nil {
return secretstores.GetSecretResponse{}, err
}
return secretstores.GetSecretResponse{
Data: map[string]string{req.Name: "secret"},
}, nil
}
func (c FailingSecretStore) BulkGetSecret(ctx context.Context, req secretstores.BulkGetSecretRequest) (secretstores.BulkGetSecretResponse, error) {
key := req.Metadata["key"]
err := c.Failure.PerformFailure(key)
if err != nil {
return secretstores.BulkGetSecretResponse{}, err
}
return secretstores.BulkGetSecretResponse{
Data: map[string]map[string]string{},
}, nil
}
func (c FailingSecretStore) Init(ctx context.Context, metadata secretstores.Metadata) error {
return nil
}
func (c FailingSecretStore) Close() error {
return nil
}
func (c FailingSecretStore) Features() []secretstores.Feature {
return []secretstores.Feature{}
}
|
mikeee/dapr
|
pkg/testing/secrets_mock.go
|
GO
|
mit
| 2,818 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"context"
"sync/atomic"
mock "github.com/stretchr/testify/mock"
state "github.com/dapr/components-contrib/state"
)
// MockStateStore is an autogenerated mock type for the Store type
type MockStateStore struct {
mock.Mock
}
func (_m *MockStateStore) BulkDelete(ctx context.Context, req []state.DeleteRequest, opts state.BulkStoreOpts) error {
ret := _m.Called(ctx, req)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, []state.DeleteRequest) error); ok {
r0 = rf(ctx, req)
} else {
r0 = ret.Error(0)
}
return r0
}
func (_m *MockStateStore) BulkSet(ctx context.Context, req []state.SetRequest, opts state.BulkStoreOpts) error {
ret := _m.Called(ctx, req)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, []state.SetRequest) error); ok {
r0 = rf(ctx, req)
} else {
r0 = ret.Error(0)
}
return r0
}
// Delete provides a mock function with given fields: req
func (_m *MockStateStore) Delete(ctx context.Context, req *state.DeleteRequest) error {
ret := _m.Called(ctx, req)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *state.DeleteRequest) error); ok {
r0 = rf(ctx, req)
} else {
r0 = ret.Error(0)
}
return r0
}
// Get provides a mock function with given fields: req
func (_m *MockStateStore) Get(ctx context.Context, req *state.GetRequest) (*state.GetResponse, error) {
ret := _m.Called(ctx, req)
var r0 *state.GetResponse
if rf, ok := ret.Get(0).(func(context.Context, *state.GetRequest) *state.GetResponse); ok {
r0 = rf(ctx, req)
} else if ret.Get(0) != nil {
r0 = ret.Get(0).(*state.GetResponse)
}
var r1 error
if rf, ok := ret.Get(1).(func(context.Context, *state.GetRequest) error); ok {
r1 = rf(ctx, req)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
func (_m *MockStateStore) BulkGet(ctx context.Context, req []state.GetRequest, opts state.BulkGetOpts) ([]state.BulkGetResponse, error) {
return nil, nil
}
// Init provides a mock function with given fields: metadata
func (_m *MockStateStore) Init(ctx context.Context, metadata state.Metadata) error {
ret := _m.Called(metadata)
var r0 error
if rf, ok := ret.Get(0).(func(state.Metadata) error); ok {
r0 = rf(metadata)
} else {
r0 = ret.Error(0)
}
return r0
}
// Ping provides a mock function
func (_m *MockStateStore) Ping() error {
return nil
}
// Set provides a mock function with given fields: req
func (_m *MockStateStore) Set(ctx context.Context, req *state.SetRequest) error {
ret := _m.Called(ctx, req)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *state.SetRequest) error); ok {
r0 = rf(ctx, req)
} else {
r0 = ret.Error(0)
}
return r0
}
// Features returns the features for this state store.
func (_m *MockStateStore) Features() []state.Feature {
return nil
}
func (_m *MockStateStore) Close() error {
return nil
}
type FailingStatestore struct {
Failure Failure
BulkFailKey atomic.Pointer[string]
}
func (f *FailingStatestore) BulkDelete(ctx context.Context, req []state.DeleteRequest, opts state.BulkStoreOpts) error {
for _, val := range req {
err := f.Failure.PerformFailure(val.Key)
if err != nil {
return err
}
}
return nil
}
func (f *FailingStatestore) BulkSet(ctx context.Context, req []state.SetRequest, opts state.BulkStoreOpts) error {
for _, val := range req {
err := f.Failure.PerformFailure(val.Key)
if err != nil {
return err
}
}
return nil
}
func (f *FailingStatestore) Delete(ctx context.Context, req *state.DeleteRequest) error {
return f.Failure.PerformFailure(req.Key)
}
func (f *FailingStatestore) Get(ctx context.Context, req *state.GetRequest) (*state.GetResponse, error) {
err := f.Failure.PerformFailure(req.Key)
if err != nil {
return nil, err
}
var res *state.GetResponse
if req.Key != "nilGetKey" {
res = &state.GetResponse{}
}
return res, nil
}
func (f *FailingStatestore) BulkGet(ctx context.Context, req []state.GetRequest, opts state.BulkGetOpts) ([]state.BulkGetResponse, error) {
bfk := f.BulkFailKey.Load()
if bfk != nil && *bfk != "" {
err := f.Failure.PerformFailure(*bfk)
if err != nil {
return nil, err
}
}
// Return keys one by one
res := []state.BulkGetResponse{}
for i := range req {
r, err := f.Get(ctx, &req[i])
if err != nil {
res = append(res, state.BulkGetResponse{
Key: req[i].Key,
Error: err.Error(),
})
continue
}
res = append(res, state.BulkGetResponse{
Key: req[i].Key,
Data: r.Data,
ETag: r.ETag,
ContentType: r.ContentType,
Metadata: r.Metadata,
})
}
return res, nil
}
func (f *FailingStatestore) Init(ctx context.Context, metadata state.Metadata) error {
return nil
}
func (f *FailingStatestore) Ping() error {
return nil
}
func (f *FailingStatestore) Set(ctx context.Context, req *state.SetRequest) error {
return f.Failure.PerformFailure(req.Key)
}
func (f *FailingStatestore) Close() error {
return nil
}
|
mikeee/dapr
|
pkg/testing/state_mock.go
|
GO
|
mit
| 5,512 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
context "context"
mock "github.com/stretchr/testify/mock"
configuration "github.com/dapr/components-contrib/configuration"
)
// MockConfigurationStore is an autogenerated mock type for the Store type
type MockConfigurationStore struct {
mock.Mock
}
// Get provides a mock function with given fields: ctx, req
func (_m *MockConfigurationStore) Get(ctx context.Context, req *configuration.GetRequest) (*configuration.GetResponse, error) {
ret := _m.Called(ctx, req)
var r0 *configuration.GetResponse
if rf, ok := ret.Get(0).(func(context.Context, *configuration.GetRequest) *configuration.GetResponse); ok {
r0 = rf(ctx, req)
} else if ret.Get(0) != nil {
r0 = ret.Get(0).(*configuration.GetResponse)
}
var r1 error
if rf, ok := ret.Get(1).(func(context.Context, *configuration.GetRequest) error); ok {
r1 = rf(ctx, req)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Init provides a mock function with given fields: metadata
func (_m *MockConfigurationStore) Init(ctx context.Context, metadata configuration.Metadata) error {
ret := _m.Called(metadata)
var r0 error
if rf, ok := ret.Get(0).(func(configuration.Metadata) error); ok {
r0 = rf(metadata)
} else {
r0 = ret.Error(0)
}
return r0
}
// Subscribe provides a mock function with given fields: ctx, req, handler
func (_m *MockConfigurationStore) Subscribe(ctx context.Context, req *configuration.SubscribeRequest, handler configuration.UpdateHandler) (string, error) {
ret := _m.Called(ctx, req, handler)
var r0 string
if rf, ok := ret.Get(0).(func(context.Context, *configuration.SubscribeRequest, configuration.UpdateHandler) string); ok {
r0 = rf(ctx, req, handler)
} else if ret.Get(0) != nil {
r0 = ret.Get(0).(string)
}
var r1 error
if rf, ok := ret.Get(1).(func(context.Context, *configuration.SubscribeRequest, configuration.UpdateHandler) error); ok {
r1 = rf(ctx, req, handler)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// Unsubscribe provides a mock function with given fields: ctx, req
func (_m *MockConfigurationStore) Unsubscribe(ctx context.Context, req *configuration.UnsubscribeRequest) error {
ret := _m.Called(ctx, req)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *configuration.UnsubscribeRequest) error); ok {
r0 = rf(ctx, req)
} else {
r0 = ret.Error(0)
}
return r0
}
type FailingConfigurationStore struct {
Failure Failure
}
func (f *FailingConfigurationStore) Get(ctx context.Context, req *configuration.GetRequest) (*configuration.GetResponse, error) {
if err := f.Failure.PerformFailure(req.Metadata["key"]); err != nil {
return nil, err
}
return &configuration.GetResponse{}, nil
}
func (f *FailingConfigurationStore) Init(ctx context.Context, metadata configuration.Metadata) error {
return nil
}
func (f *FailingConfigurationStore) Subscribe(ctx context.Context, req *configuration.SubscribeRequest, handler configuration.UpdateHandler) (string, error) {
if err := f.Failure.PerformFailure(req.Metadata["key"]); err != nil {
return "", err
}
go handler(ctx, &configuration.UpdateEvent{
Items: map[string]*configuration.Item{
req.Metadata["key"]: {
Value: "testConfig",
},
},
})
return "subscribeID", nil
}
func (f *FailingConfigurationStore) Unsubscribe(ctx context.Context, req *configuration.UnsubscribeRequest) error {
return f.Failure.PerformFailure(req.ID)
}
|
mikeee/dapr
|
pkg/testing/store_mock.go
|
GO
|
mit
| 3,967 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//nolint:goconst
package testing
import (
"context"
"errors"
// Blank import for the embed package.
_ "embed"
"github.com/lestrrat-go/jwx/v2/jwk"
contribCrypto "github.com/dapr/components-contrib/crypto"
)
var (
//go:embed rsa-pub.json
rsaPubJWK []byte
oneHundredTwentyEightBits = []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
)
// Type assertions for the interface
var (
_ contribCrypto.SubtleCrypto = (*FakeSubtleCrypto)(nil)
_ contribCrypto.SubtleCrypto = (*FailingSubtleCrypto)(nil)
)
type FakeSubtleCrypto struct{}
func (c FakeSubtleCrypto) GetKey(ctx context.Context, keyName string) (pubKey jwk.Key, err error) {
switch keyName {
case "good-key":
return jwk.ParseKey(rsaPubJWK)
case "error-key":
return nil, errors.New("error occurs with error-key")
case "with-name":
pubKey, _ = jwk.ParseKey(rsaPubJWK)
pubKey = contribCrypto.NewKey(pubKey, "my-name-is-giovanni-giorgio", nil, nil)
return
}
return nil, nil
}
func (c FakeSubtleCrypto) Encrypt(ctx context.Context, plaintext []byte, algorithm string, keyName string, nonce []byte, associatedData []byte) (ciphertext []byte, tag []byte, err error) {
// Doesn't actually do any encryption
switch keyName {
case "good-notag":
ciphertext = plaintext
case "good-tag":
ciphertext = plaintext
tag = oneHundredTwentyEightBits
case "error":
err = errors.New("simulated error")
}
return
}
func (c FakeSubtleCrypto) Decrypt(ctx context.Context, ciphertext []byte, algorithm string, keyName string, nonce []byte, tag []byte, associatedData []byte) (plaintext []byte, err error) {
// Doesn't actually do any encryption
switch keyName {
case "good":
plaintext = ciphertext
case "error":
err = errors.New("simulated error")
}
return
}
func (c FakeSubtleCrypto) WrapKey(ctx context.Context, plaintextKey jwk.Key, algorithm string, keyName string, nonce []byte, associatedData []byte) (wrappedKey []byte, tag []byte, err error) {
// Doesn't actually do any encryption
switch keyName {
case "good-notag":
wrappedKey = oneHundredTwentyEightBits
case "good-tag":
wrappedKey = oneHundredTwentyEightBits
tag = oneHundredTwentyEightBits
case "error":
err = errors.New("simulated error")
case "aes-passthrough":
err = plaintextKey.Raw(&wrappedKey)
}
return
}
func (c FakeSubtleCrypto) UnwrapKey(ctx context.Context, wrappedKey []byte, algorithm string, keyName string, nonce []byte, tag []byte, associatedData []byte) (plaintextKey jwk.Key, err error) {
// Doesn't actually do any encryption
switch keyName {
case "good", "good-notag", "good-tag":
return jwk.FromRaw(oneHundredTwentyEightBits)
case "error":
err = errors.New("simulated error")
case "aes-passthrough":
return jwk.FromRaw(wrappedKey)
}
return
}
func (c FakeSubtleCrypto) Sign(ctx context.Context, digest []byte, algorithm string, keyName string) (signature []byte, err error) {
switch keyName {
case "good":
signature = oneHundredTwentyEightBits
case "error":
err = errors.New("simulated error")
}
return
}
func (c FakeSubtleCrypto) Verify(ctx context.Context, digest []byte, signature []byte, algorithm string, keyName string) (valid bool, err error) {
switch keyName {
case "good":
valid = true
case "bad":
valid = false
case "error":
err = errors.New("simulated error")
}
return
}
func (c FakeSubtleCrypto) SupportedEncryptionAlgorithms() []string {
return []string{}
}
func (c FakeSubtleCrypto) SupportedSignatureAlgorithms() []string {
return []string{}
}
func (c FakeSubtleCrypto) Init(ctx context.Context, metadata contribCrypto.Metadata) error {
return nil
}
func (c FakeSubtleCrypto) Close() error {
return nil
}
func (c FakeSubtleCrypto) Features() []contribCrypto.Feature {
return []contribCrypto.Feature{}
}
type FailingSubtleCrypto struct {
FakeSubtleCrypto
Failure Failure
}
func (c FailingSubtleCrypto) GetKey(ctx context.Context, keyName string) (pubKey jwk.Key, err error) {
err = c.Failure.PerformFailure(keyName)
if err != nil {
return
}
return c.FakeSubtleCrypto.GetKey(ctx, keyName)
}
func (c FailingSubtleCrypto) Encrypt(ctx context.Context, plaintext []byte, algorithm string, keyName string, nonce []byte, associatedData []byte) (ciphertext []byte, tag []byte, err error) {
err = c.Failure.PerformFailure(algorithm)
if err != nil {
return
}
return c.FakeSubtleCrypto.Encrypt(ctx, plaintext, algorithm, keyName, nonce, associatedData)
}
func (c FailingSubtleCrypto) Decrypt(ctx context.Context, ciphertext []byte, algorithm string, keyName string, nonce []byte, tag []byte, associatedData []byte) (plaintext []byte, err error) {
err = c.Failure.PerformFailure(algorithm)
if err != nil {
return
}
return c.FakeSubtleCrypto.Decrypt(ctx, ciphertext, algorithm, keyName, nonce, tag, associatedData)
}
func (c FailingSubtleCrypto) WrapKey(ctx context.Context, plaintextKey jwk.Key, algorithm string, keyName string, nonce []byte, associatedData []byte) (wrappedKey []byte, tag []byte, err error) {
err = c.Failure.PerformFailure(algorithm)
if err != nil {
return
}
return c.FakeSubtleCrypto.WrapKey(ctx, plaintextKey, algorithm, keyName, nonce, associatedData)
}
func (c FailingSubtleCrypto) UnwrapKey(ctx context.Context, wrappedKey []byte, algorithm string, keyName string, nonce []byte, tag []byte, associatedData []byte) (plaintextKey jwk.Key, err error) {
err = c.Failure.PerformFailure(algorithm)
if err != nil {
return
}
return c.FakeSubtleCrypto.UnwrapKey(ctx, wrappedKey, algorithm, keyName, nonce, tag, associatedData)
}
func (c FailingSubtleCrypto) Sign(ctx context.Context, digest []byte, algorithm string, keyName string) (signature []byte, err error) {
err = c.Failure.PerformFailure(algorithm)
if err != nil {
return
}
return c.FakeSubtleCrypto.Sign(ctx, digest, algorithm, keyName)
}
func (c FailingSubtleCrypto) Verify(ctx context.Context, digest []byte, signature []byte, algorithm string, keyName string) (valid bool, err error) {
err = c.Failure.PerformFailure(algorithm)
if err != nil {
return
}
return c.FakeSubtleCrypto.Verify(ctx, digest, signature, algorithm, keyName)
}
|
mikeee/dapr
|
pkg/testing/subtlecrypto_mock.go
|
GO
|
mit
| 6,693 |
package trace
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
"github.com/dapr/kit/logger"
)
// NewStringExporter returns a new string exporter instance.
//
// It is very useful in testing scenario where we want to validate trace propagation.
func NewStringExporter(buffer *string, logger logger.Logger) *Exporter {
return &Exporter{
Buffer: buffer,
logger: logger,
}
}
// Exporter is an OpenTelemetry string exporter.
type Exporter struct {
Buffer *string
logger logger.Logger
}
// ExportSpan exports span content to the buffer.
func (se *Exporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
*se.Buffer = spans[0].Status().Code.String()
return nil
}
// ExportSpan exports span content to the buffer.
func (se *Exporter) Shutdown(ctx context.Context) error {
return nil
}
// Register creates a new string exporter endpoint and reporter.
func (se *Exporter) Register(daprID string) {
// Register a resource
r := resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(daprID),
)
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(se),
sdktrace.WithResource(r),
)
otel.SetTracerProvider(tp)
}
|
mikeee/dapr
|
pkg/testing/trace/trace.go
|
GO
|
mit
| 1,318 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"context"
"github.com/dapr/components-contrib/state"
)
type TransactionalStoreMock struct {
MaxOperations int
MockStateStore
}
// Code generated by mockery v2.3.0. DO NOT EDIT.
func (storeMock *TransactionalStoreMock) Multi(ctx context.Context, request *state.TransactionalStateRequest) error {
ret := storeMock.Called(ctx, request)
var r0 error
if rf, ok := ret.Get(0).(func(context.Context, *state.TransactionalStateRequest) error); ok {
r0 = rf(ctx, request)
} else {
r0 = ret.Error(0)
}
return r0
}
func (storeMock *TransactionalStoreMock) Features() []state.Feature {
return []state.Feature{state.FeatureTransactional}
}
func (storeMock *TransactionalStoreMock) Close() error {
return nil
}
func (storeMock *TransactionalStoreMock) MultiMaxSize() int {
return storeMock.MaxOperations
}
func (f *FailingStatestore) Multi(ctx context.Context, request *state.TransactionalStateRequest) error {
for _, op := range request.Operations {
switch req := op.(type) {
case state.DeleteRequest:
err := f.Failure.PerformFailure(req.Key)
if err != nil {
return err
}
case state.SetRequest:
err := f.Failure.PerformFailure(req.Key)
if err != nil {
return err
}
}
}
return nil
}
func (f *FailingStatestore) Features() []state.Feature {
return []state.Feature{state.FeatureTransactional, state.FeatureETag}
}
|
mikeee/dapr
|
pkg/testing/transactionalstore_mock.go
|
GO
|
mit
| 1,949 |
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testing
import (
"context"
"errors"
"time"
workflowContrib "github.com/dapr/components-contrib/workflows"
)
type MockWorkflow struct{}
const ErrorInstanceID = "errorInstanceID"
var (
ErrFakeWorkflowComponentError = errors.New("fake workflow error")
ErrFakeWorkflowNonRecursiveTerminateError = errors.New("fake workflow non recursive terminate error")
ErrFakeWorkflowNonRecurisvePurgeError = errors.New("fake workflow non recursive purge error")
)
func (w *MockWorkflow) Init(metadata workflowContrib.Metadata) error {
return nil
}
func (w *MockWorkflow) Start(ctx context.Context, req *workflowContrib.StartRequest) (*workflowContrib.StartResponse, error) {
if req.InstanceID == ErrorInstanceID {
return nil, ErrFakeWorkflowComponentError
}
res := &workflowContrib.StartResponse{
InstanceID: req.InstanceID,
}
return res, nil
}
func (w *MockWorkflow) Terminate(ctx context.Context, req *workflowContrib.TerminateRequest) error {
if req.InstanceID == ErrorInstanceID {
return ErrFakeWorkflowComponentError
}
if !req.Recursive {
// Returning fake error to test non recursive terminate
return ErrFakeWorkflowNonRecursiveTerminateError
}
return nil
}
func (w *MockWorkflow) Get(ctx context.Context, req *workflowContrib.GetRequest) (*workflowContrib.StateResponse, error) {
if req.InstanceID == ErrorInstanceID {
return nil, ErrFakeWorkflowComponentError
}
res := &workflowContrib.StateResponse{
Workflow: &workflowContrib.WorkflowState{
InstanceID: req.InstanceID,
WorkflowName: "mockWorkflowName",
CreatedAt: time.Now(),
LastUpdatedAt: time.Now(),
RuntimeStatus: "TESTING",
},
}
return res, nil
}
func (w *MockWorkflow) RaiseEvent(ctx context.Context, req *workflowContrib.RaiseEventRequest) error {
if req.InstanceID == ErrorInstanceID {
return ErrFakeWorkflowComponentError
}
return nil
}
func (w *MockWorkflow) Pause(ctx context.Context, req *workflowContrib.PauseRequest) error {
if req.InstanceID == ErrorInstanceID {
return ErrFakeWorkflowComponentError
}
return nil
}
func (w *MockWorkflow) Resume(ctx context.Context, req *workflowContrib.ResumeRequest) error {
if req.InstanceID == ErrorInstanceID {
return ErrFakeWorkflowComponentError
}
return nil
}
func (w *MockWorkflow) Purge(ctx context.Context, req *workflowContrib.PurgeRequest) error {
if req.InstanceID == ErrorInstanceID {
return ErrFakeWorkflowComponentError
}
if !req.Recursive {
// Returning fake error to test non recursive purge
return ErrFakeWorkflowNonRecurisvePurgeError
}
return nil
}
|
mikeee/dapr
|
pkg/testing/workflow_mock.go
|
GO
|
mit
| 3,148 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package validation
import (
"errors"
"fmt"
"regexp"
"strings"
)
// The consts and vars beginning with dns* were taken from: https://github.com/kubernetes/apimachinery/blob/fc49b38c19f02a58ebc476347e622142f19820b9/pkg/util/validation/validation.go
const (
dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?"
dns1123LabelErrMsg string = "a lowercase RFC 1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character"
dns1123LabelMaxLength int = 63
)
var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$")
// ValidateKubernetesAppID returns an error if the Dapr app id is not valid for the Kubernetes platform.
func ValidateKubernetesAppID(appID string) error {
if appID == "" {
return errors.New("value for the dapr.io/app-id annotation is empty")
}
err := isDNS1123Label(serviceName(appID))
if err != nil {
return fmt.Errorf("invalid app id (input: '%s', service: '%s'): %w", appID, serviceName(appID), err)
}
return nil
}
// ValidateSelfHostedAppID returns an error if the Dapr app id is not valid for self-hosted.
func ValidateSelfHostedAppID(appID string) error {
if appID == "" {
return errors.New("parameter app-id cannot be empty")
}
if strings.Contains(appID, ".") {
return errors.New("parameter app-id cannot contain dots")
}
return nil
}
func serviceName(appID string) string {
return fmt.Sprintf("%s-dapr", appID)
}
// The function was adapted from: https://github.com/kubernetes/apimachinery/blob/fc49b38c19f02a58ebc476347e622142f19820b9/pkg/util/validation/validation.go
func isDNS1123Label(value string) error {
var errs []error
if len(value) > dns1123LabelMaxLength {
errs = append(errs, fmt.Errorf("must be no more than %d characters", dns1123LabelMaxLength))
}
if !dns1123LabelRegexp.MatchString(value) {
errs = append(errs, regexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc"))
}
return errors.Join(errs...)
}
// The function was adapted from: https://github.com/kubernetes/apimachinery/blob/fc49b38c19f02a58ebc476347e622142f19820b9/pkg/util/validation/validation.go
func regexError(msg string, fmt string, examples ...string) error {
if len(examples) == 0 {
return errors.New(msg + " (regex used for validation is '" + fmt + "')")
}
msg += " (e.g. "
for i := range examples {
if i > 0 {
msg += " or "
}
msg += "'" + examples[i] + "', "
}
msg += "regex used for validation is '" + fmt + "')"
return errors.New(msg)
}
|
mikeee/dapr
|
pkg/validation/validation.go
|
GO
|
mit
| 3,071 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package validation
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateKubernetesAppID(t *testing.T) {
t.Run("invalid length", func(t *testing.T) {
id := ""
for i := 0; i < 64; i++ {
id += "a"
}
err := ValidateKubernetesAppID(id)
require.Error(t, err)
})
t.Run("invalid length if suffix -dapr is appended", func(t *testing.T) {
// service name id+"-dapr" exceeds 63 characters (59 + 5 = 64)
id := strings.Repeat("a", 59)
err := ValidateKubernetesAppID(id)
require.Error(t, err)
})
t.Run("valid id", func(t *testing.T) {
id := "my-app-id"
err := ValidateKubernetesAppID(id)
require.NoError(t, err)
})
t.Run("invalid char: .", func(t *testing.T) {
id := "my-app-id.app"
err := ValidateKubernetesAppID(id)
require.Error(t, err)
})
t.Run("invalid chars space", func(t *testing.T) {
id := "my-app-id app"
err := ValidateKubernetesAppID(id)
require.Error(t, err)
})
t.Run("invalid empty", func(t *testing.T) {
id := ""
err := ValidateKubernetesAppID(id)
assert.Contains(t, "value for the dapr.io/app-id annotation is empty", err.Error())
})
}
func TestValidateSelfHostedAppID(t *testing.T) {
t.Run("valid id", func(t *testing.T) {
id := "my-app-id"
err := ValidateSelfHostedAppID(id)
require.NoError(t, err)
})
t.Run("contains a dot", func(t *testing.T) {
id := "my-app-id.app"
err := ValidateSelfHostedAppID(id)
require.Error(t, err)
})
t.Run("contains multiple dots", func(t *testing.T) {
id := "foo.bar.baz"
err := ValidateSelfHostedAppID(id)
require.Error(t, err)
})
t.Run("invalid empty", func(t *testing.T) {
id := ""
err := ValidateSelfHostedAppID(id)
assert.Contains(t, "parameter app-id cannot be empty", err.Error())
})
}
|
mikeee/dapr
|
pkg/validation/validation_test.go
|
GO
|
mit
| 2,363 |
{
"openapi": "3.0.2",
"info": {
"title": "Service Invocation",
"version": "1.0",
"description": "Using the service invocation API, your microservice can find and reliably communicate with other microservices in your system using standard protocols (gRPC or HTTP are currently supported).",
"termsOfService": "https://github.com/dapr/docs/blob/master/LICENSE",
"contact": {},
"license": {
"name": "Apache 2.0 License",
"url": "https://github.com/dapr/docs/blob/master/LICENSE"
},
"x-logo": {
"url": ""
}
},
"servers": [
{
"url": "http://{url}",
"description": "This endpoint lets you invoke a method in another Dapr enabled app.",
"variables": {
"url": {
"default": "localhost:3500",
"description": "url"
}
},
"x-last-modified": 1597254685557
}
],
"paths": {
"/v1.0/invoke/{appId}/method/{method-name}": {
"description": "This endpoint lets you invoke a method in another Dapr enabled app.",
"get": {
"tags": [
"invocation",
"service"
],
"parameters": [
{
"deprecated": false,
"$ref": "#/components/parameters/appId"
},
{
"deprecated": false,
"$ref": "#/components/parameters/method-name"
},
{
"deprecated": false,
"$ref": "#/components/parameters/Content-Type"
},
{
"$ref": "#/components/securitySchemes/ApiKeyAuth",
"name": "ApiKeyAuth",
"x-last-modified": 1597270199372
}
],
"responses": {
"200": {
"$ref": "#/components/responses/200"
},
"500": {
"$ref": "#/components/responses/500"
}
},
"deprecated": false,
"operationId": "invoke_get",
"summary": "Invoke a method on a remote dapr app",
"description": "This endpoint lets you invoke a method in another Dapr enabled app.",
"externalDocs": {
"description": "Documentation",
"url": "https://docs.dapr.io/reference/api/service_invocation_api/"
}
},
"put": {
"requestBody": {
"description": "Within the body of the request place the data you want to send to the service:\n{\n \"arg1\": 10,\n \"arg2\": 23,\n \"operator\": \"+\"\n}\n",
"content": {
"application/json": {
"schema": {
"description": "any app arguments",
"type": "object",
"example": {
"arg1": 10,
"arg2": 23,
"operator": "+"
},
"x-rc-meta": {
"x-rc-comments": {}
}
},
"example": {
"arg1": 10,
"arg2": 23,
"operator": "+"
},
"x-rc-meta": {
"x-rc-comments": {}
}
}
}
},
"tags": [
"invocation",
"service"
],
"parameters": [
{
"deprecated": false,
"$ref": "#/components/parameters/appId"
},
{
"deprecated": false,
"$ref": "#/components/parameters/method-name"
},
{
"deprecated": false,
"$ref": "#/components/parameters/Content-Type",
"name": "Content-Type"
},
{
"$ref": "#/components/securitySchemes/ApiKeyAuth",
"name": "ApiKeyAuth",
"x-last-modified": 1597270378537
}
],
"responses": {
"200": {
"$ref": "#/components/responses/200"
},
"500": {
"$ref": "#/components/responses/500"
}
},
"operationId": "invoke_put",
"summary": "This endpoint lets you invoke a method in another Dapr enabled app.",
"externalDocs": {
"url": "https://docs.dapr.io/reference/api/service_invocation_api/"
}
},
"post": {
"requestBody": {
"description": "Within the body of the request place the data you want to send to the service:\n{\n \"arg1\": 10,\n \"arg2\": 23,\n \"operator\": \"+\"\n}\n",
"content": {
"application/json": {
"schema": {
"description": "Within the body of the request place the data you want to send to the service:\n{\n \"arg1\": 10,\n \"arg2\": 23,\n \"operator\": \"+\"\n}",
"type": "object",
"example": {
"arg1": 10,
"arg2": 23,
"operator": "+"
},
"x-rc-meta": {
"x-rc-comments": {}
}
},
"example": {
"arg1": 10,
"arg2": 23,
"operator": "+"
},
"x-rc-meta": {
"x-rc-comments": {}
}
}
}
},
"tags": [
"invocation",
"service"
],
"parameters": [
{
"deprecated": false,
"$ref": "#/components/parameters/appId"
},
{
"deprecated": false,
"$ref": "#/components/parameters/method-name"
},
{
"deprecated": false,
"$ref": "#/components/parameters/Content-Type"
},
{
"$ref": "#/components/securitySchemes/ApiKeyAuth",
"name": "ApiKeyAuth",
"x-last-modified": 1597270398630
}
],
"responses": {
"200": {
"$ref": "#/components/responses/200"
},
"500": {
"$ref": "#/components/responses/500"
}
},
"operationId": "invoke_post",
"summary": "This endpoint lets you invoke a method in another Dapr enabled app.",
"externalDocs": {
"url": "https://docs.dapr.io/reference/api/service_invocation_api/"
}
},
"delete": {
"tags": [
"invocation",
"service"
],
"parameters": [
{
"deprecated": false,
"$ref": "#/components/parameters/appId"
},
{
"deprecated": false,
"$ref": "#/components/parameters/method-name"
},
{
"deprecated": false,
"$ref": "#/components/parameters/Content-Type"
},
{
"$ref": "#/components/securitySchemes/ApiKeyAuth",
"name": "ApiKeyAuth",
"x-last-modified": 1597270419336
}
],
"responses": {
"200": {
"$ref": "#/components/responses/200"
},
"500": {
"$ref": "#/components/responses/500"
}
},
"operationId": "invoke_delete",
"summary": "This endpoint lets you invoke a method in another Dapr enabled app."
},
"x-last-modified": 1597254788230
}
},
"components": {
"responses": {
"200": {
"content": {
"text/plain": {
"schema": {
"type": "number",
"example": "",
"x-rc-meta": {
"x-rc-comments": {}
}
},
"example": 200,
"x-rc-meta": {
"x-rc-comments": {}
}
}
},
"description": "Operation succeeded",
"x-last-modified": 1597011885893
},
"500": {
"content": {
"text/plain": {
"schema": {
"format": "",
"pattern": "",
"type": "number",
"example": 500,
"x-rc-meta": {
"x-rc-comments": {}
}
},
"example": 500,
"x-rc-meta": {
"x-rc-comments": {}
}
}
},
"description": "Server Error",
"x-last-modified": 1597011858483
}
},
"parameters": {
"method-name": {
"example": "neworder",
"name": "method-name",
"description": "name of the method to be invoked",
"schema": {
"format": "",
"description": "name of the method to be invoked",
"pattern": "",
"type": "string",
"example": "neworder",
"x-rc-meta": {
"x-rc-comments": {}
}
},
"in": "path",
"required": true,
"x-last-modified": 1597011358645,
"x-rc-meta": {
"x-rc-comments": {}
}
},
"appId": {
"example": "nodeapp",
"name": "appId",
"description": "the App ID associated with the remote app",
"schema": {
"format": "",
"description": "the App ID associated with the remote app",
"pattern": "",
"type": "string",
"example": "nodeapp",
"x-rc-meta": {
"x-rc-comments": {}
}
},
"in": "path",
"required": true,
"x-last-modified": 1597253939494,
"x-rc-meta": {
"x-rc-comments": {}
}
},
"Content-Type": {
"deprecated": false,
"example": "application/json",
"name": "Content-Type",
"description": "the App ID associated with the remote app",
"schema": {
"format": "",
"description": "the App ID associated with the remote app",
"pattern": "",
"type": "string",
"example": "application/json",
"x-rc-meta": {
"x-rc-comments": {}
}
},
"in": "header",
"required": false,
"x-last-modified": 1597269332645,
"x-rc-meta": {
"x-rc-comments": {}
}
}
},
"securitySchemes": {
"ApiKeyAuth": {
"type": "apiKey",
"name": "dapr-api-token",
"in": "header",
"x-last-modified": 1597014915425
}
},
"schemas": {}
},
"tags": [
{
"name": "service",
"description": "Dapr provides users with the ability to call other applications that have unique ids. This functionality allows apps to interact with one another via named identifiers and puts the burden of service discovery on the Dapr runtime.",
"externalDocs": {
"url": "https://docs.dapr.io/reference/api/service_invocation_api/"
},
"x-last-modified": 1594246229173
},
{
"name": "invocation",
"description": "Dapr provides users with the ability to call other applications that have unique ids. This functionality allows apps to interact with one another via named identifiers and puts the burden of service discovery on the Dapr runtime.",
"externalDocs": {
"url": "https://docs.dapr.io/reference/api/service_invocation_api/"
},
"x-last-modified": 1594246379461
}
],
"externalDocs": {
"description": "Dapr provides users with the ability to call other applications that have unique ids. This functionality allows apps to interact with one another via named identifiers and puts the burden of service discovery on the Dapr runtime.",
"url": "https://docs.dapr.io/reference/api/service_invocation_api/"
},
"security": []
}
|
mikeee/dapr
|
swagger/swagger.json
|
JSON
|
mit
| 15,275 |
# Tests
This contains end-to-end tests, related test framework, and docs for Dapr:
* **apps/** includes test apps used for end-to-end tests
* **config/** includes component configurations for the default state/pubsub/bindings
* **docs/** includes documents how write and run e2e test
* **e2e/** includes e2e test drivers written using go testing
* **perf/** includes performance test drivers written using go testing
* **platforms/** includes test app manager for the specific test platform
* **runner/** includes test runner to simplify e2e tests
* **test-infra/** includes tools for test-infra
* **integration/** includes tests that runs integration tests against the daprd binary
## End-to-end tests
> Note: We're actively working on supporting diverse platforms and adding more e2e tests. If you are interested in E2E tests, please see [Dapr E2E test](https://github.com/orgs/dapr/projects/9) project.
* [Running Performance tests](./docs/running-perf-tests.md)
* [Running E2E tests](./docs/running-e2e-test.md)
* [Writing E2E tests](./docs/writing-e2e-test.md)
|
mikeee/dapr
|
tests/README.md
|
Markdown
|
mit
| 1,071 |
*/app
actorapp/actorapp
actorfeatures/actorfeatures
stateapp/stateapp
pubsub-subscriber-routing/pubsub-subscriber-routing
pubsub-subscriber-routing_grpc/pubsub-subscriber-routing_grpc
*.exe
|
mikeee/dapr
|
tests/apps/.gitignore
|
Git
|
mit
| 190 |
#
# Copyright 2021 The Dapr Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
FROM gcr.io/distroless/base-nossl:nonroot
WORKDIR /app
COPY . .
CMD ["./app"]
|
mikeee/dapr
|
tests/apps/Dockerfile
|
Dockerfile
|
mit
| 659 |
#
# Copyright 2021 The Dapr Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
FROM mcr.microsoft.com/windows/nanoserver:ltsc2022
WORKDIR /app
COPY . .
CMD ["app.exe"]
|
mikeee/dapr
|
tests/apps/Dockerfile-windows
|
none
|
mit
| 670 |
../utils/*.go
|
mikeee/dapr
|
tests/apps/actorapp/.cache-include
|
none
|
mit
| 13 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"sync"
"time"
"github.com/dapr/dapr/tests/apps/utils"
"github.com/gorilla/mux"
)
const (
appPort = 3000
daprV1URL = "http://localhost:3500/v1.0"
actorMethodURLFormat = daprV1URL + "/actors/%s/%s/method/%s"
registeredActorType = "testactor" // Actor type must be unique per test app.
actorIdleTimeout = "5s" // Short idle timeout.
drainOngoingCallTimeout = "1s"
drainRebalancedActors = true
)
type daprActor struct {
actorType string
id string
value interface{}
}
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
Timestamp int `json:"timestamp,omitempty"`
}
type daprConfig struct {
Entities []string `json:"entities,omitempty"`
ActorIdleTimeout string `json:"actorIdleTimeout,omitempty"`
DrainOngoingCallTimeout string `json:"drainOngoingCallTimeout,omitempty"`
DrainRebalancedActors bool `json:"drainRebalancedActors,omitempty"`
}
var daprConfigResponse = daprConfig{
[]string{registeredActorType},
actorIdleTimeout,
drainOngoingCallTimeout,
drainRebalancedActors,
}
var (
actorLogs = []actorLogEntry{}
actorLogsMutex = &sync.Mutex{}
)
var actors sync.Map
func appendActorLog(logEntry actorLogEntry) {
actorLogsMutex.Lock()
defer actorLogsMutex.Unlock()
actorLogs = append(actorLogs, logEntry)
}
func getActorLogs() []actorLogEntry {
return actorLogs
}
func createActorID(actorType string, id string) string {
return actorType + "." + id
}
// indexHandler is the handler for root path
func indexHandler(w http.ResponseWriter, r *http.Request) {
log.Println("indexHandler is called")
w.WriteHeader(http.StatusOK)
}
func logsHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing dapr request for %s", r.URL.RequestURI())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(getActorLogs())
}
func configHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing dapr request for %s", r.URL.RequestURI())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(daprConfigResponse)
}
func actorMethodHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing actor method request for %s", r.URL.RequestURI())
actorType := mux.Vars(r)["actorType"]
id := mux.Vars(r)["id"]
method := mux.Vars(r)["method"]
actorID := createActorID(actorType, id)
log.Printf("storing actorID %s\n", actorID)
actors.Store(actorID, daprActor{
actorType: actorType,
id: actorID,
value: nil,
})
appendActorLog(actorLogEntry{
Action: method,
ActorType: actorType,
ActorID: id,
Timestamp: epoch(),
})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
}
//nolint:forbidigo
func deactivateActorHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s actor request for %s", r.Method, r.URL.RequestURI())
actorType := mux.Vars(r)["actorType"]
id := mux.Vars(r)["id"]
if actorType != registeredActorType {
log.Printf("Unknown actor type: %s", actorType)
w.WriteHeader(http.StatusBadRequest)
return
}
actorID := createActorID(actorType, id)
fmt.Printf("actorID is %s\n", actorID)
action := ""
_, ok := actors.Load(actorID)
log.Printf("loading returned:%t\n", ok)
if ok && r.Method == "DELETE" {
action = "deactivation"
actors.Delete(actorID)
}
appendActorLog(actorLogEntry{
Action: action,
ActorType: actorType,
ActorID: id,
Timestamp: epoch(),
})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
}
// calls Dapr's Actor method: simulating actor client call.
//
//nolint:gosec
func testCallActorHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s test request for %s", r.Method, r.URL.RequestURI())
actorType := mux.Vars(r)["actorType"]
id := mux.Vars(r)["id"]
method := mux.Vars(r)["method"]
invokeURL := fmt.Sprintf(actorMethodURLFormat, actorType, id, method)
log.Printf("Invoking %s", invokeURL)
res, err := http.Post(invokeURL, "application/json", bytes.NewBuffer([]byte{}))
if err != nil {
log.Printf("Could not test actor: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Printf("Could not read actor's test response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(body)
}
func healthzHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(""))
}
// epoch returns the current unix epoch timestamp
func epoch() int {
return (int)(time.Now().UTC().UnixNano() / 1000000)
}
// appRouter initializes restful api router
func appRouter() http.Handler {
router := mux.NewRouter().StrictSlash(true)
// Log requests and their processing time
router.Use(utils.LoggerMiddleware)
router.HandleFunc("/", indexHandler).Methods("GET")
router.HandleFunc("/dapr/config", configHandler).Methods("GET")
router.HandleFunc("/actors/{actorType}/{id}/method/{method}", actorMethodHandler).Methods("PUT")
router.HandleFunc("/actors/{actorType}/{id}", deactivateActorHandler).Methods("POST", "DELETE")
router.HandleFunc("/test/{actorType}/{id}/method/{method}", testCallActorHandler).Methods("POST")
router.HandleFunc("/test/logs", logsHandler).Methods("GET")
router.HandleFunc("/healthz", healthzHandler).Methods("GET")
router.Use(mux.CORSMethodMiddleware(router))
return router
}
func main() {
log.Printf("Actor App - listening on http://localhost:%d", appPort)
utils.StartServer(appPort, appRouter, true, false)
}
|
mikeee/dapr
|
tests/apps/actorapp/app.go
|
GO
|
mit
| 6,502 |
# In e2e test, this will not be used to deploy the app to test cluster.
# This is created for testing purpose in order to deploy this app using kubectl
# before writing e2e test.
kind: Service
apiVersion: v1
metadata:
name: actorapp
labels:
testapp: actorapp
spec:
selector:
testapp: actorapp
ports:
- protocol: TCP
port: 80
targetPort: 3000
type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: stateapp
labels:
testapp: actorapp
spec:
replicas: 1
selector:
matchLabels:
testapp: actorapp
template:
metadata:
labels:
testapp: actorapp
annotations:
dapr.io/enabled: "true"
dapr.io/app-id: "actorapp"
dapr.io/app-port: "3000"
spec:
containers:
- name: actorapp
image: docker.io/YOUR_ALIAS/e2e-actorapp:dev
ports:
- containerPort: 3000
imagePullPolicy: Always
|
mikeee/dapr
|
tests/apps/actorapp/service.yaml
|
YAML
|
mit
| 930 |
../utils/*.go
|
mikeee/dapr
|
tests/apps/actorclientapp/.cache-include
|
none
|
mit
| 13 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"github.com/dapr/dapr/tests/apps/utils"
"github.com/gorilla/mux"
)
const (
appPort = 3000
daprV1URL = "http://localhost:3500/v1.0"
actorMethodURLFormat = daprV1URL + "/actors/%s/%s/method/%s"
)
type daprActorResponse struct {
Data []byte `json:"data"`
Metadata map[string]string `json:"metadata"`
}
var httpClient = utils.NewHTTPClient()
// indexHandler is the handler for root path
func indexHandler(w http.ResponseWriter, r *http.Request) {
log.Println("indexHandler is called")
w.WriteHeader(http.StatusOK)
}
func testCallActorHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s test request for %s", r.Method, r.URL.RequestURI())
actorType := mux.Vars(r)["actorType"]
id := mux.Vars(r)["id"]
method := mux.Vars(r)["method"]
url := fmt.Sprintf(actorMethodURLFormat, actorType, id, method)
body, err := httpCall(r.Method, url, "fakereq", 200)
if err != nil {
log.Printf("Could not read actor's test response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(body) == 0 {
w.WriteHeader(http.StatusOK)
return
}
var response daprActorResponse
err = json.Unmarshal(body, &response)
if err != nil {
log.Printf("Could not parse actor's test response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(response.Data)
}
func httpCall(method string, url string, requestBody interface{}, expectedHTTPStatusCode int) ([]byte, error) {
var body []byte
var err error
if requestBody != nil {
body, err = json.Marshal(requestBody)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != expectedHTTPStatusCode {
t := fmt.Errorf("Expected http status %d, received %d", expectedHTTPStatusCode, res.StatusCode) //nolint:stylecheck
return nil, t
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
return resBody, nil
}
// appRouter initializes restful api router
func appRouter() http.Handler {
router := mux.NewRouter().StrictSlash(true)
// Log requests and their processing time
router.Use(utils.LoggerMiddleware)
router.HandleFunc("/", indexHandler).Methods("GET")
router.HandleFunc("/test/{actorType}/{id}/method/{method}", testCallActorHandler).Methods("POST", "DELETE")
router.Use(mux.CORSMethodMiddleware(router))
return router
}
func main() {
log.Printf("Actor Client - listening on http://localhost:%d", appPort)
utils.StartServer(appPort, appRouter, true, false)
}
|
mikeee/dapr
|
tests/apps/actorclientapp/app.go
|
GO
|
mit
| 3,345 |
# In e2e test, this will not be used to deploy the app to test cluster.
# This is created for testing purpose in order to deploy this app using kubectl
# before writing e2e test.
kind: Service
apiVersion: v1
metadata:
name: actorclientapp
labels:
testapp: actorclientapp
spec:
selector:
testapp: actorclientapp
ports:
- protocol: TCP
port: 80
targetPort: 3000
type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: actorclient
labels:
testapp: actorclientapp
spec:
replicas: 1
selector:
matchLabels:
testapp: actorclientapp
template:
metadata:
labels:
testapp: actorclientapp
annotations:
dapr.io/enabled: "true"
dapr.io/app-id: "actorclientapp"
dapr.io/app-port: "3000"
spec:
containers:
- name: actorclientapp
image: docker.io/YOUR_ALIAS/e2e-actorclientapp:dev
ports:
- containerPort: 3000
imagePullPolicy: Always
|
mikeee/dapr
|
tests/apps/actorclientapp/service.yaml
|
YAML
|
mit
| 987 |
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
README.md
|
mikeee/dapr
|
tests/apps/actordotnet/.dockerignore
|
Dockerfile
|
mit
| 333 |
obj/
bin/
.vscode/
|
mikeee/dapr
|
tests/apps/actordotnet/.gitignore
|
Git
|
mit
| 19 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace DaprDemoActor
{
using Dapr.Actors.Runtime;
using System.Threading.Tasks;
using System.Text.Json;
[Actor(TypeName = "DotNetCarActor")]
public class CarActor : Actor, ICarActor
{
private int count = 0;
public CarActor(ActorHost host) : base(host)
{
}
public Task<int> IncrementAndGetAsync(int delta)
{
count += delta;
return Task.FromResult(count);
}
public Task<string> CarToJSONAsync(Car car)
{
string json = JsonSerializer.Serialize(car);
return Task.FromResult(json);
}
public Task<Car> CarFromJSONAsync(string content)
{
System.Console.WriteLine(content);
Car car = JsonSerializer.Deserialize<Car>(content);
return Task.FromResult(car);
}
}
}
|
mikeee/dapr
|
tests/apps/actordotnet/CarActor.cs
|
C#
|
mit
| 1,332 |
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapr.AspNetCore" Version="1.0.0-rc02" />
<PackageReference Include="Dapr.Client" Version="1.0.0-rc02" />
<PackageReference Include="Dapr.Actors" Version="1.0.0-rc02" />
<PackageReference Include="Dapr.Actors.AspNetCore" Version="1.0.0-rc02" />
</ItemGroup>
</Project>
|
mikeee/dapr
|
tests/apps/actordotnet/CarActor.csproj
|
csproj
|
mit
| 454 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace DaprDemoActor
{
using Dapr.Actors;
using Dapr.Actors.Client;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
using System.Text;
[ApiController]
[Route("/")]
public class Controller : ControllerBase
{
[HttpPost("incrementAndGet/{actorType}/{actorId}")]
public async Task<ActionResult<int>> IncrementAndGetAsync([FromRoute] string actorType, [FromRoute] string actorId)
{
var proxy = ActorProxy.Create(new ActorId(actorId), actorType);
return await proxy.InvokeAsync<int, int>("IncrementAndGetAsync", 1);
}
[HttpPost("carFromJSON/{actorType}/{actorId}")]
public async Task<ActionResult<Car>> CarFromJSONAsync([FromRoute] string actorType, [FromRoute] string actorId)
{
using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
{
string json = await reader.ReadToEndAsync();
var proxy = ActorProxy.Create(new ActorId(actorId), actorType);
return await proxy.InvokeAsync<string, Car>("CarFromJSONAsync", json);
}
}
[HttpPost("carToJSON/{actorType}/{actorId}")]
public async Task<ActionResult<string>> CarToJSONAsync([FromRoute] string actorType, [FromRoute] string actorId, [FromBody] Car car)
{
var proxy = ActorProxy.Create(new ActorId(actorId), actorType);
return await proxy.InvokeAsync<Car, string>("CarToJSONAsync", car);
}
}
}
|
mikeee/dapr
|
tests/apps/actordotnet/Controller.cs
|
C#
|
mit
| 1,980 |
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 3000
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["CarActor.csproj", "./"]
RUN dotnet restore "CarActor.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "CarActor.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "CarActor.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "CarActor.dll"]
|
mikeee/dapr
|
tests/apps/actordotnet/Dockerfile
|
Dockerfile
|
mit
| 501 |
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env
WORKDIR /app
# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /app
EXPOSE 3000
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "CarActor.dll"]
|
mikeee/dapr
|
tests/apps/actordotnet/Dockerfile-windows
|
none
|
mit
| 386 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace DaprDemoActor
{
using System.Threading.Tasks;
using Dapr.Actors;
using System.Text.Json.Serialization;
public interface ICarActor : IActor
{
Task<int> IncrementAndGetAsync(int delta);
Task<string> CarToJSONAsync(Car car);
Task<Car> CarFromJSONAsync(string content);
}
public class Car
{
[JsonPropertyName("vin")]
public string Vin { get; set; }
[JsonPropertyName("maker")]
public string Maker { get; set; }
[JsonPropertyName("model")]
public string Model { get; set; }
[JsonPropertyName("trim")]
public string Trim { get; set; }
[JsonPropertyName("modelYear")]
public int ModelYear { get; set; }
[JsonPropertyName("buildYear")]
public int BuildYear { get; set; }
[JsonPropertyName("photo")]
public byte[] Photo { get; set; }
}
}
|
mikeee/dapr
|
tests/apps/actordotnet/ICarActor.cs
|
C#
|
mit
| 1,391 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace DaprDemoActor
{
using Dapr.Actors.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseActors(options =>
{
options.Actors.RegisterActor<CarActor>();
})
.UseUrls("http://*:3000");
});
}
}
|
mikeee/dapr
|
tests/apps/actordotnet/Program.cs
|
C#
|
mit
| 1,219 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace DaprDemoActor
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
mikeee/dapr
|
tests/apps/actordotnet/Startup.cs
|
C#
|
mit
| 1,466 |
../utils/*.go
|
mikeee/dapr
|
tests/apps/actorfeatures/.cache-include
|
none
|
mit
| 13 |
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/dapr/dapr/tests/apps/utils"
"github.com/gorilla/mux"
)
const (
daprBaseURLFormat = "http://localhost:%d/v1.0"
actorMethodURLFormat = daprBaseURLFormat + "/actors/%s/%s/%s/%s"
actorSaveStateURLFormat = daprBaseURLFormat + "/actors/%s/%s/state/"
actorGetStateURLFormat = daprBaseURLFormat + "/actors/%s/%s/state/%s/"
actorReminderURLFormat = daprBaseURLFormat + "/actors/%s/%s/%s/%s"
defaultActorType = "testactorfeatures" // Actor type must be unique per test app.
actorTypeEnvName = "TEST_APP_ACTOR_TYPE" // To set to change actor type.
actorRemindersPartitionsEnvName = "TEST_APP_ACTOR_REMINDERS_PARTITIONS" // To set actor type partition count.
actorIdleTimeout = "1h"
drainOngoingCallTimeout = "30s"
drainRebalancedActors = true
secondsToWaitInMethod = 5
)
var (
appPort = 3000
daprHTTPPort = 3500
httpClient = utils.NewHTTPClient()
)
func init() {
p := os.Getenv("DAPR_HTTP_PORT")
if p != "" && p != "0" {
daprHTTPPort, _ = strconv.Atoi(p)
}
p = os.Getenv("PORT")
if p != "" && p != "0" {
appPort, _ = strconv.Atoi(p)
}
}
type daprActor struct {
actorType string
id string
value int
}
// represents a response for the APIs in this app.
type actorLogEntry struct {
Action string `json:"action,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
StartTimestamp int `json:"startTimestamp,omitempty"`
EndTimestamp int `json:"endTimestamp,omitempty"`
}
type daprConfig struct {
Entities []string `json:"entities,omitempty"`
ActorIdleTimeout string `json:"actorIdleTimeout,omitempty"`
DrainOngoingCallTimeout string `json:"drainOngoingCallTimeout,omitempty"`
DrainRebalancedActors bool `json:"drainRebalancedActors,omitempty"`
RemindersStoragePartitions int `json:"remindersStoragePartitions,omitempty"`
}
// response object from an actor invocation request
type daprActorResponse struct {
Data []byte `json:"data"`
Metadata map[string]string `json:"metadata"`
}
// request for timer or reminder.
type timerReminderRequest struct {
OldName string `json:"oldName,omitempty"`
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorID,omitempty"`
NewName string `json:"newName,omitempty"`
Data string `json:"data,omitempty"`
DueTime string `json:"dueTime,omitempty"`
Period string `json:"period,omitempty"`
TTL string `json:"ttl,omitempty"`
Callback string `json:"callback,omitempty"`
}
// requestResponse represents a request or response for the APIs in this app.
type response struct {
ActorType string `json:"actorType,omitempty"`
ActorID string `json:"actorId,omitempty"`
Method string `json:"method,omitempty"`
StartTime int `json:"start_time,omitempty"`
EndTime int `json:"end_time,omitempty"`
Message string `json:"message,omitempty"`
}
// copied from actors.go for test purposes
type TempTransactionalOperation struct {
Operation string `json:"operation"`
Request any `json:"request"`
}
type TempTransactionalUpsert struct {
Key string `json:"key"`
Value any `json:"value"`
}
type TempTransactionalDelete struct {
Key string `json:"key"`
}
var (
actorLogs = []actorLogEntry{}
actorLogsMutex = &sync.Mutex{}
registeredActorType = getActorType()
actors sync.Map
)
var envOverride sync.Map
func getEnv(envName string) string {
value, ok := envOverride.Load(envName)
if ok {
return fmt.Sprintf("%v", value)
}
return os.Getenv(envName)
}
func resetLogs() {
actorLogsMutex.Lock()
defer actorLogsMutex.Unlock()
// Reset the slice without clearing the memory
actorLogs = actorLogs[:0]
}
func getActorType() string {
actorType := getEnv(actorTypeEnvName)
if actorType == "" {
return defaultActorType
}
return actorType
}
func getActorRemindersPartitions() int {
val := getEnv(actorRemindersPartitionsEnvName)
if val == "" {
return 0
}
n, err := strconv.Atoi(val)
if err != nil {
return 0
}
return n
}
func appendLog(actorType string, actorID string, action string, start int) {
logEntry := actorLogEntry{
Action: action,
ActorType: actorType,
ActorID: actorID,
StartTimestamp: start,
EndTimestamp: epoch(),
}
actorLogsMutex.Lock()
defer actorLogsMutex.Unlock()
actorLogs = append(actorLogs, logEntry)
}
func getLogs() []actorLogEntry {
actorLogsMutex.Lock()
defer actorLogsMutex.Unlock()
dst := make([]actorLogEntry, len(actorLogs))
copy(dst, actorLogs)
return dst
}
func createActorID(actorType string, id string) string {
return fmt.Sprintf("%s.%s", actorType, id)
}
// indexHandler is the handler for root path
func indexHandler(w http.ResponseWriter, r *http.Request) {
log.Println("indexHandler is called")
w.WriteHeader(http.StatusOK)
}
func logsHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing dapr %s request for %s", r.Method, r.URL.RequestURI())
if r.Method == http.MethodDelete {
resetLogs()
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
log.Print("Responding with logs:")
json.NewEncoder(io.MultiWriter(w, os.Stdout)).
Encode(getLogs())
}
func configHandler(w http.ResponseWriter, r *http.Request) {
daprConfigResponse := daprConfig{
[]string{getActorType()},
actorIdleTimeout,
drainOngoingCallTimeout,
drainRebalancedActors,
getActorRemindersPartitions(),
}
log.Printf("Processing dapr request for %s, responding with %#v", r.URL.RequestURI(), daprConfigResponse)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(daprConfigResponse)
}
func actorMethodHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing actor method request for %s", r.URL.RequestURI())
start := epoch()
actorType := mux.Vars(r)["actorType"]
id := mux.Vars(r)["id"]
method := mux.Vars(r)["method"]
reminderOrTimer := mux.Vars(r)["reminderOrTimer"] != ""
actorID := createActorID(actorType, id)
log.Printf("storing, actorID is %s\n", actorID)
actors.Store(actorID, daprActor{
actorType: actorType,
id: actorID,
value: epoch(),
})
// if it's a state test, call state apis
if method == "savestatetest" || method == "getstatetest" ||
method == "savestatetest2" || method == "getstatetest2" {
e := actorStateTest(method, w, actorType, id)
if e != nil {
return
}
}
// Specific case to test reminder that deletes itself in its callback
if id == "1001e" {
url := fmt.Sprintf(actorReminderURLFormat, daprHTTPPort, actorType, id, "reminders", method)
_, e := httpCall("DELETE", url, nil, 204)
if e != nil {
return
}
}
hostname, err := os.Hostname()
var data []byte
if method == "hostname" {
data = []byte(hostname)
} else {
// Sleep for all calls, except timer and reminder.
if !reminderOrTimer {
time.Sleep(secondsToWaitInMethod * time.Second)
}
data, err = json.Marshal(response{
actorType,
id,
method,
start,
epoch(),
"",
})
}
if err != nil {
fmt.Printf("Error: %v", err.Error()) //nolint:forbidigo
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
return
}
appendLog(actorType, id, method, start)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(daprActorResponse{
Data: data,
})
}
func deactivateActorHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s actor request for %s", r.Method, r.URL.RequestURI())
start := epoch()
actorType := mux.Vars(r)["actorType"]
id := mux.Vars(r)["id"]
if actorType != registeredActorType {
log.Printf("Unknown actor type: %s", actorType)
w.WriteHeader(http.StatusBadRequest)
return
}
actorID := createActorID(actorType, id)
action := ""
_, ok := actors.Load(actorID)
if ok && r.Method == "DELETE" {
action = "deactivation"
actors.Delete(actorID)
}
appendLog(actorType, id, action, start)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
}
// calls Dapr's Actor method/timer/reminder: simulating actor client call.
func testCallActorHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s test request for %s", r.Method, r.URL.RequestURI())
actorType := mux.Vars(r)["actorType"]
id := mux.Vars(r)["id"]
callType := mux.Vars(r)["callType"]
method := mux.Vars(r)["method"]
url := fmt.Sprintf(actorMethodURLFormat, daprHTTPPort, actorType, id, callType, method)
log.Printf("Invoking: %s %s\n", r.Method, url)
expectedHTTPCode := 200
var req timerReminderRequest
switch callType {
case "method":
// NO OP
case "timers":
fallthrough
case "reminders":
if r.Method == http.MethodGet {
expectedHTTPCode = 200
} else {
expectedHTTPCode = 204
}
body, err := io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Printf("Could not get reminder request: %s", err.Error())
return
}
log.Println("Body data: " + string(body))
json.Unmarshal(body, &req)
}
body, err := httpCall(r.Method, url, req, expectedHTTPCode)
if err != nil {
log.Printf("Could not read actor's test response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
if len(body) == 0 {
w.WriteHeader(http.StatusOK)
return
}
var response daprActorResponse
err = json.Unmarshal(body, &response)
if err != nil {
log.Printf("Could not parse actor's test response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(response.Data)
}
func testCallMetadataHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s test request for %s", r.Method, r.URL.RequestURI())
metadataURL := fmt.Sprintf(daprBaseURLFormat+"/metadata", daprHTTPPort)
body, err := httpCall(r.Method, metadataURL, nil, 200)
if err != nil {
log.Printf("Could not read metadata response: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(body)
}
func shutdownHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s test request for %s", r.Method, r.URL.RequestURI())
shutdownURL := fmt.Sprintf(daprBaseURLFormat+"/shutdown", daprHTTPPort)
_, err := httpCall(r.Method, shutdownURL, nil, 204)
if err != nil {
log.Printf("Could not shutdown sidecar: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
go func() {
time.Sleep(1 * time.Second)
log.Fatal("simulating fatal shutdown")
}()
}
func shutdownSidecarHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s test request for %s", r.Method, r.URL.RequestURI())
shutdownURL := fmt.Sprintf(daprBaseURLFormat+"/shutdown", daprHTTPPort)
_, err := httpCall(r.Method, shutdownURL, nil, 204)
if err != nil {
log.Printf("Could not shutdown sidecar: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func testEnvHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Processing %s test request for %s", r.Method, r.URL.RequestURI())
envName := mux.Vars(r)["envName"]
if r.Method == http.MethodGet {
envValue := getEnv(envName)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(envValue))
}
if r.Method == http.MethodPost {
body, err := io.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Printf("Could not read config env value: %s", err.Error())
return
}
envOverride.Store(envName, string(body))
}
}
// the test side calls the 4 cases below in order
func actorStateTest(testName string, w http.ResponseWriter, actorType string, id string) error {
// save multiple key values
if testName == "savestatetest" {
url := fmt.Sprintf(actorSaveStateURLFormat, daprHTTPPort, actorType, id)
operations := []TempTransactionalOperation{
{
Operation: "upsert",
Request: TempTransactionalUpsert{
Key: "key1",
Value: "data1",
},
},
{
Operation: "upsert",
Request: TempTransactionalUpsert{
Key: "key2",
Value: "data2",
},
},
{
Operation: "upsert",
Request: TempTransactionalUpsert{
Key: "key3",
Value: "data3",
},
},
{
Operation: "upsert",
Request: TempTransactionalUpsert{
Key: "key4",
Value: "data4",
},
},
}
_, err := httpCall("POST", url, operations, 201)
if err != nil {
log.Printf("actor state call failed: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return err
}
} else if testName == "getstatetest" {
// perform a get on a key saved above
url := fmt.Sprintf(actorGetStateURLFormat, daprHTTPPort, actorType, id, "key1")
_, err := httpCall("GET", url, nil, 200)
if err != nil {
log.Printf("actor state call failed: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return err
}
// query a non-existing key. This should return 204 with 0 length response.
url = fmt.Sprintf(actorGetStateURLFormat, daprHTTPPort, actorType, id, "keynotpresent")
body, err := httpCall("GET", url, nil, 204)
if err != nil {
log.Printf("actor state call failed: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return err
}
if len(body) != 0 {
log.Println("expected 0 length response")
w.WriteHeader(http.StatusInternalServerError)
return errors.New("expected 0 length response")
}
// query a non-existing actor. This should return 400.
url = fmt.Sprintf(actorGetStateURLFormat, daprHTTPPort, actorType, "actoriddoesnotexist", "keynotpresent")
_, err = httpCall("GET", url, nil, 400)
if err != nil {
log.Printf("actor state call failed: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return err
}
} else if testName == "savestatetest2" {
// perform another transaction including a delete
url := fmt.Sprintf(actorSaveStateURLFormat, daprHTTPPort, actorType, id)
// modify 1 key and delete another
operations := []TempTransactionalOperation{
{
Operation: "upsert",
Request: TempTransactionalUpsert{
Key: "key1",
Value: "data1v2",
},
},
{
Operation: "delete",
Request: TempTransactionalDelete{
Key: "key4",
},
},
}
_, err := httpCall("POST", url, operations, 201)
if err != nil {
log.Printf("actor state call failed: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return err
}
} else if testName == "getstatetest2" {
// perform a get on an existing key
url := fmt.Sprintf(actorGetStateURLFormat, daprHTTPPort, actorType, id, "key1")
_, err := httpCall("GET", url, nil, 200)
if err != nil {
log.Printf("actor state call failed: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return err
}
// query a non-existing key - this was present but deleted. This should return 204 with 0 length response.
url = fmt.Sprintf(actorGetStateURLFormat, daprHTTPPort, actorType, id, "key4")
body, err := httpCall("GET", url, nil, 204)
if err != nil {
log.Printf("actor state call failed: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return err
}
if len(body) != 0 {
log.Println("expected 0 length response")
w.WriteHeader(http.StatusInternalServerError)
return errors.New("expected 0 length response")
}
} else {
return errors.New("actorStateTest() - unexpected option")
}
return nil
}
func nonHostedTestHandler(w http.ResponseWriter, r *http.Request) {
log.Print("Testing non-hosted actor reminders")
url := fmt.Sprintf(actorReminderURLFormat, daprHTTPPort, "nonhosted", "id0", "reminders", "myreminder")
tests := map[string]struct {
Method string
Body any
}{
"GetReminder": {"GET", nil},
"CreateReminder": {"PUT", struct{}{}},
"DeleteReminder": {"DELETE", struct{}{}},
}
for op, t := range tests {
body, err := httpCall(t.Method, url, t.Body, http.StatusForbidden)
if err != nil {
http.Error(w, fmt.Sprintf("Error performing %s request: %v", op, err), http.StatusInternalServerError)
return
}
if !bytes.Contains(body, []byte("ERR_ACTOR_REMINDER_NON_HOSTED")) {
http.Error(w, fmt.Sprintf("Response from %s doesn't contain the required error message: %s", op, string(body)), http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "OK")
}
func httpCall(method string, url string, requestBody interface{}, expectedHTTPStatusCode int) ([]byte, error) {
var body []byte
var err error
if requestBody != nil {
body, err = json.Marshal(requestBody)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return nil, err
}
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != expectedHTTPStatusCode {
var errBody []byte
errBody, err = io.ReadAll(res.Body)
if err == nil {
return nil, fmt.Errorf("Expected http status %d, received %d, payload ='%s'", expectedHTTPStatusCode, res.StatusCode, string(errBody)) //nolint:stylecheck
}
return nil, fmt.Errorf("Expected http status %d, received %d", expectedHTTPStatusCode, res.StatusCode) //nolint:stylecheck
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
return resBody, nil
}
func healthzHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(""))
}
// epoch returns the current unix epoch timestamp
func epoch() int {
return int(time.Now().UnixMilli())
}
// appRouter initializes restful api router
func appRouter() http.Handler {
router := mux.NewRouter().StrictSlash(true)
// Log requests and their processing time
router.Use(utils.LoggerMiddleware)
router.HandleFunc("/", indexHandler).Methods("GET")
router.HandleFunc("/dapr/config", configHandler).Methods("GET")
// The POST method is used to register reminder
// The DELETE method is used to unregister reminder
// The PATCH method is used to rename reminder
// The GET method is used to get reminder
router.HandleFunc("/test/{actorType}/{id}/{callType}/{method}", testCallActorHandler).Methods("POST", "DELETE", "PATCH", "GET")
router.HandleFunc("/actors/{actorType}/{id}/method/{method}", actorMethodHandler).Methods("PUT")
router.HandleFunc("/actors/{actorType}/{id}/method/{reminderOrTimer}/{method}", actorMethodHandler).Methods("PUT")
router.HandleFunc("/actors/{actorType}/{id}", deactivateActorHandler).Methods("POST", "DELETE")
router.HandleFunc("/test/nonhosted", nonHostedTestHandler).Methods("POST")
router.HandleFunc("/test/logs", logsHandler).Methods("GET", "DELETE")
router.HandleFunc("/test/metadata", testCallMetadataHandler).Methods("GET")
router.HandleFunc("/test/env/{envName}", testEnvHandler).Methods("GET", "POST")
router.HandleFunc("/test/shutdown", shutdownHandler).Methods("POST")
router.HandleFunc("/test/shutdownsidecar", shutdownSidecarHandler).Methods("POST")
router.HandleFunc("/healthz", healthzHandler).Methods("GET")
return router
}
func main() {
log.Printf("Actor App - listening on http://localhost:%d", appPort)
utils.StartServer(appPort, appRouter, true, false)
}
|
mikeee/dapr
|
tests/apps/actorfeatures/app.go
|
GO
|
mit
| 20,107 |
# In e2e test, this will not be used to deploy the app to test cluster.
# This is created for testing purpose in order to deploy this app using kubectl
# before writing e2e test.
kind: Service
apiVersion: v1
metadata:
name: actorapp
labels:
testapp: actorapp
spec:
selector:
testapp: actorapp
ports:
- protocol: TCP
port: 80
targetPort: 3000
type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: stateapp
labels:
testapp: actorapp
spec:
replicas: 1
selector:
matchLabels:
testapp: actorapp
template:
metadata:
labels:
testapp: actorapp
annotations:
dapr.io/enabled: "true"
dapr.io/app-id: "actorapp"
dapr.io/app-port: "3000"
spec:
containers:
- name: actorapp
image: docker.io/YOUR_ALIAS/e2e-actorapp:dev
ports:
- containerPort: 3000
imagePullPolicy: Always
|
mikeee/dapr
|
tests/apps/actorfeatures/service.yaml
|
YAML
|
mit
| 930 |
../utils/*.go
|
mikeee/dapr
|
tests/apps/actorinvocationapp/.cache-include
|
none
|
mit
| 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.