ahawker / ulid

Universally Unique Lexicographically Sortable Identifier (ULID) in Python 3

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Enforce ULID Timestamp Range

ahawker opened this issue · comments

A number of the test fixtures that generate data are powered by os.urandom. This works fine until it generates a random sequence of bytes that starts with a leading zero. This will cause tests to fail during duration due to int.bit_length stripping leading zeros in its computation.

Example test failure: https://travis-ci.org/ahawker/ulid/jobs/294263189

All of the above is a side-effect of the fact that there is no validation logic for the timestamp portion of a ULID. It should never contain a zero leading byte since the minimum value is the Unix epoch.

Items to address this issue:

  • Validation rules to enforce minimum and maximum timestamp values upon creation
  • Update test fixtures to specific generates values within valid or invalid ranges

Example:

>>> import ulid
>>> data = b"\x00\xcdh\x95}\xd9\xb2Yp':y0\xe4\xce\xdc"
>>> ulid.from_bytes(data)
<ULID('00SNM9AZESP9CQ09STF4RE9KPW')>
>>> ulid.from_int(int.from_bytes(data, byteorder='big'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/hawker/src/github.com/ahawker/ulid/ulid/api.py", line 76, in from_int
    raise ValueError('Expects integer to be 128 bits; got {} bytes'.format(length))
ValueError: Expects integer to be 128 bits; got 15 bytes