1// Copyright 2019 Keybase Inc. All rights reserved.
2// Use of this source code is governed by a BSD
3// license that can be found in the LICENSE file.
4
5// +build windows
6
7package libdokan
8
9import (
10	"errors"
11	"io"
12	"os"
13	"os/exec"
14	"path/filepath"
15	"strings"
16	"testing"
17
18	"github.com/keybase/client/go/kbfs/libcontext"
19	"github.com/keybase/client/go/kbfs/libkbfs"
20	"github.com/keybase/client/go/kbun"
21)
22
23func findGoExe() (string, error) {
24	for _, path := range []string{"go.exe",
25		os.Getenv("GOBIN") + "/go.exe", os.Getenv("GOROOT") + "/bin/go.exe"} {
26		exe, err := exec.LookPath(path)
27		if err == nil {
28			return exe, err
29		}
30
31	}
32	return "", errors.New("Cannot find go.exe")
33}
34
35func copyFile(from, to string) error {
36	src, err := Open(from)
37	if err != nil {
38		return err
39	}
40	defer src.Close()
41	tgt, err := Create(to)
42	if err != nil {
43		return err
44	}
45	defer tgt.Close()
46	_, err = io.Copy(tgt, src)
47	if err != nil {
48		return err
49	}
50	err = tgt.Sync()
51	if err != nil {
52		return err
53	}
54	return nil
55}
56
57func unames(uns []string) []kbun.NormalizedUsername {
58	res := make([]kbun.NormalizedUsername, len(uns))
59	for i, v := range uns {
60		res[i] = kbun.NormalizedUsername(v)
61	}
62	return res
63}
64
65func testNoExec(t *testing.T, users []string) error {
66	ctx := libcontext.BackgroundContextWithCancellationDelayer()
67	defer testCleanupDelayer(ctx, t)
68	config := libkbfs.MakeTestConfigOrBust(t, unames(users)...)
69	// Background flushed needed for large files.
70	config.SetDoBackgroundFlushes(true)
71	defer libkbfs.CheckConfigAndShutdown(ctx, t, config)
72	mnt, _, cancelFn := makeFS(ctx, t, config)
73	defer mnt.Close()
74	defer cancelFn()
75
76	exe, err := findGoExe()
77	if err != nil {
78		t.Fatal("Error finding go.exe: ", err)
79	}
80
81	tlfName := strings.Join(users, ",")
82	targetPath := filepath.Join(mnt.Dir, PrivateName, tlfName, "test.exe")
83
84	err = copyFile(exe, targetPath)
85	if err != nil {
86		t.Fatal("Error copying go.exe to kbfs: ", err)
87	}
88
89	return exec.Command(targetPath, "version").Run()
90
91}
92func TestNoExec(t *testing.T) {
93	err := testNoExec(t, []string{"jdoe", "janedoe"})
94	if err == nil {
95		t.Fatal("Unexpected success executing go on kbfs, expected fail (noexec)")
96	}
97	if !os.IsPermission(err) {
98		t.Fatal("Wrong error trying to execute go on kbfs: ", err)
99	}
100}
101
102func TestNoExecWhitelist(t *testing.T) {
103	err := testNoExec(t, []string{"jdoe"})
104	if err != nil {
105		t.Fatal("Unexpected failure executing go on kbfs, expected success (whitelist): ", err)
106	}
107}
108