← 全部文章ENGINEERING NOTES

同一个 TOTP 验证码能用几次:totp.Validate 的 90 秒窗口与防重放

本文目录
  1. 一个码在多长时间里有效
  2. 为什么不能指望库
  3. 两个步号可能算出同一个数字串
  4. 记账要原子,而且要和判断用同一份状态
  5. 落地时的几个取舍
  6. 完整示例
  7. 小结

给登录加两步验证(2FA),Go 里一种常见写法是用 github.com/pquerna/otp:注册时 totp.Generate 出一个密钥,让用户用验证器 App 扫码,确认绑定和登录时都用一行 totp.Validate(code, secret) 判断对错。

这一行本身没有算错,但它回答的问题是“这个码在当前时间附近是不是合法的”,而不是“这个码是不是第一次用”。只靠它,同一个 6 位验证码在有效期内可以不止一次通过校验,泄露出去的码在用户用完以后仍然有效。RFC 6238 对验证方的要求写得很直接(第 5.2 节):

The verifier MUST NOT accept the second attempt of the OTP

这篇只讲这一个点:一个码在多长时间里有效,为什么库帮不了你,以及怎么在服务端把“只能用一次”做对。要做对,需要两样东西:匹配时能识别出有歧义的数字串;记账时用一次原子的“比较并交换”,并且比较的正是做判断时读到的那份状态。文末是一个独立的 Go 包,配一组回归测试,验证这些都成立。

测试环境:

  • Go 1.27.4(当前最新版);github.com/pquerna/otp v1.5.0(2024-12-31 发布,当前最新);github.com/jackc/pgx/v5 v5.13.0(当前最新)。pgx 这个版本要求 Go 1.25,所以示例 go.mod 写 go 1.25.0,用 Go 1.25.0 也做过 go vet;
  • PostgreSQL 19.0(当前最新,2026-11-19 发布,源码编译),对照 PostgreSQL 16.15;
  • 4 核 Intel Xeon 2.30GHz,Linux。

一个码在多长时间里有效

先回顾 TOTP 怎么算。RFC 6238 第 4.2 节把时间切成固定长度的步:

T = (Current Unix time - T0) / X, where the default floor function is used in the computation.

默认 T0 = 0、X = 30 秒。验证码就是用共享密钥对步号 T 做 HMAC,再截成 6 位数字(截法来自 HOTP,RFC 4226)。手机和服务器各算各的,只要两边时钟差不多,算出来的就一样。

两边时钟不可能完全一致,用户看到码、输入、提交也要时间,所以服务端一般会多认几步。RFC 6238 第 5.2 节的建议是:

We RECOMMEND that at most one time step is allowed as the network delay.

totp.Validate 的默认配置正是这样:30 秒一步、6 位、SHA-1、Skew: 1。它内部调用 ValidateCustom,把当前步 c 以及 c+1、c−1 三个步号各算一遍,任何一个对上就返回 true。

反过来看一个属于第 c 步的码:服务端时钟处于第 c−1、c、c+1 步时它都能通过,一共 90 秒。验证器 App 只在第 c 步显示它,所以用户看到它以后,它还会再有效 30 到 60 秒,取决于用户是在这一步的开头还是结尾看到的。文末测试里的 TestWindowBounds 逐秒核对了这个范围:从第 c−1 步的第一秒到第 c+1 步的最后一秒,正好 90 秒。

这段时间里,服务端如果不记账,就没法区分第一次提交和后面的提交。

为什么不能指望库

“只能用一次”需要状态:服务端要记住每个用户上一次用掉的是什么。totp.Validate 是一个纯函数,只拿到码和密钥,记不了账,这一点无可厚非。

麻烦在于它连记账需要的信息都不给。Validate 返回 bool,ValidateCustom 返回 (bool, error),两者都不告诉你命中的是 c−1、c 还是 c+1 中的哪一步。而防重放要记的恰恰是步号:

  • 只记码本身不够。上次用掉的是第 c+1 步的码,第 c 步的码这时仍在窗口里,而且和记下的码不相等,单靠比较码挡不住它。
  • 记步号就清楚了:新码的步号必须严格大于上次接受的步号。同一个码步号相等,被拒;更早的码步号更小,也被拒。文末的 TestSameCodeOnlyOnce 和 TestOlderCodeRejectedAfterNewer 分别验证这两种情况。

所以要自己写一个循环:把窗口里的几个步号逐个算出验证码,用常数时间比较(库里 HOTP 的比较也是这样做的),并把命中的步号交出来。库提供了按步号算码的函数 hotp.GenerateCodeCustom,直接用它就行。

顺带一个小坑:如果自己调 totp.ValidateCustom 或 hotp.ValidateCustom,ValidateOpts 里的 Digits 不能留零值。totp.ValidateCustom 只给 Period 补默认值,而 HOTP 校验会先拿 Digits.Length()(零值时是 0)去比较输入长度,于是任何 6 位码都会返回 false 和一个长度错误。写测试时就踩到了这一下。

两个步号可能算出同一个数字串

只记步号还有一个漏洞:6 位码只有一百万种取值,不同步号算出同一个数字串是会发生的,相邻两步撞上的概率大约是百万分之一。

