From 04a0da4d173073ce5350794ce77ffd7fbf28bee2 Mon Sep 17 00:00:00 2001 From: iamxvbaba <28732408+iamxvbaba@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:12:27 +0800 Subject: [PATCH] feat(protocol): sync td v1.6.0 and Layer 232 Consume the published td v1.6.0 module (canonical Layer 232) without a local module replacement, and tidy the obsolete v1.5.0 checksums. payments.getStarGiftWithdrawalUrl now carries tmp_password, which this server does not issue: accounts without 2FA get PASSWORD_MISSING and any tmp_password gets TMP_PASSWORD_INVALID before slug, ownership, freshness or export checks. Layer 225-231 withdrawal requests are rejected at admission. inputReplyToMessage.quote_rich is rejected before any write. Tests follow the canonical Layer 232 constructor IDs. Source: telesrv baf61dbde05300e31fe5cdfa2f03f41c1a7b0a10 Co-Authored-By: Claude Opus 5.5 --- go.mod | 2 +- go.sum | 4 +- internal/app/account/service.go | 8 + internal/app/account/service_test.go | 12 ++ internal/domain/account.go | 1 + internal/rpc/bot_verification_flags_test.go | 4 +- internal/rpc/deps.go | 1 + internal/rpc/ephemeral.go | 3 +- internal/rpc/ephemeral_rpc_test.go | 15 ++ internal/rpc/errors.go | 3 + internal/rpc/layer231_test.go | 16 +- internal/rpc/layer232_test.go | 29 ++++ internal/rpc/messages_send.go | 5 + internal/rpc/messages_send_rpc_test.go | 17 ++ internal/rpc/payments_star_gift_lifecycle.go | 20 ++- .../payments_star_gift_withdrawal_rpc_test.go | 161 ++++++++++++++---- internal/rpc/telegram_login_rpc_test.go | 4 +- 17 files changed, 245 insertions(+), 60 deletions(-) create mode 100644 internal/rpc/layer232_test.go diff --git a/go.mod b/go.mod index d602adb6..85e4dcdb 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/golang-migrate/migrate/v4 v4.19.1 github.com/gotd/ige v0.3.0 github.com/gotd/log/logzap v0.1.1 - github.com/iamxvbaba/td v1.5.0 + github.com/iamxvbaba/td v1.6.0 github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa github.com/jackc/pgx/v5 v5.9.2 github.com/klauspost/compress v1.19.1 diff --git a/go.sum b/go.sum index 996c45d7..4db8a14c 100644 --- a/go.sum +++ b/go.sum @@ -218,8 +218,8 @@ github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXei github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= -github.com/iamxvbaba/td v1.5.0 h1:6HdUBfmXZ+27VEMYFcGTy2o4S1EnoVewwEg3MF17gHw= -github.com/iamxvbaba/td v1.5.0/go.mod h1:INkZJi18XbXtVOrldDnPtmQCJvIXhgDZdbo9MV/NY7M= +github.com/iamxvbaba/td v1.6.0 h1:w+dCLqHiyQhUXSPeDtGRQXgkbFUwfhQQj3342s0cd6o= +github.com/iamxvbaba/td v1.6.0/go.mod h1:INkZJi18XbXtVOrldDnPtmQCJvIXhgDZdbo9MV/NY7M= github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw= github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= diff --git a/internal/app/account/service.go b/internal/app/account/service.go index 6304bac6..7e09f45e 100644 --- a/internal/app/account/service.go +++ b/internal/app/account/service.go @@ -305,6 +305,14 @@ func (s *Service) CheckPassword(ctx context.Context, userID int64, check domain. return checkSRP(settings, check) } +// CheckTmpPassword validates a Layer 232 tmp_password proof. This server does +// not implement account.getTmpPassword, so it has never issued a temporary +// password: no value can match, and an empty value is the absence of a proof. +// It fails closed until issuance exists and never falls back to an SRP check. +func (s *Service) CheckTmpPassword(context.Context, int64, []byte) error { + return domain.ErrTmpPasswordInvalid +} + // GetPasswordWithoutRefresh returns persisted settings without rotating the SRP challenge. func (s *Service) GetPasswordWithoutRefresh(ctx context.Context, userID int64) (domain.PasswordSettings, error) { if s == nil || s.passwords == nil || userID == 0 { diff --git a/internal/app/account/service_test.go b/internal/app/account/service_test.go index 1689cf9e..ca8def9e 100644 --- a/internal/app/account/service_test.go +++ b/internal/app/account/service_test.go @@ -361,3 +361,15 @@ func verifierForPassword(algo domain.PasswordKDFAlgo, password []byte) []byte { x := new(big.Int).SetBytes(passwordDigest(algo, password)) return padToHash(new(big.Int).Exp(g, x, p).Bytes()) } + +func TestCheckTmpPasswordFailsClosedWithoutIssuer(t *testing.T) { + ctx := context.Background() + svc := NewService(memory.NewPasswordStore()) + // No account.getTmpPassword issuer exists, so no value is a proof: not the + // empty value, and not bytes that happen to look like a token. + for _, tmp := range [][]byte{nil, {}, bytes.Repeat([]byte{9}, 32)} { + if err := svc.CheckTmpPassword(ctx, 1001, tmp); !errors.Is(err, domain.ErrTmpPasswordInvalid) { + t.Fatalf("CheckTmpPassword(%x) = %v, want ErrTmpPasswordInvalid", tmp, err) + } + } +} diff --git a/internal/domain/account.go b/internal/domain/account.go index c5ef34c5..66dd162f 100644 --- a/internal/domain/account.go +++ b/internal/domain/account.go @@ -44,6 +44,7 @@ var ( ErrPasswordHashInvalid = errors.New("password hash invalid") ErrSRPIDInvalid = errors.New("srp id invalid") ErrSRPPasswordChanged = errors.New("srp password changed") + ErrTmpPasswordInvalid = errors.New("tmp password invalid") ErrNewSettingsInvalid = errors.New("new password settings invalid") ErrNewSaltInvalid = errors.New("new password salt invalid") ErrPasswordRecoveryNA = errors.New("password recovery not available") diff --git a/internal/rpc/bot_verification_flags_test.go b/internal/rpc/bot_verification_flags_test.go index 98ea8401..db066ada 100644 --- a/internal/rpc/bot_verification_flags_test.go +++ b/internal/rpc/bot_verification_flags_test.go @@ -122,10 +122,10 @@ func TestBotVerificationConstructorIDs(t *testing.T) { t.Fatalf("botVerifierSettings constructor id = %#x, want 0xa12aefff", tg.BotVerifierSettingsTypeID) } // The carriers, so a layer bump that reshuffles them is caught here too. - if tg.UserTypeID != 0xb1b8cc83 || tg.ChannelTypeID != 0xd49f34c6 { + if tg.UserTypeID != 0xb1b8cc83 || tg.ChannelTypeID != 0x7ad15240 { t.Fatalf("peer constructor ids = user %#x / channel %#x", tg.UserTypeID, tg.ChannelTypeID) } - if tg.UserFullTypeID != 0x6cbe645 || tg.ChannelFullTypeID != 0xa04e8d3a { + if tg.UserFullTypeID != 0xb90c2afd || tg.ChannelFullTypeID != 0xc4c4dd40 { t.Fatalf("full constructor ids = userFull %#x / channelFull %#x", tg.UserFullTypeID, tg.ChannelFullTypeID) } if tg.ChatInviteTypeID != 0x5c9d3702 || tg.BotInfoTypeID != 0x4d8a0299 { diff --git a/internal/rpc/deps.go b/internal/rpc/deps.go index 3d0be29f..cdf80550 100644 --- a/internal/rpc/deps.go +++ b/internal/rpc/deps.go @@ -460,6 +460,7 @@ type AccountService interface { GetPasswordSettings(ctx context.Context, userID int64, check domain.PasswordCheck) (domain.PrivatePasswordSettings, error) UpdatePasswordSettings(ctx context.Context, userID int64, check domain.PasswordCheck, input domain.PasswordInputSettings) error CheckPassword(ctx context.Context, userID int64, check domain.PasswordCheck) error + CheckTmpPassword(ctx context.Context, userID int64, tmpPassword []byte) error RevenueWithdrawalPasswordState(ctx context.Context, userID int64) (domain.RevenueWithdrawalPasswordState, error) RequestPasswordRecovery(ctx context.Context, userID int64) (string, error) CheckRecoveryPassword(ctx context.Context, userID int64, code string) error diff --git a/internal/rpc/ephemeral.go b/internal/rpc/ephemeral.go index c85e8a38..a55d12e0 100644 --- a/internal/rpc/ephemeral.go +++ b/internal/rpc/ephemeral.go @@ -341,8 +341,9 @@ func ephemeralReplyFromInput(reply tg.InputReplyToClass) (topMessageID, ephemera if topMessageID <= 0 || topMessageID > domain.MaxMessageBoxID { return 0, 0, messageIDInvalidErr() } + _, hasQuoteRich := value.GetQuoteRich() if value.ReplyToPeerID != nil || value.QuoteText != "" || len(value.QuoteEntities) != 0 || value.QuoteOffset != 0 || - value.MonoforumPeerID != nil || value.TodoItemID != 0 || len(value.PollOption) != 0 { + value.MonoforumPeerID != nil || value.TodoItemID != 0 || len(value.PollOption) != 0 || hasQuoteRich { return 0, 0, inputConstructorInvalidErr() } return topMessageID, 0, nil diff --git a/internal/rpc/ephemeral_rpc_test.go b/internal/rpc/ephemeral_rpc_test.go index 480bcfc2..53798ebf 100644 --- a/internal/rpc/ephemeral_rpc_test.go +++ b/internal/rpc/ephemeral_rpc_test.go @@ -99,3 +99,18 @@ func TestEphemeralReportPersistsOnlyFinalIdempotentEvidence(t *testing.T) { t.Fatalf("ReportTarget calls=%d", ephemeral.calls) } } + +func TestEphemeralReplyFromInputRejectsQuotes(t *testing.T) { + if top, id, err := ephemeralReplyFromInput(&tg.InputReplyToMessage{ReplyToMsgID: 7}); err != nil || top != 7 || id != 0 { + t.Fatalf("topic reply = (%d, %d, %v), want (7, 0, nil)", top, id, err) + } + flat := &tg.InputReplyToMessage{ReplyToMsgID: 7} + flat.SetQuoteText("quoted") + rich := &tg.InputReplyToMessage{ReplyToMsgID: 7} + rich.SetQuoteRich([]tg.RichTextClass{&tg.TextPlain{Text: "quoted"}}) + for name, input := range map[string]*tg.InputReplyToMessage{"quote_text": flat, "quote_rich": rich} { + if _, _, err := ephemeralReplyFromInput(input); err == nil || !strings.Contains(err.Error(), "INPUT_CONSTRUCTOR_INVALID") { + t.Fatalf("%s err = %v, want INPUT_CONSTRUCTOR_INVALID", name, err) + } + } +} diff --git a/internal/rpc/errors.go b/internal/rpc/errors.go index 15df3c80..1f9c21eb 100644 --- a/internal/rpc/errors.go +++ b/internal/rpc/errors.go @@ -294,6 +294,7 @@ func sessionPasswordNeededErr() error { return tgerr.New(401, "SESSION_PASSWORD_ func passwordHashInvalidErr() error { return tgerr.New(400, "PASSWORD_HASH_INVALID") } func srpIDInvalidErr() error { return tgerr.New(400, "SRP_ID_INVALID") } func srpPasswordChangedErr() error { return tgerr.New(400, "SRP_PASSWORD_CHANGED") } +func tmpPasswordInvalidErr() error { return tgerr.New(400, "TMP_PASSWORD_INVALID") } func newSettingsInvalidErr() error { return tgerr.New(400, "NEW_SETTINGS_INVALID") } func newSaltInvalidErr() error { return tgerr.New(400, "NEW_SALT_INVALID") } func emailInvalidErr() error { return tgerr.New(400, "EMAIL_INVALID") } @@ -480,6 +481,8 @@ func passwordErr(err error) error { return srpIDInvalidErr() case errors.Is(err, domain.ErrSRPPasswordChanged): return srpPasswordChangedErr() + case errors.Is(err, domain.ErrTmpPasswordInvalid): + return tmpPasswordInvalidErr() case errors.Is(err, domain.ErrNewSettingsInvalid): return newSettingsInvalidErr() case errors.Is(err, domain.ErrNewSaltInvalid): diff --git a/internal/rpc/layer231_test.go b/internal/rpc/layer231_test.go index 2fcc20cc..80605432 100644 --- a/internal/rpc/layer231_test.go +++ b/internal/rpc/layer231_test.go @@ -13,10 +13,9 @@ import ( "go.uber.org/zap/zaptest" ) -// Layer 231 is the canonical profile of the published schema. The server must -// admit it, keep it as the session default and never clamp it to an older -// profile. -func TestLayer231IsSupportedCanonicalProfile(t *testing.T) { +// Layer 231 stays an exact historical profile after canonical moved to 232: +// it resolves to itself and is never clamped to another profile. +func TestLayer231StaysSupportedExactProfile(t *testing.T) { profile, ok := tlprofile.ResolveProfile(231) if !ok || profile != tlprofile.Profile231 { t.Fatalf("ResolveProfile(231) = %d, %v, want Profile231", profile, ok) @@ -24,15 +23,6 @@ func TestLayer231IsSupportedCanonicalProfile(t *testing.T) { if !isSupportedLayer(231) { t.Fatal("isSupportedLayer(231) = false, want true") } - if isSupportedLayer(232) { - t.Fatal("isSupportedLayer(232) = true, want false for an ungenerated future layer") - } - if int(tlprofile.ProfileCanonical) != 231 { - t.Fatalf("canonical profile = %d, want 231", tlprofile.ProfileCanonical) - } - if currentClientLayer != 231 { - t.Fatalf("currentClientLayer = %d, want 231", currentClientLayer) - } } // Layer 231 changed the urlAuthResultRequest and messages.acceptUrlAuth diff --git a/internal/rpc/layer232_test.go b/internal/rpc/layer232_test.go new file mode 100644 index 00000000..7c4d9495 --- /dev/null +++ b/internal/rpc/layer232_test.go @@ -0,0 +1,29 @@ +package rpc + +import ( + "testing" + + "github.com/iamxvbaba/td/tlprofile" +) + +// Layer 232 is the canonical profile of the published schema. The server must +// admit it, keep it as the session default and never clamp it to an older +// profile. +func TestLayer232IsSupportedCanonicalProfile(t *testing.T) { + profile, ok := tlprofile.ResolveProfile(232) + if !ok || profile != tlprofile.Profile232 { + t.Fatalf("ResolveProfile(232) = %d, %v, want Profile232", profile, ok) + } + if !isSupportedLayer(232) { + t.Fatal("isSupportedLayer(232) = false, want true") + } + if isSupportedLayer(233) { + t.Fatal("isSupportedLayer(233) = true, want false for an ungenerated future layer") + } + if int(tlprofile.ProfileCanonical) != 232 { + t.Fatalf("canonical profile = %d, want 232", tlprofile.ProfileCanonical) + } + if currentClientLayer != 232 { + t.Fatalf("currentClientLayer = %d, want 232", currentClientLayer) + } +} diff --git a/internal/rpc/messages_send.go b/internal/rpc/messages_send.go index 9d2693f9..8620e2ef 100644 --- a/internal/rpc/messages_send.go +++ b/internal/rpc/messages_send.go @@ -607,6 +607,11 @@ func (r *Router) messageReplyFromInput(ctx context.Context, userID int64, peer d if _, ok := reply.GetPollOption(); ok { return nil, pollOptionInvalidErr() } + // Layer 232 rich quote 尚未建模:只存 quote_text 会静默丢掉富文本,只带 quote_rich + // 时整段引用都会丢,所以在写入前拒绝。 + if _, ok := reply.GetQuoteRich(); ok { + return nil, quoteTextInvalidErr() + } replyPeer := peer if inputPeer, ok := reply.GetReplyToPeerID(); ok { parsed, err := r.checkedMessageReadPeer(ctx, userID, inputPeer, false) diff --git a/internal/rpc/messages_send_rpc_test.go b/internal/rpc/messages_send_rpc_test.go index f5271647..4c527afc 100644 --- a/internal/rpc/messages_send_rpc_test.go +++ b/internal/rpc/messages_send_rpc_test.go @@ -369,6 +369,23 @@ func TestMessageReplyFromInputUnsupportedShapesReturnExplicitErrors(t *testing.T }), want: "POLL_OPTION_INVALID", }, + { + name: "rich quote", + input: withReplyMsg(func(reply *tg.InputReplyToMessage) { + reply.SetQuoteRich([]tg.RichTextClass{&tg.TextPlain{Text: "quoted"}}) + }), + want: "QUOTE_TEXT_INVALID", + }, + { + // The flat fallback does not make the rich quote storable: keeping only + // quote_text would still drop formatting the client asked for. + name: "rich quote with flat fallback", + input: withReplyMsg(func(reply *tg.InputReplyToMessage) { + reply.SetQuoteText("quoted") + reply.SetQuoteRich([]tg.RichTextClass{&tg.TextPlain{Text: "quoted"}}) + }), + want: "QUOTE_TEXT_INVALID", + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/rpc/payments_star_gift_lifecycle.go b/internal/rpc/payments_star_gift_lifecycle.go index 671c3a6b..2c89a601 100644 --- a/internal/rpc/payments_star_gift_lifecycle.go +++ b/internal/rpc/payments_star_gift_lifecycle.go @@ -681,18 +681,20 @@ func (r *Router) onPaymentsGetStarGiftWithdrawalURL(ctx context.Context, req *tg if err != nil { return nil, internalErr() } - // checkSRP 只在“已设密码”时认 SRP,在“未设密码”时只认 inputCheckPasswordEmpty, - // 所以这里不单设 PASSWORD_MISSING,保持与 account 域的既有判定一致。 - if err := r.deps.Account.CheckPassword(ctx, userID, domainPasswordCheck(req.Password)); err != nil { + // Layer 232 的 2FA 证明是 account.getTmpPassword 签发的 tmp_password。空值只是 + // “没有证明”,不能再像 inputCheckPasswordEmpty 那样代表未设密码账号通过; + // 与 payments.getStarsRevenueWithdrawalUrl 一致,先要求账号已设 2FA。 + if !passwordState.HasPassword { + return nil, tgerr.New(400, "PASSWORD_MISSING") + } + if err := r.deps.Account.CheckTmpPassword(ctx, userID, req.TmpPassword); err != nil { return nil, passwordErr(err) } now := r.clock.Now() - if passwordState.HasPassword { - if wait := revenueWithdrawalFreshWait(passwordState.PasswordChangedAt, now); wait < 0 { - return nil, internalErr() - } else if wait > 0 { - return nil, tgerr.New(400, fmt.Sprintf("PASSWORD_TOO_FRESH_%d", wait)) - } + if wait := revenueWithdrawalFreshWait(passwordState.PasswordChangedAt, now); wait < 0 { + return nil, internalErr() + } else if wait > 0 { + return nil, tgerr.New(400, fmt.Sprintf("PASSWORD_TOO_FRESH_%d", wait)) } authKeyID, ok := AuthKeyIDFrom(ctx) if !ok || authKeyID == ([8]byte{}) { diff --git a/internal/rpc/payments_star_gift_withdrawal_rpc_test.go b/internal/rpc/payments_star_gift_withdrawal_rpc_test.go index 1117e489..d7c9a8f3 100644 --- a/internal/rpc/payments_star_gift_withdrawal_rpc_test.go +++ b/internal/rpc/payments_star_gift_withdrawal_rpc_test.go @@ -1,14 +1,21 @@ package rpc import ( + "bytes" "context" + "encoding/binary" + "errors" "testing" "time" + "github.com/iamxvbaba/td/bin" "github.com/iamxvbaba/td/tg" "github.com/iamxvbaba/td/tgerr" + "github.com/iamxvbaba/td/tlprofile" + appaccount "telesrv/internal/app/account" "telesrv/internal/domain" + "telesrv/internal/store/memory" ) type withdrawalRPCGifts struct { @@ -38,15 +45,20 @@ func (s *withdrawalRPCGifts) Withdraw(_ context.Context, req domain.StarGiftWith return domain.StarGiftWithdrawal{URL: "https://links.example.test/gift-withdrawal/token"}, nil } +// withdrawalRPCAccount stands in for a future account.getTmpPassword issuer so +// the later admission steps stay covered. Production fails closed at +// CheckTmpPassword; TestStarGiftWithdrawalTmpPasswordFailsClosed pins that. type withdrawalRPCAccount struct { AccountService checks int + checked []byte checkErr error state domain.RevenueWithdrawalPasswordState } -func (s *withdrawalRPCAccount) CheckPassword(context.Context, int64, domain.PasswordCheck) error { +func (s *withdrawalRPCAccount) CheckTmpPassword(_ context.Context, _ int64, tmpPassword []byte) error { s.checks++ + s.checked = append([]byte(nil), tmpPassword...) return s.checkErr } @@ -95,16 +107,11 @@ func starGiftWithdrawalRouter(t *testing.T) ( return r, sender.ID, gifts, account, auth, authKeyID } -func withdrawalRequest( - slug string, - password tg.InputCheckPasswordSRPClass) *tg.PaymentsGetStarGiftWithdrawalURLRequest { - req := &tg.PaymentsGetStarGiftWithdrawalURLRequest{ - Stargift: &tg.InputSavedStarGiftSlug{Slug: slug}, +func withdrawalRequest(slug string, tmpPassword []byte) *tg.PaymentsGetStarGiftWithdrawalURLRequest { + return &tg.PaymentsGetStarGiftWithdrawalURLRequest{ + Stargift: &tg.InputSavedStarGiftSlug{Slug: slug}, + TmpPassword: tmpPassword, } - if password != nil { - req.Password = password - } - return req } func TestStarGiftWithdrawalNeedsMatchingOwnerAndKnownSlug(t *testing.T) { @@ -112,7 +119,7 @@ func TestStarGiftWithdrawalNeedsMatchingOwnerAndKnownSlug(t *testing.T) { ctx := WithAuthKeyID(WithUserID(context.Background(), userID), authKeyID) if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest( - "owned-by-someone-else", &tg.InputCheckPasswordSRP{SRPID: 1})); !tgerr.Is(err, "STARGIFT_OWNER_INVALID") { + "owned-by-someone-else", withdrawalTmpPassword(1))); !tgerr.Is(err, "STARGIFT_OWNER_INVALID") { t.Fatalf("foreign owner err = %v, want STARGIFT_OWNER_INVALID", err) } if gifts.calls != 0 { @@ -120,7 +127,7 @@ func TestStarGiftWithdrawalNeedsMatchingOwnerAndKnownSlug(t *testing.T) { } if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest( - "never-minted", &tg.InputCheckPasswordSRP{SRPID: 1})); !tgerr.Is(err, "STARGIFT_INVALID") { + "never-minted", withdrawalTmpPassword(1))); !tgerr.Is(err, "STARGIFT_INVALID") { t.Fatalf("unknown slug err = %v, want STARGIFT_INVALID", err) } if gifts.calls != 0 { @@ -128,7 +135,7 @@ func TestStarGiftWithdrawalNeedsMatchingOwnerAndKnownSlug(t *testing.T) { } got, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest( - "withdrawal-test-gift", &tg.InputCheckPasswordSRP{SRPID: 1, A: withdrawalSRPProof(9), M1: withdrawalSRPProof(9)})) + "withdrawal-test-gift", withdrawalTmpPassword(9))) if err != nil { t.Fatalf("owner withdrawal: %v", err) } @@ -143,30 +150,34 @@ func TestStarGiftWithdrawalRejectsUnproven2FAAndFreshSessions(t *testing.T) { ctx := WithAuthKeyID(WithUserID(context.Background(), userID), authKeyID) slug := "withdrawal-test-gift" - account.checkErr = domain.ErrPasswordHashInvalid + account.checkErr = domain.ErrTmpPasswordInvalid if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest( - slug, &tg.InputCheckPasswordSRP{SRPID: 1, A: withdrawalSRPProof(9), M1: withdrawalSRPProof(9)})); !tgerr.Is(err, "PASSWORD_HASH_INVALID") { - t.Fatalf("wrong password err = %v, want PASSWORD_HASH_INVALID", err) + slug, withdrawalTmpPassword(9))); !tgerr.Is(err, "TMP_PASSWORD_INVALID") { + t.Fatalf("wrong tmp password err = %v, want TMP_PASSWORD_INVALID", err) } - if gifts.calls != 0 { - t.Fatalf("wrong password still withdrew: calls=%d", gifts.calls) + if gifts.calls != 0 || !bytes.Equal(account.checked, withdrawalTmpPassword(9)) { + t.Fatalf("wrong tmp password: calls=%d checked=%x", gifts.calls, account.checked) } account.checkErr = nil + // An empty tmp_password is no proof: a passwordless account no longer + // passes the way inputCheckPasswordEmpty used to, with or without bytes. + account.state = domain.RevenueWithdrawalPasswordState{} account.checks = 0 - if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest( - slug, &tg.InputCheckPasswordEmpty{})); err != nil { - t.Fatalf("empty check on passwordless account: %v", err) + for _, tmp := range [][]byte{nil, withdrawalTmpPassword(9)} { + if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, tmp)); !tgerr.Is(err, "PASSWORD_MISSING") { + t.Fatalf("passwordless tmp %x err = %v, want PASSWORD_MISSING", tmp, err) + } } - if account.checks != 1 { - t.Fatalf("empty check skipped CheckPassword: checks=%d", account.checks) + if account.checks != 0 || gifts.calls != 0 { + t.Fatalf("passwordless account reached tmp check or withdrew: checks=%d calls=%d", account.checks, gifts.calls) } account.state = domain.RevenueWithdrawalPasswordState{ HasPassword: true, PasswordChangedAt: time.Now().Add(-time.Hour), } _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest( - slug, &tg.InputCheckPasswordSRP{SRPID: 1, A: withdrawalSRPProof(9), M1: withdrawalSRPProof(9)})) + slug, withdrawalTmpPassword(9))) if !tgerr.Is(err, "PASSWORD_TOO_FRESH") { t.Fatalf("fresh password err = %v, want PASSWORD_TOO_FRESH", err) } @@ -180,7 +191,7 @@ func TestStarGiftWithdrawalRejectsUnproven2FAAndFreshSessions(t *testing.T) { } auth.authorization.CreatedAt = time.Now().Add(-time.Minute) _, err = r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest( - slug, &tg.InputCheckPasswordSRP{SRPID: 1, A: withdrawalSRPProof(9), M1: withdrawalSRPProof(9)})) + slug, withdrawalTmpPassword(9))) if !tgerr.Is(err, "SESSION_TOO_FRESH") { t.Fatalf("fresh session err = %v, want SESSION_TOO_FRESH", err) } @@ -194,10 +205,10 @@ func TestStarGiftWithdrawalRejectsBotsAndMapsCooldown(t *testing.T) { r, userID, gifts, _, _, authKeyID := starGiftWithdrawalRouter(t) ctx := WithAuthKeyID(WithUserID(context.Background(), userID), authKeyID) slug := "withdrawal-test-gift" - srp := &tg.InputCheckPasswordSRP{SRPID: 1, A: withdrawalSRPProof(9), M1: withdrawalSRPProof(9)} + tmp := withdrawalTmpPassword(9) r.botStatus.Store(userID, true) - if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, srp)); !tgerr.Is(err, "BOT_METHOD_INVALID") { + if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, tmp)); !tgerr.Is(err, "BOT_METHOD_INVALID") { t.Fatalf("bot err = %v, want BOT_METHOD_INVALID", err) } if gifts.calls != 0 { @@ -206,17 +217,107 @@ func TestStarGiftWithdrawalRejectsBotsAndMapsCooldown(t *testing.T) { r.botStatus.Delete(userID) gifts.err = domain.ErrStarGiftExportCooldown - if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, srp)); !tgerr.Is(err, "STARGIFT_WITHDRAWAL_UNAVAILABLE") { + if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, tmp)); !tgerr.Is(err, "STARGIFT_WITHDRAWAL_UNAVAILABLE") { t.Fatalf("cooldown err = %v, want STARGIFT_WITHDRAWAL_UNAVAILABLE", err) } gifts.err = nil gifts.err = domain.ErrStarGiftTransferUnavailable - if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, srp)); !tgerr.Is(err, "STARGIFT_INVALID") { + if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, tmp)); !tgerr.Is(err, "STARGIFT_INVALID") { t.Fatalf("closed export err = %v, want STARGIFT_INVALID", err) } } +// withdrawalRPCPasswordState keeps the production account service and fakes +// only the durable 2FA facts, so CheckTmpPassword is the real gate. +type withdrawalRPCPasswordState struct { + AccountService + state domain.RevenueWithdrawalPasswordState +} + +func (s *withdrawalRPCPasswordState) RevenueWithdrawalPasswordState(context.Context, int64) (domain.RevenueWithdrawalPasswordState, error) { + return s.state, nil +} + +func TestStarGiftWithdrawalTmpPasswordFailsClosed(t *testing.T) { + r, userID, gifts, _, _, authKeyID := starGiftWithdrawalRouter(t) + ctx := WithAuthKeyID(WithUserID(context.Background(), userID), authKeyID) + r.deps.Account = &withdrawalRPCPasswordState{ + AccountService: appaccount.NewService(memory.NewPasswordStore()), + state: domain.RevenueWithdrawalPasswordState{ + HasPassword: true, PasswordChangedAt: time.Now().Add(-48 * time.Hour), + }, + } + // telesrv issues no account.getTmpPassword value: neither an empty nor an + // arbitrary tmp_password may reach the slug, freshness or export checks. + for _, slug := range []string{"withdrawal-test-gift", "never-minted"} { + for _, tmp := range [][]byte{nil, {}, withdrawalTmpPassword(9)} { + if _, err := r.onPaymentsGetStarGiftWithdrawalURL(ctx, withdrawalRequest(slug, tmp)); !tgerr.Is(err, "TMP_PASSWORD_INVALID") { + t.Fatalf("%s tmp %x err = %v, want TMP_PASSWORD_INVALID", slug, tmp, err) + } + } + } + if gifts.calls != 0 { + t.Fatalf("unverifiable tmp_password withdrew: calls=%d", gifts.calls) + } +} + +func layer231WithdrawalWire(password bin.Encoder) []byte { + // payments.getStarGiftWithdrawalUrl#d06e93a8 stargift:InputSavedStarGift + // password:InputCheckPasswordSRP, as every 225-231 client still sends it. + var b bin.Buffer + b.PutID(0xd06e93a8) + if err := (&tg.InputSavedStarGiftSlug{Slug: "withdrawal-test-gift"}).Encode(&b); err != nil { + panic(err) + } + if err := password.Encode(&b); err != nil { + panic(err) + } + return b.Copy() +} + +func TestStarGiftWithdrawalExactLayerAdmission(t *testing.T) { + r, _, _, _, _, _ := starGiftWithdrawalRouter(t) + request := withdrawalRequest("withdrawal-test-gift", withdrawalTmpPassword(9)) + wire := encodeExactLayerRPC(t, tlprofile.Profile232, request) + if id := binary.LittleEndian.Uint32(wire.Buf); id != 0xc8ca817b { + t.Fatalf("Layer 232 withdrawal wire id = %#x", id) + } + decodeWire := bin.Buffer{Buf: append([]byte(nil), wire.Buf...)} + decoded, err := tlprofile.DecodeObject(tlprofile.Profile232, &decodeWire, tlprofile.Limits{}) + if got, ok := decoded.(*tg.PaymentsGetStarGiftWithdrawalURLRequest); err != nil || !ok || + !bytes.Equal(got.TmpPassword, request.TmpPassword) { + t.Fatalf("Layer 232 withdrawal decoded = %#v, %v", decoded, err) + } + admitted, err := r.AdmitLayer(tlprofile.Profile232, &wire, tlprofile.Limits{}) + if err != nil { + t.Fatalf("admit Layer 232 withdrawal: %v", err) + } + if _, method, _ := tlprofile.SemanticName(admitted.Call().Method()); method != "payments.getStarGiftWithdrawalUrl" || + !r.dispatcher.Has(admitted.Call().Method()) { + t.Fatalf("Layer 232 withdrawal admitted as %q, registered=%v", method, r.dispatcher.Has(admitted.Call().Method())) + } + + // td rejects the historical SRP constructor at admission instead of + // dropping the proof. It surfaces as ErrUnknownRPCMethod, which the edge + // logs as "Unhandled RPC admission (compatibility trace)" and answers + // NOT_IMPLEMENTED; no handler can see it as an empty tmp_password. + for profile := tlprofile.Profile225; profile <= tlprofile.Profile231; profile++ { + for _, password := range []bin.Encoder{ + &tg.InputCheckPasswordSRP{SRPID: 1, A: withdrawalTmpPassword(2), M1: withdrawalTmpPassword(3)}, + &tg.InputCheckPasswordEmpty{}, + } { + raw := layer231WithdrawalWire(password) + legacy := bin.Buffer{Buf: append([]byte(nil), raw...)} + if _, err := r.AdmitLayer(profile, &legacy, tlprofile.Limits{}); !errors.Is(err, tlprofile.ErrUnknownRPCMethod) || + !bytes.Equal(legacy.Raw(), raw) { + t.Fatalf("Layer %d %T withdrawal admission err = %v (input consumed=%v), want ErrUnknownRPCMethod", + profile, password, err, !bytes.Equal(legacy.Raw(), raw)) + } + } + } +} + func TestUniqueStarGiftValueInfoUsesSlugError(t *testing.T) { r, userID, gifts, _, _, authKeyID := starGiftWithdrawalRouter(t) ctx := WithAuthKeyID(WithUserID(context.Background(), userID), authKeyID) @@ -239,7 +340,7 @@ func TestUniqueStarGiftValueInfoUsesSlugError(t *testing.T) { } } -func withdrawalSRPProof(fill byte) []byte { +func withdrawalTmpPassword(fill byte) []byte { out := make([]byte, 32) for i := range out { out[i] = fill diff --git a/internal/rpc/telegram_login_rpc_test.go b/internal/rpc/telegram_login_rpc_test.go index 25b4c488..9517f970 100644 --- a/internal/rpc/telegram_login_rpc_test.go +++ b/internal/rpc/telegram_login_rpc_test.go @@ -108,7 +108,7 @@ func (f *telegramLoginRPCFixture) authorization(t *testing.T, match bool) telegr } func TestTelegramLoginRPCsAcrossExactLayerProfiles(t *testing.T) { - for profile := tlprofile.Profile225; profile <= tlprofile.Profile231; profile++ { + for profile := tlprofile.Profile225; profile <= tlprofile.Profile232; profile++ { t.Run(fmt.Sprintf("layer_%d", profile), func(t *testing.T) { f := newTelegramLoginRPCFixture(t) @@ -134,7 +134,7 @@ func TestTelegramLoginRPCsAcrossExactLayerProfiles(t *testing.T) { t.Fatalf("encode exact Layer %d login result: %v", profile, err) } wantID := uint32(0x3cd623ec) - if profile == tlprofile.Profile231 { + if profile >= tlprofile.Profile231 { wantID = 0xbdca6167 } if got, _ := resultWire.PeekID(); got != wantID {