80 lines
2.1 KiB
Go
80 lines
2.1 KiB
Go
package app
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestHTTPTempShellDoesNotCreateShortcut(t *testing.T) {
|
|
a, err := New(t.TempDir())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
a.token = "secret"
|
|
srv := httptest.NewServer(a.routes())
|
|
defer srv.Close()
|
|
|
|
res := do(t, srv.URL, "POST", "/v1/send", `{"remote":"peer-a","kind":"shell","shell":"echo hi"}`)
|
|
if res.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status %d", res.StatusCode)
|
|
}
|
|
body, _ := io.ReadAll(res.Body)
|
|
_ = res.Body.Close()
|
|
if !strings.Contains(string(body), "还没有连上") {
|
|
t.Fatalf("body %s", body)
|
|
}
|
|
|
|
res = do(t, srv.URL, "GET", "/v1/shortcuts/local?remote=peer-a", "")
|
|
raw, _ := io.ReadAll(res.Body)
|
|
_ = res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
t.Fatalf("list %d %s", res.StatusCode, raw)
|
|
}
|
|
if !strings.Contains(string(raw), `"items":[]`) && !strings.Contains(string(raw), `"items": []`) {
|
|
t.Fatalf("shortcut appeared: %s", raw)
|
|
}
|
|
|
|
res = do(t, srv.URL, "POST", "/v1/shortcuts/local", `{"remote_id":"peer-a","name":"打招呼","shell":"echo hi","confirm":false}`)
|
|
raw, _ = io.ReadAll(res.Body)
|
|
_ = res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
t.Fatalf("save %d %s", res.StatusCode, raw)
|
|
}
|
|
res = do(t, srv.URL, "GET", "/v1/shortcuts/local?remote=peer-a", "")
|
|
raw, _ = io.ReadAll(res.Body)
|
|
_ = res.Body.Close()
|
|
if !strings.Contains(string(raw), "打招呼") {
|
|
t.Fatalf("saved item missing: %s", raw)
|
|
}
|
|
res = do(t, srv.URL, "GET", "/v1/shortcuts/local?remote=peer-b", "")
|
|
raw, _ = io.ReadAll(res.Body)
|
|
_ = res.Body.Close()
|
|
if strings.Contains(string(raw), "打招呼") {
|
|
t.Fatalf("leaked: %s", raw)
|
|
}
|
|
}
|
|
|
|
func do(t *testing.T, base, method, path, body string) *http.Response {
|
|
t.Helper()
|
|
var rdr io.Reader
|
|
if body != "" {
|
|
rdr = strings.NewReader(body)
|
|
}
|
|
req, err := http.NewRequest(method, base+path, rdr)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Authorization", "Bearer secret")
|
|
if body != "" {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return res
|
|
}
|