Skip to content

Commit

Permalink
make sub readable
Browse files Browse the repository at this point in the history
  • Loading branch information
zetaab committed Feb 21, 2024
1 parent 06f645d commit 5759c32
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 7 deletions.
16 changes: 9 additions & 7 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package common
import (
"context"
"crypto/rsa"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
"time"
Expand Down Expand Up @@ -159,13 +157,17 @@ func (u *User) MakeSub() string {
if u == nil {
return ""
}
sub := StringValue(u.Email)
prefix := "email"
email := StringValue(u.Email)
if u.IsServiceAccount() {
prefix = "m2m"
email = strings.ReplaceAll(email, ServiceAccountPrefix, "")
}
sub := fmt.Sprintf("%s:%s", prefix, email)
if u.Internal != nil && u.Internal.EmployeeID != "" {
sub = u.Internal.EmployeeID
sub = fmt.Sprintf("eid:%s", u.Internal.EmployeeID)
}
sub = strings.ToLower(sub)
b := sha256.Sum256([]byte(sub))
return hex.EncodeToString(b[:])
return strings.ToLower(sub)
}

// ServiceAccountPrefix email domain for service accounts.
Expand Down
46 changes: 46 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,49 @@ func TestStringEmpty(t *testing.T) {
assert.True(t, StringEmpty(""))
assert.False(t, StringEmpty("NONEMPTY"))
}

func TestMakeSub(t *testing.T) {
type testCase struct {
name string
User *User
Sub string
}

testcases := []testCase{
{
name: "empty",
User: nil,
Sub: "",
},
{
name: "human user with email",
User: &User{
Email: String("[email protected]"),
},
Sub: "email:[email protected]",
},
{
name: "machine user with email",
User: &User{
Email: String("my-machine-user@oauth2"),
},
Sub: "m2m:my-machine-user",
},
{
name: "human user with email internal claim",
User: &User{
Email: String("my-machine-user@oauth2"),
Internal: &Internal{
EmployeeID: "X123456",
},
},
Sub: "eid:x123456",
},
}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
assert.Equal(t, tc.Sub, tc.User.MakeSub())
})
}
}

0 comments on commit 5759c32

Please sign in to comment.