Skip to content

Invalid string produced when using FRIENDLY_ID_STRING_LENGTH that is not long enough #6

Description

@otonoton

I know this is an old (and probably abandoned) repo, but for others who might have borrowed friendly_id.py from here, I just want to point out a rather nasty bug I found.

If you set FRIENDLY_ID_STRING_LENGTH, and it happens to be set to a number that is too low for the ID number you are encoding, it will silently return an invalid string.

Here is a patch that instead raises an exception if that is the case:

--- a/friendly_id.py 2024-07-22 22:37:03.011344800 -0400
+++ b/friendly_id.py 2026-02-22 17:48:01.970600546 -0500
@@ -99,11 +99,13 @@
     string = ""
     # The length of the string can be determined by STRING_LENGTH or by how many
     # characters are necessary to present a base 30 representation of SIZE.
-    while STRING_LENGTH and len(string) <= STRING_LENGTH \
+    while STRING_LENGTH and len(string) < STRING_LENGTH \
                 or len(VALID_CHARS)**len(string) <= SIZE:
         # PREpend string (to remove all obvious signs of order)
         string = VALID_CHARS[int(num%len(VALID_CHARS))] + string
         num = num/len(VALID_CHARS)
+        if STRING_LENGTH and len(string) > STRING_LENGTH:
+            raise Exception('ID string length not long enough.')
     return string
 
 

Thanks!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions