package server import ( "context" "encoding/base64" "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/coder/websocket" "github.com/coder/websocket/wsjson" "git.a-wan.net/alan/pipelines/internal/protocol" ) // writeTestWebAuth writes a private auth file with a cheap scrypt hash. func writeTestWebAuth(t *testing.T, password string) string { t.Helper() salt := []byte("0123456789abcdef") key, err := scryptKey([]byte(password), salt, 1024, 8, 1, 32) if err != nil { t.Fatal(err) } hash := fmt.Sprintf("scrypt$1024$8$1$%s$%s", base64.RawURLEncoding.EncodeToString(salt), base64.RawURLEncoding.EncodeToString(key)) return writeTestAuthJSON(t, map[string]any{"password_hash": hash, "secret": strings.Repeat("s", 40), "generation": 1}) } func writeTestAuthJSON(t *testing.T, value map[string]any) string { t.Helper() path := filepath.Join(t.TempDir(), "web-auth.json") body, _ := json.Marshal(value) if err := os.WriteFile(path, body, 0o600); err != nil { t.Fatal(err) } return path } func TestWebAuthVerifierHashPlaintextAndUnsafeFiles(t *testing.T) { verifier, err := readWebAuth(writeTestWebAuth(t, "correct horse battery staple")) if err != nil { t.Fatal(err) } for candidate, want := range map[string]bool{"correct horse battery staple": true, "correct horse battery stapl": false, "": false} { if got, err := verifier.verify(candidate); err != nil || got != want { t.Fatalf("verify(%q) = %v, %v", candidate, got, err) } } legacy, err := readWebAuth(writeTestAuthJSON(t, map[string]any{"password": "legacy-password", "secret": strings.Repeat("s", 40)})) if err != nil { t.Fatal(err) } if ok, _ := legacy.verify("legacy-password"); !ok { t.Fatal("legacy plaintext password not accepted") } if ok, _ := legacy.verify("legacy-passwore"); ok { t.Fatal("wrong legacy password accepted") } public := writeTestWebAuth(t, "x") if err := os.Chmod(public, 0o644); err != nil { t.Fatal(err) } if _, err := readWebAuth(public); err == nil || !strings.Contains(err.Error(), "private") { t.Fatalf("public file accepted: %v", err) } if _, err := readWebAuth(writeTestAuthJSON(t, map[string]any{"password_hash": "scrypt$1000$8$1$AAAA$BBBB"})); err == nil { t.Fatal("malformed hash accepted") } if _, err := readWebAuth(filepath.Join(t.TempDir(), "absent.json")); err != errWebAuthMissing { t.Fatalf("missing file: %v", err) } } func TestElevationBackoffGlobalCapAndExpiry(t *testing.T) { gate := newElevationGate(writeTestWebAuth(t, "right password here"), time.Minute) now := time.Unix(1_800_000_000, 0) gate.now = func() time.Time { return now } if _, err := gate.elevate("a", "wrong"); err == nil || err.Error() != "wrong password" { t.Fatalf("wrong password: %v", err) } // The connection now waits before its next attempt, even a right one. if _, err := gate.elevate("a", "right password here"); err == nil || !strings.Contains(err.Error(), "too many") { t.Fatalf("backoff not applied: %v", err) } now = now.Add(2 * time.Second) reply, err := gate.elevate("a", "right password here") if err != nil || reply.Seconds != 60 || reply.Token == "" { t.Fatalf("elevate: %+v %v", reply, err) } if !gate.elevated("a") || !gate.tokenValid(reply.Token) || gate.elevated("b") { t.Fatal("elevation state wrong after success") } now = now.Add(time.Minute) if gate.elevated("a") || gate.tokenValid(reply.Token) { t.Fatal("elevation outlived its lifetime") } // Ten wrong passwords from separate connections close the gate for all. for i := range elevationGlobalFailures { if _, err := gate.elevate(fmt.Sprintf("c%d", i), "wrong"); err == nil { t.Fatal("wrong password accepted") } } if _, err := gate.elevate("fresh", "right password here"); err == nil || !strings.Contains(err.Error(), "too many") { t.Fatalf("global cap not applied: %v", err) } now = now.Add(elevationGlobalWindow) fresh := connectionElevationKey("fresh") if _, err := gate.elevate(fresh, "right password here"); err != nil { t.Fatalf("global window did not drain: %v", err) } gate.closed(fresh) if gate.elevated(fresh) { t.Fatal("closed connection stayed elevated") } } func elevationRequest(t *testing.T, ctx context.Context, conn *websocket.Conn, message protocol.Message) protocol.Message { t.Helper() if err := wsjson.Write(ctx, conn, message); err != nil { t.Fatal(err) } for { var reply protocol.Message if err := wsjson.Read(ctx, conn, &reply); err != nil { t.Fatal(err) } if reply.ID == message.ID { return reply } } } func TestGatedRequestsNeedElevationOnTheSameConnection(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() t.Setenv("HOME", t.TempDir()) // the gated handlers never touch the real home auth := writeTestWebAuth(t, "right password here") srv := httptest.NewServer(HandlerWithOptions(ctx, Options{WebAuthFile: auth})) defer srv.Close() dial := func() *websocket.Conn { conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", nil) if err != nil { t.Fatal(err) } t.Cleanup(func() { conn.CloseNow() }) return conn } conn := dial() gated := []protocol.Message{ {Type: protocol.ChatShellRun, ID: "run"}, {Type: protocol.ChatShellInput, ID: "input"}, {Type: protocol.DeletePath, ID: "delete", DeletePath: &protocol.DeletePathRequest{Path: "~/absent-elevation-test"}}, {Type: protocol.RenamePath, ID: "rename"}, {Type: protocol.MovePath, ID: "move"}, } for _, request := range gated { reply := elevationRequest(t, ctx, conn, request) if reply.Type != protocol.Error || reply.Code != protocol.ErrorElevationRequired { t.Fatalf("%s not refused: %+v", request.Type, reply) } } // Terminals are not gated (su -l asks for the account password); this // server has no store, so terminal_open fails on its own terms. for _, request := range []protocol.Message{ {Type: protocol.TerminalOpen, ID: "terminal"}, {Type: protocol.TerminalInput, ID: "terminal-input", TerminalRequest: &protocol.TerminalRequest{TerminalID: "absent", Data: "x"}}, } { if reply := elevationRequest(t, ctx, conn, request); reply.Code == protocol.ErrorElevationRequired { t.Fatalf("%s gated: %+v", request.Type, reply) } } // Reads are not gated. if reply := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Ping, ID: "ping"}); reply.Type != protocol.Pong { t.Fatalf("ping refused: %+v", reply) } upload := func(token string) *http.Response { request, _ := http.NewRequest(http.MethodPost, srv.URL+"/files?path=~/absent-elevation-folder", strings.NewReader("x")) request.Header.Set(chatUploadHeader, "elevation-test.txt") if token != "" { request.Header.Set(protocol.ElevationHeader, token) } response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } response.Body.Close() return response } if response := upload(""); response.StatusCode != http.StatusForbidden { t.Fatalf("upload without elevation: %d", response.StatusCode) } wrong := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "wrong", Password: "nope"}) if wrong.Type != protocol.Error || wrong.Code != protocol.ErrorElevationFailed || strings.Contains(wrong.Error, "nope") { t.Fatalf("wrong password reply: %+v", wrong) } time.Sleep(elevationBackoffBase + 100*time.Millisecond) elevated := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "right", Password: "right password here"}) if elevated.Type != protocol.Elevated || elevated.Elevation == nil || elevated.Elevation.Token == "" || elevated.Password != "" { t.Fatalf("elevate reply: %+v", elevated) } // The gate now lets the request through to its own handler. if reply := elevationRequest(t, ctx, conn, gated[2]); reply.Code == protocol.ErrorElevationRequired { t.Fatalf("elevated delete still refused: %+v", reply) } // Another connection is not elevated by this one. other := dial() if reply := elevationRequest(t, ctx, other, gated[2]); reply.Code != protocol.ErrorElevationRequired { t.Fatalf("second connection inherited elevation: %+v", reply) } if response := upload(elevated.Elevation.Token); response.StatusCode == http.StatusForbidden { t.Fatal("upload with a live elevation token refused") } if response := upload("forged"); response.StatusCode != http.StatusForbidden { t.Fatal("forged elevation token accepted") } conn.Close(websocket.StatusNormalClosure, "") deadline := time.Now().Add(5 * time.Second) for upload(elevated.Elevation.Token).StatusCode != http.StatusForbidden { if time.Now().After(deadline) { t.Fatal("upload token outlived its connection") } time.Sleep(50 * time.Millisecond) } } func TestElevationGateOffWithoutWebAuthFile(t *testing.T) { gate := newElevationGate(filepath.Join(t.TempDir(), "absent.json"), 0) var wrote []protocol.Message write := func(m protocol.Message) error { wrote = append(wrote, m); return nil } if gate.refuse(protocol.Message{Type: protocol.ChatShellRun}, "a", write) || len(wrote) != 0 { t.Fatal("gate refused without a password file") } gate.handle(protocol.Message{Type: protocol.Elevate, Password: "x"}, "a", write) if len(wrote) != 1 || wrote[0].Code != protocol.ErrorElevationUnavailable { t.Fatalf("elevate without a password file: %+v", wrote) } // A present but unusable file keeps the gate closed. broken := writeTestAuthJSON(t, map[string]any{"secret": "x"}) closed := newElevationGate(broken, 0) if !closed.refuse(protocol.Message{Type: protocol.ChatShellRun}, "a", write) { t.Fatal("unusable password file opened the gate") } if ElevationTTLFromEnvironment(func(string) string { return "30" }) != 30*time.Minute || ElevationTTLFromEnvironment(func(string) string { return "1440" }) != 24*time.Hour || ElevationTTLFromEnvironment(func(string) string { return "43201" }) != DefaultElevationTTL || ElevationTTLFromEnvironment(func(string) string { return "0" }) != DefaultElevationTTL || DefaultElevationTTL != 24*time.Hour { t.Fatal("PIPELINES_ELEVATION_MINUTES not honoured") } }