Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions internal/auth/oauth_gitea.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"strconv"
"strings"

"golang.org/x/oauth2"
)
Expand All @@ -23,11 +22,9 @@ func (p *OAuthProvider) getGiteaUserInfo(
token *oauth2.Token,
) (*OAuthUserInfo, error) {
client := p.config.Client(ctx, token)
apiURL := strings.TrimSuffix(p.config.Endpoint.AuthURL, "/login/oauth/authorize") +
"/api/v1/user"

var user giteaUser
if err := fetchJSON(ctx, client, apiURL, &user); err != nil {
if err := fetchJSON(ctx, client, p.apiURL, &user); err != nil {
return nil, fmt.Errorf("failed to get Gitea user info: %w", err)
}

Expand Down
111 changes: 111 additions & 0 deletions internal/auth/oauth_gitea_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package auth

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestNewGiteaProvider(t *testing.T) {
p := NewGiteaProvider(OAuthProviderConfig{
ClientID: "client-id",
ClientSecret: "client-secret",
RedirectURL: "https://example.com/callback",
Scopes: []string{"read:user"},
}, "https://gitea.example.com")

assert.Equal(t, "gitea", p.GetProvider())
assert.Equal(t, "Gitea", p.GetDisplayName())
assert.Equal(t, "https://gitea.example.com/login/oauth/authorize", p.config.Endpoint.AuthURL)
assert.Equal(
t,
"https://gitea.example.com/login/oauth/access_token",
p.config.Endpoint.TokenURL,
)
assert.Equal(t, "https://gitea.example.com/api/v1/user", p.apiURL)
}

func TestNewGiteaProvider_TrailingSlashStripped(t *testing.T) {
p := NewGiteaProvider(OAuthProviderConfig{}, "https://gitea.example.com/")

assert.Equal(t, "https://gitea.example.com/login/oauth/authorize", p.config.Endpoint.AuthURL)
assert.Equal(t, "https://gitea.example.com/api/v1/user", p.apiURL)
}

func TestGetGiteaUserInfo_Success(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/user", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(giteaUser{
ID: 99,
Login: "giteatester",
FullName: "Gitea Tester",
Email: "gitea@example.com",
AvatarURL: "https://gitea.example.com/avatars/99",
})
}))
defer server.Close()

p := NewGiteaProvider(OAuthProviderConfig{
ClientID: "id",
ClientSecret: "secret",
}, server.URL)

info, err := p.GetUserInfo(context.Background(), newTestToken())

require.NoError(t, err)
assert.Equal(t, "99", info.ProviderUserID)
assert.Equal(t, "giteatester", info.Username)
assert.Equal(t, "Gitea Tester", info.FullName)
assert.Equal(t, "gitea@example.com", info.Email)
assert.Equal(t, "https://gitea.example.com/avatars/99", info.AvatarURL)
}

func TestGetGiteaUserInfo_NoEmail(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(giteaUser{ID: 1, Login: "noemail", Email: ""})
}))
defer server.Close()

p := NewGiteaProvider(OAuthProviderConfig{}, server.URL)
info, err := p.GetUserInfo(context.Background(), newTestToken())

require.Error(t, err)
assert.Nil(t, info)
assert.Contains(t, err.Error(), "no email address")
}

