| 1 | package sshd |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "io" |
| 7 | "testing" |
| 8 | |
| 9 | "gitlab.com/Timfa/bluegit/internal/store" |
| 10 | "golang.org/x/crypto/ssh" |
| 11 | ) |
| 12 | |
| 13 | type memCh struct { |
| 14 | in bytes.Reader |
| 15 | out bytes.Buffer |
| 16 | err bytes.Buffer |
| 17 | } |
| 18 | |
| 19 | func (m *memCh) Read(p []byte) (int, error) { return m.in.Read(p) } |
| 20 | func (m *memCh) Write(p []byte) (int, error) { return m.out.Write(p) } |
| 21 | func (m *memCh) Close() error { return nil } |
| 22 | func (m *memCh) CloseWrite() error { return nil } |
| 23 | func (m *memCh) SendRequest(string, bool, []byte) (bool, error) { |
| 24 | return true, nil |
| 25 | } |
| 26 | func (m *memCh) Stderr() io.ReadWriter { return &m.err } |
| 27 | |
| 28 | func TestAPICommandUsesHook(t *testing.T) { |
| 29 | var gotMethod, gotPath, gotBody string |
| 30 | s := &Server{API: func(_ context.Context, user store.User, method, path string, body []byte) (int, []byte) { |
| 31 | if user.Username != "ada" { |
| 32 | t.Fatalf("user %s", user.Username) |
| 33 | } |
| 34 | gotMethod, gotPath, gotBody = method, path, string(body) |
| 35 | return 200, []byte(`{"username":"ada"}`) |
| 36 | }} |
| 37 | ch := &memCh{} |
| 38 | ch.in.Reset([]byte(`{"name":"x"}`)) |
| 39 | code := s.execGit(ch, store.User{Username: "ada"}, `api POST /api/v1/user/tokens`) |
| 40 | if code != 0 || gotMethod != "POST" || gotPath != "/api/v1/user/tokens" || gotBody != `{"name":"x"}` { |
| 41 | t.Fatalf("code %d %s %s %s", code, gotMethod, gotPath, gotBody) |
| 42 | } |
| 43 | if ch.out.String() != `{"username":"ada"}` || ch.err.String() != "status 200\n" { |
| 44 | t.Fatalf("out %q err %q", ch.out.String(), ch.err.String()) |
| 45 | } |
| 46 | |
| 47 | ch = &memCh{} |
| 48 | s.API = func(context.Context, store.User, string, string, []byte) (int, []byte) { |
| 49 | return 403, []byte(`{"message":"nee"}`) |
| 50 | } |
| 51 | if s.execGit(ch, store.User{Username: "ada"}, "api GET /api/v1/projects") != 1 { |
| 52 | t.Fatal("verwacht exit 1") |
| 53 | } |
| 54 | if ch.err.String() != "status 403\n" || ch.out.String() != `{"message":"nee"}` { |
| 55 | t.Fatalf("out %q err %q", ch.out.String(), ch.err.String()) |
| 56 | } |
| 57 | var _ ssh.Channel = ch |
| 58 | } |