Skip to content
Open
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
6 changes: 5 additions & 1 deletion plugins/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,15 @@ func GetByExecutable(executableQuery string) (schema.Plugin, schema.Executable,
return schema.Plugin{}, schema.Executable{}, fmt.Errorf("unknown plugin: %s", executableQuery)
}

// GetCredentialType returns the credential type with the given name from the given plugin. The
// credential can be identified by its name (e.g. "Access Key") or by its ID (e.g. "access_key").
func GetCredentialType(pluginName string, credentialName string) (schema.CredentialType, error) {
for _, p := range registry {
if p.Name == pluginName {
for _, credential := range p.Credentials {
return credential, nil
if credential.Name.String() == credentialName || credential.Name.ID().String() == credentialName {
return credential, nil
}
}
return schema.CredentialType{}, fmt.Errorf("unknown credential: %s (%s)", credentialName, pluginName)
}
Expand Down
119 changes: 119 additions & 0 deletions plugins/registry_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package plugins

import (
"net/url"
"testing"

"github.com/1Password/shell-plugins/sdk"
"github.com/1Password/shell-plugins/sdk/schema"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestValidatePlugins(t *testing.T) {
Expand All @@ -27,3 +30,119 @@ func TestAllPluginsHaveUniqueNames(t *testing.T) {

assert.True(t, schema.IsStringSliceASet(pluginNames))
}

// useTestRegistry replaces the registered plugins with the given ones for the duration of the test.
func useTestRegistry(t *testing.T, testPlugins ...schema.Plugin) {
t.Helper()
original := registry
registry = testPlugins
t.Cleanup(func() {
registry = original
})
}

func testURL(t *testing.T, rawURL string) *url.URL {
t.Helper()
u, err := url.Parse(rawURL)
require.NoError(t, err)
return u
}

func testPlugins(t *testing.T) []schema.Plugin {
t.Helper()
return []schema.Plugin{
{
Name: "single",
Platform: schema.PlatformInfo{Name: "Single"},
Credentials: []schema.CredentialType{
{Name: sdk.CredentialName("API Key"), ManagementURL: testURL(t, "https://single.example.com/keys")},
},
},
{
Name: "double",
Platform: schema.PlatformInfo{Name: "Double"},
Credentials: []schema.CredentialType{
{Name: sdk.CredentialName("Access Key")},
{Name: sdk.CredentialName("SSO Profile"), ManagementURL: testURL(t, "https://double.example.com/sso")},
},
},
{
Name: "nocredentials",
Platform: schema.PlatformInfo{Name: "No Credentials"},
},
}
}

func TestGetCredentialType(t *testing.T) {
useTestRegistry(t, testPlugins(t)...)

cases := map[string]struct {
pluginName string
credentialName string
expectedName sdk.CredentialName
expectedErr string
}{
"only credential type of a plugin": {
pluginName: "single",
credentialName: "API Key",
expectedName: "API Key",
},
"first credential type of a plugin with two": {
pluginName: "double",
credentialName: "Access Key",
expectedName: "Access Key",
},
"second credential type of a plugin with two": {
pluginName: "double",
credentialName: "SSO Profile",
expectedName: "SSO Profile",
},
"credential type identified by its ID": {
pluginName: "double",
credentialName: "sso_profile",
expectedName: "SSO Profile",
},
"credential type the plugin does not have": {
pluginName: "single",
credentialName: "Access Key",
expectedErr: "unknown credential: Access Key (single)",
},
"plugin without credential types": {
pluginName: "nocredentials",
credentialName: "Access Key",
expectedErr: "unknown credential: Access Key (nocredentials)",
},
"plugin that is not registered": {
pluginName: "missing",
credentialName: "Access Key",
expectedErr: "unknown plugin: missing",
},
}

for name, tc := range cases {
t.Run(name, func(t *testing.T) {
credential, err := GetCredentialType(tc.pluginName, tc.credentialName)

if tc.expectedErr != "" {
assert.EqualError(t, err, tc.expectedErr)
return
}
require.NoError(t, err)
assert.Equal(t, tc.expectedName, credential.Name)
})
}
}

func TestRegistryJSON(t *testing.T) {
useTestRegistry(t, testPlugins(t)...)

result, err := RegistryJSON()

require.NoError(t, err)
// A plugin gets a single entry, no matter how many credential types it has, with the management URL
// of the first credential type that has one. Plugins without credential types are left out.
assert.JSONEq(t, `[
{"platform_name": "Single", "management_url": "https://single.example.com/keys"},
{"platform_name": "Double", "management_url": "https://double.example.com/sso"}
]`, string(result))
}
203 changes: 203 additions & 0 deletions sdk/rpc/server/server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
package server

import (
"context"
"net"
"net/rpc"
"testing"

"github.com/1Password/shell-plugins/sdk"
"github.com/1Password/shell-plugins/sdk/rpc/proto"
"github.com/1Password/shell-plugins/sdk/schema"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const (
testAccessKey = sdk.CredentialName("Access Key")
testSSOProfile = sdk.CredentialName("SSO Profile")
)

// markingProvisioner sets an environment variable named after itself, so that a test can tell which
// provisioner handled a call.
type markingProvisioner struct {
name string
}

func (p markingProvisioner) Description() string { return p.name }

func (p markingProvisioner) Provision(_ context.Context, _ sdk.ProvisionInput, out *sdk.ProvisionOutput) {
out.AddEnvVar("PROVISIONED_BY", p.name)
}

func (p markingProvisioner) Deprovision(context.Context, sdk.DeprovisionInput, *sdk.DeprovisionOutput) {
}

// markingImporter returns an importer that reports a single candidate named after the given name, so
// that a test can tell which importer handled a call.
func markingImporter(name string) sdk.Importer {
return func(_ context.Context, _ sdk.ImportInput, out *sdk.ImportOutput) {
out.Attempts = append(out.Attempts, &sdk.ImportAttempt{
Candidates: []sdk.ImportCandidate{{NameHint: name}},
})
}
}

// testPluginWithTwoCredentialTypes returns a plugin with two credential types that are both used by
// its only executable. The first usage relies on the default provisioner of its credential type, the
// second usage brings its own.
func testPluginWithTwoCredentialTypes() schema.Plugin {
return schema.Plugin{
Name: "example",
Platform: schema.PlatformInfo{Name: "Example"},
Credentials: []schema.CredentialType{
{
Name: testAccessKey,
DefaultProvisioner: markingProvisioner{name: "access key default"},
Importer: markingImporter("access key importer"),
},
{
Name: testSSOProfile,
DefaultProvisioner: markingProvisioner{name: "sso profile default"},
Importer: markingImporter("sso profile importer"),
},
},
Executables: []schema.Executable{
{
Name: "Example CLI",
Runs: []string{"example"},
Uses: []schema.CredentialUsage{
{Name: testAccessKey, Optional: true},
{Name: testSSOProfile, Optional: true, Provisioner: markingProvisioner{name: "sso profile usage"}},
},
},
},
}
}

// connectToTestPlugin serves the given plugin over RPC, in the same way as go-plugin does, and returns
// a client that is connected to it.
func connectToTestPlugin(t *testing.T, plugin schema.Plugin) *rpc.Client {
t.Helper()

rpcServer := rpc.NewServer()
require.NoError(t, rpcServer.RegisterName("Plugin", newServer(plugin)))

serverConn, clientConn := net.Pipe()
go rpcServer.ServeConn(serverConn)

client := rpc.NewClient(clientConn)
t.Cleanup(func() {
_ = client.Close()
})
return client
}

func newTestProvisionRequest(id proto.ProvisionerID) proto.ProvisionCredentialRequest {
return proto.ProvisionCredentialRequest{
ProvisionerID: id,
ProvisionOutput: sdk.ProvisionOutput{
Environment: map[string]string{},
CommandLine: []string{"example"},
Files: map[string]sdk.OutputFile{},
},
}
}

func TestGetPluginWithTwoCredentialTypesOverRPC(t *testing.T) {
client := connectToTestPlugin(t, testPluginWithTwoCredentialTypes())

var resp proto.GetPluginResponse
require.NoError(t, client.Call("Plugin.GetPlugin", 0, &resp))

require.Len(t, resp.Credentials, 2)
assert.Equal(t, testAccessKey, resp.Credentials[0].Name)
assert.Equal(t, testSSOProfile, resp.Credentials[1].Name)
assert.Equal(t, map[proto.CredentialID]bool{0: true, 1: true}, resp.CredentialHasImporter)

require.Len(t, resp.Executables, 1)
uses := resp.Executables[0].Uses
require.Len(t, uses, 2)
assert.Equal(t, testAccessKey, uses[0].Name)
assert.True(t, uses[0].Optional)
assert.Equal(t, testSSOProfile, uses[1].Name)
assert.True(t, uses[1].Optional)
assert.Equal(t, map[proto.CredentialUsageID]bool{
{Executable: 0, Usage: 0}: false,
{Executable: 0, Usage: 1}: true,
}, resp.CredentialUsageHasProvisioner)
}

func TestProvisionWithTwoCredentialTypesOverRPC(t *testing.T) {
client := connectToTestPlugin(t, testPluginWithTwoCredentialTypes())

cases := map[string]struct {
id proto.ProvisionerID
expected string
expectedErr string
}{
"default provisioner of the first credential type": {
id: proto.ProvisionerID{IsDefaultProvisioner: true, Credential: 0},
expected: "access key default",
},
"default provisioner of the second credential type": {
id: proto.ProvisionerID{IsDefaultProvisioner: true, Credential: 1},
expected: "sso profile default",
},
"provisioner of the second credential usage": {
id: proto.ProvisionerID{CredentialUsage: proto.CredentialUsageID{Executable: 0, Usage: 1}},
expected: "sso profile usage",
},
"first credential usage has no provisioner of its own": {
id: proto.ProvisionerID{CredentialUsage: proto.CredentialUsageID{Executable: 0, Usage: 0}},
expectedErr: "field not set for plugin.Executables[0].Uses[0].Provisioner.Provisioner",
},
}

for name, tc := range cases {
t.Run(name, func(t *testing.T) {
var description string
err := client.Call("Plugin.CredentialProvisionerDescription", tc.id, &description)
if tc.expectedErr != "" {
assert.EqualError(t, err, tc.expectedErr)
return
}
require.NoError(t, err)
assert.Equal(t, tc.expected, description)

var out sdk.ProvisionOutput
require.NoError(t, client.Call("Plugin.CredentialProvisionerProvision", newTestProvisionRequest(tc.id), &out))
assert.Equal(t, map[string]string{"PROVISIONED_BY": tc.expected}, out.Environment)
assert.Equal(t, []string{"example"}, out.CommandLine)
})
}
}

func TestImportWithTwoCredentialTypesOverRPC(t *testing.T) {
client := connectToTestPlugin(t, testPluginWithTwoCredentialTypes())

cases := map[string]struct {
id proto.CredentialID
expected string
}{
"importer of the first credential type": {
id: 0,
expected: "access key importer",
},
"importer of the second credential type": {
id: 1,
expected: "sso profile importer",
},
}

for name, tc := range cases {
t.Run(name, func(t *testing.T) {
var out sdk.ImportOutput
require.NoError(t, client.Call("Plugin.CredentialImport", proto.ImportCredentialRequest{CredentialID: tc.id}, &out))

require.Len(t, out.Attempts, 1)
require.Len(t, out.Attempts[0].Candidates, 1)
assert.Equal(t, tc.expected, out.Attempts[0].Candidates[0].NameHint)
})
}
}
8 changes: 7 additions & 1 deletion sdk/schema/executable.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ type Executable struct {
Name string

// Which credentials the executable requires to run and how these should be provisioned.
//
// The order is significant when there is more than one. 1Password CLI attributes configurations
// that were saved before an executable had several credential usages to the first one, because
// they do not record which usage they belong to. Add new usages after the existing ones.
Uses []CredentialUsage

// (Optional) A URL to the documentation about this executable.
Expand Down Expand Up @@ -49,7 +53,9 @@ type CredentialUsage struct {
// `NeedsAuth`, which can still be used for more generic authentications opt-outs, such as the help flag.
NeedsAuth sdk.NeedsAuthentication

// Whether this credential is needed for the executable to run. If set to true, the executable cannot run without provisioning this credential.
// (Optional) Whether the executable can run without this credential. If set to true, the user can skip
// this credential when configuring the executable. Defaults to false, in which case the credential is
// required.
Optional bool
}

Expand Down
Loading
Loading