Skip to content

Commit

Permalink
cleanup: remove APIs we won't be exposing soon
Browse files Browse the repository at this point in the history
This removes the APIs that we don't intend to expose in the beginning.

Leaving only the minimum necessary things for folks to self-enroll
and for mediator to be useful.

This also removes the tests that are no longer relevant.

Closes: #1141
  • Loading branch information
JAORMX committed Oct 9, 2023
1 parent 90861c2 commit 97361e9
Show file tree
Hide file tree
Showing 18 changed files with 4,862 additions and 19,247 deletions.
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, 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, 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, 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
_, 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, status.Errorf(codes.Internal, "failed to create default org role: %v", err)
}

// this creates te role for the project admin
_, 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, 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, status.Errorf(codes.Internal, "failed to create provider: %v", err)
}
return &prj, 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

0 comments on commit 97361e9

Please sign in to comment.