mtls_test.go79 lines, 2.2 KB
| 1 | package mtls_test |
| 2 | |
| 3 | import ( |
| 4 | "crypto/tls" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/fiston-user/payments/internal/platform/mtls" |
| 15 | "github.com/fiston-user/payments/internal/platform/mtls/devca" |
| 16 | ) |
| 17 | |
| 18 | // issue makes a new CA, and credentials from it for each name. |
| 19 | func issue(t *testing.T, names ...string) map[string]*mtls.Config { |
| 20 | t.Helper() |
| 21 | ca, err := devca.New(time.Hour) |
| 22 | if err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | dir, creds := t.TempDir(), map[string]*mtls.Config{} |
| 26 | for _, name := range names { |
| 27 | if err := ca.Write(dir, name); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | if creds[name], err = mtls.Load(filepath.Join(dir, name)); err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | } |
| 34 | return creds |
| 35 | } |
| 36 | |
| 37 | // TestAllow calls an internal API that only ops may call, as the transfer |
| 38 | // service's review API is. |
| 39 | func TestAllow(t *testing.T) { |
| 40 | t.Parallel() |
| 41 | creds := issue(t, "transfer", "gateway", "ops") |
| 42 | srv := httptest.NewUnstartedServer(mtls.Allow("ops")(http.HandlerFunc( |
| 43 | func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, mtls.PeerFrom(r.Context())) }))) |
| 44 | srv.TLS = creds["transfer"].Server() |
| 45 | srv.StartTLS() |
| 46 | t.Cleanup(srv.Close) |
| 47 | |
| 48 | client := func(name string) *tls.Config { return creds[name].Client("transfer") } |
| 49 | anonymous := client("ops") |
| 50 | anonymous.Certificates = nil |
| 51 | forged := issue(t, "ops")["ops"].Client("transfer") // the right name, from someone else's CA |
| 52 | forged.RootCAs = anonymous.RootCAs |
| 53 | tests := []struct { |
| 54 | name string |
| 55 | config *tls.Config |
| 56 | want string // the status and body, or the error |
| 57 | }{ |
| 58 | {"no certificate", anonymous, "certificate required"}, |
| 59 | {"another CA", forged, "unknown certificate authority"}, |
| 60 | {"another service", client("gateway"), "403"}, |
| 61 | {"ops", client("ops"), "200 ops"}, |
| 62 | } |
| 63 | for _, tt := range tests { |
| 64 | t.Run(tt.name, func(t *testing.T) { |
| 65 | t.Parallel() |
| 66 | c := &http.Client{Transport: &http.Transport{TLSClientConfig: tt.config}} |
| 67 | resp, err := c.Get(srv.URL) |
| 68 | got := fmt.Sprint(err) |
| 69 | if err == nil { |
| 70 | body, _ := io.ReadAll(resp.Body) |
| 71 | resp.Body.Close() |
| 72 | got = fmt.Sprintf("%d %s", resp.StatusCode, body) |
| 73 | } |
| 74 | if !strings.Contains(got, tt.want) { |
| 75 | t.Errorf("got %s, want %s", got, tt.want) |
| 76 | } |
| 77 | }) |
| 78 | } |
| 79 | } |