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

Updating provider config #3468

Merged
merged 4 commits into from
Jun 18, 2024
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
5 changes: 3 additions & 2 deletions cmd/dev/app/image/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (

"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/protobuf/proto"

"github.com/stacklok/minder/internal/providers/credentials"
"github.com/stacklok/minder/internal/providers/dockerhub"
Expand Down Expand Up @@ -75,15 +76,15 @@ func runCmdList(cmd *cobra.Command, _ []string) error {
var err error
cred := credentials.NewOAuth2TokenCredential(viper.GetString("auth.token"))
prov, err = dockerhub.New(cred, &minderv1.DockerHubProviderConfig{
Namespace: ns.Value.String(),
Namespace: proto.String(ns.Value.String()),
})
if err != nil {
return err
}
case "ghcr":
cred := credentials.NewOAuth2TokenCredential(viper.GetString("auth.token"))
prov = ghcr.New(cred, &minderv1.GHCRProviderConfig{
Namespace: ns.Value.String(),
Namespace: proto.String(ns.Value.String()),
})
default:
return fmt.Errorf("unknown provider: %s", pclass.Value.String())
Expand Down
39 changes: 32 additions & 7 deletions docs/docs/ref/proto.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion internal/controlplane/handlers_githubwebhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -1032,7 +1032,7 @@ func (s *Server) processInstallationRepositoriesAppEvent(
return nil, fmt.Errorf("could not determine provider id: %v", err)
}

providerConfig, _, err := clients.ParseV1AppConfig(dbProv.Definition)
providerConfig, _, err := clients.ParseAndMergeV1AppConfig(dbProv.Definition)
if err != nil {
return nil, fmt.Errorf("could not parse provider config: %v", err)
}
Expand Down
2 changes: 2 additions & 0 deletions internal/controlplane/handlers_oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ func (s *Server) GetAuthorizationURL(ctx context.Context,
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "error marshalling config: %s", err)
}
} else {
confBytes = []byte("{}")
}

// Insert the new session state into the database along with the user's project ID
Expand Down
9 changes: 6 additions & 3 deletions internal/controlplane/handlers_oauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,8 +498,11 @@ func TestProviderCallback(t *testing.T) {
code: 403,
err: "The provided login token was associated with a different user.\n",
}, {
name: "No existing provider",
redirectUrl: "http://localhost:8080",
name: "No existing provider",
redirectUrl: "http://localhost:8080",
// such fallback config is stored when generating the authorization URL, but here we mock
// the state response, so let's provide the fallback ourselves.
config: []byte(`{}`),
code: 307,
projectIDBySessionNumCalls: 2,
storeMockSetup: func(store *mockdb.MockStore) {
Expand All @@ -513,7 +516,7 @@ func TestProviderCallback(t *testing.T) {
storeMockSetup: func(store *mockdb.MockStore) {
withProviderNotFound(store)
},
config: []byte(`{"missing_github_key": true}`),
config: []byte(`{`),
code: http.StatusBadRequest,
}}

Expand Down
40 changes: 40 additions & 0 deletions internal/controlplane/handlers_providers.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func (s *Server) CreateProvider(
return nil, status.Errorf(codes.InvalidArgument, "error marshalling provider provConfig: %v", marshallErr)
}
} else {
provConfig = json.RawMessage([]byte("{}"))
zerolog.Ctx(ctx).Debug().Msg("no provider provConfig, will use default")
}

Expand Down Expand Up @@ -234,6 +235,45 @@ func (s *Server) DeleteProviderByID(
}, nil
}

