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
3 changes: 3 additions & 0 deletions pkg/app/api/grpcapi/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ go_library(
"api.go",
"deployment_config_templates.go",
"piped_api.go",
"utils.go",
"web_api.go",
":deployment_config_templates.embed", #keep
],
Expand Down Expand Up @@ -50,8 +51,10 @@ go_test(
"//pkg/datastore:go_default_library",
"//pkg/datastore/datastoretest:go_default_library",
"//pkg/model:go_default_library",
"//pkg/rpc/rpcauth:go_default_library",
"@com_github_golang_mock//gomock:go_default_library",
"@com_github_stretchr_testify//assert:go_default_library",
"@org_uber_go_zap//:go_default_library",
],
)

Expand Down
86 changes: 83 additions & 3 deletions pkg/app/api/grpcapi/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ package grpcapi

import (
"context"
"errors"

"github.com/google/uuid"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
Expand All @@ -25,6 +27,8 @@ import (
"github.com/pipe-cd/pipe/pkg/app/api/commandstore"
"github.com/pipe-cd/pipe/pkg/app/api/service/apiservice"
"github.com/pipe-cd/pipe/pkg/datastore"
"github.com/pipe-cd/pipe/pkg/model"
"github.com/pipe-cd/pipe/pkg/rpc/rpcauth"
)

// API implements the behaviors for the gRPC definitions of API.
Expand Down Expand Up @@ -58,10 +62,86 @@ func (a *API) Register(server *grpc.Server) {
apiservice.RegisterAPIServiceServer(server, a)
}

func (a *API) AddApplication(_ context.Context, _ *apiservice.AddApplicationRequest) (*apiservice.AddApplicationResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
func (a *API) AddApplication(ctx context.Context, req *apiservice.AddApplicationRequest) (*apiservice.AddApplicationResponse, error) {
key, err := requireAPIKey(ctx, model.APIKey_READ_WRITE, a.logger)
if err != nil {
return nil, err
}

piped, err := getPiped(ctx, a.pipedStore, req.PipedId, a.logger)
if err != nil {
return nil, err
}

if key.ProjectId != piped.ProjectId {
return nil, status.Error(codes.InvalidArgument, "Requested piped does not belong to your project")
}

gitpath, err := makeGitPath(
req.GitPath.Repo.Id,
req.GitPath.Path,
req.GitPath.ConfigFilename,
piped,
a.logger,
)
if err != nil {
return nil, err
}

app := model.Application{
Id: uuid.New().String(),
Name: req.Name,
EnvId: req.EnvId,
PipedId: req.PipedId,
ProjectId: key.ProjectId,
GitPath: gitpath,
Kind: req.Kind,
CloudProvider: req.CloudProvider,
}
err = a.applicationStore.AddApplication(ctx, &app)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "The application already exists")
}
if err != nil {
a.logger.Error("failed to create application", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to create application")
}

return &apiservice.AddApplicationResponse{
ApplicationId: app.Id,
}, nil
}

func (a *API) SyncApplication(_ context.Context, _ *apiservice.SyncApplicationRequest) (*apiservice.SyncApplicationResponse, error) {
func (a *API) SyncApplication(ctx context.Context, _ *apiservice.SyncApplicationRequest) (*apiservice.SyncApplicationResponse, error) {
_, err := requireAPIKey(ctx, model.APIKey_READ_WRITE, a.logger)
if err != nil {
return nil, err
}

return nil, status.Error(codes.Unimplemented, "")
}

// requireAPIKey checks the existence of an API key inside the given context
// and ensures that it has enough permissions for the give role.
func requireAPIKey(ctx context.Context, role model.APIKey_Role, logger *zap.Logger) (*model.APIKey, error) {
key, err := rpcauth.ExtractAPIKey(ctx)
if err != nil {
return nil, err
}

switch key.Role {
case model.APIKey_READ_WRITE:
return key, nil

case model.APIKey_READ_ONLY:
if role == model.APIKey_READ_ONLY {
return key, nil
}
logger.Warn("detected an API key that has insufficient permissions", zap.String("key", key.Id))
return nil, status.Error(codes.PermissionDenied, "Permission denied")

default:
logger.Warn("detected an API key that has an invalid role", zap.String("key", key.Id))
return nil, status.Error(codes.PermissionDenied, "Invalid role")
}
}
89 changes: 89 additions & 0 deletions pkg/app/api/grpcapi/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,92 @@
// limitations under the License.

package grpcapi

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"go.uber.org/zap"

"github.com/pipe-cd/pipe/pkg/model"
"github.com/pipe-cd/pipe/pkg/rpc/rpcauth"
)

func TestRequireAPIKey(t *testing.T) {
testcases := []struct {
name string
key *model.APIKey
requireRole model.APIKey_Role
expectedKey *model.APIKey
expectedErr string
}{
{
name: "ok: using READ_ONLY to read",
key: &model.APIKey{
Role: model.APIKey_READ_ONLY,
},
requireRole: model.APIKey_READ_ONLY,
expectedKey: &model.APIKey{
Role: model.APIKey_READ_ONLY,
},
},
{
name: "ok: using READ_WRITE to read",
key: &model.APIKey{
Role: model.APIKey_READ_WRITE,
},
requireRole: model.APIKey_READ_ONLY,
expectedKey: &model.APIKey{
Role: model.APIKey_READ_WRITE,
},
},
{
name: "ok: using READ_WRITE to write",
key: &model.APIKey{
Role: model.APIKey_READ_WRITE,
},
requireRole: model.APIKey_READ_WRITE,
expectedKey: &model.APIKey{
Role: model.APIKey_READ_WRITE,
},
},
{
name: "invalid: using READ_ONLY to write",
key: &model.APIKey{
Role: model.APIKey_READ_ONLY,
},
requireRole: model.APIKey_READ_WRITE,
expectedErr: "rpc error: code = PermissionDenied desc = Permission denied",
},
{
name: "invalid: invalid role",
key: &model.APIKey{
Role: -1,
},
requireRole: model.APIKey_READ_ONLY,
expectedErr: "rpc error: code = PermissionDenied desc = Invalid role",
},
{
name: "invalid: api key was not included",
requireRole: model.APIKey_READ_ONLY,
expectedErr: "rpc error: code = Unauthenticated desc = Unauthenticated",
},
}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
ctx := context.TODO()
if tc.key != nil {
ctx = rpcauth.ContextWithAPIKey(ctx, tc.key)
}
key, err := requireAPIKey(ctx, tc.requireRole, zap.NewNop())
assert.Equal(t, tc.expectedKey, key)
if err != nil {
assert.Equal(t, tc.expectedErr, err.Error())
} else {
assert.Equal(t, tc.expectedErr, "")
}
})
}
}
68 changes: 68 additions & 0 deletions pkg/app/api/grpcapi/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright 2020 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"
"errors"

"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"

"github.com/pipe-cd/pipe/pkg/datastore"
"github.com/pipe-cd/pipe/pkg/git"
"github.com/pipe-cd/pipe/pkg/model"
)

func getPiped(ctx context.Context, store datastore.PipedStore, id string, logger *zap.Logger) (*model.Piped, error) {
piped, err := store.GetPiped(ctx, id)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "Piped is not found")
}
if err != nil {
logger.Error("failed to get piped", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get piped")
}

return piped, nil
}

// makeGitPath returns an ApplicationGitPath by adding Repository info and GitPath URL to given args.
func makeGitPath(repoID, path, cfgFilename string, piped *model.Piped, logger *zap.Logger) (*model.ApplicationGitPath, error) {
var repo *model.ApplicationGitRepository
for _, r := range piped.Repositories {
if r.Id == repoID {
repo = r
break
}
}
if repo == nil {
return nil, status.Error(codes.Internal, "The requested repository is not found")
}

u, err := git.MakeDirURL(repo.Remote, path, repo.Branch)
if err != nil {
logger.Error("failed to make GitPath URL", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to make GitPath URL")
}

return &model.ApplicationGitPath{
Repo: repo,
Path: path,
ConfigFilename: cfgFilename,
Url: u,
}, nil
}
Loading