--- name: implementing-totp-auth description: Guides implementation of TOTP-based two-tier authorization mechanism for RMDC system. Use when implementing authorization flows, modifying TOTP parameters, or debugging auth failures between project-management, watchdog, agent, and node components. Keywords: totp, authorization, tier-one, tier-two, security, authentication, hmac. argument-hint: ": tier-one | tier-two | dual-verify | auth-file" allowed-tools: - Read - Glob - Grep - Bash - Edit - Write --- # Implementing TOTP Authorization RMDC采用双层TOTP授权机制保护项目环境安全。 ## 动态上下文注入 ```bash # 查找TOTP实现 !`grep -rn "TOTP\|totp" rmdc-watchdog/pkg/totp/` # 查找授权验证逻辑 !`grep -n "Verify.*TOTP\|Generate.*TOTP" rmdc-watchdog/internal/service/auth_service.go` ``` ## Plan 根据 `$ARGUMENTS` 确定实现范围: | Scope | 涉及组件 | 关键参数 | |-------|----------|----------| | tier-one | project-management ↔ watchdog | 8位/30分钟/SHA256 | | tier-two | watchdog ↔ agent/node | 6位/30秒/SHA1 | | dual-verify | 所有通信 | 请求TOTP + 响应TOTP | | auth-file | watchdog授权申请/解析 | 加密主机信息 + TOTP + namespace | **产物清单**: - `pkg/totp/totp.go` - TOTP生成与验证 - `internal/service/auth_service.go` - 授权服务 - `internal/model/entity/auth_info.go` - 授权信息实体 ## Verify - [ ] Tier-One参数:8位码、30分钟有效、SHA256、AES-GCM加密 - [ ] Tier-Two参数:6位码、30秒有效、SHA1 - [ ] 双向验证:服务端响应必须包含TOTP供客户端校验 - [ ] 时间戳校验:|now - timestamp| < 5分钟(可配置) - [ ] 密钥存储:tier_one_secret/tier_two_secret不通过公网传输 - [ ] 授权文件包含:EncryptedHostMap, TOTPCode, EncryptedNamespace ```bash # 验证TOTP生成 !`cd rmdc-watchdog && go test ./pkg/totp/... -v -run TestGenerate` # 验证授权流程 !`cd rmdc-watchdog && go test ./internal/service/... -v -run TestAuth` ``` ## Execute ### 实现Tier-One TOTP ```go // 8位,30分钟有效,SHA256 func GenerateTierOneTOTP(secret string) string { return totp.Generate(secret, totp.Config{ Digits: 8, Period: 1800, // 30分钟 Algorithm: crypto.SHA256, }) } ``` ### 实现Tier-Two TOTP ```go // 6位,30秒有效,SHA1 func GenerateTierTwoTOTP(secret string) string { return totp.Generate(secret, totp.Config{ Digits: 6, Period: 30, Algorithm: crypto.SHA1, }) } ``` ### 实现双向验证 1. 客户端生成TOTP并发送请求 2. 服务端验证客户端TOTP 3. 服务端生成新TOTP并返回 4. 客户端验证服务端TOTP ## Pitfalls 1. **算法混淆**:Tier-One用SHA256,Tier-Two用SHA1,不可互换 2. **有效期错配**:30分钟 vs 30秒,单位差异大 3. **时间同步问题**:需配置 `time_offset_allowed` 容忍时钟偏差 4. **单向验证漏洞**:缺少响应TOTP会导致中间人攻击风险 5. **密钥泄露**:禁止在日志/错误信息中打印secret 6. **首次连接处理**:TOTPCode为空时需返回密钥,后续请求必须验证 ## Reference - [TOTP层级说明](reference/totp-tiers.md) - [授权流程图](reference/auth-flow.md)