Skip to content

Conversation

@ecarrara
Copy link
Member

Implements a new /api/shorten endpoint that accepts POST requests with JSON payload containing a long URL and optionally a custom short code. The endpoint is protected with Bearer token authentication via the Authorization header.

Features:

  • POST /api/shorten endpoint for creating shortened URLs
  • Bearer token authentication using API_TOKEN environment variable
  • Auto-generation of short codes with collision detection
  • Support for custom short codes with uniqueness validation
  • Returns JSON response with short_url and short_code

New files:

  • mentirinha/auth.py: Bearer token authentication decorator
  • mentirinha/utils.py: Short code generation utility

🤖 Generated with Claude Code

Implements a new /api/shorten endpoint that accepts POST requests with JSON payload
containing a long URL and optionally a custom short code. The endpoint is protected
with Bearer token authentication via the Authorization header.

Features:
- POST /api/shorten endpoint for creating shortened URLs
- Bearer token authentication using API_TOKEN environment variable
- Auto-generation of short codes with collision detection
- Support for custom short codes with uniqueness validation
- Returns JSON response with short_url and short_code

New files:
- mentirinha/auth.py: Bearer token authentication decorator
- mentirinha/utils.py: Short code generation utility

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Comment on lines +91 to +98
try:
shortened_url.full_clean()
shortened_url.save()
except ValidationError as e:
return JsonResponse(
{'error': str(e.message_dict)},
status=400
)
Copy link

Choose a reason for hiding this comment

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

Bug: Unhandled IntegrityError due to race condition when saving ShortenedUrl with duplicate short_code causes server crash.
Severity: CRITICAL | Confidence: 1.00

🔍 Detailed Analysis

The ShortenedUrl model has a unique=True constraint on short_code. The try...except block at mentirinha/views.py:91~98 only catches ValidationError, not IntegrityError. A race condition exists where two concurrent requests could pass the uniqueness check (either for custom or auto-generated codes) and then attempt to save the same short_code. The second save() operation will raise an IntegrityError, which is not caught, leading to an unhandled exception and server crash.

💡 Suggested Fix

Add except IntegrityError as e: to the try...except block to catch database unique constraint violations and return an appropriate error response, similar to how ValidationError is handled.

🤖 Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent.
Verify if this is a real issue. If it is, propose a fix; if not, explain why it's not
valid.

Location: mentirinha/views.py#L91-L98

Potential issue: The `ShortenedUrl` model has a `unique=True` constraint on
`short_code`. The `try...except` block at `mentirinha/views.py:91~98` only catches
`ValidationError`, not `IntegrityError`. A race condition exists where two concurrent
requests could pass the uniqueness check (either for custom or auto-generated codes) and
then attempt to save the same `short_code`. The second `save()` operation will raise an
`IntegrityError`, which is not caught, leading to an unhandled exception and server
crash.

Did we get this right? 👍 / 👎 to inform future reviews.

Reference_id: 2782303

Copy link

@J0sueTM J0sueTM left a comment

Choose a reason for hiding this comment

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

Overall, looks good to me, but made some suggestions and questions.

if ShortenedUrl.objects.filter(short_code=short_code).exists():
return JsonResponse(
{'error': f'Short code "{short_code}" is already in use'},
status=409
Copy link

Choose a reason for hiding this comment

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

Random number. Use HTTPStatus.


# API Authentication
# Set this to a secure random token for the /api/shorten endpoint
API_TOKEN=your-secret-api-token-here
Copy link

Choose a reason for hiding this comment

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

Why exactly do we need authentication for this internal tool? A possible option (with less code) is to block external requests for this specific endpoint from within the firewall.

However, doing that separates a specific business logic (if it is) from the code itself.

I trust your judgement on this, though.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants