Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cleanup: remove APIs we won't be exposing soon #1149

Merged
merged 1 commit into from
Oct 9, 2023
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
1,133 changes: 140 additions & 993 deletions docs/docs/protodocs/proto.md

Large diffs are not rendered by default.

115 changes: 115 additions & 0 deletions internal/controlplane/default_project.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
//
// Copyright 2023 Stacklok, Inc.
//
// 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 controlplane

import (
"context"
"encoding/json"
"fmt"

"github.com/google/uuid"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"

"github.com/stacklok/mediator/internal/db"
github "github.com/stacklok/mediator/internal/providers/github"
pb "github.com/stacklok/mediator/pkg/api/protobuf/go/mediator/v1"
)

// OrgMeta is the metadata associated with an organization
type OrgMeta struct {
Company string `json:"company"`
}

// ProjectMeta is the metadata associated with a project
type ProjectMeta struct {
Description string `json:"description"`
IsProtected bool `json:"is_protected"`
}

// CreateDefaultRecordsForOrg creates the default records, such as projects, roles and provider for the organization
func CreateDefaultRecordsForOrg(ctx context.Context, qtx db.Querier,
org db.Project, projectName string) (*pb.Project, []int32, error) {
projectmeta := &ProjectMeta{
IsProtected: true,
Description: fmt.Sprintf("Default admin project for %s", org.Name),
}

jsonmeta, err := json.Marshal(projectmeta)
if err != nil {
return nil, nil, status.Errorf(codes.Internal, "failed to marshal meta: %v", err)
}

// we need to create the default records for the organization
project, err := qtx.CreateProject(ctx, db.CreateProjectParams{
ParentID: uuid.NullUUID{
UUID: org.ID,
Valid: true,
},
Name: projectName,
Metadata: jsonmeta,
})
if err != nil {
return nil, nil, status.Errorf(codes.Internal, "failed to create default project: %v", err)
}

prj := pb.Project{
ProjectId: project.ID.String(),
Name: project.Name,
Description: projectmeta.Description,
IsProtected: projectmeta.IsProtected,
CreatedAt: timestamppb.New(project.CreatedAt),
UpdatedAt: timestamppb.New(project.UpdatedAt),
}

// we can create the default role for org and for project
// This creates the role for the organization admin
role1, err := qtx.CreateRole(ctx, db.CreateRoleParams{
OrganizationID: org.ID,
Name: fmt.Sprintf("%s-org-admin", org.Name),
IsAdmin: true,
IsProtected: true,
})
if err != nil {
return nil, nil, status.Errorf(codes.Internal, "failed to create default org role: %v", err)
}

// this creates te role for the project admin
role2, err := qtx.CreateRole(ctx, db.CreateRoleParams{
OrganizationID: org.ID,
ProjectID: uuid.NullUUID{UUID: project.ID, Valid: true},
Name: fmt.Sprintf("%s-project-admin", org.Name),
IsAdmin: true,
IsProtected: true,
})

if err != nil {
return nil, nil, status.Errorf(codes.Internal, "failed to create default project role: %v", err)
}

// Create GitHub provider
_, err = qtx.CreateProvider(ctx, db.CreateProviderParams{
Name: github.Github,
ProjectID: project.ID,
Implements: github.Implements,
Definition: json.RawMessage(`{"github": {}}`),
})
if err != nil {
return nil, nil, status.Errorf(codes.Internal, "failed to create provider: %v", err)
}
return &prj, []int32{role1.ID, role2.ID}, nil
}
133 changes: 2 additions & 131 deletions internal/controlplane/handlers_authz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,134 +14,5 @@

package controlplane

import (
"context"
"testing"

"github.com/golang/mock/gomock"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"

mockdb "github.com/stacklok/mediator/database/mock"
"github.com/stacklok/mediator/internal/auth"
pb "github.com/stacklok/mediator/pkg/api/protobuf/go/mediator/v1"
)

