package apis_test
import (
"net/http"
"strings"
"testing"
"ganigeorgiev.com/pocketbase/dbx"
"ganigeorgiev.com/pocketbase/pocketbase/core"
"ganigeorgiev.com/pocketbase/pocketbase/tests"
"ganigeorgiev.com/pocketbase/pocketbase/tools/auth"
"golang.org/x/oauth2"
)
func linkSuperuserOAuth2(t testing.TB, app *tests.TestApp, superuserEmail, provider, providerId string) {
superuser, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, superuserEmail)
if err != nil {
t.Fatal(err)
}
ea := core.NewExternalAuth(app)
ea.SetCollectionRef(superuser.Collection().Id)
ea.SetRecordRef(superuser.Id)
ea.SetProvider(provider)
ea.SetProviderId(providerId)
if err := app.Save(ea); err != nil {
t.Fatal(err)
}
}
func superusersOAuth2Setup(t testing.TB, app *tests.TestApp, user *auth.AuthUser) {
auth.Providers["test"] = func() auth.Provider {
return &oauth2MockProvider{
AuthUser: user,
Token: &oauth2.Token{AccessToken: "abc"},
}
}
collection, err := app.FindCachedCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
collection.OAuth2.Enabled = true
collection.OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "test",
ClientId: "123",
ClientSecret: "456",
}}
if err := app.Save(collection); err != nil {
t.Fatal(err)
}
}
func superuserAuthToken(t testing.TB, app *tests.TestApp, email string) string {
record, err := app.FindAuthRecordByEmail(core.CollectionNameSuperusers, email)
if err != nil {
t.Fatal(err)
}
token, err := record.NewAuthToken()
if err != nil {
t.Fatal(err)
}
return token
}
func TestRecordAuthWithOAuth2Superusers(t *testing.T) {
testApp, err := tests.NewTestApp()
if err != nil {
t.Fatal(err)
}
testToken := superuserAuthToken(t, testApp, "test@example.com")
testApp.Cleanup()
scenarios := []tests.ApiScenario{
{
Name: "disabled OAuth2 auth",
Method: http.MethodPost,
URL: "/api/collections/_superusers/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code": "123",
"codeVerifier": "456",
"redirectURL": "https://example.com"
}`),
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "missing provider config",
Method: http.MethodPost,
URL: "/api/collections/_superusers/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "missing",
"code": "123"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
superusersOAuth2Setup(t, app, &auth.AuthUser{Id: "test_id"})
},
ExpectedStatus: 400,
ExpectedContent: []string{
`"data":{`,
`"provider":`,
},
ExpectedEvents: map[string]int{"*": 0},
},
{
Name: "unmatched OAuth2 user (no existing superuser to link to)",
Method: http.MethodPost,
URL: "/api/collections/_superusers/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code": "123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
superusersOAuth2Setup(t, app, &auth.AuthUser{Id: "unknown_id", Email: "unknown@example.com"})
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
var total int
if err := app.DB().NewQuery("select count(*) from `" + core.CollectionNameSuperusers + "`").
Row(&total); err != nil {
t.Fatal(err)
}
if total != 4 {
t.Fatalf("Expected 4 superusers, got %d", total)
}
var links int
err := app.DB().NewQuery("select count(*) from _externalAuths where provider = {:p}").
Bind(dbx.Params{"p": "test"}).Row(&links)
if err != nil {
t.Fatal(err)
}
if links != 0 {
t.Fatalf("Expected no external auth links, got %d", links)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
},
},
{
Name: "existing superuser external auth link",
Method: http.MethodPost,
URL: "/api/collections/_superusers/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code": "123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
superusersOAuth2Setup(t, app, &auth.AuthUser{Id: "test_id", Email: "test@example.com"})
linkSuperuserOAuth2(t, app, "test@example.com", "test", "test_id")
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
var links int
err := app.DB().NewQuery("select count(*) from _externalAuths where provider = {:p}").
Bind(dbx.Params{"p": "test"}).Row(&links)
if err != nil {
t.Fatal(err)
}
if links != 1 {
t.Fatalf("Expected 1 external auth link, got %d", links)
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"id":"sywbhecnh46rhm0"`,
`"email":"test@example.com"`,
`"token":"`,
`"isNew":false`,
},
NotExpectedContent: []string{
`"tokenKey"`,
`"password"`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
"OnModelCreate": 1,
"OnModelCreateExecute": 1,
"OnModelValidate": 1,
"OnModelAfterCreateSuccess": 1,
"OnRecordCreate": 1,
"OnRecordCreateExecute": 1,
"OnRecordValidate": 1,
"OnRecordAfterCreateSuccess": 1,
"OnMailerRecordAuthAlertSend": 1,
"OnMailerSend": 1,
},
},
{
Name: "existing superuser matched by OAuth2 email (not allowed to link)",
Method: http.MethodPost,
URL: "/api/collections/_superusers/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code": "123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
superusersOAuth2Setup(t, app, &auth.AuthUser{Id: "new_id", Email: "test2@example.com"})
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
links, err := app.CountRecords("_externalAuths", dbx.HashExp{
"provider": "test",
"providerId": "new_id",
})
if err != nil {
t.Fatal(err)
}
if links != 0 {
t.Fatalf("Expected no external auth links, got %d", links)
}
},
ExpectedStatus: 400,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
},
},
{
Name: "existing superuser can link a new provider when already authenticated",
Method: http.MethodPost,
URL: "/api/collections/_superusers/auth-with-oauth2",
Headers: map[string]string{
"Authorization": testToken,
},
Body: strings.NewReader(`{
"provider": "test",
"code": "123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
superusersOAuth2Setup(t, app, &auth.AuthUser{Id: "new_id", Email: "other@example.com"})
},
AfterTestFunc: func(t testing.TB, app *tests.TestApp, res *http.Response) {
ea, err := app.FindFirstExternalAuthByExpr(dbx.HashExp{
"provider": "test",
"providerId": "new_id",
})
if err != nil {
t.Fatalf("Expected the external auth link to be created, got %v", err)
}
if ea.RecordRef() != "sywbhecnh46rhm0" {
t.Fatalf("Expected the link to point to the test superuser, got %q", ea.RecordRef())
}
},
ExpectedStatus: 200,
ExpectedContent: []string{
`"record":{`,
`"id":"sywbhecnh46rhm0"`,
`"email":"test@example.com"`,
`"token":"`,
`"isNew":false`,
},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
"OnRecordAuthRequest": 1,
"OnRecordEnrich": 1,
"OnModelCreate": 2,
"OnModelCreateExecute": 2,
"OnModelValidate": 2,
"OnModelAfterCreateSuccess": 2,
"OnRecordCreate": 2,
"OnRecordCreateExecute": 2,
"OnRecordValidate": 2,
"OnRecordAfterCreateSuccess": 2,
"OnMailerRecordAuthAlertSend": 1,
"OnMailerSend": 1,
},
},
{
Name: "superuser IPs restriction is enforced",
Method: http.MethodPost,
URL: "/api/collections/_superusers/auth-with-oauth2",
Body: strings.NewReader(`{
"provider": "test",
"code": "123",
"redirectURL": "https://example.com"
}`),
BeforeTestFunc: func(t testing.TB, app *tests.TestApp, e *core.ServeEvent) {
superusersOAuth2Setup(t, app, &auth.AuthUser{Id: "test_id", Email: "test@example.com"})
linkSuperuserOAuth2(t, app, "test@example.com", "test", "test_id")
app.Settings().SuperuserIPs = []string{"1.2.3.4"}
},
ExpectedStatus: 403,
ExpectedContent: []string{`"data":{}`},
ExpectedEvents: map[string]int{
"*": 0,
"OnRecordAuthWithOAuth2Request": 1,
},
},
}
for _, scenario := range scenarios {
scenario.Test(t)
}
}
func TestSuperusersCollectionOAuth2Config(t *testing.T) {
t.Parallel()
app, _ := tests.NewTestApp()
defer app.Cleanup()
collection, err := app.FindCachedCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
collection.OAuth2.Enabled = true
collection.OAuth2.Providers = []core.OAuth2ProviderConfig{{
Name: "gitlab",
ClientId: "123",
ClientSecret: "456",
}}
if err = app.Save(collection); err != nil {
t.Fatal(err)
}
reloaded, err := app.FindCachedCollectionByNameOrId(core.CollectionNameSuperusers)
if err != nil {
t.Fatal(err)
}
if !reloaded.OAuth2.Enabled {
t.Fatal("Expected the superusers OAuth2 auth to be enabled")
}
config, ok := reloaded.OAuth2.GetProviderConfig("gitlab")
if !ok {
t.Fatal("Expected the gitlab provider config to be preserved")
}
if config.ClientId != "123" || config.ClientSecret != "456" {
t.Fatalf("Unexpected provider config %+v", config)
}
if reloaded.OAuth2.MappedFields.Name != "" {
t.Fatalf("Expected the missing OAuth2 mapped fields to be unset, got %+v", reloaded.OAuth2.MappedFields)
}
}