oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "errors"
8 "io"
9 "net"
10 "net/http"
11 "net/http/httptest"
12 "strings"
13 "sync/atomic"
14 "testing"
15 "time"
16)
17
18func githubTestTransport(t *testing.T, handler http.HandlerFunc) (*http.Transport, string) {
19 t.Helper()
20 s := httptest.NewTLSServer(handler)
21 t.Cleanup(s.Close)
22 tr := s.Client().Transport.(*http.Transport).Clone()
23 tr.TLSClientConfig = tr.TLSClientConfig.Clone()
24 tr.TLSClientConfig.ServerName = "example.com"
25 tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
26 if addr != "api.github.com:443" {
27 t.Errorf("unexpected destination %q", addr)
28 }
29 return (&net.Dialer{}).DialContext(ctx, network, s.Listener.Addr().String())
30 }
31 t.Cleanup(tr.CloseIdleConnections)
32 return tr, s.Listener.Addr().String()
33}
34
35func TestCheckGitHubCommand(t *testing.T) {
36 var calls atomic.Int32
37 tr, peer := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) {
38 calls.Add(1)
39 if r.Method != "GET" || r.URL.RequestURI() != "/meta" || r.Host != "api.github.com" || r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
40 t.Errorf("unexpected request: %s %s host=%s", r.Method, r.URL.RequestURI(), r.Host)
41 }
42 w.Header().Set("X-Secret", "response-header-secret")
43 _, _ = io.WriteString(w, "response-body-secret")
44 })
45 var out bytes.Buffer
46 handled, code := runCheckCommand([]string{"check-github"}, &out, tr)
47 if !handled || code != 0 || calls.Load() != 1 {
48 t.Fatalf("handled=%v code=%d requests=%d output=%q", handled, code, calls.Load(), out.String())
49 }
50 if !strings.Contains(out.String(), "reachable: true; status: 200; latency: ") || !strings.Contains(out.String(), "TLS peer: "+peer) || strings.Count(out.String(), "\n") != 1 || strings.Contains(out.String(), "secret") {
51 t.Fatalf("unsafe or incomplete output: %q", out.String())
52 }
53 for _, args := range [][]string{nil, {"serve"}, {"check-github", "https://evil.invalid"}} {
54 if handled, _ := runCheckCommand(args, io.Discard, tr); handled {
55 t.Fatalf("unexpected command match: %q", args)
56 }
57 }
58}
59
60func TestCheckGitHubBypassesBoot(t *testing.T) {
61 t.Setenv("EQUIPO_ORIGIN", "")
62 t.Setenv("EQUIPO_INSTANCE_KEY", "")
63 tr, _ := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
64 var out, diagnostics bytes.Buffer
65 if code := commandMain([]string{"check-github"}, &out, &diagnostics, tr); code != 0 || !strings.Contains(out.String(), "status: 200;") || diagnostics.Len() != 0 {
66 t.Fatalf("code=%d output=%q diagnostics=%q", code, out.String(), diagnostics.String())
67 }
68}
69
70func TestCheckGitHubRefusesRedirect(t *testing.T) {
71 var calls atomic.Int32
72 tr, _ := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) {
73 calls.Add(1)
74 http.Redirect(w, r, "https://api.github.com/private-location-secret", http.StatusFound)
75 })
76 var out bytes.Buffer
77 if code := checkGitHub(context.Background(), &out, tr); code != 1 || calls.Load() != 1 || !strings.Contains(out.String(), "status: 302;") || strings.Contains(out.String(), "secret") {
78 t.Fatalf("code=%d requests=%d output=%q", code, calls.Load(), out.String())
79 }
80}
81
82func TestCheckGitHubDoesNotReadBody(t *testing.T) {
83 tr, _ := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) {
84 w.WriteHeader(http.StatusOK)
85 w.(http.Flusher).Flush()
86 <-r.Context().Done()
87 })
88 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
89 defer cancel()
90 start := time.Now()
91 if code := checkGitHub(ctx, io.Discard, tr); code != 0 || time.Since(start) >= 500*time.Millisecond {
92 t.Fatalf("body was read: code=%d duration=%v", code, time.Since(start))
93 }
94}
95
96func TestCheckGitHubFailureIsBoundedAndPrivate(t *testing.T) {
97 tr, _ := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })
98 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
99 defer cancel()
100 var out bytes.Buffer
101 if code := checkGitHub(ctx, &out, tr); code != 1 || strings.Contains(out.String(), "deadline") || !strings.Contains(out.String(), "reachable: false; status: 0;") {
102 t.Fatalf("code=%d output=%q", code, out.String())
103 }
104 client := githubCheckClient(nil)
105 if client.Timeout <= 0 || client.Timeout > 5*time.Second || client.Jar != nil {
106 t.Fatalf("unbounded or stateful client: %+v", client)
107 }
108 transport := client.Transport.(*http.Transport)
109 if transport.Proxy != nil || transport.TLSHandshakeTimeout <= 0 || transport.MaxResponseHeaderBytes != 16<<10 || (transport.TLSClientConfig != nil && transport.TLSClientConfig.InsecureSkipVerify) {
110 t.Fatal("unsafe production transport")
111 }
112}
113
114func TestCheckGitHubRequiresVerifiedTLS(t *testing.T) {
115 tr, _ := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
116 tr.TLSClientConfig = &tls.Config{ServerName: "wrong.invalid"}
117 var out bytes.Buffer
118 if code := checkGitHub(context.Background(), &out, tr); code != 1 || !strings.Contains(out.String(), "reachable: false; status: 0;") || !strings.Contains(out.String(), "TLS peer: -") || strings.Contains(out.String(), "certificate") {
119 t.Fatalf("code=%d output=%q", code, out.String())
120 }
121}
122
123func TestCheckGitHubUnverifiedPeerAndHTTPFailure(t *testing.T) {
124 for _, status := range []int{http.StatusOK, http.StatusServiceUnavailable} {
125 tr, _ := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(status) })
126 if status == http.StatusOK {
127 tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // Test a peer with no verified chain.
128 }
129 var out bytes.Buffer
130 if code := checkGitHub(context.Background(), &out, tr); code != 1 {
131 t.Fatalf("status=%d code=%d output=%q", status, code, out.String())
132 }
133 if status == http.StatusOK && !strings.Contains(out.String(), "TLS peer: -") {
134 t.Fatalf("unverified peer reported: %q", out.String())
135 }
136 }
137}
138
139type brokenCheckOutput struct{}
140
141func (brokenCheckOutput) Write([]byte) (int, error) { return 0, errors.New("output-secret") }
142
143func TestCheckGitHubOutputFailure(t *testing.T) {
144 tr, _ := githubTestTransport(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
145 if code := checkGitHub(context.Background(), brokenCheckOutput{}, tr); code != 1 {
146 t.Fatal("successful exit despite failed output")
147 }
148}
149