Переглянути джерело

Merge pull request #16383 from overleaf/jpa-normalize-token-prefix

[web] normalize token hash prefix ahead of comparison

GitOrigin-RevId: 44afda865df5d3517f23335509ee0e46ba74335f
Jakob Ackermann 2 роки тому
батько
коміт
d1f1530b77

+ 11 - 3
services/web/app/src/Features/TokenAccess/TokenAccessHandler.js

@@ -287,12 +287,20 @@ const TokenAccessHandler = {
     return hash.digest('hex').slice(0, 6)
   },
 
+  normalizeTokenHashPrefix(tokenHashPrefix) {
+    if (typeof tokenHashPrefix !== 'string') return ''
+    // remove (encoded) hash
+    tokenHashPrefix = tokenHashPrefix.replace('#', '').replace('%23', '')
+    // remove trailing special characters that were copied by accident
+    tokenHashPrefix = tokenHashPrefix.replace(/[^a-z0-9]+$/i, '')
+    return tokenHashPrefix
+  },
+
   checkTokenHashPrefix(token, tokenHashPrefix, type, userId, logData = {}) {
     let hashPrefixStatus
 
-    if (tokenHashPrefix) {
-      tokenHashPrefix = tokenHashPrefix.replace('#', '').replace('%23', '')
-    }
+    tokenHashPrefix =
+      TokenAccessHandler.normalizeTokenHashPrefix(tokenHashPrefix)
 
     const v1Format = /%2F[0-9]{7,8}%2F/
     const isSuspectedV1Format = v1Format.test(tokenHashPrefix)

+ 24 - 0
services/web/test/unit/src/TokenAccess/TokenAccessHandlerTests.js

@@ -649,6 +649,30 @@ describe('TokenAccessHandler', function () {
     })
   })
 
+  describe('normalizeTokenHashPrefix', function () {
+    const cases = {
+      // hex string
+      ab2345: 'ab2345',
+      '01234f': '01234f',
+      '012345': '012345',
+      // remove (encoded) hash
+      '#012345': '012345',
+      '%23012345': '012345',
+      // remove trailing special characters
+      '012345.': '012345',
+      '012345/': '012345',
+      // v1 doc
+      '%2F1234567%2F': '%2F1234567%2F',
+    }
+    for (const [input, output] of Object.entries(cases)) {
+      it(`should handle ${JSON.stringify(input)}`, function () {
+        expect(
+          this.TokenAccessHandler.normalizeTokenHashPrefix(input)
+        ).to.equal(output)
+      })
+    }
+  })
+
   describe('checkTokenHashPrefix', function () {
     const userId = 'abc123'
     const projectId = 'def456'