Skip to content
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

feat: add input validation for accounts and certificate requests endpoints #177

Merged
merged 2 commits into from
Feb 17, 2025
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
52 changes: 33 additions & 19 deletions internal/server/handlers_accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package server
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"regexp"
Expand All @@ -18,10 +19,33 @@ type CreateAccountParams struct {
Password string `json:"password"`
}

func (params *CreateAccountParams) IsValid() (bool, error) {
if params.Username == "" {
return false, errors.New("username is required")
}
if params.Password == "" {
return false, errors.New("password is required")
}
if !validatePassword(params.Password) {
return false, errors.New("Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol.")
}
return true, nil
}

type ChangeAccountParams struct {
Password string `json:"password"`
}

func (params *ChangeAccountParams) IsValid() (bool, error) {
if params.Password == "" {
return false, errors.New("password is required")
}
if !validatePassword(params.Password) {
return false, errors.New("Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol.")
}
return true, nil
}

type GetAccountResponse struct {
ID int64 `json:"id"`
Username string `json:"username"`
Expand Down Expand Up @@ -122,6 +146,11 @@ func CreateAccount(env *HandlerConfig) http.HandlerFunc {
writeError(w, http.StatusBadRequest, "Invalid JSON format")
return
}
valid, err := createAccountParams.IsValid()
if !valid {
writeError(w, http.StatusBadRequest, fmt.Errorf("Invalid request: %s", err).Error())
return
}
if createAccountParams.Username == "" {
writeError(w, http.StatusBadRequest, "Username is required")
return
Expand All @@ -130,14 +159,6 @@ func CreateAccount(env *HandlerConfig) http.HandlerFunc {
writeError(w, http.StatusBadRequest, "Password is required")
return
}
if !validatePassword(createAccountParams.Password) {
writeError(
w,
http.StatusBadRequest,
"Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol.",
)
return
}
numUsers, err := env.DB.NumUsers()
if err != nil {
writeError(w, http.StatusInternalServerError, "Failed to retrieve accounts: "+err.Error())
Expand Down Expand Up @@ -242,19 +263,12 @@ func ChangeAccountPassword(env *HandlerConfig) http.HandlerFunc {
writeError(w, http.StatusBadRequest, "Invalid JSON format")
return
}
if changeAccountParams.Password == "" {
writeError(w, http.StatusBadRequest, "Password is required")
return
}
if !validatePassword(changeAccountParams.Password) {
writeError(
w,
http.StatusBadRequest,
"Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol.",
)
valid, err := changeAccountParams.IsValid()
if !valid {
writeError(w, http.StatusBadRequest, fmt.Errorf("Invalid request: %s", err).Error())
return
}
err := env.DB.UpdateUserPassword(db.ByUserID(idNum), changeAccountParams.Password)
err = env.DB.UpdateUserPassword(db.ByUserID(idNum), changeAccountParams.Password)
if err != nil {
log.Println(err)
if errors.Is(err, sqlair.ErrNoRows) {
Expand Down
186 changes: 115 additions & 71 deletions internal/server/handlers_accounts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,41 +261,7 @@ func TestAccountsEndToEnd(t *testing.T) {
}
})

t.Run("6. Create account - no username", func(t *testing.T) {
createAccountParams := &CreateAccountParams{
Username: "",
Password: "password",
}
statusCode, response, err := createAccount(ts.URL, client, adminToken, createAccountParams)
if err != nil {
t.Fatalf("couldn't create account: %s", err)
}
if statusCode != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, statusCode)
}
if response.Error != "Username is required" {
t.Fatalf("expected error %q, got %q", "Username is required", response.Error)
}
})

t.Run("7. Create account - no password", func(t *testing.T) {
createAccountParams := &CreateAccountParams{
Username: "nopass",
Password: "",
}
statusCode, response, err := createAccount(ts.URL, client, adminToken, createAccountParams)
if err != nil {
t.Fatalf("couldn't create account: %s", err)
}
if statusCode != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, statusCode)
}
if response.Error != "Password is required" {
t.Fatalf("expected error %q, got %q", "Password is required", response.Error)
}
})

