package server import ( "context" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/coder/websocket" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/servertoken" ) const ( elevationTestPassword = "right password here" elevationTestToken = "proxy-token-0123456789abcdefghijklmnopqrstuvwxyz" sessionA = "session-a-0123456789abcdef" sessionB = "session-b-0123456789abcdef" ) // elevationServer serves a gated handler; token is the shared proxy token // ("" for a server without one). func elevationServer(t *testing.T, ctx context.Context, token string) *httptest.Server { t.Helper() t.Setenv("HOME", t.TempDir()) // the gated handlers never touch the real home srv := httptest.NewServer(HandlerWithOptions(ctx, Options{WebAuthFile: writeTestWebAuth(t, elevationTestPassword), AccessToken: token})) t.Cleanup(srv.Close) return srv } func proxiedHeaders(token, session string) http.Header { headers := http.Header{} if token != "" { headers.Set(servertoken.Header, token) } if session != "" { headers.Set(protocol.SessionHeader, session) } return headers } func dialAs(t *testing.T, ctx context.Context, srv *httptest.Server, token, session string) *websocket.Conn { t.Helper() conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/connect", &websocket.DialOptions{HTTPHeader: proxiedHeaders(token, session)}) if err != nil { t.Fatal(err) } t.Cleanup(func() { conn.CloseNow() }) return conn } var gatedDelete = protocol.Message{Type: protocol.DeletePath, ID: "delete", DeletePath: &protocol.DeletePathRequest{Path: "~/absent-elevation-test"}} func refused(t *testing.T, ctx context.Context, conn *websocket.Conn) bool { t.Helper() return elevationRequest(t, ctx, conn, gatedDelete).Code == protocol.ErrorElevationRequired } func elevateOn(t *testing.T, ctx context.Context, conn *websocket.Conn) *protocol.Elevation { t.Helper() reply := elevationRequest(t, ctx, conn, protocol.Message{Type: protocol.Elevate, ID: "elevate", Password: elevationTestPassword}) if reply.Type != protocol.Elevated || reply.Elevation == nil { t.Fatalf("elevate: %+v", reply) } return reply.Elevation } func uploadAs(t *testing.T, srv *httptest.Server, token, session, elevation string) int { t.Helper() request, _ := http.NewRequest(http.MethodPost, srv.URL+"/files?path=~/absent-elevation-folder", strings.NewReader("x")) request.Header = proxiedHeaders(token, session) request.Header.Set(chatUploadHeader, "elevation-test.txt") if elevation != "" { request.Header.Set(protocol.ElevationHeader, elevation) } response, err := http.DefaultClient.Do(request) if err != nil { t.Fatal(err) } response.Body.Close() return response.StatusCode } func TestElevationLastsForTheWebSessionAcrossConnections(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() srv := elevationServer(t, ctx, elevationTestToken) first := dialAs(t, ctx, srv, elevationTestToken, sessionA) if !refused(t, ctx, first) { t.Fatal("unelevated session allowed") } if uploadAs(t, srv, elevationTestToken, sessionA, "") != http.StatusForbidden { t.Fatal("upload allowed before elevation") } elevateOn(t, ctx, first) first.Close(websocket.StatusNormalClosure, "") // A reconnect of the same session is elevated without asking again. second := dialAs(t, ctx, srv, elevationTestToken, sessionA) if refused(t, ctx, second) { t.Fatal("reconnected session lost its elevation") } if uploadAs(t, srv, elevationTestToken, sessionA, "") == http.StatusForbidden { t.Fatal("elevated session's upload refused") } // Another session, and a connection naming no session, are not. if !refused(t, ctx, dialAs(t, ctx, srv, elevationTestToken, sessionB)) { t.Fatal("a different session inherited elevation") } if !refused(t, ctx, dialAs(t, ctx, srv, elevationTestToken, "")) { t.Fatal("a connection without a session inherited elevation") } if uploadAs(t, srv, elevationTestToken, sessionB, "") != http.StatusForbidden { t.Fatal("a different session's upload allowed") } // A malformed id is not trusted (and so elevates nothing shared). if !refused(t, ctx, dialAs(t, ctx, srv, elevationTestToken, "short")) { t.Fatal("malformed session id trusted") } } func TestSessionHeaderIgnoredWithoutTheProxyToken(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() srv := elevationServer(t, ctx, "") first := dialAs(t, ctx, srv, "", sessionA) token := elevateOn(t, ctx, first).Token if refused(t, ctx, first) { t.Fatal("elevated connection refused") } // Without a configured token the header names nothing: a second // connection claiming the same session is not elevated. if !refused(t, ctx, dialAs(t, ctx, srv, "", sessionA)) { t.Fatal("untrusted session header shared elevation") } if uploadAs(t, srv, "", sessionA, "") != http.StatusForbidden { t.Fatal("untrusted session header authorised an upload") } // The connection's own token still works until the connection closes. if uploadAs(t, srv, "", "", token) == http.StatusForbidden { t.Fatal("connection token refused") } first.Close(websocket.StatusNormalClosure, "") deadline := time.Now().Add(5 * time.Second) for uploadAs(t, srv, "", "", token) != http.StatusForbidden { if time.Now().After(deadline) { t.Fatal("connection token outlived its connection") } time.Sleep(50 * time.Millisecond) } } func TestBoundaryTrustsSessionOnlyWithToken(t *testing.T) { var seen []string next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seen = append(seen, trustedSession(r)+"|"+r.Header.Get(protocol.SessionHeader)) }) for _, token := range []string{"", elevationTestToken} { request := httptest.NewRequest(http.MethodPost, "/files", nil) request.Header = proxiedHeaders(token, sessionA) guardRequests(next, token).ServeHTTP(httptest.NewRecorder(), request) } if len(seen) != 2 || seen[0] != "|" || seen[1] != sessionA+"|" { t.Fatalf("session trust = %q", seen) } } func TestSessionElevationCapAndClose(t *testing.T) { gate := newElevationGate(writeTestWebAuth(t, elevationTestPassword), time.Hour) now := time.Unix(1_800_000_000, 0) gate.now = func() time.Time { return now } key := sessionElevationKey(sessionA) reply, err := gate.elevate(key, elevationTestPassword) if err != nil || reply.Seconds != 3600 { t.Fatalf("elevate: %+v %v", reply, err) } // A session's connection closing keeps the session elevated. gate.closed(key) if !gate.elevated(key) || !gate.tokenValid(reply.Token) { t.Fatal("session elevation ended with a connection") } now = now.Add(time.Hour - time.Second) if !gate.elevated(key) { t.Fatal("session elevation ended before its cap") } now = now.Add(time.Second) if gate.elevated(key) || gate.tokenValid(reply.Token) { t.Fatal("session elevation outlived its cap") } }