mirror of
https://github.com/sstent/FitTrack_GarminSync.git
synced 2026-01-25 16:41:41 +00:00
Compare commits
5 Commits
02fa8aa1eb
...
010-specif
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b0ba76c22 | |||
| 846725a81e | |||
| b9cc50f69a | |||
| 805915419f | |||
| 4443e10037 |
@@ -24,6 +24,7 @@ def login(ctx: CliContext, username: str, password: str, mfa_code: Optional[str]
|
||||
"""Authenticate with your Garmin account"""
|
||||
|
||||
async def run_login():
|
||||
nonlocal mfa_code # Add this line
|
||||
api_client = ctx.api_client # Use api_client from context
|
||||
if api_client is None:
|
||||
click.echo("Error: API client not initialized.")
|
||||
|
||||
111
contracts/garmin_auth_session.json
Normal file
111
contracts/garmin_auth_session.json
Normal file
@@ -0,0 +1,111 @@
|
||||
{
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "Garmin Sync Authentication API",
|
||||
"version": "1.0.0",
|
||||
"description": "API for managing Garmin Connect authentication and session persistence."
|
||||
},
|
||||
"paths": {
|
||||
"/api/v1/garmin/session/login": {
|
||||
"post": {
|
||||
"summary": "Initiate Garmin Connect Login",
|
||||
"operationId": "login_garmin_session_login_post",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"username": { "type": "string" },
|
||||
"password": { "type": "string", "format": "password" }
|
||||
},
|
||||
"required": ["username", "password"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Login successful or MFA required",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": { "type": "string", "enum": ["SUCCESS", "MFA_REQUIRED"] },
|
||||
"message": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Invalid credentials"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/garmin/session/mfa": {
|
||||
"post": {
|
||||
"summary": "Submit MFA Code",
|
||||
"operationId": "mfa_garmin_session_mfa_post",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mfa_code": { "type": "string" }
|
||||
},
|
||||
"required": ["mfa_code"]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "MFA submission successful, session persisted",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": { "type": "string", "example": "SUCCESS" },
|
||||
"message": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Invalid MFA code or no pending login"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/garmin/session/status": {
|
||||
"get": {
|
||||
"summary": "Get Garmin Session Status",
|
||||
"operationId": "status_garmin_session_status_get",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Current status of the persisted session",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": { "type": "string", "enum": ["VALID", "MISSING", "EXPIRED", "MFA_PENDING"] },
|
||||
"last_validated": { "type": "string", "format": "date-time" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# Specification Quality Checklist: Persist Garmin Authentication for Stateless Sync
|
||||
|
||||
**Purpose**: Validate specification completeness and quality before proceeding to planning
|
||||
**Created**: 2025-12-22
|
||||
**Feature**: [specs/010-specification-overview-the/spec.md](specs/010-specification-overview-the/spec.md)
|
||||
|
||||
## Content Quality
|
||||
|
||||
- [x] No implementation details (languages, frameworks, APIs)
|
||||
- [x] Focused on user value and business needs
|
||||
- [x] Written for non-technical stakeholders
|
||||
- [x] All mandatory sections completed
|
||||
|
||||
## Requirement Completeness
|
||||
|
||||
- [x] No [NEEDS CLARIFICATION] markers remain
|
||||
- [x] Requirements are testable and unambiguous
|
||||
- [x] Success criteria are measurable
|
||||
- [x] Success criteria are technology-agnostic (no implementation details)
|
||||
- [x] All acceptance scenarios are defined
|
||||
- [x] Edge cases are identified
|
||||
- [x] Scope is clearly bounded
|
||||
- [x] Dependencies and assumptions identified
|
||||
|
||||
## Feature Readiness
|
||||
|
||||
- [x] All functional requirements have clear acceptance criteria
|
||||
- [x] User scenarios cover primary flows
|
||||
- [x] Feature meets measurable outcomes defined in Success Criteria
|
||||
- [x] No implementation details leak into specification
|
||||
|
||||
## Notes
|
||||
|
||||
- All items passed validation. The specification is ready for the next phase.
|
||||
39
specs/010-specification-overview-the/data-model.md
Normal file
39
specs/010-specification-overview-the/data-model.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# Data Model: Garmin Authentication State
|
||||
|
||||
**Date**: 2025-12-22
|
||||
|
||||
This document defines the data model for storing a user's persisted Garmin Connect authentication state, as required by the `Persist Garmin Authentication for Stateless Sync` feature.
|
||||
|
||||
## Entity: `GarminAuthenticationState`
|
||||
|
||||
This entity represents a user's authenticated session with Garmin Connect. It is designed to be stored in the CentralDB and is associated with a single application user.
|
||||
|
||||
### Fields
|
||||
|
||||
| Field Name | Data Type | Nullable | Description |
|
||||
| ----------------- | ------------- | -------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `user_id` | Foreign Key | False | The unique identifier for the application user this authentication state belongs to. |
|
||||
| `session_data` | Text / Blob | True | The serialized, possibly encrypted, session data from the `garth` library. Null if no session is stored. |
|
||||
| `mfa_pending` | Boolean | False | A flag indicating if the authentication process is currently paused, awaiting an MFA code from the user. |
|
||||
| `last_validated` | Timestamp | True | The timestamp when the session was last successfully used to communicate with the Garmin API. |
|
||||
| `created_at` | Timestamp | False | The timestamp when this record was created. |
|
||||
| `updated_at` | Timestamp | False | The timestamp when this record was last updated. |
|
||||
|
||||
### Relationships
|
||||
|
||||
- **Belongs to**: `User`. A one-to-one relationship exists between a `User` and their `GarminAuthenticationState`.
|
||||
|
||||
### State Transitions
|
||||
|
||||
The `GarminAuthenticationState` entity can transition through several states:
|
||||
|
||||
1. **Non-existent**: No record exists for the user. This is the initial state.
|
||||
2. **MFA Pending**: A record exists with `mfa_pending = true` and `session_data` is likely `null`. This occurs after an initial login attempt triggers an MFA challenge.
|
||||
3. **Active / Persisted**: A record exists with `mfa_pending = false` and `session_data` is populated. This is the state for a successfully authenticated user, allowing for stateless background syncs.
|
||||
4. **Invalid / Stale**: The `session_data` is present but no longer valid for authentication with Garmin's servers, and it could not be refreshed. This state is not explicitly stored but is determined at runtime, leading to the clearing of the `session_data`.
|
||||
|
||||
### Validation Rules
|
||||
|
||||
- `user_id` must correspond to an existing user in the `users` table.
|
||||
- `session_data` should be stored in an encrypted format to protect sensitive session information. [NEEDS CLARIFICATION: The encryption method and key management strategy needs to be defined during implementation.]
|
||||
- `last_validated` should be updated after every successful background sync or API call to Garmin Connect.
|
||||
61
specs/010-specification-overview-the/plan.md
Normal file
61
specs/010-specification-overview-the/plan.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Implementation Plan: Persist Garmin Authentication for Stateless Sync
|
||||
|
||||
**Feature Spec**: [/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/spec.md](/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/spec.md)
|
||||
**Branch**: `010-specification-overview-the`
|
||||
|
||||
## Technical Context
|
||||
|
||||
This section outlines the technologies and architectural decisions for implementing the feature.
|
||||
|
||||
- **Authentication Library**: `garth` will be used for handling the Garmin Connect authentication lifecycle, including login, MFA, and session serialization.
|
||||
- **API Framework**: FastAPI will be used to build the new REST API endpoints, with Pydantic for data modeling.
|
||||
- **Database**: The CentralDB (PostgreSQL/SQLite) will store the persisted session data.
|
||||
- **ORM**: SQLAlchemy will be used to define the `GarminAuthenticationState` model and interact with the database.
|
||||
- **Session Storage**: The serialized `garth` session will be stored as a Text/Blob field in the `GarminAuthenticationState` table.
|
||||
- **Background Jobs**: Existing background job services will be modified to load the session from the DB, use it, and update it if refreshed.
|
||||
|
||||
## Constitution Check
|
||||
|
||||
This feature plan is evaluated against the project's constitution.
|
||||
|
||||
- [x] **I. Python Modernization**: All new code will use Python 3.13+ with type hints.
|
||||
- [x] **II. Virtual Environment Isolation**: Development will occur within the existing `.venv`.
|
||||
- [x] **III. Test-Driven Development**: Tests will be created for the new services and endpoints.
|
||||
- [x] **V. Project Structure Standards**: New code will be placed in the appropriate `src/api`, `src/models`, and `src/services` directories.
|
||||
- [x] **VI. Service-Specific Standards**:
|
||||
- `centraldb_service`: The plan uses the mandated SQLAlchemy 2.0+ and FastAPI.
|
||||
- `garminsync_service`: The plan directly addresses OAuth flows for Garmin Connect.
|
||||
- [x] **X. API Standards**: A new FastAPI router will be created, and the OpenAPI contract will be published.
|
||||
|
||||
**Result**: The plan is fully compliant with the project constitution.
|
||||
|
||||
---
|
||||
|
||||
## Phase 0: Outline & Research
|
||||
|
||||
The research phase focused on validating the use of `garth` and confirming its integration with the existing technology stack.
|
||||
|
||||
- **`research.md`**: [/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/research.md](/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/research.md)
|
||||
|
||||
All technical unknowns have been resolved. The chosen stack is `FastAPI` + `SQLAlchemy` + `garth`.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Design & Contracts
|
||||
|
||||
This phase defines the data structures and API contracts for the feature.
|
||||
|
||||
- **`data-model.md`**: [/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/data-model.md](/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/data-model.md)
|
||||
- **API Contracts**:
|
||||
- [/home/sstent/Projects/FitTrack/GarminSync/contracts/garmin_auth_session.json](/home/sstent/Projects/FitTrack/GarminSync/contracts/garmin_auth_session.json)
|
||||
- **`quickstart.md`**: [/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/quickstart.md](/home/sstent/Projects/FitTrack/GarminSync/specs/010-specification-overview-the/quickstart.md)
|
||||
|
||||
### Agent Context Update
|
||||
|
||||
No new technologies are being introduced that are not already listed in the agent's context (`GEMINI.md`). The plan uses the existing stack (`FastAPI`, `garth`, `SQLAlchemy`, `httpx`, `pydantic`). Therefore, no update to the agent context is required at this time.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Implementation Tasks
|
||||
|
||||
This phase will be detailed in the next step (`/speckit.tasks`) and will involve creating the actual Python code based on the design artifacts from Phase 1.
|
||||
51
specs/010-specification-overview-the/quickstart.md
Normal file
51
specs/010-specification-overview-the/quickstart.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Quickstart: Implementing Persisted Garmin Authentication
|
||||
|
||||
**Date**: 2025-12-22
|
||||
|
||||
This guide provides a high-level overview for developers implementing the `Persist Garmin Authentication for Stateless Sync` feature.
|
||||
|
||||
## 1. Database Model
|
||||
|
||||
- **Action**: Implement the `GarminAuthenticationState` model as defined in `data-model.md`.
|
||||
- **File**: Create a new model in `src/models/garmin_auth_state.py`.
|
||||
- **Details**: Ensure the model includes `user_id`, `session_data`, `mfa_pending`, and `last_validated` fields. Use SQLAlchemy and create a corresponding Alembic migration script.
|
||||
|
||||
## 2. API Endpoints
|
||||
|
||||
- **Action**: Implement the three new endpoints defined in `contracts/garmin_auth_session.json`.
|
||||
- **Files**: Add a new router in `src/api/v1/auth.py`.
|
||||
- **Logic**:
|
||||
- `POST /api/v1/garmin/session/login`:
|
||||
- Initialize `garth`.
|
||||
- Call `garth.login(username, password)`.
|
||||
- If `garth.MFARequired` is raised, create/update the `GarminAuthenticationState` record with `mfa_pending=True` and return `{"status": "MFA_REQUIRED"}`.
|
||||
- If successful, `dumps()` the session, save it to `session_data`, set `mfa_pending=False`, and return `{"status": "SUCCESS"}`.
|
||||
- `POST /api/v1/garmin/session/mfa`:
|
||||
- Load the pending `garth` client state.
|
||||
- Call `garth.enter_mfa(mfa_code)`.
|
||||
- On success, `dumps()` the completed session and persist it to the database.
|
||||
- `GET /api/v1/garmin/session/status`:
|
||||
- Query the `GarminAuthenticationState` for the current user.
|
||||
- Perform a lightweight validation call with the loaded session (e.g., `garth.connectapi.get_user_settings()`).
|
||||
- Return the status (`VALID`, `MISSING`, `EXPIRED`, `MFA_PENDING`).
|
||||
|
||||
## 3. Update Background Sync Services
|
||||
|
||||
- **Action**: Modify the existing background sync services (`GarminActivityService`, `GarminHealthService`) to use the persisted session.
|
||||
- **Files**: Update the relevant service files in `src/services/`.
|
||||
- **Pattern: Load-Use-Update**:
|
||||
1. **Load**: At the start of the job, fetch the `session_data` from the database.
|
||||
2. **Initialize**: Call `garth.client.loads(session_data)` to initialize the client.
|
||||
3. **Use**: Perform the sync operations. `garth` will handle automatic token refreshes.
|
||||
4. **Update**: Before the job finishes, check if the session was modified (refreshed). If so, `dumps()` the new session and update the `session_data` field in the database. This is critical for maintaining a fresh session for the next job.
|
||||
|
||||
## 4. Error Handling
|
||||
|
||||
- Implement logic to catch `garth` exceptions for invalid sessions.
|
||||
- If a session is invalid and cannot be refreshed, update the sync job status to `AUTH_EXPIRED` and clear the `session_data` from the database.
|
||||
|
||||
## 5. Testing
|
||||
|
||||
- Write unit tests for the new API endpoints and the Load-Use-Update pattern.
|
||||
- Write integration tests that cover the full login (including MFA) and background sync flow.
|
||||
- Mock the `garth` library to simulate different scenarios: successful login, MFA required, invalid session, and token refresh.
|
||||
36
specs/010-specification-overview-the/research.md
Normal file
36
specs/010-specification-overview-the/research.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Research: Persist Garmin Authentication for Stateless Sync
|
||||
|
||||
**Date**: 2025-12-22
|
||||
|
||||
This document outlines the decisions made regarding the technical implementation for persisting Garmin authentication sessions.
|
||||
|
||||
## 1. Authentication Library
|
||||
|
||||
- **Decision**: Use the `garth` library for handling Garmin Connect authentication.
|
||||
- **Rationale**: The initial feature description explicitly mentions `garth`. This library is purpose-built for interacting with the Garmin Connect API, handles MFA, and most importantly, supports session export (`dumps`) and import (`loads`). This is the cornerstone of the "stateless sync" requirement, allowing us to persist the session state. It aligns with the existing project dependencies mentioned in `GEMINI.md`.
|
||||
- **Alternatives considered**:
|
||||
- `garminconnect`: Another popular library. While it's great for fetching data, its session management is not as explicitly designed for serialization and deserialization as `garth`'s, which is critical for this feature. We will continue to use it for data fetching, but `garth` will manage the authentication lifecycle.
|
||||
|
||||
## 2. Session Data Storage
|
||||
|
||||
- **Decision**: Store the serialized `garth` session in the CentralDB.
|
||||
- **Rationale**: The feature spec requires a persistent store. The CentralDB (as defined in the constitution and project context) is the designated single source of truth for user-related data. Storing the session here ensures that any service or background worker can access it. The session data will be stored as a text or blob type.
|
||||
- **Alternatives considered**:
|
||||
- **Redis Cache**: Could be used for faster access, but it's not guaranteed to be persistent. The constitution mentions Redis for rate limiting, not for primary data storage.
|
||||
- **Local File System**: Not suitable for a distributed or stateless service architecture, as different workers would not have access to the same session file.
|
||||
|
||||
## 3. API Framework
|
||||
|
||||
- **Decision**: Use FastAPI for the new API endpoints.
|
||||
- **Rationale**: The project constitution mandates FastAPI for all API services. It's already in use in the project, ensuring consistency. Pydantic, which comes with FastAPI, will be used for request/response modeling.
|
||||
- **Alternatives considered**: None, as this is a strict requirement from the project constitution.
|
||||
|
||||
## 4. Database Interaction
|
||||
|
||||
- **Decision**: Use SQLAlchemy to interact with the CentralDB.
|
||||
- **Rationale**: The constitution specifies SQLAlchemy as the ORM. This ensures that the data model for the `GarminAuthenticationState` is managed consistently with other project models.
|
||||
- **Alternatives considered**: None. This is a constitutional requirement.
|
||||
|
||||
## Conclusion
|
||||
|
||||
The technical approach is a straightforward integration of `garth`'s session management with the existing FastAPI and SQLAlchemy stack. All technical choices are dictated by the feature's core requirements and the project's established constitution.
|
||||
87
specs/010-specification-overview-the/spec.md
Normal file
87
specs/010-specification-overview-the/spec.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# Feature Specification: Persist Garmin Authentication for Stateless Sync
|
||||
|
||||
**Feature Branch**: `010-specification-overview-the`
|
||||
**Created**: 2025-12-22
|
||||
**Status**: Draft
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
### User Story 1 - Seamless Background Sync (Priority: P1)
|
||||
|
||||
A user's Garmin data (activities, health metrics) is synced automatically in the background without requiring them to log in repeatedly.
|
||||
|
||||
**Why this priority**: This is the core value proposition of the feature, directly addressing the pain point of frequent manual logins and enabling reliable, automated data synchronization.
|
||||
|
||||
**Independent Test**: Can be tested by triggering a background sync job for a user with a persisted session and verifying that new activities from Garmin Connect appear in the system without any manual user interaction.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a user has a valid, persisted Garmin session in the database, **When** a background sync job is triggered, **Then** the system successfully fetches new data from Garmin Connect.
|
||||
2. **Given** a user's persisted session token has expired but is refreshable, **When** a background sync job is triggered, **Then** the system automatically refreshes the session, saves the new session state, and successfully completes the sync.
|
||||
|
||||
---
|
||||
|
||||
### User Story 2 - Initial Login with MFA (Priority: P2)
|
||||
|
||||
A user performs a one-time login through the system. If Garmin requires Multi-Factor Authentication (MFA), the user is prompted to enter the code to complete the login, and the session is then persisted.
|
||||
|
||||
**Why this priority**: This handles the necessary onboarding and authentication path for users, including the common MFA challenge, which is critical for establishing the initial persistent session.
|
||||
|
||||
**Independent Test**: Can be tested by a new user logging in with credentials known to trigger an MFA prompt. The test is successful if the system prompts for the MFA code and, upon submission of a valid code, successfully establishes and persists the session.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a user is performing an initial login and their account requires MFA, **When** they submit their username and password, **Then** the system indicates that an MFA code is required.
|
||||
2. **Given** the system is waiting for an MFA code, **When** the user submits the correct MFA code, **Then** the system completes the authentication, persists the session, and confirms a successful login.
|
||||
|
||||
---
|
||||
|
||||
### User Story 3 - Session Invalidation and Re-authentication (Priority: P3)
|
||||
|
||||
If a persisted Garmin session becomes invalid (e.g., user revoked access from Garmin's side) and cannot be refreshed, the system gracefully handles the failure and notifies the user that they need to re-authenticate.
|
||||
|
||||
**Why this priority**: This ensures system resilience and clear communication with the user when the authentication link is broken, preventing silent failures.
|
||||
|
||||
**Independent Test**: Can be tested by manually invalidating a user's session (e.g., revoking app permissions in Garmin Connect), then triggering a background sync. The test is successful if the sync job fails with a clear "authentication expired" status and the persisted session data is cleared.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a user's persisted session is invalid and not refreshable, **When** a background sync is attempted, **Then** the sync job's status is marked as `AUTH_EXPIRED`.
|
||||
2. **Given** a sync job has failed due to an unrecoverable authentication error, **Then** the invalid session data is cleared from the database to prevent further failed attempts.
|
||||
|
||||
### Edge Cases
|
||||
|
||||
- What happens if a user enters the wrong MFA code multiple times?
|
||||
- How does the system handle network errors during session validation or refresh?
|
||||
- What if the database is unavailable when the system tries to load or save the session state?
|
||||
- How does the system behave if the session data in the database is corrupted or malformed?
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
- **FR-001**: The system MUST allow a user to authenticate with their Garmin Connect credentials.
|
||||
- **FR-002**: The system MUST be able to handle Multi-Factor Authentication (MFA) challenges during the login process.
|
||||
- **FR-003**: The system MUST securely persist a user's Garmin Connect authentication state to eliminate the need for repeated logins.
|
||||
- **FR-004**: Background data synchronization jobs MUST use the persisted authentication state to connect to Garmin Connect.
|
||||
- **FR-005**: The system MUST automatically refresh the authentication state if it expires and a refresh is possible.
|
||||
- **FR-006**: After a successful refresh, the system MUST update the persisted authentication state with the new details.
|
||||
- **FR-007**: If the authentication state becomes invalid and cannot be refreshed, the system MUST record a sync failure with a clear authentication error status.
|
||||
- **FR-008**: The system MUST clear any invalid, persisted authentication state to force a new login.
|
||||
- **FR-009**: The system MUST provide a way to check the current status of the persisted authentication (e.g., valid, missing, expired).
|
||||
|
||||
### Key Entities *(include if feature involves data)*
|
||||
|
||||
- **GarminAuthenticationState**: Represents a user's authenticated session with Garmin Connect.
|
||||
- **Attributes**: Authentication Data (stores necessary session info), MFA Pending (flag for pending MFA), Last Validated (timestamp).
|
||||
- **Relationships**: Associated with a single User.
|
||||
|
||||
## Success Criteria *(mandatory)*
|
||||
|
||||
### Measurable Outcomes
|
||||
|
||||
- **SC-001**: Reduce the number of user-facing login prompts by 99% for active users with valid credentials over a 30-day period.
|
||||
- **SC-002**: 99.9% of background sync jobs for users with a valid persisted session should initiate successfully without requiring manual login.
|
||||
- **SC-003**: The end-to-end success rate for background syncs, including session loading, execution, and potential session refresh/save, should exceed 98%.
|
||||
- **SC-004**: System should successfully handle MFA-based logins on the first attempt for 95% of users who are required to enter an MFA code.
|
||||
- **SC-005**: In the case of a session invalidation, the system must detect the failure, mark the sync status appropriately, and clear the session within 5 minutes.
|
||||
110
specs/010-specification-overview-the/tasks.md
Normal file
110
specs/010-specification-overview-the/tasks.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# Task Breakdown: Persist Garmin Authentication for Stateless Sync
|
||||
|
||||
This document breaks down the implementation of the "Persist Garmin Authentication for Stateless Sync" feature into actionable, dependency-ordered tasks.
|
||||
|
||||
**Implementation Strategy**:
|
||||
The feature will be delivered in increments based on user story dependencies. The foundational database work will be done first. Then, we will implement the login/MFA flow (US2) to enable session creation. With sessions available, we'll implement the core background sync logic (US1). Finally, we'll add session invalidation and status checks (US3). This ensures a logical build-up of functionality.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Foundational Setup
|
||||
|
||||
**Goal**: Prepare the database schema and core data structures. This phase must be completed before any user story implementation can begin.
|
||||
|
||||
- **T001**: **[DB Model]** Define the `GarminAuthenticationState` SQLAlchemy model in a new file `src/models/garmin_auth_state.py`.
|
||||
- **T002**: **[DB Migration]** Create a new Alembic migration script to add the `garmin_authentication_state` table to the database.
|
||||
- **T003**: **[Test]** Write a unit test in `tests/unit/models/test_garmin_auth_state.py` to verify the model's structure and relationships. [P]
|
||||
- **T004**: **[Pydantic Model]** Define Pydantic schemas for API requests and responses related to authentication (Login, MFA, Status) in `src/models/schemas/garmin_auth.py`. [P]
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: [US2] Initial Login and MFA Flow
|
||||
|
||||
**User Story**: A user can perform a one-time login, handle an MFA challenge, and have their session persisted.
|
||||
**Independent Test**: A user can log in via the API, enter an MFA code when prompted, and a valid session will be stored in the database, verifiable by checking the `garmin_authentication_state` table.
|
||||
|
||||
- **T005**: **[Test]** Create an API test file `tests/api/test_auth_api.py` with tests for the `POST /login` and `POST /mfa` endpoints, covering success, MFA required, and failure cases.
|
||||
- **T006**: **[Service]** Create a new service `src/services/garmin_auth_service.py` containing the business logic for logging in, handling MFA, and saving the session to the database using `garth`.
|
||||
- **T007**: **[API Endpoint]** Create a new API router in `src/api/v1/auth.py`. Implement the `POST /api/v1/garmin/session/login` endpoint, calling the auth service.
|
||||
- **T008**: **[API Endpoint]** Implement the `POST /api/v1/garmin/session/mfa` endpoint in `src/api/v1/auth.py`, calling the auth service.
|
||||
- **T009**: **[Test]** Write unit tests in `tests/unit/services/test_garmin_auth_service.py` to mock `garth` and the database, verifying the service logic for login and MFA handling. [P]
|
||||
|
||||
**Checkpoint**: User Story 2 is complete. The system can now authenticate users and persist their sessions.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: [US1] Seamless Background Sync
|
||||
|
||||
**User Story**: Background sync jobs can run automatically using the persisted session.
|
||||
**Independent Test**: Trigger a background sync for a user with a valid persisted session. Verify that the job completes successfully without any manual intervention and that new data is fetched. Test the auto-refresh mechanism by using a slightly expired (but refreshable) mock session.
|
||||
|
||||
- **T010**: **[Test]** Update tests for background sync services (e.g., `tests/unit/services/test_activity_sync.py`) to include scenarios where the service loads a session from the database.
|
||||
- **T011**: **[Service]** Modify the existing background sync services (e.g., `GarminActivityService`) to implement the "Load-Use-Update" pattern:
|
||||
- Load the `GarminAuthenticationState` from the DB.
|
||||
- Initialize `garth` with the session data.
|
||||
- Perform the sync.
|
||||
- If the session was refreshed by `garth`, update the `session_data` and `last_validated` fields in the database.
|
||||
|
||||
**Checkpoint**: User Story 1 is complete. The system can now perform its core function of stateless, automated synchronization.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: [US3] Session Invalidation and Status
|
||||
|
||||
**User Story**: The system can detect an invalid session, report it, and allow a client to check the session's status.
|
||||
**Independent Test**: For a user with a persisted session, manually invalidate it. Trigger a sync and verify the job status becomes `AUTH_EXPIRED` and the session data is cleared from the DB. Also, call the `GET /status` endpoint before and after to see the status change.
|
||||
|
||||
- **T012**: **[Test]** Add API tests to `tests/api/test_auth_api.py` for the `GET /status` endpoint.
|
||||
- **T013**: **[API Endpoint]** Implement the `GET /api/v1/garmin/session/status` endpoint in `src/api/v1/auth.py`. The endpoint should use the auth service to validate the token. [P]
|
||||
- **T014**: **[Test]** Add unit tests to `tests/unit/services/test_garmin_auth_service.py` for the session validation logic.
|
||||
- **T015**: **[Service]** Add a `get_session_status` method to `src/services/garmin_auth_service.py` that performs a lightweight check on the session.
|
||||
- **T016**: **[Service]** Enhance the error handling in background sync services. If a sync fails with an unrecoverable auth error, the service must call a method in the auth service to clear the `session_data` from the database.
|
||||
|
||||
**Checkpoint**: User Story 3 is complete. The system is now resilient to session invalidation.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Polish & Integration
|
||||
|
||||
- **T017**: **[Documentation]** Update the main `README.md` and any relevant developer docs to explain the new authentication flow.
|
||||
- **T018**: **[CI/CD]** Ensure all new tests are integrated into the CI pipeline and that all pre-commit hooks pass.
|
||||
|
||||
## Dependencies
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Phase 1 [Foundational]
|
||||
T001(DB Model) --> T002(DB Migration);
|
||||
T003(Test Model);
|
||||
T004(Pydantic Model);
|
||||
end
|
||||
|
||||
subgraph Phase 2 [US2 - Login/MFA]
|
||||
T005(API Tests) --> T007(Login Endpoint);
|
||||
T007 --> T008(MFA Endpoint);
|
||||
T009(Unit Tests) --> T006(Auth Service);
|
||||
T007 & T008 --> T006;
|
||||
end
|
||||
|
||||
subgraph Phase 3 [US1 - Background Sync]
|
||||
T010(Sync Tests) --> T011(Update Sync Service);
|
||||
end
|
||||
|
||||
subgraph Phase 4 [US3 - Invalidation]
|
||||
T012(Status API Test) --> T013(Status Endpoint);
|
||||
T014(Status Unit Test) --> T015(Status Service Logic);
|
||||
T013 --> T015;
|
||||
T011 --> T016(Enhance Error Handling);
|
||||
end
|
||||
|
||||
Phase 1 --> Phase 2;
|
||||
Phase 2 --> Phase 3;
|
||||
Phase 3 --> Phase 4;
|
||||
Phase 4 --> T017(Docs) & T018(CI/CD);
|
||||
```
|
||||
|
||||
## Parallel Execution Examples
|
||||
|
||||
- **Within Phase 1**: `T003` and `T004` can be done in parallel while `T001` and `T002` are being worked on sequentially.
|
||||
- **Within Phase 2**: The API tests (`T005`) and unit tests (`T009`) can be developed in parallel before the service (`T006`) and endpoints (`T007`, `T008`) are implemented.
|
||||
- **Within Phase 4**: The status endpoint (`T012`-`T015`) can be developed in parallel with the error handling enhancements for the sync service (`T016`).
|
||||
Reference in New Issue
Block a user