Go的monkey.PatchInstanceMethod返回 "permission denied"错误?

标签 go monkeypatching

我试图想出一个简单的、最小的例子来重现这个错误,但没能(它只发生在一个私有(private)仓库中),但我将首先展示我的尝试。假设我们有一个具有以下结构的 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)
}

该测试通过。

现在,在我的“真实” repo 中,我有一个类似的单元测试
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 时 panic 在这一行:
patchGuard := monkey.PatchInstanceMethod(reflect.TypeOf(cmd), "Output", func(_ *exec.Cmd) ([]byte, error) {

})

知道是什么原因造成的吗?我的“真实” repo 和我的临时 repo 之间一定有一些区别。

最佳答案

mprotect系统调用在 MacOS Catalina 上失败,更多解释:Using mprotect to make text segment writable on macOS
如果你在 go test 中使用 go monkey 库。然后你不能直接运行 go test 。实际上去测试做以下事情:

  • 将测试函数编译成临时二进制文件
  • 执行二进制
  • 删除临时二进制文件

  • 要解决这个问题,我们需要首先生成测试二进制文件,使用 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
    

    关于Go的monkey.PatchInstanceMethod返回 "permission denied"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59260100/

    相关文章:

    ruby - 猴子补丁类方​​法

    go - 让 http.handleFunc() 在 gRPC 服务器上工作

    mysql - SQL结构和日历?

    go - "invalid memory address or nil pointer deference"做教程

    ruby - 猴子修补 ruby​​ 类的推荐方法

    python - Pytest:如何通过输入调用测试单独的函数?

    python - 如何检查是否可以在 Python 对象中设置(修补)属性

    go - 如何在 Go 中编辑阅读器

    sql - 使用 Go 插入到 Postgresql 表中

    python - monkeypatching stdlib 方法是 Python 中的一个好习惯吗?