| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "io" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "os" |
| 12 | "os/exec" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "syscall" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/rastrillo/rastrillo" |
| 20 | ) |
| 21 | |
| 22 | func syntheticConfig(t *testing.T) []byte { |
| 23 | t.Helper() |
| 24 | raw, err := os.ReadFile("testdata/synthetic-config.json") |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | return raw |
| 29 | } |
| 30 | |
| 31 | func TestConfigMarksOnlyNamedClientsFirstParty(t *testing.T) { |
| 32 | t.Setenv("OFICINA_CONNECT_DEK", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{5}, 32))) |
| 33 | raw := append([]byte(`{"clients":[{"id":"base","name":"Base","redirects":["https://base.example.test/callback"],"first_party":true},{"id":"host","name":"Host","redirects":["https://host.example.test/callback"]}],`), syntheticConfig(t)[1:]...) |
| 34 | cfg, err := loadConfig(raw) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | if len(cfg.Clients) != 2 || !cfg.Clients[0].FirstParty || cfg.Clients[1].FirstParty { |
| 39 | t.Fatalf("clients %+v", cfg.Clients) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | func TestApplicationHeaderBudget(t *testing.T) { |
| 44 | for _, kind := range []string{"target", "host", "repeated"} { |
| 45 | t.Run(kind, func(t *testing.T) { |
| 46 | r := httptest.NewRequest("GET", "/", nil) |
| 47 | r.Host = "h" |
| 48 | r.Header = make(http.Header) |
| 49 | switch kind { |
| 50 | case "target": |
| 51 | r.RequestURI = strings.Repeat("a", appHeaderLimit-len("Host")-len(r.Host)) |
| 52 | case "host": |
| 53 | r.Host = strings.Repeat("a", appHeaderLimit-len("Host")-len(r.RequestURI)) |
| 54 | case "repeated": |
| 55 | r.Header["Long-Header-Name"] = []string{strings.Repeat("a", appHeaderLimit-2*len("Long-Header-Name")-len("Host")-len(r.Host)-len(r.RequestURI)), ""} |
| 56 | } |
| 57 | calls := 0 |
| 58 | h := limitAppHeaders(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(204) })) |
| 59 | w := httptest.NewRecorder() |
| 60 | h.ServeHTTP(w, r) |
| 61 | if w.Code != 204 || calls != 1 { |
| 62 | t.Fatalf("boundary rejected: %d", w.Code) |
| 63 | } |
| 64 | switch kind { |
| 65 | case "target": |
| 66 | r.RequestURI += "a" |
| 67 | case "host": |
| 68 | r.Host += "a" |
| 69 | case "repeated": |
| 70 | r.Header["Long-Header-Name"][1] = "a" |
| 71 | } |
| 72 | w = httptest.NewRecorder() |
| 73 | h.ServeHTTP(w, r) |
| 74 | if w.Code != 431 || calls != 1 || w.Header().Get("Set-Cookie") != "" { |
| 75 | t.Fatalf("over budget reached app: %d calls %d", w.Code, calls) |
| 76 | } |
| 77 | }) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | func TestRuntimeExecutable(t *testing.T) { |
| 82 | // Build the real entry point, including the link-time platform version probe. |
| 83 | dir, err := os.MkdirTemp("", "connect-runtime-") |
| 84 | if err != nil { |
| 85 | t.Fatal(err) |
| 86 | } |
| 87 | t.Cleanup(func() { os.RemoveAll(dir) }) |
| 88 | binary := filepath.Join(dir, "oficina-connect") |
| 89 | build := exec.Command("go", "build", "-ldflags=-X amadan.net/rastrillo/rastrillo.BuildVersion=runtime-test-1234", "-o", binary, ".") |
| 90 | if out, err := build.CombinedOutput(); err != nil { |
| 91 | t.Fatalf("build: %v: %s", err, out) |
| 92 | } |
| 93 | raw := syntheticConfig(t) |
| 94 | baseEnv := []string{} |
| 95 | for _, v := range os.Environ() { |
| 96 | if !strings.HasPrefix(v, "OFICINA_") && !strings.HasPrefix(v, "STATE_DIRECTORY=") && !strings.HasPrefix(v, "LISTEN_") { |
| 97 | baseEnv = append(baseEnv, v) |
| 98 | } |
| 99 | } |
| 100 | secret := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{5}, 32)) |
| 101 | token := "synthetic-directory-secret-must-not-appear" |
| 102 | newCommand := func(t *testing.T, config []byte, args ...string) (*exec.Cmd, string) { |
| 103 | t.Helper() |
| 104 | work := filepath.Join(dir, strings.ReplaceAll(t.Name(), "/", "-")) |
| 105 | state := filepath.Join(work, "state") |
| 106 | if err := os.MkdirAll(state, 0700); err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | cmd := exec.Command(binary, args...) |
| 110 | cmd.Dir = work |
| 111 | cmd.Env = append(append([]string{}, baseEnv...), "STATE_DIRECTORY="+state, "OFICINA_CONNECT_CONFIG_BASE64="+base64.StdEncoding.EncodeToString(config), "OFICINA_CONNECT_DEK="+secret, "OFICINA_DIRECTORY_TOKEN="+token) |
| 112 | return cmd, state |
| 113 | } |
| 114 | for _, mode := range []string{"platform", "platform-db", "bare-socket", "standalone", "config-limit"} { |
| 115 | t.Run(mode, func(t *testing.T) { |
| 116 | socket := filepath.Join(dir, mode+".sock") |
| 117 | args := []string{"serve", "-socket", socket} |
| 118 | data := raw |
| 119 | if mode == "config-limit" { |
| 120 | data = append(append([]byte{}, raw...), bytes.Repeat([]byte(" "), platformConfigLimit-len(raw))...) |
| 121 | } |
| 122 | if mode == "bare-socket" { |
| 123 | args = args[1:] |
| 124 | } |
| 125 | if mode == "platform-db" { |
| 126 | args = append(args, "-db", "override.db") |
| 127 | } |
| 128 | cmd, state := newCommand(t, data, args...) |
| 129 | var client *http.Client |
| 130 | baseURL := "http://connect.example.test" |
| 131 | if mode == "standalone" { |
| 132 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 133 | if err != nil { |
| 134 | t.Fatal(err) |
| 135 | } |
| 136 | addr := listener.Addr().String() |
| 137 | listener.Close() |
| 138 | configPath := filepath.Join(state, "config.json") |
| 139 | if err := os.WriteFile(configPath, raw, 0600); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | cmd.Args = []string{binary, "-config", configPath, "-listen", addr, "-db", filepath.Join(state, "oficina-connect.db")} |
| 143 | for i, v := range cmd.Env { |
| 144 | if strings.HasPrefix(v, "OFICINA_CONNECT_CONFIG_BASE64=") { |
| 145 | cmd.Env[i] = "OFICINA_CONNECT_CONFIG_BASE64=" |
| 146 | } |
| 147 | } |
| 148 | transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 149 | return (&net.Dialer{}).DialContext(ctx, "tcp", addr) |
| 150 | }} |
| 151 | client = &http.Client{Transport: transport, Timeout: time.Second} |
| 152 | defer transport.CloseIdleConnections() |
| 153 | } else { |
| 154 | transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 155 | return (&net.Dialer{}).DialContext(ctx, "unix", socket) |
| 156 | }} |
| 157 | client = &http.Client{Transport: transport, Timeout: time.Second} |
| 158 | defer transport.CloseIdleConnections() |
| 159 | } |
| 160 | var output bytes.Buffer |
| 161 | cmd.Stdout = &output |
| 162 | cmd.Stderr = &output |
| 163 | if err := cmd.Start(); err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | finished := false |
| 167 | t.Cleanup(func() { |
| 168 | if !finished { |
| 169 | cmd.Process.Kill() |
| 170 | cmd.Wait() |
| 171 | } |
| 172 | }) |
| 173 | deadline := time.Now().Add(10 * time.Second) |
| 174 | for { |
| 175 | resp, err := client.Get(baseURL + "/healthz") |
| 176 | if err == nil { |
| 177 | resp.Body.Close() |
| 178 | if resp.StatusCode == 200 { |
| 179 | break |
| 180 | } |
| 181 | } |
| 182 | if time.Now().After(deadline) { |
| 183 | t.Fatal("startup timeout") |
| 184 | } |
| 185 | time.Sleep(20 * time.Millisecond) |
| 186 | } |
| 187 | check := func(path, host string, status int, contains string) { |
| 188 | t.Helper() |
| 189 | req, _ := http.NewRequest("GET", baseURL+path, nil) |
| 190 | req.Host = host |
| 191 | resp, err := client.Do(req) |
| 192 | if err != nil { |
| 193 | t.Fatal(err) |
| 194 | } |
| 195 | body, _ := io.ReadAll(resp.Body) |
| 196 | resp.Body.Close() |
| 197 | if resp.StatusCode != status || (!strings.Contains(string(body), contains) || (path == "/api/version" && string(body) != contains)) { |
| 198 | t.Fatalf("%s host %s: %d %s", path, host, resp.StatusCode, body) |
| 199 | } |
| 200 | } |
| 201 | check("/.well-known/oauth-authorization-server", "connect.example.test", 200, "https://connect.example.test") |
| 202 | check("/.well-known/oauth-authorization-server", "wrong.example.test", 404, "") |
| 203 | if mode != "standalone" { |
| 204 | check("/api/version", "probe.invalid", 200, "runtime-test-1234") |
| 205 | check("/healthz", "probe.invalid", 200, "") |
| 206 | } |
| 207 | req, _ := http.NewRequest("GET", baseURL+"/.well-known/oauth-authorization-server", nil) |
| 208 | headerSize := appHeaderLimit + 1 |
| 209 | if mode == "standalone" { |
| 210 | headerSize += 8192 |
| 211 | } // net/http reserves an extra read buffer |
| 212 | req.Header.Set("X-Large", strings.Repeat("a", headerSize)) |
| 213 | resp, err := client.Do(req) |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | resp.Body.Close() |
| 218 | if resp.StatusCode != 431 { |
| 219 | t.Fatalf("large headers status %d", resp.StatusCode) |
| 220 | } |
| 221 | // The framework parser still caps headers independently of app middleware. |
| 222 | if mode != "standalone" { |
| 223 | req, _ = http.NewRequest("GET", baseURL+"/healthz", nil) |
| 224 | req.Header.Set("X-Large", strings.Repeat("a", 32<<10)) |
| 225 | resp, err = client.Do(req) |
| 226 | if err != nil { |
| 227 | t.Fatal(err) |
| 228 | } |
| 229 | resp.Body.Close() |
| 230 | if resp.StatusCode != 200 { |
| 231 | t.Fatalf("probe incorrectly subject to app budget: %d", resp.StatusCode) |
| 232 | } |
| 233 | req, _ = http.NewRequest("GET", baseURL+"/healthz", nil) |
| 234 | req.Header.Set("X-Large", strings.Repeat("a", (1<<20)+8192)) |
| 235 | resp, err = client.Do(req) |
| 236 | if err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | resp.Body.Close() |
| 240 | if resp.StatusCode != 431 { |
| 241 | t.Fatalf("parser limit: %d", resp.StatusCode) |
| 242 | } |
| 243 | } |
| 244 | if err := cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | done := make(chan error, 1) |
| 248 | go func() { done <- cmd.Wait() }() |
| 249 | select { |
| 250 | case err := <-done: |
| 251 | finished = true |
| 252 | if err != nil { |
| 253 | t.Fatalf("shutdown %v: %s", err, output.String()) |
| 254 | } |
| 255 | case <-time.After(15 * time.Second): |
| 256 | t.Fatal("shutdown timeout") |
| 257 | } |
| 258 | database := "oficina-connect.db" |
| 259 | if mode == "platform-db" { |
| 260 | database = "override.db" |
| 261 | } |
| 262 | if _, err := os.Stat(filepath.Join(state, database)); err != nil { |
| 263 | t.Fatalf("persistent database missing: %v", err) |
| 264 | } |
| 265 | if _, err := os.Stat(filepath.Join(cmd.Dir, database)); !os.IsNotExist(err) { |
| 266 | t.Fatal("database escaped STATE_DIRECTORY") |
| 267 | } |
| 268 | if strings.Contains(output.String(), secret) || strings.Contains(output.String(), token) { |
| 269 | t.Fatal("secret in logs") |
| 270 | } |
| 271 | }) |
| 272 | } |
| 273 | for _, kind := range []string{"oversize", "malformed", "unknown", "duplicate", "missing-dek", "missing-directory", "mixed-config", "mixed-listen", "noncanonical-base64"} { |
| 274 | t.Run(kind, func(t *testing.T) { |
| 275 | data := raw |
| 276 | args := []string{"serve", "-socket", filepath.Join(dir, "refuse.sock")} |
| 277 | switch kind { |
| 278 | case "oversize": |
| 279 | data = append(append([]byte{}, raw...), bytes.Repeat([]byte(" "), platformConfigLimit+1-len(raw))...) |
| 280 | case "malformed": |
| 281 | data = []byte(`{"canary":"DO_NOT_LOG_CONFIG"`) |
| 282 | case "unknown": |
| 283 | data = append([]byte(`{"DO_NOT_LOG_CONFIG":true,`), raw[1:]...) |
| 284 | case "duplicate": |
| 285 | data = append([]byte(`{"origin":"DO_NOT_LOG_CONFIG",`), raw[1:]...) |
| 286 | case "mixed-config": |
| 287 | args = append(args, "-config", "unused") |
| 288 | case "mixed-listen": |
| 289 | args = append(args, "-listen", "127.0.0.1:0") |
| 290 | } |
| 291 | if kind == "noncanonical-base64" { |
| 292 | data = append([]byte{}, data...) |
| 293 | for len(data)%3 != 1 { |
| 294 | data = append(data, ' ') |
| 295 | } |
| 296 | } |
| 297 | cmd, state := newCommand(t, data, args...) |
| 298 | if kind == "noncanonical-base64" { |
| 299 | encoded := []byte(base64.StdEncoding.EncodeToString(data)) |
| 300 | alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" |
| 301 | index := strings.IndexByte(alphabet, encoded[len(encoded)-3]) |
| 302 | encoded[len(encoded)-3] = alphabet[index+1] // same decoded bytes, nonzero unused bits |
| 303 | if decoded, err := base64.StdEncoding.DecodeString(string(encoded)); err != nil || !bytes.Equal(decoded, data) { |
| 304 | t.Fatal("bad mutation fixture") |
| 305 | } |
| 306 | for i, v := range cmd.Env { |
| 307 | if strings.HasPrefix(v, "OFICINA_CONNECT_CONFIG_BASE64=") { |
| 308 | cmd.Env[i] = "OFICINA_CONNECT_CONFIG_BASE64=" + string(encoded) |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | if kind == "missing-dek" || kind == "missing-directory" { |
| 313 | prefix := "OFICINA_CONNECT_DEK=" |
| 314 | if kind == "missing-directory" { |
| 315 | prefix = "OFICINA_DIRECTORY_TOKEN=" |
| 316 | } |
| 317 | for i, v := range cmd.Env { |
| 318 | if strings.HasPrefix(v, prefix) { |
| 319 | cmd.Env[i] = prefix |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) |
| 324 | defer cancel() |
| 325 | bounded := exec.CommandContext(ctx, binary, cmd.Args[1:]...) |
| 326 | bounded.Env = cmd.Env |
| 327 | bounded.Dir = cmd.Dir |
| 328 | out, err := bounded.CombinedOutput() |
| 329 | if err == nil || ctx.Err() != nil { |
| 330 | t.Fatalf("expected prompt startup refusal: %v", err) |
| 331 | } |
| 332 | for _, s := range []string{secret, token, "DO_NOT_LOG_CONFIG"} { |
| 333 | if bytes.Contains(out, []byte(s)) { |
| 334 | t.Fatal("sensitive diagnostic") |
| 335 | } |
| 336 | } |
| 337 | if kind == "mixed-config" || kind == "mixed-listen" || kind == "noncanonical-base64" { |
| 338 | if _, err := os.Stat(filepath.Join(state, "oficina-connect.db")); !os.IsNotExist(err) { |
| 339 | t.Fatal("mixed arguments opened database") |
| 340 | } |
| 341 | } |
| 342 | }) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | func TestServingOptionsOwnershipAndDeadlines(t *testing.T) { |
| 347 | opts := servingOptions(rastrillo.Options{DBPath: "already-open.db", Socket: "activation.sock", Addr: "127.0.0.1:9876"}, http.NotFoundHandler()) |
| 348 | if opts.DBPath != "" { |
| 349 | t.Fatal("framework must not open a second database") |
| 350 | } |
| 351 | if opts.Socket != "activation.sock" || opts.Addr != "127.0.0.1:9876" { |
| 352 | t.Fatal("activation coordinates lost") |
| 353 | } |
| 354 | if opts.ReadHeaderTimeout != 10*time.Second || opts.ReadTimeout != 30*time.Second || opts.WriteTimeout != 60*time.Second || opts.IdleTimeout != 60*time.Second { |
| 355 | t.Fatalf("unexpected HTTP deadlines: %+v", opts) |
| 356 | } |
| 357 | if !opts.NoSpeculationRules { |
| 358 | t.Fatal("consent endpoints must not enable speculative loads") |
| 359 | } |
| 360 | } |
| 361 | |