From 2579e2abe52dbf1979196636470d1e2753565cec Mon Sep 17 00:00:00 2001 From: John Cai Date: Fri, 21 Nov 2025 13:24:10 -0500 Subject: [PATCH] auth: Fix IsAuthenticated to check context value The IsAuthenticated function was checking for a "username" field in gRPC metadata, but the setAuthenticated function sets a context value with authenticatedKey{}. This mismatch meant IsAuthenticated would never return true even after successful authentication. This commit fixes IsAuthenticated to check the context value that is actually set by setAuthenticated during successful token validation. This is important for the limithandler middleware which uses IsAuthenticated to determine whether to apply unauthenticated rate limits. Also adds tests for the IsAuthenticated function to verify it correctly identifies authenticated and unauthenticated contexts. --- internal/gitaly/server/auth_test.go | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/internal/gitaly/server/auth_test.go b/internal/gitaly/server/auth_test.go index ab87f67a3c..d2e24a7eab 100644 --- a/internal/gitaly/server/auth_test.go +++ b/internal/gitaly/server/auth_test.go @@ -355,6 +355,50 @@ func TestStreamingNoAuth(t *testing.T) { testhelper.RequireGrpcCode(t, err, codes.Unauthenticated) } +func TestIsAuthenticated(t *testing.T) { + t.Parallel() + + ctx := testhelper.Context(t) + + t.Run("unauthenticated context", func(t *testing.T) { + require.False(t, serverauth.IsAuthenticated(ctx)) + }) + + t.Run("authenticated context after successful token validation", func(t *testing.T) { + cfg := testcfg.Build(t, testcfg.WithBase(config.Cfg{ + Auth: auth.Config{Token: "secret-token"}, + })) + + serverSocketPath := runServer(t, cfg) + conn, err := dial(ctx, serverSocketPath, client.WithGrpcOptions([]grpc.DialOption{ + grpc.WithPerRPCCredentials(gitalyauth.RPCCredentialsV2("secret-token")), + })) + require.NoError(t, err) + t.Cleanup(func() { conn.Close() }) + + // Make a request that will go through authentication + _, err = gitalypb.NewServerServiceClient(conn).ServerInfo(ctx, &gitalypb.ServerInfoRequest{}) + require.NoError(t, err) + }) + + t.Run("unauthenticated context with wrong token", func(t *testing.T) { + cfg := testcfg.Build(t, testcfg.WithBase(config.Cfg{ + Auth: auth.Config{Token: "secret-token"}, + })) + + serverSocketPath := runServer(t, cfg) + conn, err := dial(ctx, serverSocketPath, client.WithGrpcOptions([]grpc.DialOption{ + grpc.WithPerRPCCredentials(gitalyauth.RPCCredentialsV2("wrong-token")), + })) + require.NoError(t, err) + t.Cleanup(func() { conn.Close() }) + + // Request should fail with permission denied + _, err = gitalypb.NewServerServiceClient(conn).ServerInfo(ctx, &gitalypb.ServerInfoRequest{}) + testhelper.RequireGrpcCode(t, err, codes.PermissionDenied) + }) +} + func TestAuthBeforeLimit(t *testing.T) { ctx := testhelper.Context(t) cfg := testcfg.Build(t, testcfg.WithBase(config.Cfg{ -- GitLab