feat: 实现工位终端滑动续签机制,强化安全与身份追溯

- 新增滑动续签功能:人工触屏触发本地心跳 + 30秒节流刷新JWT,避免作业中令牌过期
- 拆分质量检验权限:过程检/完工检使用不同权限码,细化权限粒度
- 新增操作人用户ID字段:报工、拧紧记录落库时携带可信用户ID,解决身份追溯问题
- 移除编译期默认密钥,启动期校验所有必要密钥非空,防止密钥泄露风险
- 修复WMS附件越权遍历问题:使用UUID文件名替代顺序ID访问附件
- 实现登录态过期数据隔离:仅返回当前操作人的待同步数据,避免身份混淆
This commit is contained in:
SunYF
2026-10-06 19:36:22 +08:00
parent f1cf57e9b2
commit 756d978900
71 changed files with 2417 additions and 556 deletions
@@ -29,7 +29,8 @@ func doBind(svcCtx *svc.ServiceContext, r *http.Request) (any, error) {
if req.Sn == "" || req.FlowId <= 0 {
return nil, nil
}
op := operator(r, req.Operator)
LogImpersonation(svcCtx, r, req.Operator, "/api/internal/workpiece/binds")
op := StationOp(r, req.Operator)
stationNo := ""
if req.StationNo > 0 {
stationNo = itoa(req.StationNo)
@@ -64,7 +65,8 @@ func doUnbind(svcCtx *svc.ServiceContext, r *http.Request) error {
if err := httpx.ParseJSON(r, &req); err != nil {
return err
}
return logic.New(svcCtx).RemoveBind(r.Context(), req.Sn, req.FlowId, req.MaterialCode, req.BindValue, operator(r, req.Operator))
LogImpersonation(svcCtx, r, req.Operator, "/api/internal/workpiece/binds/remove")
return logic.New(svcCtx).RemoveBind(r.Context(), req.Sn, req.FlowId, req.MaterialCode, req.BindValue, StationOp(r, req.Operator))
}
// UnbindInternalHandler POST /api/internal/workpiece/binds/remove
@@ -188,7 +188,7 @@ func StationReceiveMaterialInternalHandler(svcCtx *svc.ServiceContext) http.Hand
httpx.BadRequest(w, "缺少备料单号")
return
}
if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, operator(r, "")); err != nil {
if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, StationOp(r, "")); err != nil {
httpx.Fail(w, 3114, err.Error())
return
}
@@ -71,7 +71,7 @@ func TorqueReportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.BadRequest(w, "请求体解析失败")
return
}
if err := logic.New(svcCtx).ReportTorque(r.Context(), req, operator(r, req.Operator)); err != nil {
if err := logic.New(svcCtx).ReportTorque(r.Context(), req, operator(r, req.Operator), 0); err != nil {
httpx.Fail(w, 3203, err.Error())
return
}
@@ -1,9 +1,13 @@
package production
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
token "bj_power_mes/common/token"
"bj_power_mes/common/httpx"
"bj_power_mes/ent"
"bj_power_mes/ent/material"
@@ -49,6 +53,98 @@ func InternalAuth(serverCtx *svc.ServiceContext) func(http.HandlerFunc) http.Han
}
}
// StationSessionAuth 工位终端报工鉴权中间件(安全方案 B · 关闭 #11/#14 冒名留痕)。
// 要求工位终端在 Authorization: Bearer 携带「登录时 MES 签发的 JWT」(与 MES 前端同源同密钥),
// 校验通过后从该 token 的 claims 提取可信操作人(Name)与工位号(StationNo)注入请求头;
// 报工/拧紧 handler 据此落痕,忽略请求体里的 operator/stationNo。
// 与 InternalAuth(X-API-TOKEN 网关)互补:前者管“哪个系统”,本中间件管“哪个操作工”的可信身份。
func StationSessionAuth(serverCtx *svc.ServiceContext) func(http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authz := r.Header.Get("Authorization")
if !strings.HasPrefix(authz, "Bearer ") {
httpx.FailHTTP(w, http.StatusUnauthorized, "缺少工位登录凭证,请重新登录")
return
}
claims, err := token.Parse(serverCtx.Config.Auth.AccessSecret, strings.TrimPrefix(authz, "Bearer "))
if err != nil || claims == nil || time.Until(claims.ExpiresAt.Time) <= 0 {
httpx.FailHTTP(w, http.StatusUnauthorized, "工位登录凭证无效或已过期,请重新登录")
return
}
r.Header.Set("X-Station-Operator", claims.Name)
r.Header.Set("X-Station-Operator-Id", strconv.Itoa(claims.UserId))
if claims.StationNo > 0 {
r.Header.Set("X-Station-No", strconv.Itoa(claims.StationNo))
}
next(w, r)
}
}
}
// StationOp 报工链路可信操作人解析(方案 B · 关闭 #11/#14 冒名留痕):优先取工位登录态注入的 Name,
// 未携带登录态时(如 MES 前端 JWT 虚拟工位作业路径)回退到原有 operator(r, bodyOp)。
// 这样同一 StationReport 既服务于终端(强可信)也服务于管理后台(登录账号留痕),互不破坏。
func StationOp(r *http.Request, bodyOp string) string {
if v := r.Header.Get("X-Station-Operator"); v != "" {
return v
}
return operator(r, bodyOp)
}
// StationNo 报工链路可信工位号解析(方案 B):优先取工位登录态注入的 StationNo,否则回退请求体。
func StationNo(r *http.Request, bodyNo int) int {
if v := r.Header.Get("X-Station-No"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
}
return bodyNo
}
// StationOpId 报工链路可信操作人 ID(方案 B 补1):取工位登录态注入的 UserId,
// 用于落库/审计时同时携带「姓名 + 用户ID」,避免重名导致追溯歧义。
func StationOpId(r *http.Request) string {
return r.Header.Get("X-Station-Operator-Id")
}
// StationOpIdInt 报工链路可信操作人 ID(落库 operator_id 用)。
// 返回值语义(核实2):
// - 未携带 X-Station-Operator-Id 头(MES 前端虚拟工位 / PLC 扫码等无工位登录态路径)
// → (0, nil):0 = 「未采集」,属合法语义,不报错;
// - 携带了头但内容非法或 ≤0(正常只可能来自 StationSessionAuth 注入的 JWT userId,
// 出现即说明凭证被伪造/中间件被绕过)→ (0, error):调用方必须拒绝请求,
// 杜绝「身份静默丢失为 0」被当成正常数据入库。
func StationOpIdInt(r *http.Request) (int, error) {
v := r.Header.Get("X-Station-Operator-Id")
if v == "" {
return 0, nil
}
n, err := strconv.Atoi(v)
if err != nil || n <= 0 {
return 0, fmt.Errorf("工位登录态操作人ID非法:%q", v)
}
return n, nil
}
// LogImpersonation 防冒名探测器(方案 B 补2):当请求体 operator 与登录态可信 operator 不一致时,
// 写一条 security.impersonation 安全告警(含双方身份与工位号),用于上线后监测是否有人伪造操作人。
// 仅在携带登录态(内部路由经 StationSessionAuth)时生效;管理后台 JWT 路径 bodyOp 为空不触发。
func LogImpersonation(svcCtx *svc.ServiceContext, r *http.Request, bodyOp, path string) {
trusted := r.Header.Get("X-Station-Operator")
if bodyOp != "" && trusted != "" && bodyOp != trusted {
svcCtx.EventLog.Write(r.Context(), "security.impersonation", "", trusted, "auth", "",
"工位终端上报操作人与登录态不一致(疑似冒名)",
map[string]any{
"path": path,
"bodyOperator": bodyOp,
"trustedOperator": trusted,
"trustedOperatorId": r.Header.Get("X-Station-Operator-Id"),
"stationNo": r.Header.Get("X-Station-No"),
})
}
}
// ---------- 内部 API(看板/工位终端/WMS 调用) ----------
func TorqueReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
@@ -58,7 +154,18 @@ func TorqueReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.BadRequest(w, "请求体解析失败")
return
}
if err := logic.New(svcCtx).ReportTorque(r.Context(), req, operator(r, req.Operator)); err != nil {
// 方案 B(#11/#14):操作人/工位号取自工位登录态可信身份,忽略请求体
if v := r.Header.Get("X-Station-No"); v != "" {
req.StationNo = v
}
LogImpersonation(svcCtx, r, req.Operator, "/api/internal/torque/report")
recOpId, derr := StationOpIdInt(r)
if derr != nil {
httpx.Fail(w, 2001, derr.Error())
return
}
recOpName := StationOp(r, req.Operator)
if err := logic.New(svcCtx).ReportTorque(r.Context(), req, recOpName, recOpId); err != nil {
httpx.Fail(w, 2001, err.Error())
return
}
@@ -73,7 +180,16 @@ func WorkpieceReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc
httpx.BadRequest(w, "请求体解析失败")
return
}
if err := logic.New(svcCtx).ReportProcess(r.Context(), req, operator(r, "")); err != nil {
// 方案 B(#11/#14):操作人/工位号取自工位登录态可信身份,忽略请求体
req.StationNo = StationNo(r, req.StationNo)
LogImpersonation(svcCtx, r, req.Operator, "/api/internal/workpiece/report")
recOpId, derr := StationOpIdInt(r)
if derr != nil {
httpx.Fail(w, 2002, derr.Error())
return
}
recOpName := StationOp(r, req.Operator)
if err := logic.New(svcCtx).ReportProcess(r.Context(), req, recOpName, recOpId); err != nil {
httpx.Fail(w, 2002, err.Error())
return
}
@@ -158,7 +274,8 @@ func OnlineWorkpieceInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc
httpx.BadRequest(w, "请求体解析失败")
return
}
if msg, err := logic.New(svcCtx).OnlineWorkpiece(r.Context(), req, operator(r, r.URL.Query().Get("operator"))); err != nil {
LogImpersonation(svcCtx, r, r.URL.Query().Get("operator"), "/api/internal/workpiece/online")
if msg, err := logic.New(svcCtx).OnlineWorkpiece(r.Context(), req, StationOp(r, r.URL.Query().Get("operator"))); err != nil {
httpx.Fail(w, 2007, err.Error())
return
} else {
@@ -176,7 +293,8 @@ func DoneWorkpieceInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.BadRequest(w, "请求体解析失败")
return
}
if err := logic.New(svcCtx).DoneWorkpiece(r.Context(), req, operator(r, r.URL.Query().Get("operator"))); err != nil {
LogImpersonation(svcCtx, r, r.URL.Query().Get("operator"), "/api/internal/workpiece/done")
if err := logic.New(svcCtx).DoneWorkpiece(r.Context(), req, StationOp(r, r.URL.Query().Get("operator"))); err != nil {
httpx.Fail(w, 2008, err.Error())
return
}
@@ -0,0 +1,157 @@
package production_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
tokenx "bj_power_mes/common/token"
"bj_power_mes/internal/config"
"bj_power_mes/internal/db"
"bj_power_mes/internal/eventlog"
"bj_power_mes/internal/handler/production"
"bj_power_mes/internal/svc"
eventlogpred "bj_power_mes/ent/eventlog"
)
// TestStationSecurityVerify 运行期验证方案 B 安全整改(核实2 / 补1 / 补2):
// - 正常登录:报工 operator 取自 JWT 可信身份(真实姓名)
// - 伪造请求体 operator:仍以 JWT 真实姓名落痕,且冒名探测器写 security.impersonation
// - 无/过期 Bearer:401,不进入业务
//
// 仅连 PostgreSQL(dev 库),不依赖 Redis/PLC,测试后清理自身写入的审计行。
func TestStationSecurityVerify(t *testing.T) {
secret := "Hardman_2026"
c := config.Config{
Auth: config.AuthConf{AccessSecret: secret, AccessExpire: 3600},
Internal: config.InternalConf{Token: secret},
}
entClient, _ := db.MustNewDB(db.DatabaseConf{
Host: "127.0.0.1", Port: 5432, User: "postgres", Password: "postgres",
Dbname: "bj_power_mes", MaxIdle: 5, MaxOpen: 5,
})
svcCtx := &svc.ServiceContext{Config: c, EntClient: entClient, EventLog: eventlog.NewWriter(entClient)}
ctx := context.Background()
// 真实登录态 JWT:用户 7 张三,工位 3
realTok, err := tokenx.Issue(secret, time.Hour, tokenx.Claims{
UserId: 7, Username: "zhangsan", Name: "张三", StationNo: 3,
})
if err != nil {
t.Fatalf("签发 JWT 失败: %v", err)
}
// 过期 JWT(expire = -1h)
expiredTok, _ := tokenx.Issue(secret, -time.Hour, tokenx.Claims{
UserId: 7, Username: "zhangsan", Name: "张三", StationNo: 3,
})
type reportBody struct {
Operator string `json:"operator"`
StationNo string `json:"stationNo"`
}
type echoResp struct {
Resolved string `json:"resolved"`
Trusted string `json:"trusted"`
OpId string `json:"opId"`
StationNo string `json:"stationNo"`
}
var capture = func(w http.ResponseWriter, r *http.Request) {
var req reportBody
_ = json.NewDecoder(r.Body).Decode(&req)
resolved := production.StationOp(r, req.Operator)
production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/torque/report")
resp := echoResp{
Resolved: resolved,
Trusted: r.Header.Get("X-Station-Operator"),
OpId: r.Header.Get("X-Station-Operator-Id"),
StationNo: r.Header.Get("X-Station-No"),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
h := production.StationSessionAuth(svcCtx)(capture)
ts := httptest.NewServer(h)
defer ts.Close()
doPost := func(tok, bodyOp string) (int, echoResp) {
body, _ := json.Marshal(reportBody{Operator: bodyOp, StationNo: "3"})
req, _ := http.NewRequest(http.MethodPost, ts.URL, bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("请求失败: %v", err)
}
defer resp.Body.Close()
var er echoResp
_ = json.NewDecoder(resp.Body).Decode(&er)
return resp.StatusCode, er
}
beforeCount, _ := svcCtx.EntClient.EventLog.Query().
Where(eventlogpred.EventType("security.impersonation")).Count(ctx)
testStart := time.Now()
// 场景1:正常登录,请求体 operator 与 JWT 一致(张三)
code, er := doPost(realTok, "张三")
if code != 200 {
t.Errorf("[场景1] 期望 200,实际 %d", code)
}
if er.Resolved != "张三" {
t.Errorf("[场景1] 落痕操作人应为 JWT 真实姓名『张三』,实际 %q", er.Resolved)
}
if er.OpId != "7" {
t.Errorf("[场景1] 补1 operatorId 应为 7,实际 %q", er.OpId)
}
if er.StationNo != "3" {
t.Errorf("[场景1] 工位号应为 3,实际 %q", er.StationNo)
}
t.Logf("[场景1 正常登录] code=%d resolved=%q opId=%q stationNo=%q", code, er.Resolved, er.OpId, er.StationNo)
// 场景2:伪造请求体 operator=李四,应以 JWT 张三落痕,并触发冒名探测器
code, er = doPost(realTok, "李四")
if code != 200 {
t.Errorf("[场景2] 期望 200,实际 %d", code)
}
if er.Resolved != "张三" {
t.Errorf("[场景2] 冒名请求体被忽略失败:落痕操作人应为『张三』,实际 %q", er.Resolved)
}
t.Logf("[场景2 伪造请求体] code=%d resolved=%q (请求体 operator=李四 已被忽略)", code, er.Resolved)
afterCount, _ := svcCtx.EntClient.EventLog.Query().
Where(eventlogpred.EventType("security.impersonation")).Count(ctx)
if afterCount <= beforeCount {
t.Errorf("[场景2] 冒名探测器未落库:security.impersonation 行数 %d -> %d", beforeCount, afterCount)
} else {
t.Logf("[场景2 冒名探测器] security.impersonation 新增 %d 行(已落库)", afterCount-beforeCount)
}
// 场景3a:无 Bearer → 401
code, _ = doPost("", "王五")
if code != http.StatusUnauthorized {
t.Errorf("[场景3a] 无凭证期望 401,实际 %d", code)
} else {
t.Logf("[场景3a 无登录凭证] code=%d(已拦截)", code)
}
// 场景3b:过期 Bearer → 401(触发工位终端重登录续传,数据不丢)
code, _ = doPost(expiredTok, "张三")
if code != http.StatusUnauthorized {
t.Errorf("[场景3b] 过期凭证期望 401,实际 %d", code)
} else {
t.Logf("[场景3b 凭证过期] code=%d(已拦截,终端应暂停重传而非丢数据)", code)
}
// 清理:仅删除本测试写入的 security.impersonation 行(按时间窗)
_, _ = svcCtx.EntClient.EventLog.Delete().
Where(eventlogpred.EventType("security.impersonation"), eventlogpred.CreatedAtGTE(testStart)).Exec(ctx)
}
@@ -22,7 +22,8 @@ func StationPauseInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.BadRequest(w, "请求体解析失败")
return
}
if err := logic.New(svcCtx).SetStationPause(r.Context(), req.StationNo, req.Paused, req.Reason, operator(r, req.Operator)); err != nil {
LogImpersonation(svcCtx, r, req.Operator, "/api/internal/station/pause")
if err := logic.New(svcCtx).SetStationPause(r.Context(), req.StationNo, req.Paused, req.Reason, StationOp(r, req.Operator)); err != nil {
httpx.Fail(w, 2115, err.Error())
return
}