From 10fe29b3f044a0bf43589570aa620a51f2c4f0c8 Mon Sep 17 00:00:00 2001 From: Maxim Lebedev Date: Sat, 25 Sep 2021 16:33:41 +0500 Subject: [PATCH] :fire: Removed PKCE package, use same named model instead --- internal/model/pkce.go | 16 +++++++ internal/pkce/pkce.go | 106 ----------------------------------------- 2 files changed, 16 insertions(+), 106 deletions(-) create mode 100644 internal/model/pkce.go delete mode 100644 internal/pkce/pkce.go diff --git a/internal/model/pkce.go b/internal/model/pkce.go new file mode 100644 index 0000000..2c3730a --- /dev/null +++ b/internal/model/pkce.go @@ -0,0 +1,16 @@ +package model + +import ( + "bytes" + "hash" +) + +type PKCE struct { + Challenge string + Method hash.Hash + Verifier string +} + +func (pkce PKCE) IsValid() bool { + return bytes.Equal([]byte(pkce.Challenge), pkce.Method.Sum([]byte(pkce.Verifier))) +} diff --git a/internal/pkce/pkce.go b/internal/pkce/pkce.go deleted file mode 100644 index b0b63cb..0000000 --- a/internal/pkce/pkce.go +++ /dev/null @@ -1,106 +0,0 @@ -package pkce - -import ( - "crypto/md5" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "encoding/base64" - "hash" - "math/rand" - "strings" - "time" - - "gitlab.com/toby3d/indieauth/internal/model" - "gitlab.com/toby3d/indieauth/internal/random" -) - -type Code struct { - Challenge string - ChallengeMethod string - Verifier string -} - -const ( - DefaultMethod string = "S256" - MaximumLength int = 128 - MinimumLength int = 43 -) - -var methods []string = []string{ - "PLAIN", - "MD5", - "S1", - "S256", - "S512", -} - -func New(method string) (*Code, error) { - if method == "" { - method = DefaultMethod - } - - method = strings.ToUpper(method) - - if !contains(methods, method) { - return nil, model.Error{ - Code: "invalid_request", - Description: "the given 'code_challenge_method' is invalid or not supported", - } - } - - return &Code{ - ChallengeMethod: method, - }, nil -} - -func (c *Code) Generate() { - if c.Verifier != "" { - c.generateVerifier(0) - } - - c.generateChallenge() -} - -func (c *Code) generateVerifier(length int) { - if length <= 0 { - length = rand.New(rand.NewSource(time.Now().UnixNano())).Intn(MaximumLength-MinimumLength) + MinimumLength - } - - c.Verifier = base64.URLEncoding.EncodeToString([]byte(random.New().String(length))) -} - -func (c *Code) generateChallenge() { - var h hash.Hash - - switch c.ChallengeMethod { - case "PLAIN": - c.Challenge = c.Verifier - - return - case "MD5": - h = md5.New() - case "S1": - h = sha1.New() - case "S256": - h = sha256.New() - case "S512": - h = sha512.New() - } - - h.Write([]byte(c.Verifier)) - - c.Challenge = base64.URLEncoding.EncodeToString(h.Sum(nil)) -} - -func contains(src []string, find string) bool { - for i := range src { - if src[i] != find { - continue - } - - return true - } - - return false -}