feat: sync lijiaoqiao implementation and staging validation artifacts
This commit is contained in:
295
platform-token-runtime/internal/token/audit_executable_test.go
Normal file
295
platform-token-runtime/internal/token/audit_executable_test.go
Normal file
@@ -0,0 +1,295 @@
|
||||
package token_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lijiaoqiao/platform-token-runtime/internal/auth/middleware"
|
||||
"lijiaoqiao/platform-token-runtime/internal/auth/model"
|
||||
"lijiaoqiao/platform-token-runtime/internal/auth/service"
|
||||
)
|
||||
|
||||
func TestTOKAud001IssueSuccessEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
|
||||
record, err := rt.IssueAndAudit(context.Background(), service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 10 * time.Minute,
|
||||
RequestID: "req-aud-001",
|
||||
}, auditor)
|
||||
if err != nil {
|
||||
t.Fatalf("issue with audit failed: %v", err)
|
||||
}
|
||||
|
||||
event, ok := auditor.LastEvent()
|
||||
if !ok {
|
||||
t.Fatalf("expected issue success event")
|
||||
}
|
||||
if event.EventName != service.EventTokenIssueSuccess {
|
||||
t.Fatalf("unexpected event name: got=%s want=%s", event.EventName, service.EventTokenIssueSuccess)
|
||||
}
|
||||
assertAuditRequiredFields(t, event)
|
||||
if event.TokenID != record.TokenID {
|
||||
t.Fatalf("unexpected token_id in event: got=%s want=%s", event.TokenID, record.TokenID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKAud002IssueFailEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
|
||||
_, err := rt.IssueAndAudit(context.Background(), service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 0,
|
||||
RequestID: "req-aud-002",
|
||||
}, auditor)
|
||||
if err == nil {
|
||||
t.Fatalf("expected issue failure")
|
||||
}
|
||||
|
||||
event, ok := auditor.LastEvent()
|
||||
if !ok {
|
||||
t.Fatalf("expected issue fail event")
|
||||
}
|
||||
if event.EventName != service.EventTokenIssueFail {
|
||||
t.Fatalf("unexpected event name: got=%s want=%s", event.EventName, service.EventTokenIssueFail)
|
||||
}
|
||||
assertAuditRequiredFields(t, event)
|
||||
if event.ResultCode != "ISSUE_FAILED" {
|
||||
t.Fatalf("unexpected result_code: got=%s want=ISSUE_FAILED", event.ResultCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKAud003AuthnFailEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
authorizer := service.NewScopeRoleAuthorizer()
|
||||
|
||||
handler := middleware.BuildTokenAuthChain(middleware.AuthMiddlewareConfig{
|
||||
Verifier: rt,
|
||||
StatusResolver: rt,
|
||||
Authorizer: authorizer,
|
||||
Auditor: auditor,
|
||||
}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/supply/accounts", nil)
|
||||
req.Header.Set("Authorization", "Bearer invalid-token")
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unexpected status code: got=%d want=%d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
event, ok := auditor.LastEvent()
|
||||
if !ok {
|
||||
t.Fatalf("expected audit event for authn failure")
|
||||
}
|
||||
if event.EventName != service.EventTokenAuthnFail {
|
||||
t.Fatalf("unexpected event name: got=%s want=%s", event.EventName, service.EventTokenAuthnFail)
|
||||
}
|
||||
if event.RequestID == "" {
|
||||
t.Fatalf("request_id must not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKAud004AuthzDeniedEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
authorizer := service.NewScopeRoleAuthorizer()
|
||||
|
||||
ctx := context.Background()
|
||||
viewer, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2002",
|
||||
Role: model.RoleViewer,
|
||||
Scope: []string{"supply:read"},
|
||||
TTL: 5 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue viewer token failed: %v", err)
|
||||
}
|
||||
|
||||
handler := middleware.BuildTokenAuthChain(middleware.AuthMiddlewareConfig{
|
||||
Verifier: rt,
|
||||
StatusResolver: rt,
|
||||
Authorizer: authorizer,
|
||||
Auditor: auditor,
|
||||
}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/supply/packages", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+viewer.AccessToken)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("unexpected status code: got=%d want=%d", rec.Code, http.StatusForbidden)
|
||||
}
|
||||
event, ok := auditor.LastEvent()
|
||||
if !ok {
|
||||
t.Fatalf("expected audit event for authz denial")
|
||||
}
|
||||
if event.EventName != service.EventTokenAuthzDenied {
|
||||
t.Fatalf("unexpected event name: got=%s want=%s", event.EventName, service.EventTokenAuthzDenied)
|
||||
}
|
||||
if event.SubjectID != viewer.SubjectID {
|
||||
t.Fatalf("unexpected subject_id: got=%s want=%s", event.SubjectID, viewer.SubjectID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKAud005RevokeSuccessEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
|
||||
record, err := rt.Issue(context.Background(), service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 8 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue token failed: %v", err)
|
||||
}
|
||||
_, err = rt.RevokeAndAudit(context.Background(), record.TokenID, "operator_request", "req-aud-005", record.SubjectID, auditor)
|
||||
if err != nil {
|
||||
t.Fatalf("revoke with audit failed: %v", err)
|
||||
}
|
||||
|
||||
event, ok := auditor.LastEvent()
|
||||
if !ok {
|
||||
t.Fatalf("expected revoke success event")
|
||||
}
|
||||
if event.EventName != service.EventTokenRevokeSuccess {
|
||||
t.Fatalf("unexpected event name: got=%s want=%s", event.EventName, service.EventTokenRevokeSuccess)
|
||||
}
|
||||
assertAuditRequiredFields(t, event)
|
||||
if event.TokenID != record.TokenID {
|
||||
t.Fatalf("unexpected token_id in event: got=%s want=%s", event.TokenID, record.TokenID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKAud006QueryKeyRejectedEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
authorizer := service.NewScopeRoleAuthorizer()
|
||||
|
||||
handler := middleware.BuildTokenAuthChain(middleware.AuthMiddlewareConfig{
|
||||
Verifier: rt,
|
||||
StatusResolver: rt,
|
||||
Authorizer: authorizer,
|
||||
Auditor: auditor,
|
||||
}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/supply/accounts?api_key=raw-secret-value", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unexpected status code: got=%d want=%d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
event, ok := auditor.LastEvent()
|
||||
if !ok {
|
||||
t.Fatalf("expected query key rejection audit event")
|
||||
}
|
||||
if event.EventName != service.EventTokenQueryKeyRejected {
|
||||
t.Fatalf("unexpected event name: got=%s want=%s", event.EventName, service.EventTokenQueryKeyRejected)
|
||||
}
|
||||
|
||||
serialized := strings.Join([]string{
|
||||
event.EventID,
|
||||
event.EventName,
|
||||
event.RequestID,
|
||||
event.TokenID,
|
||||
event.SubjectID,
|
||||
event.Route,
|
||||
event.ResultCode,
|
||||
event.ClientIP,
|
||||
}, "|")
|
||||
if strings.Contains(serialized, "raw-secret-value") {
|
||||
t.Fatalf("audit event must not contain raw query key value")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKAud007EventImmutability(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
|
||||
issued, err := rt.IssueAndAudit(context.Background(), service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 20 * time.Minute,
|
||||
RequestID: "req-aud-007-1",
|
||||
}, auditor)
|
||||
if err != nil {
|
||||
t.Fatalf("issue with audit failed: %v", err)
|
||||
}
|
||||
_, err = rt.RevokeAndAudit(context.Background(), issued.TokenID, "test", "req-aud-007-2", issued.SubjectID, auditor)
|
||||
if err != nil {
|
||||
t.Fatalf("revoke with audit failed: %v", err)
|
||||
}
|
||||
|
||||
firstRead := auditor.Events()
|
||||
secondRead := auditor.Events()
|
||||
if len(firstRead) < 2 || len(secondRead) < 2 {
|
||||
t.Fatalf("expected at least two audit events")
|
||||
}
|
||||
for idx := range firstRead {
|
||||
if firstRead[idx].EventID != secondRead[idx].EventID ||
|
||||
firstRead[idx].EventName != secondRead[idx].EventName ||
|
||||
!firstRead[idx].CreatedAt.Equal(secondRead[idx].CreatedAt) {
|
||||
t.Fatalf("event should be immutable across reads at index=%d", idx)
|
||||
}
|
||||
}
|
||||
for idx := 1; idx < len(firstRead); idx++ {
|
||||
if firstRead[idx].CreatedAt.Before(firstRead[idx-1].CreatedAt) {
|
||||
t.Fatalf("event timeline should be ordered by created_at")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertAuditRequiredFields(t *testing.T, event service.AuditEvent) {
|
||||
t.Helper()
|
||||
if event.EventID == "" {
|
||||
t.Fatalf("event_id must not be empty")
|
||||
}
|
||||
if event.RequestID == "" {
|
||||
t.Fatalf("request_id must not be empty")
|
||||
}
|
||||
if event.ResultCode == "" {
|
||||
t.Fatalf("result_code must not be empty")
|
||||
}
|
||||
if event.Route == "" {
|
||||
t.Fatalf("route must not be empty")
|
||||
}
|
||||
if event.CreatedAt.IsZero() {
|
||||
t.Fatalf("created_at must not be zero")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package token_test
|
||||
|
||||
import "testing"
|
||||
|
||||
type auditTemplateCase struct {
|
||||
ID string
|
||||
Name string
|
||||
TriggerCase string
|
||||
Assertions []string
|
||||
}
|
||||
|
||||
func TestTokenAuditTemplateCases(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []auditTemplateCase{
|
||||
{
|
||||
ID: "TOK-AUD-001",
|
||||
Name: "签发成功事件",
|
||||
TriggerCase: "TOK-LIFE-001",
|
||||
Assertions: []string{
|
||||
"存在 token.issue.success",
|
||||
"event_id/request_id/result_code/route/created_at 齐全",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-AUD-002",
|
||||
Name: "签发失败事件",
|
||||
TriggerCase: "TOK-LIFE-002",
|
||||
Assertions: []string{
|
||||
"存在 token.issue.fail",
|
||||
"result_code 准确",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-AUD-003",
|
||||
Name: "鉴权失败事件",
|
||||
TriggerCase: "无效 token 访问受保护接口",
|
||||
Assertions: []string{
|
||||
"存在 token.authn.fail",
|
||||
"包含 request_id",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-AUD-004",
|
||||
Name: "越权事件",
|
||||
TriggerCase: "TOK-LIFE-008",
|
||||
Assertions: []string{
|
||||
"存在 token.authz.denied",
|
||||
"包含 subject_id",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-AUD-005",
|
||||
Name: "吊销事件",
|
||||
TriggerCase: "TOK-LIFE-005",
|
||||
Assertions: []string{
|
||||
"存在 token.revoke.success",
|
||||
"包含 token_id",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-AUD-006",
|
||||
Name: "query key 拒绝事件",
|
||||
TriggerCase: "query key 访问受保护接口",
|
||||
Assertions: []string{
|
||||
"存在 token.query_key.rejected",
|
||||
"不含敏感值",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-AUD-007",
|
||||
Name: "事件不可篡改",
|
||||
TriggerCase: "重复读取同 event_id",
|
||||
Assertions: []string{
|
||||
"核心字段不可变",
|
||||
"时间顺序正确",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(tc.ID, func(t *testing.T) {
|
||||
t.Skipf("模板用例,待接入实现: %s", tc.Name)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package token_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lijiaoqiao/platform-token-runtime/internal/auth/middleware"
|
||||
"lijiaoqiao/platform-token-runtime/internal/auth/model"
|
||||
"lijiaoqiao/platform-token-runtime/internal/auth/service"
|
||||
)
|
||||
|
||||
func TestTOKLife001IssueSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
ctx := context.Background()
|
||||
|
||||
first, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 30 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue token failed: %v", err)
|
||||
}
|
||||
second, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 30 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue second token failed: %v", err)
|
||||
}
|
||||
|
||||
if first.Status != service.TokenStatusActive {
|
||||
t.Fatalf("unexpected status: got=%s want=%s", first.Status, service.TokenStatusActive)
|
||||
}
|
||||
if !first.ExpiresAt.After(first.IssuedAt) {
|
||||
t.Fatalf("expires_at must be greater than issued_at")
|
||||
}
|
||||
if first.TokenID == second.TokenID {
|
||||
t.Fatalf("token_id should be unique")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKLife002IssueInvalidInput(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
ctx := context.Background()
|
||||
_, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 0,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for invalid ttl_seconds")
|
||||
}
|
||||
if got := rt.TokenCount(); got != 0 {
|
||||
t.Fatalf("unexpected token count after invalid issue: got=%d want=0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKLife003IssueIdempotencyReplay(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
ctx := context.Background()
|
||||
|
||||
first, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 30 * time.Minute,
|
||||
IdempotencyKey: "idem-life-003",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("first issue failed: %v", err)
|
||||
}
|
||||
second, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 30 * time.Minute,
|
||||
IdempotencyKey: "idem-life-003",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("replay issue failed: %v", err)
|
||||
}
|
||||
|
||||
if first.TokenID != second.TokenID {
|
||||
t.Fatalf("replayed issue must return same token_id: first=%s second=%s", first.TokenID, second.TokenID)
|
||||
}
|
||||
if got := rt.TokenCount(); got != 1 {
|
||||
t.Fatalf("idempotent replay must not create duplicate token: got=%d want=1", got)
|
||||
}
|
||||
|
||||
_, err = rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:read"},
|
||||
TTL: 30 * time.Minute,
|
||||
IdempotencyKey: "idem-life-003",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("expected payload mismatch conflict for same idempotency key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKLife004RefreshSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
ctx := context.Background()
|
||||
|
||||
issued, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 1 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue token failed: %v", err)
|
||||
}
|
||||
previousExpiresAt := issued.ExpiresAt
|
||||
|
||||
refreshed, err := rt.Refresh(ctx, issued.TokenID, 15*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("refresh token failed: %v", err)
|
||||
}
|
||||
|
||||
if refreshed.Status != service.TokenStatusActive {
|
||||
t.Fatalf("unexpected status after refresh: got=%s want=%s", refreshed.Status, service.TokenStatusActive)
|
||||
}
|
||||
if !refreshed.ExpiresAt.After(previousExpiresAt) {
|
||||
t.Fatalf("expires_at should be delayed after refresh")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKLife005RevokeSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
start := time.Now()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
ctx := context.Background()
|
||||
|
||||
issued, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 10 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue token failed: %v", err)
|
||||
}
|
||||
if _, err := rt.Revoke(ctx, issued.TokenID, "security_event"); err != nil {
|
||||
t.Fatalf("revoke token failed: %v", err)
|
||||
}
|
||||
|
||||
introspected, err := rt.Introspect(ctx, issued.AccessToken)
|
||||
if err != nil {
|
||||
t.Fatalf("introspect failed: %v", err)
|
||||
}
|
||||
if introspected.Status != service.TokenStatusRevoked {
|
||||
t.Fatalf("unexpected status after revoke: got=%s want=%s", introspected.Status, service.TokenStatusRevoked)
|
||||
}
|
||||
if time.Since(start) > 5*time.Second {
|
||||
t.Fatalf("revoke propagation exceeded 5 seconds in in-memory runtime")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKLife006RevokedTokenAccessDenied(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
authorizer := service.NewScopeRoleAuthorizer()
|
||||
ctx := context.Background()
|
||||
|
||||
issued, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 5 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue token failed: %v", err)
|
||||
}
|
||||
if _, err := rt.Revoke(ctx, issued.TokenID, "test_revoke"); err != nil {
|
||||
t.Fatalf("revoke failed: %v", err)
|
||||
}
|
||||
|
||||
handler := middleware.BuildTokenAuthChain(middleware.AuthMiddlewareConfig{
|
||||
Verifier: rt,
|
||||
StatusResolver: rt,
|
||||
Authorizer: authorizer,
|
||||
Auditor: auditor,
|
||||
}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/supply/accounts", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+issued.AccessToken)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unexpected status code: got=%d want=%d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
if code := decodeMiddlewareErrorCode(t, rec); code != service.CodeAuthTokenInactive {
|
||||
t.Fatalf("unexpected error code: got=%s want=%s", code, service.CodeAuthTokenInactive)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKLife007ExpiredTokenInactive(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
current := time.Date(2026, 3, 29, 15, 0, 0, 0, time.UTC)
|
||||
rt := service.NewInMemoryTokenRuntime(func() time.Time { return current })
|
||||
ctx := context.Background()
|
||||
|
||||
issued, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2001",
|
||||
Role: model.RoleOwner,
|
||||
Scope: []string{"supply:*"},
|
||||
TTL: 2 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue token failed: %v", err)
|
||||
}
|
||||
current = current.Add(3 * time.Second)
|
||||
|
||||
introspected, err := rt.Introspect(ctx, issued.AccessToken)
|
||||
if err != nil {
|
||||
t.Fatalf("introspect failed: %v", err)
|
||||
}
|
||||
if introspected.Status != service.TokenStatusExpired {
|
||||
t.Fatalf("unexpected token status: got=%s want=%s", introspected.Status, service.TokenStatusExpired)
|
||||
}
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
authorizer := service.NewScopeRoleAuthorizer()
|
||||
handler := middleware.BuildTokenAuthChain(middleware.AuthMiddlewareConfig{
|
||||
Verifier: rt,
|
||||
StatusResolver: rt,
|
||||
Authorizer: authorizer,
|
||||
Auditor: auditor,
|
||||
}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/supply/accounts", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+issued.AccessToken)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unexpected status code: got=%d want=%d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
if code := decodeMiddlewareErrorCode(t, rec); code != service.CodeAuthTokenInactive {
|
||||
t.Fatalf("unexpected error code: got=%s want=%s", code, service.CodeAuthTokenInactive)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTOKLife008ViewerWriteDenied(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
auditor := service.NewMemoryAuditEmitter()
|
||||
rt := service.NewInMemoryTokenRuntime(nil)
|
||||
authorizer := service.NewScopeRoleAuthorizer()
|
||||
|
||||
ctx := context.Background()
|
||||
viewer, err := rt.Issue(ctx, service.IssueTokenInput{
|
||||
SubjectID: "2002",
|
||||
Role: model.RoleViewer,
|
||||
Scope: []string{"supply:read"},
|
||||
TTL: 10 * time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("issue viewer token failed: %v", err)
|
||||
}
|
||||
|
||||
nextCalled := false
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
nextCalled = true
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := middleware.BuildTokenAuthChain(middleware.AuthMiddlewareConfig{
|
||||
Verifier: rt,
|
||||
StatusResolver: rt,
|
||||
Authorizer: authorizer,
|
||||
Auditor: auditor,
|
||||
}, next)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/supply/packages", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+viewer.AccessToken)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("unexpected status code: got=%d want=%d", rec.Code, http.StatusForbidden)
|
||||
}
|
||||
if code := decodeMiddlewareErrorCode(t, rec); code != service.CodeAuthScopeDenied {
|
||||
t.Fatalf("unexpected error code: got=%s want=%s", code, service.CodeAuthScopeDenied)
|
||||
}
|
||||
if nextCalled {
|
||||
t.Fatalf("write handler should be blocked for viewer token")
|
||||
}
|
||||
}
|
||||
|
||||
type middlewareErrorEnvelope struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
func decodeMiddlewareErrorCode(t *testing.T, rec *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
var envelope middlewareErrorEnvelope
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("failed to decode middleware error response: %v", err)
|
||||
}
|
||||
return envelope.Error.Code
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package token_test
|
||||
|
||||
import "testing"
|
||||
|
||||
// 说明:
|
||||
// 1. 本文件保留完整 TOK-LIFE 模板清单作为覆盖基线。
|
||||
// 2. 首批可执行用例已在 lifecycle_executable_test.go 落地:
|
||||
// TOK-LIFE-001 / TOK-LIFE-004 / TOK-LIFE-005 / TOK-LIFE-008。
|
||||
|
||||
type lifecycleTemplateCase struct {
|
||||
ID string
|
||||
Name string
|
||||
Preconditions []string
|
||||
Steps []string
|
||||
Assertions []string
|
||||
}
|
||||
|
||||
func TestTokenLifecycleTemplateCases(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []lifecycleTemplateCase{
|
||||
{
|
||||
ID: "TOK-LIFE-001",
|
||||
Name: "签发成功",
|
||||
Preconditions: []string{
|
||||
"tenant_id=1001",
|
||||
"subject_owner=2001",
|
||||
},
|
||||
Steps: []string{
|
||||
"调用 POST /api/v1/platform/tokens/issue",
|
||||
"记录 token_id/issued_at/expires_at/status",
|
||||
},
|
||||
Assertions: []string{
|
||||
"status=active",
|
||||
"expires_at>issued_at",
|
||||
"token_id 唯一",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-LIFE-002",
|
||||
Name: "签发参数非法",
|
||||
Preconditions: []string{
|
||||
"ttl_seconds 超上限",
|
||||
},
|
||||
Steps: []string{
|
||||
"调用 POST /api/v1/platform/tokens/issue",
|
||||
},
|
||||
Assertions: []string{
|
||||
"返回 400",
|
||||
"不落 active token",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-LIFE-003",
|
||||
Name: "幂等签发重放",
|
||||
Steps: []string{
|
||||
"相同 Idempotency-Key 重复调用签发接口",
|
||||
},
|
||||
Assertions: []string{
|
||||
"返回同一 token_id",
|
||||
"无重复写入",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-LIFE-004",
|
||||
Name: "续期成功",
|
||||
Steps: []string{
|
||||
"调用 POST /api/v1/platform/tokens/{tokenId}/refresh",
|
||||
},
|
||||
Assertions: []string{
|
||||
"expires_at 延后",
|
||||
"status=active",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-LIFE-005",
|
||||
Name: "吊销成功",
|
||||
Steps: []string{
|
||||
"调用 POST /api/v1/platform/tokens/{tokenId}/revoke",
|
||||
"立即调用 introspect 查询状态",
|
||||
},
|
||||
Assertions: []string{
|
||||
"status 最终为 revoked",
|
||||
"吊销生效延迟 <=5s",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-LIFE-006",
|
||||
Name: "吊销后访问受限接口",
|
||||
Steps: []string{
|
||||
"使用已吊销 token 访问受保护接口",
|
||||
},
|
||||
Assertions: []string{
|
||||
"返回 401 AUTH_TOKEN_INACTIVE",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-LIFE-007",
|
||||
Name: "过期自动失效",
|
||||
Steps: []string{
|
||||
"签发短 TTL token",
|
||||
"等待 token 过期",
|
||||
"调用 introspect 查询状态",
|
||||
},
|
||||
Assertions: []string{
|
||||
"status=expired",
|
||||
"返回不可用错误",
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "TOK-LIFE-008",
|
||||
Name: "viewer 越权写操作",
|
||||
Preconditions: []string{
|
||||
"viewer scope=supply:read",
|
||||
},
|
||||
Steps: []string{
|
||||
"viewer token 调用写接口",
|
||||
},
|
||||
Assertions: []string{
|
||||
"返回 403 AUTH_SCOPE_DENIED",
|
||||
"无写入副作用",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(tc.ID, func(t *testing.T) {
|
||||
t.Skipf("模板用例,待接入实现: %s", tc.Name)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user