Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TT-2539] added access/transaction logs #6616

Open
wants to merge 91 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
91 commits
Select commit Hold shift + click to select a range
44c3967
Revert "Revert "[TT-2539] added access/transaction logs" (#6524)"
LLe27 Oct 8, 2024
f4470c9
[TT-13186/TT-13199] implement upstream basic authentication (#6596)
jeffy-mathew Oct 9, 2024
d0a04e0
[TT-13243] Test/ci improvements (#6611)
titpetric Oct 9, 2024
9b1ff8d
[TT-13139] Request times out in some cases when sending input via htt…
buraksezer Oct 9, 2024
0acea13
[TT-13238] Clean up RPC data model (#6608)
titpetric Oct 9, 2024
8ef7c6d
[TT-13242] Moved/Cleaned up nestedApiDefinition to model.MergedAPI (#…
titpetric Oct 9, 2024
667a549
[TT-13258] exp/workflow-lint: Update to latest known actions (#6620)
buger Oct 10, 2024
86a3d28
[TT-13266] Fix python tests (#6624)
titpetric Oct 10, 2024
e31a08f
[TT-12897] Merge path based permissions when combining policies (#6597)
titpetric Oct 10, 2024
849d346
[TT-13262] Fix/delete build cache for plugin compiler (#6623)
titpetric Oct 10, 2024
71941ea
[TT-8004/TT-13092]enable validate request middleware during OAS impor…
jeffy-mathew Oct 11, 2024
69344f9
[TT-13186/TT-13199] replace auth header instead of adding auth header…
jeffy-mathew Oct 11, 2024
74c514c
[TT-13280] Adjust golangci-lint to raise up errors in PRs directly (#…
titpetric Oct 14, 2024
6b687a2
TT-13130 updated version of gorpc library and prevent panic on start …
sredxny Oct 14, 2024
2b577bd
[TT-13184] Implement OAuth 2.0 Client Credentials Flow for GW authent…
andrei-tyk Oct 14, 2024
24058e8
[TT-12897/TT-13284] Add additional partitioned test case, fix orderin…
titpetric Oct 15, 2024
35500ee
[TT-12814] Make schema more flexible, don't enforce additionalPropert…
titpetric Oct 15, 2024
e004269
refactor access logs and tests
Oct 15, 2024
8f37f4b
TT-13130 update gorpc version (#6644)
sredxny Oct 16, 2024
33db0e2
Tt 13184 Upstream OAuth2 updates to fix TTL issue (#6643)
andrei-tyk Oct 17, 2024
cf5aeb0
[TT-12990] fix upstream endpoint RL not considering endpoint method (…
jeffy-mathew Oct 18, 2024
aee8137
TT-13269 - Refactor/streams (#6593)
titpetric Oct 19, 2024
1fcb4fd
[TT-12702] revert wrappedServeHTTP to use recordDetail (#6654)
jeffy-mathew Oct 23, 2024
14d8e3e
[TT-11426/TT-13322] Add deprecation notice for external OAuth middlew…
jeffy-mathew Oct 24, 2024
93f430c
[TT-13185] Implement Password Flow OAuth (#6649)
andrei-tyk Oct 24, 2024
c1b4429
[TT-13381] Linters should only work for PRs (#6664)
titpetric Oct 24, 2024
cea1df4
[TT-12417] Do not delete keys on synchronization (#6642)
mativm02 Oct 24, 2024
917f0ef
[TT-13185] reorganize contract in upstream oauth (#6668)
andrei-tyk Oct 25, 2024
deaa79e
[TT-13271] custom oauth response fields (#6660)
andrei-tyk Oct 25, 2024
29bc56a
[TT-13400] Fixing OTel CI (#6659)
mativm02 Oct 25, 2024
f1b55b5
[TT-13359] move upstream basic auth to ee package (#6669)
jeffy-mathew Oct 27, 2024
bb09d39
[TT-13185] upstream oauth allowed_authorize_types not being filled on…
andrei-tyk Oct 28, 2024
dafbab6
TT-13185, fixed lines lost in merge conflicts (#6681)
andrei-tyk Oct 29, 2024
b42113c
added logic to check for access log custom template
Oct 29, 2024
479dcd9
[TT-13375/TT-13422] Add validation rules for Upstream auth (#6680)
jeffy-mathew Oct 30, 2024
0c8a86a
[TT-13008]: modified default streams logger (#6682)
kofoworola Oct 30, 2024
3114d14
[TT-13185] fix missing extracts (#6685)
andrei-tyk Oct 30, 2024
3633678
[TT-11426/TT-13322]add deprecation notice for oidc middleware (#6686)
jeffy-mathew Oct 31, 2024
4a14e3a
[TT-13201] Streams Definition Validator (#6656)
buraksezer Oct 31, 2024
85e8a94
TT-13271, fix for token metadata not being cached (#6689)
andrei-tyk Nov 1, 2024
9335a51
[TT-12885] Add plugin development guide for manual builds (#6598)
titpetric Nov 2, 2024
fa63dbe
[TT-13391] Move upstream OAuth to EE (#6684)
andrei-tyk Nov 5, 2024
2611a47
improve error handling of streams in non-ee version (TT-13269) (#6691)
pvormste Nov 6, 2024
d7bed08
[TT-13375] Improved Upstream Auth validation rules (#6694)
lghiur Nov 6, 2024
810f981
add stream analytics to ee (TT-13233) (#6671)
pvormste Nov 6, 2024
36afb48
[TT-13271] Make enabled and allowedAuthorizeTypes required fields (#6…
lghiur Nov 7, 2024
79a393e
[TT-13508] Streams poor performance when reconnecting to a Streams AP…
buraksezer Nov 8, 2024
6db3156
[TT-13422] Do not allow empty string in upstream auth configuration s…
jeffy-mathew Nov 8, 2024
adb1f25
[TT-13508] Downgrade Bento to v1.2.0 and use our own fork to cherry-p…
buraksezer Nov 8, 2024
43ac641
[TT-13535/TT-13566] make upstream oauth password client secret not re…
jeffy-mathew Nov 13, 2024
f0fcb3f
Revert "[TT-13422] Do not allow empty string in upstream auth configu…
jeffy-mathew Nov 14, 2024
c8f21dc
[TT-13535/TT-13566] Make upstream oauth flow client secret omitempty …
jeffy-mathew Nov 18, 2024
cb62825
[TT-13485] update dependencies with vulnerabilities reported (#6711)
jeffy-mathew Nov 19, 2024
e19f5cf
[TT-13475] update OAS version (#6712)
lghiur Nov 19, 2024
6eb5178
[TT-13535/TT-13566] Ease up required fields in classic API schema (#6…
jeffy-mathew Nov 19, 2024
72dd619
[TT-13607] Only import components/io and components/kafka (#6720)
buraksezer Nov 20, 2024
7081f2e
[TT-13507] Fix for custom domains with substring listen path (#6705)
andrei-tyk Nov 21, 2024
35f58ac
[TT-13658] added missing logger from provider initialisation (#6729)
andrei-tyk Nov 28, 2024
8bd75f0
[TT-13439] update response content-length when response body is modif…
jeffy-mathew Dec 2, 2024
b0206d2
[TT-13670] Decouple OAuthManager behind interface (#6735)
titpetric Dec 2, 2024
7fbd718
[TT-13390] Silently skip loading bundle on managment node (#6739)
jeffy-mathew Dec 4, 2024
3162814
[TT-13669] Add pre-commit, pre-push hooks (#6733)
jeffy-mathew Dec 4, 2024
7fc67f7
[TT-13142] Fix panic when detailed analytics is turned on with SSE st…
jeffy-mathew Dec 5, 2024
e805241
[TT-13695] Testing fixes, skip dangerous tests (#6736)
titpetric Dec 5, 2024
ff3679e
[testing/gha] Cache is handled by setup/go, this blocks (#6749)
titpetric Dec 6, 2024
178848d
[DX-1423] Update TYK_GW_SECRETS definition (#6360)
dcs3spp Dec 6, 2024
9439737
[TT-12775] Request size limit breaks GET and DELETE requests (#6734)
buraksezer Dec 9, 2024
9c5a43b
[TT-12775] Add request size limit test for POST, PUT and PATCH method…
buraksezer Dec 9, 2024
4af6152
[TT-12710]deleting All Partitioned Policies a Key is linked to does n…
andrei-tyk Dec 11, 2024
9916296
[TT-13155] Explicitly copy BaseMiddleware for each middleware that ta…
titpetric Dec 12, 2024
abc3fa6
TT-13513 TT-12767 TT-12768 ensure to save oauth clients locally when …
sredxny Dec 12, 2024
accfde0
[TT-13715] Upgrade to Bento v1.4.0 (#6762)
buraksezer Dec 12, 2024
f48eb98
[TT-13608] Issues with custom scalar in query variable (#6766)
buraksezer Dec 12, 2024
524a6b6
[TT-13217] Add updated dockerfile for python, test with 5.3.0/5.3.6-r…
titpetric Dec 13, 2024
1b2df0e
[TT-13021]Transfer encoding fix (#6770)
andrei-tyk Dec 16, 2024
2887a4a
[TT-11711] Fix listenpath validation (#6772)
titpetric Dec 16, 2024
2df5817
[TT-12495] Add support for RSASSA-PSS signed JWTs (#6368)
sedkis Dec 17, 2024
1deb1e6
[TT-13021], fixed missing lines (#6787)
andrei-tyk Dec 18, 2024
51e50c3
[TT-13753] Fix sonarcloud coverage via upload-artifact (#6790)
titpetric Dec 19, 2024
d59ae8c
[TT-12741] Looped ap is wrongfully inherit the caller's authenticatio…
buraksezer Dec 19, 2024
3a9b536
[TT-13741] [master] exp/modcheck: Update go.mod dependencies (#6794)
buger Dec 19, 2024
465d3ac
[TT-13564] Add classic to OAS translation guide (#6774)
jeffy-mathew Dec 20, 2024
d46c967
[TT-13742] Update swagger to 5.7.1 (#6803)
lghiur Dec 20, 2024
0276c06
[TT-13761] add batch request to the latest open api specs (#6797)
yurisasuke Dec 22, 2024
f65d41a
Merging to master: Merging to release-5.3: [TT-13769] Extend plugin c…
buger Dec 31, 2024
acb2e19
[TT-13766] Bump newrelic dependency (#6809)
titpetric Jan 3, 2025
1d1ba4e
rebase the PR and fixed merge conflicts
Jan 7, 2025
1c320f7
refactor access logs and tests
Oct 15, 2024
5f3448d
fixed merge conflicts with rebase
Jan 7, 2025
2319ba9
fix merge conflicts and local branch
Jan 7, 2025
af3465b
fix linter issues and test cases
Jan 7, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ session_state_gen_test.go
__pycache__/
tyk.test
tyk-gateway.pid
*.go-e

tyk_linux_*
.aider*
Expand Down
9 changes: 9 additions & 0 deletions cli/linter/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,15 @@
"type": "string",
"enum": ["", "standard", "json"]
},
"access_logs": {
"type": ["object", "null"],
"additionalProperties": false,
"properties": {
"enabled": {
"type": "boolean"
}
}
},
"enable_http_profiler": {
"type": "boolean"
},
Expand Down
10 changes: 10 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,12 @@ type AnalyticsConfigConfig struct {
SerializerType string `json:"serializer_type"`
}

// AccessLogsConfig defines the type of transactions logs printed to stdout
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// AccessLogsConfig defines the type of transactions logs printed to stdout
// AccessLogsConfig defines the type of transactions logs printed to stdout.

type AccessLogsConfig struct {
// Enable the transaction logs. Default: false
Copy link
Contributor

@titpetric titpetric Jan 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Enable the transaction logs. Default: false
// Enabled controls enabling the transaction logs. Default: false.

Enabled bool `json:"enabled"`
}

type HealthCheckConfig struct {
// Setting this value to `true` will enable the health-check endpoint on /Tyk/health.
EnableHealthChecks bool `json:"enable_health_checks"`
Expand Down Expand Up @@ -1009,6 +1015,10 @@ type Config struct {
// If not set or left empty, it will default to `standard`.
LogFormat string `json:"log_format"`

// You can configure the transaction logs to be turned on
// If not set or left empty, it will default to 'false'
Comment on lines +1025 to +1026
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// You can configure the transaction logs to be turned on
// If not set or left empty, it will default to 'false'
// AccessLogs configures the output for access logs.
// If not configured, the access log is disabled.

AccessLogs AccessLogsConfig `json:"access_logs"`

// Section for configuring OpenTracing support
// Deprecated: use OpenTelemetry instead.
Tracer Tracer `json:"tracing"`
Expand Down
7 changes: 7 additions & 0 deletions gateway/handler_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,13 @@ func (e *ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, errMs
log.WithError(err).Error("could not store analytic record")
}
}

// Print the transaction logs for error situations if enabled. Success transaction
// logs will be handled by the "handler_success.go"
if e.Spec.GlobalConfig.AccessLogs.Enabled {
e.recordAccessLog(r, response, nil)
}

// Report in health check
reportHealthValue(e.Spec, BlockedRequestLog, "-1")
}
51 changes: 51 additions & 0 deletions gateway/handler_error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"strings"
"testing"

"github.com/TykTechnologies/tyk/config"

"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/test"
)
Expand Down Expand Up @@ -122,3 +124,52 @@ func TestHandleDefaultErrorJSON(t *testing.T) {
})

}

func BenchmarkErrorLogTransaction(b *testing.B) {
b.Run("AccessLogs enabled with Hashkeys set to true", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = true
globalConf.AccessLogs.Enabled = true
}
benchmarkErrorLogTransaction(b, conf)

})
b.Run("AccessLogs enabled with Hashkeys set to false", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = false
globalConf.AccessLogs.Enabled = true
}
benchmarkErrorLogTransaction(b, conf)
})

b.Run("AccessLogs disabled with Hashkeys set to true", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = true
globalConf.AccessLogs.Enabled = false
}
benchmarkErrorLogTransaction(b, conf)
})

b.Run("AccessLogs disabled with Hashkeys set to false", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = false
globalConf.AccessLogs.Enabled = false
}
benchmarkErrorLogTransaction(b, conf)
})
}

func benchmarkErrorLogTransaction(b *testing.B, conf func(globalConf *config.Config)) {
b.ReportAllocs()
b.Helper()
b.ResetTimer()

ts := StartTest(conf)
defer ts.Close()

for i := 0; i < b.N; i++ {
ts.Run(b, test.TestCase{
Code: http.StatusNotFound,
})
}
}
10 changes: 8 additions & 2 deletions gateway/handler_success.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import (
"strings"
"time"

graphqlinternal "github.com/TykTechnologies/tyk/internal/graphql"

"github.com/TykTechnologies/tyk/apidef"
graphqlinternal "github.com/TykTechnologies/tyk/internal/graphql"
"github.com/TykTechnologies/tyk/internal/httputil"

"github.com/TykTechnologies/tyk-pump/analytics"
Expand Down Expand Up @@ -382,8 +381,15 @@ func (s *SuccessHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) *http
Upstream: int64(DurationToMillisecond(resp.UpstreamLatency)),
}
s.RecordHit(r, latency, resp.Response.StatusCode, resp.Response, false)

// Don't print a transaction log there is no "resp", that indicates an error.
// In error situations, transaction log is already printed by "handler_error.go"
if s.Spec.GlobalConfig.AccessLogs.Enabled {
s.recordAccessLog(r, resp.Response, &latency)
}
}
log.Debug("Done proxy")

return nil
}

Expand Down
55 changes: 55 additions & 0 deletions gateway/handler_success_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,3 +326,58 @@ func TestAnalyticsIgnoreSubgraph(t *testing.T) {
)
assert.NoError(t, err)
}

func BenchmarkSuccessLogTransaction(b *testing.B) {
b.Run("AccessLogs enabled with Hashkeys set to true", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = true
globalConf.AccessLogs.Enabled = true
}
benchmarkSuccessLogTransaction(b, conf)

})
b.Run("AccessLogs enabled with Hashkeys set to false", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = false
globalConf.AccessLogs.Enabled = true
}
benchmarkSuccessLogTransaction(b, conf)
})
b.Run("AccessLogs disabled with Hashkeys set to true", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = true
globalConf.AccessLogs.Enabled = false
}
benchmarkSuccessLogTransaction(b, conf)
})
b.Run("AccessLogs disabled with Hashkeys set to false", func(b *testing.B) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = false
globalConf.AccessLogs.Enabled = false
}
benchmarkSuccessLogTransaction(b, conf)
})
}

func benchmarkSuccessLogTransaction(b *testing.B, conf func(globalConf *config.Config)) {
b.ReportAllocs()
b.Helper()
b.ResetTimer()

ts := StartTest(conf)
defer ts.Close()

API := BuildAPI(func(spec *APISpec) {
spec.Name = "test-api"
spec.APIID = "test-api-id"
spec.Proxy.ListenPath = "/"
})[0]

ts.Gw.LoadAPI(API)

for i := 0; i < b.N; i++ {
ts.Run(b, test.TestCase{
Code: http.StatusOK,
})
}
}
16 changes: 16 additions & 0 deletions gateway/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ import (
"strconv"
"time"

"github.com/TykTechnologies/tyk-pump/analytics"

"github.com/TykTechnologies/tyk/internal/cache"
"github.com/TykTechnologies/tyk/internal/event"
"github.com/TykTechnologies/tyk/internal/httputil/accesslog"
"github.com/TykTechnologies/tyk/internal/otel"
"github.com/TykTechnologies/tyk/internal/policy"
"github.com/TykTechnologies/tyk/rpc"
Expand Down Expand Up @@ -376,6 +379,19 @@ func (t *BaseMiddleware) ApplyPolicies(session *user.SessionState) error {
return store.Apply(session)
}

// recordAccessLog is only used for Success/Error handler
func (t *BaseMiddleware) recordAccessLog(req *http.Request, resp *http.Response, latency *analytics.Latency) {
hashKeys := t.Gw.GetConfig().HashKeys

accessLog := accesslog.NewRecord(t.Spec.APIID, t.Spec.OrgID)
accessLog.WithAuthToken(req, hashKeys, t.Gw.obfuscateKey)
accessLog.WithLatency(latency)
accessLog.WithRequest(req)
accessLog.WithResponse(resp)

t.Logger().WithFields(accessLog.Fields()).Info()
}

func copyAllowedURLs(input []user.AccessSpec) []user.AccessSpec {
if input == nil {
return nil
Expand Down
53 changes: 53 additions & 0 deletions internal/crypto/hash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package crypto

import (
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"

"github.com/TykTechnologies/murmur3"
)

const (
HashSha256 = "sha256"
HashMurmur32 = "murmur32"
HashMurmur64 = "murmur64"
HashMurmur128 = "murmur128"
)

func hashFunction(algorithm string) (hash.Hash, error) {
switch algorithm {
case HashSha256:
return sha256.New(), nil
case HashMurmur64:
return murmur3.New64(), nil
case HashMurmur128:
return murmur3.New128(), nil
case "", HashMurmur32:
return murmur3.New32(), nil
default:
return murmur3.New32(), fmt.Errorf("Unknown key hash function: %s. Falling back to murmur32.", algorithm)
}
}

func HashStr(in string, withAlg ...string) string {
var algo string
if len(withAlg) > 0 && withAlg[0] != "" {
algo = withAlg[0]
} else {
algo = TokenHashAlgo(in)
}

h, _ := hashFunction(algo)
h.Write([]byte(in))
return hex.EncodeToString(h.Sum(nil))
}

func HashKey(in string, hashKey bool) string {
if !hashKey {
// Not hashing? Return the raw key
return in
}
return HashStr(in)
}
83 changes: 83 additions & 0 deletions internal/crypto/token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package crypto

import (
"encoding/base64"
"encoding/hex"
"fmt"
"strings"

"github.com/buger/jsonparser"

"github.com/TykTechnologies/tyk/internal/uuid"
)

// `{"` in base64
const B64JSONPrefix = "ey"

const DefaultHashAlgorithm = "murmur64"

const MongoBsonIdLength = 24

// GenerateToken generates a token.
// If hashing algorithm is empty, it uses legacy key generation.
func GenerateToken(orgID, keyID, hashAlgorithm string) (string, error) {
if keyID == "" {
keyID = uuid.NewHex()
}

if hashAlgorithm != "" {
_, err := hashFunction(hashAlgorithm)
if err != nil {
hashAlgorithm = DefaultHashAlgorithm
}

jsonToken := fmt.Sprintf(`{"org":"%s","id":"%s","h":"%s"}`, orgID, keyID, hashAlgorithm)

Check failure

Code scanning / CodeQL

Potentially unsafe quoting Critical

If this
JSON value
contains a double quote, it could break out of the enclosing quotes.
If this
JSON value
contains a double quote, it could break out of the enclosing quotes.
If this
JSON value
contains a double quote, it could break out of the enclosing quotes.

Copilot Autofix AI about 17 hours ago

To fix the problem, we need to ensure that any user-provided data embedded in the JSON string is properly escaped. This can be achieved by using a JSON library to construct the JSON string instead of manually formatting it. This approach ensures that all special characters are correctly escaped.

  • Replace the manual JSON string construction with a call to json.Marshal to safely encode the data.
  • Update the GenerateToken function to use json.Marshal for creating the JSON token.
Suggested changeset 1
internal/crypto/token.go

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/internal/crypto/token.go b/internal/crypto/token.go
--- a/internal/crypto/token.go
+++ b/internal/crypto/token.go
@@ -35,4 +35,12 @@
 
-		jsonToken := fmt.Sprintf(`{"org":"%s","id":"%s","h":"%s"}`, orgID, keyID, hashAlgorithm)
-		return base64.StdEncoding.EncodeToString([]byte(jsonToken)), err
+		tokenData := map[string]string{
+			"org": orgID,
+			"id":  keyID,
+			"h":   hashAlgorithm,
+		}
+		jsonToken, err := json.Marshal(tokenData)
+		if err != nil {
+			return "", err
+		}
+		return base64.StdEncoding.EncodeToString(jsonToken), nil
 	}
EOF
@@ -35,4 +35,12 @@

jsonToken := fmt.Sprintf(`{"org":"%s","id":"%s","h":"%s"}`, orgID, keyID, hashAlgorithm)
return base64.StdEncoding.EncodeToString([]byte(jsonToken)), err
tokenData := map[string]string{
"org": orgID,
"id": keyID,
"h": hashAlgorithm,
}
jsonToken, err := json.Marshal(tokenData)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(jsonToken), nil
}
Copilot is powered by AI and may make mistakes. Always verify output.
Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
return base64.StdEncoding.EncodeToString([]byte(jsonToken)), err
}

// Legacy keys
return orgID + keyID, nil
}

func TokenHashAlgo(token string) string {
// Legacy tokens not b64 and not JSON records
if strings.HasPrefix(token, B64JSONPrefix) {
if jsonToken, err := base64.StdEncoding.DecodeString(token); err == nil {
hashAlgo, _ := jsonparser.GetString(jsonToken, "h")
return hashAlgo
}
}

return ""
}

func TokenID(token string) (id string, err error) {
jsonToken, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return "", err
}

return jsonparser.GetString(jsonToken, "id")
}

func TokenOrg(token string) string {
if strings.HasPrefix(token, B64JSONPrefix) {
if jsonToken, err := base64.StdEncoding.DecodeString(token); err == nil {
// Checking error in case if it is a legacy tooken which just by accided has the same b64JSON prefix
if org, err := jsonparser.GetString(jsonToken, "org"); err == nil {
return org
}
}
}

// 24 is mongo bson id length
if len(token) > MongoBsonIdLength {
newToken := token[:MongoBsonIdLength]
_, err := hex.DecodeString(newToken)
if err == nil {
return newToken
}
}

return ""
}
3 changes: 2 additions & 1 deletion internal/httputil/Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ version: "3"

vars:
testArgs: -v
coverpkg: ./...,github.com/TykTechnologies/tyk/internal/httputil/...

tasks:
test:
desc: "Run tests (requires redis)"
cmds:
- task: fmt
- go test {{.testArgs}} -count=1 -cover -coverprofile=rate.cov -coverpkg=./... ./...
- go test {{.testArgs}} -count=1 -cover -coverprofile=rate.cov {{.coverpkg}} ./...

bench:
desc: "Run benchmarks"
Expand Down
Loading
Loading