Go的monkey.PatchInstanceMethod返回“权限被拒绝”错误?

时间:2019-12-10 04:10:58

标签: go monkeypatching

我试图提出一个简单的,最小的示例来重现此错误,但无法(仅在一个私有仓库中发生),但我将从展示我的尝试开始。假设我们有一个具有以下结构的Go模块:

.
├── command
│   ├── command.go
│   └── command_test.go
├── go.mod
└── go.sum

go.mod读取的地方

module github.com/kurtpeek/monkeypatching

go 1.12

require (
    bou.ke/monkey v1.0.2
    github.com/google/go-cmp v0.3.1 // indirect
    github.com/pkg/errors v0.8.1 // indirect
    github.com/stretchr/testify v1.4.0
    gotest.tools v2.2.0+incompatible
)

command.go

package command

import "os/exec"

// RunCommand runs a command
func RunCommand() ([]byte, error) {
    return exec.Command("profiles", "list", "-all").Output()
}

command_test.go

package command

import (
    "os/exec"
    "reflect"
    "testing"

    "bou.ke/monkey"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)

func TestRunCommand(t *testing.T) {
    var cmd *exec.Cmd
    patchGuard := monkey.PatchInstanceMethod(reflect.TypeOf(cmd), "Output", func(_ *exec.Cmd) ([]byte, error) {
        return []byte("foobar"), nil
    })
    defer patchGuard.Unpatch()

    output, err := RunCommand()
    require.NoError(t, err)
    assert.Equal(t, []byte("foobar"), output)
}

此测试通过。

现在,在我的“真实”仓库中,我有一个类似的单元测试

func TestFindIdentity(t *testing.T) {
    certPEM, err := ioutil.ReadFile("testdata/6dc9bf91-37c6-4882-bfaf-301f118f7fac.pem")
    require.NoError(t, err)

    var cmd *exec.Cmd
    patchGuard := monkey.PatchInstanceMethod(reflect.TypeOf(cmd), "Output", func(_ *exec.Cmd) ([]byte, error) {
        output, err := ioutil.ReadFile("testdata/find_identity_match.txt")
        require.NoError(t, err)
        return output, nil
    })
    defer patchGuard.Unpatch()

    found, err := FindIdentity(certPEM)

    assert.True(t, found)
}

FindIdentity()读取的地方

// FindIdentity checks whether there is an identity (certificate + private key) for the given certificate in the system keychain
func FindIdentity(certPEM []byte) (bool, error) {
    ctx, cancel := context.WithTimeout(context.TODO(), time.Second*5)
    defer cancel()

    fingerprint, err := GetFingerprint(certPEM)
    if err != nil {
        return false, fmt.Errorf("get cert fingerprint: %v", err)
    }

    output, err := exec.CommandContext(ctx, cmdSecurity, "find-identity", systemKeychain).Output()
    if err != nil {
        return false, fmt.Errorf("find identity: %v", err)
    }

    return strings.Contains(string(output), fingerprint), nil
}

// GetFingerprint generates a SHA-1 fingerprint of a certificate, which is how it can be identified from the `security` command
func GetFingerprint(certPEM []byte) (string, error) {
    block, _ := pem.Decode(certPEM)
    if block == nil {
        return "", errors.New("failed to decode cert PEM")
    }

    cert, err := x509.ParseCertificate(block.Bytes)
    if err != nil {
        return "", fmt.Errorf("parse certificate: %v", err)
    }

    fingerprint := fmt.Sprintf("%x", sha1.Sum(cert.Raw))
    fingerprint = strings.Replace(fingerprint, " ", "", -1)
    return strings.ToUpper(fingerprint), nil
}

因此,类似地,它使用在单元测试中修补的Command。但是,如果尝试运行单元测试,则会出现此错误:

Running tool: /usr/local/opt/go@1.12/bin/go test -timeout 30s github.com/fleetsmith/agent/agent/auth/defaultauth -run ^(TestFindIdentity)$

--- FAIL: TestFindIdentity (0.00s)
panic: permission denied [recovered]
    panic: permission denied

goroutine 25 [running]:
testing.tRunner.func1(0xc000494100)
    /usr/local/Cellar/go@1.12/1.12.12/libexec/src/testing/testing.go:830 +0x392
panic(0x48fede0, 0xc000554730)
    /usr/local/Cellar/go@1.12/1.12.12/libexec/src/runtime/panic.go:522 +0x1b5
bou.ke/monkey.mprotectCrossPage(0x41c20e0, 0xc, 0x7)
    /Users/kurt/go/pkg/mod/bou.ke/monkey@v1.0.2/replace_unix.go:15 +0xe6
bou.ke/monkey.copyToLocation(0x41c20e0, 0xc0000ebd2c, 0xc, 0xc)
    /Users/kurt/go/pkg/mod/bou.ke/monkey@v1.0.2/replace_unix.go:26 +0x6d
bou.ke/monkey.replaceFunction(0x41c20e0, 0xc0001a2510, 0x13, 0x41c20e0, 0x48c3b00)
    /Users/kurt/go/pkg/mod/bou.ke/monkey@v1.0.2/replace.go:29 +0xe6
bou.ke/monkey.patchValue(0x48c3b60, 0xc0000bc078, 0x13, 0x48c3b60, 0xc0001a2510, 0x13)
    /Users/kurt/go/pkg/mod/bou.ke/monkey@v1.0.2/monkey.go:87 +0x22f
bou.ke/monkey.PatchInstanceMethod(0x4b359a0, 0x4996280, 0x49d0699, 0x6, 0x48c3b60, 0xc0001a2510, 0x0)
    /Users/kurt/go/pkg/mod/bou.ke/monkey@v1.0.2/monkey.go:62 +0x160
github.com/fleetsmith/agent/agent/auth/defaultauth.TestFindIdentity(0xc000494100)
    /Users/kurt/go/src/github.com/fleetsmith/agent/agent/auth/defaultauth/keychain_test.go:46 +0x146
testing.tRunner(0xc000494100, 0x4a30260)
    /usr/local/Cellar/go@1.12/1.12.12/libexec/src/testing/testing.go:865 +0xc0
created by testing.(*T).Run
    /usr/local/Cellar/go@1.12/1.12.12/libexec/src/testing/testing.go:916 +0x35a
FAIL    github.com/fleetsmith/agent/agent/auth/defaultauth  0.390s
Error: Tests failed.

具体来说,在此行调用permission denied时,我会惊慌monkey.PatchInstanceMethod

patchGuard := monkey.PatchInstanceMethod(reflect.TypeOf(cmd), "Output", func(_ *exec.Cmd) ([]byte, error) {

})

有什么想法会导致这种情况吗?我的“真实”存储库和我的临时存储库之间一定有一些区别。

1 个答案:

答案 0 :(得分:0)

mprotect在MacOS Catalina上的系统调用失败,对此有更多解释:Using mprotect to make text segment writable on macOS

如果您在go测试中使用go猴子库。这样就无法直接运行go测试。实际去做以下事情:

  • 将测试功能编译为一个临时二进制文件
  • 执行二进制文件
  • 删除临时二进制文件

要变通解决此问题,我们需要首先生成测试二进制文件,然后使用dd修改编译后的二进制文件。例如

$ go test -c -o test-bin mytest/abc

使用-c和-o选项,go test将生成一个名为test-bin的二进制文件。链接后,通过dd命令将二进制文件从set __TEXT(max_prot)修改为0x7

$  printf '\x07' | dd of=test-bin bs=1 seek=160 count=1 conv=notrunc

最后,您可以运行测试二进制文件:

./test-bin