系统列表
Distributed Systems in Go:生产级分布式平台 SDK 与微服务实战
专栏《分布式 Go 系统工程》配套完整代码实战工程,涵盖并发模型、消息队列适配、Saga 编排、弹性容错与可观测性等生产级模式。
README.mdSYSTEM.mdcmd/auth/main.gocmd/gateway/main.gocmd/orders/main.goconfig/grafana/datasources/datasources.yamlconfig/prometheus.yamlconfig/tempo.yamldeploy/kube/orderflow-infra.yamldocker-compose.ymlgo.modgo.suminternal/auth/handler.gointernal/auth/service.gointernal/domain/events.gointernal/inventory/handler.gointernal/inventory/service.gointernal/notifications/service.gointernal/orders/handler.gointernal/orders/service.gointernal/payment/service.gomigrations/000001_init_schema.up.sqlpkg/platform/auth/auth_test.gopkg/platform/auth/claims.gopkg/platform/auth/jwks.gopkg/platform/auth/middleware.gopkg/platform/auth/password.gopkg/platform/auth/token.gopkg/platform/cli/cli_test.gopkg/platform/cli/health.gopkg/platform/concurrency/context.gopkg/platform/concurrency/shutdown.gopkg/platform/concurrency/shutdown_test.gopkg/platform/concurrency/workerpool.gopkg/platform/concurrency/workerpool_test.gopkg/platform/config/config_test.gopkg/platform/config/loader.gopkg/platform/consistency/consistency_test.gopkg/platform/consistency/idempotency.gopkg/platform/consistency/optimistic.gopkg/platform/consistency/saga.gopkg/platform/ctxutil/context.gopkg/platform/ctxutil/context_test.gopkg/platform/ctxutil/keys.gopkg/platform/database/database_test.gopkg/platform/database/errors.gopkg/platform/database/migrate.gopkg/platform/database/pool.gopkg/platform/database/retry.gopkg/platform/database/tx.gopkg/platform/messaging/fake.gopkg/platform/messaging/fake_test.gopkg/platform/messaging/interfaces.gopkg/platform/messaging/kafka/consumer.gopkg/platform/messaging/kafka/producer.gopkg/platform/messaging/nats/publisher.gopkg/platform/messaging/nats/subscriber.gopkg/platform/messaging/schema.gopkg/platform/middleware/bodyclose.gopkg/platform/middleware/chain.gopkg/platform/middleware/cors.gopkg/platform/middleware/errors.gopkg/platform/middleware/health.gopkg/platform/middleware/logging.gopkg/platform/middleware/middleware_test.gopkg/platform/middleware/recover.gopkg/platform/middleware/requestid.gopkg/platform/middleware/timeout.gopkg/platform/observability/context.gopkg/platform/observability/logger.gopkg/platform/observability/metrics.gopkg/platform/observability/observability_test.gopkg/platform/observability/tracing.gopkg/platform/orchestration/budget.gopkg/platform/orchestration/degrade.gopkg/platform/orchestration/fanout.gopkg/platform/orchestration/orchestration_test.gopkg/platform/resilience/circuit.gopkg/platform/resilience/resilience_test.gopkg/platform/resilience/retry.gotests/live_infra_test.gotests/orderflow_integration_test.go
pkg/platform/auth/token.go
| package auth |
| import ( |
| "crypto/ecdsa" |
| "crypto/rand" |
| "crypto/sha256" |
| "encoding/base64" |
| "encoding/json" |
| "errors" |
| "fmt" |
| "math/big" |
| "strings" |
| "time" |
| ) |
| var ( |
| ErrInvalidToken = errors.New("invalid token format") |
| ErrExpiredToken = errors.New("token is expired") |
| ErrInvalidSig = errors.New("signature verification failed") |
| ErrUnsupportedAlg = errors.New("unsupported signing algorithm") |
| ) |
| type tokenHeader struct { |
| Alg string `json:"alg"` |
| Typ string `json:"typ"` |
| Kid string `json:"kid,omitempty"` |
| } |
| // GenerateToken signs claims using ECDSA (ES256) and returns a compact JWT string. |
| func GenerateToken(claims *Claims, key *ecdsa.PrivateKey, kid string) (string, error) { |
| if claims.IssuedAt.IsZero() { |
| claims.IssuedAt = time.Now() |
| } |
| if claims.ExpiresAt.IsZero() { |
| claims.ExpiresAt = claims.IssuedAt.Add(24 * time.Hour) |
| } |
| header := tokenHeader{ |
| Alg: "ES256", |
| Typ: "JWT", |
| Kid: kid, |
| } |
| hBytes, err := json.Marshal(header) |
| if err != nil { |
| return "", fmt.Errorf("marshal header: %w", err) |
| } |
| cBytes, err := json.Marshal(claims) |
| if err != nil { |
| return "", fmt.Errorf("marshal claims: %w", err) |
| } |
| hB64 := base64.RawURLEncoding.EncodeToString(hBytes) |
| cB64 := base64.RawURLEncoding.EncodeToString(cBytes) |
| signingInput := hB64 + "." + cB64 |
| digest := sha256.Sum256([]byte(signingInput)) |
| r, s, err := ecdsa.Sign(rand.Reader, key, digest[:]) |
| if err != nil { |
| return "", fmt.Errorf("ecdsa sign: %w", err) |
| } |
| // IEEE P1363 encoding for ES256: 32 bytes r + 32 bytes s |
| curveByteSize := 32 |
| sig := make([]byte, curveByteSize*2) |
| rBytes := r.Bytes() |
| sBytes := s.Bytes() |
| copy(sig[curveByteSize-len(rBytes):curveByteSize], rBytes) |
| copy(sig[2*curveByteSize-len(sBytes):], sBytes) |
| sigB64 := base64.RawURLEncoding.EncodeToString(sig) |
| return signingInput + "." + sigB64, nil |
| } |
| // ValidateToken verifies the JWT signature against the public key and returns parsed Claims. |
| func ValidateToken(tokenStr string, pub *ecdsa.PublicKey) (*Claims, error) { |
| parts := strings.Split(tokenStr, ".") |
| if len(parts) != 3 { |
| return nil, ErrInvalidToken |
| } |
| hBytes, err := base64.RawURLEncoding.DecodeString(parts[0]) |
| if err != nil { |
| return nil, fmt.Errorf("decode header: %w", err) |
| } |
| var header tokenHeader |
| if err := json.Unmarshal(hBytes, &header); err != nil { |
| return nil, fmt.Errorf("unmarshal header: %w", err) |
| } |
| if header.Alg != "ES256" { |
| return nil, ErrUnsupportedAlg |
| } |
| sig, err := base64.RawURLEncoding.DecodeString(parts[2]) |
| if err != nil || len(sig) != 64 { |
| return nil, ErrInvalidSig |
| } |
| r := new(big.Int).SetBytes(sig[:32]) |
| s := new(big.Int).SetBytes(sig[32:]) |
| signingInput := parts[0] + "." + parts[1] |
| digest := sha256.Sum256([]byte(signingInput)) |
| if !ecdsa.Verify(pub, digest[:], r, s) { |
| return nil, ErrInvalidSig |
| } |
| cBytes, err := base64.RawURLEncoding.DecodeString(parts[1]) |
| if err != nil { |
| return nil, fmt.Errorf("decode claims: %w", err) |
| } |
| var claims Claims |
| if err := json.Unmarshal(cBytes, &claims); err != nil { |
| return nil, fmt.Errorf("unmarshal claims: %w", err) |
| } |
| if !claims.Valid() { |
| return nil, ErrExpiredToken |
| } |
| return &claims, nil |
| } |