func TestGetGiteaUserInfo_NonOKStatus(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"message":"Unauthorized"}`))
}))
defer server.Close()

p := NewGiteaProvider(OAuthProviderConfig{}, server.URL)
info, err := p.GetUserInfo(context.Background(), newTestToken())

require.Error(t, err)
assert.Nil(t, info)
assert.Contains(t, err.Error(), "failed to get Gitea user info")
}

func TestGetGiteaUserInfo_InvalidJSON(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte("not json"))
}))
defer server.Close()

p := NewGiteaProvider(OAuthProviderConfig{}, server.URL)
info, err := p.GetUserInfo(context.Background(), newTestToken())

require.Error(t, err)
assert.Nil(t, info)
}
148 changes: 148 additions & 0 deletions internal/auth/oauth_github_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package auth

import (
"encoding/json"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestNewGitHubProvider(t *testing.T) {
p := NewGitHubProvider(OAuthProviderConfig{
ClientID: "client-id",
ClientSecret: "client-secret",
RedirectURL: "https://example.com/callback",
Scopes: []string{"user:email"},
})

assert.Equal(t, "github", p.GetProvider())
assert.Equal(t, "GitHub", p.GetDisplayName())
assert.Equal(t, "https://github.com/login/oauth/authorize", p.config.Endpoint.AuthURL)
assert.Equal(t, "https://github.com/login/oauth/access_token", p.config.Endpoint.TokenURL)
}

func TestGetGitHubUserInfo_Success(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/user" {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(githubUser{
ID: 12345,
Login: "octocat",
Name: "The Octocat",
Email: "octocat@github.com",
AvatarURL: "https://github.com/avatars/octocat",
})
return
}
http.NotFound(w, r)
})

p := NewGitHubProvider(OAuthProviderConfig{ClientID: "id", ClientSecret: "secret"})
ctx := contextWithMock(handler)

info, err := p.GetUserInfo(ctx, newTestToken())

require.NoError(t, err)
assert.Equal(t, "12345", info.ProviderUserID)
assert.Equal(t, "octocat", info.Username)
assert.Equal(t, "The Octocat", info.FullName)
assert.Equal(t, "octocat@github.com", info.Email)
assert.Equal(t, "https://github.com/avatars/octocat", info.AvatarURL)
}

func TestGetGitHubUserInfo_FetchesPrimaryEmail(t *testing.T) {
// Simulates a GitHub account with no public email: /user returns empty email,
// so the provider falls back to /user/emails to find the primary verified address.
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/user":
_ = json.NewEncoder(w).Encode(githubUser{ID: 1, Login: "nomail", Email: ""})
case "/user/emails":
_ = json.NewEncoder(w).Encode([]githubEmail{
{Email: "secondary@example.com", Primary: false, Verified: true},
{Email: "primary@example.com", Primary: true, Verified: true},
})
default:
http.NotFound(w, r)
}
})

p := NewGitHubProvider(OAuthProviderConfig{ClientID: "id", ClientSecret: "secret"})
info, err := p.GetUserInfo(contextWithMock(handler), newTestToken())

require.NoError(t, err)
assert.Equal(t, "primary@example.com", info.Email)
}

func TestGetGitHubUserInfo_FallsBackToFirstVerifiedEmail(t *testing.T) {
// No primary+verified email; provider should fall back to the first verified email.
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/user":
_ = json.NewEncoder(w).Encode(githubUser{ID: 1, Login: "user", Email: ""})
case "/user/emails":
_ = json.NewEncoder(w).Encode([]githubEmail{
{Email: "unverified@example.com", Primary: true, Verified: false},
{Email: "fallback@example.com", Primary: false, Verified: true},
})
}
})

p := NewGitHubProvider(OAuthProviderConfig{ClientID: "id", ClientSecret: "secret"})
info, err := p.GetUserInfo(contextWithMock(handler), newTestToken())

require.NoError(t, err)
assert.Equal(t, "fallback@example.com", info.Email)
}

func TestGetGitHubUserInfo_NoVerifiedEmail(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/user":
_ = json.NewEncoder(w).Encode(githubUser{ID: 1, Login: "user", Email: ""})
case "/user/emails":
_ = json.NewEncoder(w).Encode([]githubEmail{
{Email: "unverified@example.com", Primary: true, Verified: false},
})
}
})

p := NewGitHubProvider(OAuthProviderConfig{ClientID: "id", ClientSecret: "secret"})
info, err := p.GetUserInfo(contextWithMock(handler), newTestToken())

require.Error(t, err)
assert.Nil(t, info)
assert.Contains(t, err.Error(), "no verified email")
}

func TestGetGitHubUserInfo_NonOKStatus(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"message":"Bad credentials"}`))
})

p := NewGitHubProvider(OAuthProviderConfig{ClientID: "id", ClientSecret: "secret"})
info, err := p.GetUserInfo(contextWithMock(handler), newTestToken())

require.Error(t, err)
assert.Nil(t, info)
assert.Contains(t, err.Error(), "failed to get GitHub user info")
}

func TestGetGitHubUserInfo_InvalidJSON(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte("not json"))
})

p := NewGitHubProvider(OAuthProviderConfig{ClientID: "id", ClientSecret: "secret"})
info, err := p.GetUserInfo(contextWithMock(handler), newTestToken())

require.Error(t, err)
assert.Nil(t, info)
}
42 changes: 42 additions & 0 deletions internal/auth/oauth_gitlab.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package auth

import (
"context"
"errors"
"fmt"
"strconv"

"golang.org/x/oauth2"
)

type gitlabUser struct {
ID int64 `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
AvatarURL string `json:"avatar_url"`
}

func (p *OAuthProvider) getGitLabUserInfo(
ctx context.Context,
token *oauth2.Token,
) (*OAuthUserInfo, error) {
client := p.config.Client(ctx, token)

var user gitlabUser
if err := fetchJSON(ctx, client, p.apiURL, &user); err != nil {
return nil, fmt.Errorf("failed to get GitLab user info: %w", err)
}

if user.Email == "" {
return nil, errors.New("gitlab account has no email address")
}

return &OAuthUserInfo{
ProviderUserID: strconv.FormatInt(user.ID, 10),
Username: user.Username,
Email: user.Email,
FullName: user.Name,
AvatarURL: user.AvatarURL,
}, nil
}
Loading
Loading