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
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,13 @@ ALPHONE_TEST_S3_SECRET_ACCESS_KEY=0123456789abcdef0123456789abcdef0123456789abcd
# How long invite and reset links live, 168h and 1h when unset.
# ALPHONE_INVITE_TTL=168h
# ALPHONE_RESET_TTL=1h
# Invitations and resends one inviting account and one workspace may send per window, counted apart
# and only while a mail relay is set, 10, 20, 5 and 10 per 24h when unset.
# ALPHONE_INVITES_PER_INVITER=10
# ALPHONE_INVITES_PER_TENANT=20
# ALPHONE_INVITE_RESENDS_PER_INVITER=5
# ALPHONE_INVITE_RESENDS_PER_TENANT=10
# ALPHONE_INVITE_LIMIT_WINDOW=24h
# Reset requests allowed per client IP within one reset link lifetime, 3 when unset.
# ALPHONE_RESET_ATTEMPTS=3
# Reset links that may stand for one account at once, 3 when unset.
Expand Down
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ E2E_WEBHOOK_ALLOWED_HOSTS ?= 127.0.0.1/32
E2E_ENCRYPTION_KEY ?= e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0e2e0
E2E_PRIVACY_URL ?= https://example.com/privacy
E2E_TERMS_URL ?= https://example.com/terms
E2E_INVITES_PER_INVITER ?= 1000
E2E_INVITE_RESENDS_PER_INVITER ?= 1000
E2E_INVITES_PER_TENANT ?= 100000
E2E_INVITE_RESENDS_PER_TENANT ?= 100000

e2e-build:
pnpm --filter @alphone/frontend build
Expand All @@ -186,6 +190,10 @@ e2e-serve: db-up e2e-build
ALPHONE_ENCRYPTION_KEY="$(E2E_ENCRYPTION_KEY)" \
ALPHONE_PRIVACY_URL="$(E2E_PRIVACY_URL)" \
ALPHONE_TERMS_URL="$(E2E_TERMS_URL)" \
ALPHONE_INVITES_PER_INVITER="$(E2E_INVITES_PER_INVITER)" \
ALPHONE_INVITE_RESENDS_PER_INVITER="$(E2E_INVITE_RESENDS_PER_INVITER)" \
ALPHONE_INVITES_PER_TENANT="$(E2E_INVITES_PER_TENANT)" \
ALPHONE_INVITE_RESENDS_PER_TENANT="$(E2E_INVITE_RESENDS_PER_TENANT)" \
./alphone serve

e2e-db-reset: db-up
Expand Down
163 changes: 163 additions & 0 deletions cmd/alphone/invitationlimitwiring_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// SPDX-License-Identifier: Elastic-2.0

package main

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"testing"

"github.com/gopherium/framework/gonsole/testkit"
)

// invitationBody is the graph body that invites one address.
const invitationBody = `{"query":"mutation { invite(email: \"%s\", name: \"Maria Perez\") { delivered } }"}`

// resendBody is the graph body that resends the invitation of one address.
const resendBody = `{"query":"mutation { resendInvite(email: \"%s\") { delivered } }"}`

// startRunWithARelay serves run over a fresh database, a mock relay and env, answering its address and its database.
func startRunWithARelay(t *testing.T, env map[string]string) (string, string) {
t.Helper()
relay := mailRelay(t)
databaseURL := testDatabaseURL(t)
addr := testkit.FreeAddr(t)
env["ALPHONE_DATABASE_URL"] = databaseURL
env["ALPHONE_ADDR"] = addr
env["ALPHONE_SMTP_HOST"] = "127.0.0.1"
env["ALPHONE_SMTP_PORT"] = strconv.Itoa(relay.PortNumber())
env["ALPHONE_SMTP_FROM"] = "crm@example.com"
env["ALPHONE_SMTP_TLS"] = "none"
env["ALPHONE_PUBLIC_URL"] = "https://crm.example.com"
ctx, cancel := context.WithCancel(t.Context())
runErr := make(chan error, 1)
go func() {
runErr <- run(ctx, testkit.Getenv(env), io.Discard, registerPlugins)
}()
t.Cleanup(func() { stopRun(t, cancel, runErr) })
baseURL := "http://" + addr
waitForServer(t, baseURL)
return baseURL, databaseURL
}

// adminSessionAs stores an admin under the address and answers the session it logs in with.
func adminSessionAs(t *testing.T, baseURL, databaseURL, address string) *http.Cookie {
t.Helper()
seedAdminAs(t, databaseURL, address)
return loginSessionAs(t, baseURL, address)
}