// PatchProvider patches a provider by name from a specific project.
func (s *Server) PatchProvider(
ctx context.Context,
req *minderv1.PatchProviderRequest,
) (*minderv1.PatchProviderResponse, error) {
entityCtx := engine.EntityFromContext(ctx)
projectID := entityCtx.Project.ID
providerName := entityCtx.Provider.Name

if providerName == "" {
return nil, status.Errorf(codes.InvalidArgument, "provider name is required")
}

err := s.providerManager.PatchProviderConfig(ctx, providerName, projectID, req.GetPatch().GetConfig().AsMap())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be getting a provider instance and then calling PatchConfig on the provider instance? I'm okay with having this on providerManager, I just don't have a feel for when we create an instance and when we don't.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, me neither. Getting a provider instance and then patching it is pretty much what the implementation of PatchProviderConfig does now.

@dmjb do you have an opinion since you created the ProviderManager interface?

if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, util.UserVisibleError(codes.NotFound, "provider not found")
}
return nil, status.Errorf(codes.Internal, "error patching provider: %v", err)
}

dbProv, err := s.providerStore.GetByNameInSpecificProject(ctx, projectID, providerName)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, util.UserVisibleError(codes.NotFound, "provider not found")
}
return nil, status.Errorf(codes.Internal, "error getting provider: %v", err)
}

prov, err := protobufProviderFromDB(ctx, s.store, s.cryptoEngine, &s.cfg.Provider, dbProv)
if err != nil {
return nil, status.Errorf(codes.Internal, "error creating provider: %v", err)
}

return &minderv1.PatchProviderResponse{
Provider: prov,
}, nil
}