t.Run("8. Change account password - success", func(t *testing.T) {
t.Run("6. Change account password - success", func(t *testing.T) {
changeAccountPasswordParams := &ChangeAccountPasswordParams{
Password: "newPassword1",
}
Expand All @@ -311,7 +277,7 @@ func TestAccountsEndToEnd(t *testing.T) {
}
})

t.Run("9. Change account password - no user", func(t *testing.T) {
t.Run("7. Change account password - no user", func(t *testing.T) {
changeAccountPasswordParams := &ChangeAccountPasswordParams{
Password: "newPassword1",
}
Expand All @@ -327,39 +293,7 @@ func TestAccountsEndToEnd(t *testing.T) {
}
})

t.Run("10. Change account password - no password", func(t *testing.T) {
changeAccountPasswordParams := &ChangeAccountPasswordParams{
Password: "",
}
statusCode, response, err := changeAccountPassword(ts.URL, client, adminToken, 1, changeAccountPasswordParams)
if err != nil {
t.Fatalf("couldn't create account: %s", err)
}
if statusCode != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, statusCode)
}
if response.Error != "Password is required" {
t.Fatalf("expected error %q, got %q", "Password is required", response.Error)
}
})

t.Run("11. Change account password - bad password", func(t *testing.T) {
changeAccountPasswordParams := &ChangeAccountPasswordParams{
Password: "password",
}
statusCode, response, err := changeAccountPassword(ts.URL, client, adminToken, 1, changeAccountPasswordParams)
if err != nil {
t.Fatalf("couldn't create account: %s", err)
}
if statusCode != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, statusCode)
}
if response.Error != "Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol." {
t.Fatalf("expected error %q, got %q", "Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol.", response.Error)
}
})

t.Run("12. Delete account - success", func(t *testing.T) {
t.Run("8. Delete account - success", func(t *testing.T) {
statusCode, response, err := deleteAccount(ts.URL, client, adminToken, 2)
if err != nil {
t.Fatalf("couldn't delete account: %s", err)
Expand All @@ -372,7 +306,7 @@ func TestAccountsEndToEnd(t *testing.T) {
}
})

t.Run("13. Delete account - no user", func(t *testing.T) {
t.Run("9. Delete account - no user", func(t *testing.T) {
statusCode, response, err := deleteAccount(ts.URL, client, adminToken, 100)
if err != nil {
t.Fatalf("couldn't delete account: %s", err)
Expand All @@ -385,7 +319,7 @@ func TestAccountsEndToEnd(t *testing.T) {
}
})

t.Run("14. Get my admin account - admin token", func(t *testing.T) {
t.Run("10. Get my admin account - admin token", func(t *testing.T) {
statusCode, response, err := getMyAccount(ts.URL, client, adminToken)
if err != nil {
t.Fatalf("couldn't get account: %s", err)
Expand All @@ -407,3 +341,113 @@ func TestAccountsEndToEnd(t *testing.T) {
}
})
}

func TestCreateAccountInvalidInputs(t *testing.T) {
tempDir := t.TempDir()
db_path := filepath.Join(tempDir, "db.sqlite3")
ts, _, err := setupServer(db_path)
if err != nil {
t.Fatalf("couldn't create test server: %s", err)
}
defer ts.Close()
client := ts.Client()

var adminToken string
var nonAdminToken string
t.Run("prepare user accounts and tokens", prepareAccounts(ts.URL, client, &adminToken, &nonAdminToken))

tests := []struct {
testName string
username string
password string
error string
}{
{
testName: "No username",
username: "",
password: "password",
error: "Invalid request: username is required",
},
{
testName: "No password",
username: "username",
password: "",
error: "Invalid request: password is required",
},
{
testName: "bad password",
username: "username",
password: "123",
error: "Invalid request: Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol.",
},
}

for _, test := range tests {
t.Run(test.testName, func(t *testing.T) {
createAccountParams := &CreateAccountParams{
Username: test.username,
Password: test.password,
}
statusCode, createCertResponse, err := createAccount(ts.URL, client, adminToken, createAccountParams)
if err != nil {
t.Fatal(err)
}
if statusCode != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, statusCode)
}
if createCertResponse.Error != test.error {
t.Fatalf("expected error %s, got %s", test.error, createCertResponse.Error)
}
})
}
}

func TestChangeAccountPasswordInvalidInputs(t *testing.T) {
tempDir := t.TempDir()
db_path := filepath.Join(tempDir, "db.sqlite3")
ts, _, err := setupServer(db_path)
if err != nil {
t.Fatalf("couldn't create test server: %s", err)
}
defer ts.Close()
client := ts.Client()

var adminToken string
var nonAdminToken string
t.Run("prepare user accounts and tokens", prepareAccounts(ts.URL, client, &adminToken, &nonAdminToken))

tests := []struct {
testName string
password string
error string
}{
{
testName: "No password",
password: "",
error: "Invalid request: password is required",
},
{
testName: "bad password",
password: "123",
error: "Invalid request: Password must have 8 or more characters, must include at least one capital letter, one lowercase letter, and either a number or a symbol.",
},
}

for _, test := range tests {
t.Run(test.testName, func(t *testing.T) {
changeAccountParams := &ChangeAccountPasswordParams{
Password: test.password,
}
statusCode, createCertResponse, err := changeAccountPassword(ts.URL, client, adminToken, 1, changeAccountParams)
if err != nil {
t.Fatal(err)
}
if statusCode != http.StatusBadRequest {
t.Fatalf("expected status %d, got %d", http.StatusBadRequest, statusCode)
}
if createCertResponse.Error != test.error {
t.Fatalf("expected error %s, got %s", test.error, createCertResponse.Error)
}
})
}
}
Loading
Loading