func TestIsSuperadminAuthorized(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)
defer ctrl.Finish()

orgID := uuid.New()
projectID := uuid.New()

request := &pb.GetProjectByIdRequest{ProjectId: projectID.String()}
// Create a new context and set the claims value
ctx := auth.WithPermissionsContext(context.Background(), auth.UserPermissions{
UserId: 1,
OrganizationId: orgID,
ProjectIds: []uuid.UUID{projectID},
IsStaff: true, // TODO: remove this
Roles: []auth.RoleInfo{
{RoleID: 1, IsAdmin: true, ProjectID: &projectID, OrganizationID: orgID}},
})

mockStore := mockdb.NewMockStore(ctrl)
mockStore.EXPECT().GetProjectByID(ctx, gomock.Any())
mockStore.EXPECT().ListRolesByProjectID(ctx, gomock.Any())
mockStore.EXPECT().ListUsersByProject(ctx, gomock.Any())

server := &Server{
store: mockStore,
}

response, err := server.GetProjectById(ctx, request)

assert.NoError(t, err)
assert.NotNil(t, response)
}

func TestIsNonadminAuthorized(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)
defer ctrl.Finish()

orgID := uuid.New()
projectID := uuid.New()

request := &pb.CreateRoleByOrganizationRequest{OrganizationId: orgID.String(), Name: "test"}
// Create a new context and set the claims value
ctx := auth.WithPermissionsContext(context.Background(), auth.UserPermissions{
UserId: 1,
OrganizationId: orgID,
ProjectIds: []uuid.UUID{projectID},
Roles: []auth.RoleInfo{
{RoleID: 1, IsAdmin: false, ProjectID: &projectID, OrganizationID: orgID}},
})

rpcOpts, err := optionsForMethod(&grpc.UnaryServerInfo{FullMethod: "/mediator.v1.RoleService/CreateRoleByOrganization"})
if err != nil {
t.Fatalf("Unable to get rpc options: %v", err)
}
ctx = withRpcOptions(ctx, rpcOpts)

mockStore := mockdb.NewMockStore(ctrl)
server := &Server{
store: mockStore,
}
mockStore.EXPECT().CreateRole(ctx, gomock.Any()).Times(0)

_, err = server.CreateRoleByOrganization(ctx, request)

t.Logf("Got error: %v", err)

if err == nil {
t.Error("Expected error when user is not authorized, but got nil")
} else {
t.Logf("Successfully received error when user is not authorized: %v", err)
}
}

func TestByResourceUnauthorized(t *testing.T) {
t.Parallel()

ctrl := gomock.NewController(t)
defer ctrl.Finish()

orgID := uuid.New()
projectID1 := uuid.New()
projectID2 := uuid.New()

request := &pb.GetRoleByIdRequest{Id: 1}
// Create a new context and set the claims value
ctx := auth.WithPermissionsContext(context.Background(), auth.UserPermissions{
UserId: 2,
OrganizationId: orgID,
ProjectIds: []uuid.UUID{projectID1},
Roles: []auth.RoleInfo{
{RoleID: 2, IsAdmin: true, ProjectID: &projectID2, OrganizationID: orgID}},
})

rpcOpts, err := optionsForMethod(&grpc.UnaryServerInfo{FullMethod: "/mediator.v1.RoleService/GetRoleById"})
if err != nil {
t.Fatalf("Unable to get rpc options: %v", err)
}
ctx = withRpcOptions(ctx, rpcOpts)

mockStore := mockdb.NewMockStore(ctrl)
server := &Server{
store: mockStore,
}
mockStore.EXPECT().GetRoleByID(ctx, gomock.Any()).Times(1)

_, err = server.GetRoleById(ctx, request)

if err == nil {
t.Error("Expected error when user is not authorized, but got nil")
} else {
t.Logf("Successfully received error when user is not authorized: %v", err)
}
}
// TODO: We shoul come up with a different set of tests for authorization
// since we no longer have most privileged operations.
Loading