Skip to content

Conversation

@konard
Copy link
Contributor

@konard konard commented Oct 30, 2025

Summary

This PR addresses issue #14 by implementing Bearer token authentication via Authorization header across all API endpoints in the api-gateway, while maintaining full backward compatibility with query parameter authentication.

Fixes #14

🔍 Problem Analysis

Current State

The api-gateway authentication system currently uses:

  • User tokens: Already support Authorization: Bearer <token> header
  • Master/Admin tokens: Only support ?masterToken=<token> query parameter

Issues Identified

  1. Security Risk: Query parameters are exposed in server logs, browser history, and proxy logs
  2. Non-standard: Does not follow OAuth 2.0 RFC 6750 best practices
  3. Inconsistency: Mixed authentication methods within the same API
  4. OpenAI Compatibility: Hinders alignment with OpenAI API standard (needed for Cursor support)

🛡️ Security Analysis

Why Bearer Tokens in Headers are More Secure

According to OAuth 2.0 RFC 6750 and 2025 security standards:

Query Parameter Risks:

  • ❌ Exposed in web server access logs
  • ❌ Stored in browser history
  • ❌ Logged by proxies and load balancers
  • ❌ Leaked via Referer headers when clicking external links
  • ❌ Visible in URL sharing/screenshots
  • ❌ May trigger security audit failures

Authorization Header Benefits:

  • ✅ Not logged by default in most web servers
  • ✅ Not stored in browser history
  • ✅ Not leaked via Referer headers
  • ✅ Industry standard (OAuth 2.0, OpenAI, AWS, etc.)
  • ✅ Required for SOC 2 and ISO 27001 compliance
  • ✅ Better separation of concerns (auth vs data)

OAuth 2.0 RFC 6750 Quote:

"The HTTP request URI query parameters SHOULD NOT be used to transport access tokens."

Is This Just Common Practice or Actually More Secure?

Answer: Both. It's a common practice because it's more secure.

📚 Documentation

This PR includes comprehensive documentation:

  1. BEARER_TOKEN_SOLUTION.md - Complete solution with:

    • Detailed security analysis
    • Architecture diagrams
    • Implementation guide
    • Migration guide for API consumers
    • Timeline and testing strategy
  2. IMPLEMENTATION_PLAN.md - Technical implementation details:

    • Files to modify
    • Code patterns
    • Testing checklist
    • Deployment steps

🔧 Implementation

Changes in api-gateway

Implementation PR: deep-assistant/api-gateway#4

Service Layer

Added getMasterTokenFromRequest(req) method to TokensService:

getMasterTokenFromRequest(req) {
  // Priority 1: Authorization header (recommended)
  if (req.headers.authorization?.startsWith('Bearer ')) {
    return req.headers.authorization.split('Bearer ')[1];
  }

  // Priority 2: Query parameter (deprecated, logs warning)
  if (req.query.masterToken) {
    console.log('⚠️ [DEPRECATED] Using masterToken in query parameter...');
    return req.query.masterToken;
  }

  throw new HttpException(401, "Missing authentication token...");
}

Controllers Updated

Updated 10 endpoints across 5 controllers:

  • tokensController.js (4 endpoints)
  • completionsController.js (1 endpoint)
  • dialogsController.js (1 endpoint)
  • systemMessagesController.js (2 endpoints)
  • referralController.js (2 endpoints)

✅ Backward Compatibility

No breaking changes - all existing code continues to work!

Query Parameter (Deprecated but Still Works)

curl "https://api.example.com/token?userId=123&masterToken=secret"
# ⚠️ Logs deprecation warning

Authorization Header (Recommended)

curl -H "Authorization: Bearer secret" \
  "https://api.example.com/token?userId=123"
# ✅ Standard approach

🔄 Migration Path

For API Consumers (telegram-bot, etc.)

Before:

const response = await fetch(
  `${API_URL}/token?userId=${userId}&masterToken=${MASTER_TOKEN}`
);

After:

const response = await fetch(
  `${API_URL}/token?userId=${userId}`,
  {
    headers: {
      'Authorization': `Bearer ${MASTER_TOKEN}`
    }
  }
);

📅 Timeline

Phase Duration Actions
Phase 1: Implementation Week 1 ✅ Complete - PR ready for review
Phase 2: Review & Merge Week 1-2 Review and merge api-gateway#4
Phase 3: Deployment Week 2 Deploy to production
Phase 4: Notification Month 1 Notify all API consumers
Phase 5: Migration Months 2-6 Update consumers to use headers
Phase 6: Monitoring Months 6-12 Monitor deprecation warnings
Phase 7: Removal v2.0.0 Remove query parameter support

🎯 Benefits

Immediate Benefits

  1. Enhanced Security - Reduced risk of token exposure
  2. Standards Compliance - Follows OAuth 2.0 and REST best practices
  3. OpenAI Compatibility - Better alignment with OpenAI API standard
  4. No Breaking Changes - Full backward compatibility

Long-term Benefits

  1. Future-proofing - Easier to add OAuth 2.0 flows later
  2. Audit Compliance - Meets SOC 2 and ISO 27001 requirements
  3. Professional API - Industry-standard authentication
  4. Cursor Support - Enables using our API with Cursor IDE (issue Support Cursor by our API Gateway for OpenAI models #8)

🧪 Testing

Completed

  • ✅ Bearer header authentication method implemented
  • ✅ Query parameter fallback with deprecation warnings
  • ✅ Clear error messages for missing authentication
  • ✅ All 10 endpoints updated consistently

Next Steps (After Merge)

  • Deploy to staging environment
  • Test all endpoints with Bearer header
  • Test backward compatibility with query parameters
  • Verify deprecation warnings in logs
  • Update telegram-bot to use headers
  • Monitor production logs for usage patterns

🔗 Related Issues & PRs

📋 Checklist

  • Security analysis completed and documented
  • Implementation plan created
  • Code implemented in api-gateway
  • Backward compatibility maintained
  • Deprecation warnings added
  • Documentation written
  • Implementation PR created
  • Migration guide provided
  • Code reviewed and approved
  • Merged to main and deployed
  • API consumers notified

🤝 Next Actions

  1. Review: Please review this PR and api-gateway#4
  2. Merge: Merge api-gateway#4 to implement the changes
  3. Deploy: Deploy api-gateway to production
  4. Notify: Notify telegram-bot maintainers about the migration path
  5. Update: Update telegram-bot to use Bearer headers (future PR)

🤖 Generated with Claude Code

Adding CLAUDE.md with task information for AI processing.
This file will be removed when the task is complete.

Issue: undefined
@konard konard self-assigned this Oct 30, 2025
This commit adds detailed documentation for implementing Bearer token
authentication via Authorization headers across all API endpoints.

Key documents added:
- IMPLEMENTATION_PLAN.md: Technical implementation details
- BEARER_TOKEN_SOLUTION.md: Complete solution with security analysis

The solution addresses Issue #14 by:
- Providing security analysis comparing headers vs query parameters
- Designing backward-compatible implementation approach
- Creating migration guide for API consumers
- Establishing timeline for transition period

Security improvements:
- Follows OAuth 2.0 RFC 6750 standards
- Prevents token exposure in logs and browser history
- Aligns with industry best practices
- Enables better OpenAI API compatibility

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

Co-Authored-By: Claude <noreply@anthropic.com>
@konard konard changed the title [WIP] Allow to use bearer header in all our API Allow to use bearer header in all our API Oct 30, 2025
@konard konard marked this pull request as ready for review October 30, 2025 04:26
@konard
Copy link
Contributor Author

konard commented Oct 30, 2025

🤖 Solution Draft Log

This log file contains the complete execution trace of the AI solution draft process.

📎 Log file uploaded as GitHub Gist (332KB)
🔗 View complete solution draft log


Now working session is ended, feel free to review and add any feedback on the solution draft.

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.

Allow to use bearer header in all our API

2 participants