这时“比较并推进步号”保证的只是同一绑定下已经消费的步号不能再用,管不到数字串这一层:同一个数字串背后有两个步号,消费掉其中一个,另一个在步号上仍然是“新的”。

示例的 MatchStep 因此在匹配阶段加了两条拒绝规则:

  1. 窗口里命中不止一步,直接拒绝。数字串有歧义,就不去猜它“应该”是哪一步。命中数是在整个窗口上数的,不先排除已经用过的步号,所以无论记账状态如何,有歧义的输入都不会被接受。
  2. 数字串与上次接受的那一步的码相同,也拒绝。窗口往前移动以后,数字串较早的那次出现会滑出窗口,窗口内就看不出歧义了;这一条管的就是这种情形。只有第一条是不够的。

这两条的范围要说清楚:它们额外拒绝的是窗口内有歧义的输入,以及与最近一次成功结果同值的输入,并不是对历史上用过的所有 6 位字符串去重。很久以前接受过的某个数字串,后来在某一步又作为新码出现,仍会被正常接受,那本来就是一个合法的新码。

两条规则都依赖“上次接受的是哪一步”,所以它们只有在写入时这个前提仍然成立才有效,这是下一节要解决的问题。

测试里用一个可替换的算码函数,人为让两个步号算出同一个码:TestAmbiguousRejected 逐条核对窗口处在碰撞附近各个位置时的结果,TestCollisionAcceptedOnceAsWindowMoves 断言在这组受控碰撞里,这个数字串从进入窗口到离开窗口只被接受一次。它们覆盖的就是这一组受控碰撞,不能外推成对任意历史输入去重。

代价是:用户手上的码恰好有歧义时,要等下一个码。按上面的概率,这是百万分之一量级的事。

记账要原子,而且要和判断用同一份状态

有了步号,最自然的写法是“先查再写”:处理请求时读出用户行里的 totp_last_step,验证码对上且步号更大,就把新步号写回去。问题是读和写之间没有约束,判断和写入必须合成一步。

合成一步时还要注意比较的是什么。只要求“新步号大于库里当前的值”是不够的:上一节的第二条规则是拿读到的那个步号算出来的,如果读完以后别的请求已经成功消费、改了状态,这次判断的依据就过期了,而“新步号更大”这个条件仍可能成立,写入会带着过期的判断生效。换绑也是一样:读到的是旧密钥,写入时密钥已经换了。

所以示例把消费做成“比较并交换”:写入的前提是,库里的步号和密钥版本都仍然等于读到的值。

UPDATE totp_user
   SET totp_last_step = $4
 WHERE id = $1
   AND totp_key_version = $2
   AND totp_last_step IS NOT DISTINCT FROM $3
   AND (totp_last_step IS NULL OR totp_last_step < $4)

$2、$3 是做判断时读到的密钥版本和步号(从没用过时步号是 NULL,所以用 IS NOT DISTINCT FROM 比较)。影响行数是 1 才算消费成功。

为什么一条带条件的 UPDATE 就够了,不需要显式加锁,也不需要把隔离级别提到可串行化?因为在默认的读已提交级别下,UPDATE 碰到一行已经被别的事务改过、还没提交时,会先等那个事务结束。PostgreSQL 文档(19 版“Read Committed Isolation Level”一节)是这样说的:

the would-be updater will wait for the first updating transaction to commit or roll back

对方提交以后,它不会沿用自己先前看到的旧版本,而是在新版本上重新判断条件:

The search condition of the command (the WHERE clause) is re-evaluated

这时步号或密钥版本已经不等于读到的值,条件不成立,影响行数是 0。

写入失败说明状态在读和写之间变了。Verifier 的处理是按最新状态从头再判一次:重新读状态,密钥版本变了就拒绝(ErrKeyChanged),否则用新的步号重新跑 MatchStep。同一个码被别人抢先用掉,重判时自然得到 ErrReused。重判有次数上限,超过就返回错误,不会无限循环。

这样,“步号更新”“数字串不同于上次”“密钥没换”这几条判断,和写入在同一个前提下生效。存储的测试套件 runStoreSuite 覆盖了这几种并发情形,内存实现和 PostgreSQL 实现跑的是同一套用例:

  • SameCodeConcurrent:32 个请求带着同一个正确的码并发校验,用一个门让它们先全部读完旧状态,再一起去写,每一轮都确实走到“多个请求拿着同一份旧状态去写”。每轮恰好接受 1 次,其余重判后得到 ErrReused;
  • StaleJudgmentRejudged:一个请求读完状态、还没写入时,另一个请求用同一个数字串消费了碰撞中的另一步。前者的写入必须失败,重判后被拒;
  • RebindDuringVerify 和 StaleKeyVersion:读完状态后发生换绑,或者拿着旧版本的密钥来校验,都会被拒;
  • ConsumeComparesState:直接调用消费,状态对不上或步号不更新时都不写。

在 PostgreSQL 19.0 和 16.15 上各跑 3 遍都通过。作为对测试本身的检查,把 UPDATE 里对读到状态的比较去掉、只留“步号更大”时,StaleJudgmentRejudged、RebindDuringVerify 和 ConsumeComparesState 会失败;SameCodeConcurrent 仍然通过,因为它只涉及同一个步号。这也说明了分工:原子更新本身保证的是同一绑定下已消费的步号不能再用;窗口内的歧义和与最近一次结果同值的输入,要靠匹配规则拒绝;再由“比较读到的状态”保证这些判断和写入用的是同一份状态。

换成别的存储也是一样的道理。单进程可以用互斥锁(示例的 MemStore),多实例部署就必须放到共享存储里,用那个存储自己的原子比较并交换。只在进程内存里记账,换一台实例就失效了。

落地时的几个取舍

注册确认用掉的码也要记账。很多实现在用户扫码以后要求输入一个码确认,确认成功就启用 2FA。这一步如果只调 Validate,不写步号,那这个码随后在登录时还能再通过一次。启用 2FA 时把确认码的步号一起写进去。换密钥(重新绑定)时在同一次写入里换上新密钥、把密钥版本加一、把步号清空;校验时带上读到的密钥版本,消费只对当前版本生效。

失败不能前移。只有验证成功才写步号。码不对、码已用过、有歧义、被并发请求抢先,这几种情况都不应该改动记录,否则一个错误请求就能把合法用户手上的码作废。示例的 TestFailureDoesNotAdvance 和 ConsumeComparesState 测的就是这个。

同一个人在两台设备上同时登录会被拒一次。用户在电脑上用了这一步的码,30 秒内又在手机上输入同一个码,第二次会失败,要等下一个码。这是 RFC 要求的行为,界面上给一句“这个验证码刚用过,请等下一个”比笼统的“验证码错误”好理解。

防重放不防猜。6 位数字,Skew: 1 时窗口里有 3 个合法码,每次猜中的概率约 3/10⁶。RFC 4226 第 6 节给过 HOTP 的估算公式 Sec = sv/10^Digit(s 是窗口大小,v 是尝试次数),可见成功率随尝试次数线性增长,唯一的办法是限制尝试次数。RFC 4226 第 7.3 节要求设一个尝试上限,并且计数要跨登录会话:

T SHOULD be set as low as possible, while still ensuring that usability is not significantly impacted.

因为重放或歧义被拒的请求,也应该算进失败次数。

容忍窗口别开大。Skew 每加 1,窗口两头各多 30 秒,窗口里的合法码也多 2 个,歧义的机会也跟着变多。用户总说验证码失效,先查服务器的时钟同步,而不是把 Skew 调大。

一次性的备用码是同一个问题。备用码(恢复码)通常是一组只能用一次的随机串。如果把它们存成一个 JSON 数组,“读出数组、删掉命中的一项、写回”,同样是先查后写。每个备用码存一行,用 DELETE ... WHERE user_id = $1 AND code_hash = $2 看影响行数,就把消费变成了原子的。

完整示例

一个独立的 Go 包,不依赖任何私有代码,只包含防护本身和它的回归测试。文件结构:

totpguard/
├── go.mod
├── verify.go         # MatchStep、StepStore 接口、Verifier
├── memstore.go       # 单进程实现
├── pgstore.go        # PostgreSQL 实现
├── verify_test.go       # 窗口、一次性、碰撞、失败不前移
├── store_suite_test.go  # 两种存储共用的并发与换绑用例
└── pgstore_test.go      # 让 PostgreSQL 实现跑同一套用例

go.mod:

module example.com/totpguard

go 1.25.0

require (
	github.com/jackc/pgx/v5 v5.13.0
	github.com/pquerna/otp v1.5.0
)

require (
	github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
	github.com/jackc/pgpassfile v1.0.0 // indirect
	github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
	github.com/jackc/puddle/v2 v2.2.3 // indirect
	golang.org/x/sync v0.22.0 // indirect
	golang.org/x/text v0.41.0 // indirect
)

verify.go:

// Package totpguard 在 TOTP 校验之上加一层“一次性”约束:
// 每个用户只接受步号严格递增的验证码,拒绝在窗口内有歧义的数字串,
// 并且只有在读到的记账状态和密钥版本都没变的前提下才消费。
package totpguard

import (
	"context"
	"crypto/subtle"
	"errors"
	"strings"
	"time"

	"github.com/pquerna/otp"
	"github.com/pquerna/otp/hotp"
)

// CodeFunc 按步号算出验证码。留成可替换的,测试里才能构造“两个步号同一个码”的情况。
type CodeFunc func(secret string, step uint64, o Options) (string, error)

// Options 与常见验证器 App 的默认值保持一致:30 秒一步、6 位、SHA-1、前后各容忍 1 步。
type Options struct {
	Period    uint
	Skew      uint
	Digits    otp.Digits
	Algorithm otp.Algorithm
	Code      CodeFunc // nil 时用 HOTP(RFC 4226)
}

var DefaultOptions = Options{Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1}

func hotpCode(secret string, step uint64, o Options) (string, error) {
	return hotp.GenerateCodeCustom(secret, step, hotp.ValidateOpts{Digits: o.Digits, Algorithm: o.Algorithm})
}

// Step 是 RFC 6238 里的 T:floor((Unix 时间 - 0) / Period)。
func Step(t time.Time, period uint) int64 {
	sec, p := t.Unix(), int64(period)
	if sec < 0 && sec%p != 0 {
		return sec/p - 1
	}
	return sec / p
}

var (
	// ErrAmbiguous:这个数字串在当前窗口里对应不止一个步号。
	ErrAmbiguous = errors.New("totp: code matches more than one step in the window")
	// ErrReused:这个数字串和上次接受的验证码相同,或者它的步号不比上次新。
	ErrReused = errors.New("totp: code already used")
	// ErrMismatch:窗口里没有任何步号的验证码与之相符。
	ErrMismatch = errors.New("totp: code does not match")
	// ErrKeyChanged:调用方拿到的密钥已经不是当前绑定的那一把(换绑了)。
	ErrKeyChanged = errors.New("totp: key was rebound")
	// ErrContended:并发修改太频繁,重判几次仍没写成。
	ErrContended = errors.New("totp: too much concurrent change")
)

// MatchStep 找出 passcode 对应的步号,last 是该用户上次接受的步号(从未接受过传 -1)。
//
// 规则:
//  1. 把窗口 [当前步-Skew, 当前步+Skew] 里每一步的码都算出来,逐个用常数时间比较;
//  2. 命中不止一步,视为歧义,拒绝;
//  3. 命中的步号不大于 last,拒绝;
//  4. 数字串与 last 那一步的码相同,也拒绝:同一个数字串不连着被接受两次。
func MatchStep(passcode, secret string, now time.Time, last int64, o Options) (int64, error) {
	passcode = strings.TrimSpace(passcode)
	if len(passcode) != o.Digits.Length() {
		return 0, ErrMismatch
	}
	code := o.Code
	if code == nil {
		code = hotpCode
	}
	cur := Step(now, o.Period)
	matched, hits := int64(-1), 0
	for s := cur - int64(o.Skew); s <= cur+int64(o.Skew); s++ {
		if s < 0 {
			continue
		}
		c, err := code(secret, uint64(s), o)
		if err != nil {
			return 0, err
		}
		if subtle.ConstantTimeCompare([]byte(c), []byte(passcode)) == 1 {
			matched = s
			hits++
		}
	}
	switch {
	case hits == 0:
		return 0, ErrMismatch
	case hits > 1:
		return 0, ErrAmbiguous
	case matched <= last:
		return 0, ErrReused
	}
	if last >= 0 {
		prev, err := code(secret, uint64(last), o)
		if err != nil {
			return 0, err
		}
		if subtle.ConstantTimeCompare([]byte(prev), []byte(passcode)) == 1 {
			return 0, ErrReused
		}
	}
	return matched, nil
}

// State 是一个用户的记账状态。
type State struct {
	LastStep   int64 // 上次接受的步号,从未接受过为 -1
	KeyVersion int64 // 当前绑定的密钥版本,每次换绑加一
}

// Key 是调用方随用户记录一起读出的密钥和它的版本。
type Key struct {
	Secret  string
	Version int64
}

// StepStore 保存记账状态。
//
// Consume 必须是原子的“比较并交换”:只有当前状态仍然等于 seen(步号和密钥版本都相同),
// 并且 step 大于 seen.LastStep 时,才把步号写成 step 并返回 true。
// 这样 MatchStep 依据 seen 做出的所有判断,和写入在同一个前提下生效。
type StepStore interface {
	State(ctx context.Context, user string) (State, error)
	Consume(ctx context.Context, user string, seen State, step int64) (bool, error)
}

type Verifier struct {
	Store StepStore
	Opts  Options
	Now   func() time.Time
	// MaxAttempts 是状态被并发改掉时最多重判几次,0 表示 3。
	MaxAttempts int
}

// Verify 只在验证码正确、没有歧义、比上次接受的更新,并且密钥没有被换绑时返回 nil。
// 任何失败都不会改动记录。
func (v *Verifier) Verify(ctx context.Context, user string, key Key, passcode string) error {
	now := time.Now
	if v.Now != nil {
		now = v.Now
	}
	attempts := v.MaxAttempts
	if attempts <= 0 {
		attempts = 3
	}
	for i := 0; i < attempts; i++ {
		seen, err := v.Store.State(ctx, user)
		if err != nil {
			return err
		}
		if seen.KeyVersion != key.Version {
			return ErrKeyChanged
		}
		step, err := MatchStep(passcode, key.Secret, now(), seen.LastStep, v.Opts)
		if err != nil {
			return err
		}
		ok, err := v.Store.Consume(ctx, user, seen, step)
		if err != nil {
			return err
		}
		if ok {
			return nil
		}
		// 读到 seen 之后有人改了状态(别的请求消费了,或者换绑了)。
		// 刚才的判断已经过期,按最新状态从头再判一次。
	}
	return ErrContended
}

memstore.go:

package totpguard

import (
	"context"
	"sync"
)

// MemStore 是单进程内的实现;多实例部署要换成共享存储(见 PGStore)。
type MemStore struct {
	mu    sync.Mutex
	state map[string]State
}

func NewMemStore() *MemStore { return &MemStore{state: map[string]State{}} }

// Enroll 绑定第一把密钥,版本为 1。
func (m *MemStore) Enroll(user string) {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.state[user] = State{LastStep: -1, KeyVersion: 1}
}

