package gatewayauthsessionuser_test import ( "bytes" "context" "crypto/ed25519" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "path/filepath" "testing" "time" gatewayv1 "galaxy/gateway/proto/galaxy/gateway/v1" contractsgatewayv1 "galaxy/integration/internal/contracts/gatewayv1" contractsuserv1 "galaxy/integration/internal/contracts/userv1" "galaxy/integration/internal/harness" usermodel "galaxy/model/user" "github.com/redis/go-redis/v9" "github.com/stretchr/testify/require" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) const gatewayAuthsessionUserTestTimeZone = "Europe/Kaliningrad" type gatewayAuthsessionUserHarness struct { redis *redis.Client mailStub *harness.MailStub authsessionPublicURL string userServiceURL string gatewayPublicURL string gatewayGRPCAddr string responseSignerPublicKey ed25519.PublicKey gatewayProcess *harness.Process authsessionProcess *harness.Process userServiceProcess *harness.Process } func newGatewayAuthsessionUserHarness(t *testing.T) *gatewayAuthsessionUserHarness { t.Helper() redisServer := harness.StartMiniredis(t) redisClient := redis.NewClient(&redis.Options{ Addr: redisServer.Addr(), Protocol: 2, DisableIdentity: true, }) t.Cleanup(func() { require.NoError(t, redisClient.Close()) }) mailStub := harness.NewMailStub(t) responseSignerPath, responseSignerPublicKey := harness.WriteResponseSignerPEM(t, t.Name()) userServiceAddr := harness.FreeTCPAddress(t) authsessionPublicAddr := harness.FreeTCPAddress(t) authsessionInternalAddr := harness.FreeTCPAddress(t) gatewayPublicAddr := harness.FreeTCPAddress(t) gatewayGRPCAddr := harness.FreeTCPAddress(t) userServiceBinary := harness.BuildBinary(t, "userservice", "./user/cmd/userservice") authsessionBinary := harness.BuildBinary(t, "authsession", "./authsession/cmd/authsession") gatewayBinary := harness.BuildBinary(t, "gateway", "./gateway/cmd/gateway") userServiceEnv := harness.StartUserServicePersistence(t, redisServer.Addr()).Env userServiceEnv["USERSERVICE_LOG_LEVEL"] = "info" userServiceEnv["USERSERVICE_INTERNAL_HTTP_ADDR"] = userServiceAddr userServiceEnv["OTEL_TRACES_EXPORTER"] = "none" userServiceEnv["OTEL_METRICS_EXPORTER"] = "none" userServiceProcess := harness.StartProcess(t, "userservice", userServiceBinary, userServiceEnv) harness.WaitForHTTPStatus(t, userServiceProcess, "http://"+userServiceAddr+"/api/v1/internal/users/user-missing/exists", http.StatusOK) authsessionEnv := map[string]string{ "AUTHSESSION_LOG_LEVEL": "info", "AUTHSESSION_PUBLIC_HTTP_ADDR": authsessionPublicAddr, "AUTHSESSION_PUBLIC_HTTP_REQUEST_TIMEOUT": time.Second.String(), "AUTHSESSION_INTERNAL_HTTP_ADDR": authsessionInternalAddr, "AUTHSESSION_INTERNAL_HTTP_REQUEST_TIMEOUT": time.Second.String(), "AUTHSESSION_REDIS_MASTER_ADDR": redisServer.Addr(), "AUTHSESSION_REDIS_PASSWORD": "integration", "AUTHSESSION_USER_SERVICE_MODE": "rest", "AUTHSESSION_USER_SERVICE_BASE_URL": "http://" + userServiceAddr, "AUTHSESSION_USER_SERVICE_REQUEST_TIMEOUT": time.Second.String(), "AUTHSESSION_MAIL_SERVICE_MODE": "rest", "AUTHSESSION_MAIL_SERVICE_BASE_URL": mailStub.BaseURL(), "AUTHSESSION_MAIL_SERVICE_REQUEST_TIMEOUT": time.Second.String(), "AUTHSESSION_REDIS_GATEWAY_SESSION_CACHE_KEY_PREFIX": "gateway:session:", "AUTHSESSION_REDIS_GATEWAY_SESSION_EVENTS_STREAM": "gateway:session_events", "OTEL_TRACES_EXPORTER": "none", "OTEL_METRICS_EXPORTER": "none", } authsessionProcess := harness.StartProcess(t, "authsession", authsessionBinary, authsessionEnv) waitForAuthsessionPublicReady(t, authsessionProcess, "http://"+authsessionPublicAddr) gatewayEnv := map[string]string{ "GATEWAY_LOG_LEVEL": "info", "GATEWAY_PUBLIC_HTTP_ADDR": gatewayPublicAddr, "GATEWAY_AUTHENTICATED_GRPC_ADDR": gatewayGRPCAddr, "GATEWAY_AUTH_SERVICE_BASE_URL": "http://" + authsessionPublicAddr, "GATEWAY_USER_SERVICE_BASE_URL": "http://" + userServiceAddr, "GATEWAY_PUBLIC_AUTH_UPSTREAM_TIMEOUT": (500 * time.Millisecond).String(), "GATEWAY_REDIS_MASTER_ADDR": redisServer.Addr(), "GATEWAY_REDIS_PASSWORD": "integration", "GATEWAY_SESSION_CACHE_REDIS_KEY_PREFIX": "gateway:session:", "GATEWAY_SESSION_EVENTS_REDIS_STREAM": "gateway:session_events", "GATEWAY_CLIENT_EVENTS_REDIS_STREAM": "gateway:client_events", "GATEWAY_REPLAY_REDIS_KEY_PREFIX": "gateway:replay:", "GATEWAY_RESPONSE_SIGNER_PRIVATE_KEY_PEM_PATH": filepath.Clean(responseSignerPath), "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_PUBLIC_AUTH_RATE_LIMIT_REQUESTS": "100", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_PUBLIC_AUTH_RATE_LIMIT_WINDOW": "1s", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_PUBLIC_AUTH_RATE_LIMIT_BURST": "100", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_SEND_EMAIL_CODE_IDENTITY_RATE_LIMIT_REQUESTS": "100", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_SEND_EMAIL_CODE_IDENTITY_RATE_LIMIT_WINDOW": "1s", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_SEND_EMAIL_CODE_IDENTITY_RATE_LIMIT_BURST": "100", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_CONFIRM_EMAIL_CODE_IDENTITY_RATE_LIMIT_REQUESTS": "100", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_CONFIRM_EMAIL_CODE_IDENTITY_RATE_LIMIT_WINDOW": "1s", "GATEWAY_PUBLIC_HTTP_ANTI_ABUSE_CONFIRM_EMAIL_CODE_IDENTITY_RATE_LIMIT_BURST": "100", "OTEL_TRACES_EXPORTER": "none", "OTEL_METRICS_EXPORTER": "none", } gatewayProcess := harness.StartProcess(t, "gateway", gatewayBinary, gatewayEnv) harness.WaitForHTTPStatus(t, gatewayProcess, "http://"+gatewayPublicAddr+"/healthz", http.StatusOK) harness.WaitForTCP(t, gatewayProcess, gatewayGRPCAddr) return &gatewayAuthsessionUserHarness{ redis: redisClient, mailStub: mailStub, authsessionPublicURL: "http://" + authsessionPublicAddr, userServiceURL: "http://" + userServiceAddr, gatewayPublicURL: "http://" + gatewayPublicAddr, gatewayGRPCAddr: gatewayGRPCAddr, responseSignerPublicKey: responseSignerPublicKey, gatewayProcess: gatewayProcess, authsessionProcess: authsessionProcess, userServiceProcess: userServiceProcess, } } func (h *gatewayAuthsessionUserHarness) sendChallenge(t *testing.T, email string) string { t.Helper() return h.sendChallengeWithAcceptLanguage(t, email, "") } func (h *gatewayAuthsessionUserHarness) sendChallengeWithAcceptLanguage(t *testing.T, email string, acceptLanguage string) string { t.Helper() response := postJSONValueWithHeaders( t, h.gatewayPublicURL+"/api/v1/public/auth/send-email-code", map[string]string{"email": email}, map[string]string{"Accept-Language": acceptLanguage}, ) require.Equal(t, http.StatusOK, response.StatusCode) var body struct { ChallengeID string `json:"challenge_id"` } require.NoError(t, decodeStrictJSONPayload([]byte(response.Body), &body)) return body.ChallengeID } func (h *gatewayAuthsessionUserHarness) confirmCode(t *testing.T, challengeID string, code string, clientPrivateKey ed25519.PrivateKey) httpResponse { t.Helper() return postJSONValue(t, h.gatewayPublicURL+"/api/v1/public/auth/confirm-email-code", map[string]string{ "challenge_id": challengeID, "code": code, "client_public_key": base64.StdEncoding.EncodeToString(clientPrivateKey.Public().(ed25519.PublicKey)), "time_zone": gatewayAuthsessionUserTestTimeZone, }) } func (h *gatewayAuthsessionUserHarness) ensureUser(t *testing.T, email string, preferredLanguage string, timeZone string) ensureByEmailResponse { t.Helper() response := postJSONValue(t, h.userServiceURL+"/api/v1/internal/users/ensure-by-email", map[string]any{ "email": email, "registration_context": map[string]string{ "preferred_language": preferredLanguage, "time_zone": timeZone, }, }) var body ensureByEmailResponse requireJSONStatus(t, response, http.StatusOK, &body) return body } func (h *gatewayAuthsessionUserHarness) lookupUserByEmail(t *testing.T, email string) (httpResponse, userLookupResponse) { t.Helper() response := postJSONValue(t, h.userServiceURL+"/api/v1/internal/user-lookups/by-email", map[string]string{ "email": email, }) if response.StatusCode != http.StatusOK { return response, userLookupResponse{} } var body userLookupResponse require.NoError(t, decodeStrictJSONPayload([]byte(response.Body), &body)) return response, body } func (h *gatewayAuthsessionUserHarness) blockByEmail(t *testing.T, email string) { t.Helper() response := postJSONValue(t, h.userServiceURL+"/api/v1/internal/user-blocks/by-email", map[string]string{ "email": email, "reason_code": "policy_blocked", }) require.Equal(t, http.StatusOK, response.StatusCode, "response body: %s", response.Body) } func (h *gatewayAuthsessionUserHarness) waitForGatewaySession(t *testing.T, deviceSessionID string) gatewaySessionRecord { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { payload, err := h.redis.Get(context.Background(), "gateway:session:"+deviceSessionID).Bytes() if err == nil { var record gatewaySessionRecord require.NoError(t, decodeStrictJSONPayload(payload, &record)) return record } time.Sleep(25 * time.Millisecond) } t.Fatalf("gateway session projection for %s was not published in time", deviceSessionID) return gatewaySessionRecord{} } func (h *gatewayAuthsessionUserHarness) executeGetMyAccount(t *testing.T, deviceSessionID string, requestID string, clientPrivateKey ed25519.PrivateKey) *usermodel.AccountResponse { t.Helper() conn := h.dialGateway(t) client := gatewayv1.NewEdgeGatewayClient(conn) payload, err := contractsuserv1.EncodeGetMyAccountRequest() require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() response, err := client.ExecuteCommand(ctx, newExecuteCommandRequest(deviceSessionID, requestID, contractsuserv1.MessageTypeGetMyAccount, payload, clientPrivateKey)) require.NoError(t, err) require.Equal(t, contractsuserv1.ResultCodeOK, response.GetResultCode()) assertSignedExecuteCommandResponse(t, response, h.responseSignerPublicKey) accountResponse, err := contractsuserv1.DecodeAccountResponse(response.GetPayloadBytes()) require.NoError(t, err) return accountResponse } func (h *gatewayAuthsessionUserHarness) dialGateway(t *testing.T) *grpc.ClientConn { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() conn, err := grpc.DialContext( ctx, h.gatewayGRPCAddr, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), ) require.NoError(t, err) t.Cleanup(func() { require.NoError(t, conn.Close()) }) return conn } type httpResponse struct { StatusCode int Body string Header http.Header } type ensureByEmailResponse struct { Outcome string `json:"outcome"` UserID string `json:"user_id,omitempty"` } type gatewaySessionRecord struct { DeviceSessionID string `json:"device_session_id"` UserID string `json:"user_id"` ClientPublicKey string `json:"client_public_key"` Status string `json:"status"` RevokedAtMS *int64 `json:"revoked_at_ms,omitempty"` } type userLookupResponse struct { User usermodel.Account `json:"user"` } func postJSONValue(t *testing.T, targetURL string, body any) httpResponse { t.Helper() return postJSONValueWithHeaders(t, targetURL, body, nil) } func postJSONValueWithHeaders(t *testing.T, targetURL string, body any, headers map[string]string) httpResponse { t.Helper() payload, err := json.Marshal(body) require.NoError(t, err) request, err := http.NewRequest(http.MethodPost, targetURL, bytes.NewReader(payload)) require.NoError(t, err) request.Header.Set("Content-Type", "application/json") for key, value := range headers { if value == "" { continue } request.Header.Set(key, value) } client := &http.Client{Timeout: 5 * time.Second} response, err := client.Do(request) require.NoError(t, err) defer response.Body.Close() responseBody, err := io.ReadAll(response.Body) require.NoError(t, err) return httpResponse{ StatusCode: response.StatusCode, Body: string(responseBody), Header: response.Header.Clone(), } } func decodeStrictJSONPayload(payload []byte, target any) error { decoder := json.NewDecoder(bytes.NewReader(payload)) decoder.DisallowUnknownFields() if err := decoder.Decode(target); err != nil { return err } if err := decoder.Decode(&struct{}{}); err != io.EOF { if err == nil { return fmt.Errorf("unexpected trailing JSON input") } return err } return nil } func requireJSONStatus(t *testing.T, response httpResponse, wantStatus int, target any) { t.Helper() require.Equal(t, wantStatus, response.StatusCode, "response body: %s", response.Body) require.NoError(t, decodeStrictJSONPayload([]byte(response.Body), target)) } func requireLookupNotFound(t *testing.T, response httpResponse) { t.Helper() require.Equal(t, http.StatusNotFound, response.StatusCode, "response body: %s", response.Body) require.JSONEq(t, `{"error":{"code":"subject_not_found","message":"subject not found"}}`, response.Body) } func lastMailCodeFor(t *testing.T, stub *harness.MailStub, email string) string { t.Helper() deliveries := stub.RecordedDeliveries() for index := len(deliveries) - 1; index >= 0; index-- { if deliveries[index].Email == email { return deliveries[index].Code } } t.Fatalf("mail stub did not record delivery for %s", email) return "" } func waitForAuthsessionPublicReady(t *testing.T, process *harness.Process, baseURL string) { t.Helper() client := &http.Client{Timeout: 250 * time.Millisecond} deadline := time.Now().Add(10 * time.Second) for time.Now().Before(deadline) { response, err := postJSONValueMaybe(client, baseURL+"/api/v1/public/auth/send-email-code", map[string]string{ "email": "", }) if err == nil && response.StatusCode == http.StatusBadRequest { return } time.Sleep(25 * time.Millisecond) } t.Fatalf("wait for authsession public readiness: timeout\n%s", process.Logs()) } func postJSONValueMaybe(client *http.Client, targetURL string, body any) (httpResponse, error) { payload, err := json.Marshal(body) if err != nil { return httpResponse{}, err } request, err := http.NewRequest(http.MethodPost, targetURL, bytes.NewReader(payload)) if err != nil { return httpResponse{}, err } request.Header.Set("Content-Type", "application/json") response, err := client.Do(request) if err != nil { return httpResponse{}, err } defer response.Body.Close() responseBody, err := io.ReadAll(response.Body) if err != nil { return httpResponse{}, err } return httpResponse{ StatusCode: response.StatusCode, Body: string(responseBody), Header: response.Header.Clone(), }, nil } func newClientPrivateKey(label string) ed25519.PrivateKey { seed := sha256.Sum256([]byte("galaxy-integration-gateway-authsession-user-client-" + label)) return ed25519.NewKeyFromSeed(seed[:]) } func newExecuteCommandRequest(deviceSessionID string, requestID string, messageType string, payload []byte, clientPrivateKey ed25519.PrivateKey) *gatewayv1.ExecuteCommandRequest { payloadHash := contractsgatewayv1.ComputePayloadHash(payload) request := &gatewayv1.ExecuteCommandRequest{ ProtocolVersion: contractsgatewayv1.ProtocolVersionV1, DeviceSessionId: deviceSessionID, MessageType: messageType, TimestampMs: time.Now().UnixMilli(), RequestId: requestID, PayloadBytes: payload, PayloadHash: payloadHash, TraceId: "trace-" + requestID, } request.Signature = contractsgatewayv1.SignRequest(clientPrivateKey, contractsgatewayv1.RequestSigningFields{ ProtocolVersion: request.GetProtocolVersion(), DeviceSessionID: request.GetDeviceSessionId(), MessageType: request.GetMessageType(), TimestampMS: request.GetTimestampMs(), RequestID: request.GetRequestId(), PayloadHash: request.GetPayloadHash(), }) return request } func assertSignedExecuteCommandResponse(t *testing.T, response *gatewayv1.ExecuteCommandResponse, publicKey ed25519.PublicKey) { t.Helper() require.NoError(t, contractsgatewayv1.VerifyPayloadHash(response.GetPayloadBytes(), response.GetPayloadHash())) require.NoError(t, contractsgatewayv1.VerifyResponseSignature(publicKey, response.GetSignature(), contractsgatewayv1.ResponseSigningFields{ ProtocolVersion: response.GetProtocolVersion(), RequestID: response.GetRequestId(), TimestampMS: response.GetTimestampMs(), ResultCode: response.GetResultCode(), PayloadHash: response.GetPayloadHash(), })) }