chore: import clean Agent Desk snapshot (2/7)
This commit is contained in:
271
internal/pkg/openidentity/external_identity_test.go
Normal file
271
internal/pkg/openidentity/external_identity_test.go
Normal file
@@ -0,0 +1,271 @@
|
||||
package openidentity
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"agent-desk/internal/pkg/enums"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
testSecret = "shared-identity-secret"
|
||||
testChannelID = "web-main"
|
||||
testUserID = "u_10001"
|
||||
)
|
||||
|
||||
func TestSignAndVerifyExternalIDSignature(t *testing.T) {
|
||||
now := time.Now()
|
||||
signature := SignExternalID(testSecret, testChannelID, testUserID, now)
|
||||
|
||||
if len(signature) != 64 {
|
||||
t.Fatalf("signature = %q, want 64 hex chars", signature)
|
||||
}
|
||||
if strings.ToLower(signature) != signature {
|
||||
t.Fatalf("signature = %q, want lower-case hex", signature)
|
||||
}
|
||||
if !VerifyExternalIDSignature(testSecret, testChannelID, testUserID, signature, now.Unix(), 24*time.Hour, now) {
|
||||
t.Fatal("expected a freshly produced signature to verify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExternalIDSignatureRejects(t *testing.T) {
|
||||
now := time.Now()
|
||||
valid := SignExternalID(testSecret, testChannelID, testUserID, now)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
secret string
|
||||
channelID string
|
||||
externalID string
|
||||
signature string
|
||||
issuedAt int64
|
||||
}{
|
||||
{name: "wrong secret", secret: "other-secret", channelID: testChannelID, externalID: testUserID, signature: valid, issuedAt: now.Unix()},
|
||||
{name: "empty secret disables the feature", secret: "", channelID: testChannelID, externalID: testUserID, signature: valid, issuedAt: now.Unix()},
|
||||
{name: "signature from another channel", secret: testSecret, channelID: "web-other", externalID: testUserID, signature: valid, issuedAt: now.Unix()},
|
||||
{name: "signature for another visitor", secret: testSecret, channelID: testChannelID, externalID: "u_20002", signature: valid, issuedAt: now.Unix()},
|
||||
{name: "truncated signature", secret: testSecret, channelID: testChannelID, externalID: testUserID, signature: valid[:len(valid)-2], issuedAt: now.Unix()},
|
||||
{name: "single flipped nibble", secret: testSecret, channelID: testChannelID, externalID: testUserID, signature: flipLastChar(valid), issuedAt: now.Unix()},
|
||||
{name: "not hex", secret: testSecret, channelID: testChannelID, externalID: testUserID, signature: strings.Repeat("z", 64), issuedAt: now.Unix()},
|
||||
{name: "empty signature", secret: testSecret, channelID: testChannelID, externalID: testUserID, signature: "", issuedAt: now.Unix()},
|
||||
{name: "empty external id", secret: testSecret, channelID: testChannelID, externalID: "", signature: valid, issuedAt: now.Unix()},
|
||||
{name: "missing issued at", secret: testSecret, channelID: testChannelID, externalID: testUserID, signature: valid, issuedAt: 0},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if VerifyExternalIDSignature(tt.secret, tt.channelID, tt.externalID, tt.signature, tt.issuedAt, 24*time.Hour, now) {
|
||||
t.Fatal("expected signature to be rejected")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The timestamp travels as its own field so the host does not have to encode it
|
||||
// inside the signature, but it is covered by the signed bytes, so re-dating a
|
||||
// captured signature breaks verification.
|
||||
func TestVerifyExternalIDSignatureRejectsRedatedSignature(t *testing.T) {
|
||||
now := time.Now()
|
||||
signature := SignExternalID(testSecret, testChannelID, testUserID, now)
|
||||
|
||||
// Claim the signature was issued a minute ago.
|
||||
if VerifyExternalIDSignature(testSecret, testChannelID, testUserID, signature, now.Add(-time.Minute).Unix(), 24*time.Hour, now) {
|
||||
t.Fatal("expected a re-dated signature to be rejected")
|
||||
}
|
||||
// Claim it was issued an hour from now to push it past the window.
|
||||
if VerifyExternalIDSignature(testSecret, testChannelID, testUserID, signature, now.Add(time.Hour).Unix(), 24*time.Hour, now) {
|
||||
t.Fatal("expected a future-dated signature to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExternalIDSignatureExpires(t *testing.T) {
|
||||
issuedAt := time.Now().Add(-25 * time.Hour)
|
||||
signature := SignExternalID(testSecret, testChannelID, testUserID, issuedAt)
|
||||
|
||||
if VerifyExternalIDSignature(testSecret, testChannelID, testUserID, signature, issuedAt.Unix(), 24*time.Hour, time.Now()) {
|
||||
t.Fatal("expected a signature older than the max age to be rejected")
|
||||
}
|
||||
if !VerifyExternalIDSignature(testSecret, testChannelID, testUserID, signature, issuedAt.Unix(), 72*time.Hour, time.Now()) {
|
||||
t.Fatal("expected the same signature to be accepted with a longer max age")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExternalIDSignatureToleratesSmallClockSkew(t *testing.T) {
|
||||
issuedAt := time.Now().Add(2 * time.Minute)
|
||||
signature := SignExternalID(testSecret, testChannelID, testUserID, issuedAt)
|
||||
|
||||
if !VerifyExternalIDSignature(testSecret, testChannelID, testUserID, signature, issuedAt.Unix(), 24*time.Hour, time.Now()) {
|
||||
t.Fatal("expected a small forward clock skew to be tolerated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyExternalIDSignatureDefaultsMaxAge(t *testing.T) {
|
||||
issuedAt := time.Now().Add(-(DefaultIdentityMaxAge - time.Hour))
|
||||
signature := SignExternalID(testSecret, testChannelID, testUserID, issuedAt)
|
||||
|
||||
if !VerifyExternalIDSignature(testSecret, testChannelID, testUserID, signature, issuedAt.Unix(), 0, time.Now()) {
|
||||
t.Fatal("expected the default max age to apply when none is configured")
|
||||
}
|
||||
}
|
||||
|
||||
// A plain embed passes an unsigned external ID. It must keep working, but the
|
||||
// visitor must land as an anonymous guest rather than as an identified user.
|
||||
func TestGetExternalUserUnsignedIDIsGuest(t *testing.T) {
|
||||
ctx, _ := newIdentityContext(map[string]string{
|
||||
"X-External-Id": "guest_abc",
|
||||
"X-External-Name": "Ivan",
|
||||
})
|
||||
|
||||
user, err := GetExternalUser(ctx, Secrets{IdentityHMAC: testSecret, ChannelID: testChannelID})
|
||||
if err != nil {
|
||||
t.Fatalf("unsigned embed must not be rejected: %v", err)
|
||||
}
|
||||
if user.ExternalSource != enums.ExternalSourceGuest {
|
||||
t.Fatalf("ExternalSource = %q, want %q", user.ExternalSource, enums.ExternalSourceGuest)
|
||||
}
|
||||
if user.ExternalID != "guest_abc" {
|
||||
t.Fatalf("ExternalID = %q, want guest_abc", user.ExternalID)
|
||||
}
|
||||
if user.ExternalName != "Ivan" {
|
||||
t.Fatalf("ExternalName = %q, want Ivan", user.ExternalName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetExternalUserSignedIDIsIdentified(t *testing.T) {
|
||||
ctx, _ := newIdentityContext(signedIdentityHeaders(testSecret, testChannelID, testUserID, time.Now()))
|
||||
|
||||
user, err := GetExternalUser(ctx, Secrets{IdentityHMAC: testSecret, ChannelID: testChannelID})
|
||||
if err != nil {
|
||||
t.Fatalf("signed id must be accepted: %v", err)
|
||||
}
|
||||
if user.ExternalSource != enums.ExternalSourceUser {
|
||||
t.Fatalf("ExternalSource = %q, want %q", user.ExternalSource, enums.ExternalSourceUser)
|
||||
}
|
||||
if user.ExternalID != testUserID {
|
||||
t.Fatalf("ExternalID = %q, want %q", user.ExternalID, testUserID)
|
||||
}
|
||||
}
|
||||
|
||||
// The core impersonation case: someone replays a valid signature against a
|
||||
// different visitor ID.
|
||||
func TestGetExternalUserReplayedSignatureDowngradesToGuest(t *testing.T) {
|
||||
ctx, _ := newIdentityContext(signedIdentityHeaders(testSecret, testChannelID, "attacker_1", time.Now()))
|
||||
ctx.Request.Header.Set("X-External-Id", "victim_999")
|
||||
|
||||
user, err := GetExternalUser(ctx, Secrets{IdentityHMAC: testSecret, ChannelID: testChannelID})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if user.ExternalSource != enums.ExternalSourceGuest {
|
||||
t.Fatalf("ExternalSource = %q, want %q for a replayed signature", user.ExternalSource, enums.ExternalSourceGuest)
|
||||
}
|
||||
}
|
||||
|
||||
// Without a configured secret nothing can ever be trusted, which is the safe
|
||||
// default for an existing deployment.
|
||||
func TestGetExternalUserWithoutConfiguredSecretIsGuest(t *testing.T) {
|
||||
ctx, _ := newIdentityContext(signedIdentityHeaders(testSecret, testChannelID, testUserID, time.Now()))
|
||||
|
||||
user, err := GetExternalUser(ctx, Secrets{ChannelID: testChannelID})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if user.ExternalSource != enums.ExternalSourceGuest {
|
||||
t.Fatalf("ExternalSource = %q, want guest when no secret is configured", user.ExternalSource)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetExternalUserExpiredSignatureIsGuest(t *testing.T) {
|
||||
ctx, _ := newIdentityContext(signedIdentityHeaders(testSecret, testChannelID, testUserID, time.Now().Add(-25*time.Hour)))
|
||||
|
||||
user, err := GetExternalUser(ctx, Secrets{IdentityHMAC: testSecret, IdentityMaxAge: 24 * time.Hour, ChannelID: testChannelID})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if user.ExternalSource != enums.ExternalSourceGuest {
|
||||
t.Fatalf("ExternalSource = %q, want guest for an expired signature", user.ExternalSource)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetExternalUserRequiresAnExternalID(t *testing.T) {
|
||||
ctx, _ := newIdentityContext(map[string]string{"X-Channel-Id": testChannelID})
|
||||
|
||||
if _, err := GetExternalUser(ctx, Secrets{IdentityHMAC: testSecret, ChannelID: testChannelID}); err == nil {
|
||||
t.Fatal("expected an error when no external id is supplied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetExternalUserAcceptsIdentityFromQuery(t *testing.T) {
|
||||
now := time.Now()
|
||||
signature := SignExternalID(testSecret, testChannelID, testUserID, now)
|
||||
|
||||
ctx, _ := newIdentityContext(nil)
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet,
|
||||
"/api/customer/session_exchange?externalId="+testUserID+
|
||||
"&externalIdSignature="+signature+
|
||||
"&externalIdSignedAt="+itoa(now.Unix()), nil)
|
||||
|
||||
user, err := GetExternalUser(ctx, Secrets{IdentityHMAC: testSecret, ChannelID: testChannelID})
|
||||
if err != nil {
|
||||
t.Fatalf("signed id from the query string must be accepted: %v", err)
|
||||
}
|
||||
if user.ExternalSource != enums.ExternalSourceUser {
|
||||
t.Fatalf("ExternalSource = %q, want %q", user.ExternalSource, enums.ExternalSourceUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetExternalUserIgnoresGarbageIssuedAt(t *testing.T) {
|
||||
now := time.Now()
|
||||
ctx, _ := newIdentityContext(map[string]string{
|
||||
"X-External-Id": testUserID,
|
||||
"X-External-Id-Signature": SignExternalID(testSecret, testChannelID, testUserID, now),
|
||||
"X-External-Id-Signed-At": "not-a-number",
|
||||
})
|
||||
|
||||
user, err := GetExternalUser(ctx, Secrets{IdentityHMAC: testSecret, ChannelID: testChannelID})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if user.ExternalSource != enums.ExternalSourceGuest {
|
||||
t.Fatalf("ExternalSource = %q, want guest for an unparsable timestamp", user.ExternalSource)
|
||||
}
|
||||
}
|
||||
|
||||
func signedIdentityHeaders(secret, channelID, externalID string, issuedAt time.Time) map[string]string {
|
||||
return map[string]string{
|
||||
"X-External-Id": externalID,
|
||||
"X-External-Id-Signature": SignExternalID(secret, channelID, externalID, issuedAt),
|
||||
"X-External-Id-Signed-At": itoa(issuedAt.UTC().Unix()),
|
||||
"X-External-Name": "Ivan",
|
||||
}
|
||||
}
|
||||
|
||||
func newIdentityContext(headers map[string]string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(recorder)
|
||||
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/customer/session_exchange", nil)
|
||||
for key, value := range headers {
|
||||
ctx.Request.Header.Set(key, value)
|
||||
}
|
||||
return ctx, recorder
|
||||
}
|
||||
|
||||
func flipLastChar(signature string) string {
|
||||
last := signature[len(signature)-1]
|
||||
replacement := byte('0')
|
||||
if last == '0' {
|
||||
replacement = '1'
|
||||
}
|
||||
return signature[:len(signature)-1] + string(replacement)
|
||||
}
|
||||
|
||||
func itoa(value int64) string {
|
||||
return strconv.FormatInt(value, 10)
|
||||
}
|
||||
269
internal/pkg/openidentity/openidentity.go
Normal file
269
internal/pkg/openidentity/openidentity.go
Normal file
@@ -0,0 +1,269 @@
|
||||
package openidentity
|
||||
|
||||
import (
|
||||
"agent-desk/internal/pkg/enums"
|
||||
"agent-desk/internal/pkg/errorsx"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"agent-desk/internal/pkg/httpx/params"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/mlogclub/simple/common/strs"
|
||||
)
|
||||
|
||||
// ExternalUser 外部访客身份(IM 客户),与站内 AuthPrincipal 区分。
|
||||
type ExternalUser struct {
|
||||
ExternalSource enums.ExternalSource `json:"externalSource"`
|
||||
ExternalID string `json:"externalId"`
|
||||
ExternalName string `json:"externalName"`
|
||||
}
|
||||
|
||||
type UserTokenClaims struct {
|
||||
UserID string `json:"userId"`
|
||||
Name string `json:"name"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// Secrets holds everything needed to decide how much a visitor's claimed
|
||||
// identity can be trusted.
|
||||
type Secrets struct {
|
||||
// UserToken is the per-channel secret used to verify a host-issued JWT.
|
||||
UserToken string
|
||||
// IdentityHMAC is the deployment-wide shared secret a host uses to sign an
|
||||
// external visitor ID. When empty, no signature is ever accepted and every
|
||||
// visitor stays anonymous.
|
||||
IdentityHMAC string
|
||||
// IdentityMaxAge bounds how old a signed identity may be. Zero means
|
||||
// DefaultIdentityMaxAge.
|
||||
IdentityMaxAge time.Duration
|
||||
// ChannelID is bound into the signed payload so a signature obtained for one
|
||||
// channel cannot be replayed on another.
|
||||
ChannelID string
|
||||
}
|
||||
|
||||
// DefaultIdentityMaxAge is how long a signed visitor identity stays acceptable
|
||||
// when identity.maxAgeMinutes is not configured.
|
||||
const DefaultIdentityMaxAge = 24 * time.Hour
|
||||
|
||||
// identityFutureSkewTolerance absorbs modest clock differences between the host
|
||||
// platform and this server. It is deliberately far smaller than the max age, so
|
||||
// it widens the replay window by minutes rather than by hours.
|
||||
const identityFutureSkewTolerance = 5 * time.Minute
|
||||
|
||||
// SignedIdentityPayload is the exact byte string a host must sign to have its
|
||||
// external visitor ID treated as identified.
|
||||
//
|
||||
// HMAC-SHA256(identitySecret, channelId + "\n" + externalId + "\n" + issuedAt)
|
||||
//
|
||||
// issuedAt is unix seconds. Lower-case hex output. Three details are deliberate:
|
||||
//
|
||||
// - The channel id is included because CustomerIdentity is keyed by
|
||||
// (source, externalId) globally, so without it a signature minted for one
|
||||
// channel would assert the same identity on every other channel.
|
||||
// - The timestamp is inside the signed bytes even though it also travels as its
|
||||
// own field, so it cannot be re-dated without breaking the signature. This
|
||||
// bounds how long a leaked pair stays usable; it is not a defence against key
|
||||
// recovery, which HMAC does not permit in the first place.
|
||||
// - Nothing is encrypted. The signature passes through the visitor's browser,
|
||||
// so a cipher would hide nothing from the party we are defending against.
|
||||
func SignedIdentityPayload(channelID, externalID string, issuedAt time.Time) string {
|
||||
return channelID + "\n" + externalID + "\n" + strconv.FormatInt(issuedAt.UTC().Unix(), 10)
|
||||
}
|
||||
|
||||
// SignExternalID produces the signature a host sends alongside its external
|
||||
// visitor ID and the issuedAt value it was signed over. Exported so integrators
|
||||
// and tests share one definition.
|
||||
func SignExternalID(secret, channelID, externalID string, issuedAt time.Time) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write([]byte(SignedIdentityPayload(channelID, externalID, issuedAt)))
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// SignExternalIDNow is the form a host calls: sign the id as of now.
|
||||
func SignExternalIDNow(secret, channelID, externalID string) (signature string, issuedAt int64) {
|
||||
now := time.Now()
|
||||
return SignExternalID(secret, channelID, externalID, now), now.UTC().Unix()
|
||||
}
|
||||
|
||||
// VerifyExternalIDSignature reports whether signature is a currently valid
|
||||
// signature for externalID on this channel. A blank secret disables the feature
|
||||
// rather than failing, so an unconfigured deployment keeps today's behaviour.
|
||||
func VerifyExternalIDSignature(secret, channelID, externalID, signature string, issuedAtUnix int64, maxAge time.Duration, now time.Time) bool {
|
||||
if strs.IsBlank(secret) || strs.IsBlank(externalID) || strs.IsBlank(signature) || issuedAtUnix <= 0 {
|
||||
return false
|
||||
}
|
||||
if maxAge <= 0 {
|
||||
maxAge = DefaultIdentityMaxAge
|
||||
}
|
||||
|
||||
issuedAt := time.Unix(issuedAtUnix, 0)
|
||||
age := now.Sub(issuedAt)
|
||||
if age > maxAge || age < -identityFutureSkewTolerance {
|
||||
return false
|
||||
}
|
||||
|
||||
expected := SignExternalID(secret, channelID, externalID, issuedAt)
|
||||
// hmac.Equal is constant time, so a caller cannot recover the expected
|
||||
// signature byte by byte by timing the rejection.
|
||||
return hmac.Equal([]byte(expected), []byte(strings.TrimSpace(signature)))
|
||||
}
|
||||
|
||||
func GetExternalUser(ctx *gin.Context, secrets Secrets) (*ExternalUser, error) {
|
||||
if userToken := getUserToken(ctx); strs.IsNotBlank(userToken) {
|
||||
claims, err := verifyUserToken(userToken, secrets.UserToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ExternalUser{
|
||||
ExternalSource: enums.ExternalSourceUser,
|
||||
ExternalID: claims.UserID,
|
||||
ExternalName: claims.Name,
|
||||
}, nil
|
||||
}
|
||||
return getExternalIDUser(ctx, secrets)
|
||||
}
|
||||
|
||||
func verifyUserToken(userToken, secret string) (*UserTokenClaims, error) {
|
||||
if strs.IsBlank(userToken) {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0263")
|
||||
}
|
||||
if strs.IsBlank(secret) {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0266")
|
||||
}
|
||||
|
||||
claims := &UserTokenClaims{}
|
||||
token, err := jwt.ParseWithClaims(userToken, claims, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, errors.New("unsupported signing method")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
}, jwt.WithExpirationRequired(), jwt.WithValidMethods([]string{
|
||||
jwt.SigningMethodHS256.Alg(),
|
||||
jwt.SigningMethodHS384.Alg(),
|
||||
jwt.SigningMethodHS512.Alg(),
|
||||
}))
|
||||
if err != nil {
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0264")
|
||||
}
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0265")
|
||||
}
|
||||
if token == nil || !token.Valid {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0265")
|
||||
}
|
||||
|
||||
if strs.IsBlank(claims.UserID) {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0262")
|
||||
}
|
||||
if strs.IsBlank(claims.Name) {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0261")
|
||||
}
|
||||
if claims.ExpiresAt == nil {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0264")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func getUserToken(ctx *gin.Context) string {
|
||||
auth := strings.TrimSpace(ctx.GetHeader("Authorization"))
|
||||
if len(auth) > 7 && strings.EqualFold(auth[:7], "Bearer ") {
|
||||
if token := strings.TrimSpace(auth[7:]); token != "" {
|
||||
return token
|
||||
}
|
||||
}
|
||||
userToken, _ := params.Get(ctx, "userToken")
|
||||
return strings.TrimSpace(userToken)
|
||||
}
|
||||
|
||||
// getExternalIDUser resolves the visitor from an external ID. A host that signs
|
||||
// its ID with the shared identity secret is trusted and treated as identified;
|
||||
// anything else, including a missing or wrong signature, is downgraded to an
|
||||
// anonymous guest rather than rejected, so the plain embed keeps working.
|
||||
func getExternalIDUser(ctx *gin.Context, secrets Secrets) (*ExternalUser, error) {
|
||||
externalID := getExternalID(ctx)
|
||||
if strs.IsBlank(externalID) {
|
||||
return nil, errorsx.UnauthorizedI18n("error.e0262")
|
||||
}
|
||||
externalID = strings.TrimSpace(externalID)
|
||||
externalName := getExternalName(ctx)
|
||||
|
||||
if VerifyExternalIDSignature(secrets.IdentityHMAC, secrets.ChannelID, externalID, getExternalIDSignature(ctx), getExternalIDIssuedAt(ctx), secrets.IdentityMaxAge, time.Now()) {
|
||||
return &ExternalUser{
|
||||
ExternalSource: enums.ExternalSourceUser,
|
||||
ExternalID: externalID,
|
||||
ExternalName: externalName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &ExternalUser{
|
||||
ExternalSource: enums.ExternalSourceGuest,
|
||||
ExternalID: externalID,
|
||||
ExternalName: externalName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getExternalID(ctx *gin.Context) string {
|
||||
externalID := ctx.GetHeader("X-External-Id")
|
||||
if strs.IsBlank(externalID) {
|
||||
externalID, _ = params.Get(ctx, "externalId")
|
||||
}
|
||||
return externalID
|
||||
}
|
||||
|
||||
func getExternalIDSignature(ctx *gin.Context) string {
|
||||
signature := ctx.GetHeader("X-External-Id-Signature")
|
||||
if strs.IsBlank(signature) {
|
||||
signature, _ = params.Get(ctx, "externalIdSignature")
|
||||
}
|
||||
return signature
|
||||
}
|
||||
|
||||
// getExternalIDIssuedAt reads the unix-seconds timestamp the host signed. It is
|
||||
// covered by the signature, so a tampered value simply fails to match.
|
||||
func getExternalIDIssuedAt(ctx *gin.Context) int64 {
|
||||
raw := ctx.GetHeader("X-External-Id-Signed-At")
|
||||
if strs.IsBlank(raw) {
|
||||
raw, _ = params.Get(ctx, "externalIdSignedAt")
|
||||
}
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0
|
||||
}
|
||||
issuedAt, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return issuedAt
|
||||
}
|
||||
|
||||
func getExternalName(ctx *gin.Context) string {
|
||||
externalName := ctx.GetHeader("X-External-Name")
|
||||
if strs.IsBlank(externalName) {
|
||||
externalName, _ = params.Get(ctx, "externalName")
|
||||
}
|
||||
if strs.IsNotBlank(externalName) {
|
||||
externalName, _ = url.QueryUnescape(externalName)
|
||||
}
|
||||
return externalName
|
||||
}
|
||||
|
||||
func decodeExternalDisplayName(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
dec, err := url.QueryUnescape(s)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
return strings.TrimSpace(dec)
|
||||
}
|
||||
86
internal/pkg/openidentity/openidentity_test.go
Normal file
86
internal/pkg/openidentity/openidentity_test.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package openidentity
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func TestVerifyUserTokenOK(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}, "secret")
|
||||
|
||||
claims, err := verifyUserToken(token, "secret")
|
||||
if err != nil {
|
||||
t.Fatalf("expected token to verify: %v", err)
|
||||
}
|
||||
if claims.UserID != "u_10001" || claims.Name != "张三" {
|
||||
t.Fatalf("unexpected claims: %#v", claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenUsesJWTHeaderAlgorithm(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS384, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}, "secret")
|
||||
|
||||
claims, err := verifyUserToken(token, "secret")
|
||||
if err != nil {
|
||||
t.Fatalf("expected HS384 token to verify from JWT header: %v", err)
|
||||
}
|
||||
if claims.UserID != "u_10001" || claims.Name != "张三" {
|
||||
t.Fatalf("unexpected claims: %#v", claims)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenRejectsInvalidSignature(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(time.Hour).Unix(),
|
||||
}, "secret")
|
||||
|
||||
if _, err := verifyUserToken(token, "other-secret"); err == nil {
|
||||
t.Fatalf("expected invalid signature to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenRejectsExpiredToken(t *testing.T) {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, map[string]any{
|
||||
"userId": "u_10001",
|
||||
"name": "张三",
|
||||
"exp": time.Now().Add(-time.Minute).Unix(),
|
||||
}, "secret")
|
||||
|
||||
if _, err := verifyUserToken(token, "secret"); err == nil {
|
||||
t.Fatalf("expected expired token to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyUserTokenRequiresUserIDAndName(t *testing.T) {
|
||||
tests := []map[string]any{
|
||||
{"name": "张三", "exp": time.Now().Add(time.Hour).Unix()},
|
||||
{"userId": "u_10001", "exp": time.Now().Add(time.Hour).Unix()},
|
||||
}
|
||||
for _, payload := range tests {
|
||||
token := signTestUserToken(t, jwt.SigningMethodHS256, payload, "secret")
|
||||
if _, err := verifyUserToken(token, "secret"); err == nil {
|
||||
t.Fatalf("expected payload %#v to fail", payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func signTestUserToken(t *testing.T, method jwt.SigningMethod, payload map[string]any, secret string) string {
|
||||
t.Helper()
|
||||
token, err := jwt.NewWithClaims(method, jwt.MapClaims(payload)).SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
Reference in New Issue
Block a user