diff --git a/.gitignore b/.gitignore index 347855d..a96d222 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ -.env +.env.* +*.env +!.env.example +!example.env vegeta.conf \ No newline at end of file diff --git a/api/client/client.go b/api/client/client.go index 1c53af3..6c6d56b 100644 --- a/api/client/client.go +++ b/api/client/client.go @@ -7,8 +7,8 @@ import ( "time" "github.com/simpleauthlink/authapi/api" - "github.com/simpleauthlink/authapi/api/io" "github.com/simpleauthlink/authapi/token" + "go.k7z7z.cc/x/net/http/io" ) const ( @@ -33,6 +33,7 @@ type Config struct { AppID *token.AppID AppSecret string Timeout time.Duration + Unsafe bool } // init method initializes the Config struct with default values if they are @@ -94,22 +95,24 @@ func New(cfg *Config) (*Client, error) { cfg.init() // create a new HTTP client httpClient := &http.Client{Timeout: cfg.Timeout} - // check if the api is reachable - r, err := req[any](cfg, http.MethodGet, api.HealthCheckPath, nil) - if err != nil { - return nil, err - } - // make a request to the health check endpoint - resp, err := httpClient.Do(r) - if err != nil { - return nil, ErrAPIUnavailable - } - defer func() { - _ = resp.Body.Close() - }() - // check if the response is OK - if resp.StatusCode != http.StatusOK { - return nil, ErrAPIUnavailable + if !cfg.Unsafe { + // check if the api is reachable + r, err := req[any](cfg, http.MethodGet, api.HealthCheckPath, nil) + if err != nil { + return nil, err + } + // make a request to the health check endpoint + resp, err := httpClient.Do(r) + if err != nil { + return nil, ErrAPIUnavailable + } + defer func() { + _ = resp.Body.Close() + }() + // check if the response is OK + if resp.StatusCode != http.StatusOK { + return nil, ErrAPIUnavailable + } } // if everything is fine, return a new client instance return &Client{ @@ -122,7 +125,7 @@ func New(cfg *Config) (*Client, error) { // and the provided application ID and secret. Both inputs are required. The // application ID is expected as a string to prevent the user from converting // it. -func Default(strAppID, appSecret string) (*Client, error) { +func Default(strAppID, appSecret string, unsafe bool) (*Client, error) { if appSecret == "" { return nil, ErrInvalidAppSecret } @@ -130,14 +133,15 @@ func Default(strAppID, appSecret string) (*Client, error) { return nil, ErrInvalidAppID } appID := new(token.AppID).SetString(strAppID) - if !new(token.App).SetID(appID).Valid(nil) { - return nil, ErrInvalidAppID + if err := new(token.App).SetID(appID).Valid(nil); err != nil { + return nil, ErrInvalidAppID.With(err) } return New(&Config{ APIEndpoint: DefaultAPIEndpoint, AppID: appID, AppSecret: appSecret, Timeout: DefaultClientTimeout, + Unsafe: unsafe, }) } @@ -206,12 +210,12 @@ func (c *Client) RequestToken(email string) error { if err := c.config.Validate(true); err != nil { return err } + data := &api.TokenRequest{Email: email} // check if the email is valid - if _, err := mail.ParseAddress(email); err != nil { - return ErrInvalidEmailAddress + if !data.IsEmail() { + return ErrInvalidRequestTokenInputs } // create the request with the email data - data := &api.TokenRequest{Email: email} req, err := req(c.config, http.MethodPost, api.TokensPath, data) if err != nil { return err @@ -360,7 +364,7 @@ func req[T any](config *Config, method, path string, data *T) (*http.Request, er // set the body and content type if data is provided if data != nil { // write json data if provided - if err := io.RequestWith(&data).WriteJSON(req); err != nil { + if err := io.RequestWith(data).WriteJSON(req); err != nil { return nil, err } } diff --git a/api/client/client_test.go b/api/client/client_test.go index 5d90b91..0ce7185 100644 --- a/api/client/client_test.go +++ b/api/client/client_test.go @@ -6,28 +6,30 @@ import ( "fmt" "log" "math" - "math/big" "net/http" "net/http/httptest" "net/url" + "os" "strings" "testing" "time" "github.com/simpleauthlink/authapi/api" - "github.com/simpleauthlink/authapi/api/io" - "github.com/simpleauthlink/authapi/internal/fakesmtpserver" + "github.com/simpleauthlink/authapi/notification" "github.com/simpleauthlink/authapi/notification/email" - "github.com/simpleauthlink/authapi/notification/templates/login" + "github.com/simpleauthlink/authapi/notification/email/templates/login" "github.com/simpleauthlink/authapi/token" + xnet "go.k7z7z.cc/x/net" + "go.k7z7z.cc/x/net/http/io" + "go.k7z7z.cc/x/net/smtp/testsmtp" ) var ( // server + testPort int + testEmailPort int + testEndpoint string testServer = "127.0.0.1" - testPort = randomPort() - testEmailPort = randomPort() - testEndpoint = fmt.Sprintf("http://%s:%d", testServer, testPort) testServerSecret = "serversecret" testServerEmail = "server@email.com" // client @@ -40,11 +42,21 @@ var ( ) func TestMain(m *testing.M) { + var err error + testPort, err = xnet.SafeTestPort() + if err != nil { + panic(err) + } + testEmailPort, err = xnet.SafeTestPort() + if err != nil { + panic(err) + } + testEndpoint = fmt.Sprintf("http://%s:%d", testServer, testPort) + ctx, cancel := context.WithCancel(context.Background()) defer cancel() // create the email queue - emailQueue, err := email.NewEmailQueue(ctx, &email.EmailConfig{ - FromName: "test", + emailQueue, err := notification.NewQueue(ctx, 10, &email.EmailConfig{ FromAddress: testServerEmail, SMTPServer: testServer, SMTPPort: testEmailPort, @@ -53,9 +65,9 @@ func TestMain(m *testing.M) { panic("failed to create email queue: " + err.Error()) } // start the email queue and defer to stop it - emailQueue.Start() + emailQueue.Start(1) defer emailQueue.Stop() - smtpServer := fakesmtpserver.NewServer(testServer, testEmailPort, testEmailCh) + smtpServer := testsmtp.NewServer(testServer, testEmailPort, testEmailCh) if err := smtpServer.Start(ctx); err != nil { panic("failed to start fake SMTP server: " + err.Error()) } @@ -65,7 +77,6 @@ func TestMain(m *testing.M) { Server: testServer, ServerPort: testPort, Secret: testServerSecret, - DemoMode: false, }, emailQueue) if err != nil { log.Fatalln("ERR: error creating service:", err) @@ -76,8 +87,12 @@ func TestMain(m *testing.M) { panic("failed to start service: " + err.Error()) } }() - defer service.Stop() - m.Run() + defer func() { + if err := service.Stop(); err != nil { + log.Printf("error closing service: %v", err) + } + }() + os.Exit(m.Run()) } func TestSuccessFlow(t *testing.T) { @@ -101,7 +116,7 @@ func TestSuccessFlow(t *testing.T) { t.Fatalf("failed to request token: %v", err) } // wait to receive the email - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -181,6 +196,10 @@ func TestConfig(t *testing.T) { } func TestNew(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer srv.Close() t.Run("nil config", func(t *testing.T) { _, err := New(nil) if err != nil { @@ -208,43 +227,43 @@ func TestNew(t *testing.T) { }) t.Run("invalid health check call", func(t *testing.T) { _, err := New(&Config{ - APIEndpoint: "http://nonexistent.host.issue", - }) - if err != ErrAPIUnavailable { - t.Fatalf("expected ErrAPIUnavailable, got %v", err) - } - }) - t.Run("invalid health check response", func(t *testing.T) { - _, err := New(&Config{ - APIEndpoint: "http://google.com/invalid-endpoint", + APIEndpoint: srv.URL, }) if err != ErrAPIUnavailable { t.Fatalf("expected ErrAPIUnavailable, got %v", err) } }) + // t.Run("invalid health check response", func(t *testing.T) { + // _, err := New(&Config{ + // APIEndpoint: "http://localhost:1/invalid-endpoint", + // }) + // if err != ErrAPIUnavailable { + // t.Fatalf("expected ErrAPIUnavailable, got %v", err) + // } + // }) } func TestDefault(t *testing.T) { t.Run("invalid app secret", func(t *testing.T) { - _, err := Default(testStrAppID, "") + _, err := Default(testStrAppID, "", true) if err != ErrInvalidAppSecret { t.Fatalf("expected ErrInvalidAppSecret, got %v", err) } }) t.Run("empty app ID", func(t *testing.T) { - _, err := Default("", testClientSecret) + _, err := Default("", testClientSecret, true) if err != ErrInvalidAppID { t.Fatalf("expected ErrInvalidAppID, got %v", err) } }) t.Run("invalid app ID", func(t *testing.T) { - _, err := Default("invalid-app-id", testClientSecret) + _, err := Default("invalid-app-id", testClientSecret, true) if err != ErrInvalidAppID { t.Fatalf("expected ErrInvalidAppID, got %v", err) } }) t.Run("valid app ID and secret", func(t *testing.T) { - _, err := Default(testStrAppID, testClientSecret) + _, err := Default(testStrAppID, testClientSecret, true) if err != nil { t.Fatalf("expected no error, got %v", err) } @@ -346,7 +365,7 @@ func TestRequestToken(t *testing.T) { } }) - t.Run("invalid email", func(t *testing.T) { + t.Run("invalid request inputs", func(t *testing.T) { cli, err := New(&Config{APIEndpoint: testEndpoint}) if err != nil { t.Fatalf("failed to create client: %v", err) @@ -356,15 +375,19 @@ func TestRequestToken(t *testing.T) { t.Fatalf("failed to create app ID: %v", err) } cli.SetupAppID(appID, testClientSecret) - if err := cli.RequestToken(""); err != ErrInvalidEmailAddress { - t.Fatalf("expected ErrInvalidEmailAddress, got %v", err) + if err := cli.RequestToken(""); err != ErrInvalidRequestTokenInputs { + t.Fatalf("expected ErrInvalidRequestTokenInputs, got %v", err) } - if err := cli.RequestToken("invalid-email"); err != ErrInvalidEmailAddress { - t.Fatalf("expected ErrInvalidEmailAddress, got %v", err) + if err := cli.RequestToken("invalid-email"); err != ErrInvalidRequestTokenInputs { + t.Fatalf("expected ErrInvalidRequestTokenInputs, got %v", err) } }) t.Run("request error", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer srv.Close() cli, err := New(&Config{APIEndpoint: testEndpoint}) if err != nil { t.Fatalf("failed to create client: %v", err) @@ -375,17 +398,8 @@ func TestRequestToken(t *testing.T) { } cli.SetupAppID(appID, testClientSecret) // invalid API endpoint - cli.config.APIEndpoint = "http://nonexistent.host.issue" - testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != ErrAPIUnavailable { - t.Fatalf("expected ErrAPIUnavailable, got %v", err) - } - // non-200 response - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "Internal Server Error", http.StatusInternalServerError) - })) - defer srv.Close() cli.config.APIEndpoint = srv.URL + testEmail := randomEmail() if err := cli.RequestToken(testEmail); err != ErrRequestToken { t.Fatalf("expected ErrRequestToken, got %v", err) } @@ -406,6 +420,24 @@ func TestRequestToken(t *testing.T) { t.Fatalf("expected no error, got %v", err) } }) + + t.Run("Do connection error", func(t *testing.T) { + cli, err := New(&Config{APIEndpoint: testEndpoint}) + if err != nil { + t.Fatalf("failed to create client: %v", err) + } + appID, err := cli.NewAppID(testAppName, testRedirectURI, testClientSecret, testTimeout) + if err != nil { + t.Fatalf("failed to create app ID: %v", err) + } + cli.SetupAppID(appID, testClientSecret) + // Unreachable endpoint → httpClient.Do returns error → ErrAPIUnavailable + cli.config.APIEndpoint = "http://nonexistent.host.issue" + testEmail := randomEmail() + if err := cli.RequestToken(testEmail); err != ErrAPIUnavailable { + t.Fatalf("expected ErrAPIUnavailable, got %v", err) + } + }) } func TestVerifyToken(t *testing.T) { @@ -450,7 +482,7 @@ func TestVerifyToken(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -472,7 +504,7 @@ func TestVerifyToken(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -496,7 +528,7 @@ func TestVerifyToken(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -523,7 +555,7 @@ func TestVerifyToken(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -540,16 +572,14 @@ func TestVerifyToken(t *testing.T) { }) } -func readTokenFromEmail(email string) (*token.Token, error) { +func readTokenFromEmail(t testing.TB, email string) (*token.Token, error) { // wait for the email to be sent - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() for { select { case <-ctx.Done(): return nil, ctx.Err() - case <-time.After(testTimeout): - return nil, fmt.Errorf("timeout waiting for email") case msg := <-testEmailCh: token := login.FindToken(email, msg) if token != nil { @@ -586,7 +616,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -637,7 +667,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -668,7 +698,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -722,7 +752,7 @@ func TestAuthorizedRequestHeaders(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -760,7 +790,7 @@ func TestAuthorizedRequestHeaders(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -789,7 +819,7 @@ func TestAuthorizedRequestHeaders(t *testing.T) { if err := cli.RequestToken(testEmail); err != nil { t.Fatalf("failed to request token: %v", err) } - testToken, err := readTokenFromEmail(testEmail) + testToken, err := readTokenFromEmail(t, testEmail) if err != nil { t.Fatalf("failed to read token from email: %v", err) } @@ -911,14 +941,9 @@ func Test_req(t *testing.T) { } func randomEmail() string { - randStr := strings.ToLower(rand.Text()[0:8]) - return fmt.Sprintf("%s@example.com", randStr) -} - -func randomPort() int { - port, err := rand.Int(rand.Reader, big.NewInt(65535-1024)) - if err != nil { - panic(err) + randStr := strings.ToLower(rand.Text()) + if len(randStr) < 8 { + randStr = "testuser" + randStr } - return int(port.Int64()) + 1024 + return fmt.Sprintf("%s@example.com", randStr[:8]) } diff --git a/api/client/errors.go b/api/client/errors.go index 579a071..55e2ee2 100644 --- a/api/client/errors.go +++ b/api/client/errors.go @@ -1,21 +1,22 @@ package client -import "fmt" +import "go.k7z7z.cc/x/errors" var ( - ErrInvalidAPIEndpoint = fmt.Errorf("invalid API endpoint") - ErrInvalidTimeout = fmt.Errorf("invalid timeout value") - ErrInvalidAppID = fmt.Errorf("invalid application ID") - ErrInvalidAppName = fmt.Errorf("invalid application ID name") - ErrInvalidAppRedirectURI = fmt.Errorf("invalid application redirect URI") - ErrInvalidAppSessionDuration = fmt.Errorf("invalid application session duration") - ErrInvalidAppSecret = fmt.Errorf("invalid application secret") - ErrInvalidEmailAddress = fmt.Errorf("invalid email address") - ErrAPIUnavailable = fmt.Errorf("API is unavailable") - ErrRequestAppID = fmt.Errorf("failed to request application ID") - ErrRequestToken = fmt.Errorf("failed to request token") - ErrInvalidToken = fmt.Errorf("invalid token provided") - ErrCreateRequest = fmt.Errorf("failed to create request") - ErrMissingAuthHeaders = fmt.Errorf("missing authentication headers") - ErrMissingAuthURLParams = fmt.Errorf("missing authentication URL parameters") + ErrInvalidAPIEndpoint = errors.New("invalid API endpoint") + ErrInvalidTimeout = errors.New("invalid timeout value") + ErrInvalidAppID = errors.New("invalid application ID") + ErrInvalidAppName = errors.New("invalid application ID name") + ErrInvalidAppRedirectURI = errors.New("invalid application redirect URI") + ErrInvalidAppSessionDuration = errors.New("invalid application session duration") + ErrInvalidAppSecret = errors.New("invalid application secret") + ErrInvalidEmailAddress = errors.New("invalid email address") + ErrInvalidRequestTokenInputs = errors.New("invalid request token inputs") + ErrAPIUnavailable = errors.New("API is unavailable") + ErrRequestAppID = errors.New("failed to request application ID") + ErrRequestToken = errors.New("failed to request token") + ErrInvalidToken = errors.New("invalid token provided") + ErrCreateRequest = errors.New("failed to create request") + ErrMissingAuthHeaders = errors.New("missing authentication headers") + ErrMissingAuthURLParams = errors.New("missing authentication URL parameters") ) diff --git a/api/errors.go b/api/errors.go index 6613cf8..a765c17 100644 --- a/api/errors.go +++ b/api/errors.go @@ -3,25 +3,21 @@ package api import ( "net/http" - "github.com/simpleauthlink/authapi/api/io" + "go.k7z7z.cc/x/net/http/io" ) var ( // Decode data errors - DecodeAppIDRequestErr = io.NewAPIError(1001, http.StatusBadRequest).With("could not decode app id request") - DecodeTokenRequestErr = io.NewAPIError(1002, http.StatusBadRequest).With("could not decode token request") - DecodeTokenStatusRequestErr = io.NewAPIError(1003, http.StatusBadRequest).With("could not decode token status request") - // Encode data errors - EncodeAppIDResponseErr = io.NewAPIError(1010, http.StatusInternalServerError).With("could not encode app id response") - EncodeTokenStatusResponseErr = io.NewAPIError(1011, http.StatusInternalServerError).With("could not encode token status response") + ErrDecodeAppIDRequest = io.NewAPIError(4001, http.StatusBadRequest).With("could not decode app id request") + ErrDecodeTokenRequest = io.NewAPIError(4002, http.StatusBadRequest).With("could not decode token request") + ErrDecodeTokenStatusRequest = io.NewAPIError(4003, http.StatusBadRequest).With("could not decode token status request") // Bad request errors - InvalidAppHeadersErr = io.NewAPIError(1020, http.StatusBadRequest).With("invalid app headers") - InvalidAppIDErr = io.NewAPIError(1021, http.StatusBadRequest).With("invalid app id") - InvalidAppSecretErr = io.NewAPIError(1022, http.StatusBadRequest).With("invalid app secret") - InvalidDemoEmailInboxErr = io.NewAPIError(1023, http.StatusBadRequest).With("invalid demo email inbox") + ErrInvalidAppHeaders = io.NewAPIError(4004, http.StatusBadRequest).With("invalid app headers") + ErrInvalidAppID = io.NewAPIError(4005, http.StatusBadRequest).With("invalid app id") + ErrInvalidAppSecret = io.NewAPIError(4006, http.StatusBadRequest).With("invalid app secret") + ErrInvalidNotificationChannel = io.NewAPIError(4007, http.StatusBadRequest).With("invalid notification channel identified") // Internal errors - GenerateTokenErr = io.NewAPIError(1030, http.StatusInternalServerError).With("could not generate token") - GenerateEmailErr = io.NewAPIError(1031, http.StatusInternalServerError).With("could not generate email") - SendEmailErr = io.NewAPIError(1032, http.StatusInternalServerError).With("could not send email") - InternalErr = io.NewAPIError(1033, http.StatusInternalServerError).With("internal server error") + ErrGenerateToken = io.NewAPIError(5001, http.StatusInternalServerError).With("could not generate token") + ErrGenerateNotification = io.NewAPIError(5002, http.StatusInternalServerError).With("could not generate notification") + ErrNotificationChannel = io.NewAPIError(5003, http.StatusInternalServerError).With("could not send notification") ) diff --git a/api/handlers.go b/api/handlers.go index 8b4472c..ab120aa 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -1,14 +1,13 @@ package api import ( - "fmt" "net/http" "net/url" - "github.com/simpleauthlink/authapi/api/io" - "github.com/simpleauthlink/authapi/notification" - "github.com/simpleauthlink/authapi/notification/templates/login" + "github.com/simpleauthlink/authapi/notification/email" + "github.com/simpleauthlink/authapi/notification/email/templates/login" "github.com/simpleauthlink/authapi/token" + "go.k7z7z.cc/x/net/http/io" ) // generateAppIDHandler handles the request to generate an app id it decodes @@ -22,27 +21,28 @@ func (s *Service) generateAppIDHandler(w http.ResponseWriter, r *http.Request) { // decode the app data from the request body req := new(io.Request[AppIDRequest]) if err := req.Read(r); err != nil { - DecodeAppIDRequestErr.WithErr(err).Write(w) + ErrDecodeAppIDRequest.WithErr(err).Write(w) return } // create the app from the data and check if it is valid - app, appSecret := req.Data.parseApp() - secret := new(token.Secret).SetParts([]byte(s.cfg.Secret), []byte(appSecret)) - app.SetSecret(secret) - if !app.Valid(secret.Hash()) { - InvalidAppIDErr.Write(w) + app, err := req.Data.parseApp(s.cfg.Secret) + if err != nil { + ErrInvalidAppID.WithErr(err).Write(w) + return + } + if err := app.Valid(app.AppSecretHash); err != nil { + ErrInvalidAppID.WithErr(err).Write(w) return } // return the app id - io.ResponseWith(&AppIDResponse{app.ID(secret).String()}).WriteJSON(w) + io.ResponseWith(&AppIDResponse{app.ID(app.Secret).String()}).WriteJSON(w) } -func (s *Service) requestTokenHandler(w http.ResponseWriter, r *http.Request) { +func (s *Service) appAndSecretFromRequest(r *http.Request) (*token.App, *token.Secret, *io.APIError) { // get the app id from the request header strAppID, strAppSecret, err := appConfigFromRequest(r) if err != nil { - InvalidAppHeadersErr.WithErr(err).Write(w) - return + return nil, nil, ErrInvalidAppHeaders } // decode the app id get the app from it appID := new(token.AppID).SetString(strAppID) @@ -50,81 +50,93 @@ func (s *Service) requestTokenHandler(w http.ResponseWriter, r *http.Request) { // compose the app secret with both parts secret := new(token.Secret).SetParts([]byte(s.cfg.Secret), []byte(strAppSecret)) if !secret.Valid() { - InvalidAppSecretErr.Write(w) - return + return nil, nil, ErrInvalidAppSecret } // check if the app id is valid (it should be a valid app) - if !app.Valid(secret.Hash()) { - InvalidAppIDErr.Write(w) + if err := app.Valid(secret.Hash()); err != nil { + return nil, nil, ErrInvalidAppID + } + return app, secret, nil +} + +func (s *Service) requestTokenHandler(w http.ResponseWriter, r *http.Request) { + app, secret, err := s.appAndSecretFromRequest(r) + if err != nil { + err.Write(w) return } + appID := app.ID(secret) // decode the token request from the request body req := new(io.Request[TokenRequest]) if err := req.Read(r); err != nil { - DecodeTokenRequestErr.WithErr(err).Write(w) - return - } - // generate user token - token := appID.GenerateToken(*secret, req.Data.Email) - if token == nil { - GenerateTokenErr.With(req.Data.Email).Write(w) + ErrDecodeTokenRequest.WithErr(err).Write(w) return } - // compose the email with the token - loginData := login.Data{ - AppName: app.Name, - Email: req.Data.Email, - Token: token.String(), - Link: app.RedirectURI + url.QueryEscape(token.String()), - } - loginEmail, err := login.Template.Compose(notification.NotificationParams{ - To: req.Data.Email, - Subject: loginData.Subject(), - }, loginData) - if err != nil { - GenerateEmailErr.WithErr(err).Write(w) - return - } - // push the email to the notification queue - if err := s.nq.Push(loginEmail); err != nil { - SendEmailErr.WithErr(err).Write(w) + + switch { + case req.Data.IsEmail(): + // generate user genToken + genToken := appID.GenerateToken(*secret, token.UserID(req.Data.Email)) + if genToken == nil { + ErrGenerateToken.With(req.Data.Email).Write(w) + return + } + + linkURL, err := url.Parse(app.RedirectURI) + if err != nil { + ErrGenerateNotification.WithErr(err).Write(w) + return + } + q := linkURL.Query() + q.Set("token", genToken.String()) + q.Set("user", req.Data.Email) + linkURL.RawQuery = q.Encode() + + // compose the email with the token + loginData := login.Data{ + AppName: app.Name, + Email: req.Data.Email, + Token: genToken.String(), + Link: linkURL.String(), + } + loginEmail, err := login.Template.Compose(email.EmailParams{ + To: req.Data.Email, + Subject: loginData.Subject(), + }, loginData) + if err != nil { + ErrGenerateNotification.WithErr(err).Write(w) + return + } + // push the email to the notification queue + if err := s.nq.Push(loginEmail); err != nil { + ErrNotificationChannel.WithErr(err).Write(w) + return + } + default: + ErrInvalidNotificationChannel.Write(w) return } io.OkResponse().WriteJSON(w) } func (s *Service) verifyTokenHandler(w http.ResponseWriter, r *http.Request) { - // get the app id from the request header - strAppID, strAppSecret, err := appConfigFromRequest(r) + app, secret, err := s.appAndSecretFromRequest(r) if err != nil { - InvalidAppHeadersErr.WithErr(err).Write(w) - return - } - // decode the app id get the app from it - appID := new(token.AppID).SetString(strAppID) - app := new(token.App).SetID(appID) - // compose the app secret with both parts - secret := new(token.Secret).SetParts([]byte(s.cfg.Secret), []byte(strAppSecret)) - if !secret.Valid() { - InvalidAppSecretErr.Write(w) - return - } - // check if the app id is valid (it should be a valid app) - if !app.Valid(secret.Hash()) { - InvalidAppIDErr.Write(w) + err.Write(w) return } + appID := app.ID(secret) // decode the token status request from the request body req := new(io.Request[TokenStatusRequest]) if err := req.Read(r); err != nil { - DecodeTokenStatusRequestErr.WithErr(err).Write(w) + ErrDecodeTokenStatusRequest.WithErr(err).Write(w) return } // check if the token is valid tkn := new(token.Token).SetString(req.Data.Token) exp := tkn.Expiration().Time() io.ResponseWith(&TokenStatusResponse{ - Valid: appID.VerifyToken(*tkn, *secret, req.Data.Email), + Valid: appID.VerifyToken(*tkn, *secret, token.UserID(req.Data.Email)), Expiration: exp, }).WriteJSON(w) } @@ -132,38 +144,3 @@ func (s *Service) verifyTokenHandler(w http.ResponseWriter, r *http.Request) { func (s *Service) healthCheckHandler(w http.ResponseWriter, r *http.Request) { io.OkResponse().Write(w) } - -func (s *Service) demoInboxHandler(w http.ResponseWriter, r *http.Request) { - // get the email from get parameters - email := r.URL.Query().Get("email") - if email == "" { - InvalidDemoEmailInboxErr.Write(w) - return - } - // set http headers required for SSE - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - // create a channel for client disconnection - clientGone := r.Context().Done() - // create a response controller - rc := http.NewResponseController(w) - for { - select { - case <-s.ctx.Done(): - case <-clientGone: - return - case msg := <-s.demoMailInbox: - // find the token in the email - if testToken := login.FindToken(email, msg); testToken != nil { - // send an event to the client with the token in the "data" field - if _, err := fmt.Fprintf(w, "data: %s\n\n", testToken); err != nil { - return - } - if err := rc.Flush(); err != nil { - return - } - } - } - } -} diff --git a/api/handlers_test.go b/api/handlers_test.go index ba2c7de..f6cea26 100644 --- a/api/handlers_test.go +++ b/api/handlers_test.go @@ -9,10 +9,12 @@ import ( "testing" "time" - apiio "github.com/simpleauthlink/authapi/api/io" + "github.com/simpleauthlink/authapi/notification" "github.com/simpleauthlink/authapi/notification/email" - "github.com/simpleauthlink/authapi/notification/templates/login" + "github.com/simpleauthlink/authapi/notification/email/templates/login" "github.com/simpleauthlink/authapi/token" + xnet "go.k7z7z.cc/x/net" + apiio "go.k7z7z.cc/x/net/http/io" ) type testCaseAPIHandler[ReqType, ResType any] struct { @@ -26,7 +28,7 @@ type testCaseAPIHandler[ReqType, ResType any] struct { } func (testCase testCaseAPIHandler[Rq, Rs]) url() string { - return fmt.Sprintf("%s%s", testServerApiURL, testCase.endpoint) + return fmt.Sprintf("%s%s", testServerAPIURL, testCase.endpoint) } func (testCase testCaseAPIHandler[Rq, Rs]) Run(t *testing.T) { @@ -114,7 +116,7 @@ func TestGenerateAppIDHandler(t *testing.T) { method: http.MethodPost, endpoint: AppsPath, request: nil, - err: DecodeAppIDRequestErr, + err: ErrDecodeAppIDRequest, }.Run(t) testCaseAPIHandler[AppIDRequest, AppIDResponse]{ name: "invalid request", @@ -126,7 +128,19 @@ func TestGenerateAppIDHandler(t *testing.T) { Duration: time.Second.String(), Secret: testAppSecret, }, - err: InvalidAppIDErr, + err: ErrInvalidAppID, + }.Run(t) + testCaseAPIHandler[AppIDRequest, AppIDResponse]{ + name: "invalid duration string", + method: http.MethodPost, + endpoint: AppsPath, + request: &AppIDRequest{ + Name: testAppName, + RedirectURL: testAppRedirectURL, + Duration: "not-a-duration", + Secret: testAppSecret, + }, + err: ErrInvalidAppID, }.Run(t) } @@ -150,7 +164,7 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { Email: testUserEmail, }, response: nil, - err: InvalidAppHeadersErr, + err: ErrInvalidAppHeaders, }.Run(t) testCaseAPIHandler[TokenRequest, any]{ name: "invalid app id request", @@ -164,7 +178,7 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { Email: testUserEmail, }, response: nil, - err: InvalidAppIDErr, + err: ErrInvalidAppID, }.Run(t) testCaseAPIHandler[TokenRequest, any]{ name: "no app secret request", @@ -177,21 +191,7 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { Email: testUserEmail, }, response: nil, - err: InvalidAppHeadersErr, - }.Run(t) - testCaseAPIHandler[TokenRequest, any]{ - name: "no email provided", - method: http.MethodPost, - endpoint: TokensPath, - header: http.Header{ - AppIDHeader: []string{testAppID.String()}, - AppSecretHeader: []string{testAppSecret}, - }, - request: &TokenRequest{ - Email: "", - }, - response: nil, - err: GenerateTokenErr, + err: ErrInvalidAppHeaders, }.Run(t) invalid := []byte("invalid") testCaseAPIHandler[[]byte, any]{ @@ -204,9 +204,13 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { }, request: &invalid, response: nil, - err: DecodeTokenRequestErr, + err: ErrDecodeTokenRequest, }.Run(t) + originalTemplate := login.Template + defer func() { + login.Template = originalTemplate + }() login.Template = email.EmailTemplate{ HTML: "", Plain: `\[{{.Token}}]`, @@ -232,7 +236,6 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { if testToken == nil { t.Fatal("could not find token in email") } - break case <-time.After(2 * time.Second): t.Fatal("timed out waiting for the email to be received") } @@ -255,6 +258,94 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { }, }.Run(t) + // invalid token tests + testTokenStr := testToken.String() + parts := bytes.Split([]byte(testTokenStr), []byte(".")) + if len(parts) != 2 { + t.Fatalf("expected 2 token parts, got %d", len(parts)) + } + expPart, sigPart := string(parts[0]), string(parts[1]) + + verifyToken := func(name, tokenStr string, expectValid bool) { + t.Run(name, func(t *testing.T) { + rawBody, _ := json.Marshal(&TokenStatusRequest{ + Token: tokenStr, + Email: testUserEmail, + }) + req, err := http.NewRequest(http.MethodPut, + testServerAPIURL+TokensPath, bytes.NewReader(rawBody)) + if err != nil { + t.Fatalf("could not create request: %v", err) + } + req.Header.Set(AppIDHeader, testAppID.String()) + req.Header.Set(AppSecretHeader, testAppSecret) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("could not send request: %v", err) + } + defer func() { + _ = resp.Body.Close() + }() + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200, got %d", resp.StatusCode) + } + var tr TokenStatusResponse + if err := json.NewDecoder(resp.Body).Decode(&tr); err != nil { + t.Fatalf("could not decode response: %v", err) + } + if tr.Valid != expectValid { + t.Errorf("expected Valid=%v, got Valid=%v", expectValid, tr.Valid) + } + }) + } + + // verify POST /tokens returns 200 for any body (dangerous if misused for verification) + verifyPostNotVerify := func(name, body string) { + t.Run("POST "+name, func(t *testing.T) { + req, err := http.NewRequest(http.MethodPost, + testServerAPIURL+TokensPath, + bytes.NewReader([]byte(body))) + if err != nil { + t.Fatalf("could not create request: %v", err) + } + req.Header.Set(AppIDHeader, testAppID.String()) + req.Header.Set(AppSecretHeader, testAppSecret) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("could not send request: %v", err) + } + defer func() { + _ = resp.Body.Close() + }() + if resp.StatusCode != http.StatusOK { + t.Errorf("POST with %s returned %d, expected 200", name, resp.StatusCode) + } + }) + } + // If user accidentally sends token+email via POST, it returns 200, + // looks like "verified" + invalidTokenBody := fmt.Sprintf(`{"token":"%s","email":"%s"}`, testTokenStr, testUserEmail) + verifyPostNotVerify("valid token via POST", invalidTokenBody) + verifyPostNotVerify("modified exp via POST", fmt.Sprintf(`{"token":"%s","email":"%s"}`, + expPart[:2]+"B"+expPart[3:]+"."+sigPart, testUserEmail)) + verifyPostNotVerify("garbage via POST", `{"token":"abc","email":"x@y.com"}`) + + verifyToken("valid original token", testTokenStr, true) + + if len(expPart) >= 3 { + modifiedExp := expPart[:2] + "B" + expPart[3:] + verifyToken("modified expiration (A→B)", modifiedExp+"."+sigPart, false) + } + + if len(sigPart) >= 29 { + modifiedSig := sigPart[:28] + "f" + sigPart[29:] + verifyToken("modified signature (a→f)", expPart+"."+modifiedSig, false) + } + + verifyToken("empty token", "", false) + verifyToken("garbage token", "not.a.token", false) + verifyToken("random token", "YWJj.eHl6", false) + testCaseAPIHandler[TokenStatusRequest, any]{ name: "invalid app id", method: http.MethodPut, @@ -268,7 +359,7 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { Email: testUserEmail, }, response: nil, - err: InvalidAppIDErr, + err: ErrInvalidAppID, }.Run(t) testCaseAPIHandler[TokenStatusRequest, any]{ @@ -283,7 +374,7 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { Email: testUserEmail, }, response: nil, - err: InvalidAppHeadersErr, + err: ErrInvalidAppHeaders, }.Run(t) testCaseAPIHandler[TokenStatusRequest, any]{ @@ -295,7 +386,7 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { Email: testUserEmail, }, response: nil, - err: InvalidAppHeadersErr, + err: ErrInvalidAppHeaders, }.Run(t) testCaseAPIHandler[any, any]{ @@ -306,6 +397,108 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { AppIDHeader: []string{testAppID.String()}, AppSecretHeader: []string{testAppSecret}, }, - err: DecodeTokenStatusRequestErr, + err: ErrDecodeTokenStatusRequest, }.Run(t) } + +func TestRequestTokenHandlerErrorBranches(t *testing.T) { + // Build the same app/secret as TestMain + app := &token.App{ + Name: testAppName, + RedirectURI: testAppRedirectURL, + SessionDuration: testAppSessionDuration, + } + secret := new(token.Secret).SetParts([]byte(testServerSecret), []byte(testAppSecret)) + app.SetSecret(secret) + appID := app.ID(secret) + + t.Run("invalid notification channel", func(t *testing.T) { + testCaseAPIHandler[TokenRequest, any]{ + name: "non-email hits default", + method: http.MethodPost, + endpoint: TokensPath, + header: http.Header{ + AppIDHeader: []string{appID.String()}, + AppSecretHeader: []string{testAppSecret}, + }, + request: &TokenRequest{Email: "not-an-email"}, + err: ErrInvalidNotificationChannel, + }.Run(t) + }) + + t.Run("template compose failure", func(t *testing.T) { + original := login.Template + defer func() { login.Template = original }() + login.Template = email.EmailTemplate{ + HTML: "", + Plain: `Hi {{.Email}}. Token: {{.Token}`, // syntax error: missing } + } + testCaseAPIHandler[TokenRequest, any]{ + name: "broken template", + method: http.MethodPost, + endpoint: TokensPath, + header: http.Header{ + AppIDHeader: []string{appID.String()}, + AppSecretHeader: []string{testAppSecret}, + }, + request: &TokenRequest{Email: testUserEmail}, + err: ErrGenerateNotification, + }.Run(t) + }) + + t.Run("queue push failure", func(t *testing.T) { + port, err := xnet.SafeTestPort() + if err != nil { + t.Fatal(err) + } + // Zero-size queue: Push always returns ErrQueueFull + eq, err := notification.NewQueue(t.Context(), 0) + if err != nil { + t.Fatal(err) + } + // no workers: push always returns ErrQueueFull on unbuffered channel + eq.Start(0) + defer eq.Stop() + + srv, err := New(t.Context(), &Config{ + Server: testServerAddr, + ServerPort: port, + Secret: testServerSecret, + }, eq) + if err != nil { + t.Fatal(err) + } + go func() { _ = srv.Start() }() + defer func() { _ = srv.Stop() }() + + // Wait for server to be ready + for range 10 { + if srv.Ping() { + break + } + time.Sleep(100 * time.Millisecond) + } + + endpoint := fmt.Sprintf("http://%s:%d%s", testServerAddr, port, TokensPath) + rawBody, _ := json.Marshal(&TokenRequest{Email: testUserEmail}) + req, _ := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(rawBody)) + req.Header.Set(AppIDHeader, appID.String()) + req.Header.Set(AppSecretHeader, testAppSecret) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("request failed: %v", err) + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusInternalServerError { + t.Errorf("expected 500, got %d", resp.StatusCode) + } + var apiErr apiio.APIError + if err := json.NewDecoder(resp.Body).Decode(&apiErr); err != nil { + t.Fatalf("decode error: %v", err) + } + if apiErr.Code != ErrNotificationChannel.Code { + t.Errorf("expected code %d, got %d", ErrNotificationChannel.Code, apiErr.Code) + } + }) +} diff --git a/api/helpers.go b/api/helpers.go index 49fb9fc..6fcbdbd 100644 --- a/api/helpers.go +++ b/api/helpers.go @@ -9,7 +9,7 @@ import ( // headers. It returns an error if the app id or app secret is missing. The // app id and app secret are used to authenticate the app making the request. // The app id is a unique identifier for the app, and the app secret is a -// shared secret used to verify the authenticity of the request for this +// shared secret used to verify the authenticity of the request for this // service. func appConfigFromRequest(r *http.Request) (string, string, error) { // get the app id from the request header diff --git a/api/io/apierror.go b/api/io/apierror.go deleted file mode 100644 index 6e9f9f3..0000000 --- a/api/io/apierror.go +++ /dev/null @@ -1,85 +0,0 @@ -package io - -import ( - "encoding/json" - "fmt" - "net/http" -) - -// APIError represents an error response from the API. It includes a code, -// message, and optional error string. The StatusCode field is used to set the -// HTTP status code for the response. It has some methods to manipulate the -// error message and write the error response to an http.ResponseWriter. -type APIError struct { - Code int `json:"code"` - Message string `json:"message"` - Err string `json:"error,omitempty"` - StatusCode int `json:"-"` -} - -// Error implements the error interface for APIError. It returns a string -// representation of the error, including the code, message, error string, -// and status code. It can be used for logging or debugging purposes. -func (e *APIError) Error() string { - return fmt.Sprintf("code: %d, message: %s, error: %s, status_code: %d", e.Code, e.Message, e.Err, e.StatusCode) -} - -// WithErr appends an error message to the existing error string in the -// APIError. If the existing error string is empty, it sets it to the new -// error message. This method is useful for chaining error messages together -// for better debugging and logging. It returns the updated APIError instance -// and also updates the current instance. -func (e *APIError) WithErr(err error) *APIError { - if e.Err == "" { - e.Err = err.Error() - return e - } - e.Err = fmt.Sprintf("%s: %s", e.Err, err.Error()) - return e -} - -// With appends a string message to the existing message in the APIError. If -// the existing message is empty, it sets it to the new message. This method -// is useful for chaining messages together for better debugging and logging. -// It returns the updated APIError instance and also updates the current -// instance. -func (e *APIError) With(msg string) *APIError { - if e.Message == "" { - e.Message = msg - return e - } - e.Message = fmt.Sprintf("%s: %s", e.Message, msg) - return e -} - -// WriteJSON writes the APIError as a JSON response to the provided -// http.ResponseWriter. It sets the Content-Type header to "application/json" -// and writes the status code and serialized error bytes to the response. -// If an error occurs during writing, it writes an internal server error -// response instead. -func (e *APIError) Write(w http.ResponseWriter) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(e.StatusCode) - if _, err := w.Write(e.bytes()); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} - -// bytes serializes the APIError to JSON bytes. If an error occurs during -// serialization, it returns nil. -func (e *APIError) bytes() []byte { - bErr, _ := json.Marshal(e) - return bErr -} - -// NewAPIError creates a new APIError instance with the provided code and -// status code. It initializes the error string and message to empty strings. -// This function is useful for creating a new APIError instance with -// specific error codes and status codes. It returns a pointer to the -// newly created APIError instance. -func NewAPIError(code, status int) *APIError { - return &APIError{ - Code: code, - StatusCode: status, - } -} diff --git a/api/io/apierror_test.go b/api/io/apierror_test.go deleted file mode 100644 index cb85b80..0000000 --- a/api/io/apierror_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package io - -import ( - "errors" - "net/http" - "net/http/httptest" - "testing" -) - -func TestNewAPIError(t *testing.T) { - err := NewAPIError(1001, http.StatusBadRequest) - if err.Code != 1001 { - t.Errorf("expected code 1001, got %d", err.Code) - } - if err.StatusCode != http.StatusBadRequest { - t.Errorf("expected status code %d, got %d", http.StatusBadRequest, err.StatusCode) - } - if err.Message != "" { - t.Errorf("expected empty message, got %s", err.Message) - } - if err.Err != "" { - t.Errorf("expected empty error string, got %s", err.Err) - } -} - -func TestAPIError_Error(t *testing.T) { - err := NewAPIError(1001, http.StatusBadRequest) - err.Message = "Bad Request" - err.Err = "Invalid input" - expected := "code: 1001, message: Bad Request, error: Invalid input, status_code: 400" - if err.Error() != expected { - t.Errorf("expected %s, got %s", expected, err.Error()) - } -} - -func TestAPIError_WithErr(t *testing.T) { - err := NewAPIError(1001, http.StatusBadRequest) - _ = err.WithErr(errors.New("Invalid input")) - if err.Err != "Invalid input" { - t.Errorf("expected error string 'Invalid input', got %s", err.Err) - } - - _ = err.WithErr(errors.New("Missing field")) - if err.Err != "Invalid input: Missing field" { - t.Errorf("expected error string 'Invalid input: Missing field', got %s", err.Err) - } -} - -func TestAPIError_With(t *testing.T) { - err := NewAPIError(1001, http.StatusBadRequest) - _ = err.With("Bad Request") - if err.Message != "Bad Request" { - t.Errorf("expected message 'Bad Request', got %s", err.Message) - } - - _ = err.With("Invalid input") - if err.Message != "Bad Request: Invalid input" { - t.Errorf("expected message 'Bad Request: Invalid input', got %s", err.Message) - } -} - -func TestAPIError_Write(t *testing.T) { - t.Run("write error", func(t *testing.T) { - err := NewAPIError(1001, http.StatusInternalServerError) - rr := httptest.NewRecorder() - err.Write(&errorWriter{ResponseRecorder: rr}) - if status := rr.Code; status != http.StatusInternalServerError { - t.Errorf("expected status code %d, got %d", http.StatusInternalServerError, status) - } - }) - - t.Run("success", func(t *testing.T) { - err := NewAPIError(1001, http.StatusBadRequest) - err.Message = "Bad Request" - err.Err = "Invalid input" - - rr := httptest.NewRecorder() - err.Write(rr) - - if status := rr.Code; status != http.StatusBadRequest { - t.Errorf("expected status code %d, got %d", http.StatusBadRequest, status) - } - - expected := `{"code":1001,"message":"Bad Request","error":"Invalid input"}` - if rr.Body.String() != expected { - t.Errorf("expected body %s, got %s", expected, rr.Body.String()) - } - }) -} - -func TestAPIError_bytes(t *testing.T) { - err := NewAPIError(1001, http.StatusBadRequest) - err.Message = "Bad Request" - err.Err = "Invalid input" - - data := err.bytes() - expected := `{"code":1001,"message":"Bad Request","error":"Invalid input"}` - if string(data) != expected { - t.Errorf("expected %s, got %s", expected, string(data)) - } -} diff --git a/api/io/errors.go b/api/io/errors.go deleted file mode 100644 index c61ad79..0000000 --- a/api/io/errors.go +++ /dev/null @@ -1,14 +0,0 @@ -package io - -import "fmt" - -var ( - ErrNilRequest = fmt.Errorf("nil request") - ErrNilRequestBody = fmt.Errorf("nil request body") - ErrNotInitializedRequest = fmt.Errorf("request not initialized") - ErrEmptyRequestBody = fmt.Errorf("empty request body") - ErrReadBody = fmt.Errorf("failed to read request body") - ErrEncodeBody = fmt.Errorf("failed to encode request body") - ErrDecodeBody = fmt.Errorf("failed to decode request body") - ErrHTTPStatusNotOk = fmt.Errorf("no HTTP status OK") -) diff --git a/api/io/req.go b/api/io/req.go deleted file mode 100644 index e9a8ed2..0000000 --- a/api/io/req.go +++ /dev/null @@ -1,87 +0,0 @@ -package io - -import ( - "bytes" - "encoding/json" - "io" - "net/http" -) - -// Request represents a request with a generic data type to be unmarshalled -// from the request body. It implements the Read method to read and -// unmarshal the request body into the Data field. -type Request[T any] struct { - Data T - initialized bool -} - -// RequestWith creates a new Request[T] with the provided data. If the data -// is nil, it returns an empty Request[T], if not, the data is wrapped and -// the resulting request is marked as initialized. This method is useful for -// creating requests with different data types without needing to define -// separate request structs for each type. -func RequestWith[T any](data *T) *Request[T] { - if data == nil { - return &Request[T]{} - } - return &Request[T]{ - Data: *data, - initialized: true, - } -} - -// Read reads the request body and unmarshals it into the Data field of the -// Request struct. It returns an error if the request body is nil or empty, -// or if there is an error during unmarshalling. If the Request struct is nil, -// it initializes a new instance of Request[T]. This method is useful for -// handling incoming requests in a generic way, allowing for different data -// types to be processed without needing to define separate request structs -// for each type. -func (req *Request[T]) Read(r *http.Request) error { - if req == nil { - req = new(Request[T]) - } - if r == nil { - return ErrNilRequest - } - if r.Body == nil { - return ErrNilRequestBody - } - rawBody, err := io.ReadAll(r.Body) - if err != nil { - return ErrReadBody - } - if len(rawBody) == 0 { - return ErrEmptyRequestBody - } - if err := json.Unmarshal(rawBody, &req.Data); err != nil { - return ErrDecodeBody - } - return nil -} - -// WriteJSON writes the request data to the provided http.Request in JSON -// format. It sets the Content-Type header to "application/json" and replaces -// the request body with the JSON marshalled data. If the request is not -// initialized, it returns an error. This method is useful for sending -// requests with structured JSON data. It can be used in HTTP handlers -// or middleware to send requests with specific data types. -func (req *Request[T]) WriteJSON(r *http.Request) error { - if r == nil { - return ErrNilRequest - } - if req == nil || !req.initialized { - return ErrNotInitializedRequest - } - // set the content type to application/json - r.Header.Set("Content-Type", "application/json") - // replace the request with a new one with the same method and URL - // but with the request body set to the JSON marshalled data - buf := new(bytes.Buffer) - if err := json.NewEncoder(buf).Encode(req.Data); err != nil { - return ErrEncodeBody - } - r.Body = io.NopCloser(buf) - r.ContentLength = int64(buf.Len()) - return nil -} diff --git a/api/io/req_test.go b/api/io/req_test.go deleted file mode 100644 index 8c11a06..0000000 --- a/api/io/req_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package io - -import ( - "bytes" - "encoding/json" - "errors" - "io" - "math" - "net/http" - "testing" -) - -type readerFunc func([]byte) (int, error) - -func (f readerFunc) Read(p []byte) (int, error) { return f(p) } - -func TestRequestWith(t *testing.T) { - t.Run("nil data", func(t *testing.T) { - var data *any = nil - req := RequestWith(data) - if req == nil || req.initialized { - t.Errorf("expected uninitialized request, got %v", req) - } - }) - - t.Run("non-nil data", func(t *testing.T) { - data := "test" - req := RequestWith(&data) - if !req.initialized || req.Data != data { - t.Errorf("expected initialized request with data %s, got %v", data, req) - } - }) -} - -func TestReadRequest(t *testing.T) { - t.Run("nil request", func(t *testing.T) { - var req *Request[any] = nil - if err := req.Read(nil); err == nil { - t.Errorf("expected error for nil request, got nil") - } else if !errors.Is(err, ErrNilRequest) { - t.Errorf("expected ErrNilRequest, got %v", err) - } - if err := req.Read(&http.Request{}); err == nil { - t.Errorf("expected error for empty request body, got nil") - } else if !errors.Is(err, ErrNilRequestBody) { - t.Errorf("expected ErrNilRequestBody, got %v", err) - } - }) - - t.Run("read body error", func(t *testing.T) { - errReq := &http.Request{ - Body: io.NopCloser(readerFunc(func([]byte) (int, error) { - return 0, errors.New("forced read error") - })), - } - var req Request[any] - if err := req.Read(errReq); err == nil { - t.Errorf("expected error for read body, got nil") - } else if !errors.Is(err, ErrReadBody) { - t.Errorf("expected ErrReadBody, got %v", err) - } - }) - - t.Run("empty body", func(t *testing.T) { - errReq := &http.Request{ - Body: io.NopCloser(bytes.NewBuffer([]byte{})), - } - var req Request[any] - if err := req.Read(errReq); err == nil { - t.Errorf("expected error for empty body, got nil") - } else if !errors.Is(err, ErrEmptyRequestBody) { - t.Errorf("expected ErrEmptyRequestBody, got %v", err) - } - }) - - t.Run("unmarshal error", func(t *testing.T) { - errReq := &http.Request{ - Body: io.NopCloser(bytes.NewBuffer([]byte("invalid json"))), - } - var req Request[any] - if err := req.Read(errReq); err == nil { - t.Errorf("expected error for unmarshal, got nil") - } else if !errors.Is(err, ErrDecodeBody) { - t.Errorf("expected ErrDecodeBody, got %v", err) - } - }) - - t.Run("success", func(t *testing.T) { - type Data struct { - Message string `json:"message"` - } - data := &Data{Message: "Hello, World!"} - body, _ := json.Marshal(data) - req, err := http.NewRequest("POST", "/", bytes.NewBuffer(body)) - if err != nil { - t.Fatal(err) - } - - var request Request[Data] - if err := request.Read(req); err != nil { - t.Errorf("unexpected error: %v", err) - } - if request.Data.Message != data.Message { - t.Errorf("expected %s, got %s", data.Message, request.Data.Message) - } - }) -} - -func TestWriteJSONRequest(t *testing.T) { - t.Run("nil request", func(t *testing.T) { - var req *Request[any] = nil - if err := req.WriteJSON(nil); err == nil { - t.Errorf("expected error for nil request, got nil") - } else if !errors.Is(err, ErrNilRequest) { - t.Errorf("expected ErrNilRequest, got %v", err) - } - }) - - t.Run("not initialized", func(t *testing.T) { - req := new(Request[any]) - if err := req.WriteJSON(&http.Request{}); err == nil { - t.Errorf("expected error for not initialized request, got nil") - } else if !errors.Is(err, ErrNotInitializedRequest) { - t.Errorf("expected ErrNotInitializedRequest, got %v", err) - } - }) - - t.Run("write JSON error", func(t *testing.T) { - data := struct { - Invalid float64 - }{ - Invalid: math.NaN(), - } - req := RequestWith(&data) - httpReq := &http.Request{ - Header: make(http.Header), - } - if err := req.WriteJSON(httpReq); err == nil { - t.Errorf("expected error for write JSON, got nil") - } else if !errors.Is(err, ErrEncodeBody) { - t.Errorf("expected ErrEncodeBody, got %v", err) - } - if httpReq.Header.Get("Content-Type") != "application/json" { - t.Errorf("expected Content-Type to be application/json, got %s", httpReq.Header.Get("Content-Type")) - } - }) - - t.Run("success", func(t *testing.T) { - data := struct { - Message string `json:"message"` - }{ - Message: "Hello, World!", - } - req := RequestWith(&data) - httpReq := &http.Request{ - Header: make(http.Header), - } - if err := req.WriteJSON(httpReq); err != nil { - t.Errorf("unexpected error: %v", err) - } - if httpReq.Header.Get("Content-Type") != "application/json" { - t.Errorf("expected Content-Type to be application/json, got %s", httpReq.Header.Get("Content-Type")) - } - }) -} diff --git a/api/io/res.go b/api/io/res.go deleted file mode 100644 index 50f606b..0000000 --- a/api/io/res.go +++ /dev/null @@ -1,147 +0,0 @@ -package io - -import ( - "encoding/json" - "io" - "net/http" -) - -// Response represents a response with a generic data type. It can be used to -// send JSON responses or plain text responses. The Data field holds the -// response data, and the empty field indicates whether the response is empty -// or not. It has methods to write the response to an http.ResponseWriter in -// JSON format or plain text format. -type Response[T any] struct { - Data T - empty bool -} - -// ResponseWith creates a new Response instance with the provided data. If -// the data is nil, it returns an empty response. This method is useful for -// creating responses with different data types without needing to define -// separate response structs for each type. It returns a pointer to the -// Response instance. -func ResponseWith[T any](data *T) *Response[T] { - if data == nil { - return &Response[T]{empty: true} - } - return &Response[T]{ - Data: *data, - empty: false, - } -} - -// OkResponse creates a new Response instance with the provided byte slice. -// If the byte slice is empty, it returns an empty response. This method is -// useful for creating responses with raw byte data. It returns a pointer to -// the Response instance. The empty field indicates whether the response is -// empty or not. If the byte slice is empty, the response is considered empty. -// If the byte slice is not empty, the response is considered non-empty. -func OkResponse(body ...byte) *Response[any] { - if len(body) > 0 { - return &Response[any]{Data: body, empty: false} - } - return &Response[any]{empty: true} -} - -// WriteJSON writes the response data to the provided http.ResponseWriter in -// JSON format. It sets the Content-Type header to "application/json" and -// writes the response data as JSON. If the response is empty, it writes a -// plain text "OK" response with a 200 OK status code. If there is an error -// during JSON encoding or response writing, it writes an error response with -// a 500 Internal Server Error status code. This method is useful for sending -// JSON responses to the client. It can be used in HTTP handlers or middleware -// to send structured JSON responses. -func (r *Response[T]) WriteJSON(w http.ResponseWriter) { - if !r.empty { - w.Header().Set("Content-Type", "application/json") - if err := json.NewEncoder(w).Encode(r.Data); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - return - } - if _, err := w.Write([]byte(http.StatusText(http.StatusOK))); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } -} - -// Write writes the response data to the provided http.ResponseWriter in -// plain text format. It sets the Content-Type header to "text/plain" and -// writes the response data as plain text. If the response is empty, it writes -// a plain text "OK" response with a 200 OK status code. If there is an error -// during response writing, it writes an error response with a 500 Internal -// Server Error status code. This method is useful for sending plain text -// responses to the client. It can be used in HTTP handlers or middleware to -// send simple text responses. It is a more generic method than WriteJSON, as -// it does not require the response data to be JSON-serializable. -func (r *Response[T]) Write(w http.ResponseWriter) { - if r.empty { - if _, err := w.Write([]byte(http.StatusText(http.StatusOK))); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - return - } - if data, ok := r.bytes(); ok { - if _, err := w.Write(data); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - } -} - -// Read reads the response data from the provided http.Response. It expects -// the response body to be in JSON format and unmarshals it into the provided -// generic type T. If the response status code is not 200 OK, it returns an -// error indicating the unexpected status code. If there is an error reading -// the response body or unmarshaling the JSON data, it returns an error. This -// method is useful for handling HTTP responses in a generic way, allowing -// you to read and process the response data without needing to know the -// specific type of the response data in advance. -func (r *Response[T]) Read(res *http.Response) (T, error) { - if res == nil { - return *new(T), ErrNilRequest - } - if res.Body == nil { - return *new(T), ErrNilRequestBody - } - defer func() { - _ = res.Body.Close() - }() - result := new(T) - // read the response body - rawBody, err := io.ReadAll(res.Body) - if err != nil { - return *result, ErrReadBody - } - // check the status code of the response - if res.StatusCode != http.StatusOK { - return *result, ErrHTTPStatusNotOk - } - // unmarshal the response body into the result - if err := json.Unmarshal(rawBody, result); err != nil { - return *result, ErrDecodeBody - } - return *result, nil -} - -// bytes returns the response data as a byte slice. If the response is empty, -// it returns nil and a boolean indicating that the response is empty. If the -// response data is not a byte slice, it returns nil and a boolean indicating -// that the response data is not a byte slice. This method is useful for -// converting the response data to a byte slice for writing to the response -// writer or for further processing. -func (r *Response[T]) bytes() ([]byte, bool) { - // check if the response is empty - if r.empty { - return nil, true - } - // ensure that the response data is an slice of bytes - switch v := any(r.Data).(type) { - case []byte: - return v, true - case string: - return []byte(v), true - default: - return nil, false - } -} diff --git a/api/io/res_test.go b/api/io/res_test.go deleted file mode 100644 index 9262844..0000000 --- a/api/io/res_test.go +++ /dev/null @@ -1,270 +0,0 @@ -package io - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "math" - "net/http" - "net/http/httptest" - "testing" -) - -type errorWriter struct { - *httptest.ResponseRecorder -} - -func (e *errorWriter) Write(p []byte) (int, error) { - return 0, fmt.Errorf("forced write error") -} - -func TestResponseWith(t *testing.T) { - type Data struct { - Message string `json:"message"` - } - nilResp := ResponseWith[Data](nil) - if !nilResp.empty { - t.Errorf("expected response to be empty") - } - data := &Data{Message: "Hello, World!"} - resp := ResponseWith(data) - if resp.empty { - t.Errorf("expected response to be non-empty") - } - if resp.Data.Message != data.Message { - t.Errorf("expected %s, got %s", data.Message, resp.Data.Message) - } -} - -func TestOkResponse(t *testing.T) { - t.Run("non-empty", func(t *testing.T) { - body := []byte("Hello, World!") - if noEmptyRes := OkResponse(body...); noEmptyRes.empty { - t.Errorf("expected response to be non-empty") - } - }) - t.Run("empty", func(t *testing.T) { - if emptyRes := OkResponse(); !emptyRes.empty { - t.Errorf("expected response to be empty") - } - }) -} - -func TestWriteJSON(t *testing.T) { - type Data struct { - Message float64 `json:"message"` - } - - t.Run("encode error", func(t *testing.T) { - resp := &Response[Data]{Data: Data{Message: math.NaN()}, empty: false} - rr := httptest.NewRecorder() - resp.WriteJSON(rr) - if status := rr.Code; status != http.StatusInternalServerError { - t.Errorf("expected status code %d, got %d", http.StatusInternalServerError, status) - } - }) - - t.Run("write error", func(t *testing.T) { - resp := &Response[any]{Data: nil, empty: true} - rr := httptest.NewRecorder() - resp.WriteJSON(&errorWriter{ResponseRecorder: rr}) - if status := rr.Code; status != http.StatusInternalServerError { - t.Errorf("expected status code %d, got %d", http.StatusInternalServerError, status) - } - }) - - t.Run("non-empty", func(t *testing.T) { - data := &Data{Message: 1} - resp := ResponseWith(data) - - rr := httptest.NewRecorder() - resp.WriteJSON(rr) - - if status := rr.Code; status != http.StatusOK { - t.Errorf("expected status code %d, got %d", http.StatusOK, status) - } - - expected, _ := json.Marshal(data) - if rr.Body.String() != string(expected)+"\n" { // Ensure newline is accounted for - t.Errorf("expected body %s, got %s", string(expected)+"\n", rr.Body.String()) - } - }) - - t.Run("empty", func(t *testing.T) { - // write json with nil data - nilResp := ResponseWith[string](nil) - rr := httptest.NewRecorder() - nilResp.WriteJSON(rr) - if status := rr.Code; status != http.StatusOK { - t.Errorf("expected status code %d, got %d", http.StatusOK, status) - } - }) -} - -func TestWrite(t *testing.T) { - t.Run("empty", func(t *testing.T) { - resp := OkResponse() - rr := httptest.NewRecorder() - resp.Write(rr) - - if status := rr.Code; status != http.StatusOK { - t.Errorf("expected status code %d, got %d", http.StatusOK, status) - } - - if rr.Body.String() != "OK" { - t.Errorf("expected body OK, got %s", rr.Body.String()) - } - }) - - t.Run("empty error", func(t *testing.T) { - resp := &Response[any]{empty: true} - rr := httptest.NewRecorder() - resp.Write(&errorWriter{ResponseRecorder: rr}) - - if status := rr.Code; status != http.StatusInternalServerError { - t.Errorf("expected status code %d, got %d", http.StatusInternalServerError, status) - } - }) - - t.Run("non-empty", func(t *testing.T) { - body := []byte("Hello, World!") - resp := OkResponse(body...) - - rr := httptest.NewRecorder() - resp.Write(rr) - - if status := rr.Code; status != http.StatusOK { - t.Errorf("expected status code %d, got %d", http.StatusOK, status) - } - - if rr.Body.String() != string(body) { - t.Errorf("expected body %s, got %s", string(body), rr.Body.String()) - } - }) - - t.Run("non-empty error", func(t *testing.T) { - body := []byte("Hello, World!") - resp := OkResponse(body...) - - rr := httptest.NewRecorder() - resp.Write(&errorWriter{ResponseRecorder: rr}) - - if status := rr.Code; status != http.StatusInternalServerError { - t.Errorf("expected status code %d, got %d", http.StatusInternalServerError, status) - } - }) -} - -func TestRead(t *testing.T) { - t.Run("nil response", func(t *testing.T) { - if _, err := new(Response[string]).Read(nil); err != ErrNilRequest { - t.Errorf("expected error %v, got %v", ErrNilRequest, err) - } - }) - - t.Run("nil body", func(t *testing.T) { - if _, err := new(Response[string]).Read(&http.Response{Body: nil}); err != ErrNilRequestBody { - t.Errorf("expected error %v, got %v", ErrNilRequestBody, err) - } - }) - - t.Run("read error", func(t *testing.T) { - res := &http.Response{ - Body: io.NopCloser(readerFunc(func([]byte) (int, error) { - return 0, fmt.Errorf("forced read error") - })), - } - if _, err := new(Response[string]).Read(res); err != ErrReadBody { - t.Errorf("expected error %v, got %v", ErrReadBody, err) - } - }) - - t.Run("status not OK", func(t *testing.T) { - res := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewBuffer([]byte(`{"message":"error"}`))), - } - if _, err := new(Response[string]).Read(res); err != ErrHTTPStatusNotOk { - t.Errorf("expected error %v, got %v", ErrHTTPStatusNotOk, err) - } - }) - - t.Run("unmarshal error", func(t *testing.T) { - res := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewBuffer([]byte("invalid json"))), - } - if _, err := new(Response[string]).Read(res); err != ErrDecodeBody { - t.Errorf("expected error %v, got %v", ErrDecodeBody, err) - } - }) - - t.Run("success", func(t *testing.T) { - type Data struct { - Message string `json:"message"` - } - data := &Data{Message: "Hello, World!"} - body, _ := json.Marshal(data) - res := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewBuffer(body)), - } - result, err := new(Response[Data]).Read(res) - if err != nil { - t.Errorf("expected no error, got %v", err) - } - if result.Message != data.Message { - t.Errorf("expected %s, got %s", data.Message, result.Message) - } - }) -} - -func TestBytes(t *testing.T) { - t.Run("empty", func(t *testing.T) { - resp := OkResponse() - data, ok := resp.bytes() - if !ok { - t.Errorf("expected bytes to be valid") - } - if data != nil { - t.Errorf("expected nil data for empty response, got %v", data) - } - }) - - t.Run("bytes", func(t *testing.T) { - body := []byte("Hello, World!") - resp := ResponseWith(&body) - data, ok := resp.bytes() - if !ok { - t.Errorf("expected bytes to be valid") - } - if string(data) != string(body) { - t.Errorf("expected body %s, got %s", string(body), string(data)) - } - }) - - t.Run("string", func(t *testing.T) { - msg := "Hello, World!" - resp := ResponseWith(&msg) - data, ok := resp.bytes() - if !ok { - t.Errorf("expected bytes to be valid") - } - if string(data) != msg { - t.Errorf("expected body %s, got %s", msg, string(data)) - } - }) - - t.Run("invalid type", func(t *testing.T) { - imsg := 123 - resp := ResponseWith(&imsg) - data, ok := resp.bytes() - if ok { - t.Errorf("expected bytes to be invalid") - } - if data != nil { - t.Errorf("expected nil data for invalid response, got %v", data) - } - }) -} diff --git a/api/routes.go b/api/routes.go index 0d0deb7..3f62f68 100644 --- a/api/routes.go +++ b/api/routes.go @@ -3,16 +3,13 @@ package api // routes paths constants const ( // HealthCheckPath constant is the path used to check the health of the API - // server. It is a string with a value of "/health". + // server. It is a string with a value of "/ping". HealthCheckPath = "/ping" // AppsPath constant is the path used to create the apps in the API server. AppsPath = "/apps" // TokensPath constant is the path used to generate and verify the tokens // in the API server. TokensPath = "/tokens" - // DemoInboxPath constant is the path used to get the demo email inbox - // in the API server when it runs in demo mode. - DemoInboxPath = "/demo/inbox" ) // other api related constants diff --git a/api/service.go b/api/service.go index a54df66..dc134ac 100644 --- a/api/service.go +++ b/api/service.go @@ -4,70 +4,47 @@ import ( "context" "fmt" "net/http" - "os" - "os/signal" - "sync" - "syscall" "time" - "github.com/lucasmenendez/apihandler" - "github.com/simpleauthlink/authapi/internal/fakesmtpserver" "github.com/simpleauthlink/authapi/notification" + xhttp "go.k7z7z.cc/x/net/http" ) // Config struct represents the configuration for the API service. It contains // the server address, server port, and secret key for the service. The server // address is the address where the service will listen for incoming requests, // and the server port is the port number where the service will listen for -// incoming requests. The secret key is used to sign and verify tokens. The -// demo mode is used to enable or disable the demo functionality of the service. -// The demo SMTP address and port are used to configure the demo mail server. -// The demo mode is used to enable or disable the demo functionality of the -// service. +// incoming requests. The secret key is used to sign and verify tokens. type Config struct { Server string ServerPort int Secret string - // demo stuff - DemoMode bool - DemoSMTPAddr string - DemoSMTPPort int } // Service struct represents the API service. It contains the context, cancel -// function, wait group, configuration, notification queue, API handler, HTTP -// server, and demo mail server. The context is used to manage the lifecycle -// of the service, while the wait group is used to wait for background processes -// to finish. The notification queue is used to send notifications, and the API -// handler is used to handle incoming requests. The HTTP server is used to -// serve the API endpoints, and the demo mail server is used to simulate -// sending emails in demo mode. -// The demo mail server is a fake SMTP server that captures emails sent to it -// for testing purposes. The demo mail inbox is a channel that receives the -// captured emails. +// function, wait group, configuration, notification queue, API handler and +// HTTP server. The context is used to manage the lifecycle of the service, +// while the wait group is used to wait for background processes to finish. +// The notification queue is used to send notifications, and the API handler +// is used to handle incoming requests. type Service struct { - ctx context.Context - cancel context.CancelFunc - wait sync.WaitGroup - cfg *Config - nq notification.Queue - handler *apihandler.Handler - httpServer *http.Server - // demo stuff - demoMailServer *fakesmtpserver.FakeSMTPServer - demoMailInbox chan string + ctx context.Context + cancel context.CancelFunc + cfg *Config + nq *notification.Queue + *xhttp.Handler + *http.Server } // New function creates a new service instance. It takes a context, a config // struct, and a notification queue as parameters. It returns a pointer to the // service instance and an error if something goes wrong during the process. // The function is responsible for setting up the service and its dependencies. -// It handles the configuration, rate limiting, and HTTP server setup. It also -// manages the demo mode functionality, including the demo mail server and -// inbox. The function is designed to be used as a constructor for the service -// and is responsible for initializing all the necessary components for the -// service to function properly. -func New(ctx context.Context, cfg *Config, nq notification.Queue) (*Service, error) { +// It handles the configuration, rate limiting, and HTTP server setup. The +// function is designed to be used as a constructor for the service and is +// responsible for initializing all the necessary components for the service +// to function properly. +func New(ctx context.Context, cfg *Config, nq *notification.Queue) (*Service, error) { internalCtx, cancel := context.WithCancel(ctx) // create the service srv := &Service{ @@ -75,29 +52,28 @@ func New(ctx context.Context, cfg *Config, nq notification.Queue) (*Service, err cancel: cancel, cfg: cfg, nq: nq, - handler: apihandler.NewHandler(true), - } - // demo stuff - if cfg.DemoMode { - srv.demoMailInbox = make(chan string, 1) - srv.demoMailServer = fakesmtpserver.NewServer(cfg.DemoSMTPAddr, - cfg.DemoSMTPPort, srv.demoMailInbox) - if err := srv.demoMailServer.Start(internalCtx); err != nil { - return nil, err - } - _ = srv.handler.Get(DemoInboxPath, srv.demoInboxHandler) + Handler: xhttp.NewHandler(true), } // create the rate limiter - rl := apihandler.NewRateLimiter(internalCtx, 100, time.Minute) + rl := xhttp.NewRateLimiter(internalCtx, 100, time.Minute) // register the routes and handlers - _ = srv.handler.Post(AppsPath, rl.Middleware(srv.generateAppIDHandler)) - _ = srv.handler.Post(TokensPath, rl.Middleware(srv.requestTokenHandler)) - _ = srv.handler.Put(TokensPath, rl.Middleware(srv.verifyTokenHandler)) - _ = srv.handler.Get(HealthCheckPath, rl.Middleware(srv.healthCheckHandler)) + if err := srv.Post(AppsPath, rl.Middleware(srv.generateAppIDHandler)); err != nil { + return nil, err + } + if err := srv.Post(TokensPath, rl.Middleware(srv.requestTokenHandler)); err != nil { + return nil, err + } + if err := srv.Put(TokensPath, rl.Middleware(srv.verifyTokenHandler)); err != nil { + return nil, err + } + // do not use rate limiter middleware for health check handler + if err := srv.Get(HealthCheckPath, srv.healthCheckHandler); err != nil { + return nil, err + } // build the http server - srv.httpServer = &http.Server{ + srv.Server = &http.Server{ Addr: fmt.Sprintf("%s:%d", cfg.Server, cfg.ServerPort), - Handler: srv.handler, + Handler: srv.Handler, } return srv, nil } @@ -105,19 +81,21 @@ func New(ctx context.Context, cfg *Config, nq notification.Queue) (*Service, err // Start method starts the service by starting the http server. func (s *Service) Start() error { // start the api server - if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed { return err } return nil } // Stop method stops the service. It cancels the context and waits for the -// background processes to finish. It also closes the http server and the -// demo mail server if it is running. -func (s *Service) Stop() { +// background processes to finish. It also closes the http server. +func (s *Service) Stop() error { // cancel the context and wait for the background processes finish s.cancel() - defer s.wait.Wait() + if err := s.Close(); err != nil { + return err + } + return nil } // Ping method checks if the service is up and running. It sends a GET request @@ -134,18 +112,8 @@ func (s *Service) Ping() bool { if err != nil { return false } + defer func() { + _ = response.Body.Close() + }() return response.StatusCode == http.StatusOK } - -// WaitToShutdown method waits for the service to shutdown. It listens for the -// interrupt signal and shutdown the http server and the service. If something -// goes wrong during the process, it returns an error. -func (s *Service) WaitToShutdown() error { - done := make(chan os.Signal, 1) - signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) - <-done - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - defer s.Stop() - return s.httpServer.Shutdown(ctx) -} diff --git a/api/service_test.go b/api/service_test.go index 4703a1e..4739c38 100644 --- a/api/service_test.go +++ b/api/service_test.go @@ -3,20 +3,28 @@ package api import ( "context" "fmt" + "log" + "net" "os" "testing" "time" - "github.com/simpleauthlink/authapi/internal/fakesmtpserver" + "github.com/simpleauthlink/authapi/notification" "github.com/simpleauthlink/authapi/notification/email" + xnet "go.k7z7z.cc/x/net" + "go.k7z7z.cc/x/net/smtp/testsmtp" +) + +var ( + testServerSMTPPort int + testServerAPIPort int + testServerAPIURL string + inboxChan = make(chan string, 1) ) const ( testServerAddr = "127.0.0.1" - testServerSMTPPort = 2526 - testServerAPIPort = 5555 testServerSecret = "server-secret" - testSenderName = "TestAPI" testSender = "api-test@testmail.com" testUserEmail = "user@testmail.com" testAppName = "TestApp" @@ -25,33 +33,37 @@ const ( testAppSecret = "test-secret" ) -var ( - testServerApiURL = fmt.Sprintf("http://%s:%d", testServerAddr, testServerAPIPort) - inboxChan = make(chan string, 1) -) - func TestMain(m *testing.M) { + var err error + testServerSMTPPort, err = xnet.SafeTestPort() + if err != nil { + log.Fatal(err) + } + testServerAPIPort, err = xnet.SafeTestPort() + if err != nil { + log.Fatal(err) + } + testServerAPIURL = fmt.Sprintf("http://%s:%d", testServerAddr, testServerAPIPort) defer close(inboxChan) // create context with cancel ctx, cancel := context.WithCancel(context.Background()) defer cancel() // start test SMTP server to receive the email - testSrv := fakesmtpserver.NewServer(testServerAddr, testServerSMTPPort, inboxChan) + testSrv := testsmtp.NewServer(testServerAddr, testServerSMTPPort, inboxChan) if err := testSrv.Start(ctx); err != nil { - panic(err) + log.Fatal(err) } defer testSrv.Stop() // create email queue with valid config - eq, err := email.NewEmailQueue(ctx, &email.EmailConfig{ + eq, err := notification.NewQueue(ctx, 10, &email.EmailConfig{ SMTPServer: testServerAddr, SMTPPort: testServerSMTPPort, - FromName: testSenderName, FromAddress: testSender, }) if err != nil { - panic(err) + log.Fatal(err) } - eq.Start() + eq.Start(1) defer eq.Stop() // create the API service apiSrv, err := New(ctx, &Config{ @@ -60,19 +72,23 @@ func TestMain(m *testing.M) { Secret: testServerSecret, }, eq) if err != nil { - panic(err) + log.Fatal(err) } go func() { if err := apiSrv.Start(); err != nil { - panic(err) + log.Fatal(err) + } + }() + defer func() { + if err := apiSrv.Stop(); err != nil { + log.Fatal(err) } }() - defer apiSrv.Stop() // make ping to the server to check if it is running nRetries := 5 for { if nRetries == 0 { - panic("API server is not running") + log.Fatal("API server is not running") } if ok := apiSrv.Ping(); ok { break @@ -83,3 +99,83 @@ func TestMain(m *testing.M) { // run the tests os.Exit(m.Run()) } + +func TestStartError(t *testing.T) { + port, err := xnet.SafeTestPort() + if err != nil { + t.Fatal(err) + } + // Block the port so ListenAndServe fails + l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = l.Close() }() + + eq, err := notification.NewQueue(t.Context(), 10) + if err != nil { + t.Fatal(err) + } + + srv, err := New(t.Context(), &Config{ + Server: testServerAddr, + ServerPort: port, + Secret: testServerSecret, + }, eq) + if err != nil { + t.Fatal(err) + } + + err = srv.Start() + if err == nil { + t.Error("expected error when port is in use") + } +} + +func TestServiceStop(t *testing.T) { + tempServerAPIPort, err := xnet.SafeTestPort() + if err != nil { + t.Fatal(err) + } + tempServerSMTPPort, err := xnet.SafeTestPort() + if err != nil { + t.Fatal(err) + } + // create email queue with valid config + eq, err := notification.NewQueue(t.Context(), 10, &email.EmailConfig{ + SMTPServer: testServerAddr, + SMTPPort: tempServerSMTPPort, + FromAddress: testSender, + }) + if err != nil { + log.Fatal(err) + } + eq.Start(1) + defer eq.Stop() + // create the API service + tempSrv, err := New(t.Context(), &Config{ + Server: testServerAddr, + ServerPort: tempServerAPIPort, + Secret: testServerSecret, + }, eq) + if err != nil { + log.Fatal(err) + } + go func() { + if err := tempSrv.Start(); err != nil { + log.Fatal(err) + } + }() + // verify server is up + if !tempSrv.Ping() { + t.Error("server should be reachable after start") + } + + if err := tempSrv.Stop(); err != nil { + t.Fatalf("stop returned error: %v", err) + } + // verify server is down + if tempSrv.Ping() { + t.Error("server should not be reachable after stop") + } +} diff --git a/api/types.go b/api/types.go index 4daaebd..31dfce7 100644 --- a/api/types.go +++ b/api/types.go @@ -1,6 +1,7 @@ package api import ( + "net/mail" "time" "github.com/simpleauthlink/authapi/token" @@ -13,16 +14,19 @@ type AppIDRequest struct { Secret string `json:"secret"` } -func (data *AppIDRequest) parseApp() (*token.App, string) { - if duration, err := time.ParseDuration(data.Duration); err == nil { - app := &token.App{ - Name: data.Name, - RedirectURI: data.RedirectURL, - SessionDuration: duration, - } - return app, data.Secret +func (data *AppIDRequest) parseApp(secret string) (*token.App, error) { + duration, err := time.ParseDuration(data.Duration) + if err != nil { + return nil, err } - return new(token.App), "" + app := &token.App{ + Name: data.Name, + RedirectURI: data.RedirectURL, + SessionDuration: duration, + } + finalSecret := new(token.Secret).SetParts([]byte(secret), []byte(data.Secret)) + app.SetSecret(finalSecret) + return app, nil } type AppIDResponse struct { @@ -33,6 +37,11 @@ type TokenRequest struct { Email string `json:"email"` } +func (tr *TokenRequest) IsEmail() bool { + _, err := mail.ParseAddress(tr.Email) + return err == nil +} + type TokenStatusRequest struct { Token string `json:"token"` Email string `json:"email"` diff --git a/cmd/authapi/main.go b/cmd/authapi/main.go index e487ef9..838d6bc 100644 --- a/cmd/authapi/main.go +++ b/cmd/authapi/main.go @@ -2,83 +2,85 @@ package main import ( "context" - "fmt" - "log" + "os" "github.com/simpleauthlink/authapi/api" - "github.com/simpleauthlink/authapi/cmd" - "github.com/simpleauthlink/authapi/internal/osflag" + "github.com/simpleauthlink/authapi/notification" "github.com/simpleauthlink/authapi/notification/email" + "go.k7z7z.cc/x/flag" + "go.k7z7z.cc/x/log" + "go.k7z7z.cc/x/proc" ) -type config struct { - host string - port int - emailAddr string - emailUser string - emailPass string - emailHost string - emailPort int - secret string -} - -func (c *config) String() string { - return fmt.Sprintf(`{"server": "%s:%d", "smtpServer": "%s:%d", "smtpAuth": "%s:%s", "secret": "%s"}`, - c.host, c.port, c.emailHost, c.emailPort, c.emailAddr, c.emailPass, c.secret) +type Config struct { + email.EmailConfig + APIHost string `env:"HOST" flag:"host" sflag:"h" usage:"service host"` + APIPort int `env:"PORT" flag:"port" sflag:"p" usage:"service port"` + Secret string `env:"SECRET" flag:"secret" sflag:"s" usage:"secret used to generate the tokens"` + NotificationQueueSize int `env:"NOTIFICATION_QUEUE_SIZE" flag:"queue-size" usage:"size of the notification queue"` + NotificationQueueWorkers int `env:"NOTIFICATION_QUEUE_WORKERS" flag:"queue-workers" usage:"number of workers of the notification queue"` } func main() { - log.SetFlags(log.LstdFlags | log.Lshortfile) - c := new(config) - // get config from flags - osflag.StringVar(&c.host, cmd.HostEnv, cmd.HostFlag, cmd.DefaultHost, cmd.HostFlagDesc, false) - osflag.IntVar(&c.port, cmd.PortEnv, cmd.PortFlag, cmd.DefaultPort, cmd.HostFlagDesc, false) - osflag.StringVar(&c.emailAddr, cmd.EmailAddrEnv, cmd.EmailAddrFlag, cmd.DefaultEmailAddr, cmd.EmailAddrFlagDesc, true) - osflag.StringVar(&c.emailUser, cmd.EmailUserEnv, cmd.EmailUserFlag, cmd.DefaultEmailUser, cmd.EmailUserFlagDesc, true) - osflag.StringVar(&c.emailPass, cmd.EmailPassEnv, cmd.EmailPassFlag, cmd.DefaultEmailPass, cmd.EmailPassFlagDesc, true) - osflag.StringVar(&c.emailHost, cmd.EmailHostEnv, cmd.EmailHostFlag, cmd.DefaultEmailHost, cmd.EmailHostFlagDesc, true) - osflag.IntVar(&c.emailPort, cmd.EmailPortEnv, cmd.EmailPortFlag, cmd.DefaultEmailPort, cmd.EmailPortFlagDesc, false) - osflag.StringVar(&c.secret, cmd.SecretEnv, cmd.SecretFlag, cmd.DefaultSecret, cmd.SecretFlagDesc, true) - if err := osflag.Parse(nil); err != nil { - log.Fatalln("ERR: error parsing flags:", err) + log.SetLevel(log.DebugLevel) + c := &Config{ + APIHost: "0.0.0.0", + APIPort: 8080, + EmailConfig: email.EmailConfig{ + SMTPPort: 587, + }, + NotificationQueueSize: 1000, + NotificationQueueWorkers: 10, + } + envvars, err := proc.EnvvarsFromFile(".env") + if err != nil { + log.Errw("error loading env file", "err", err) + return } - if !osflag.Parsed() { - log.Fatalln("ERR: error parsing flags:", "flags not parsed") - osflag.PrintDefaults() + if err := proc.UnmarshalEnvvars(envvars, c); err != nil { + log.Errw("error processing envvars", "err", err) + return } - log.Println("INF: starting service with config:", c.String()) - // create email queue - emailQueue, err := email.NewEmailQueue(context.Background(), &email.EmailConfig{ - FromName: "SimpleAuthLink", - FromAddress: c.emailAddr, - SMTPUsername: c.emailUser, - SMTPPassword: c.emailPass, - SMTPServer: c.emailHost, - SMTPPort: c.emailPort, - }) + if err := flag.UnmarshalArgs(os.Args[1:], c); err != nil { + log.Errw("error loading flags", "err", err) + return + } + + log.Infow("starting service with config:", + "api-host", c.APIHost, + "api-port", c.APIPort, + "queue-size", c.NotificationQueueSize, + "queue-workers", c.NotificationQueueWorkers) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + // create notification queue + notificationQueue, err := notification.NewQueue(ctx, c.NotificationQueueSize, &c.EmailConfig) if err != nil { - log.Fatalln("WRN: something occurs during email queue creation:", err) + log.Errw("error creating notification queue", "err", err) + return } // start the email queue and defer to stop it - emailQueue.Start() - defer emailQueue.Stop() - // create the service - service, err := api.New(context.Background(), &api.Config{ - Server: c.host, - ServerPort: c.port, - Secret: c.secret, - }, emailQueue) + notificationQueue.Start(c.NotificationQueueWorkers) + defer notificationQueue.Stop() + // create the apiService + apiService, err := api.New(ctx, &api.Config{ + Server: c.APIHost, + ServerPort: c.APIPort, + Secret: c.Secret, + }, notificationQueue) if err != nil { - log.Fatalln("ERR: error creating service:", err) + log.Errw("error creating service", "err", err) + return } - // start the service in background - go func() { - if err := service.Start(); err != nil { - log.Fatalln("ERR: error running service:", err) - } - }() - // wait for the service to finish - if err := service.WaitToShutdown(); err != nil { - log.Fatalln("ERR: error waiting for service to finish:", err) + // start the service and wait for it to finish + if err = new(proc.Shutdown).WithInterrupt().WithRecovery().WithRun(func(ctx context.Context) error { + return apiService.Start() + }).WithCallback(func(_ context.Context) error { + return apiService.Stop() + }).Wait(ctx); err != nil { + log.Errw("error during shutdown", "err", err) + return } + log.Info("HTTP server stopped, exiting...") } diff --git a/cmd/consts.go b/cmd/consts.go deleted file mode 100644 index 0a5bb9e..0000000 --- a/cmd/consts.go +++ /dev/null @@ -1,38 +0,0 @@ -package cmd - -const ( - DefaultHost = "0.0.0.0" - DefaultPort = 8080 - DefaultEmailAddr = "" - DefaultEmailUser = "" - DefaultEmailPass = "" - DefaultEmailHost = "" - DefaultEmailPort = 587 - DefaultSecret = "simpleauthlink-secret" - - HostFlag = "host" - PortFlag = "port" - EmailAddrFlag = "email-addr" - EmailUserFlag = "email-user" - EmailPassFlag = "email-pass" - EmailHostFlag = "email-host" - EmailPortFlag = "email-port" - SecretFlag = "secret" - HostFlagDesc = "service host" - PortFlagDesc = "service port" - EmailAddrFlagDesc = "email account address" - EmailUserFlagDesc = "email account username" - EmailPassFlagDesc = "email account password" - EmailHostFlagDesc = "email server host" - EmailPortFlagDesc = "email server port" - SecretFlagDesc = "secret used to generate the tokens" - - HostEnv = "HOST" - PortEnv = "PORT" - EmailAddrEnv = "EMAIL_ADDR" - EmailUserEnv = "EMAIL_USER" - EmailPassEnv = "EMAIL_PASS" - EmailHostEnv = "EMAIL_HOST" - EmailPortEnv = "EMAIL_PORT" - SecretEnv = "SECRET" -) diff --git a/cmd/demo/main.go b/cmd/demo/main.go index ea4a4aa..3f20329 100644 --- a/cmd/demo/main.go +++ b/cmd/demo/main.go @@ -2,62 +2,118 @@ package main import ( "context" - "log" + "fmt" + "net/http" + "os" "github.com/simpleauthlink/authapi/api" - "github.com/simpleauthlink/authapi/cmd" - "github.com/simpleauthlink/authapi/internal/osflag" + "github.com/simpleauthlink/authapi/notification" "github.com/simpleauthlink/authapi/notification/email" + "github.com/simpleauthlink/authapi/notification/email/templates/login" + "go.k7z7z.cc/x/flag" + "go.k7z7z.cc/x/log" + "go.k7z7z.cc/x/net/http/io" + "go.k7z7z.cc/x/net/smtp/testsmtp" + "go.k7z7z.cc/x/proc" ) +type DemoConfig struct { + APIHost string `env:"HOST" flag:"host" sflag:"h" usage:"service host"` + APIPort int `env:"PORT" flag:"port" sflag:"p" usage:"service port"` + Secret string `env:"SECRET" flag:"secret" sflag:"s" usage:"secret used to generate the tokens"` +} + +var demoMailInbox = make(chan string, 1) + func main() { - var ( - demoServer string - demoPort int - demoSecret string - ) - osflag.StringVar(&demoServer, cmd.HostEnv, cmd.HostFlag, cmd.DefaultHost, cmd.HostFlagDesc, false) - osflag.IntVar(&demoPort, cmd.PortEnv, cmd.PortFlag, cmd.DefaultPort, cmd.PortFlagDesc, false) - osflag.StringVar(&demoSecret, cmd.SecretEnv, cmd.SecretFlag, cmd.DefaultSecret, cmd.SecretFlagDesc, false) - if err := osflag.Parse(nil); err != nil { - log.Fatalln("ERR: error parsing flags:", err) - } - log.Println("INF: starting service with config:", demoServer, demoPort, demoSecret) + log.SetLevel(log.DebugLevel) + c := &DemoConfig{ + APIHost: "0.0.0.0", + APIPort: 8080, + Secret: "demo-service", + } + if err := flag.UnmarshalArgs(os.Args[1:], c); err != nil { + log.Errw("error parsing flags", "err", err) + return + } + log.Infow("config loaded", "config", c) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - // create the email queue - emailQueue, err := email.NewEmailQueue(context.Background(), &email.EmailConfig{ - FromName: "SimpleAuthLink Demo", + demoMailServer := testsmtp.NewServer(c.APIHost, 2525, demoMailInbox) + if err := demoMailServer.Start(ctx); err != nil { + log.Errw("error starting test smtp server", "err", err) + return + } + emailConfig := &email.EmailConfig{ FromAddress: "demo@simpleauth.link", - SMTPServer: demoServer, + SMTPServer: c.APIHost, SMTPPort: 2525, - }) + } + // create the email queue + notificationQueue, err := notification.NewQueue(ctx, 10, emailConfig) if err != nil { - log.Fatalln("WRN: something occurs during email queue creation:", err) + log.Errw("error initializing notification queue", "err", err) + return } // start the email queue and defer to stop it - emailQueue.Start() - defer emailQueue.Stop() - // create the service - service, err := api.New(ctx, &api.Config{ - Server: demoServer, - ServerPort: demoPort, - Secret: demoSecret, - DemoMode: true, - DemoSMTPAddr: demoServer, - DemoSMTPPort: 2525, - }, emailQueue) + notificationQueue.Start(5) + defer notificationQueue.Stop() + // create the apiService + apiService, err := api.New(ctx, &api.Config{ + Server: c.APIHost, + ServerPort: c.APIPort, + Secret: c.Secret, + }, notificationQueue) if err != nil { - log.Fatalln("ERR: error creating service:", err) + log.Errw("error creating api service", "err", err) + return + } + if err := apiService.Get("/demo/inbox", demoInboxHandler); err != nil { + log.Errw("error adding new handler for inbox", "err", err) + return + } + // start the service and wait for it to finish + if err = new(proc.Shutdown).WithInterrupt().WithRecovery().WithRun(func(ctx context.Context) error { + return apiService.Start() + }).WithCallback(func(_ context.Context) error { + return apiService.Stop() + }).Wait(ctx); err != nil { + log.Errw("error during shutdown", "err", err) + return + } + log.Info("HTTP server stopped, exiting...") +} + +func demoInboxHandler(w http.ResponseWriter, r *http.Request) { + // get the email from get parameters + email := r.URL.Query().Get("email") + if email == "" { + io.NewAPIError(400001, http.StatusBadRequest).Write(w) + return } - // start the service in background - go func() { - if err := service.Start(); err != nil { - log.Fatalln("ERR: error running service:", err) + // set http headers required for SSE + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + // create a channel for client disconnection + clientGone := r.Context().Done() + // create a response controller + rc := http.NewResponseController(w) + for { + select { + case <-clientGone: + return + case msg := <-demoMailInbox: + // find the token in the email + if testToken := login.FindToken(email, msg); testToken != nil { + // send an event to the client with the token in the "data" field + if _, err := fmt.Fprintf(w, "data: %s\n\n", testToken); err != nil { + return + } + if err := rc.Flush(); err != nil { + return + } + } } - }() - // wait for the service to finish - if err := service.WaitToShutdown(); err != nil { - log.Fatalln("ERR: error waiting for service to finish:", err) } } diff --git a/docker/Dockerfile.demo b/docker/Dockerfile.demo index 38694fb..dc0eb0f 100644 --- a/docker/Dockerfile.demo +++ b/docker/Dockerfile.demo @@ -1,5 +1,5 @@ # build -FROM golang:1.24-alpine as builder +FROM golang:1.26-alpine as builder WORKDIR /app/data COPY . . diff --git a/docker/Dockerfile.prod b/docker/Dockerfile.prod index dc43de2..d139ed6 100644 --- a/docker/Dockerfile.prod +++ b/docker/Dockerfile.prod @@ -1,5 +1,5 @@ # build -FROM golang:1.24-alpine as builder +FROM golang:1.26-alpine as builder WORKDIR /app/data COPY . . diff --git a/example.env b/example.env index b2e07b8..59ff4e2 100644 --- a/example.env +++ b/example.env @@ -5,4 +5,6 @@ EMAIL_USER="test@test.com" EMAIL_PASS="smtp_server_password" EMAIL_HOST="smtp.example.com" EMAIL_PORT=587 -SECRET="my_backend_secret" \ No newline at end of file +SECRET="my_backend_secret" +NOTIFICATION_QUEUE_SIZE=1000 +NOTIFICATION_QUEUE_WORKERS=10 \ No newline at end of file diff --git a/go.mod b/go.mod index b825496..4e1ecc7 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,5 @@ module github.com/simpleauthlink/authapi -go 1.24 +go 1.26.1 -require github.com/lucasmenendez/apihandler v0.0.9 +require go.k7z7z.cc/x v0.0.8 diff --git a/go.sum b/go.sum index aec883f..e681ec5 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,2 @@ -github.com/lucasmenendez/apihandler v0.0.9 h1:zn/e5Sszi+GFLXNxUONm21M5uq1Fg/9cDN0BoVCvK8A= -github.com/lucasmenendez/apihandler v0.0.9/go.mod h1:YZdczL55/HFLSgM4PrEsl+ynxiPXDBeGpagK31Tpe8Q= +go.k7z7z.cc/x v0.0.8 h1:UfonSVEff5JE+quwFzqJzRPsLNj8PI/WiZOEWTeYCoQ= +go.k7z7z.cc/x v0.0.8/go.mod h1:agkBp0/4U76/06tbzZospy6BumxGq34z0URyolRWMLg= diff --git a/internal/base64url/base64url.go b/internal/base64url/base64url.go deleted file mode 100644 index 9d0468d..0000000 --- a/internal/base64url/base64url.go +++ /dev/null @@ -1,36 +0,0 @@ -// base64url package provides a way to encode and decode data using a modified -// base64 encoding scheme that is safe for URLs. -package base64url - -import ( - "bytes" - "encoding/base64" -) - -// RawEncode function encodes the input byte slice into a base64 URL-safe -// encoded byte slice. It encodes the input using the raw standard base64 -// encoding and then replaces the URL-unsafe characters. -func RawEncode(src []byte) []byte { - rawBase64 := make([]byte, base64.RawStdEncoding.EncodedLen(len(src))) - base64.RawStdEncoding.Encode(rawBase64, src) - // replace the characters that are not URL safe (+, /) - rawBase64 = bytes.ReplaceAll(rawBase64, []byte("+"), []byte("-")) - rawBase64 = bytes.ReplaceAll(rawBase64, []byte("/"), []byte("_")) - return rawBase64 -} - -// RawDecode function decodes the input byte slice from a base64 URL-safe -// encoded byte slice. It replaces the URL-unsafe characters with their -// standard base64 counterparts and then decodes the result using the raw -// standard base64 decoding. -func RawDecode(data []byte) ([]byte, error) { - // recover the characters that are not URL safe (+, /) - rawBase64 := bytes.ReplaceAll(data, []byte("-"), []byte("+")) - rawBase64 = bytes.ReplaceAll(rawBase64, []byte("_"), []byte("/")) - // return the decoded string from basic base64 - res := make([]byte, base64.RawStdEncoding.DecodedLen(len(data))) - if _, err := base64.RawStdEncoding.Decode(res, rawBase64); err != nil { - return nil, err - } - return res, nil -} diff --git a/internal/base64url/base64url_test.go b/internal/base64url/base64url_test.go deleted file mode 100644 index 4dce4a8..0000000 --- a/internal/base64url/base64url_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package base64url - -import ( - "bytes" - "testing" -) - -func TestRawEncode(t *testing.T) { - inputs := [][]byte{ - // normal - []byte("Hello, World!"), - // some input that produce "+" - {0xFF, 0xFF, 0xFF}, - // some input that produce "/" - {0xFB, 0xEF, 0xBF}, - } - expectedOutputs := [][]byte{ - []byte("SGVsbG8sIFdvcmxkIQ"), - []byte("____"), - []byte("---_"), - } - for i, input := range inputs { - encoded := RawEncode(input) - if !bytes.Equal(encoded, expectedOutputs[i]) { - t.Errorf("Unexpected output for input %q: got %q, want %q", - input, encoded, expectedOutputs[i]) - } - } -} - -func TestRawDecode(t *testing.T) { - t.Run("success", func(t *testing.T) { - - inputs := [][]byte{ - // normal - []byte("SGVsbG8sIFdvcmxkIQ"), - // some input that produce "+" - []byte("____"), - // some input that produce "/" - []byte("---_"), - } - expectedOutputs := [][]byte{ - []byte("Hello, World!"), - {0xFF, 0xFF, 0xFF}, - {0xFB, 0xEF, 0xBF}, - } - for i, input := range inputs { - decoded, err := RawDecode(input) - if err != nil { - t.Errorf("Unexpected error for input %q: %v", - input, err) - continue - } - if !bytes.Equal(decoded, expectedOutputs[i]) { - t.Errorf("Unexpected output for input %q: got %q, want %q", - input, decoded, expectedOutputs[i]) - } - } - }) - t.Run("decode error", func(t *testing.T) { - invalidInputs := [][]byte{ - []byte("SGVsbG8sIFdvcmxkIQ==="), - } - for _, input := range invalidInputs { - decoded, err := RawDecode(input) - if err == nil { - t.Errorf("Expected error for input %q, got %q", - input, decoded) - } - } - }) -} - -func TestRawEncodeDecode(t *testing.T) { - inputs := [][]byte{ - // normal - []byte("Hello, World!"), - // some input that produce "+" - {0xFF, 0xFF, 0xFF}, - // some input that produce "/" - {0xFB, 0xEF, 0xBF}, - } - for _, input := range inputs { - encoded := RawEncode(input) - decoded, err := RawDecode(encoded) - if err != nil { - t.Errorf("Unexpected error for input %q: %v", - input, err) - continue - } - if !bytes.Equal(decoded, input) { - t.Errorf("Unexpected output for input %q: got %q, want %q", - input, decoded, input) - } - } -} diff --git a/internal/error.go b/internal/error.go deleted file mode 100644 index 852d61c..0000000 --- a/internal/error.go +++ /dev/null @@ -1,41 +0,0 @@ -package internal - -import "fmt" - -// Error represents an error with a message and a trace. It is a custom struct -// that can be used to wrap errors with additional information. -type Error struct { - msg string - trace error -} - -// NewErr creates a new Error instance with the given message. It is a helper -// function that simplifies the creation of Error instances in other packages. -func NewErr(msg string) *Error { - return &Error{msg: msg} -} - -// Error returns the error message. If the error has a trace, it is appended to -// the message. The error implements the error interface. -func (e *Error) Error() string { - err := fmt.Errorf("%s", e.msg) - if e.trace != nil { - err = fmt.Errorf("%s: %w", err, e.trace) - } - return err.Error() -} - -// With adds an error as a trace to the error. It is a helper function that -// simplifies the addition of traces to Error instances in other packages. -func (e *Error) With(err error) *Error { - e.trace = err - return e -} - -// Withf adds a formatted error message as a trace to the error. It is a helper -// function that simplifies the addition of formatted traces to Error instances -// in other packages. -func (e *Error) Withf(tmpl string, args ...any) *Error { - e.trace = fmt.Errorf(tmpl, args...) - return e -} diff --git a/internal/error_test.go b/internal/error_test.go deleted file mode 100644 index 6cb6e8d..0000000 --- a/internal/error_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package internal - -import ( - "errors" - "fmt" - "testing" -) - -func TestNewErr(t *testing.T) { - err := NewErr("test message") - if err.msg != "test message" { - t.Errorf("expected message 'test message', got '%s'", err.msg) - } - if err.trace != nil { - t.Errorf("expected nil trace, got '%v'", err.trace) - } -} - -func TestError(t *testing.T) { - err := NewErr("test message") - if err.Error() != "test message" { - t.Errorf("expected 'test message', got '%s'", err.Error()) - } - - wrappedErr := errors.New("wrapped error") - _ = err.With(wrappedErr) - expected := "test message: wrapped error" - if err.Error() != expected { - t.Errorf("expected '%s', got '%s'", expected, err.Error()) - } -} - -func TestWith(t *testing.T) { - err := NewErr("test message") - wrappedErr := errors.New("wrapped error") - _ = err.With(wrappedErr) - if err.trace != wrappedErr { - t.Errorf("expected trace '%v', got '%v'", wrappedErr, err.trace) - } -} - -func TestWithf(t *testing.T) { - err := NewErr("test message") - _ = err.Withf("formatted %s", "error") - expectedTrace := fmt.Errorf("formatted %s", "error").Error() - if err.trace.Error() != expectedTrace { - t.Errorf("expected trace '%s', got '%s'", expectedTrace, err.trace.Error()) - } -} diff --git a/internal/fakesmtpserver/server.go b/internal/fakesmtpserver/server.go deleted file mode 100644 index 2682fc9..0000000 --- a/internal/fakesmtpserver/server.go +++ /dev/null @@ -1,141 +0,0 @@ -package fakesmtpserver - -// fakesmtpserver package provides a simple SMTP server for testing purposes. -// It allows you to simulate an SMTP server that can receive emails and store -// them in a channel. This is useful for testing email sending functionality -// in applications without needing to set up a real SMTP server. The server -// can be started and stopped, and it handles basic SMTP commands like HELO, -// MAIL FROM, RCPT TO, and DATA. It also provides a way to retrieve the -// received emails from the inbox channel. - -import ( - "bufio" - "context" - "fmt" - "net" - "strings" - "sync" -) - -// FakeSMTPServer represents a simple SMTP testing server. -type FakeSMTPServer struct { - addr string - inbox chan string - listener net.Listener - mu sync.Mutex // Mutex to protect listener -} - -// NewServer creates a new FakeSMTPServer instance that listens on the given -// address and port and stores the received emails in the inbox channel -// provided. -func NewServer(addr string, port int, inbox chan string) *FakeSMTPServer { - return &FakeSMTPServer{ - addr: fmt.Sprintf("%s:%d", addr, port), - inbox: inbox, - } -} - -// Start method launches the test SMTP server. -func (s *FakeSMTPServer) Start(ctx context.Context) error { - var err error - s.mu.Lock() - s.listener, err = net.Listen("tcp", s.addr) - s.mu.Unlock() - if err != nil { - return err - } - go func() { - for { - select { - case <-ctx.Done(): - // use Stop to safely close the listener - s.Stop() - return - default: - // copy listener under lock - s.mu.Lock() - listener := s.listener - s.mu.Unlock() - if listener == nil { - return - } - conn, err := listener.Accept() - if err != nil { - continue - } - go s.handleConn(conn) - } - } - }() - return nil -} - -// Stop method shuts down the test SMTP server. -func (s *FakeSMTPServer) Stop() { - // copy listener under lock - s.mu.Lock() - listener := s.listener - // set listener to nil under lock and unlock - s.listener = nil - s.mu.Unlock() - // close the listener if it is not nil - if listener != nil { - _ = listener.Close() - } -} - -func (s *FakeSMTPServer) handleConn(conn net.Conn) { - defer func() { - _ = conn.Close() - }() - reader := bufio.NewReader(conn) - // send greeting - if _, err := fmt.Fprintf(conn, "220 Fake SMTP Service Ready\r\n"); err != nil { - return - } - var dataBuilder strings.Builder - inData := false - // read incoming data - for { - line, err := reader.ReadString('\n') - if err != nil { - return - } - line = strings.TrimRight(line, "\r\n") - // check if we are in the data section - if inData { - if line == "." { - inData = false - // send back a confirmation and store the data - if _, err := fmt.Fprintf(conn, "250 OK\r\n"); err != nil { - return - } - s.inbox <- dataBuilder.String() - dataBuilder.Reset() - continue - } - dataBuilder.WriteString(line + "\n") - continue - } - // simple command handling - switch { - case strings.HasPrefix(line, "HELO"), strings.HasPrefix(line, "EHLO"): - _, _ = fmt.Fprintf(conn, "250 Hello\r\n") - case strings.HasPrefix(line, "MAIL FROM:"): - _, _ = fmt.Fprintf(conn, "250 OK\r\n") - case strings.HasPrefix(line, "RCPT TO:"): - _, _ = fmt.Fprintf(conn, "250 OK\r\n") - case strings.HasPrefix(line, "DATA"): - // prepare to receive data - _, _ = fmt.Fprintf(conn, "354 End data with .\r\n") - inData = true - case strings.HasPrefix(line, "QUIT"): - // close the connection - _, _ = fmt.Fprintf(conn, "221 Bye\r\n") - return - default: - _, _ = fmt.Fprintf(conn, "250 OK\r\n") - } - - } -} diff --git a/internal/fakesmtpserver/server_test.go b/internal/fakesmtpserver/server_test.go deleted file mode 100644 index 5619369..0000000 --- a/internal/fakesmtpserver/server_test.go +++ /dev/null @@ -1,259 +0,0 @@ -package fakesmtpserver - -import ( - "bufio" - "context" - "net" - "strconv" - "strings" - "testing" - "time" -) - -func getFreePort() (string, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return "", err - } - defer func() { - _ = listener.Close() - }() - return listener.Addr().String(), nil -} - -func splitHostPort(address string) (string, int, error) { - host, portStr, err := net.SplitHostPort(address) - if err != nil { - return "", 0, err - } - port, err := strconv.Atoi(portStr) - if err != nil { - return "", 0, err - } - return host, port, nil -} - -func TestFakeSMTPServer(t *testing.T) { - inbox := make(chan string, 1) - address, err := getFreePort() - if err != nil { - t.Fatalf("Failed to get free port: %v", err) - } - host, port, err := splitHostPort(address) - if err != nil { - t.Fatalf("Failed to split host and port: %v", err) - } - server := NewServer(host, port, inbox) - ctx, cancel := context.WithCancel(t.Context()) // Fixed incorrect t.Context() - defer cancel() - - errChan := make(chan error, 1) // Channel to capture errors from the goroutine - - // Start the server - go func() { - if err := server.Start(ctx); err != nil { - errChan <- err // Send error to the channel - } - close(errChan) // Close the channel when done - }() - time.Sleep(100 * time.Millisecond) // Give the server time to start - - // Check for errors from the goroutine - select { - case err := <-errChan: - if err != nil { - t.Fatalf("Failed to start server: %v", err) - } - default: - // No error, continue with the test - } - - // Connect to the server and send an email - conn, err := net.Dial("tcp", address) - if err != nil { - t.Fatalf("Failed to connect to server: %v", err) - } - defer func() { - _ = conn.Close() - }() - - reader := bufio.NewReader(conn) - writer := bufio.NewWriter(conn) - - // Read greeting - if greeting, _ := reader.ReadString('\n'); !strings.HasPrefix(greeting, "220") { - t.Fatalf("Expected greeting, got: %s", greeting) - } - - // Send HELO - if _, err := writer.WriteString("HELO localhost\r\n"); err != nil { - t.Fatalf("Failed to write HELO command: %v", err) - } - if err := writer.Flush(); err != nil { - t.Fatalf("Failed to flush writer: %v", err) - } - if response, _ := reader.ReadString('\n'); !strings.HasPrefix(response, "250") { - t.Fatalf("Expected HELO response, got: %s", response) - } - - // Send MAIL FROM - if _, err := writer.WriteString("MAIL FROM:\r\n"); err != nil { - t.Fatalf("Failed to write MAIL FROM command: %v", err) - } - if err := writer.Flush(); err != nil { - t.Fatalf("Failed to flush writer: %v", err) - } - if response, _ := reader.ReadString('\n'); !strings.HasPrefix(response, "250") { - t.Fatalf("Expected MAIL FROM response, got: %s", response) - } - - // Send RCPT TO - if _, err := writer.WriteString("RCPT TO:\r\n"); err != nil { - t.Fatalf("Failed to write RCPT TO command: %v", err) - } - if err := writer.Flush(); err != nil { - t.Fatalf("Failed to flush writer: %v", err) - } - if response, _ := reader.ReadString('\n'); !strings.HasPrefix(response, "250") { - t.Fatalf("Expected RCPT TO response, got: %s", response) - } - - // Send DATA - if _, err := writer.WriteString("DATA\r\n"); err != nil { - t.Fatalf("Failed to write DATA command: %v", err) - } - if err := writer.Flush(); err != nil { - t.Fatalf("Failed to flush writer: %v", err) - } - if response, _ := reader.ReadString('\n'); !strings.HasPrefix(response, "354") { - t.Fatalf("Expected DATA response, got: %s", response) - } - - // Send email content - if _, err := writer.WriteString("Subject: Test Email\r\n\r\nThis is a test email.\r\n.\r\n"); err != nil { - t.Fatalf("Failed to write email content: %v", err) - } - if err := writer.Flush(); err != nil { - t.Fatalf("Failed to flush writer: %v", err) - } - if response, _ := reader.ReadString('\n'); !strings.HasPrefix(response, "250") { - t.Fatalf("Expected email content response, got: %s", response) - } - - // Send QUIT - if _, err := writer.WriteString("QUIT\r\n"); err != nil { - t.Fatalf("Failed to write QUIT command: %v", err) - } - if err := writer.Flush(); err != nil { - t.Fatalf("Failed to flush writer: %v", err) - } - if response, _ := reader.ReadString('\n'); !strings.HasPrefix(response, "221") { - t.Fatalf("Expected QUIT response, got: %s", response) - } - - // Verify email content in inbox - select { - case email := <-inbox: - if !strings.Contains(email, "Subject: Test Email") || !strings.Contains(email, "This is a test email.") { - t.Fatalf("Unexpected email content: %s", email) - } - case <-time.After(1 * time.Second): - t.Fatal("Timeout waiting for email in inbox") - } - - // Stop the server - server.Stop() -} - -func TestFakeSMTPServer_UnsupportedCommand(t *testing.T) { - inbox := make(chan string, 1) - address, err := getFreePort() - if err != nil { - t.Fatalf("Failed to get free port: %v", err) - } - host, port, err := splitHostPort(address) - if err != nil { - t.Fatalf("Failed to split host and port: %v", err) - } - server := NewServer(host, port, inbox) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - errChan := make(chan error, 1) - - // Start the server - go func() { - if err := server.Start(ctx); err != nil { - errChan <- err - } - close(errChan) - }() - time.Sleep(100 * time.Millisecond) - - // Check for errors from the goroutine - select { - case err := <-errChan: - if err != nil { - t.Fatalf("Failed to start server: %v", err) - } - default: - } - - // Connect to the server and send an unsupported command - conn, err := net.Dial("tcp", address) - if err != nil { - t.Fatalf("Failed to connect to server: %v", err) - } - defer func() { - _ = conn.Close() - }() - - reader := bufio.NewReader(conn) - writer := bufio.NewWriter(conn) - - // Read greeting - if greeting, _ := reader.ReadString('\n'); !strings.HasPrefix(greeting, "220") { - t.Fatalf("Expected greeting, got: %s", greeting) - } - - // Send unsupported command - if _, err := writer.WriteString("FOO BAR\r\n"); err != nil { - t.Fatalf("Failed to write unsupported command: %v", err) - } - if err := writer.Flush(); err != nil { - t.Fatalf("Failed to flush writer: %v", err) - } - if response, _ := reader.ReadString('\n'); !strings.HasPrefix(response, "250") { - t.Fatalf("Expected default response, got: %s", response) - } - - // Stop the server - server.Stop() -} - -func TestFakeSMTPServer_BadAddress(t *testing.T) { - inbox := make(chan string, 1) - server := NewServer("invalid-address", 2527, inbox) // Added a dummy port - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - - errChan := make(chan error, 1) - - // Start the server - go func() { - if err := server.Start(ctx); err != nil { - errChan <- err - } - close(errChan) - }() - time.Sleep(100 * time.Millisecond) - - // Check for errors from the goroutine - select { - case err := <-errChan: - if err == nil { - t.Fatalf("Expected error starting server with bad address, got nil") - } - default: - } -} diff --git a/internal/osflag/osflag.go b/internal/osflag/osflag.go deleted file mode 100644 index 17decd6..0000000 --- a/internal/osflag/osflag.go +++ /dev/null @@ -1,254 +0,0 @@ -package osflag - -// osflag package provides a way to manage command line flags and environment -// variables in Go applications. It allows for the creation of command line -// flags that can also be overwritten by environment variables. By default it -// loads a `.env` file, but this can be overridden by passing an `WithEnvFile` -// option to the `Parse` method. It also checks for required flags and ensures -// that they are set before parsing the command line arguments. - -import ( - "bufio" - "flag" - "fmt" - "os" - "strings" - "time" -) - -// Options is a struct that holds options for the Parse method. -type Options struct { - envFile string -} - -// WithEnvFile function creates an Options instance with the specified -// envFile path. If the path is empty, it returns nil. This function is used -// to specify a custom env file path when calling the Parse method. -func WithEnvFile(path string) *Options { - if path == "" { - return nil - } - return &Options{envFile: path} -} - -// osflag is a struct that holds the name, environment variable, and -// required mark of a flag. It is used to manage command line flags -// and their corresponding environment variables. -type osflag struct { - name string - env string - required bool -} - -// OsFlagSet is a struct that embeds flag.FlagSet and adds support for env -// variables. It allows for the creation of command line flags that can also -// be overwritten by environment variables. By default it loads `.env` file, -// but this can be overridden by passing an WithEnvFile option to the Parse -// method. It also checks for required flags and ensures that they are set -// before parsing the command line arguments. -type OsFlagSet struct { - *flag.FlagSet - flags map[string]osflag - parsed bool -} - -// CommandLine is the default OsFlagSet instance. -var CommandLine *OsFlagSet - -// init initializes the CommandLine variable with a new OsFlagSet instance. -func init() { - CommandLine = new(OsFlagSet) - if len(os.Args) == 0 { - CommandLine.FlagSet = flag.NewFlagSet("", flag.ExitOnError) - } else { - CommandLine.FlagSet = flag.NewFlagSet(os.Args[0], flag.ExitOnError) - } - CommandLine.flags = make(map[string]osflag) -} - -// BoolVar method registers a boolean flag with the given name, env variable, -// default value, usage string, and required mark. -func (of *OsFlagSet) BoolVar(p *bool, env, name string, value bool, usage string, required bool) { - of.flags[name] = osflag{name, env, required} - of.FlagSet.BoolVar(p, name, value, usage) -} - -// DurationVar method registers a duration flag with the given name, env -// variable, default value, usage string, and required mark. -func (of *OsFlagSet) DurationVar(p *time.Duration, env, name string, value time.Duration, usage string, required bool) { - of.flags[name] = osflag{name, env, required} - of.FlagSet.DurationVar(p, name, value, usage) -} - -// Float64Var method registers a float64 flag with the given name, env variable, -// default value, usage string, and required mark. -func (of *OsFlagSet) Float64Var(p *float64, env, name string, value float64, usage string, required bool) { - of.flags[name] = osflag{name, env, required} - of.FlagSet.Float64Var(p, name, value, usage) -} - -// IntVar method registers an int flag with the given name, env variable, -// default value, usage string, and required mark. -func (of *OsFlagSet) IntVar(p *int, env, name string, value int, usage string, required bool) { - of.flags[name] = osflag{name, env, required} - of.FlagSet.IntVar(p, name, value, usage) -} - -// StringVar method registers a string flag with the given name, env variable, -// default value, usage string, and required mark. -func (of *OsFlagSet) StringVar(p *string, env, name string, value string, usage string, required bool) { - of.flags[name] = osflag{name, env, required} - of.FlagSet.StringVar(p, name, value, usage) -} - -// UintVar method registers a uint flag with the given name, env variable, -// default value, usage string, and required mark. -func (of *OsFlagSet) UintVar(p *uint, env, name string, value uint, usage string, required bool) { - of.flags[name] = osflag{name, env, required} - of.FlagSet.UintVar(p, name, value, usage) -} - -// Parse method parses the command line arguments and loads the environment -// variables from the specified env file. It checks if all required flags are -// set and it overwrites the command line flags with the values from the env -// variables if they are set. It returns an error if any required flags are -// not set or if there is an error loading the env file. -func (of *OsFlagSet) Parse(opts *Options) error { - if err := of.FlagSet.Parse(os.Args[1:]); err != nil { - return err - } - // load the env file - envFile := ".env" - if opts != nil && opts.envFile != "" { - envFile = opts.envFile - } - if err := loadEnv(envFile); err != nil { - return fmt.Errorf("failed to load env file: %w", err) - } - // check if all required flags are set - for name, osf := range of.flags { - if envValue := os.Getenv(osf.env); envValue != "" { - if err := of.Set(name, envValue); err != nil { - return fmt.Errorf("failed to set flag %s from env: %w", name, err) - } - } - // check if the flag is required and not set - if osf.required { - f := of.Lookup(name) - if f == nil || f.Value.String() == "" { - return fmt.Errorf("required flag %s is not set", name) - } - } - } - of.parsed = of.FlagSet.Parsed() - return nil -} - -// Parsed method returns true if the command line arguments have been parsed. -func (of *OsFlagSet) Parsed() bool { - return of.parsed -} - -// PrintDefaults method prints the default values of all flags. -func (of *OsFlagSet) PrintDefaults() { - of.FlagSet.PrintDefaults() -} - -// BoolVar method registers a boolean flag with the given name, env variable, -// default value, usage string, and required mark. -func BoolVar(p *bool, env, name string, value bool, usage string, required bool) { - CommandLine.BoolVar(p, env, name, value, usage, required) -} - -// DurationVar method registers a duration flag with the given name, env -// variable, default value, usage string, and required mark. -func DurationVar(p *time.Duration, env, name string, value time.Duration, usage string, required bool) { - CommandLine.DurationVar(p, env, name, value, usage, required) -} - -// Float64Var method registers a float64 flag with the given name, env variable, -// default value, usage string, and required mark. -func Float64Var(p *float64, env, name string, value float64, usage string, required bool) { - CommandLine.Float64Var(p, env, name, value, usage, required) -} - -// IntVar method registers an int flag with the given name, env variable, -// default value, usage string, and required mark. -func IntVar(p *int, env, name string, value int, usage string, required bool) { - CommandLine.IntVar(p, env, name, value, usage, required) -} - -// StringVar method registers a string flag with the given name, env variable, -// default value, usage string, and required mark. -func StringVar(p *string, env, name string, value string, usage string, required bool) { - CommandLine.StringVar(p, env, name, value, usage, required) -} - -// UintVar method registers a uint flag with the given name, env variable, -// default value, usage string, and required mark. -func UintVar(p *uint, env, name string, value uint, usage string, required bool) { - CommandLine.UintVar(p, env, name, value, usage, required) -} - -// Parse method parses the command line arguments and loads the environment -// variables from the specified env file. It checks if all required flags are -// set and it overwrites the command line flags with the values from the env -// variables if they are set. It returns an error if any required flags are -// not set or if there is an error loading the env file. -func Parse(opts *Options) error { - return CommandLine.Parse(opts) -} - -// Parsed method returns true if the command line arguments have been parsed. -func Parsed() bool { - return CommandLine.parsed -} - -// PrintDefaults method prints the default values of all flags. -func PrintDefaults() { - CommandLine.PrintDefaults() -} - -// loadEnv function loads environment variables from a file. If the file does -// not exist, it returns nil and does not raise an error. It reads the file -// line by line, ignoring empty lines and comments. It sets the environment -// variables in the current process using os.Setenv. It removes any "export " -// prefix and surrounding quotes from the variable assignments. It returns -// an error if there is an issue opening or reading the file (different from -// the file not existing). -func loadEnv(path string) error { - envFile, err := os.Open(path) - if err != nil { - // if the file does not exist, return nil - if os.IsNotExist(err) { - return nil - } - return fmt.Errorf("failed to open env file: %w", err) - } - defer func() { - _ = envFile.Close() - }() - // create a line scanner - scanner := bufio.NewScanner(envFile) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if line == "" || strings.HasPrefix(line, "#") { - continue // skip empty lines and comments - } - // remove "export " prefix if present - line = strings.TrimPrefix(line, "export ") - // split on the first '=' character - parts := strings.SplitN(line, "=", 2) - if len(parts) != 2 { - continue // or return an error if preferred - } - key := strings.TrimSpace(parts[0]) - value := strings.TrimSpace(parts[1]) - value = strings.Trim(value, "\"'") // remove surrounding quotes - // set var in the current env - if err := os.Setenv(key, value); err != nil { - return fmt.Errorf("failed to set env variable %q: %w", key, err) - } - } - return nil -} diff --git a/internal/osflag/osflag_test.go b/internal/osflag/osflag_test.go deleted file mode 100644 index 05d6aa3..0000000 --- a/internal/osflag/osflag_test.go +++ /dev/null @@ -1,186 +0,0 @@ -package osflag - -import ( - "flag" - "os" - "testing" - "time" -) - -func resetCommandLine() { - CommandLine = new(OsFlagSet) - CommandLine.FlagSet = flag.NewFlagSet("", flag.ExitOnError) - CommandLine.flags = make(map[string]osflag) - - // Filter out test framework flags - os.Args = os.Args[:1] -} - -func TestBoolVar(t *testing.T) { - resetCommandLine() - var flagValue bool - if err := os.Setenv("TEST_BOOL", "true"); err != nil { - t.Fatalf("Failed to set env variable: %v", err) - } - defer func() { - _ = os.Unsetenv("TEST_BOOL") - }() - - CommandLine.BoolVar(&flagValue, "TEST_BOOL", "boolFlag", false, "A boolean flag", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - - if !flagValue { - t.Errorf("Expected true, got %v", flagValue) - } -} - -func TestDurationVar(t *testing.T) { - resetCommandLine() - var flagValue time.Duration - if err := os.Setenv("TEST_DURATION", "5s"); err != nil { - t.Fatalf("Failed to set env variable: %v", err) - } - defer func() { - _ = os.Unsetenv("TEST_DURATION") - }() - - CommandLine.DurationVar(&flagValue, "TEST_DURATION", "durationFlag", 0, "A duration flag", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - - if flagValue != 5*time.Second { - t.Errorf("Expected 5s, got %v", flagValue) - } -} - -func TestFloat64Var(t *testing.T) { - resetCommandLine() - var flagValue float64 - if err := os.Setenv("TEST_FLOAT", "3.14"); err != nil { - t.Fatalf("Failed to set env variable: %v", err) - } - defer func() { - _ = os.Unsetenv("TEST_FLOAT") - }() - - CommandLine.Float64Var(&flagValue, "TEST_FLOAT", "floatFlag", 0.0, "A float flag", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - - if flagValue != 3.14 { - t.Errorf("Expected 3.14, got %v", flagValue) - } -} - -func TestIntVar(t *testing.T) { - resetCommandLine() - var flagValue int - if err := os.Setenv("TEST_INT", "42"); err != nil { - t.Fatalf("Failed to set env variable: %v", err) - } - defer func() { - _ = os.Unsetenv("TEST_INT") - }() - - CommandLine.IntVar(&flagValue, "TEST_INT", "intFlag", 0, "An int flag", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - - if flagValue != 42 { - t.Errorf("Expected 42, got %v", flagValue) - } -} - -func TestStringVar(t *testing.T) { - resetCommandLine() - var flagValue string - if err := os.Setenv("TEST_STRING", "hello"); err != nil { - t.Fatalf("Failed to set env variable: %v", err) - } - defer func() { - _ = os.Unsetenv("TEST_STRING") - }() - - CommandLine.StringVar(&flagValue, "TEST_STRING", "stringFlag", "default", "A string flag", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - - if flagValue != "hello" { - t.Errorf("Expected 'hello', got %v", flagValue) - } -} - -func TestUintVar(t *testing.T) { - resetCommandLine() - var flagValue uint - if err := os.Setenv("TEST_UINT", "100"); err != nil { - t.Fatalf("Failed to set env variable: %v", err) - } - defer func() { - _ = os.Unsetenv("TEST_UINT") - }() - - CommandLine.UintVar(&flagValue, "TEST_UINT", "uintFlag", 0, "A uint flag", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - - if flagValue != 100 { - t.Errorf("Expected 100, got %v", flagValue) - } -} - -func TestRequiredFlag(t *testing.T) { - resetCommandLine() - var flagValue string - CommandLine.StringVar(&flagValue, "", "requiredFlag", "", "A required flag", true) - - if err := CommandLine.Parse(nil); err == nil { - t.Errorf("Expected error for missing required flag, got nil") - } -} - -func TestDefaultValues(t *testing.T) { - resetCommandLine() - var flagValue string - CommandLine.StringVar(&flagValue, "", "defaultFlag", "defaultValue", "A flag with a default value", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - - if flagValue != "defaultValue" { - t.Errorf("Expected 'defaultValue', got %v", flagValue) - } -} - -func TestLoadEnv(t *testing.T) { - resetCommandLine() - // try to load a non-existing env file (should not error) - if err := loadEnv("non_existing.env"); err != nil { - t.Fatalf("Expected no error for non-existing env file, got: %v", err) - } - // create .env file - envFileContent := []byte("TEST_ENV=envValue") - envFilePath := ".env" - if err := os.WriteFile(envFilePath, envFileContent, 0o644); err != nil { - t.Fatalf("Failed to create env file: %v", err) - } - defer func() { - _ = os.Remove(envFilePath) - }() - // parse flags and check the value - var flagValue string - CommandLine.StringVar(&flagValue, "TEST_ENV", "envFlag", "defaultValue", "A flag with an env variable", false) - if err := CommandLine.Parse(nil); err != nil { - t.Fatalf("Failed to parse command line: %v", err) - } - if flagValue != "envValue" { - t.Errorf("Expected 'envValue', got %v", flagValue) - } -} diff --git a/notification/email/config.go b/notification/email/config.go new file mode 100644 index 0000000..c0e95e7 --- /dev/null +++ b/notification/email/config.go @@ -0,0 +1,43 @@ +package email + +import ( + "net/mail" + "strings" + + "github.com/simpleauthlink/authapi/notification" +) + +// defaultSendRetries is the default number of retries to send the email. +const defaultSendRetries = 3 + +// EmailConfig struct represents the email configuration that is needed to send +// an email using and SMTP server. It includes the email address (used as the +// sender address but also as the username for the SMTP server), the email +// server hostname, its port and the password. +type EmailConfig struct { + FromAddress string `env:"EMAIL_ADDR" flag:"email-addr" usage:"account address that will send the email notifications"` + SMTPUsername string `env:"EMAIL_USER" flag:"email-user" usage:"account username to get authorized into the SMTP server"` + SMTPPassword string `env:"EMAIL_PASS" flag:"email-pass" usage:"account password to get authorized into the SMTP server"` + SMTPServer string `env:"EMAIL_HOST" flag:"email-host" usage:"SMTP server host"` + SMTPPort int `env:"EMAIL_PORT" flag:"email-port" usage:"SMTP server port"` + Retries int +} + +// Valid method checks if the email configuration is valid. It returns true if +// the sender name, the SMTP server and its port are not empty, and the sender +// email address is valid. It also sets the number of retries to the default +// value if it is not set. +func (cfg *EmailConfig) Valid() bool { + if cfg.FromAddress == "" || cfg.SMTPServer == "" || cfg.SMTPPort == 0 { + return false + } + fromAddress := strings.TrimSpace(cfg.FromAddress) + fromAddress = strings.Trim(fromAddress, `"`) + _, err := mail.ParseAddress(fromAddress) + return err == nil +} + +func (cfg *EmailConfig) Support(n notification.Notification) bool { + _, ok := any(n).(*EmailNotification) + return ok +} diff --git a/notification/email/emailqueue_test.go b/notification/email/config_test.go similarity index 66% rename from notification/email/emailqueue_test.go rename to notification/email/config_test.go index 8c3ad2a..be547a7 100644 --- a/notification/email/emailqueue_test.go +++ b/notification/email/config_test.go @@ -2,18 +2,18 @@ package email import ( "context" + "os" "strings" "testing" "time" - "github.com/simpleauthlink/authapi/internal/fakesmtpserver" "github.com/simpleauthlink/authapi/notification" + xnet "go.k7z7z.cc/x/net" + "go.k7z7z.cc/x/net/smtp/testsmtp" ) const ( testServerAddr = "127.0.0.1" - testServerPort = 2525 - testSenderName = "Test Sender" testSender = "sender@testmail.com" testReceiver = "receiver@testmail.com" testSubject = "Test email" @@ -21,25 +21,32 @@ const ( testHTMLBody = "

This is a test email

" ) -var inboxChan = make(chan string, 1) +var ( + testServerPort int + inboxChan = make(chan string, 1) +) func TestMain(m *testing.M) { + var err error + if testServerPort, err = xnet.SafeTestPort(); err != nil { + panic(err) + } defer close(inboxChan) // create context with cancel ctx, cancel := context.WithCancel(context.Background()) defer cancel() // start test SMTP server to receive the email - testSrv := fakesmtpserver.NewServer(testServerAddr, testServerPort, inboxChan) + testSrv := testsmtp.NewServer(testServerAddr, testServerPort, inboxChan) if err := testSrv.Start(ctx); err != nil { panic(err) } defer testSrv.Stop() - m.Run() + os.Exit(m.Run()) } func TestValidEmail(t *testing.T) { - if !(¬ification.Notification{ - Params: notification.NotificationParams{ + if !(&EmailNotification{ + Params: EmailParams{ To: testReceiver, Subject: testSubject, }, @@ -48,8 +55,8 @@ func TestValidEmail(t *testing.T) { }).Valid() { t.Error("expected email to be valid") } - if !(¬ification.Notification{ - Params: notification.NotificationParams{ + if !(&EmailNotification{ + Params: EmailParams{ To: testReceiver, Subject: testSubject, }, @@ -58,8 +65,8 @@ func TestValidEmail(t *testing.T) { }).Valid() { t.Error("expected email to be valid") } - if (¬ification.Notification{ - Params: notification.NotificationParams{ + if (&EmailNotification{ + Params: EmailParams{ To: testReceiver, Subject: "", }, @@ -68,8 +75,8 @@ func TestValidEmail(t *testing.T) { }).Valid() { t.Error("expected email to be invalid") } - if (¬ification.Notification{ - Params: notification.NotificationParams{ + if (&EmailNotification{ + Params: EmailParams{ To: "", Subject: testSubject, }, @@ -78,8 +85,8 @@ func TestValidEmail(t *testing.T) { }).Valid() { t.Error("expected email to be invalid") } - if (¬ification.Notification{ - Params: notification.NotificationParams{ + if (&EmailNotification{ + Params: EmailParams{ To: "invalidEmail", Subject: testSubject, }, @@ -88,7 +95,7 @@ func TestValidEmail(t *testing.T) { }).Valid() { t.Error("expected email to be invalid") } - if (¬ification.Notification{}).Valid() { + if (&EmailNotification{}).Valid() { t.Error("expected email to be invalid") } } @@ -97,7 +104,6 @@ func TestValidConfig(t *testing.T) { if !(&EmailConfig{ SMTPServer: testServerAddr, SMTPPort: testServerPort, - FromName: testSenderName, FromAddress: testSender, }).Valid() { t.Error("expected config to be valid") @@ -105,7 +111,6 @@ func TestValidConfig(t *testing.T) { if (&EmailConfig{ SMTPServer: "", SMTPPort: testServerPort, - FromName: testSenderName, FromAddress: testSender, }).Valid() { t.Error("expected config to be invalid") @@ -113,7 +118,6 @@ func TestValidConfig(t *testing.T) { if (&EmailConfig{ SMTPServer: testServerAddr, SMTPPort: 0, - FromName: testSenderName, FromAddress: testSender, }).Valid() { t.Error("expected config to be invalid") @@ -121,15 +125,6 @@ func TestValidConfig(t *testing.T) { if (&EmailConfig{ SMTPServer: testServerAddr, SMTPPort: testServerPort, - FromName: "", - FromAddress: testSender, - }).Valid() { - t.Error("expected config to be invalid") - } - if (&EmailConfig{ - SMTPServer: testServerAddr, - SMTPPort: testServerPort, - FromName: testSenderName, FromAddress: "", }).Valid() { t.Error("expected config to be invalid") @@ -138,25 +133,9 @@ func TestValidConfig(t *testing.T) { func TestNewEmailQueue(t *testing.T) { // create email queue with valid config - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - eq, err := NewEmailQueue(ctx, &EmailConfig{ - SMTPServer: testServerAddr, - SMTPPort: testServerPort, - FromName: testSenderName, - FromAddress: testSender, - }) - if err != nil { - t.Fatal(err) - } - if eq == nil { - t.Error("expected email queue to be created") - } - // create email queue with auth - eq, err = NewEmailQueue(ctx, &EmailConfig{ + eq, err := notification.NewQueue(t.Context(), 10, &EmailConfig{ SMTPServer: testServerAddr, SMTPPort: testServerPort, - FromName: testSenderName, FromAddress: testSender, SMTPUsername: "username", SMTPPassword: "password", @@ -168,10 +147,9 @@ func TestNewEmailQueue(t *testing.T) { t.Error("expected email queue to be created") } // create email queue with invalid config - eq, err = NewEmailQueue(ctx, &EmailConfig{ + eq, err = notification.NewQueue(t.Context(), 10, &EmailConfig{ SMTPServer: "", SMTPPort: testServerPort, - FromName: testSenderName, FromAddress: testSender, }) if err == nil { @@ -184,26 +162,27 @@ func TestNewEmailQueue(t *testing.T) { func TestSendEmail(t *testing.T) { // create email queue but don't start it - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - eq, err := NewEmailQueue(ctx, &EmailConfig{ + config := &EmailConfig{ SMTPServer: testServerAddr, SMTPPort: testServerPort, - FromName: testSenderName, FromAddress: testSender, - }) + } + eq, err := notification.NewQueue(t.Context(), 10, config) if err != nil { t.Fatal(err) } + eq.Start(1) + defer eq.Stop() // send email - if err := eq.Send(notification.Notification{ - Params: notification.NotificationParams{ + emailNotification := &EmailNotification{ + Params: EmailParams{ To: testReceiver, Subject: testSubject, }, Body: []byte(testHTMLBody), PlainBody: []byte(testBody), - }); err != nil { + } + if err := emailNotification.Send(config); err != nil { t.Fatal(err) } // check if the email was received @@ -221,58 +200,59 @@ func TestSendEmail(t *testing.T) { case <-time.After(2 * time.Second): t.Error("timed out waiting for the email to be received") } + invalidEmail := &EmailNotification{} // try to send invalid email - if err := eq.Send(notification.Notification{}); err == nil { + if err := invalidEmail.Send(config); err == nil { t.Error("expected error sending invalid email") } // try to compose a invalid email - if body, err := eq.composeBody(notification.Notification{}); err == nil { + if body, err := invalidEmail.composeBody(config); err == nil { t.Error("expected error composing invalid email") } else if body != nil { t.Error("expected body to be nil") } // try to send email to an invalid SMTP server - badEq, err := NewEmailQueue(ctx, &EmailConfig{ - SMTPServer: testServerAddr, - SMTPPort: 8080, - FromName: testSenderName, - FromAddress: testSender, - }) + badConf := &EmailConfig{ + SMTPServer: testServerAddr, + SMTPPort: 8080, + FromAddress: testSender, + SMTPUsername: "user", + SMTPPassword: "pass", + } + badEq, err := notification.NewQueue(t.Context(), 10, badConf) if err != nil { t.Fatal(err) } - if err := badEq.Send(notification.Notification{ - Params: notification.NotificationParams{ + badEq.Start(1) + defer badEq.Stop() + otherNotification := &EmailNotification{ + Params: EmailParams{ To: testReceiver, Subject: testSubject, }, Body: nil, PlainBody: []byte(testBody), - }); err == nil { + } + if err := otherNotification.Send(badConf); err == nil { t.Error("expected error sending email") } } func TestPushSendEmail(t *testing.T) { // create email queue and start it - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - errCh := make(chan error, 1) - eq, err := NewEmailQueue(ctx, &EmailConfig{ + eq, err := notification.NewQueue(t.Context(), 10, &EmailConfig{ SMTPServer: testServerAddr, SMTPPort: testServerPort, - FromName: testSenderName, FromAddress: testSender, - ErrorCh: errCh, }) if err != nil { t.Fatal(err) } - eq.Start() + eq.Start(1) defer eq.Stop() // push email - if err := eq.Push(notification.Notification{ - Params: notification.NotificationParams{ + if err := eq.Push(&EmailNotification{ + Params: EmailParams{ To: testReceiver, Subject: testSubject, }, @@ -293,10 +273,19 @@ func TestPushSendEmail(t *testing.T) { case <-time.After(2 * time.Second): t.Error("timed out waiting for the email to be received") } - // sleep to pop nil email - time.Sleep(2 * time.Second) // push invalid email - if err := eq.Push(notification.Notification{}); err == nil { + if err := eq.Push(&EmailNotification{}); err == nil { t.Error("expected error pushing invalid email") } } + +func TestSendWrongConfigType(t *testing.T) { + n := &EmailNotification{ + Params: EmailParams{To: testReceiver, Subject: testSubject}, + PlainBody: []byte(testBody), + } + // Pass a non-EmailConfig to trigger the type assertion failure + if err := n.Send(nil); err != ErrInvalidConfig { + t.Errorf("expected ErrInvalidConfig, got %v", err) + } +} diff --git a/notification/email/emailqueue.go b/notification/email/emailqueue.go deleted file mode 100644 index f381db3..0000000 --- a/notification/email/emailqueue.go +++ /dev/null @@ -1,221 +0,0 @@ -package email - -import ( - "bytes" - "context" - "fmt" - "mime/multipart" - "net/mail" - "net/smtp" - "net/textproto" - "sync" - - "github.com/simpleauthlink/authapi/notification" -) - -// defaultSendRetries is the default number of retries to send the email. -const defaultSendRetries = 3 - -// EmailConfig struct represents the email configuration that is needed to send -// an email using and SMTP server. It includes the email address (used as the -// sender address but also as the username for the SMTP server), the email -// server hostname, its port and the password. -type EmailConfig struct { - FromName string - FromAddress string - SMTPUsername string - SMTPPassword string - SMTPServer string - SMTPPort int - Retries int - ErrorCh chan error -} - -// Valid method checks if the email configuration is valid. It returns true if -// the sender name, the SMTP server and its port are not empty, and the sender -// email address is valid. It also sets the number of retries to the default -// value if it is not set. -func (cfg *EmailConfig) Valid() bool { - if cfg.FromName == "" || cfg.SMTPServer == "" || cfg.SMTPPort == 0 { - return false - } - if cfg.Retries == 0 { - cfg.Retries = defaultSendRetries - } - _, err := mail.ParseAddress(cfg.FromAddress) - return err == nil -} - -// EmailQueue struct represents the email queue. It includes the context and the -// cancel function to stop the queue, the configuration of the server to send -// the email, the list of emails to send, and the waiter to wait for the -// background process to finish. -type EmailQueue struct { - ctx context.Context - cancel context.CancelFunc - cfg *EmailConfig - auth smtp.Auth - items []*notification.Notification - itemsMtx sync.Mutex - waiter sync.WaitGroup - errCh chan error -} - -// NewEmailQueue creates a new EmailQueue with the provided configuration. -func NewEmailQueue(ctx context.Context, cfg *EmailConfig) (*EmailQueue, error) { - // check if the configuration is valid - if !cfg.Valid() { - return nil, ErrInvalidConfig - } - // init the email queue - internalCtx, cancel := context.WithCancel(ctx) - eq := &EmailQueue{ - ctx: internalCtx, - cancel: cancel, - cfg: cfg, - items: []*notification.Notification{}, - errCh: cfg.ErrorCh, - } - // init SMTP auth - if cfg.SMTPUsername != "" && cfg.SMTPPassword != "" { - eq.auth = smtp.PlainAuth("", cfg.SMTPUsername, cfg.SMTPPassword, cfg.SMTPServer) - } - // return the email queue - return eq, nil -} - -// Start method starts the email queue. It listens for new emails in the queue -// and sends them using the provided configuration. -func (eq *EmailQueue) Start() { - eq.waiter.Add(1) - go func() { - defer eq.waiter.Done() - for { - select { - case <-eq.ctx.Done(): - return - default: - e, ok := eq.Pop() - if !ok { - continue - } - if err := eq.Send(e); err != nil { - if eq.errCh != nil { - eq.errCh <- err - } - } - } - } - }() -} - -// Stop method stops the email queue. -func (eq *EmailQueue) Stop() { - eq.cancel() - eq.waiter.Wait() -} - -// Pop method removes the first email in the queue and returns it. -func (eq *EmailQueue) Pop() (notification.Notification, bool) { - eq.itemsMtx.Lock() - defer eq.itemsMtx.Unlock() - if len(eq.items) == 0 { - return notification.Notification{}, false - } - e := eq.items[0] - eq.items = eq.items[1:] - return *e, true -} - -// Push method adds a new email to the queue. -func (eq *EmailQueue) Push(n notification.Notification) error { - // check if the email is valid - if !n.Valid() { - return ErrInvalidEmail - } - eq.itemsMtx.Lock() - eq.items = append(eq.items, &n) - eq.itemsMtx.Unlock() - return nil -} - -// Send method sends the email using the queue configuration. It uses the -// email address as the sender address and the username for the SMTP server. -// It composes the email message, creates the auth object with the email -// credentials, the server string with the host and the port, and the receipts. -// Finally, it sends the email. If something fails during the process, it -// returns an error. It can be used even the queue is not started. -func (eq *EmailQueue) Send(n notification.Notification) error { - // check if the email is valid - if !n.Valid() { - return ErrInvalidEmail - } - // compose the email body - body, err := eq.composeBody(n) - if err != nil { - return ErrComposeEmail.With(err) - } - // create the server string with the host and the port and the receipts - server := fmt.Sprintf("%s:%d", eq.cfg.SMTPServer, eq.cfg.SMTPPort) - receipts := []string{n.Params.To} - // send the email - for i := 0; i < eq.cfg.Retries; i++ { - if err = smtp.SendMail(server, eq.auth, eq.cfg.FromAddress, receipts, body); err == nil { - break - } - } - if err != nil { - return ErrSendEmail.With(err) - } - return nil -} - -// composeBody creates the email body with the message data. It creates a -// multipart email with a plain text and an HTML part. It returns the email -// content as a byte slice or an error if the body could not be composed. -func (eq *EmailQueue) composeBody(n notification.Notification) ([]byte, error) { - // parse 'to' email address - to, err := mail.ParseAddress(n.Params.To) - if err != nil { - return nil, ErrParseAddress.With(err) - } - // create email headers - var headers bytes.Buffer - boundary := "----=_Part_0_123456789.123456789" - headers.WriteString(fmt.Sprintf("From: %s\r\n", eq.cfg.FromAddress)) - headers.WriteString(fmt.Sprintf("To: %s\r\n", to.String())) - headers.WriteString(fmt.Sprintf("Subject: %s\r\n", n.Params.Subject)) - headers.WriteString("MIME-Version: 1.0\r\n") - headers.WriteString(fmt.Sprintf("Content-Type: multipart/alternative; boundary=\"%s\"\r\n", boundary)) - headers.WriteString("\r\n") // blank line between headers and body - // create multipart writer - var body bytes.Buffer - writer := multipart.NewWriter(&body) - if err := writer.SetBoundary(boundary); err != nil { - return nil, ErrSetBoundary.With(err) - } - // plain text part - textPart, _ := writer.CreatePart(textproto.MIMEHeader{ - "Content-Type": {"text/plain; charset=\"UTF-8\""}, - "Content-Transfer-Encoding": {"7bit"}, - }) - if _, err := textPart.Write(n.PlainBody); err != nil { - return nil, ErrWriteBody.With(err) - } - // HTML part - htmlPart, _ := writer.CreatePart(textproto.MIMEHeader{ - "Content-Type": {"text/html; charset=\"UTF-8\""}, - "Content-Transfer-Encoding": {"7bit"}, - }) - if _, err := htmlPart.Write(n.Body); err != nil { - return nil, ErrWriteHTMLBody.With(err) - } - if err := writer.Close(); err != nil { - return nil, ErrCloseEmailWriter.With(err) - } - // combine headers and body and return the content - var email bytes.Buffer - email.Write(headers.Bytes()) - email.Write(body.Bytes()) - return email.Bytes(), nil -} diff --git a/notification/email/errors.go b/notification/email/errors.go index 1415164..c27c92f 100644 --- a/notification/email/errors.go +++ b/notification/email/errors.go @@ -1,33 +1,33 @@ package email -import "github.com/simpleauthlink/authapi/internal" +import "go.k7z7z.cc/x/errors" var ( // ErrInvalidConfig is the error returned when the configuration is invalid. - ErrInvalidConfig = internal.NewErr("invalid configuration") - // ErrInitQueue is the error returned when the queue cannot be initialized. - ErrInitQueue = internal.NewErr("error initializing the queue") + ErrInvalidConfig = errors.New("invalid configuration") // ErrInvalidEmail is the error returned when the email is invalid. - ErrInvalidEmail = internal.NewErr("invalid email") + ErrInvalidEmail = errors.New("invalid email") // ErrInvalidTemplate is the error returned when the template is invalid. - ErrInvalidTemplate = internal.NewErr("invalid template") + ErrInvalidTemplate = errors.New("invalid template") // ErrSendEmail is the error returned when the email cannot be sent. - ErrSendEmail = internal.NewErr("error sending email") + ErrSendEmail = errors.New("error sending email") // ErrComposeEmail is the error returned when the email cannot be composed. - ErrComposeEmail = internal.NewErr("error composing email") + ErrComposeEmail = errors.New("error composing email") + // ErrCreatePart is the error returned when an email part cannot be written. + ErrCreatePart = errors.New("error creating email part") // ErrParseAddress is the error returned when the email address cannot // be parsed. - ErrParseAddress = internal.NewErr("error parsing email address") + ErrParseAddress = errors.New("error parsing email address") // ErrSetBoundary is the error returned when the boundary cannot be set // when a multipart email is composed. - ErrSetBoundary = internal.NewErr("error setting boundary") - // ErrWriteHTMLBody is the error returned when the email plain body cannot + ErrSetBoundary = errors.New("error setting boundary") + // ErrWriteBody is the error returned when the email plain body cannot // be written. - ErrWriteBody = internal.NewErr("error writing email plain body") + ErrWriteBody = errors.New("error writing email plain body") // ErrWriteHTMLBody is the error returned when the email HTML body cannot // be written. - ErrWriteHTMLBody = internal.NewErr("error writing email html body") + ErrWriteHTMLBody = errors.New("error writing email html body") // ErrCloseEmailWriter is the error returned when the email writer cannot // be closed after composing the email. - ErrCloseEmailWriter = internal.NewErr("error closing email writer") + ErrCloseEmailWriter = errors.New("error closing email writer") ) diff --git a/notification/email/notification.go b/notification/email/notification.go new file mode 100644 index 0000000..4b98643 --- /dev/null +++ b/notification/email/notification.go @@ -0,0 +1,139 @@ +package email + +import ( + "bytes" + "fmt" + "mime/multipart" + "net/mail" + "net/smtp" + "net/textproto" + "time" + + "github.com/simpleauthlink/authapi/notification" +) + +// EmailParams holds the recipient and subject for an email notification. +type EmailParams struct { + To string + Subject string +} + +// Valid reports whether the recipient is a parseable email address and the +// subject is non-empty. +func (p EmailParams) Valid() bool { + _, err := mail.ParseAddress(p.To) + return err == nil && p.Subject != "" +} + +// EmailNotification is a notification that can be sent via SMTP. At least one +// of Body (HTML) or PlainBody (plain text) must be set. +type EmailNotification struct { + Params EmailParams + Body []byte + PlainBody []byte +} + +// Valid method checks if the email is valid. It returns true if the recipient +// email address, the subject and the body are not empty. +func (n *EmailNotification) Valid() bool { + return n.Params.Valid() && max(len(n.Body), len(n.PlainBody)) > 0 +} + +// Send delivers the email via the SMTP server configured in the provided +// EmailConfig. It retries up to cfg.Retries times (or a default of 3) on +// transient failures. +func (n *EmailNotification) Send(conf notification.QueueConfig) error { + cfg, ok := any(conf).(*EmailConfig) + if !ok { + return ErrInvalidConfig + } + // init SMTP auth + var auth smtp.Auth + if cfg.SMTPUsername != "" && cfg.SMTPPassword != "" { + auth = smtp.PlainAuth("", cfg.SMTPUsername, cfg.SMTPPassword, cfg.SMTPServer) + } + // check if the email is valid + if !n.Valid() { + return ErrInvalidEmail + } + // compose the email body + body, err := n.composeBody(cfg) + if err != nil { + return ErrComposeEmail.With(err) + } + receipts := []string{n.Params.To} + // create the server string with the host and the port and the receipts + server := fmt.Sprintf("%s:%d", cfg.SMTPServer, cfg.SMTPPort) + // send the email + retries := cfg.Retries + if retries == 0 { + retries = defaultSendRetries + } + for range retries { + if err = smtp.SendMail(server, auth, cfg.FromAddress, receipts, body); err == nil { + break + } + time.Sleep(100 * time.Millisecond) + } + if err != nil { + return ErrSendEmail.With(err) + } + return nil +} + +func (n *EmailNotification) composeBody(conf *EmailConfig) ([]byte, error) { + // parse 'to' email address + to, err := mail.ParseAddress(n.Params.To) + if err != nil { + return nil, ErrParseAddress.With(err) + } + // create email headers + var headers bytes.Buffer + boundary := "----=_Part_0_123456789.123456789" + _, _ = fmt.Fprintf(&headers, "From: %s\r\n", conf.FromAddress) + _, _ = fmt.Fprintf(&headers, "To: %s\r\n", to.String()) + _, _ = fmt.Fprintf(&headers, "Subject: %s\r\n", n.Params.Subject) + _, _ = fmt.Fprintf(&headers, "MIME-Version: 1.0\r\n") + _, _ = fmt.Fprintf(&headers, "Content-Type: multipart/alternative; boundary=\"%s\"\r\n", boundary) + _, _ = fmt.Fprintf(&headers, "\r\n") // blank line between headers and body + // create multipart writer + var body bytes.Buffer + writer := multipart.NewWriter(&body) + if err := writer.SetBoundary(boundary); err != nil { + return nil, ErrSetBoundary.With(err) + } + // plain text part + if len(n.PlainBody) > 0 { + textPart, err := writer.CreatePart(textproto.MIMEHeader{ + "Content-Type": {"text/plain; charset=\"UTF-8\""}, + "Content-Transfer-Encoding": {"7bit"}, + }) + if err != nil { + return nil, ErrCreatePart.With(err) + } + if _, err := textPart.Write(n.PlainBody); err != nil { + return nil, ErrWriteBody.With(err) + } + } + // HTML part + if len(n.Body) > 0 { + htmlPart, err := writer.CreatePart(textproto.MIMEHeader{ + "Content-Type": {"text/html; charset=\"UTF-8\""}, + "Content-Transfer-Encoding": {"7bit"}, + }) + if err != nil { + return nil, ErrCreatePart.With(err) + } + if _, err := htmlPart.Write(n.Body); err != nil { + return nil, ErrWriteHTMLBody.With(err) + } + } + if err := writer.Close(); err != nil { + return nil, ErrCloseEmailWriter.With(err) + } + // combine headers and body and return the content + var email bytes.Buffer + email.Write(headers.Bytes()) + email.Write(body.Bytes()) + return email.Bytes(), nil +} diff --git a/notification/email/notification_test.go b/notification/email/notification_test.go new file mode 100644 index 0000000..df6aedc --- /dev/null +++ b/notification/email/notification_test.go @@ -0,0 +1,90 @@ +package email + +import ( + "testing" +) + +func TestEmailParams_Valid(t *testing.T) { + tests := []struct { + name string + params EmailParams + valid bool + }{ + { + name: "Valid params", + params: EmailParams{To: "test@example.com", Subject: "Test Subject"}, + valid: true, + }, + { + name: "Invalid email", + params: EmailParams{To: "invalid-email", Subject: "Test Subject"}, + valid: false, + }, + { + name: "Empty subject", + params: EmailParams{To: "test@example.com", Subject: ""}, + valid: false, + }, + { + name: "Empty email and subject", + params: EmailParams{To: "", Subject: ""}, + valid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.params.Valid(); got != tt.valid { + t.Errorf("expected valid: %v, got: %v", tt.valid, got) + } + }) + } +} + +func TestNotification_Valid(t *testing.T) { + tests := []struct { + name string + notification EmailNotification + valid bool + }{ + { + name: "Valid notification with Body", + notification: EmailNotification{ + Params: EmailParams{To: "test@example.com", Subject: "Test Subject"}, + Body: []byte("Test Body"), + }, + valid: true, + }, + { + name: "Valid notification with PlainBody", + notification: EmailNotification{ + Params: EmailParams{To: "test@example.com", Subject: "Test Subject"}, + PlainBody: []byte("Test Plain Body"), + }, + valid: true, + }, + { + name: "Invalid notification with empty Body and PlainBody", + notification: EmailNotification{ + Params: EmailParams{To: "test@example.com", Subject: "Test Subject"}, + }, + valid: false, + }, + { + name: "Invalid notification with invalid Params", + notification: EmailNotification{ + Params: EmailParams{To: "invalid-email", Subject: "Test Subject"}, + Body: []byte("Test Body"), + }, + valid: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.notification.Valid(); got != tt.valid { + t.Errorf("expected valid: %v, got: %v", tt.valid, got) + } + }) + } +} diff --git a/notification/email/template.go b/notification/email/template.go index 4e9bb7a..3271fbe 100644 --- a/notification/email/template.go +++ b/notification/email/template.go @@ -4,8 +4,6 @@ import ( "bytes" htmltemplate "html/template" texttemplate "text/template" - - "github.com/simpleauthlink/authapi/notification" ) // EmailTemplate is the definition of an email template, which contains the @@ -20,26 +18,26 @@ type EmailTemplate struct { // be filled. It tries to fill both the HTML and plain text templates, but if // any of them is missing, it will return an error. If some of the placeholders // in the template are not filled, they will be left as they are. -func (temp *EmailTemplate) Compose(params notification.NotificationParams, data any) (notification.Notification, error) { +func (temp *EmailTemplate) Compose(params EmailParams, data any) (*EmailNotification, error) { if !params.Valid() { - return notification.Notification{}, ErrComposeEmail + return nil, ErrComposeEmail } // compose the html body body, err := temp.composeHTML(data) if err != nil { - return notification.Notification{}, err + return nil, err } // compose the plain body plainBody, err := temp.composePlain(data) if err != nil { - return notification.Notification{}, err + return nil, err } // if both bodies are empty, return an error if plainBody == nil && body == nil { - return notification.Notification{}, ErrInvalidTemplate + return nil, ErrInvalidTemplate } // return the email with the filled bodies - email := notification.Notification{ + email := &EmailNotification{ Params: params, Body: body, PlainBody: plainBody, diff --git a/notification/email/template_test.go b/notification/email/template_test.go index 1d5881d..949fa5f 100644 --- a/notification/email/template_test.go +++ b/notification/email/template_test.go @@ -2,8 +2,6 @@ package email import ( "testing" - - "github.com/simpleauthlink/authapi/notification" ) var testTemplate = &EmailTemplate{ @@ -22,7 +20,7 @@ func TestCompose(t *testing.T) { Title: "Test Title", Content: "Test Content", } - email, err := testTemplate.Compose(notification.NotificationParams{ + email, err := testTemplate.Compose(EmailParams{ To: testReceiver, Subject: testSubject, }, data) @@ -44,21 +42,21 @@ func TestCompose(t *testing.T) { t.Fatalf("got %v, want %v", string(email.PlainBody), expectedPlain) } // no subject - if _, err := testTemplate.Compose(notification.NotificationParams{ + if _, err := testTemplate.Compose(EmailParams{ To: testReceiver, Subject: "", }, data); err == nil { t.Fatalf("expected error, got nil") } // no to address - if _, err := testTemplate.Compose(notification.NotificationParams{ + if _, err := testTemplate.Compose(EmailParams{ To: "", Subject: testSubject, }, data); err == nil { t.Fatalf("expected error, got nil") } // bad to address - if _, err := testTemplate.Compose(notification.NotificationParams{ + if _, err := testTemplate.Compose(EmailParams{ To: "bad email", Subject: testSubject, }, data); err == nil { @@ -66,7 +64,7 @@ func TestCompose(t *testing.T) { } // invalid template emptyTemplate := &EmailTemplate{} - validParams := notification.NotificationParams{ + validParams := EmailParams{ To: testReceiver, Subject: testSubject, } @@ -150,3 +148,35 @@ func Test_composeHTML(t *testing.T) { t.Fatalf("expected nil, got %v", string(body)) } } + +func TestComposeWithBrokenTemplate(t *testing.T) { + validParams := EmailParams{ + To: testReceiver, + Subject: testSubject, + } + data := testData{Title: "T", Content: "C"} + + // Broken HTML template: Parse error + t.Run("broken HTML template", func(t *testing.T) { + bad := &EmailTemplate{ + HTML: "{{.Title}", // missing closing brace + Plain: "OK {{.Title}}", + } + _, err := bad.Compose(validParams, data) + if err == nil { + t.Error("expected parse error for broken HTML template") + } + }) + + // Broken Plain template: Parse error + t.Run("broken Plain template", func(t *testing.T) { + bad := &EmailTemplate{ + HTML: "OK {{.Title}}", + Plain: "{{.Title}", // missing closing brace + } + _, err := bad.Compose(validParams, data) + if err == nil { + t.Error("expected parse error for broken Plain template") + } + }) +} diff --git a/notification/templates/login/definition.go b/notification/email/templates/login/definition.go similarity index 88% rename from notification/templates/login/definition.go rename to notification/email/templates/login/definition.go index 9a66b67..f8ddaca 100644 --- a/notification/templates/login/definition.go +++ b/notification/email/templates/login/definition.go @@ -4,7 +4,6 @@ import ( _ "embed" "regexp" - "github.com/simpleauthlink/authapi/notification" "github.com/simpleauthlink/authapi/notification/email" "github.com/simpleauthlink/authapi/token" ) @@ -29,15 +28,15 @@ func (d Data) Subject() string { // regular expression to fill the template with regex and find the token in // the email content. Then it decodes the token and returns it. If the token // is not found, it returns nil. -func FindToken(email, content string) *token.Token { +func FindToken(emailAddress, content string) *token.Token { loginData := Data{ AppName: `.+`, - Email: email, + Email: emailAddress, Token: `(.+\..+)`, Link: `.+`, } - loginEmail, err := Template.Compose(notification.NotificationParams{ - To: email, + loginEmail, err := Template.Compose(email.EmailParams{ + To: emailAddress, Subject: loginData.Subject(), }, loginData) if err != nil { diff --git a/notification/email/templates/login/definition_test.go b/notification/email/templates/login/definition_test.go new file mode 100644 index 0000000..9b1d9f1 --- /dev/null +++ b/notification/email/templates/login/definition_test.go @@ -0,0 +1,118 @@ +package login + +import ( + "fmt" + "testing" + "time" + + "github.com/simpleauthlink/authapi/notification/email" + "github.com/simpleauthlink/authapi/token" +) + +func TestSubject(t *testing.T) { + tests := []struct { + name string + data Data + expected string + }{ + { + name: "normal app name", + data: Data{AppName: "MyApp"}, + expected: "Your token for 'MyApp'", + }, + { + name: "empty app name", + data: Data{AppName: ""}, + expected: "Your token for ''", + }, + { + name: "special chars", + data: Data{AppName: "App's Name"}, + expected: "Your token for 'App's Name'", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.data.Subject(); got != tt.expected { + t.Errorf("got %q, want %q", got, tt.expected) + } + }) + } +} + +func TestFindToken(t *testing.T) { + // Generate a real token and compose a real plain-text email + app := &token.App{ + Name: "TestApp", + RedirectURI: "https://example.com/callback", + SessionDuration: 30 * time.Minute, + } + servicePart := []byte("test-service-secret") + appPart := []byte("test-app-secret") + secret := new(token.Secret).SetParts(servicePart, appPart) + app.SetSecret(secret) + appID := app.ID(secret) + + testEmail := "user@test.com" + testToken := appID.GenerateToken(*secret, token.UserID(testEmail)) + if testToken == nil { + t.Fatal("failed to generate test token") + } + + loginData := Data{ + AppName: "TestApp", + Email: testEmail, + Token: testToken.String(), + Link: "https://example.com/callback?token=" + testToken.String(), + } + loginEmail, err := Template.Compose(email.EmailParams{ + To: testEmail, + Subject: loginData.Subject(), + }, loginData) + if err != nil { + t.Fatal(err) + } + emailContent := string(loginEmail.PlainBody) + + t.Run("valid email content with token", func(t *testing.T) { + found := FindToken(testEmail, emailContent) + if found == nil { + t.Fatal("expected token to be found, got nil") + } + if got := found.String(); got != testToken.String() { + t.Errorf("got %q, want %q", got, testToken.String()) + } + }) + + t.Run("empty content", func(t *testing.T) { + if got := FindToken(testEmail, ""); got != nil { + t.Errorf("expected nil for empty content, got %v", got) + } + }) + + t.Run("wrong email address", func(t *testing.T) { + // Regex contains the literal email, should not match for a different + // email + if got := FindToken("other@test.com", emailContent); got != nil { + t.Errorf("expected nil for wrong email, got %v", got) + } + }) + + t.Run("content without any token", func(t *testing.T) { + if got := FindToken(testEmail, "some random text without tokens"); got != nil { + t.Errorf("expected nil for content without token, got %v", got) + } + }) + + t.Run("content with garbage that looks like a token", func(t *testing.T) { + // Construct content that contains the email but a malformed token + garbage := fmt.Sprintf("Hi, %s\nIt contains your login token: 'not.a.real.token'\n", testEmail) + // This might return nil because the regex capture may not match, or it + // may return a "token" that does not round-trip. + // Either way, verify FindToken does not panic and the result (if any) + // is non-nil but SetString'd token from the raw match. + found := FindToken(testEmail, garbage) + // We dont assert nil because the regex may match; we just check no panic. + _ = found + }) +} diff --git a/notification/templates/login/template.html b/notification/email/templates/login/template.html similarity index 100% rename from notification/templates/login/template.html rename to notification/email/templates/login/template.html diff --git a/notification/notification.go b/notification/notification.go index 308c79a..82f91ed 100644 --- a/notification/notification.go +++ b/notification/notification.go @@ -1,33 +1,148 @@ package notification -import "net/mail" +import ( + "context" + "fmt" + "sync" +) -type NotificationParams struct { - To string - Subject string +// ErrQueueFull is returned when the notification queue is at capacity. +var ErrQueueFull = fmt.Errorf("notification queue full") + +// Notification is the interface that must be implemented by any notification +// channel (email, SMS, push, etc.). Implementations must be sendable via a +// QueueConfig that supports them. +type Notification interface { + // Valid returns true if the notification has all required fields set. + Valid() bool + // Send delivers the notification using the given configuration. + Send(QueueConfig) error +} + +// QueueConfig is the interface for notification channel configurations. Each +// channel (email, SMS, etc.) provides its own config that implements this +// interface. +type QueueConfig interface { + // Valid returns true if the configuration is complete and usable. + Valid() bool + // Support reports whether this configuration can send the given + // notification type. + Support(Notification) bool +} + +// Queue is a generic multi-channel notification queue. It fans out each +// notification to the first QueueConfig that Supports it. Workers are started +// by Start and stopped by Stop. Errors are emitted on the channel returned by +// Errors. +type Queue struct { + ctx context.Context + cancel context.CancelFunc + ch chan Notification + + configs []QueueConfig + waiter sync.WaitGroup + errCh chan error + closedMu sync.RWMutex + closed bool +} + +// NewQueue creates a new Queue with the given buffer size and channel +// configurations. Each config must pass Valid(). Returns an error if any +// config is invalid. +func NewQueue(ctx context.Context, queueSize int, configs ...QueueConfig) (*Queue, error) { + for _, cfg := range configs { + if !cfg.Valid() { + return nil, fmt.Errorf("invalid config provided") + } + } + + internalCtx, cancel := context.WithCancel(ctx) + return &Queue{ + ctx: internalCtx, + cancel: cancel, + ch: make(chan Notification, queueSize), + configs: configs, + errCh: make(chan error, 1), + }, nil +} + +// Start launches workers goroutines that consume the queue. Each worker reads +// notifications and sends them via the matching config. Send errors are pushed +// to the Errors channel (non-blocking). +func (eq *Queue) Start(workers int) { + for range workers { + eq.waiter.Go(func() { + for { + select { + case <-eq.ctx.Done(): + return + case e, ok := <-eq.ch: + if !ok { + return + } + if err := eq.send(e); err != nil { + select { + case eq.errCh <- err: + default: + } + } + } + } + }) + } } -func (p NotificationParams) Valid() bool { - _, err := mail.ParseAddress(p.To) - return err == nil && p.Subject != "" +// Stop gracefully shuts down the queue: closes the input channel, cancels the +// context, waits for all workers to finish, and closes the Errors channel. New +// pushes after Stop are silently accepted (return nil). +func (eq *Queue) Stop() { + eq.closedMu.Lock() + eq.closed = true + close(eq.ch) + eq.closedMu.Unlock() + eq.cancel() + eq.waiter.Wait() + close(eq.errCh) } -type Notification struct { - Params NotificationParams - Body []byte - PlainBody []byte +// Push enqueues a notification. Returns ErrQueueFull if the buffer is full, or +// nil if the notification was accepted (including after Stop). +func (eq *Queue) Push(n Notification) error { + if !n.Valid() { + return fmt.Errorf("invalid notification") + } + eq.closedMu.RLock() + defer eq.closedMu.RUnlock() + if eq.closed { + return nil + } + select { + case eq.ch <- n: + return nil + default: + return ErrQueueFull + } } -// Valid method checks if the email is valid. It returns true if the recipient -// email address, the subject and the body are not empty. -func (n *Notification) Valid() bool { - return n.Params.Valid() && max(len(n.Body), len(n.PlainBody)) > 0 +// Errors returns a receive-only channel that emits errors encountered +// by workers during notification sends. The caller must continuously +// read from this channel after calling Start to prevent workers from +// blocking. The channel is closed when Stop is called. +func (eq *Queue) Errors() <-chan error { + return eq.errCh } -type Queue interface { - Start() - Stop() - Pop() (Notification, bool) - Push(Notification) error - Send(Notification) error +func (eq *Queue) send(n Notification) error { + for _, cfg := range eq.configs { + if !cfg.Support(n) { + continue + } + if !cfg.Valid() { + return fmt.Errorf("invalid configuration") + } + if err := n.Send(cfg); err != nil { + return err + } + } + return nil } diff --git a/notification/notification_test.go b/notification/notification_test.go index 573947c..cbfb5fa 100644 --- a/notification/notification_test.go +++ b/notification/notification_test.go @@ -1,90 +1,202 @@ package notification import ( + "context" + "fmt" "testing" + "time" ) -func TestNotificationParams_Valid(t *testing.T) { - tests := []struct { - name string - params NotificationParams - valid bool - }{ - { - name: "Valid params", - params: NotificationParams{To: "test@example.com", Subject: "Test Subject"}, - valid: true, - }, - { - name: "Invalid email", - params: NotificationParams{To: "invalid-email", Subject: "Test Subject"}, - valid: false, - }, - { - name: "Empty subject", - params: NotificationParams{To: "test@example.com", Subject: ""}, - valid: false, - }, - { - name: "Empty email and subject", - params: NotificationParams{To: "", Subject: ""}, - valid: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := tt.params.Valid(); got != tt.valid { - t.Errorf("expected valid: %v, got: %v", tt.valid, got) - } - }) +type testConfig struct{} + +func (testConfig) Valid() bool { + return true +} + +func (testConfig) Support(n Notification) bool { + return true +} + +type testNotification struct{} + +func (testNotification) Valid() bool { + return true +} + +func (testNotification) Send(QueueConfig) error { + return nil +} + +func TestPushQueueFull(t *testing.T) { + queue, err := NewQueue(context.Background(), 1, testConfig{}) + if err != nil { + t.Fatalf("init queue: %v", err) + } + queue.Start(1) + defer queue.Stop() + + if err := queue.Push(testNotification{}); err != nil { + t.Fatalf("first push: %v", err) + } + if err := queue.Push(testNotification{}); err != ErrQueueFull { + t.Errorf("expected ErrQueueFull, got %v", err) + } +} + +func TestWorkerPool(t *testing.T) { + queue, err := NewQueue(context.Background(), 10, testConfig{}) + if err != nil { + t.Fatalf("init queue: %v", err) + } + queue.Start(4) + defer queue.Stop() + + for range 10 { + if err := queue.Push(testNotification{}); err != nil { + t.Fatalf("push: %v", err) + } } } -func TestNotification_Valid(t *testing.T) { - tests := []struct { - name string - notification Notification - valid bool - }{ - { - name: "Valid notification with Body", - notification: Notification{ - Params: NotificationParams{To: "test@example.com", Subject: "Test Subject"}, - Body: []byte("Test Body"), - }, - valid: true, - }, - { - name: "Valid notification with PlainBody", - notification: Notification{ - Params: NotificationParams{To: "test@example.com", Subject: "Test Subject"}, - PlainBody: []byte("Test Plain Body"), - }, - valid: true, - }, - { - name: "Invalid notification with empty Body and PlainBody", - notification: Notification{ - Params: NotificationParams{To: "test@example.com", Subject: "Test Subject"}, - }, - valid: false, - }, - { - name: "Invalid notification with invalid Params", - notification: Notification{ - Params: NotificationParams{To: "invalid-email", Subject: "Test Subject"}, - Body: []byte("Test Body"), - }, - valid: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got := tt.notification.Valid(); got != tt.valid { - t.Errorf("expected valid: %v, got: %v", tt.valid, got) - } - }) +var errSendFailure = fmt.Errorf("send failure") + +type testErrorNotification struct{} + +func (testErrorNotification) Valid() bool { return true } +func (testErrorNotification) Send(QueueConfig) error { return errSendFailure } + +func TestErrors(t *testing.T) { + queue, err := NewQueue(context.Background(), 10, testConfig{}) + if err != nil { + t.Fatalf("init queue: %v", err) + } + + errCh := queue.Errors() + if errCh == nil { + t.Fatal("Errors() returned nil channel") + } + + queue.Start(1) + + // push a notification that triggers an error + if err := queue.Push(testErrorNotification{}); err != nil { + t.Fatalf("push: %v", err) + } + + // verify the error arrives on the Errors() channel + select { + case got := <-errCh: + if got != errSendFailure { + t.Errorf("expected %v, got %v", errSendFailure, got) + } + case <-time.After(2 * time.Second): + t.Fatal("expected error on Errors() channel") + } + + // verify Stop() closes the Errors() channel + queue.Stop() + _, ok := <-errCh + if ok { + t.Error("expected Errors() channel to be closed after Stop()") + } +} + +func TestPushAfterStop(t *testing.T) { + queue, err := NewQueue(context.Background(), 10, testConfig{}) + if err != nil { + t.Fatal(err) + } + queue.Start(1) + queue.Stop() + + // Push after Stop: returns nil (silent accept) + if err := queue.Push(testNotification{}); err != nil { + t.Errorf("expected nil after Stop, got %v", err) + } +} + +type invalidNotification struct{} + +func (invalidNotification) Valid() bool { return false } +func (invalidNotification) Send(QueueConfig) error { return nil } + +func TestPushInvalidNotification(t *testing.T) { + queue, err := NewQueue(context.Background(), 10, testConfig{}) + if err != nil { + t.Fatal(err) + } + queue.Start(1) + defer queue.Stop() + + // Push an invalid notification (always returns false from Valid) + err = queue.Push(invalidNotification{}) + if err == nil { + t.Error("expected error for invalid notification, got nil") + } +} + +// Config that Supports nothing — triggers the "no config matches" branch +type noSupportConfig struct{} + +func (noSupportConfig) Valid() bool { return true } +func (noSupportConfig) Support(n Notification) bool { return false } + +// Config that becomes invalid after construction +type invalidOnSendConfig struct{ valid bool } + +func (c *invalidOnSendConfig) Valid() bool { return c.valid } +func (c *invalidOnSendConfig) Support(n Notification) bool { return true } + +func TestSendNoSupport(t *testing.T) { + queue, err := NewQueue(context.Background(), 10, noSupportConfig{}) + if err != nil { + t.Fatal(err) + } + queue.Start(1) + defer queue.Stop() + + // Sends succeed (no config matches → no error but no delivery) + if err := queue.Push(testNotification{}); err != nil { + t.Fatalf("unexpected push error: %v", err) + } +} + +func TestSendInvalidConfig(t *testing.T) { + cfg := &invalidOnSendConfig{valid: true} + queue, err := NewQueue(context.Background(), 10, cfg) + if err != nil { + t.Fatal(err) + } + queue.Start(1) + defer queue.Stop() + + // Make config invalid mid-flight + cfg.valid = false + + // Push a notification — worker hits cfg.Valid() → false → error on Errors channel + if err := queue.Push(testNotification{}); err != nil { + t.Fatalf("push: %v", err) + } + select { + case got := <-queue.Errors(): + if got == nil { + t.Error("expected error from send") + } + case <-time.After(time.Second): + t.Error("expected error on Errors() channel") + } +} + +func TestSendSuccess(t *testing.T) { + queue, err := NewQueue(context.Background(), 10, testConfig{}) + if err != nil { + t.Fatal(err) + } + queue.Start(1) + + if err := queue.Push(testNotification{}); err != nil { + t.Fatalf("push: %v", err) } + // Worker processes notification via send's happy-path (Send returns nil). + queue.Stop() } diff --git a/token/app.go b/token/app.go index ab967ac..f6241f1 100644 --- a/token/app.go +++ b/token/app.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/simpleauthlink/authapi/internal/base64url" + "go.k7z7z.cc/x/encoding/base64url" ) // App represents an application that can request tokens. It has a name, a @@ -16,32 +16,35 @@ type App struct { RedirectURI string SessionDuration time.Duration AppSecretHash []byte + Secret *Secret } // Valid method returns true if the app is valid, false otherwise. An app is // considered valid if its name is between 3 and 20 characters, its redirect // URI is a valid URI, and its session duration is between 5 minutes and 24 // hours. -func (app *App) Valid(secretHash []byte) bool { +func (app *App) Valid(secretHash []byte) error { if app == nil { - return false + return ErrInvalidApp } // check if the app name is between the min and max length if len(app.Name) < appNameMinLen || len(app.Name) > appNameMaxLen { - return false + return ErrInvalidAppName } // check if the redirect URI is valid if !uriRegexp.MatchString(app.RedirectURI) || len(app.RedirectURI) > redirectURIMaxLen { - return false + return ErrInvalidRedirectURI } // check if the session duration is between the min and max duration if app.SessionDuration < minDuration || app.SessionDuration > maxDuration { - return false + return ErrInvalidSessionDuration } if secretHash != nil { - return bytes.Equal(app.AppSecretHash, secretHash) + if !bytes.Equal(app.AppSecretHash, secretHash) { + return ErrInvalidSecret + } } - return true + return nil } // Attributes method returns the app's attributes as a slice of strings. This @@ -79,7 +82,7 @@ func (app *App) SetAttributes(attrs []string) *App { } app.AppSecretHash = appSecretHash // check if the app is valid and return it if it is - if !app.Valid(nil) { + if err := app.Valid(nil); err != nil { return nil } return app @@ -89,7 +92,7 @@ func (app *App) SetAttributes(attrs []string) *App { // and encoding the app. The resulting string is the app's attributes joined // by the app data separator. func (app *App) String() string { - if !app.Valid(nil) { + if err := app.Valid(nil); err != nil { return "" } // join the app's attributes with the app data separator @@ -121,7 +124,7 @@ func (app *App) SetBytes(data []byte) *App { // Marshal method returns the app as a base64-encoded byte slice. It is used // to be included in the app ID, which makes it self-contained. func (app *App) Marshal() []byte { - if !app.Valid(nil) { + if err := app.Valid(nil); err != nil { return nil } return base64url.RawEncode(app.Bytes()) @@ -142,7 +145,7 @@ func (app *App) Unmarshal(data []byte) *App { // created by encoding the app as a base64-encoded byte slice using the // Marshal method. func (app *App) ID(secret *Secret) *AppID { - if !app.Valid(secret.Hash()) { + if err := app.Valid(secret.Hash()); err != nil { return nil } return new(AppID).SetBytes(app.Marshal()) @@ -168,5 +171,6 @@ func (app *App) SetSecret(secret *Secret) *App { } // set the app secret hash app.AppSecretHash = secret.Hash() + app.Secret = secret return app } diff --git a/token/app_test.go b/token/app_test.go index a68acd0..408ac0f 100644 --- a/token/app_test.go +++ b/token/app_test.go @@ -21,47 +21,47 @@ func TestValidApp(t *testing.T) { RedirectURI: testRedirectURI, SessionDuration: testSessionDuration, } - if !app.Valid(nil) { + if err := app.Valid(nil); err != nil { t.Errorf("expected valid app data") } // test app name app.Name = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." - if app.Valid(nil) { + if err := app.Valid(nil); err == nil { t.Errorf("expected invalid app data") } app.Name = "no" - if app.Valid(nil) { + if err := app.Valid(nil); err == nil { t.Errorf("expected invalid app data") } app.Name = testAppName // test redirect URI app.RedirectURI = "https://example.com/login?app=lorem_ipsum_dolor_sit_amet_consectetur_adipiscing_elit_sed_do_eiusmod_tempor_incididunt_ut_labore_et_dolore_magna_aliqua" - if app.Valid(nil) { + if err := app.Valid(nil); err == nil { t.Errorf("expected invalid app data") } app.RedirectURI = "no_url" - if app.Valid(nil) { + if err := app.Valid(nil); err == nil { t.Errorf("expected invalid app data") } app.RedirectURI = testRedirectURI // test session duration app.SessionDuration = minDuration - 1 - if app.Valid(nil) { + if err := app.Valid(nil); err == nil { t.Errorf("expected invalid app data") } app.SessionDuration = maxDuration + 1 - if app.Valid(nil) { + if err := app.Valid(nil); err == nil { t.Errorf("expected invalid app data") } var nilApp *App - if nilApp.Valid(nil) { + if err := nilApp.Valid(nil); err == nil { t.Errorf("expected invalid app data") } app.AppSecretHash = testAppSecret.Hash() servicePart := []byte("invalid-service-secret") appPart := []byte("invalid-app-secret") invalidSecret := new(Secret).SetParts(servicePart, appPart) - if app.Valid(invalidSecret.Hash()) { + if err := app.Valid(invalidSecret.Hash()); err == nil { t.Errorf("expected invalid app data") } } diff --git a/token/errors.go b/token/errors.go index 287a594..3e01f9d 100644 --- a/token/errors.go +++ b/token/errors.go @@ -1,10 +1,11 @@ package token -import "fmt" +import "go.k7z7z.cc/x/errors" var ( - ErrInvalidAppID = fmt.Errorf("invalid app ID") - ErrInvalidAppName = fmt.Errorf("invalid app name") - ErrInvalidRedirectURI = fmt.Errorf("invalid redirect URI") - ErrInvalidSessionDuration = fmt.Errorf("invalid session duration") + ErrInvalidApp = errors.New("invalid app") + ErrInvalidAppName = errors.New("invalid app name") + ErrInvalidRedirectURI = errors.New("invalid redirect URI") + ErrInvalidSessionDuration = errors.New("invalid session duration") + ErrInvalidSecret = errors.New("invalid secret") ) diff --git a/token/expiration.go b/token/expiration.go index 302d1c2..1564f9f 100644 --- a/token/expiration.go +++ b/token/expiration.go @@ -3,7 +3,7 @@ package token import ( "time" - "github.com/simpleauthlink/authapi/internal/base64url" + "go.k7z7z.cc/x/encoding/base64url" ) // Expiration represents a time when a token expires. It is a wrapper around @@ -118,7 +118,7 @@ func (exp *Expiration) SetBytes(data []byte) *Expiration { // invalid, nil is returned. func (exp *Expiration) Marshal() []byte { bExp := exp.Bytes() - if len(bExp) == 0 || bExp[0] == 0 { + if len(bExp) == 0 { return nil } return base64url.RawEncode(bExp) diff --git a/token/id.go b/token/id.go index 3bab249..2e6ad86 100644 --- a/token/id.go +++ b/token/id.go @@ -5,9 +5,13 @@ import ( "crypto/hmac" "crypto/sha256" - "github.com/simpleauthlink/authapi/internal/base64url" + "go.k7z7z.cc/x/encoding/base64url" ) +// UserID represents the identifier for the user that is trying to generate or +// verify a token. It is a wrapper arund string. +type UserID string + // AppID represents an application ID that is used to generate and verify // tokens. It is a wrapper around a byte slice that provides additional // methods for setting and getting the application ID. @@ -45,7 +49,7 @@ func (id *AppID) Bytes() []byte { // valid, the application ID is not set and nil is returned. func (id *AppID) SetBytes(data []byte) *AppID { // check if the application ID is valid - if !new(App).Unmarshal(data).Valid(nil) { + if err := new(App).Unmarshal(data).Valid(nil); err != nil { return nil } // if no application ID is provided, create a new one @@ -75,7 +79,8 @@ func (id *AppID) PrivKey(secret Secret) ed25519.PrivateKey { return nil } hFn := hmac.New(sha256.New, secret.Bytes()) - hID := hFn.Sum(bID) + hFn.Write(bID) + hID := hFn.Sum(nil) return ed25519.NewKeyFromSeed(hID[:32]) } @@ -137,13 +142,13 @@ func (id *AppID) Verify(secret Secret, msg, sig []byte) bool { } // GenerateToken method returns a token for the application ID. If the app ID -// is nil, the secret is invalid, or the email is empty, nil is returned. It +// is nil, the secret is invalid, or the userID is empty, nil is returned. It // internally calls the Message method to generate the message for the token // and uses it to sign the message. The token is generated by hashing the -// application ID with the email and expiration time, and signing the result +// application ID with the userID and expiration time, and signing the result // with the secret. The signature is then used to create a token with the // expiration time and signature. -func (id *AppID) GenerateToken(secret Secret, email string) Token { +func (id *AppID) GenerateToken(secret Secret, userID UserID) Token { // check if the application ID is valid if id == nil { return nil @@ -155,8 +160,11 @@ func (id *AppID) GenerateToken(secret Secret, email string) Token { } // calculate the expiration time for the current app exp := new(Expiration).SetDuration(app.SessionDuration) + if exp == nil { + return nil + } // get the message to sign - msg := id.Message(email, *exp) + msg := id.Message(userID, *exp) // sign the message with the secret sig := id.Sign(secret, msg) // check if the signature is valid @@ -168,29 +176,29 @@ func (id *AppID) GenerateToken(secret Secret, email string) Token { } // Message method returns the message for the application ID. If the app ID -// is nil, the email is empty, or the expiration time is invalid, nil is +// is nil, the userID is empty, or the expiration time is invalid, nil is // returned. It is used to generate the message for the token by hashing the -// application ID with the email and expiration time. The message is generated -// by appending the application ID with the email and expiration time, and +// application ID with the userID and expiration time. The message is generated +// by appending the application ID with the userID and expiration time, and // hashing the result with sha256 to create a unique message for the token. -func (id *AppID) Message(email string, exp Expiration) []byte { +func (id *AppID) Message(userID UserID, exp Expiration) []byte { // check if the application ID is valid, the email is not empty, and the // expiration time is valid - if id == nil || len(email) == 0 || !exp.Valid() { + if id == nil || len(userID) == 0 || !exp.Valid() { return nil } // hash the application ID with the email and expiration time - hmsg := sha256.Sum256(append(append(id.Bytes(), []byte(email)...), exp.Bytes()...)) + hmsg := sha256.Sum256(append(append(id.Bytes(), []byte(userID)...), exp.Bytes()...)) return hmsg[:] } // VerifyToken method returns true if the token is valid for the application // ID. If the app ID is nil, the token is nil, the secret is invalid, or the -// email is empty, false is returned. It is used to verify the token by +// userID is empty, false is returned. It is used to verify the token by // checking that the expiration time is valid and the signature is correct. -// The token is verified by hashing the application ID with the email and +// The token is verified by hashing the application ID with the userID and // expiration time, and verifying the signature with the secret. -func (id *AppID) VerifyToken(token Token, secret Secret, email string) bool { +func (id *AppID) VerifyToken(token Token, secret Secret, userID UserID) bool { // check if the application ID is valid if id == nil { return false @@ -206,7 +214,7 @@ func (id *AppID) VerifyToken(token Token, secret Secret, email string) bool { return false } // get the message to verify - msg := id.Message(email, *exp) + msg := id.Message(userID, *exp) if len(msg) == 0 { return false } diff --git a/token/id_test.go b/token/id_test.go index 8419a2d..58deabc 100644 --- a/token/id_test.go +++ b/token/id_test.go @@ -129,15 +129,6 @@ func TestPrivKeySignVerifyAppID(t *testing.T) { } } -func TestMessage(t *testing.T) { - if privKey := new(AppID).PrivKey(*testAppSecret); privKey != nil { - t.Errorf("expected nil, got %v", privKey) - } - if sig := new(AppID).Sign(*testAppSecret, []byte("test data")); sig != nil { - t.Errorf("expected nil, got %v", sig) - } -} - func TestGenerateTokenVerifyToken(t *testing.T) { t.Parallel() var nilAppID *AppID @@ -163,45 +154,146 @@ func TestGenerateTokenVerifyToken(t *testing.T) { if id == nil { t.Fatalf("error decoding app ID") } - email := "test@email.com" - if id.VerifyToken([]byte{}, *testAppSecret, email) { + userID := UserID("test@email.com") + if id.VerifyToken([]byte{}, *testAppSecret, userID) { t.Errorf("expected token to be invalid") } dummyToken := new(Token).SetExpiration(*new(Expiration).SetDuration(minDuration * 3)) - if id.VerifyToken(*dummyToken, *testAppSecret, email) { + if id.VerifyToken(*dummyToken, *testAppSecret, userID) { t.Errorf("expected token to be invalid") } dummyToken = new(Token).SetSignature([]byte("test")) - if id.VerifyToken(*dummyToken, *testAppSecret, email) { + if id.VerifyToken(*dummyToken, *testAppSecret, userID) { t.Errorf("expected token to be invalid") } if invalidToken := id.GenerateToken(*testAppSecret, ""); invalidToken != nil { t.Fatalf("expected nil, got %v", invalidToken) } - token := id.GenerateToken(*testAppSecret, email) + token := id.GenerateToken(*testAppSecret, userID) if token == nil { t.Fatalf("error creating token") } if id.VerifyToken(token, *testAppSecret, "") { t.Errorf("expected token to be invalid") } - if !id.VerifyToken(token, *testAppSecret, email) { + if !id.VerifyToken(token, *testAppSecret, userID) { t.Errorf("expected token to be valid") } time.Sleep(app.SessionDuration + time.Second) - if id.VerifyToken(token, *testAppSecret, email) { + if id.VerifyToken(token, *testAppSecret, userID) { t.Errorf("expected token to be invalid") } - if id.VerifyToken(nil, *testAppSecret, email) { + if id.VerifyToken(nil, *testAppSecret, userID) { t.Errorf("expected token to be invalid") } exp := new(Expiration).SetDuration(minDuration) - if id.VerifyToken(exp.Marshal(), *testAppSecret, email) { + if id.VerifyToken(exp.Marshal(), *testAppSecret, userID) { t.Errorf("expected token to be invalid") } } +func TestTokenModificationRejected(t *testing.T) { + t.Parallel() + + servicePart := []byte("service-secret") + appPart := []byte("app-secret") + secret := new(Secret).SetParts(servicePart, appPart) + app := &App{ + Name: testAppName, + RedirectURI: testRedirectURI, + SessionDuration: minDuration, + } + app.SetSecret(secret) + id := app.ID(secret) + if id == nil { + t.Fatalf("error decoding app ID") + } + userID := UserID("test@email.com") + + token := id.GenerateToken(*secret, userID) + if token == nil { + t.Fatalf("error creating token") + } + if !id.VerifyToken(token, *secret, userID) { + t.Fatalf("original token should be valid") + } + + parts := bytes.Split([]byte(token.String()), []byte{tokenSeparator}) + if len(parts) != 2 { + t.Fatalf("expected 2 parts in token, got %d", len(parts)) + } + expPart, sigPart := string(parts[0]), string(parts[1]) + + if len(expPart) < 4 { + t.Fatalf("expiration part too short") + } + modifiedExp := string(expPart[0]) + string(expPart[1]) + "B" + expPart[3:] + modifiedToken1 := modifiedExp + string(tokenSeparator) + sigPart + tkn1 := new(Token).SetString(modifiedToken1) + if id.VerifyToken(*tkn1, *secret, userID) { + t.Errorf("modified expiration token should be invalid") + } + + if len(sigPart) < 30 { + t.Fatalf("signature part too short") + } + modifiedSig := sigPart[:28] + "f" + sigPart[29:] + modifiedToken2 := expPart + string(tokenSeparator) + modifiedSig + tkn2 := new(Token).SetString(modifiedToken2) + if id.VerifyToken(*tkn2, *secret, userID) { + t.Errorf("modified signature token should be invalid") + } +} + +func TestTokenCrossAppRejected(t *testing.T) { + t.Parallel() + + servicePart := []byte("service-secret") + + app1Part := []byte("app-one-secret") + secret1 := new(Secret).SetParts(servicePart, app1Part) + app1 := &App{ + Name: testAppName, + RedirectURI: testRedirectURI, + SessionDuration: minDuration, + } + app1.SetSecret(secret1) + id1 := app1.ID(secret1) + if id1 == nil { + t.Fatalf("error decoding app1 ID") + } + + app2Part := []byte("app-two-secret") + secret2 := new(Secret).SetParts(servicePart, app2Part) + app2 := &App{ + Name: "OtherApp", + RedirectURI: testRedirectURI, + SessionDuration: minDuration, + } + app2.SetSecret(secret2) + id2 := app2.ID(secret2) + if id2 == nil { + t.Fatalf("error decoding app2 ID") + } + + userID := UserID("test@email.com") + + token := id1.GenerateToken(*secret1, userID) + if token == nil { + t.Fatalf("error creating token") + } + if !id1.VerifyToken(token, *secret1, userID) { + t.Fatalf("original token should be valid for app1") + } + if id2.VerifyToken(token, *secret2, userID) { + t.Errorf("app1's token should be invalid for app2") + } + if id1.VerifyToken(token, *secret2, userID) { + t.Errorf("token should be invalid with wrong secret") + } +} + func Test_hedgedNonce(t *testing.T) { if res := hedgedNonce(); res != nil { t.Errorf("expected nil, got %v", res) diff --git a/token/secret.go b/token/secret.go index 9b54921..868eefb 100644 --- a/token/secret.go +++ b/token/secret.go @@ -4,8 +4,8 @@ import "crypto/sha256" // secretHashSize is the size of the secret hash. It is used to determine // the size of the secret when it is hashed. The hash is created by hashing -// the secret to a sha256 size. The hash is used to sign and verify tokens. -// The hash is also used to create the app ID and it is part of it. +// the secret to a sha256 size, but then it is truncated to 12 bytes. +// The hash is used to sign and verify tokens, and to create the app ID and it is part of it. const secretHashSize = 12 // Secret represents a secret that is used to sign and verify tokens. It is diff --git a/token/token_test.go b/token/token_test.go index 6b9c80a..e7ca1c7 100644 --- a/token/token_test.go +++ b/token/token_test.go @@ -140,7 +140,7 @@ func Test_partsToken(t *testing.T) { token = token.SetExpiration(*exp) rawExp, _, ok := token.parts() if !ok { - t.Errorf("expected false, got true") + t.Errorf("expected true, got false") } if !bytes.Equal(rawExp, exp.Marshal()) { t.Errorf("expected %v, got %v", exp.Marshal(), rawExp)