-
Notifications
You must be signed in to change notification settings - Fork 59
feat: per-user OAuth2 connections (Strava, Spotify, GitHub, Google) #912
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nsluke
wants to merge
3
commits into
tronbyt:main
Choose a base branch
from
nsluke:feat/oauth-connections
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| // Package connections implements the third-party OAuth2 connection store | ||
| // that lets pixlet apps (Strava, Spotify, Google Calendar, ...) render with | ||
| // a fresh access token without users hand-pasting refresh tokens. | ||
| package connections | ||
|
|
||
| import ( | ||
| "crypto/aes" | ||
| "crypto/cipher" | ||
| "crypto/rand" | ||
| "crypto/sha256" | ||
| "errors" | ||
| "io" | ||
| ) | ||
|
|
||
| // deriveKey turns the server's session secret_key (any length) into a stable | ||
| // 32-byte AES-256 key. We use a fixed info string so rotating session keys | ||
| // (which would also rotate this key) intentionally invalidates stored tokens. | ||
| func deriveKey(secret string) [32]byte { | ||
| return sha256.Sum256([]byte("tronbyt-connections-v1\x00" + secret)) | ||
| } | ||
|
|
||
| // Seal encrypts plaintext with AES-256-GCM. Output layout: nonce || ciphertext. | ||
| func Seal(secret string, plaintext []byte) ([]byte, error) { | ||
| if len(plaintext) == 0 { | ||
| return nil, nil | ||
| } | ||
| key := deriveKey(secret) | ||
| block, err := aes.NewCipher(key[:]) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| gcm, err := cipher.NewGCM(block) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| nonce := make([]byte, gcm.NonceSize()) | ||
| if _, err := io.ReadFull(rand.Reader, nonce); err != nil { | ||
| return nil, err | ||
| } | ||
| return gcm.Seal(nonce, nonce, plaintext, nil), nil | ||
| } | ||
|
|
||
| // Open reverses Seal. Empty input returns empty output (treated as "not set"). | ||
| func Open(secret string, sealed []byte) ([]byte, error) { | ||
| if len(sealed) == 0 { | ||
| return nil, nil | ||
| } | ||
| key := deriveKey(secret) | ||
| block, err := aes.NewCipher(key[:]) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| gcm, err := cipher.NewGCM(block) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if len(sealed) < gcm.NonceSize() { | ||
| return nil, errors.New("connections: sealed token too short") | ||
| } | ||
| nonce, ct := sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():] | ||
| return gcm.Open(nil, nonce, ct, nil) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| package connections | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestSealOpenRoundtrip(t *testing.T) { | ||
| secret := "this-is-a-test-secret" | ||
| plaintext := []byte("strava-refresh-token-1234567890") | ||
|
|
||
| sealed, err := Seal(secret, plaintext) | ||
| require.NoError(t, err) | ||
| require.NotEmpty(t, sealed) | ||
| assert.False(t, bytes.Equal(sealed, plaintext), "sealed output should differ from plaintext") | ||
|
|
||
| opened, err := Open(secret, sealed) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, plaintext, opened) | ||
| } | ||
|
|
||
| func TestSealNonDeterministic(t *testing.T) { | ||
| // AES-GCM uses a random nonce, so sealing the same plaintext twice | ||
| // must produce different ciphertexts. This guards against ECB-style | ||
| // regressions if anyone "simplifies" the implementation later. | ||
| secret := "secret" | ||
| plaintext := []byte("same-plaintext-each-time") | ||
|
|
||
| a, err := Seal(secret, plaintext) | ||
| require.NoError(t, err) | ||
| b, err := Seal(secret, plaintext) | ||
| require.NoError(t, err) | ||
| assert.False(t, bytes.Equal(a, b), "two seals of the same plaintext must differ") | ||
| } | ||
|
|
||
| func TestOpenWithWrongKey(t *testing.T) { | ||
| sealed, err := Seal("right-secret", []byte("payload")) | ||
| require.NoError(t, err) | ||
|
|
||
| _, err = Open("wrong-secret", sealed) | ||
| assert.Error(t, err, "opening with the wrong key must fail") | ||
| } | ||
|
|
||
| func TestSealOpenEmpty(t *testing.T) { | ||
| // Empty input is a legitimate "not set" state — round-trip without | ||
| // error so the service can store/clear tokens uniformly. | ||
| sealed, err := Seal("secret", nil) | ||
| require.NoError(t, err) | ||
| assert.Empty(t, sealed) | ||
|
|
||
| opened, err := Open("secret", nil) | ||
| require.NoError(t, err) | ||
| assert.Empty(t, opened) | ||
| } | ||
|
|
||
| func TestOpenTooShort(t *testing.T) { | ||
| _, err := Open("secret", []byte{1, 2, 3}) | ||
| assert.Error(t, err) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| package connections | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "strconv" | ||
| "time" | ||
|
|
||
| "golang.org/x/oauth2" | ||
| ) | ||
|
|
||
| // GitHub returns the GitHub provider. GitHub is the marquee device-flow | ||
| // provider: the token exchange needs only a client id, so an admin can | ||
| // enable it with a single env var and no secret. | ||
| // | ||
| // Note for admins: "Enable Device Flow" must be ticked on the OAuth app | ||
| // (Settings → Developer settings → OAuth Apps); without it the flow | ||
| // fails with device_flow_disabled. | ||
| func GitHub() *Provider { | ||
| return &Provider{ | ||
| Name: "github", | ||
| DisplayName: "GitHub", | ||
| AuthorizeURL: "https://github.com/login/oauth/authorize", | ||
| TokenURL: "https://github.com/login/oauth/access_token", | ||
| DeviceAuthURL: "https://github.com/login/device/code", | ||
| DeviceAuthNeedsSecret: false, | ||
| AuthStyle: oauth2.AuthStyleInParams, | ||
| DefaultScopes: []string{"read:user"}, | ||
| Identify: identifyGitHub, | ||
| } | ||
| } | ||
|
|
||
| // identifyGitHub calls /user for the account id and a display name. | ||
| func identifyGitHub(ctx context.Context, accessToken string) (externalID, displayName string, err error) { | ||
| req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/user", nil) | ||
| if err != nil { | ||
| return "", "", err | ||
| } | ||
| req.Header.Set("Authorization", "Bearer "+accessToken) | ||
| req.Header.Set("Accept", "application/vnd.github+json") | ||
| req.Header.Set("X-GitHub-Api-Version", "2022-11-28") | ||
|
|
||
| client := &http.Client{Timeout: 15 * time.Second} | ||
| resp, err := client.Do(req) | ||
| if err != nil { | ||
| return "", "", err | ||
| } | ||
| defer func() { _ = resp.Body.Close() }() | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return "", "", fmt.Errorf("github /user returned %d", resp.StatusCode) | ||
| } | ||
|
|
||
| var body struct { | ||
| ID int64 `json:"id"` | ||
| Login string `json:"login"` | ||
| Name string `json:"name"` | ||
| } | ||
| if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { | ||
| return "", "", err | ||
| } | ||
|
|
||
| externalID = strconv.FormatInt(body.ID, 10) | ||
| switch { | ||
| case body.Login != "": | ||
| displayName = body.Login | ||
| case body.Name != "": | ||
| displayName = body.Name | ||
| default: | ||
| displayName = formatExternalID("github", externalID) | ||
| } | ||
| return externalID, displayName, nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| package connections | ||
|
|
||
| import ( | ||
| "golang.org/x/oauth2" | ||
| ) | ||
|
|
||
| // Google returns the Google OAuth2 provider definition. Endpoints from | ||
| // https://developers.google.com/identity/protocols/oauth2/web-server. | ||
| // Redirect (authorization code) flow only: Google's device flow has a | ||
| // small scope allowlist (TV-class scopes like YouTube and Drive) that | ||
| // excludes the API scopes apps actually declare — analytics.readonly, | ||
| // calendar.readonly, and friends — so DeviceAuthURL stays empty. | ||
| // | ||
| // Google only issues a refresh token when the authorize redirect carries | ||
| // access_type=offline, and only guarantees one on re-auth when | ||
| // prompt=consent forces the consent screen. Those two are pinned in | ||
| // AuthCodeParams rather than inherited from the default options: the | ||
| // default happens to spell the same thing today, but it goes through | ||
| // oauth2.ApprovalForce, whose spelling has changed before (it used to be | ||
| // approval_prompt=force — a parameter Google now rejects when prompt is | ||
| // present). Refresh responses do not rotate the refresh token — the | ||
| // omitted-refresh-token path in Service.refresh keeps the stored one. | ||
| // | ||
| // No Identify: the userinfo endpoint needs an email/profile scope on the | ||
| // token, and we request only what the app's schema declares. ExternalID | ||
| // stays empty; the connections page shows a plain "Connected" state and | ||
| // the app config page falls back to the provider display name. | ||
| // | ||
| // Note for admins: a Cloud project whose OAuth consent screen is in | ||
| // "Testing" status issues refresh tokens that EXPIRE AFTER 7 DAYS. Publish | ||
| // the consent screen to "In production" for durable tokens — staying | ||
| // unverified is fine (users click through a warning screen), it just caps | ||
| // the app at 100 lifetime users, which doesn't matter for self-hosting. | ||
| // See .env.example. | ||
| func Google() *Provider { | ||
| return &Provider{ | ||
| Name: "google", | ||
| DisplayName: "Google", | ||
| AuthorizeURL: "https://accounts.google.com/o/oauth2/v2/auth", | ||
| TokenURL: "https://oauth2.googleapis.com/token", | ||
| AuthStyle: oauth2.AuthStyleInParams, | ||
| AuthCodeParams: []oauth2.AuthCodeOption{ | ||
| oauth2.AccessTypeOffline, | ||
| oauth2.SetAuthURLParam("prompt", "consent"), | ||
| }, | ||
| DefaultScopes: []string{"https://www.googleapis.com/auth/analytics.readonly"}, | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Correct the Google production verification guidance.
These files state that publishing without verification is sufficient for this Google connection. Google distinguishes personal use from public production. Published external unverified apps have a hard 100-user cap and warning UI. Public apps that access user data must complete verification. State the personal-use exception and the production requirements instead of saying verification is unnecessary. (developers.google.com)
.env.example#L78-L84: replace the categorical verification guidance with the applicable personal-use and public-production conditions.docs/oauth-connections.md#L78-L84: correct the administrator setup guidance.docs/oauth-connections.md#L195-L195: remove the assertion that no verification is needed.internal/connections/google.go#L29-L33: correct the provider comment to match the administrator documentation.📍 Affects 3 files
.env.example#L78-L84(this comment)docs/oauth-connections.md#L78-L84docs/oauth-connections.md#L195-L195internal/connections/google.go#L29-L33🤖 Prompt for AI Agents