// Rebind 换绑:版本加一,步号清空。真实系统里新密钥要在同一次写入里一起换上。
func (m *MemStore) Rebind(user string) int64 {
	m.mu.Lock()
	defer m.mu.Unlock()
	s := m.state[user]
	s.KeyVersion++
	s.LastStep = -1
	m.state[user] = s
	return s.KeyVersion
}

func (m *MemStore) State(_ context.Context, user string) (State, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if s, ok := m.state[user]; ok {
		return s, nil
	}
	return State{LastStep: -1}, nil
}

func (m *MemStore) Consume(_ context.Context, user string, seen State, step int64) (bool, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	cur, ok := m.state[user]
	if !ok || cur != seen || step <= cur.LastStep {
		return false, nil
	}
	cur.LastStep = step
	m.state[user] = cur
	return true, nil
}

pgstore.go:

package totpguard

import (
	"context"
	"errors"
	"fmt"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// PGStore 把记账状态存在用户表的两列里:
//
//	totp_last_step   bigint           -- NULL 表示还没用过任何验证码
//	totp_key_version bigint NOT NULL  -- 每次换绑加一
//
// 表还要有 id text 主键。真实系统里加密后的密钥也在这一行,换绑时一起更新。
type PGStore struct {
	Pool  *pgxpool.Pool
	Table string // 由调用方给出的可信表名,不来自用户输入
}

func (s PGStore) ident() string { return pgx.Identifier{s.Table}.Sanitize() }

func (s PGStore) State(ctx context.Context, user string) (State, error) {
	var last *int64
	var version int64
	q := fmt.Sprintf(`SELECT totp_last_step, totp_key_version FROM %s WHERE id = $1`, s.ident())
	err := s.Pool.QueryRow(ctx, q, user).Scan(&last, &version)
	if errors.Is(err, pgx.ErrNoRows) {
		return State{LastStep: -1}, nil
	}
	if err != nil {
		return State{}, err
	}
	st := State{LastStep: -1, KeyVersion: version}
	if last != nil {
		st.LastStep = *last
	}
	return st, nil
}

// Consume 是一条带条件的 UPDATE:步号和密钥版本都必须仍是读到的值。
func (s PGStore) Consume(ctx context.Context, user string, seen State, step int64) (bool, error) {
	var seenLast *int64
	if seen.LastStep >= 0 {
		seenLast = &seen.LastStep
	}
	q := fmt.Sprintf(`
UPDATE %s
   SET totp_last_step = $4
 WHERE id = $1
   AND totp_key_version = $2
   AND totp_last_step IS NOT DISTINCT FROM $3
   AND (totp_last_step IS NULL OR totp_last_step < $4)`, s.ident())
	tag, err := s.Pool.Exec(ctx, q, user, seen.KeyVersion, seenLast, step)
	if err != nil {
		return false, err
	}
	return tag.RowsAffected() == 1, nil
}

// Rebind 换绑:版本加一、步号清空,返回新版本。
func (s PGStore) Rebind(ctx context.Context, user string) (int64, error) {
	var v int64
	q := fmt.Sprintf(`
UPDATE %s
   SET totp_key_version = totp_key_version + 1,
       totp_last_step = NULL
 WHERE id = $1
RETURNING totp_key_version`, s.ident())
	err := s.Pool.QueryRow(ctx, q, user).Scan(&v)
	return v, err
}

verify_test.go:

package totpguard

import (
	"context"
	"errors"
	"fmt"
	"testing"
	"time"
)

// 演示用的固定密钥(Base32,20 字节),不要拿去用。
const testSecret = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"

var testKey = Key{Secret: testSecret, Version: 1}

func at(sec int64) time.Time { return time.Unix(sec, 0).UTC() }

func codeAtStep(t *testing.T, step int64) string {
	t.Helper()
	c, err := hotpCode(testSecret, uint64(step), DefaultOptions)
	if err != nil {
		t.Fatal(err)
	}
	return c
}

func verifierAt(store StepStore, o Options, now *time.Time) *Verifier {
	return &Verifier{Store: store, Opts: o, Now: func() time.Time { return *now }}
}

func newMem() *MemStore {
	m := NewMemStore()
	m.Enroll("u")
	return m
}

// collidingOptions 用假的算码函数让第 100、101 步算出同一个码 "111111",其余各步互不相同。
func collidingOptions() Options {
	o := DefaultOptions
	o.Code = func(_ string, step uint64, _ Options) (string, error) {
		if step == 100 || step == 101 {
			return "111111", nil
		}
		return fmt.Sprintf("%06d", 200000+step), nil
	}
	return o
}

// 窗口:第 c 步的码只在服务端处于第 c-1、c、c+1 步时被接受,共 90 秒。
func TestWindowBounds(t *testing.T) {
	ctx := context.Background()
	c := Step(at(1_800_000_000), 30)
	code := codeAtStep(t, c)
	first, last := int64(-1), int64(-1)
	for sec := (c - 3) * 30; sec < (c+4)*30; sec++ {
		now := at(sec)
		v := verifierAt(newMem(), DefaultOptions, &now) // 每次用新的记录,只看窗口
		if v.Verify(ctx, "u", testKey, code) == nil {
			if first < 0 {
				first = sec
			}
			last = sec
		}
	}
	if first != (c-1)*30 || last != (c+2)*30-1 {
		t.Fatalf("accepted from %d to %d, want %d to %d", first, last, (c-1)*30, (c+2)*30-1)
	}
}

// 成功一次以后,同一个码在剩下的有效期里都不再被接受。
func TestSameCodeOnlyOnce(t *testing.T) {
	ctx := context.Background()
	c := Step(at(1_800_000_000), 30)
	now := at(c*30 + 10)
	v := verifierAt(newMem(), DefaultOptions, &now)
	code := codeAtStep(t, c)
	if err := v.Verify(ctx, "u", testKey, code); err != nil {
		t.Fatalf("first use: %v", err)
	}
	for sec := now.Unix() + 1; sec < (c+2)*30; sec++ {
		now = at(sec)
		if err := v.Verify(ctx, "u", testKey, code); !errors.Is(err, ErrReused) {
			t.Fatalf("t=%d: got %v, want ErrReused", sec, err)
		}
	}
}

// 用过更新的码以后,更早、但还在窗口内的码也不再被接受。
func TestOlderCodeRejectedAfterNewer(t *testing.T) {
	ctx := context.Background()
	c := Step(at(1_800_000_000), 30)
	now := at((c+1)*30 + 5)
	v := verifierAt(newMem(), DefaultOptions, &now)
	if err := v.Verify(ctx, "u", testKey, codeAtStep(t, c+1)); err != nil {
		t.Fatalf("newer code: %v", err)
	}
	if err := v.Verify(ctx, "u", testKey, codeAtStep(t, c)); !errors.Is(err, ErrReused) {
		t.Fatalf("older code: got %v, want ErrReused", err)
	}
}

// 失败不前移记录。
func TestFailureDoesNotAdvance(t *testing.T) {
	ctx := context.Background()
	c := Step(at(1_800_000_000), 30)
	now := at(c*30 + 10)
	store := newMem()
	v := verifierAt(store, DefaultOptions, &now)
	code := codeAtStep(t, c)
	wrong := "000000"
	if wrong == code {
		wrong = "000001"
	}
	if err := v.Verify(ctx, "u", testKey, wrong); !errors.Is(err, ErrMismatch) {
		t.Fatalf("wrong code: got %v", err)
	}
	if st, _ := store.State(ctx, "u"); st.LastStep != -1 {
		t.Fatalf("last step moved to %d after a failure", st.LastStep)
	}
	if err := v.Verify(ctx, "u", testKey, code); err != nil {
		t.Fatalf("right code after a failure: %v", err)
	}
}

// 歧义:逐条核对窗口在碰撞附近的每个位置。
func TestAmbiguousRejected(t *testing.T) {
	o := collidingOptions()
	cases := []struct {
		nowStep, last int64
		want          error
		step          int64
	}{
		{99, -1, nil, 100},         // 窗口 98..100,只命中 100
		{100, -1, ErrAmbiguous, 0}, // 窗口 99..101,命中两步
		{101, -1, ErrAmbiguous, 0}, // 窗口 100..102,命中两步
		{102, -1, nil, 101},        // 窗口 101..103,只命中 101,此前没用过
		{102, 100, ErrReused, 0},   // 同上,但第 100 步刚用过,码同值
		{102, 101, ErrReused, 0},   // 步号不比上次新
	}
	for _, tc := range cases {
		step, err := MatchStep("111111", "unused", at(tc.nowStep*30+1), tc.last, o)
		if !errors.Is(err, tc.want) || (err == nil && step != tc.step) {
			t.Errorf("now=%d last=%d: got (%d, %v), want (%d, %v)", tc.nowStep, tc.last, step, err, tc.step, tc.want)
		}
	}
}

// 窗口移动:在这组受控碰撞里,同一个数字串从进入窗口到离开窗口只被接受一次。
func TestCollisionAcceptedOnceAsWindowMoves(t *testing.T) {
	ctx := context.Background()
	now := at(0)
	v := verifierAt(newMem(), collidingOptions(), &now)
	accepted := 0
	for sec := int64(99 * 30); sec < 103*30; sec++ {
		now = at(sec)
		if v.Verify(ctx, "u", Key{Secret: "unused", Version: 1}, "111111") == nil {
			accepted++
		}
	}
	if accepted != 1 {
		t.Fatalf("accepted %d times, want 1", accepted)
	}
}

// 内存实现跑一遍和 PostgreSQL 相同的并发与换绑用例(见 store_suite_test.go)。
func TestMemStoreSuite(t *testing.T) {
	runStoreSuite(t, func(t *testing.T) suiteStore {
		m := newMem()
		return suiteStore{
			StepStore: m,
			Reset:     func() { m.Enroll("u") },
			Rebind:    func() (int64, error) { return m.Rebind("u"), nil },
		}
	})
}

store_suite_test.go:

package totpguard

import (
	"context"
	"errors"
	"sync"
	"testing"
)

// suiteStore 是被测存储加上两个测试用的管理操作。
type suiteStore struct {
	StepStore
	Reset  func()                // 把用户 "u" 恢复成刚绑定:版本 1,没用过任何码
	Rebind func() (int64, error) // 换绑用户 "u",返回新版本
}

// gateStore 让最先到达的 n 次 State 调用都停在门口,等 n 个都读完再一起放行;
// 之后的调用(重判)直接通过。这样每一轮都确实走到“n 个请求拿着同一份旧状态去写”。
type gateStore struct {
	StepStore
	n     int
	mu    sync.Mutex
	count int
	open  chan struct{}
}

func newGate(s StepStore, n int) *gateStore {
	return &gateStore{StepStore: s, n: n, open: make(chan struct{})}
}

func (g *gateStore) State(ctx context.Context, user string) (State, error) {
	st, err := g.StepStore.State(ctx, user)
	g.mu.Lock()
	g.count++
	k := g.count
	if k == g.n {
		close(g.open)
	}
	g.mu.Unlock()
	if k <= g.n {
		<-g.open
	}
	return st, err
}

// hookStore 在第一次 Consume 之前执行一次 hook,用来在“读到状态”和“写入”之间插入别的修改。
type hookStore struct {
	StepStore
	once sync.Once
	hook func()
}

func (h *hookStore) Consume(ctx context.Context, user string, seen State, step int64) (bool, error) {
	h.once.Do(h.hook)
	return h.StepStore.Consume(ctx, user, seen, step)
}

func runStoreSuite(t *testing.T, open func(t *testing.T) suiteStore) {
	ctx := context.Background()

	// 同一个码并发提交:每一轮恰好接受一次,其余重判后得到 ErrReused。
	t.Run("SameCodeConcurrent", func(t *testing.T) {
		const n, rounds = 32, 20
		s := open(t)
		c := Step(at(1_800_000_000), 30)
		now := at(c*30 + 10)
		code := codeAtStep(t, c)
		for r := 0; r < rounds; r++ {
			s.Reset()
			v := verifierAt(newGate(s.StepStore, n), DefaultOptions, &now)
			errs := make(chan error, n)
			var wg sync.WaitGroup
			for i := 0; i < n; i++ {
				wg.Add(1)
				go func() {
					defer wg.Done()
					errs <- v.Verify(ctx, "u", testKey, code)
				}()
			}
			wg.Wait()
			close(errs)
			accepted := 0
			for err := range errs {
				switch {
				case err == nil:
					accepted++
				case !errors.Is(err, ErrReused):
					t.Fatalf("round %d: unexpected error %v", r, err)
				}
			}
			if accepted != 1 {
				t.Fatalf("round %d: accepted %d times, want 1", r, accepted)
			}
		}
	})

	// 判断依据过期:请求 B 读到“从没用过”以后,请求 A 用同一个数字串消费了第 100 步。
	// B 的写入必须失败并按最新状态重判,得到 ErrReused,而不是拿着旧判断消费第 101 步。
	t.Run("StaleJudgmentRejudged", func(t *testing.T) {
		s := open(t)
		s.Reset()
		o := collidingOptions()
		key := Key{Secret: "unused", Version: 1}
		nowA, nowB := at(99*30+1), at(102*30+1)
		a := verifierAt(s.StepStore, o, &nowA)
		var errA error
		b := verifierAt(&hookStore{StepStore: s.StepStore, hook: func() {
			errA = a.Verify(ctx, "u", key, "111111")
		}}, o, &nowB)
		errB := b.Verify(ctx, "u", key, "111111")
		if errA != nil {
			t.Fatalf("A: %v", errA)
		}
		if !errors.Is(errB, ErrReused) {
			t.Fatalf("B: got %v, want ErrReused", errB)
		}
		if st, _ := s.State(ctx, "u"); st.LastStep != 100 {
			t.Fatalf("last step = %d, want 100", st.LastStep)
		}
	})

	// 读到状态以后发生换绑:写入失败,重判时发现密钥版本变了。
	t.Run("RebindDuringVerify", func(t *testing.T) {
		s := open(t)
		s.Reset()
		c := Step(at(1_800_000_000), 30)
		now := at(c*30 + 10)
		var rebindErr error
		v := verifierAt(&hookStore{StepStore: s.StepStore, hook: func() {
			_, rebindErr = s.Rebind()
		}}, DefaultOptions, &now)
		err := v.Verify(ctx, "u", testKey, codeAtStep(t, c))
		if rebindErr != nil {
			t.Fatal(rebindErr)
		}
		if !errors.Is(err, ErrKeyChanged) {
			t.Fatalf("got %v, want ErrKeyChanged", err)
		}
		if st, _ := s.State(ctx, "u"); st.LastStep != -1 || st.KeyVersion != 2 {
			t.Fatalf("state = %+v, want last -1 version 2", st)
		}
	})

	// 拿着旧版本的密钥来校验,直接拒绝;拿新版本则正常。
	t.Run("StaleKeyVersion", func(t *testing.T) {
		s := open(t)
		s.Reset()
		version, err := s.Rebind()
		if err != nil {
			t.Fatal(err)
		}
		c := Step(at(1_800_000_000), 30)
		now := at(c*30 + 10)
		v := verifierAt(s.StepStore, DefaultOptions, &now)
		code := codeAtStep(t, c)
		if err := v.Verify(ctx, "u", testKey, code); !errors.Is(err, ErrKeyChanged) {
			t.Fatalf("old key: got %v, want ErrKeyChanged", err)
		}
		if err := v.Verify(ctx, "u", Key{Secret: testSecret, Version: version}, code); err != nil {
			t.Fatalf("new key: %v", err)
		}
	})

	// Consume 只认读到的状态:状态对不上、步号不更新,都不写。
	t.Run("ConsumeComparesState", func(t *testing.T) {
		s := open(t)
		s.Reset()
		seen, err := s.State(ctx, "u")
		if err != nil {
			t.Fatal(err)
		}
		if ok, _ := s.Consume(ctx, "u", seen, 500); !ok {
			t.Fatal("first consume should succeed")
		}
		if ok, _ := s.Consume(ctx, "u", seen, 501); ok { // seen 已过期
			t.Fatal("consume with stale state should fail")
		}
		now, _ := s.State(ctx, "u")
		if ok, _ := s.Consume(ctx, "u", now, 500); ok { // 步号不更新
			t.Fatal("consume with a non-increasing step should fail")
		}
		if st, _ := s.State(ctx, "u"); st.LastStep != 500 {
			t.Fatalf("last step = %d, want 500", st.LastStep)
		}
	})

}

pgstore_test.go:PostgreSQL 的测试需要一个可以随意建表删表的测试库,通过环境变量 TOTPGUARD_TEST_DSN 给出;每个子测试建一张随机名字的表,结束时删掉。没设这个变量时会跳过。

package totpguard

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"os"
	"testing"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// 需要一个可以随意建表删表的测试库,例如:
//
//	TOTPGUARD_TEST_DSN='host=/path/to/socket dbname=scratch' go test -run PG ./...
//
// 每个子测试建一张随机名字的表,结束时删掉;没设这个变量就跳过。
func TestPGStoreSuite(t *testing.T) {
	dsn := os.Getenv("TOTPGUARD_TEST_DSN")
	if dsn == "" {
		t.Skip("TOTPGUARD_TEST_DSN not set")
	}
	runStoreSuite(t, func(t *testing.T) suiteStore {
		ctx := context.Background()
		cfg, err := pgxpool.ParseConfig(dsn)
		if err != nil {
			t.Fatal(err)
		}
		cfg.MaxConns = 40
		pool, err := pgxpool.NewWithConfig(ctx, cfg)
		if err != nil {
			t.Fatal(err)
		}
		b := make([]byte, 6)
		_, _ = rand.Read(b)
		table := "totpguard_test_" + hex.EncodeToString(b)
		ident := pgx.Identifier{table}.Sanitize()
		_, err = pool.Exec(ctx, fmt.Sprintf(`CREATE TABLE %s (
			id               text PRIMARY KEY,
			totp_last_step   bigint,
			totp_key_version bigint NOT NULL
		)`, ident))
		if err != nil {
			pool.Close()
			t.Fatal(err)
		}
		t.Cleanup(func() {
			_, _ = pool.Exec(context.Background(), `DROP TABLE IF EXISTS `+ident)
			pool.Close()
		})
		var version string
		_ = pool.QueryRow(ctx, `SHOW server_version`).Scan(&version)
		t.Logf("PostgreSQL %s", version)

		store := PGStore{Pool: pool, Table: table}
		return suiteStore{
			StepStore: store,
			Reset: func() {
				_, err := pool.Exec(ctx, fmt.Sprintf(`INSERT INTO %s (id, totp_last_step, totp_key_version)
					VALUES ('u', NULL, 1)
					ON CONFLICT (id) DO UPDATE SET totp_last_step = NULL, totp_key_version = 1`, ident))
				if err != nil {
					t.Fatal(err)
				}
			},
			Rebind: func() (int64, error) { return store.Rebind(ctx, "u") },
		}
	})
}

运行:

go mod tidy
go vet ./...
go test -race ./...
# 有测试库时再跑 PostgreSQL 的那一套
TOTPGUARD_TEST_DSN='host=/path/to/socket dbname=scratch' go test -race -run PG -v ./...

小结

  • totp.Validate 只判断码在当前时间附近是否合法,默认前后各容忍一步,一个码总共 90 秒有效,用户看到以后还会再有效 30 到 60 秒。
  • 防重放要记“上次接受的步号”,新码步号必须严格更大。库不返回命中的步号,需要自己用 hotp.GenerateCodeCustom 循环。
  • 不同步号可能算出同一个数字串。匹配时窗口内命中多步就拒绝,与最近一次接受的码同值也拒绝;只有第一条不够。这两条不是对所有历史数字串去重。
  • 记账必须是原子的比较并交换,比较的是做判断时读到的步号和密钥版本;写入失败就按最新状态重判。一条带条件的 UPDATE 就能做到,PostgreSQL 19 和 16 上测试结果一致。单靠“步号更大”只能保证同一绑定下已消费的步号不能再用,解决不了数字串碰撞。
  • 注册确认的码也要记账,失败不前移,换密钥清空;防重放之外还要限流,备用码用同样的原子写法。

参考:

  • RFC 6238,TOTP: Time-Based One-Time Password Algorithm,第 4.2、5.2 节
  • RFC 4226,HOTP: An HMAC-Based One-Time Password Algorithm,第 6、7.3 节
  • PostgreSQL 19 文档,Transaction Isolation,Read Committed Isolation Level 一节
— 文章结束 —返回文章归档 ↑

讨论

点击后加载 giscus 讨论。登录与发表由你自行操作。