func protobufProviderFromDB(
ctx context.Context, store db.Store,
cryptoEngine crypto.Engine, pc *config.ProviderConfig, p *db.Provider,
Expand Down
38 changes: 10 additions & 28 deletions internal/controlplane/handlers_providers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,9 @@ func TestCreateProvider(t *testing.T) {
name: "test-github-defaults",
providerClass: db.ProviderClassGithub,
expected: minder.Provider{
Name: "test-github-defaults",
Config: newPbStruct(t, map[string]interface{}{
"github": map[string]interface{}{},
}),
Class: string(db.ProviderClassGithub),
Name: "test-github-defaults",
Config: newPbStruct(t, map[string]interface{}{}),
Class: string(db.ProviderClassGithub),
},
},
{
Expand All @@ -162,11 +160,9 @@ func TestCreateProvider(t *testing.T) {
name: "test-github-app-defaults",
providerClass: db.ProviderClassGithubApp,
expected: minder.Provider{
Name: "test-github-app-defaults",
Config: newPbStruct(t, map[string]interface{}{
"github_app": map[string]interface{}{},
}),
Class: string(db.ProviderClassGithubApp),
Name: "test-github-app-defaults",
Config: newPbStruct(t, map[string]interface{}{}),
Class: string(db.ProviderClassGithubApp),
},
},
{
Expand Down Expand Up @@ -255,17 +251,6 @@ func TestCreateProvider(t *testing.T) {
jsonConfig, err := scenario.expected.Config.MarshalJSON()
require.NoError(t, err)

var jsonUserConfig []byte
if scenario.userConfig != nil {
jsonUserConfig, err = scenario.userConfig.MarshalJSON()
require.NoError(t, err)
}

if scenario.providerClass == db.ProviderClassGithubApp || scenario.providerClass == db.ProviderClassGithub {
fakeServer.mockGhService.EXPECT().GetConfig(gomock.Any(), scenario.providerClass, jsonUserConfig).
Return(jsonConfig, nil)
}

fakeServer.mockStore.EXPECT().CreateProvider(gomock.Any(), partialCreateParamsMatcher{
value: db.CreateProviderParams{
Name: scenario.name,
Expand Down Expand Up @@ -375,9 +360,6 @@ func TestCreateProviderFailures(t *testing.T) {
Provider: engine.Provider{Name: providerName},
})

fakeServer.mockGhService.EXPECT().GetConfig(gomock.Any(), db.ProviderClassGithub, gomock.Any()).
Return(json.RawMessage(`{ "github": {} }`), nil)

fakeServer.mockStore.EXPECT().CreateProvider(gomock.Any(), gomock.Any()).
Return(db.Provider{}, &pq.Error{Code: "23505"}) // unique_violation

Expand Down Expand Up @@ -427,7 +409,10 @@ func TestCreateProviderFailures(t *testing.T) {
},
})
assert.Error(t, err)
require.ErrorContains(t, err, "error validating DockerHub v1 provider config: namespace is required")
st, ok := status.FromError(err)
require.True(t, ok)
assert.Equal(t, codes.InvalidArgument, st.Code())
require.ErrorContains(t, err, "namespace is required")
})

t.Run("github-app-does-not-validate", func(t *testing.T) {
Expand All @@ -442,9 +427,6 @@ func TestCreateProviderFailures(t *testing.T) {
fakeServer := testServer(t, ctrl)
providerName := "bad-github-app"

fakeServer.mockGhService.EXPECT().GetConfig(gomock.Any(), db.ProviderClassGithubApp, gomock.Any()).
Return(json.RawMessage(`{ "auto_registration": { "entities": { "blah": {"enabled": true }}}, "github-app": {}}`), nil)

_, err := fakeServer.server.CreateProvider(context.Background(), &minder.CreateProviderRequest{
Context: &minder.Context{
Project: &projectIDStr,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func testGithubProvider(baseURL string) (provifv1.GitHub, error) {

return clients.NewRestClient(
&pb.GitHubProviderConfig{
Endpoint: baseURL,
Endpoint: &baseURL,
},
nil,
&ratecache.NoopRestClientCache{},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/google/go-github/v61/github"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/known/structpb"

Expand Down Expand Up @@ -91,7 +92,7 @@ var TestActionTypeValid interfaces.ActionType = "remediate-test"
func testGithubProvider() (provifv1.GitHub, error) {
return clients.NewRestClient(
&pb.GitHubProviderConfig{
Endpoint: ghApiUrl + "/",
Endpoint: proto.String(ghApiUrl + "/"),
},
nil,
&ratecache.NoopRestClientCache{},
Expand Down
3 changes: 2 additions & 1 deletion internal/engine/actions/remediate/remediate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"

"github.com/stacklok/minder/internal/engine/actions/remediate"
"github.com/stacklok/minder/internal/engine/actions/remediate/noop"
Expand Down Expand Up @@ -142,7 +143,7 @@ func TestNewRuleRemediator(t *testing.T) {
}

func HTTPProvider() (provifv1.Provider, error) {
cfg := pb.RESTProviderConfig{BaseUrl: "https://api.github.com/"}
cfg := pb.RESTProviderConfig{BaseUrl: proto.String("https://api.github.com/")}
return httpclient.NewREST(
&cfg,
telemetry.NewNoopMetrics(),
Expand Down
5 changes: 3 additions & 2 deletions internal/engine/actions/remediate/rest/rest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/known/structpb"

Expand Down Expand Up @@ -54,7 +55,7 @@ func testGithubProvider(baseURL string) (provifv1.REST, error) {

return clients.NewRestClient(
&pb.GitHubProviderConfig{
Endpoint: baseURL,
Endpoint: &baseURL,
},
nil,
&ratecache.NoopRestClientCache{},
Expand Down Expand Up @@ -141,7 +142,7 @@ func TestNewRestRemediate(t *testing.T) {

restProvider, err := httpclient.NewREST(
&pb.RESTProviderConfig{
BaseUrl: "https://api.github.com/",
BaseUrl: proto.String("https://api.github.com/"),
},
telemetry.NewNoopMetrics(),
credentials.NewGitHubTokenCredential("token"),
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/ingester/artifact/artifact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func testGithubProvider() (provinfv1.GitHub, error) {

return clients.NewRestClient(
&pb.GitHubProviderConfig{
Endpoint: baseURL,
Endpoint: &baseURL,
},
nil,
&ratecache.NoopRestClientCache{},
Expand Down
Loading