internal/sshd/refusal_test.go

ff759b53942049b2043e132f5482b442a7265b98
gitbay/internal/sshd/refusal_test.go history · blame · raw

68 lines · 2010 bytes

 1package sshd
 2
 3import (
 4	"bytes"
 5	"path/filepath"
 6	"strings"
 7	"testing"
 8
 9	"gitbay.org/gitbay/internal/config"
10	"gitbay.org/gitbay/internal/control"
11	"gitbay.org/gitbay/internal/protocol"
12	"gitbay.org/gitbay/internal/store"
13)
14
15// execFixture: alice owns the public alice/app; bob has no grant on it.
16func execFixture(t *testing.T) (config.Config, *store.Store, store.User) {
17	t.Helper()
18	st, err := store.Open(filepath.Join(t.TempDir(), "gitbay.db"))
19	if err != nil {
20		t.Fatal(err)
21	}
22	t.Cleanup(func() { st.Close() })
23	if err := st.MigrateUp(); err != nil {
24		t.Fatal(err)
25	}
26	alice, err := st.CreateUser("alice", false)
27	if err != nil {
28		t.Fatal(err)
29	}
30	if _, err := st.CreateRepo("user", alice, "app", "public"); err != nil {
31		t.Fatal(err)
32	}
33	bobID, err := st.CreateUser("bob", false)
34	if err != nil {
35		t.Fatal(err)
36	}
37	bob, err := st.UserByID(bobID)
38	if err != nil {
39		t.Fatal(err)
40	}
41	cfg := config.Default()
42	cfg.Server.Root = t.TempDir()
43	return cfg, st, bob
44}
45
46// A refused push leaves one row holding the target, the key and the exit
47// code, whether runGit refused it or the account is not yet active.
48func TestRefusedPushIsAudited(t *testing.T) {
49	for _, pending := range []bool{false, true} {
50		cfg, st, bob := execFixture(t)
51		bob.Pending = pending
52		key := store.SSHKey{Scope: "full", Fingerprint: "SHA256:test"}
53		var out, errOut bytes.Buffer
54		code := Exec(cfg, st, bob, key, control.Term{}, "git-receive-pack alice/app",
55			strings.NewReader(""), &out, &errOut, nil, nil, nil)
56		if code != protocol.ExitDenied {
57			t.Fatalf("pending %v: exit %d: %s", pending, code, errOut.String())
58		}
59		got, err := st.AuditEntries(store.AuditFilter{ActionPrefix: "refused git-receive-pack", Limit: 5})
60		if err != nil || len(got) != 1 || got[0].Actor != "bob" {
61			t.Fatalf("pending %v: entries %+v, %v", pending, got, err)
62		}
63		want := `{"argv":["alice/app"],"exit":4,"source":"SHA256:test"}`
64		if got[0].Data != want {
65			t.Fatalf("pending %v: data %s, want %s", pending, got[0].Data, want)
66		}
67	}
68}