// graphAnswerAs posts a graph body with the session cookie and returns the answer, errors included.
func graphAnswerAs(t *testing.T, session *http.Cookie, baseURL, body string) string {
t.Helper()
response := doAuthed(t, t.Context(), session, http.MethodPost, baseURL+"/api/graphql", body)
answer, err := io.ReadAll(response.Body)
_ = response.Body.Close()
if err != nil {
t.Fatalf("reading the graph answer: %v", err)
}
return string(answer)
}

// wantNoGraphErrors fails the test when the answer carries any error.
func wantNoGraphErrors(t *testing.T, answer string) {
t.Helper()
if strings.Contains(answer, `"errors"`) {
t.Fatalf("answer = %s, want the call allowed under the limit", answer)
}
}

// wantInvitationLimitAnswer fails the test unless the answer is rejected past a limit that counts over one hour.
func wantInvitationLimitAnswer(t *testing.T, answer string) {
t.Helper()
if !strings.Contains(answer, `"reason":"invitation_limit_reached"`) || !strings.Contains(answer, `"retryAfter":7200`) {
t.Fatalf("answer = %s, want invitation_limit_reached waiting twice the one hour window", answer)
}
}

// usersWriteTokenSecret mints an API token holding the users write scope through the session and returns its secret.
func usersWriteTokenSecret(t *testing.T, session *http.Cookie, baseURL string) string {
t.Helper()
answer := graphAnswerAs(t, session, baseURL,
`{"query":"mutation { apiTokenCreate(name: \"automation\", scopes: [\"users:write\"]) { secret } }"}`)
var minted struct {
Data struct {
APITokenCreate struct {
Secret string `json:"secret"`
} `json:"apiTokenCreate"`
} `json:"data"`
}
if err := json.Unmarshal([]byte(answer), &minted); err != nil || minted.Data.APITokenCreate.Secret == "" {
t.Fatalf("minting the token answered %s (%v), want a secret", answer, err)
}
return minted.Data.APITokenCreate.Secret
}

// graphAnswerByToken posts a graph query with the token secret and returns the answer, errors included.
func graphAnswerByToken(t *testing.T, secret, baseURL, query string) string {
t.Helper()
response := postGraphQuery(t, strings.TrimPrefix(baseURL, "http://"), query, bearerOf(secret))
answer, err := io.ReadAll(response.Body)
_ = response.Body.Close()
if err != nil {
t.Fatalf("reading the graph answer: %v", err)
}
return string(answer)
}

func TestAnInvitationByAnAPITokenCountsForTheTokensOwner(t *testing.T) {
t.Parallel()

baseURL, databaseURL := startRunWithARelay(t, map[string]string{
"ALPHONE_INVITES_PER_INVITER": "1",
"ALPHONE_INVITE_LIMIT_WINDOW": "1h",
})
session := adminSessionAs(t, baseURL, databaseURL, "first.admin@example.com")
secret := usersWriteTokenSecret(t, session, baseURL)
wantNoGraphErrors(t, graphAnswerAs(t, session, baseURL, fmt.Sprintf(invitationBody, "first@example.com")))

wantInvitationLimitAnswer(t, graphAnswerByToken(t, secret, baseURL,
`mutation { invite(email: "second@example.com", name: "Maria Perez") { delivered } }`))
}

func TestEachInvitationLimitSettingReachesItsLimiter(t *testing.T) {
t.Parallel()

tests := map[string]struct {
setting string
body string
isPerTenant bool
}{
"invitations per inviter": {setting: "ALPHONE_INVITES_PER_INVITER", body: invitationBody},
"invitations per tenant": {setting: "ALPHONE_INVITES_PER_TENANT", body: invitationBody, isPerTenant: true},
"resends per inviter": {setting: "ALPHONE_INVITE_RESENDS_PER_INVITER", body: resendBody},
"resends per tenant": {setting: "ALPHONE_INVITE_RESENDS_PER_TENANT", body: resendBody, isPerTenant: true},
}
for testName, tc := range tests {
t.Run(testName, func(t *testing.T) {
t.Parallel()

baseURL, databaseURL := startRunWithARelay(t, map[string]string{
tc.setting: "1",
"ALPHONE_INVITE_LIMIT_WINDOW": "1h",
})
firstSession := adminSessionAs(t, baseURL, databaseURL, "first.admin@example.com")
secondSession := adminSessionAs(t, baseURL, databaseURL, "second.admin@example.com")
wantNoGraphErrors(t, graphAnswerAs(t, firstSession, baseURL, fmt.Sprintf(tc.body, "first@example.com")))

if tc.isPerTenant {
wantInvitationLimitAnswer(t,
graphAnswerAs(t, secondSession, baseURL, fmt.Sprintf(tc.body, "second@example.com")))
return
}
wantInvitationLimitAnswer(t,
graphAnswerAs(t, firstSession, baseURL, fmt.Sprintf(tc.body, "second@example.com")))
wantNoGraphErrors(t, graphAnswerAs(t, secondSession, baseURL, fmt.Sprintf(tc.body, "third@example.com")))
})
}
}
114 changes: 104 additions & 10 deletions cmd/alphone/mailconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,25 +86,25 @@ func TestTheMailDefaultsApply(t *testing.T) {
func TestTheTokenLifetimesDefaultWithoutAMailer(t *testing.T) {
t.Parallel()

held, err := loadRunConfig(testkit.Getenv(map[string]string{
settings, err := loadRunConfig(testkit.Getenv(map[string]string{
"ALPHONE_DATABASE_URL": "postgres://localhost/x",
}))

if err != nil {
t.Fatalf("loadRunConfig() error = %v, want nil", err)
}
if held.inviteTTL != authkit.DefaultInviteTTL {
t.Errorf("inviteTTL = %v, want the authkit default %v", held.inviteTTL, authkit.DefaultInviteTTL)
if settings.invitation.ttl != authkit.DefaultInviteTTL {
t.Errorf("invitation.ttl = %v, want the authkit default %v", settings.invitation.ttl, authkit.DefaultInviteTTL)
}
if held.reset.ttl != authkit.DefaultResetTTL {
t.Errorf("resetTTL = %v, want the authkit default %v", held.reset.ttl, authkit.DefaultResetTTL)
if settings.reset.ttl != authkit.DefaultResetTTL {
t.Errorf("resetTTL = %v, want the authkit default %v", settings.reset.ttl, authkit.DefaultResetTTL)
}
}

func TestTheTokenLifetimesAreReadWithoutAMailer(t *testing.T) {
t.Parallel()

held, err := loadRunConfig(testkit.Getenv(map[string]string{
settings, err := loadRunConfig(testkit.Getenv(map[string]string{
"ALPHONE_DATABASE_URL": "postgres://localhost/x",
"ALPHONE_INVITE_TTL": "24h",
"ALPHONE_RESET_TTL": "30m",
Expand All @@ -113,11 +113,11 @@ func TestTheTokenLifetimesAreReadWithoutAMailer(t *testing.T) {
if err != nil {
t.Fatalf("loadRunConfig() error = %v, want nil", err)
}
if held.inviteTTL != 24*time.Hour {
t.Errorf("inviteTTL = %v, want 24h", held.inviteTTL)
if settings.invitation.ttl != 24*time.Hour {
t.Errorf("invitation.ttl = %v, want 24h", settings.invitation.ttl)
}
if held.reset.ttl != 30*time.Minute {
t.Errorf("resetTTL = %v, want 30m", held.reset.ttl)
if settings.reset.ttl != 30*time.Minute {
t.Errorf("resetTTL = %v, want 30m", settings.reset.ttl)
}
}

Expand Down Expand Up @@ -500,3 +500,97 @@ func TestTheResetCooldownRidesItsOwnWindow(t *testing.T) {
t.Errorf("resetCooldownBudget() = %+v, want one mail per 30s", held)
}
}

func TestTheInvitationLimitsDefault(t *testing.T) {
t.Parallel()

settings, err := loadRunConfig(testkit.Getenv(map[string]string{
"ALPHONE_DATABASE_URL": "postgres://localhost/x",
}))

if err != nil {
t.Fatalf("loadRunConfig() error = %v, want nil", err)
}
want := invitationSettings{
ttl: authkit.DefaultInviteTTL,
invitesPerInviter: 10,
invitesPerTenant: 20,
resendsPerInviter: 5,
resendsPerTenant: 10,
window: 24 * time.Hour,
}
if settings.invitation != want {
t.Errorf("invitation = %+v, want the defaults %+v", settings.invitation, want)
}
}

func TestTheInvitationLimitsAreReadFromTheEnvironment(t *testing.T) {
t.Parallel()

settings, err := loadRunConfig(testkit.Getenv(map[string]string{
"ALPHONE_DATABASE_URL": "postgres://localhost/x",
"ALPHONE_INVITE_TTL": "48h",
"ALPHONE_INVITES_PER_INVITER": "3",
"ALPHONE_INVITES_PER_TENANT": "7",
"ALPHONE_INVITE_RESENDS_PER_INVITER": "2",
"ALPHONE_INVITE_RESENDS_PER_TENANT": "4",
"ALPHONE_INVITE_LIMIT_WINDOW": "6h",
}))

if err != nil {
t.Fatalf("loadRunConfig() error = %v, want nil", err)
}
want := invitationSettings{
ttl: 48 * time.Hour,
invitesPerInviter: 3,
invitesPerTenant: 7,
resendsPerInviter: 2,
resendsPerTenant: 4,
window: 6 * time.Hour,
}
if settings.invitation != want {
t.Errorf("invitation = %+v, want %+v", settings.invitation, want)
}
}

func TestAMalformedInvitationLimitIsRejectedWithItsName(t *testing.T) {
t.Parallel()

tests := map[string]struct {
key string
raw string
}{
"invitations per inviter in words": {"ALPHONE_INVITES_PER_INVITER", "a few"},
"no invitations per inviter": {"ALPHONE_INVITES_PER_INVITER", "0"},
"negative invitations per tenant": {"ALPHONE_INVITES_PER_TENANT", "-1"},
"resends per inviter in words": {"ALPHONE_INVITE_RESENDS_PER_INVITER", "many"},
"no resends per tenant": {"ALPHONE_INVITE_RESENDS_PER_TENANT", "0"},
"a window in words": {"ALPHONE_INVITE_LIMIT_WINDOW", "a day"},
"no window": {"ALPHONE_INVITE_LIMIT_WINDOW", "0s"},
"a negative window": {"ALPHONE_INVITE_LIMIT_WINDOW", "-1h"},
}
for testName, tc := range tests {
t.Run(testName, func(t *testing.T) {
t.Parallel()

_, err := loadRunConfig(testkit.Getenv(map[string]string{
"ALPHONE_DATABASE_URL": "postgres://localhost/x",
tc.key: tc.raw,
}))

if err == nil || !strings.HasPrefix(err.Error(), tc.key+": ") {
t.Errorf("loadRunConfig() with %s=%q error = %v, want it rejected naming %s", tc.key, tc.raw, err, tc.key)
}
})
}
}

func TestEachInvitationLimitCountsOverTheWindow(t *testing.T) {
t.Parallel()

invitation := invitationSettings{window: 6 * time.Hour}

if got := invitation.budget(7); got.Limit != 7 || got.Window != 6*time.Hour {
t.Errorf("budget(7) = %+v, want limit 7 over 6h", got)
}
}
24 changes: 18 additions & 6 deletions cmd/alphone/mailwiring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"io"
"mime/quotedprintable"
"net/http"
Expand Down Expand Up @@ -52,13 +53,19 @@ func stopRun(t *testing.T, cancel context.CancelFunc, runErr <-chan error) {

// seedAdmin stores an enabled admin account able to invite.
func seedAdmin(t *testing.T, databaseURL string) {
t.Helper()
seedAdminAs(t, databaseURL, "admin@example.com")
}

// seedAdminAs stores an enabled admin account able to invite under the address.
func seedAdminAs(t *testing.T, databaseURL, address string) {
t.Helper()
pool, err := pgxpool.New(t.Context(), databaseURL)
if err != nil {
t.Fatalf("connecting pool: %v", err)
}
t.Cleanup(pool.Close)
admin, err := gouncer.NewUser("admin@example.com", "Admin", "correct horse battery")
admin, err := gouncer.NewUser(address, "Admin", "correct horse battery")
if err != nil {
t.Fatalf("gouncer.NewUser() error = %v, want nil", err)
}
Expand All @@ -71,14 +78,19 @@ func seedAdmin(t *testing.T, databaseURL string) {
// loginSession logs the seeded admin in and answers the session cookie.
func loginSession(t *testing.T, baseURL string) *http.Cookie {
t.Helper()
login, err := http.Post(baseURL+"/api/graphql", "application/json", strings.NewReader(
`{"query":"mutation { login(email: \"admin@example.com\",`+
` password: \"correct horse battery\") { me { id } } }"}`))
return loginSessionAs(t, baseURL, "admin@example.com")
}

// loginSessionAs logs the account under the address in and answers the session cookie.
func loginSessionAs(t *testing.T, baseURL, address string) *http.Cookie {
t.Helper()
response, err := http.Post(baseURL+"/api/graphql", "application/json", strings.NewReader(fmt.Sprintf(
`{"query":"mutation { login(email: \"%s\", password: \"correct horse battery\") { me { id } } }"}`, address)))
if err != nil {
t.Fatalf("graph login: %v", err)
}
defer func() { _ = login.Body.Close() }()
for _, cookie := range login.Cookies() {
defer func() { _ = response.Body.Close() }()
for _, cookie := range response.Cookies() {
if cookie.Name == "__Host-alphone_session" {
return cookie
}
Expand Down
Loading
Loading