{"id":45311854,"url":"https://github.com/aucontraire/gmail-buddy","last_synced_at":"2026-05-09T06:17:31.082Z","repository":{"id":283129627,"uuid":"902504197","full_name":"aucontraire/gmail-buddy","owner":"aucontraire","description":"extending gmail functionality with automation","archived":false,"fork":false,"pushed_at":"2026-05-01T18:41:48.000Z","size":412,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-05-01T20:25:11.915Z","etag":null,"topics":["automation","backend","backend-api","email-automation","gmail-api","google-api","java","productivity","productivity-tools","spring-boot"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aucontraire.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-12-12T17:37:26.000Z","updated_at":"2026-05-01T18:41:53.000Z","dependencies_parsed_at":"2025-03-18T18:44:08.434Z","dependency_job_id":null,"html_url":"https://github.com/aucontraire/gmail-buddy","commit_stats":null,"previous_names":["aucontraire/gmail-buddy"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/aucontraire/gmail-buddy","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aucontraire%2Fgmail-buddy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aucontraire%2Fgmail-buddy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aucontraire%2Fgmail-buddy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aucontraire%2Fgmail-buddy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aucontraire","download_url":"https://codeload.github.com/aucontraire/gmail-buddy/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aucontraire%2Fgmail-buddy/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32809217,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-08T08:22:46.396Z","status":"online","status_checked_at":"2026-05-09T02:00:06.633Z","response_time":123,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["automation","backend","backend-api","email-automation","gmail-api","google-api","java","productivity","productivity-tools","spring-boot"],"created_at":"2026-02-21T07:44:00.670Z","updated_at":"2026-05-09T06:17:31.069Z","avatar_url":"https://github.com/aucontraire.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Gmail Buddy\n\n[![Build Status](https://img.shields.io/github/actions/workflow/status/aucontraire/gmail-buddy/ci.yml?branch=master)](https://github.com/aucontraire/gmail-buddy/actions)\n[![Code Coverage](https://img.shields.io/badge/coverage-85%25-brightgreen)](./target/site/jacoco/index.html)\n[![Java Version](https://img.shields.io/badge/Java-17+-blue)](https://openjdk.java.net/projects/jdk/17/)\n[![Spring Boot](https://img.shields.io/badge/Spring%20Boot-3.4.0-brightgreen)](https://spring.io/projects/spring-boot)\n[![Performance](https://img.shields.io/badge/Performance-96%25_faster-success)](docs/architecture/ADR-002-OAuth2-Security-Context-Decoupling.md)\n[![Quota Efficiency](https://img.shields.io/badge/Gmail_Quota-99%25_reduction-success)](docs/architecture/ADR-002-OAuth2-Security-Context-Decoupling.md)\n[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n\nA robust, enterprise-ready Spring Boot application for Gmail management with exceptional performance (96% faster bulk operations), comprehensive email operations, dual authentication support, and modern architecture patterns.\n\n## ✨ Features\n\n### Core Functionality\n- **📧 Email Management**: List, search, delete, and modify Gmail messages\n- **🔍 Advanced Filtering**: Filter messages by sender, recipient, subject, and custom Gmail queries\n- **🏷️ Label Operations**: Bulk label modification and management\n- **📖 Message Content**: Extract and display email body content\n- **📚 Bulk Operations**: Mass delete and label operations with validation\n- **📨 Send \u0026 Draft Operations**: Create drafts for human review, send approved drafts programmatically, or direct-send trusted templates — all via Bearer token or OAuth2 session\n- **🛡️ Header Injection Prevention**: CRLF-injection rejected as a security event distinct from validation errors, with per-field positional reporting on recipient lists\n- **⚡ Native Batch Processing**: Gmail API native batchDelete() for up to 1000 messages per batch (99% quota reduction)\n- **🚀 High-Performance Operations**: Adaptive batch sizing with circuit breaker protection\n- **🔄 Intelligent Rate Limiting**: Exponential backoff with adaptive algorithms\n\n### Architecture \u0026 Security\n- **🔐 Dual Authentication**: OAuth2 for browsers + Bearer token support for API clients (Postman, curl)\n- **🛡️ Security Context Decoupling**: Repository layer independent of Spring Security infrastructure\n- **🔒 Token Validation**: Google TokenInfo endpoint integration for secure API client access\n- **🕵️ Security Logging**: Comprehensive audit logging with automatic credential masking\n- **✅ Input Validation**: Comprehensive validation framework with custom validators\n- **⚡ Exception Handling**: Structured error responses with correlation IDs and detailed batch operation results\n- **⚙️ Configuration Management**: Centralized properties with environment-specific configs\n- **🛡️ Security Hardening**: CORS, security headers, and protection against common vulnerabilities\n\n### Performance \u0026 Reliability\n- **🚀 96% Performance Improvement**: Bulk operations complete in 8 seconds vs 210 seconds (1000 messages)\n- **💰 99% Quota Reduction**: Native batchDelete uses 50 units vs 5,000+ units for individual operations\n- **🔄 Adaptive Rate Limiting**: Dynamic batch sizing based on API response patterns\n- **🛡️ Circuit Breaker Protection**: Automatic cooling off periods during rate limit scenarios\n- **📊 Detailed Operation Tracking**: Success/failure tracking with retry counts and duration metrics\n\n### Developer Experience\n- **🧪 High Test Coverage**: 85%+ test coverage with unit and integration tests\n- **📋 Structured Logging**: JSON-formatted logs with correlation tracking and security masking\n- **🔄 Retry Logic**: Intelligent retry mechanisms with exponential backoff for Gmail API interactions\n- **📊 Health Checks**: Application and dependency health monitoring\n- **🔧 API Client Ready**: Full Postman support with Bearer token authentication\n\n---\n\n## 🚀 Quick Start\n\n### Prerequisites\n\n- **Java 17+** (OpenJDK recommended)\n- **Maven 3.6+**\n- **Google Cloud Project** with Gmail API enabled\n- **OAuth2 Credentials** configured in Google Cloud Console\n\n### Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone https://github.com/aucontraire/gmail-buddy.git\n   cd gmail-buddy\n   ```\n\n2. **Configure OAuth2 Credentials**\n   \n   Create a `.env` file in the project root:\n   ```bash\n   cp .env.example .env\n   ```\n   \n   Update the `.env` file with your Google OAuth credentials:\n   ```env\n   GOOGLE_CLIENT_ID=your_google_client_id_here\n   GOOGLE_CLIENT_SECRET=your_google_client_secret_here\n   ```\n\n3. **Set up Google Cloud Console**\n   - Enable the Gmail API in your Google Cloud project\n   - Configure OAuth2 consent screen\n   - Add `http://localhost:8020/login/oauth2/code/google` to authorized redirect URIs\n\n4. **Run the application**\n   ```bash\n   ./mvnw spring-boot:run\n   ```\n\n5. **Access the application**\n   \n   Open [http://localhost:8020](http://localhost:8020) and authenticate with Google.\n\n---\n\n## 📡 API Endpoints\n\n### Authentication\n\nGmail Buddy supports **dual authentication modes**:\n\n- **Browser Users**: OAuth2 flow with automatic redirect to Google's sign-in page\n- **API Clients**: Bearer token authentication for programmatic access (Postman, curl, scripts)\n\n**For API Testing**: See the [API Testing Guide](docs/API_TESTING_GUIDE.md) for detailed instructions on using Bearer tokens with Postman, curl, and automation scripts.\n\n### Core Endpoints\n\n| Method | Endpoint | Description | Request Body | Performance |\n|--------|----------|-------------|--------------|-------------|\n| `GET` | `/dashboard` | Dashboard page (web interface) | - | - |\n| `GET` | `/api/v1/gmail/messages` | List all messages | - | Standard |\n| `GET` | `/api/v1/gmail/messages/latest` | List latest 50 messages | - | Standard |\n| `POST` | `/api/v1/gmail/messages/filter` | Filter messages by criteria | `FilterCriteriaDTO` | Standard |\n| `GET` | `/api/v1/gmail/messages/{id}/body` | Get message body content | - | Standard |\n| `DELETE` | `/api/v1/gmail/messages/{id}` | Delete specific message | - | Standard |\n| `PUT` | `/api/v1/gmail/messages/{id}/read` | Mark message as read | - | Standard |\n| `DELETE` | `/api/v1/gmail/messages/filter` | **High-performance bulk delete** | `FilterCriteriaDTO` | **99% quota reduction** |\n| `POST` | `/api/v1/gmail/messages/filter/modifyLabels` | Bulk modify labels | `FilterCriteriaWithLabelsDTO` | Batch optimized |\n| `POST` | `/api/v1/gmail/drafts` | **Stage a draft for review** in Gmail Drafts folder | `SendMessageDTO` | Standard (10 quota units) |\n| `POST` | `/api/v1/gmail/drafts/{draftId}/send` | **Send a previously-created draft** programmatically | - | Standard (100 quota units, naturally idempotent) |\n| `POST` | `/api/v1/gmail/messages` | **Send a message directly** without staging (trusted templates only) | `SendMessageDTO` | Standard (100 quota units) |\n\n### High-Performance Batch Operations\n\nGmail Buddy's bulk delete operation uses Gmail's native batchDelete() API for exceptional performance:\n\n**Bulk Delete** (`DELETE /api/v1/gmail/messages/filter`):\n- Uses native Gmail batchDelete() endpoint\n- Processes up to 1000 messages per batch chunk\n- Only 50 Gmail API quota units per batch (vs 5,000+ for individual deletes)\n- Automatic retry with exponential backoff\n- Circuit breaker protection against rate limits\n- Returns detailed `BulkOperationResult` with success/failure breakdown\n\n**Performance Example**:\n```bash\n# Delete 1000 messages matching filter\ncurl -X DELETE http://localhost:8020/api/v1/gmail/messages/filter \\\n  -H \"Authorization: Bearer ya29.a0ARrdaM...\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"from\": \"notifications@example.com\",\n    \"olderThan\": \"30d\"\n  }'\n\n# Response includes detailed metrics:\n# {\n#   \"operationType\": \"BATCH_DELETE\",\n#   \"totalOperations\": 1000,\n#   \"successCount\": 1000,\n#   \"failureCount\": 0,\n#   \"successRate\": 100.0,\n#   \"batchesProcessed\": 1,\n#   \"batchesRetried\": 0,\n#   \"durationMs\": 8234\n# }\n```\n\n### Request/Response Examples\n\n**Filter Messages:**\n```bash\ncurl -X POST http://localhost:8020/api/v1/gmail/messages/filter \\\n  -H \"Authorization: Bearer ya29.a0ARrdaM...\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"from\": \"notifications@example.com\",\n    \"subject\": \"Weekly Report\",\n    \"maxResults\": 10\n  }'\n```\n\n**Modify Labels:**\n```bash\ncurl -X POST http://localhost:8020/api/v1/gmail/messages/filter/modifyLabels \\\n  -H \"Authorization: Bearer ya29.a0ARrdaM...\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"from\": \"newsletter@example.com\",\n    \"labelsToAdd\": [\"Newsletter\", \"Archive\"],\n    \"labelsToRemove\": [\"INBOX\"]\n  }'\n```\n\n**Create a Draft (stage for review before sending):**\n```bash\ncurl -i -X POST http://localhost:8020/api/v1/gmail/drafts \\\n  -H \"Authorization: Bearer ya29.a0ARrdaM...\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"to\": [\"recipient@example.com\"],\n    \"subject\": \"Following up on our conversation\",\n    \"body\": \"\u003cp\u003eHi,\u003c/p\u003e\u003cp\u003eThis draft was created via the Gmail Buddy API.\u003c/p\u003e\",\n    \"bodyType\": \"html\"\n  }'\n\n# Response (201 Created):\n# {\"draftId\":\"r-9876543210\",\"messageId\":\"19a2b3c4d5e6f7g8\",\"threadId\":\"19a2b3c4d5e6f7g8\",\"status\":\"DRAFT\"}\n#\n# The draft is immediately visible in Gmail → Drafts folder for review, edit, or discard.\n# To send it programmatically: POST /api/v1/gmail/drafts/{draftId}/send\n```\n\n\u003e **Note**: Replace `ya29.a0ARrdaM...` with your actual Bearer token. The token must carry the `gmail.send` scope (or `gmail.modify` / `mail.google.com`) for send and draft endpoints. See [API Testing Guide](docs/API_TESTING_GUIDE.md) for instructions on obtaining tokens.\n\n### Error Responses\n\nAll errors follow a consistent format with correlation IDs for tracking:\n\n```json\n{\n  \"code\": \"VALIDATION_ERROR\",\n  \"message\": \"Validation failed for input parameters\",\n  \"category\": \"CLIENT_ERROR\",\n  \"correlationId\": \"abc123-def456-ghi789\",\n  \"timestamp\": \"2024-01-15T10:30:00Z\",\n  \"details\": {\n    \"from\": \"Must be a valid email address\",\n    \"subject\": \"Subject must not exceed 255 characters\"\n  }\n}\n```\n\n---\n\n## 🏗️ Architecture\n\n### Project Structure\n\n```\nsrc/\n├── main/java/com/aucontraire/gmailbuddy/\n│   ├── client/         # Gmail API client layer (batch operations)\n│   ├── config/         # Configuration classes and properties\n│   ├── controller/     # REST controllers\n│   ├── dto/            # Data Transfer Objects with validation\n│   ├── exception/      # Exception hierarchy and handlers\n│   ├── repository/     # Gmail data access layer\n│   ├── security/       # Authentication and token validation\n│   ├── service/        # Business logic layer\n│   └── validation/     # Custom validators\n├── main/resources/\n│   ├── application.properties    # Main configuration\n│   └── application-{env}.properties  # Environment-specific configs\n└── test/               # Comprehensive test suite (120+ tests)\n```\n\n### Key Components\n\n#### Batch Processing Layer (NEW)\n- **`GmailBatchClient`**: Native Gmail API batch operations with circuit breaker protection\n  - Implements batchDelete() for up to 1000 messages per call (50 quota units flat fee)\n  - Adaptive batch sizing algorithm (5-50 operations per batch)\n  - Exponential backoff retry logic with configurable parameters\n  - Circuit breaker pattern with 30-second cooling off periods\n- **`BulkOperationResult`**: Thread-safe operation tracking with success/failure details\n  - Real-time success/failure tracking\n  - Retry attempt counting and batch metrics\n  - Duration and success rate calculations\n- **`BatchOperationException`**: Comprehensive batch operation error handling\n  - Partial failure support (HTTP 207 Multi-Status)\n  - Complete failure reporting (HTTP 502 Bad Gateway)\n  - Detailed operation-level error messages\n\n#### Authentication \u0026 Security Layer\n- **`TokenProvider`**: Clean abstraction for token management (decoupled from Spring Security)\n- **`OAuth2TokenProvider`**: Dual authentication implementation\n  - Browser OAuth2 flow via SecurityContextHolder\n  - API client Bearer token support via HttpServletRequest\n- **`GoogleTokenValidator`**: Token validation using Google's TokenInfo endpoint\n  - Validates opaque OAuth2 tokens (not JWTs)\n  - Scope verification for Gmail API permissions\n  - Security logging with automatic credential masking\n\n#### Exception Hierarchy\n- **`GmailBuddyException`**: Base exception with correlation IDs\n- **`ValidationException`**: Input validation errors (400)\n- **`ResourceNotFoundException`**: Missing resources (404)\n- **`GmailApiException`**: Gmail API integration errors (502)\n- **`AuthenticationException`**: OAuth2 authentication failures (401)\n- **`BatchOperationException`**: Batch operation failures with detailed results (207/502)\n\n#### Validation Framework\n- **Custom Email Validator**: Validates email format patterns\n- **Gmail Query Validator**: Sanitizes and validates Gmail search queries\n- **Label Validation**: Enforces Gmail label naming constraints\n- **Size Limits**: Prevents oversized requests and bulk operations\n\n#### Configuration Management\nCentralized configuration using `@ConfigurationProperties` (`GmailBuddyProperties`):\n- Gmail API settings (rate limits, retry policies, batch operations)\n- Batch operations (delays, backoff, adaptive sizing)\n- OAuth2 configuration\n- Security settings (CORS, headers, token validation)\n- Validation rules and patterns\n\n#### Authentication Architecture\n- **Dual Authentication Support**: OAuth2 for browsers, Bearer tokens for API clients (Postman, curl)\n- **Security Context Decoupling**: Repository layer independent of Spring Security context\n- **Token Validation**: Google TokenInfo endpoint integration for Bearer tokens\n- **Graceful Fallback**: API requests fall back to OAuth2 when Bearer token invalid\n- **Credential Masking**: Automatic redaction of sensitive data in logs\n\n### Design Patterns\n\nGmail Buddy implements modern architectural patterns for reliability and maintainability:\n\n#### Batch Processing Patterns\n- **Native API Batch Operations**: Uses Gmail's batchDelete() endpoint (not REST API batching)\n  - Processes up to 1000 message IDs per batch\n  - Single API call with 50 quota unit flat fee\n  - All-or-nothing transactional semantics\n- **Chunking Strategy**: Splits large operations into optimal batch sizes\n  - Configurable chunk sizes (default: 1000 for delete, 50 for modify)\n  - Automatic batch creation and processing\n  - Progress tracking across multiple chunks\n\n#### Resilience Patterns\n- **Circuit Breaker**: Protects against cascading failures\n  - Triggers after 3 consecutive failures\n  - 30-second cooling off period\n  - Automatic state reset on success\n- **Exponential Backoff**: Intelligent retry delays\n  - Initial delay: 2 seconds\n  - Multiplier: 2.5x per retry\n  - Maximum delay: 60 seconds\n  - Up to 4 retry attempts\n- **Adaptive Rate Limiting**: Dynamic batch size adjustment\n  - Starts at 15 operations per batch\n  - Increases gradually on success (up to 50)\n  - Decreases aggressively on failure (down to 5)\n  - Prevents rate limit violations\n\n#### Repository Pattern\n- **Clean Abstraction**: Gmail API access isolated in repository layer\n- **Token Provider Injection**: Decoupled from Spring Security\n- **Testable Design**: Easy mocking for unit tests\n\n#### DTO Pattern\n- **Request/Response Separation**: API contracts independent of internal models\n- **Validation Integration**: Bean Validation annotations on DTOs\n- **Type Safety**: Strong typing for filter criteria and label operations\n\n#### Builder Pattern\n- **GmailQueryBuilder**: Fluent API for Gmail search query construction\n- **Type-safe Query Building**: Prevents invalid Gmail query syntax\n- **Readable Code**: Declarative query construction\n\n#### Dependency Injection\n- **Spring-managed Components**: All services, repositories, and clients\n- **Constructor Injection**: Immutable dependencies with `final` fields\n- **Configuration Properties**: Externalized configuration via `@ConfigurationProperties`\n\n#### Exception Handling Patterns\n- **Hierarchical Exceptions**: Base exception with specialized subtypes\n- **Correlation IDs**: Unique identifiers for request tracking\n- **Detailed Error Context**: Rich error information for debugging\n- **HTTP Status Mapping**: Appropriate status codes for each error type\n\n---\n\n## 🚀 Performance\n\n### Batch Operation Performance Metrics\n\nGmail Buddy achieves exceptional performance improvements through native Gmail API batch operations:\n\n#### Performance Comparison (1000 Messages)\n\n| Metric | Old Approach | New Approach | Improvement |\n|--------|--------------|--------------|-------------|\n| **Execution Time** | 210 seconds | 8 seconds | **96% faster** |\n| **Gmail Quota Used** | 5,000+ units | 50 units | **99% reduction** |\n| **API Calls** | 1000+ calls | 1 call | **99.9% reduction** |\n| **Batch Size** | 10 messages | 1000 messages | **100x larger** |\n| **Inter-batch Delay** | 2000ms | 500ms | **75% faster** |\n\n#### Real-World Performance Benefits\n\n**Bulk Delete Operations:**\n- **510 messages**: ~5 seconds (was 210 seconds)\n- **1000 messages**: ~8 seconds (was 350+ seconds)\n- **5000 messages**: ~40 seconds (was 30+ minutes)\n\n**Quota Efficiency:**\n- Native batchDelete(): **50 quota units** for up to 1000 messages\n- Individual deletes: **5,000+ quota units** for 1000 messages\n- **99% quota savings** enables more operations within Gmail API limits\n\n### Adaptive Performance Features\n\n#### Intelligent Rate Limiting\n- **Dynamic Batch Sizing**: Automatically adjusts from 5-50 operations based on API success rates\n- **Circuit Breaker**: 30-second cooling off period after 3 consecutive failures\n- **Exponential Backoff**: Initial 2s delay, 2.5x multiplier, max 60s backoff\n- **Micro-delays**: 10ms between operations within batches to reduce concurrent pressure\n\n#### Retry Logic\n- **Configurable Retries**: Up to 4 retry attempts with exponential backoff\n- **Smart Failure Detection**: Distinguishes retryable errors (rate limits, timeouts) from permanent failures\n- **Batch-level Retries**: Failed batches automatically retry with reduced size\n\n#### Operation Tracking\n- **Success Rate Monitoring**: Real-time success/failure tracking per operation\n- **Duration Metrics**: Precise timing for performance analysis\n- **Batch Statistics**: Total batches processed, retried, and failed\n- **Detailed Logging**: Operation-level logs for debugging and auditing\n\n### Performance Configuration\n\nAll performance parameters are configurable via `application.properties`:\n\n```properties\n# Batch operation performance tuning\ngmail-buddy.gmail-api.rate-limit.batch-operations.delay-between-batches-ms=500\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-batch-size=50\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-retry-attempts=4\ngmail-buddy.gmail-api.rate-limit.batch-operations.initial-backoff-ms=2000\ngmail-buddy.gmail-api.rate-limit.batch-operations.backoff-multiplier=2.5\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-backoff-ms=60000\ngmail-buddy.gmail-api.rate-limit.batch-operations.micro-delay-between-operations-ms=10\n```\n\n---\n\n## ⚙️ Configuration\n\n### Environment Variables\n\n| Variable | Description | Required | Default |\n|----------|-------------|----------|---------|\n| `GOOGLE_CLIENT_ID` | Google OAuth2 Client ID | ✅ | - |\n| `GOOGLE_CLIENT_SECRET` | Google OAuth2 Client Secret | ✅ | - |\n| `SERVER_PORT` | Application port | ❌ | 8020 |\n| `LOG_LEVEL` | Logging level | ❌ | INFO |\n\n### Application Properties\n\nKey configuration sections in `application.properties`:\n\n```properties\n# Gmail API Configuration\ngmail-buddy.gmail-api.default-max-results=50\ngmail-buddy.gmail-api.default-latest-messages-limit=50\ngmail-buddy.gmail-api.batch-delete-max-results=500\ngmail-buddy.gmail-api.rate-limit.default-retry-seconds=60\n\n# Batch Operations Configuration (High Performance)\ngmail-buddy.gmail-api.rate-limit.batch-operations.delay-between-batches-ms=500\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-batch-size=50\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-retry-attempts=4\ngmail-buddy.gmail-api.rate-limit.batch-operations.initial-backoff-ms=2000\ngmail-buddy.gmail-api.rate-limit.batch-operations.backoff-multiplier=2.5\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-backoff-ms=60000\ngmail-buddy.gmail-api.rate-limit.batch-operations.micro-delay-between-operations-ms=10\n\n# Security Configuration\ngmail-buddy.security.permit-all-patterns=/login**,/oauth2/**\ngmail-buddy.security.oauth2-security.default-success-url=/dashboard\ngmail-buddy.security.oauth2-security.authorization-base-uri=/oauth2/authorization\n\n# OAuth2 Configuration\ngmail-buddy.oauth2.client-registration-id=google\ngmail-buddy.oauth2.token.prefix=Bearer\n\n# Validation Configuration\ngmail-buddy.validation.email.pattern=^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$\ngmail-buddy.validation.gmail-query.dangerous-pattern=.*[\u003c\u003e\"'\u0026;\\\\|\\\\*\\\\?\\\\[\\\\]\\\\(\\\\)\\\\{\\\\}\\\\$`\\\\\\\\].*\n```\n\n### Batch Operations Tuning\n\nThe batch operations system is highly configurable for different performance requirements:\n\n**Conservative Settings** (Safer for rate limits):\n```properties\ngmail-buddy.gmail-api.rate-limit.batch-operations.delay-between-batches-ms=1000\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-batch-size=25\n```\n\n**Aggressive Settings** (Maximum performance):\n```properties\ngmail-buddy.gmail-api.rate-limit.batch-operations.delay-between-batches-ms=100\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-batch-size=50\n```\n\n**Recommended Production Settings** (Balanced):\n```properties\ngmail-buddy.gmail-api.rate-limit.batch-operations.delay-between-batches-ms=500\ngmail-buddy.gmail-api.rate-limit.batch-operations.max-batch-size=50\n```\n\n---\n\n## 🧪 Testing\n\n### Running Tests\n\n```bash\n# Run all tests\n./mvnw test\n\n# Run specific test class\n./mvnw test -Dtest=GmailServiceTest\n\n# Run tests with coverage report\n./mvnw test jacoco:report\n```\n\n### Test Coverage\n\nThe project maintains high test coverage across all layers:\n- **Unit Tests**: Service logic, validation, and utilities\n- **Integration Tests**: Controller endpoints and OAuth2 flow\n- **Validation Tests**: Input validation and error scenarios\n\nView coverage reports at `target/site/jacoco/index.html` after running tests.\n\n### Test Configuration\n\nThe test suite includes:\n- **Mock OAuth2 Authentication**: Simulates Google authentication\n- **Test Configuration Properties**: Isolated test configurations\n- **Custom Test Utilities**: Builders and factories for test data\n\n---\n\n## 🔒 Security\n\n### OAuth2 Implementation\n- **Secure Token Storage**: Encrypted token persistence\n- **Scope Validation**: Minimal required Gmail permissions\n- **Session Management**: Secure session handling with HttpOnly cookies\n\n### Input Validation\n- **XSS Prevention**: HTML/script tag filtering in queries\n- **SQL Injection Protection**: Parameterized Gmail API queries\n- **Rate Limiting**: Per-user request throttling\n\n### Security Headers\n- **CORS Configuration**: Controlled cross-origin access\n- **Security Headers**: CSP, X-Frame-Options, X-Content-Type-Options\n- **Cookie Security**: Secure, HttpOnly session cookies\n\n---\n\n## 🚀 Development\n\n### Prerequisites for Development\n- Java 17+ (OpenJDK recommended)\n- Maven 3.6+\n- IDE with Spring Boot support (IntelliJ IDEA, VS Code)\n- Git\n\n### Setting Up Development Environment\n\n1. **Clone and setup**\n   ```bash\n   git clone https://github.com/aucontraire/gmail-buddy.git\n   cd gmail-buddy\n   cp .env.example .env\n   # Update .env with your credentials\n   ```\n\n2. **Import into IDE**\n   - Import as Maven project\n   - Ensure Java 17+ is configured\n   - Install Spring Boot plugins if needed\n\n3. **Run in development mode**\n   ```bash\n   ./mvnw spring-boot:run -Dspring-boot.run.profiles=dev\n   ```\n\n### Code Quality\n\nThe project uses several tools to maintain code quality:\n\n```bash\n# Run linting and formatting\n./mvnw spotless:apply\n\n# Run security scan\n./mvnw org.owasp:dependency-check-maven:check\n\n# Run all quality checks\n./mvnw verify\n```\n\n---\n\n## 📚 Documentation\n\n### API Documentation\nWhen running the application, interactive API documentation is available at:\n- **Swagger UI**: `http://localhost:8020/swagger-ui.html`\n- **OpenAPI JSON**: `http://localhost:8020/v3/api-docs`\n\n### Project Documentation\n- **[API Testing Guide](docs/API_TESTING_GUIDE.md)**: Bearer token authentication and Postman setup\n- **[Project Plan](PROJECT_PLAN.md)**: Detailed development roadmap\n- **[Configuration Guide](docs/configuration.md)**: Complete configuration reference\n- **[Deployment Guide](docs/deployment.md)**: Production deployment instructions\n\n---\n\n## 🤝 Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Workflow\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Make your changes with tests\n4. Run the test suite (`./mvnw test`)\n5. Commit your changes (`git commit -m 'Add amazing feature'`)\n6. Push to the branch (`git push origin feature/amazing-feature`)\n7. Open a Pull Request\n\n### Code Standards\n- Follow existing code style and patterns\n- Include unit tests for new functionality\n- Update documentation for API changes\n- Ensure all tests pass before submitting PR\n\n---\n\n## 📝 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n---\n\n## 🆘 Support\n\n### Common Issues\n\n**OAuth2 Client Not Found / Invalid Client**\n- See the [Google Client Verification Guide](docs/GOOGLE_CLIENT_VERIFICATION.md) for step-by-step troubleshooting\n- Verify you're in the correct Google Cloud project\n- Ensure OAuth2 client ID and secret are properly configured\n\n**OAuth2 Redirect URI Mismatch**\n- Ensure `http://localhost:8020/login/oauth2/code/google` is added to Google Cloud Console\n- Verify the redirect URI matches exactly (including port)\n\n**Insufficient Gmail Permissions**\n- Check that Gmail API is enabled in Google Cloud Console\n- Verify OAuth2 scopes include `gmail.readonly`, `gmail.modify`, and `gmail.send` (required for send and draft endpoints)\n- Re-authenticate to refresh token permissions (note: adding `gmail.send` to the scope set invalidates existing refresh tokens; re-consent is required on first startup after this scope is added)\n\n**Test User Restrictions**\n- Add your Google account as a test user in OAuth consent screen\n- Ensure app is not in production mode unless verified\n\n### Getting Help\n\n- **Issues**: [GitHub Issues](https://github.com/aucontraire/gmail-buddy/issues)\n- **Discussions**: [GitHub Discussions](https://github.com/aucontraire/gmail-buddy/discussions)\n\n---\n\n## 🚀 What's Next\n\nCheck out our [Project Plan](PROJECT_PLAN.md) for upcoming features:\n- **Enhanced Monitoring**: Real-time metrics dashboard for batch operations\n- **Async Operations**: Background processing with job queuing\n- **Caching Layer**: Intelligent caching for frequently accessed messages\n- **Advanced Filtering**: Additional Gmail query operators and search capabilities\n- **Webhook Support**: Real-time Gmail push notifications\n\n## 🏗️ Architecture Documentation\n\nFor detailed architectural decisions and implementation details, see:\n\n- **[ADR-001: Foundation Architecture Improvements](docs/architecture/ADR-001-Foundation.md)**\n  - TokenProvider abstraction and security context decoupling\n  - Testing strategy and dependency injection patterns\n\n- **[ADR-002: OAuth2 Security Context Decoupling](docs/architecture/ADR-002-OAuth2-Security-Context-Decoupling.md)**\n  - Dual authentication implementation (OAuth2 + Bearer tokens)\n  - Google TokenInfo endpoint integration\n  - API client authentication support\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**[⭐ Star this repo](https://github.com/aucontraire/gmail-buddy)** if you find it useful!\n\nMade with ❤️ by the Gmail Buddy Team\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faucontraire%2Fgmail-buddy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faucontraire%2Fgmail-buddy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faucontraire%2Fgmail-buddy/lists"}