Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions pkg/app/pipedv1/cmd/piped/grpcapi/plugin_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Copyright 2024 The PipeCD 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 grpcapi

import (
"context"
"fmt"

"github.com/pipe-cd/pipecd/pkg/app/pipedv1/cmd/piped/service"
"github.com/pipe-cd/pipecd/pkg/config"
"github.com/pipe-cd/pipecd/pkg/crypto"
"github.com/pipe-cd/pipecd/pkg/model"

"go.uber.org/zap"
"google.golang.org/grpc"
)

type PluginAPI struct {
service.PluginServiceServer

cfg *config.PipedSpec
Logger *zap.Logger
}

// Register registers all handling of this service into the specified gRPC server.
func (a *PluginAPI) Register(server *grpc.Server) {
service.RegisterPluginServiceServer(server, a)
}

func NewPluginAPI(cfg *config.PipedSpec, logger *zap.Logger) *PluginAPI {
return &PluginAPI{
cfg: cfg,
Logger: logger.Named("plugin-api"),
}
}

func (a *PluginAPI) DecryptSecret(ctx context.Context, req *service.DecryptSecretRequest) (*service.DecryptSecretResponse, error) {
decrypter, err := initializeSecretDecrypter(a.cfg.SecretManagement)
if err != nil {
a.Logger.Error("failed to initialize secret decrypter", zap.Error(err))
return nil, err
}

// Return the secret as is in case of no decrypter configured.
if decrypter == nil {
return &service.DecryptSecretResponse{
DecryptedSecret: req.Secret,
}, nil
}

decrypted, err := decrypter.Decrypt(req.Secret)
if err != nil {
a.Logger.Error("failed to decrypt the secret", zap.Error(err))
return nil, err
}

return &service.DecryptSecretResponse{
DecryptedSecret: decrypted,
}, nil
}

func initializeSecretDecrypter(sm *config.SecretManagement) (crypto.Decrypter, error) {
if sm == nil {
return nil, nil
}

switch sm.Type {
case model.SecretManagementTypeNone:
return nil, nil

case model.SecretManagementTypeKeyPair:
key, err := sm.KeyPair.LoadPrivateKey()
if err != nil {
return nil, err
}
decrypter, err := crypto.NewHybridDecrypter(key)
if err != nil {
return nil, fmt.Errorf("failed to initialize decrypter (%w)", err)
}
return decrypter, nil

case model.SecretManagementTypeGCPKMS:
return nil, fmt.Errorf("type %q is not implemented yet", sm.Type.String())

case model.SecretManagementTypeAWSKMS:
return nil, fmt.Errorf("type %q is not implemented yet", sm.Type.String())

default:
return nil, fmt.Errorf("unsupported secret management type: %s", sm.Type.String())
}
}
75 changes: 75 additions & 0 deletions pkg/app/pipedv1/cmd/piped/grpcapi/plugin_api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright 2024 The PipeCD 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 grpcapi

import (
"testing"

"github.com/pipe-cd/pipecd/pkg/config"
"github.com/pipe-cd/pipecd/pkg/model"
)

// Test for initializeSecretDecrypter function.
func TestInitializeSecretDecrypter(t *testing.T) {
testcases := []struct {
name string
cfg *config.SecretManagement
expected bool
expectedErr bool
}{
{
name: "no secret management config",
cfg: nil,
expected: false,
expectedErr: false,
},
{
name: "secret management type none",
cfg: &config.SecretManagement{Type: model.SecretManagementTypeNone},
expected: false,
expectedErr: false,
},
{
name: "unsupported secret management type",
cfg: &config.SecretManagement{Type: "unsupported"},
expected: false,
expectedErr: true,
},
{
name: "unspoerted secret management type GCPKMS",
cfg: &config.SecretManagement{Type: model.SecretManagementTypeGCPKMS},
expected: false,
expectedErr: true,
},
{
name: "unsupported secret mamagement type AWSKMS",
cfg: &config.SecretManagement{Type: model.SecretManagementTypeAWSKMS},
expected: false,
expectedErr: true,
},
}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
decrypter, err := initializeSecretDecrypter(tc.cfg)
if (err != nil) != tc.expectedErr {
t.Errorf("unexpected error: %v", err)
}
if (decrypter != nil) != tc.expected {
t.Errorf("unexpected result: %v", decrypter)
}
})
}
}
33 changes: 29 additions & 4 deletions pkg/app/pipedv1/cmd/piped/piped.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import (
"github.com/pipe-cd/pipecd/pkg/app/pipedv1/apistore/eventstore"
"github.com/pipe-cd/pipecd/pkg/app/pipedv1/appconfigreporter"
"github.com/pipe-cd/pipecd/pkg/app/pipedv1/chartrepo"
"github.com/pipe-cd/pipecd/pkg/app/pipedv1/cmd/piped/grpcapi"
"github.com/pipe-cd/pipecd/pkg/app/pipedv1/controller"
"github.com/pipe-cd/pipecd/pkg/app/pipedv1/controller/controllermetrics"
"github.com/pipe-cd/pipecd/pkg/app/pipedv1/driftdetector"
Expand All @@ -70,6 +71,7 @@ import (
"github.com/pipe-cd/pipecd/pkg/crypto"
"github.com/pipe-cd/pipecd/pkg/git"
"github.com/pipe-cd/pipecd/pkg/model"
"github.com/pipe-cd/pipecd/pkg/rpc"
"github.com/pipe-cd/pipecd/pkg/rpc/rpcauth"
"github.com/pipe-cd/pipecd/pkg/rpc/rpcclient"
"github.com/pipe-cd/pipecd/pkg/version"
Expand All @@ -93,6 +95,7 @@ type piped struct {
insecure bool
certFile string
adminPort int
pluginServicePort int
toolsDir string
enableDefaultKubernetesCloudProvider bool
gracePeriod time.Duration
Expand All @@ -107,10 +110,11 @@ func NewCommand() *cobra.Command {
panic(fmt.Sprintf("failed to detect the current user's home directory: %v", err))
}
p := &piped{
adminPort: 9085,
toolsDir: path.Join(home, ".piped", "tools"),
gracePeriod: 30 * time.Second,
maxRecvMsgSize: 1024 * 1024 * 10, // 10MB
adminPort: 9085,
pluginServicePort: 9087,
toolsDir: path.Join(home, ".piped", "tools"),
gracePeriod: 30 * time.Second,
maxRecvMsgSize: 1024 * 1024 * 10, // 10MB
}
cmd := &cobra.Command{
Use: "piped",
Expand All @@ -126,6 +130,7 @@ func NewCommand() *cobra.Command {
cmd.Flags().BoolVar(&p.insecure, "insecure", p.insecure, "Whether disabling transport security while connecting to control-plane.")
cmd.Flags().StringVar(&p.certFile, "cert-file", p.certFile, "The path to the TLS certificate file.")
cmd.Flags().IntVar(&p.adminPort, "admin-port", p.adminPort, "The port number used to run a HTTP server for admin tasks such as metrics, healthz.")
cmd.Flags().IntVar(&p.pluginServicePort, "plugin-service-port", p.pluginServicePort, "The port number used to run a gRPC server for plugin services.")

cmd.Flags().StringVar(&p.toolsDir, "tools-dir", p.toolsDir, "The path to directory where to install needed tools such as kubectl, helm, kustomize.")
cmd.Flags().BoolVar(&p.enableDefaultKubernetesCloudProvider, "enable-default-kubernetes-cloud-provider", p.enableDefaultKubernetesCloudProvider, "Whether the default kubernetes provider is enabled or not. This feature is deprecated.")
Expand Down Expand Up @@ -364,6 +369,25 @@ func (p *piped) run(ctx context.Context, input cli.Input) (runErr error) {
})
}

// Start running plugin service server.
{
var (
service = grpcapi.NewPluginAPI(cfg, input.Logger)
opts = []rpc.Option{
rpc.WithPort(p.pluginServicePort),
rpc.WithGracePeriod(p.gracePeriod),
rpc.WithLogger(input.Logger),
rpc.WithLogUnaryInterceptor(input.Logger),
rpc.WithRequestValidationUnaryInterceptor(),
}
)
// TODO: Ensure piped <-> plugin communication is secure.
server := rpc.NewServer(service, opts...)
group.Go(func() error {
return server.Run(ctx)
})
}

decrypter, err := p.initializeSecretDecrypter(cfg)
if err != nil {
input.Logger.Error("failed to initialize secret decrypter", zap.Error(err))
Expand Down Expand Up @@ -686,6 +710,7 @@ func (p *piped) loadConfigByte(ctx context.Context) ([]byte, error) {
return nil, fmt.Errorf("one of config-file, config-gcp-secret or config-aws-secret must be set")
}

// TODO: Remove this once the decryption task by plugin call to the plugin service is implemented.
func (p *piped) initializeSecretDecrypter(cfg *config.PipedSpec) (crypto.Decrypter, error) {
sm := cfg.SecretManagement
if sm == nil {
Expand Down