summaryrefslogtreecommitdiff
path: root/internal/store
diff options
context:
space:
mode:
authorPeter Stone <thepeterstone@gmail.com>2026-08-16 00:03:51 +0000
committerPeter Stone <thepeterstone@gmail.com>2026-08-16 00:03:51 +0000
commit3660486153a16760d2b980e546bbbd29408fb8d4 (patch)
treee29199d88b7365eca0438e41ac23fa0bd533f7c2 /internal/store
parentb55cfbbd433bed6035dfa228ee700e2cca060ca4 (diff)
Replace Google Tasks service-account auth with real OAuth
Service-account auth structurally cannot see a regular user's personal task lists (no equivalent of Calendar's per-item sharing model) -- confirmed via GetTaskLists returning exactly the service account's own empty "My Tasks" list, never the real user's three lists. Zero rows were ever cached in production as a result. Adds a standard 3-legged OAuth flow: /settings/google-tasks/connect redirects to Google's consent screen (AccessTypeOffline+ApprovalForce so a refresh_token is always issued), /callback exchanges the code and persists the token (new oauth_tokens table), /disconnect clears it. GoogleTasksClient now takes an option.ClientOption instead of a credentials file path; NewGoogleTasksOAuthClient wraps it with a dbTokenSource that reloads/refreshes from the DB on each access-token expiry and re-persists -- carefully preserving the original refresh_token when Google's refresh response omits one (it usually does), which would otherwise silently and permanently break future refreshes. Settings page shows connection status and a Connect/Disconnect button. Calendar keeps using service-account auth (that one actually works). Requires a one-time manual step: create an OAuth 2.0 Client ID in Google Cloud Console and set GOOGLE_OAUTH_CLIENT_ID/SECRET in .env -- documented in .env.example.
Diffstat (limited to 'internal/store')
-rw-r--r--internal/store/oauth_tokens.go62
-rw-r--r--internal/store/oauth_tokens_test.go121
2 files changed, 183 insertions, 0 deletions
diff --git a/internal/store/oauth_tokens.go b/internal/store/oauth_tokens.go
new file mode 100644
index 0000000..12df515
--- /dev/null
+++ b/internal/store/oauth_tokens.go
@@ -0,0 +1,62 @@
+package store
+
+import (
+ "database/sql"
+ "time"
+
+ "golang.org/x/oauth2"
+)
+
+// GetOAuthToken returns the stored token for a source (e.g. "google_tasks"),
+// or nil if none has been saved yet (integration not connected).
+func (s *Store) GetOAuthToken(source string) (*oauth2.Token, error) {
+ var accessToken, refreshToken, tokenType string
+ var expiry sql.NullTime
+ err := s.db.QueryRow(`
+ SELECT access_token, refresh_token, token_type, expiry FROM oauth_tokens WHERE source = ?
+ `, source).Scan(&accessToken, &refreshToken, &tokenType, &expiry)
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ tok := &oauth2.Token{
+ AccessToken: accessToken,
+ RefreshToken: refreshToken,
+ TokenType: tokenType,
+ }
+ if expiry.Valid {
+ tok.Expiry = expiry.Time
+ }
+ return tok, nil
+}
+
+// SaveOAuthToken upserts the token for a source. A refreshed token from
+// oauth2.TokenSource sometimes omits RefreshToken (Google only returns it
+// on the initial grant) -- callers must pass the original refresh token
+// through if the new one is empty, since ON CONFLICT here always
+// overwrites rather than preserving the old value.
+func (s *Store) SaveOAuthToken(source string, tok *oauth2.Token) error {
+ var expiry *time.Time
+ if !tok.Expiry.IsZero() {
+ expiry = &tok.Expiry
+ }
+ _, err := s.db.Exec(`
+ INSERT INTO oauth_tokens (source, access_token, refresh_token, token_type, expiry, updated_at)
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
+ ON CONFLICT(source) DO UPDATE SET
+ access_token = excluded.access_token,
+ refresh_token = excluded.refresh_token,
+ token_type = excluded.token_type,
+ expiry = excluded.expiry,
+ updated_at = CURRENT_TIMESTAMP
+ `, source, tok.AccessToken, tok.RefreshToken, tok.TokenType, expiry)
+ return err
+}
+
+// DeleteOAuthToken removes a source's stored token (disconnect).
+func (s *Store) DeleteOAuthToken(source string) error {
+ _, err := s.db.Exec(`DELETE FROM oauth_tokens WHERE source = ?`, source)
+ return err
+}
diff --git a/internal/store/oauth_tokens_test.go b/internal/store/oauth_tokens_test.go
new file mode 100644
index 0000000..20c4a79
--- /dev/null
+++ b/internal/store/oauth_tokens_test.go
@@ -0,0 +1,121 @@
+package store
+
+import (
+ "database/sql"
+ "path/filepath"
+ "testing"
+ "time"
+
+ _ "github.com/mattn/go-sqlite3"
+ "golang.org/x/oauth2"
+)
+
+func newOAuthTokensTestStore(t *testing.T) *Store {
+ t.Helper()
+ dbPath := filepath.Join(t.TempDir(), "test.db")
+ db, err := sql.Open("sqlite3", dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Close() })
+ if _, err := db.Exec(`
+ CREATE TABLE oauth_tokens (
+ source TEXT PRIMARY KEY,
+ access_token TEXT NOT NULL,
+ refresh_token TEXT NOT NULL,
+ token_type TEXT NOT NULL DEFAULT 'Bearer',
+ expiry DATETIME,
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
+ )
+ `); err != nil {
+ t.Fatal(err)
+ }
+ return &Store{db: db}
+}
+
+func TestGetOAuthToken_NotConnected_ReturnsNil(t *testing.T) {
+ s := newOAuthTokensTestStore(t)
+
+ tok, err := s.GetOAuthToken("google_tasks")
+ if err != nil {
+ t.Fatalf("GetOAuthToken: %v", err)
+ }
+ if tok != nil {
+ t.Errorf("tok = %+v, want nil", tok)
+ }
+}
+
+func TestSaveOAuthToken_ThenGet_RoundTrips(t *testing.T) {
+ s := newOAuthTokensTestStore(t)
+
+ expiry := time.Now().Add(time.Hour).Truncate(time.Second)
+ in := &oauth2.Token{
+ AccessToken: "access-1",
+ RefreshToken: "refresh-1",
+ TokenType: "Bearer",
+ Expiry: expiry,
+ }
+ if err := s.SaveOAuthToken("google_tasks", in); err != nil {
+ t.Fatalf("SaveOAuthToken: %v", err)
+ }
+
+ got, err := s.GetOAuthToken("google_tasks")
+ if err != nil {
+ t.Fatalf("GetOAuthToken: %v", err)
+ }
+ if got == nil {
+ t.Fatal("got nil, want a token")
+ }
+ if got.AccessToken != "access-1" || got.RefreshToken != "refresh-1" || got.TokenType != "Bearer" {
+ t.Errorf("got = %+v, want access-1/refresh-1/Bearer", got)
+ }
+ if !got.Expiry.Equal(expiry) {
+ t.Errorf("Expiry = %v, want %v", got.Expiry, expiry)
+ }
+}
+
+func TestSaveOAuthToken_Upserts(t *testing.T) {
+ s := newOAuthTokensTestStore(t)
+
+ if err := s.SaveOAuthToken("google_tasks", &oauth2.Token{AccessToken: "old", RefreshToken: "refresh-1"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.SaveOAuthToken("google_tasks", &oauth2.Token{AccessToken: "new", RefreshToken: "refresh-2"}); err != nil {
+ t.Fatal(err)
+ }
+
+ got, err := s.GetOAuthToken("google_tasks")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.AccessToken != "new" || got.RefreshToken != "refresh-2" {
+ t.Errorf("got = %+v, want access token updated to new/refresh-2", got)
+ }
+
+ var count int
+ if err := s.db.QueryRow(`SELECT COUNT(*) FROM oauth_tokens`).Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 1 {
+ t.Errorf("row count = %d, want 1 (upsert, not insert)", count)
+ }
+}
+
+func TestDeleteOAuthToken_RemovesRow(t *testing.T) {
+ s := newOAuthTokensTestStore(t)
+
+ if err := s.SaveOAuthToken("google_tasks", &oauth2.Token{AccessToken: "a", RefreshToken: "r"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DeleteOAuthToken("google_tasks"); err != nil {
+ t.Fatalf("DeleteOAuthToken: %v", err)
+ }
+
+ got, err := s.GetOAuthToken("google_tasks")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != nil {
+ t.Errorf("got = %+v, want nil after delete", got)
+ }
+}