From 87da86087b66452087c1b185e67203469235bfbe Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Wed, 19 Aug 2026 19:44:16 +0200 Subject: [PATCH 1/9] initial inclusion of the user id (email) in the token it-self --- api/client/client.go | 23 +-- api/client/client_test.go | 133 +++--------------- api/handlers.go | 5 +- api/handlers_test.go | 10 +- api/service_test.go | 7 + api/types.go | 1 - .../email/templates/login/definition_test.go | 3 +- token/email.go | 43 ++++++ token/id.go | 35 +++-- token/id_test.go | 56 ++++---- token/token.go | 120 ++++++++++------ token/token_test.go | 28 +++- 12 files changed, 227 insertions(+), 237 deletions(-) create mode 100644 token/email.go diff --git a/api/client/client.go b/api/client/client.go index 6c6d56b..f3e3998 100644 --- a/api/client/client.go +++ b/api/client/client.go @@ -2,7 +2,6 @@ package client import ( "net/http" - "net/mail" "net/url" "time" @@ -21,7 +20,6 @@ const ( DefaultAuthTokenHeader = "X-Auth-Token" DefaultAuthEmailHeader = "X-Auth-User" DefaultAuthTokenURLParam = "token" - DefaultAuthEmailURLParam = "user" ) // Config holds the configuration for the client. It includes the API endpoint, @@ -241,7 +239,7 @@ func (c *Client) RequestToken(email string) error { // valid email format. If the token is valid, it returns true and the // expiration time. If the token is invalid or the email address is not valid, // it returns false. If the request fails, it also returns an error. -func (c *Client) VerifyToken(token *token.Token, email string) (bool, time.Time, error) { +func (c *Client) VerifyToken(token *token.Token) (bool, time.Time, error) { // validate the configuration before making the request, for this operation // the app ID and secret are required if err := c.config.Validate(true); err != nil { @@ -251,14 +249,9 @@ func (c *Client) VerifyToken(token *token.Token, email string) (bool, time.Time, if token == nil { return false, time.Time{}, ErrInvalidToken } - // check if the email is valid - if _, err := mail.ParseAddress(email); err != nil { - return false, time.Time{}, ErrInvalidEmailAddress - } // create the request with the token and email data data := &api.TokenStatusRequest{ Token: token.String(), - Email: email, } req, err := req(c.config, http.MethodPut, api.TokensPath, data) if err != nil { @@ -297,17 +290,16 @@ func (c *Client) AuthorizedRequestURLParams(r *http.Request) (string, bool, erro } // get the strToken and email from the request headers strToken := params.Get(DefaultAuthTokenURLParam) - userEmail := params.Get(DefaultAuthEmailURLParam) // check if the token and email are valid - if strToken == "" || userEmail == "" { + if strToken == "" { return "", false, ErrMissingAuthURLParams } userToken := new(token.Token).SetString(strToken) - valid, _, err := c.VerifyToken(userToken, userEmail) + valid, _, err := c.VerifyToken(userToken) if err != nil { return "", false, err } - return userEmail, valid, nil + return userToken.Email().String(), valid, nil } // AuthorizedRequestHeaders method checks if the request is authorized by @@ -323,17 +315,16 @@ func (c *Client) AuthorizedRequestHeaders(r *http.Request) (string, bool, error) } // get the strToken and email from the request headers strToken := r.Header.Get(DefaultAuthTokenHeader) - userEmail := r.Header.Get(DefaultAuthEmailHeader) // check if the token and email are valid - if strToken == "" || userEmail == "" { + if strToken == "" { return "", false, ErrMissingAuthHeaders } userToken := new(token.Token).SetString(strToken) - valid, _, err := c.VerifyToken(userToken, userEmail) + valid, _, err := c.VerifyToken(userToken) if err != nil { return "", false, err } - return userEmail, valid, nil + return userToken.Email().String(), valid, nil } // req internal method creates a new HTTP request with the provided config, diff --git a/api/client/client_test.go b/api/client/client_test.go index 0ce7185..71330f9 100644 --- a/api/client/client_test.go +++ b/api/client/client_test.go @@ -121,7 +121,7 @@ func TestSuccessFlow(t *testing.T) { t.Fatalf("failed to read token from email: %v", err) } // verify the token - valid, _, err := cli.VerifyToken(testToken, testEmail) + valid, _, err := cli.VerifyToken(testToken) if err != nil { t.Fatalf("failed to verify token: %v", err) } @@ -131,7 +131,7 @@ func TestSuccessFlow(t *testing.T) { // wait for the token to expire time.Sleep(testTimeout) // verify the token after expiration - valid, _, err = cli.VerifyToken(testToken, testEmail) + valid, _, err = cli.VerifyToken(testToken) if err != nil { t.Fatalf("failed to verify token after expiration: %v", err) } @@ -233,14 +233,14 @@ func TestNew(t *testing.T) { 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) - // } - // }) + 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) { @@ -446,8 +446,7 @@ func TestVerifyToken(t *testing.T) { if err != nil { t.Fatalf("failed to create client: %v", err) } - testEmail := randomEmail() - if _, _, err := cli.VerifyToken(nil, testEmail); err != ErrInvalidAppID { + if _, _, err := cli.VerifyToken(nil); err != ErrInvalidAppID { t.Fatalf("expected ErrInvalidAppID, got %v", err) } }) @@ -462,34 +461,11 @@ func TestVerifyToken(t *testing.T) { t.Fatalf("failed to create app ID: %v", err) } cli.SetupAppID(appID, testClientSecret) - testEmail := randomEmail() - if _, _, err := cli.VerifyToken(nil, testEmail); err != ErrInvalidToken { + if _, _, err := cli.VerifyToken(nil); err != ErrInvalidToken { t.Fatalf("expected ErrInvalidToken, got %v", err) } }) - t.Run("invalid email", 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) - testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { - t.Fatalf("failed to request token: %v", err) - } - testToken, err := readTokenFromEmail(t, testEmail) - if err != nil { - t.Fatalf("failed to read token from email: %v", err) - } - if _, _, err := cli.VerifyToken(testToken, ""); err != ErrInvalidEmailAddress { - t.Fatalf("expected ErrInvalidEmailAddress, got %v", err) - } - }) t.Run("request error", func(t *testing.T) { cli, err := New(&Config{APIEndpoint: testEndpoint}) if err != nil { @@ -510,7 +486,7 @@ func TestVerifyToken(t *testing.T) { } // invalid API endpoint cli.config.APIEndpoint = "http://nonexistent.host.issue" - if _, _, err := cli.VerifyToken(testToken, testEmail); err != ErrAPIUnavailable { + if _, _, err := cli.VerifyToken(testToken); err != ErrAPIUnavailable { t.Fatalf("expected ErrAPIUnavailable, got %v", err) } }) @@ -537,7 +513,7 @@ func TestVerifyToken(t *testing.T) { })) defer srv.Close() cli.config.APIEndpoint = srv.URL - if _, _, err := cli.VerifyToken(testToken, testEmail); err != io.ErrHTTPStatusNotOk { + if _, _, err := cli.VerifyToken(testToken); err != io.ErrHTTPStatusNotOk { t.Fatalf("expected ErrHTTPStatusNotOk, got %v", err) } }) @@ -559,7 +535,7 @@ func TestVerifyToken(t *testing.T) { if err != nil { t.Fatalf("failed to read token from email: %v", err) } - valid, expTime, err := cli.VerifyToken(testToken, testEmail) + valid, expTime, err := cli.VerifyToken(testToken) if err != nil { t.Fatalf("expected no error, got %v", err) } @@ -621,8 +597,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { t.Fatalf("failed to read token from email: %v", err) } reqURL, _ := url.Parse("http://example.com/test") - reqURL.RawQuery = fmt.Sprintf("%s=%s&%s=%s", - DefaultAuthEmailURLParam, testEmail, + reqURL.RawQuery = fmt.Sprintf("%s=%s", DefaultAuthTokenURLParam, testToken.String()) req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) @@ -662,37 +637,6 @@ func TestAuthorizedRequestURLParams(t *testing.T) { } }) - t.Run("invalid email in request params", func(t *testing.T) { - testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { - t.Fatalf("failed to request token: %v", err) - } - testToken, err := readTokenFromEmail(t, testEmail) - if err != nil { - t.Fatalf("failed to read token from email: %v", err) - } - invalidEmail := "noemail.com" - reqURL, _ := url.Parse("http://example.com/test") - reqURL.RawQuery = fmt.Sprintf("%s=%s&%s=%s", - DefaultAuthEmailURLParam, invalidEmail, - DefaultAuthTokenURLParam, testToken.String()) - - req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) - if err != nil { - t.Fatalf("failed to create request: %v", err) - } - email, valid, err := cli.AuthorizedRequestURLParams(req) - if err != ErrInvalidEmailAddress { - t.Fatalf("expected ErrInvalidEmailAddress, got %v", err) - } - if valid { - t.Fatal("expected token to be invalid") - } - if email != "" { - t.Fatalf("expected email to be empty, got %s", email) - } - }) - t.Run("invalid auth in request params", func(t *testing.T) { testEmail := randomEmail() if err := cli.RequestToken(testEmail); err != nil { @@ -704,8 +648,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { } otherEmail := "other@email.com" reqURL, _ := url.Parse("http://example.com/test") - reqURL.RawQuery = fmt.Sprintf("%s=%s&%s=%s", - DefaultAuthEmailURLParam, url.QueryEscape(otherEmail), + reqURL.RawQuery = fmt.Sprintf("%s=%s", DefaultAuthTokenURLParam, url.QueryEscape(testToken.String())) req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) @@ -716,11 +659,11 @@ func TestAuthorizedRequestURLParams(t *testing.T) { if err != nil { t.Fatalf("failed to get authorized request URL params: %v", err) } - if valid { + if !valid { t.Fatal("expected token to be invalid") } - if email != otherEmail { - t.Fatalf("expected email to be empty, got %s", email) + if email == otherEmail { + t.Fatalf("expected %s, got %s", email, otherEmail) } }) } @@ -785,35 +728,6 @@ func TestAuthorizedRequestHeaders(t *testing.T) { } }) - t.Run("invalid email in request headers", func(t *testing.T) { - testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { - t.Fatalf("failed to request token: %v", err) - } - testToken, err := readTokenFromEmail(t, testEmail) - if err != nil { - t.Fatalf("failed to read token from email: %v", err) - } - invalidEmail := "noemail.com" - - req, err := http.NewRequest(http.MethodGet, "http://example.com/test", nil) - if err != nil { - t.Fatalf("failed to create request: %v", err) - } - req.Header.Set(DefaultAuthEmailHeader, invalidEmail) - req.Header.Set(DefaultAuthTokenHeader, testToken.String()) - email, valid, err := cli.AuthorizedRequestHeaders(req) - if err != ErrInvalidEmailAddress { - t.Fatalf("expected ErrInvalidEmailAddress, got %v", err) - } - if valid { - t.Fatal("expected token to be invalid") - } - if email != "" { - t.Fatalf("expected email to be empty, got %s", email) - } - }) - t.Run("invalid auth in request headers", func(t *testing.T) { testEmail := randomEmail() if err := cli.RequestToken(testEmail); err != nil { @@ -828,17 +742,16 @@ func TestAuthorizedRequestHeaders(t *testing.T) { if err != nil { t.Fatalf("failed to create request: %v", err) } - req.Header.Set(DefaultAuthEmailHeader, otherEmail) req.Header.Set(DefaultAuthTokenHeader, testToken.String()) email, valid, err := cli.AuthorizedRequestHeaders(req) if err != nil { t.Fatalf("failed to get authorized request headers: %v", err) } - if valid { + if !valid { t.Fatal("expected token to be invalid") } - if email != otherEmail { - t.Fatalf("expected email to be empty, got %s", email) + if email == otherEmail { + t.Fatalf("expected %s, got %s", email, otherEmail) } }) } diff --git a/api/handlers.go b/api/handlers.go index ab120aa..f44f6ae 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -76,7 +76,8 @@ func (s *Service) requestTokenHandler(w http.ResponseWriter, r *http.Request) { switch { case req.Data.IsEmail(): // generate user genToken - genToken := appID.GenerateToken(*secret, token.UserID(req.Data.Email)) + userEmail := new(token.Email).SetString(req.Data.Email) + genToken := appID.GenerateToken(*secret, *userEmail) if genToken == nil { ErrGenerateToken.With(req.Data.Email).Write(w) return @@ -136,7 +137,7 @@ func (s *Service) verifyTokenHandler(w http.ResponseWriter, r *http.Request) { tkn := new(token.Token).SetString(req.Data.Token) exp := tkn.Expiration().Time() io.ResponseWith(&TokenStatusResponse{ - Valid: appID.VerifyToken(*tkn, *secret, token.UserID(req.Data.Email)), + Valid: appID.VerifyToken(*tkn, *secret), Expiration: exp, }).WriteJSON(w) } diff --git a/api/handlers_test.go b/api/handlers_test.go index f6cea26..9d6ea2e 100644 --- a/api/handlers_test.go +++ b/api/handlers_test.go @@ -250,7 +250,6 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { }, request: &TokenStatusRequest{ Token: testToken.String(), - Email: testUserEmail, }, response: &TokenStatusResponse{ Valid: true, @@ -260,8 +259,11 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { // invalid token tests testTokenStr := testToken.String() + if !testToken.Valid() { + t.Fatal("valid token expected") + } parts := bytes.Split([]byte(testTokenStr), []byte(".")) - if len(parts) != 2 { + if len(parts) != 3 { t.Fatalf("expected 2 token parts, got %d", len(parts)) } expPart, sigPart := string(parts[0]), string(parts[1]) @@ -270,7 +272,6 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { 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)) @@ -356,7 +357,6 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { }, request: &TokenStatusRequest{ Token: testToken.String(), - Email: testUserEmail, }, response: nil, err: ErrInvalidAppID, @@ -371,7 +371,6 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { }, request: &TokenStatusRequest{ Token: testToken.String(), - Email: testUserEmail, }, response: nil, err: ErrInvalidAppHeaders, @@ -383,7 +382,6 @@ func TestRequestTokenAndStatusHandler(t *testing.T) { endpoint: TokensPath, request: &TokenStatusRequest{ Token: testToken.String(), - Email: testUserEmail, }, response: nil, err: ErrInvalidAppHeaders, diff --git a/api/service_test.go b/api/service_test.go index 4739c38..4f3e184 100644 --- a/api/service_test.go +++ b/api/service_test.go @@ -166,6 +166,13 @@ func TestServiceStop(t *testing.T) { log.Fatal(err) } }() + // wait for the server to be up before pinging + for range 10 { + if tempSrv.Ping() { + break + } + time.Sleep(100 * time.Millisecond) + } // verify server is up if !tempSrv.Ping() { t.Error("server should be reachable after start") diff --git a/api/types.go b/api/types.go index 31dfce7..6e52caf 100644 --- a/api/types.go +++ b/api/types.go @@ -44,7 +44,6 @@ func (tr *TokenRequest) IsEmail() bool { type TokenStatusRequest struct { Token string `json:"token"` - Email string `json:"email"` } type TokenStatusResponse struct { diff --git a/notification/email/templates/login/definition_test.go b/notification/email/templates/login/definition_test.go index 9b1d9f1..620b5a9 100644 --- a/notification/email/templates/login/definition_test.go +++ b/notification/email/templates/login/definition_test.go @@ -54,7 +54,8 @@ func TestFindToken(t *testing.T) { appID := app.ID(secret) testEmail := "user@test.com" - testToken := appID.GenerateToken(*secret, token.UserID(testEmail)) + userID := new(token.Email).SetString(testEmail) + testToken := appID.GenerateToken(*secret, *userID) if testToken == nil { t.Fatal("failed to generate test token") } diff --git a/token/email.go b/token/email.go new file mode 100644 index 0000000..845498c --- /dev/null +++ b/token/email.go @@ -0,0 +1,43 @@ +package token + +import "go.k7z7z.cc/x/encoding/base64url" + +type Email []byte + +func (e *Email) SetBytes(bEmail []byte) *Email { + if e == nil { + e = new(Email) + } + *e = bEmail + return e +} + +func (e *Email) Bytes() []byte { + return *e +} + +func (e *Email) Marshal() []byte { + if e == nil { + return nil + } + return base64url.RawEncode(*e) +} + +func (e *Email) Unmarshal(raw []byte) *Email { + if e == nil { + e = new(Email) + } + dec, err := base64url.RawDecode(raw) + if err != nil { + return e + } + return e.SetBytes(dec) +} + +func (e *Email) SetString(email string) *Email { + return e.SetBytes([]byte(email)) +} + +func (e *Email) String() string { + return string(e.Bytes()) +} diff --git a/token/id.go b/token/id.go index 2e6ad86..168a256 100644 --- a/token/id.go +++ b/token/id.go @@ -8,10 +8,6 @@ import ( "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. @@ -142,13 +138,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 userID is empty, nil is returned. It +// is nil, the secret is invalid, or the email 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 userID and expiration time, and signing the result +// application ID with the email 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, userID UserID) Token { +func (id *AppID) GenerateToken(secret Secret, email Email) Token { // check if the application ID is valid if id == nil { return nil @@ -164,7 +160,7 @@ func (id *AppID) GenerateToken(secret Secret, userID UserID) Token { return nil } // get the message to sign - msg := id.Message(userID, *exp) + msg := id.Message(email, *exp) // sign the message with the secret sig := id.Sign(secret, msg) // check if the signature is valid @@ -172,37 +168,38 @@ func (id *AppID) GenerateToken(secret Secret, userID UserID) Token { return nil } // create a new token with the expiration time and signature - return *new(Token).SetExpiration(*exp).SetSignature(sig) + return *new(Token).SetExpiration(*exp).SetSignature(sig).SetEmail(email) } // Message method returns the message for the application ID. If the app ID -// is nil, the userID is empty, or the expiration time is invalid, nil is +// is nil, the email 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 userID and expiration time. The message is generated -// by appending the application ID with the userID and expiration time, and +// application ID with the email and expiration time. The message is generated +// by appending the application ID with the email and expiration time, and // hashing the result with sha256 to create a unique message for the token. -func (id *AppID) Message(userID UserID, exp Expiration) []byte { +func (id *AppID) Message(email Email, 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(userID) == 0 || !exp.Valid() { + if id == nil || len(email) == 0 || !exp.Valid() { return nil } // hash the application ID with the email and expiration time - hmsg := sha256.Sum256(append(append(id.Bytes(), []byte(userID)...), exp.Bytes()...)) + hmsg := sha256.Sum256(append(append(id.Bytes(), email.Bytes()...), 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 -// userID is empty, false is returned. It is used to verify the token by +// email 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 userID and +// The token is verified by hashing the application ID with the email and // expiration time, and verifying the signature with the secret. -func (id *AppID) VerifyToken(token Token, secret Secret, userID UserID) bool { +func (id *AppID) VerifyToken(token Token, secret Secret) bool { // check if the application ID is valid if id == nil { return false } + email := token.Email() // check if the expiration time is valid exp := token.Expiration() if exp == nil || !exp.Valid() { @@ -214,7 +211,7 @@ func (id *AppID) VerifyToken(token Token, secret Secret, userID UserID) bool { return false } // get the message to verify - msg := id.Message(userID, *exp) + msg := id.Message(*email, *exp) if len(msg) == 0 { return false } diff --git a/token/id_test.go b/token/id_test.go index 58deabc..12e480a 100644 --- a/token/id_test.go +++ b/token/id_test.go @@ -132,13 +132,13 @@ func TestPrivKeySignVerifyAppID(t *testing.T) { func TestGenerateTokenVerifyToken(t *testing.T) { t.Parallel() var nilAppID *AppID - if res := nilAppID.GenerateToken(nil, ""); res != nil { + if res := nilAppID.GenerateToken(nil, nil); res != nil { t.Errorf("expected nil, got %v", res) } - if nilAppID.VerifyToken(nil, *testAppSecret, "") { + if nilAppID.VerifyToken(nil, *testAppSecret) { t.Errorf("expected token to be invalid") } - if res := new(AppID).GenerateToken(nil, ""); res != nil { + if res := new(AppID).GenerateToken(nil, nil); res != nil { t.Errorf("expected nil, got %v", res) } app := &App{ @@ -154,41 +154,38 @@ func TestGenerateTokenVerifyToken(t *testing.T) { if id == nil { t.Fatalf("error decoding app ID") } - userID := UserID("test@email.com") - if id.VerifyToken([]byte{}, *testAppSecret, userID) { + if id.VerifyToken([]byte{}, *testAppSecret) { t.Errorf("expected token to be invalid") } dummyToken := new(Token).SetExpiration(*new(Expiration).SetDuration(minDuration * 3)) - if id.VerifyToken(*dummyToken, *testAppSecret, userID) { + if id.VerifyToken(*dummyToken, *testAppSecret) { t.Errorf("expected token to be invalid") } dummyToken = new(Token).SetSignature([]byte("test")) - if id.VerifyToken(*dummyToken, *testAppSecret, userID) { + if id.VerifyToken(*dummyToken, *testAppSecret) { t.Errorf("expected token to be invalid") } - if invalidToken := id.GenerateToken(*testAppSecret, ""); invalidToken != nil { + if invalidToken := id.GenerateToken(*testAppSecret, nil); invalidToken != nil { t.Fatalf("expected nil, got %v", invalidToken) } - token := id.GenerateToken(*testAppSecret, userID) + userID := new(Email).SetString("test@email.com") + 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, userID) { + if !id.VerifyToken(token, *testAppSecret) { t.Errorf("expected token to be valid") } time.Sleep(app.SessionDuration + time.Second) - if id.VerifyToken(token, *testAppSecret, userID) { + if id.VerifyToken(token, *testAppSecret) { t.Errorf("expected token to be invalid") } - if id.VerifyToken(nil, *testAppSecret, userID) { + if id.VerifyToken(nil, *testAppSecret) { t.Errorf("expected token to be invalid") } exp := new(Expiration).SetDuration(minDuration) - if id.VerifyToken(exp.Marshal(), *testAppSecret, userID) { + if id.VerifyToken(exp.Marshal(), *testAppSecret) { t.Errorf("expected token to be invalid") } } @@ -209,19 +206,19 @@ func TestTokenModificationRejected(t *testing.T) { if id == nil { t.Fatalf("error decoding app ID") } - userID := UserID("test@email.com") - - token := id.GenerateToken(*secret, userID) + + userID := new(Email).SetString("test@email.com") + token := id.GenerateToken(*secret, *userID) if token == nil { t.Fatalf("error creating token") } - if !id.VerifyToken(token, *secret, userID) { + if !id.VerifyToken(token, *secret) { 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)) + if len(parts) != numOfTokenParts { + t.Fatalf("expected %d parts in token, got %d", numOfTokenParts, len(parts)) } expPart, sigPart := string(parts[0]), string(parts[1]) @@ -231,7 +228,7 @@ func TestTokenModificationRejected(t *testing.T) { 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) { + if id.VerifyToken(*tkn1, *secret) { t.Errorf("modified expiration token should be invalid") } @@ -241,7 +238,7 @@ func TestTokenModificationRejected(t *testing.T) { modifiedSig := sigPart[:28] + "f" + sigPart[29:] modifiedToken2 := expPart + string(tokenSeparator) + modifiedSig tkn2 := new(Token).SetString(modifiedToken2) - if id.VerifyToken(*tkn2, *secret, userID) { + if id.VerifyToken(*tkn2, *secret) { t.Errorf("modified signature token should be invalid") } } @@ -277,19 +274,18 @@ func TestTokenCrossAppRejected(t *testing.T) { t.Fatalf("error decoding app2 ID") } - userID := UserID("test@email.com") - - token := id1.GenerateToken(*secret1, userID) + userID := new(Email).SetString("test@email.com") + token := id1.GenerateToken(*secret1, *userID) if token == nil { t.Fatalf("error creating token") } - if !id1.VerifyToken(token, *secret1, userID) { + if !id1.VerifyToken(token, *secret1) { t.Fatalf("original token should be valid for app1") } - if id2.VerifyToken(token, *secret2, userID) { + if id2.VerifyToken(token, *secret2) { t.Errorf("app1's token should be invalid for app2") } - if id1.VerifyToken(token, *secret2, userID) { + if id1.VerifyToken(token, *secret2) { t.Errorf("token should be invalid with wrong secret") } } diff --git a/token/token.go b/token/token.go index ce90604..43a3554 100644 --- a/token/token.go +++ b/token/token.go @@ -2,12 +2,31 @@ package token import "bytes" +const numOfTokenParts = 3 + +var emypyToken = bytes.Join(make([][]byte, numOfTokenParts), []byte{tokenSeparator}) + // Token is a type that represents a user token. It is a wrapper around a byte // slice that provides additional methods for setting and getting the token. It // should have 2 parts, the first part is the expiration time, and the second // part is the signature. type Token []byte +func (t *Token) Valid() bool { + if t == nil { + return false + } + _, _, _, ok := t.split() + switch { + case !ok: + return false + case t.Expiration() == nil || t.Signature() == nil || t.Email() == nil: + return false + default: + return true + } +} + // String method returns the token as a string. It is useful for encoding the // token. If the token is nil, an empty string is returned. It internally calls // the Bytes method to get the token as a byte slice. @@ -15,6 +34,9 @@ func (t *Token) String() string { if t == nil { return "" } + if bytes.Equal(emypyToken, t.Bytes()) { + return "" + } return string(t.Bytes()) } @@ -40,11 +62,11 @@ func (t *Token) Bytes() []byte { return nil } // check if the token has valid parts - if _, _, ok := t.parts(); !ok { + if _, _, _, ok := t.split(); !ok { return nil } // return the token as a byte slice - return []byte(*t) + return *t } // SetBytes method sets the token from a byte slice. It is useful for @@ -62,7 +84,7 @@ func (t *Token) SetBytes(data []byte) *Token { ntoken := &Token{} *ntoken = data // check if the new token has valid parts - if _, _, ok := ntoken.parts(); !ok { + if _, _, _, ok := ntoken.split(); !ok { return t } // set the token to the new token @@ -76,10 +98,11 @@ func (t *Token) SetBytes(data []byte) *Token { // signature as byte slices. It checks that the expiration time is valid before // returning it. func (t *Token) Expiration() *Expiration { - if rawExp, _, ok := t.parts(); ok { - return new(Expiration).Unmarshal(rawExp) + rawExp, _, _, ok := t.split() + if rawExp == nil || !ok { + return nil } - return nil + return new(Expiration).Unmarshal(rawExp) } // SetExpiration method sets the token's expiration time. If the token is nil, @@ -88,32 +111,18 @@ func (t *Token) Expiration() *Expiration { // time with the new expiration time. It checks that the expiration time is // valid before setting it. func (t *Token) SetExpiration(exp Expiration) *Token { - // if no token is provided, create a new one - if t == nil { - t = new(Token) - } - // if expiration is invalid, return the current token - if !exp.Valid() { - return t - } - // create a base content with the new expiration and no signature - baseContent := append(exp.Marshal(), tokenSeparator) - // get the current signature, if there is one, return a token with the - // base content and no signature - sig := t.Signature() - if sig == nil { - return t.SetBytes(baseContent) - } - // if there is a signature, update the token to replace the expiration - // part with the new expiration - return t.SetBytes(append(baseContent, sig...)) + return t.join([][]byte{ + exp.Marshal(), + t.Signature(), + t.Email().Marshal(), + }) } // Signature method returns the token's signature. If the token is nil, nil is // returned. It internally calls the parts method to get the signature part as // byte slices. func (t *Token) Signature() []byte { - _, sig, _ := t.parts() + _, sig, _, _ := t.split() return sig } @@ -122,34 +131,53 @@ func (t *Token) Signature() []byte { // internally calls the parts method to replace the token's signature with // the new signature. func (t *Token) SetSignature(sig []byte) *Token { - // if no token is provided, create a new one - if t == nil { - t = new(Token) - } - // create a base content with no expiration and the new signature - baseContent := append([]byte{tokenSeparator}, sig...) - // get the current expiration, if there is none, return a token with the - // base content and no expiration - exp := t.Expiration() - if exp == nil { - return t.SetBytes(baseContent) + return t.join([][]byte{ + t.Expiration().Marshal(), + sig, + t.Email().Marshal(), + }) +} + +func (t *Token) Email() *Email { + _, _, rawEmail, ok := t.split() + if rawEmail == nil || !ok { + return nil } - // if there is an expiration, update the token to replace the signature - // part with the new signature - return t.SetBytes(append(exp.Marshal(), baseContent...)) + return new(Email).Unmarshal(rawEmail) +} + +func (t *Token) SetEmail(email Email) *Token { + return t.join([][]byte{ + t.Expiration().Marshal(), + t.Signature(), + email.Marshal(), + }) } -// parts private method returns the token's expiration time and signature as +// split private method returns the token's expiration time and signature as // byte slices. It also returns a boolean indicating if the token has valid // parts. If the token is nil, or the parts are invalid, the parts are nil and // the boolean is false. It splits the token by the token separator and checks // that the result has 2 parts (expiration time and signature). -func (t *Token) parts() ([]byte, []byte, bool) { +func (t *Token) split() ([]byte, []byte, []byte, bool) { if t == nil { - return nil, nil, false + return nil, nil, nil, false } - if p := bytes.Split([]byte(*t), []byte{tokenSeparator}); len(p) == 2 { - return p[0], p[1], true + p := bytes.Split([]byte(*t), []byte{tokenSeparator}) + if len(p) != numOfTokenParts { + return nil, nil, nil, false + } + return p[0], p[1], p[2], true +} + +func (t *Token) join(parts [][]byte) *Token { + // if no token is provided, create a new one + if t == nil { + t = new(Token) + } + if len(parts) != numOfTokenParts { + return t } - return nil, nil, false + content := bytes.Join(parts, []byte{tokenSeparator}) + return t.SetBytes(content) } diff --git a/token/token_test.go b/token/token_test.go index e7ca1c7..2d1dbe5 100644 --- a/token/token_test.go +++ b/token/token_test.go @@ -17,19 +17,25 @@ func TestStringSetStringToken(t *testing.T) { t.Errorf("expected empty string, got %s", token.String()) } exp := new(Expiration).SetDuration(minDuration * 2) - expected := string(exp.Marshal()) + string(tokenSeparator) + expected := string(exp.Marshal()) + string(tokenSeparator) + string(tokenSeparator) token.SetString(expected) if token.String() != expected { t.Errorf("expected %s, got %s", expected, token.String()) } - expected = string(tokenSeparator) + "testSignature" + expected = string(tokenSeparator) + "testSignature" + string(tokenSeparator) token.SetString(expected) if token.String() != expected { t.Errorf("expected %s, got %s", expected, token.String()) } - expected = string(exp.Marshal()) + string(tokenSeparator) + "testSignature" + expected = string(exp.Marshal()) + string(tokenSeparator) + "testSignature" + string(tokenSeparator) + token.SetString(expected) + if token.String() != expected { + t.Errorf("expected %s, got %s", expected, token.String()) + } + + expected = string(exp.Marshal()) + string(tokenSeparator) + "testSignature" + string(tokenSeparator) + "testEmail" token.SetString(expected) if token.String() != expected { t.Errorf("expected %s, got %s", expected, token.String()) @@ -48,18 +54,28 @@ func TestBytesSetBytesToken(t *testing.T) { } exp := new(Expiration).SetDuration(minDuration * 2) onlyExp := append(exp.Marshal(), tokenSeparator) + onlyExp = append(onlyExp, tokenSeparator) token.SetBytes(onlyExp) if !bytes.Equal(token.Bytes(), onlyExp) { t.Errorf("expected %v, got %v", onlyExp, token.Bytes()) } onlySign := append([]byte{tokenSeparator}, []byte("testSignature")...) + onlySign = append(onlySign, tokenSeparator) token.SetBytes(onlySign) if !bytes.Equal(token.Bytes(), onlySign) { t.Errorf("expected %v, got %v", onlySign, token.Bytes()) } + onlyExpAndSign := append(append(exp.Marshal(), tokenSeparator), []byte("testSignature")...) + onlyExpAndSign = append(onlyExpAndSign, tokenSeparator) + token.SetBytes(onlyExpAndSign) + if !bytes.Equal(token.Bytes(), onlyExpAndSign) { + t.Errorf("expected %v, got %v", onlyExpAndSign, token.Bytes()) + } + fullToken := append(append(exp.Marshal(), tokenSeparator), []byte("testSignature")...) + fullToken = append(append(fullToken, tokenSeparator), []byte("testEmail")...) token.SetBytes(fullToken) if !bytes.Equal(token.Bytes(), fullToken) { t.Errorf("expected %v, got %v", fullToken, token.Bytes()) @@ -133,12 +149,12 @@ func TestSignatureSetSignatureToken(t *testing.T) { func Test_partsToken(t *testing.T) { var token *Token - if _, _, ok := token.parts(); ok { + if _, _, _, ok := token.split(); ok { t.Errorf("expected false, got true") } exp := new(Expiration).SetDuration(minDuration * 2) token = token.SetExpiration(*exp) - rawExp, _, ok := token.parts() + rawExp, _, _, ok := token.split() if !ok { t.Errorf("expected true, got false") } @@ -146,7 +162,7 @@ func Test_partsToken(t *testing.T) { t.Errorf("expected %v, got %v", exp.Marshal(), rawExp) } token.SetSignature([]byte("test")) - rawExp, sign, ok := token.parts() + rawExp, sign, _, ok := token.split() if !ok { t.Errorf("expected true, got false") } From 1f540947d81fac4bac67a6aa8633d16da5569ca8 Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Wed, 19 Aug 2026 22:22:23 +0200 Subject: [PATCH 2/9] api documentation --- .github/workflows/swagger.yml | 108 ++++++++++++++++++++++++++++++++++ api/{service.go => api.go} | 50 +++++++++++++--- api/client/client_test.go | 1 + api/handlers.go | 61 +++++++++++++++++-- docs/swagger.yaml | 0 scripts/generate-swagger.sh | 27 +++++++++ 6 files changed, 234 insertions(+), 13 deletions(-) create mode 100644 .github/workflows/swagger.yml rename api/{service.go => api.go} (72%) create mode 100644 docs/swagger.yaml create mode 100755 scripts/generate-swagger.sh diff --git a/.github/workflows/swagger.yml b/.github/workflows/swagger.yml new file mode 100644 index 0000000..185037e --- /dev/null +++ b/.github/workflows/swagger.yml @@ -0,0 +1,108 @@ +name: API Swagger Docs + +on: + push: + branches: + - main + paths-ignore: + - "docs/swagger.yaml" + pull_request: + paths: + - "api/**/*" + - "scripts/generate-swagger.sh" + +jobs: + api-swagger: + name: Generate swagger.yaml + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-go@v7 + with: + go-version-file: "go.mod" + cache: false + + - name: Make swagger.yaml + run: ./scripts/generate-swagger.sh + + - name: Publish Artifact + uses: actions/upload-artifact@v7 + with: + name: swagger.yaml + path: docs/swagger.yaml + + - name: Check if there is a difference + uses: mathiasvr/command-output@v2.0.0 + id: diff + with: + run: git diff --no-color docs/swagger.yaml + + - name: Mark previous comment as outdated if no diff + if: ${{ github.event_name == 'pull_request' && steps.diff.outputs.stdout == '' }} + uses: marocchino/sticky-pull-request-comment@v3 + with: + header: diff + hide: true + hide_classify: "OUTDATED" + + - name: Post comment with diff in original PR + if: ${{ github.event_name == 'pull_request' && steps.diff.outputs.stdout }} + uses: marocchino/sticky-pull-request-comment@v3 + with: + header: diff + message: | + This PR introduces the following changes in the API documentation: + ```diff + ${{ steps.diff.outputs.stdout }} + ``` + + - name: Commit and push if stage is outdated + if: ${{ github.event_name == 'push' && steps.diff.outputs.stdout }} + run: | + git config user.name "github-actions" + git config user.email "github-actions@users.noreply.github.com" + git add docs/swagger.yaml + git commit -m "ci: regenerate swagger.yaml after merge" + git push + + deploy-pages: + name: Deploy Swagger UI to GitHub Pages + needs: api-swagger + if: github.event_name == 'push' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + concurrency: + group: pages + cancel-in-progress: false + + steps: + - uses: actions/checkout@v7 + + - name: Overwrite docs/swagger.yaml with the freshly generated spec + uses: actions/download-artifact@v4 + with: + name: swagger.yaml + path: docs + + - uses: actions/configure-pages@v6 + + - name: Upload docs/ (Swagger UI + spec) + uses: actions/upload-pages-artifact@v3 + with: + path: docs + + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 diff --git a/api/service.go b/api/api.go similarity index 72% rename from api/service.go rename to api/api.go index dc134ac..39a93cc 100644 --- a/api/service.go +++ b/api/api.go @@ -1,3 +1,37 @@ +// Package api provides the HTTP API for the SimpleAuth.link service. +// +// @title SimpleAuth.link API +// @version 1.0 +// @description Passwordless authentication API for your users using just an email address. +// +// @contact.name API Support +// @contact.url https://simpleauth.link +// @contact.email info@simpleauth.link +// +// @license.name AGPL-3.0 +// @license.url https://github.com/SimpleAuthLink/authapi/blob/main/LICENSE +// +// @host api.simpleauth.link +// @BasePath / +// @schemes https +// +// @securityDefinitions.apikey AppID +// @in header +// @name AppID +// +// @securityDefinitions.apikey AppSecret +// @in header +// @name AppSecret +// +// @tag.name apps +// @tag.description Create and manage your App +// @tag.docs.url https://docs.simpleauth.link/about/apps +// @tag.docs.description About Apps +// +// @tag.name tokens +// @tag.description Request and verify tokens +// @tag.docs.url https://docs.simpleauth.link/about/tokens +// @tag.docs.description About Tokens package api import ( @@ -21,13 +55,13 @@ type Config struct { Secret string } -// Service struct represents the API service. It contains the context, cancel +// APIService struct represents the API service. It contains the context, cancel // 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 { +type APIService struct { ctx context.Context cancel context.CancelFunc cfg *Config @@ -36,7 +70,7 @@ type Service struct { *http.Server } -// New function creates a new service instance. It takes a context, a config +// New function creates a new api 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. @@ -44,10 +78,10 @@ type Service struct { // 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) { +func New(ctx context.Context, cfg *Config, nq *notification.Queue) (*APIService, error) { internalCtx, cancel := context.WithCancel(ctx) // create the service - srv := &Service{ + srv := &APIService{ ctx: internalCtx, cancel: cancel, cfg: cfg, @@ -79,7 +113,7 @@ func New(ctx context.Context, cfg *Config, nq *notification.Queue) (*Service, er } // Start method starts the service by starting the http server. -func (s *Service) Start() error { +func (s *APIService) Start() error { // start the api server if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed { return err @@ -89,7 +123,7 @@ func (s *Service) Start() error { // Stop method stops the service. It cancels the context and waits for the // background processes to finish. It also closes the http server. -func (s *Service) Stop() error { +func (s *APIService) Stop() error { // cancel the context and wait for the background processes finish s.cancel() if err := s.Close(); err != nil { @@ -102,7 +136,7 @@ func (s *Service) Stop() error { // to the health check endpoint and returns true if the response status code // is 200 OK, otherwise it returns false. If something goes wrong during the // process, it returns false. -func (s *Service) Ping() bool { +func (s *APIService) Ping() bool { url := fmt.Sprintf("http://%s:%d%s", s.cfg.Server, s.cfg.ServerPort, HealthCheckPath) request, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { diff --git a/api/client/client_test.go b/api/client/client_test.go index 71330f9..ca7660c 100644 --- a/api/client/client_test.go +++ b/api/client/client_test.go @@ -120,6 +120,7 @@ func TestSuccessFlow(t *testing.T) { if err != nil { t.Fatalf("failed to read token from email: %v", err) } + log.Print(testToken.String()) // verify the token valid, _, err := cli.VerifyToken(testToken) if err != nil { diff --git a/api/handlers.go b/api/handlers.go index f44f6ae..21af21b 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -17,7 +17,18 @@ import ( // generate tokens. It is created by encoding the app as a base64-encoded // byte slice resulting in concatenating the app name, redirect uri, and // session duration. -func (s *Service) generateAppIDHandler(w http.ResponseWriter, r *http.Request) { +// +// @Summary Create an App +// @Description Create an App with a provided secret and get the AppID to +// @Description be used to generate tokens for your users. +// @Tags apps +// @Accept json +// @Produce json +// @Param request body api.AppIDRequest true "App ID Request" +// @Success 200 {object} api.AppIDResponse +// @Failure 400 {object} io.APIError +// @Router /apps [post] +func (s *APIService) 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 { @@ -38,7 +49,7 @@ func (s *Service) generateAppIDHandler(w http.ResponseWriter, r *http.Request) { io.ResponseWith(&AppIDResponse{app.ID(app.Secret).String()}).WriteJSON(w) } -func (s *Service) appAndSecretFromRequest(r *http.Request) (*token.App, *token.Secret, *io.APIError) { +func (s *APIService) 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 { @@ -59,7 +70,26 @@ func (s *Service) appAndSecretFromRequest(r *http.Request) (*token.App, *token.S return app, secret, nil } -func (s *Service) requestTokenHandler(w http.ResponseWriter, r *http.Request) { +// requestTokenHandler handles the request to request a new token for a +// given user email address. It takes the AppID and the AppSecret from the +// request headers, and the user email from the request body, encoded into +// a TokenRequest struct. It validates the input data, generates the user +// token with the user email address and send to it the resulting token. +// +// @Summary Request a new token for the user +// @Description Using the AppID and the AppSecret, request a new token for +// @Description an user using its email address. The user will receive the +// @Description session token via email to that address. +// @Tags tokens +// @Accept json +// @Security AppID && AppSecret +// @Produce json +// @Param request body api.TokenRequest true "Token Request" +// @Success 200 +// @Failure 400 {object} io.APIError +// @Failure 500 {object} io.APIError +// @Router /tokens [post] +func (s *APIService) requestTokenHandler(w http.ResponseWriter, r *http.Request) { app, secret, err := s.appAndSecretFromRequest(r) if err != nil { err.Write(w) @@ -120,7 +150,22 @@ func (s *Service) requestTokenHandler(w http.ResponseWriter, r *http.Request) { io.OkResponse().WriteJSON(w) } -func (s *Service) verifyTokenHandler(w http.ResponseWriter, r *http.Request) { +// verifyTokenHandler handles the a token verification request. It takes the +// AppID and the AppSecret from the request headers. It validates the token +// for the given app configuration and check the token expiration. +// +// @Summary Verify a user token +// @Description Check that the provided token is valid for the AppID and +// @Description secret. +// @Tags tokens +// @Accept json +// @Produce json +// @Security AppID && AppSecret +// @Param request body api.TokenStatusRequest true "Token Request" +// @Success 200 {object} api.TokenStatusResponse +// @Failure 400 {object} io.APIError +// @Router /tokens [put] +func (s *APIService) verifyTokenHandler(w http.ResponseWriter, r *http.Request) { app, secret, err := s.appAndSecretFromRequest(r) if err != nil { err.Write(w) @@ -142,6 +187,12 @@ func (s *Service) verifyTokenHandler(w http.ResponseWriter, r *http.Request) { }).WriteJSON(w) } -func (s *Service) healthCheckHandler(w http.ResponseWriter, r *http.Request) { +// healthCheckHandler handles the ping request. +// +// @Summary Ping endpoint +// @Description Use this endpoint to ensure that the service is up. +// @Success 200 +// @Router /ping [get] +func (s *APIService) healthCheckHandler(w http.ResponseWriter, r *http.Request) { io.OkResponse().Write(w) } diff --git a/docs/swagger.yaml b/docs/swagger.yaml new file mode 100644 index 0000000..e69de29 diff --git a/scripts/generate-swagger.sh b/scripts/generate-swagger.sh new file mode 100755 index 0000000..6d2f811 --- /dev/null +++ b/scripts/generate-swagger.sh @@ -0,0 +1,27 @@ +#!/bin/bash +SWAG_VERSION=v1.16.6 +# Check if swag is installed, if not install it +if ! (swag --version | grep -q "^swag version ${SWAG_VERSION}$") ; then + echo "swag not found, installing..." + go install github.com/swaggo/swag/cmd/swag@${SWAG_VERSION} + [ $? -ne 0 ] && echo "Error: swag installation failed." && exit 1 + echo "swag installed successfully." +fi + +# Create docs package directory if it doesn't exist +mkdir -p docs +rm -f docs/swagger.yaml + +# Generate Swagger documentation from code comments +echo "Running swag..." +swag fmt -d ./ +go mod download +swag init -g api/api.go -o docs --outputTypes yaml --parseDependency --parseInternal --parseDepth=4 + +# Check if the swagger.yaml file was generated +if [ -f docs/swagger.yaml ]; then + echo "Swagger documentation generated successfully at docs/swagger.yaml" +else + echo "Error: swagger.yaml was not generated." + exit 1 +fi \ No newline at end of file From 57da4551edd754fe9deeccd0d9ad99dd5ab0fc01 Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Wed, 19 Aug 2026 22:53:06 +0200 Subject: [PATCH 3/9] initial dockerfile --- Dockerfile | 35 +++++++++++++++++++++++++++ api/api.go | 27 ++++++++++++++------- api/handlers.go | 6 ++--- scripts/generate-swagger.sh | 47 ++++++++++++++++++++----------------- 4 files changed, 82 insertions(+), 33 deletions(-) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f4a94ca --- /dev/null +++ b/Dockerfile @@ -0,0 +1,35 @@ +# syntax=docker/dockerfile:1 + +FROM golang:1.26-bookworm AS build + +WORKDIR /src + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . + +ARG TARGETOS +ARG TARGETARCH + +RUN CGO_ENABLED=0 \ + GOOS=${TARGETOS:-linux} \ + GOARCH=${TARGETARCH:-amd64} \ + go build \ + -trimpath \ + -ldflags="-s -w" \ + -o /out/api \ + ./cmd/authapi + + +FROM gcr.io/distroless/static-debian13:nonroot + +WORKDIR /app + +COPY --from=build --chown=nonroot:nonroot /out/api /app/api + +EXPOSE 8080 + +USER nonroot:nonroot + +ENTRYPOINT ["/app/api"] \ No newline at end of file diff --git a/api/api.go b/api/api.go index 39a93cc..8238034 100644 --- a/api/api.go +++ b/api/api.go @@ -11,17 +11,18 @@ // @license.name AGPL-3.0 // @license.url https://github.com/SimpleAuthLink/authapi/blob/main/LICENSE // -// @host api.simpleauth.link -// @BasePath / -// @schemes https +// @servers.url https://api.simpleauth.link +// @servers.description Production // -// @securityDefinitions.apikey AppID -// @in header -// @name AppID +// @servers.url https://demo.simpleauth.link +// @servers.description Demo // -// @securityDefinitions.apikey AppSecret -// @in header -// @name AppSecret +// @servers.url {scheme}://{host} +// @servers.description Custom +// @servers.variables.enum scheme https +// @servers.variables.enum scheme http +// @servers.variables.default scheme https +// @servers.variables.default host api.simpleauth.link // // @tag.name apps // @tag.description Create and manage your App @@ -34,6 +35,14 @@ // @tag.docs.description About Tokens package api +// @securityDefinitions.apikey AppID +// @in header +// @name AppID + +// @securityDefinitions.apikey AppSecret +// @in header +// @name AppSecret + import ( "context" "fmt" diff --git a/api/handlers.go b/api/handlers.go index 21af21b..b78f118 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -78,12 +78,12 @@ func (s *APIService) appAndSecretFromRequest(r *http.Request) (*token.App, *toke // // @Summary Request a new token for the user // @Description Using the AppID and the AppSecret, request a new token for -// @Description an user using its email address. The user will receive the +// @Description a user using its email address. The user will receive the // @Description session token via email to that address. // @Tags tokens // @Accept json -// @Security AppID && AppSecret // @Produce json +// @Security AppID || AppSecret // @Param request body api.TokenRequest true "Token Request" // @Success 200 // @Failure 400 {object} io.APIError @@ -160,7 +160,7 @@ func (s *APIService) requestTokenHandler(w http.ResponseWriter, r *http.Request) // @Tags tokens // @Accept json // @Produce json -// @Security AppID && AppSecret +// @Security AppID || AppSecret // @Param request body api.TokenStatusRequest true "Token Request" // @Success 200 {object} api.TokenStatusResponse // @Failure 400 {object} io.APIError diff --git a/scripts/generate-swagger.sh b/scripts/generate-swagger.sh index 6d2f811..3013b60 100755 --- a/scripts/generate-swagger.sh +++ b/scripts/generate-swagger.sh @@ -1,27 +1,32 @@ #!/bin/bash -SWAG_VERSION=v1.16.6 -# Check if swag is installed, if not install it -if ! (swag --version | grep -q "^swag version ${SWAG_VERSION}$") ; then - echo "swag not found, installing..." - go install github.com/swaggo/swag/cmd/swag@${SWAG_VERSION} - [ $? -ne 0 ] && echo "Error: swag installation failed." && exit 1 - echo "swag installed successfully." -fi -# Create docs package directory if it doesn't exist +set -euo pipefail + +SWAG_VERSION="v2.0.0-rc5" +SWAG="github.com/swaggo/swag/v2/cmd/swag@${SWAG_VERSION}" + +echo "Downloading Go dependencies..." +go vet ./... + +echo "Formatting Swagger annotations..." +go run "$SWAG" fmt -d ./ + +echo "Generating OpenAPI 3.1 documentation..." mkdir -p docs rm -f docs/swagger.yaml -# Generate Swagger documentation from code comments -echo "Running swag..." -swag fmt -d ./ -go mod download -swag init -g api/api.go -o docs --outputTypes yaml --parseDependency --parseInternal --parseDepth=4 - -# Check if the swagger.yaml file was generated -if [ -f docs/swagger.yaml ]; then - echo "Swagger documentation generated successfully at docs/swagger.yaml" -else - echo "Error: swagger.yaml was not generated." +go run "$SWAG" init \ + --v3.1 \ + --generalInfo api/api.go \ + --output docs \ + --outputTypes yaml \ + --parseDependency \ + --parseInternal \ + --parseDepth 4 + +if [ ! -f docs/swagger.yaml ]; then + echo "Error: docs/swagger.yaml was not generated." >&2 exit 1 -fi \ No newline at end of file +fi + +echo "OpenAPI documentation generated successfully at docs/openapi.yaml" \ No newline at end of file From 3b8344ce71979a0658ce8e0f23f9b38084d515d4 Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Thu, 20 Aug 2026 13:38:37 +0200 Subject: [PATCH 4/9] email comments and tests --- token/email.go | 13 ++++++++ token/email_test.go | 79 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 token/email_test.go diff --git a/token/email.go b/token/email.go index 845498c..cc00e4e 100644 --- a/token/email.go +++ b/token/email.go @@ -2,8 +2,12 @@ package token import "go.k7z7z.cc/x/encoding/base64url" +// Email type wraps a byte slice to handle an user email regarding the token +// generation, managment and validation. type Email []byte +// SetBytes method writes a byte slice to the current Email type instance. If +// a nil email is used, it is initialized. func (e *Email) SetBytes(bEmail []byte) *Email { if e == nil { e = new(Email) @@ -12,10 +16,13 @@ func (e *Email) SetBytes(bEmail []byte) *Email { return e } +// Bytes method return the byte slice value of the current Email type. func (e *Email) Bytes() []byte { return *e } +// Marshal method encodes the current email using a url safe version of base64 +// encoding. func (e *Email) Marshal() []byte { if e == nil { return nil @@ -23,6 +30,9 @@ func (e *Email) Marshal() []byte { return base64url.RawEncode(*e) } +// Unmarshal method decodes the base64 encoded email into a Email type +// instance. If the current email is not initialized, it is initialized +// first. If decoding fails, it returns the current Email instance instead. func (e *Email) Unmarshal(raw []byte) *Email { if e == nil { e = new(Email) @@ -34,10 +44,13 @@ func (e *Email) Unmarshal(raw []byte) *Email { return e.SetBytes(dec) } +// SetString method rites the stirng input as byte slice to the current Email +// type instance. It wraps the SetBytes method. func (e *Email) SetString(email string) *Email { return e.SetBytes([]byte(email)) } +// String method return the string value of the current Email type. func (e *Email) String() string { return string(e.Bytes()) } diff --git a/token/email_test.go b/token/email_test.go new file mode 100644 index 0000000..2bbe3ec --- /dev/null +++ b/token/email_test.go @@ -0,0 +1,79 @@ +package token + +import ( + "bytes" + "testing" + + "go.k7z7z.cc/x/encoding/base64url" +) + +func TestEmailBytes(t *testing.T) { + testEmail := []byte("user@example.com") + t.Run("existing email pointer", func(t *testing.T) { + email := new(Email).SetBytes(testEmail) + if !bytes.Equal(email.Bytes(), testEmail) { + t.Fatalf("expected %s, got %s", string(testEmail), string(email.Bytes())) + } + }) + + t.Run("nil email pointer", func(t *testing.T) { + var email *Email + email = email.SetBytes(testEmail) + if !bytes.Equal(email.Bytes(), testEmail) { + t.Fatalf("expected %s, got %s", string(testEmail), string(email.Bytes())) + } + }) +} + +func TestEmailMarshal(t *testing.T) { + t.Run("success marshal unmarshal", func(t *testing.T) { + testEmail := []byte("user@example.com") + expectedEmail := new(Email).SetBytes(testEmail) + + enc := expectedEmail.Marshal() + newEmail := new(Email).Unmarshal(enc) + if !bytes.Equal(newEmail.Bytes(), expectedEmail.Bytes()) { + t.Fatalf("expected %s, got %s", string(expectedEmail.Bytes()), string(newEmail.Bytes())) + } + }) + + t.Run("marshal nil email", func(t *testing.T) { + var nilEmail *Email + enc := nilEmail.Marshal() + if enc != nil { + t.Fatalf("expected nil, got %v", enc) + } + }) + + t.Run("marshal empty email", func(t *testing.T) { + enc := new(Email).Marshal() + if enc != nil { + t.Fatalf("expected nil, got %v", enc) + } + }) + + t.Run("unmarshal nil email", func(t *testing.T) { + rawEmail := "user@example.com" + encEmail := base64url.RawEncode([]byte(rawEmail)) + var nilEmail *Email + newEmail := nilEmail.Unmarshal(encEmail) + if !bytes.Equal(newEmail.Bytes(), []byte(rawEmail)) { + t.Fatalf("expected %s, got %s", rawEmail, string(newEmail.Bytes())) + } + }) + + t.Run("unmarshal wrong email", func(t *testing.T) { + enc := new(Email).Unmarshal([]byte("SGVsbG8===")) + if len(enc.Bytes()) != 0 { + t.Fatalf("expected nil, got %v", enc.Bytes()) + } + }) +} + +func TestEmailStrin(t *testing.T) { + rawEmail := "user@example.com" + newEmail := new(Email).SetString(rawEmail) + if newEmail.String() != rawEmail { + t.Fatalf("expected %s, got %s", rawEmail, newEmail.String()) + } +} From ece09910a29a031142a8e2b06282f0cfd4ddaea0 Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Tue, 25 Aug 2026 22:29:07 +0200 Subject: [PATCH 5/9] new token package tests, documentation and minor changes --- token/app.go | 3 ++ token/app_test.go | 101 +++++++++++++++++++++++---------------- token/email.go | 29 +++++++++++- token/email_test.go | 27 +++++++++++ token/expiration.go | 11 ++++- token/id.go | 22 ++++----- token/id_test.go | 109 ++++++++++++++++++++++++++----------------- token/secret.go | 20 ++++++-- token/secret_test.go | 38 ++++++++------- token/token.go | 54 +++++++++++++++------ token/token_test.go | 107 ++++++++++++++++++++++++++++++++++++++++++ 11 files changed, 388 insertions(+), 133 deletions(-) diff --git a/token/app.go b/token/app.go index f6241f1..d7fc737 100644 --- a/token/app.go +++ b/token/app.go @@ -162,6 +162,9 @@ func (app *App) SetID(id *AppID) *App { return app.Unmarshal(id.Bytes()) } +// SetSectret method sets the app secret. The app secret is a the secret part +// that comes from the app creator and is used to sign tokens with the secret +// part from the auth api instance. func (app *App) SetSecret(secret *Secret) *App { if app == nil { return nil diff --git a/token/app_test.go b/token/app_test.go index 408ac0f..bc9f052 100644 --- a/token/app_test.go +++ b/token/app_test.go @@ -21,49 +21,68 @@ func TestValidApp(t *testing.T) { RedirectURI: testRedirectURI, SessionDuration: testSessionDuration, } - 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 err := app.Valid(nil); err == nil { - t.Errorf("expected invalid app data") - } - app.Name = "no" - if err := app.Valid(nil); err == nil { - t.Errorf("expected invalid app data") - } + + t.Run("no secret hash", func(t *testing.T) { + if err := app.Valid(nil); err != nil { + t.Fatalf("expected valid app data") + } + }) + + t.Run("too long app name", func(t *testing.T) { + app.Name = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." + if err := app.Valid(nil); err == nil { + t.Fatalf("expected invalid app data") + } + }) + + t.Run("too short app name", func(t *testing.T) { + app.Name = "no" + if err := app.Valid(nil); err == nil { + t.Fatalf("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 err := app.Valid(nil); err == nil { - t.Errorf("expected invalid app data") - } - app.RedirectURI = "no_url" - if err := app.Valid(nil); err == nil { - t.Errorf("expected invalid app data") - } + t.Run("invalid redirect uri", func(t *testing.T) { + 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 err := app.Valid(nil); err == nil { + t.Fatalf("expected invalid app data") + } + }) + t.Run("no redirect uri", func(t *testing.T) { + app.RedirectURI = "no_url" + if err := app.Valid(nil); err == nil { + t.Fatalf("expected invalid app data") + } + }) app.RedirectURI = testRedirectURI - // test session duration - app.SessionDuration = minDuration - 1 - if err := app.Valid(nil); err == nil { - t.Errorf("expected invalid app data") - } - app.SessionDuration = maxDuration + 1 - if err := app.Valid(nil); err == nil { - t.Errorf("expected invalid app data") - } - var nilApp *App - 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 err := app.Valid(invalidSecret.Hash()); err == nil { - t.Errorf("expected invalid app data") - } + t.Run("no min duration reached", func(t *testing.T) { + app.SessionDuration = minDuration - 1 + if err := app.Valid(nil); err == nil { + t.Fatalf("expected invalid app data") + } + }) + t.Run("max duration reached", func(t *testing.T) { + app.SessionDuration = maxDuration + 1 + if err := app.Valid(nil); err == nil { + t.Fatalf("expected invalid app data") + } + }) + app.SessionDuration = testSessionDuration + t.Run("nil app", func(t *testing.T) { + var nilApp *App + if err := nilApp.Valid(nil); err == nil { + t.Fatalf("expected invalid app data") + } + }) + t.Run("invalid app secret", func(t *testing.T) { + app.AppSecretHash = testAppSecret.Hash() + servicePart := []byte("invalid-service-secret") + appPart := []byte("invalid-app-secret") + invalidSecret := new(Secret).SetParts(servicePart, appPart) + if err := app.Valid(invalidSecret.Hash()); err == nil { + t.Fatalf("expected invalid app data") + } + }) } func TestAttributesSetAttributesApp(t *testing.T) { diff --git a/token/email.go b/token/email.go index cc00e4e..b6b8f13 100644 --- a/token/email.go +++ b/token/email.go @@ -1,11 +1,38 @@ package token -import "go.k7z7z.cc/x/encoding/base64url" +import ( + "bytes" + "net/mail" + + "go.k7z7z.cc/x/encoding/base64url" +) // Email type wraps a byte slice to handle an user email regarding the token // generation, managment and validation. type Email []byte +// Valid method returns a boolean indicating if the current email is a valid +// email address or not. It returns false if the email is nil, empty or invalid +// address. +func (e *Email) Valid() bool { + // If the current email is nil, return false + if e == nil { + return false + } + // Trim the given email + value := bytes.TrimSpace(e.Bytes()) + if len(value) == 0 { + return false + } + // Ensure that the trimmed email is equal to the original one after parse + // it as an email address. + addr, err := mail.ParseAddress(string(value)) + if err != nil { + return false + } + return addr.Address == string(value) +} + // SetBytes method writes a byte slice to the current Email type instance. If // a nil email is used, it is initialized. func (e *Email) SetBytes(bEmail []byte) *Email { diff --git a/token/email_test.go b/token/email_test.go index 2bbe3ec..bca0d4e 100644 --- a/token/email_test.go +++ b/token/email_test.go @@ -7,6 +7,33 @@ import ( "go.k7z7z.cc/x/encoding/base64url" ) +func TestEmailValid(t *testing.T) { + t.Run("valid email", func(t *testing.T) { + testEmail := []byte("user@example.com") + if !new(Email).SetBytes(testEmail).Valid() { + t.Fatal("expected to be valid") + } + }) + t.Run("nil email", func(t *testing.T) { + var nilEmail *Email + if nilEmail.Valid() { + t.Fatal("expected to be invalid") + } + }) + t.Run("empty email", func(t *testing.T) { + testEmail := []byte(" ") + if new(Email).SetBytes(testEmail).Valid() { + t.Fatal("expected to be invalid") + } + }) + t.Run("wrong email", func(t *testing.T) { + testEmail := []byte("test@") + if new(Email).SetBytes(testEmail).Valid() { + t.Fatal("expected to be invalid") + } + }) +} + func TestEmailBytes(t *testing.T) { testEmail := []byte("user@example.com") t.Run("existing email pointer", func(t *testing.T) { diff --git a/token/expiration.go b/token/expiration.go index 1564f9f..382358a 100644 --- a/token/expiration.go +++ b/token/expiration.go @@ -11,10 +11,19 @@ import ( // expiration time. type Expiration time.Time +// Empty method returns if the current expiration is empty or not. An Empty +// instance is considered empty when it is nil or zero time.Time. +func (exp *Expiration) Empty() bool { + if exp == nil { + return true + } + return exp.Time().IsZero() +} + // Valid method returns true if the expiration is valid, false otherwise. An // expiration is considered valid if it is in the future. func (exp *Expiration) Valid() bool { - return time.Now().Before(exp.Time()) + return !exp.Empty() && time.Now().Before(exp.Time()) } // Time method returns the expiration time as a time.Time. diff --git a/token/id.go b/token/id.go index 168a256..f3daa6e 100644 --- a/token/id.go +++ b/token/id.go @@ -88,7 +88,7 @@ func (id *AppID) PrivKey(secret Secret) ed25519.PrivateKey { // with the private key. The signature is then encoded to base64 before // being returned to be used as a part of the token, keeping it as short as // possible. -func (id *AppID) Sign(secret Secret, msg []byte) []byte { +func (id *AppID) Sign(secret Secret, msg []byte) Signature { // check if the application ID is valid or the message is empty if id == nil || len(msg) == 0 { return nil @@ -114,7 +114,7 @@ func (id *AppID) Sign(secret Secret, msg []byte) []byte { // verified by appending a nonce to it and hashing the result with the // public key. The signature is then decoded from base64 and verified with // the public key to ensure that it was signed by the private key. -func (id *AppID) Verify(secret Secret, msg, sig []byte) bool { +func (id *AppID) Verify(secret Secret, msg []byte, sig Signature) bool { // check if the application ID is valid or the message and signature are // not empty if id == nil || len(msg) == 0 || len(sig) == 0 { @@ -151,14 +151,11 @@ func (id *AppID) GenerateToken(secret Secret, email Email) Token { } // get the application for the application ID app := new(App).SetID(id) - if app == nil { + if app == nil || app.Valid(nil) != nil { return nil } // 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) // sign the message with the secret @@ -180,7 +177,7 @@ func (id *AppID) GenerateToken(secret Secret, email Email) Token { func (id *AppID) Message(email Email, 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 || !email.Valid() || !exp.Valid() { return nil } // hash the application ID with the email and expiration time @@ -200,21 +197,18 @@ func (id *AppID) VerifyToken(token Token, secret Secret) bool { return false } email := token.Email() + if !email.Valid() { + return false + } // check if the expiration time is valid exp := token.Expiration() - if exp == nil || !exp.Valid() { + if !exp.Valid() { return false } // check if the token contains a signature sig := token.Signature() - if len(sig) == 0 { - return false - } // get the message to verify msg := id.Message(*email, *exp) - if len(msg) == 0 { - return false - } // verify the token with the secret return id.Verify(secret, msg, sig) } diff --git a/token/id_test.go b/token/id_test.go index 12e480a..47ff0e4 100644 --- a/token/id_test.go +++ b/token/id_test.go @@ -131,16 +131,19 @@ func TestPrivKeySignVerifyAppID(t *testing.T) { func TestGenerateTokenVerifyToken(t *testing.T) { t.Parallel() - var nilAppID *AppID - if res := nilAppID.GenerateToken(nil, nil); res != nil { - t.Errorf("expected nil, got %v", res) - } - if nilAppID.VerifyToken(nil, *testAppSecret) { - t.Errorf("expected token to be invalid") - } - if res := new(AppID).GenerateToken(nil, nil); res != nil { - t.Errorf("expected nil, got %v", res) - } + t.Run("invalid app id", func(t *testing.T) { + var nilAppID *AppID + if res := nilAppID.GenerateToken(nil, nil); res != nil { + t.Errorf("expected nil, got %v", res) + } + if nilAppID.VerifyToken(nil, *testAppSecret) { + t.Errorf("expected token to be invalid") + } + if res := new(AppID).GenerateToken(nil, nil); res != nil { + t.Errorf("expected nil, got %v", res) + } + }) + app := &App{ Name: testAppName, RedirectURI: testRedirectURI, @@ -154,40 +157,60 @@ func TestGenerateTokenVerifyToken(t *testing.T) { if id == nil { t.Fatalf("error decoding app ID") } - if id.VerifyToken([]byte{}, *testAppSecret) { - t.Errorf("expected token to be invalid") - } - dummyToken := new(Token).SetExpiration(*new(Expiration).SetDuration(minDuration * 3)) - if id.VerifyToken(*dummyToken, *testAppSecret) { - t.Errorf("expected token to be invalid") - } - dummyToken = new(Token).SetSignature([]byte("test")) - if id.VerifyToken(*dummyToken, *testAppSecret) { - t.Errorf("expected token to be invalid") - } - if invalidToken := id.GenerateToken(*testAppSecret, nil); invalidToken != nil { - t.Fatalf("expected nil, got %v", invalidToken) - } + + t.Run("no vaid token", func(t *testing.T) { + if id.VerifyToken([]byte{}, *testAppSecret) { + t.Errorf("expected token to be invalid") + } + }) + + t.Run("invalid token generation", func(t *testing.T) { + dummyToken := new(Token).SetExpiration(*new(Expiration).SetDuration(minDuration * 3)) + if id.VerifyToken(*dummyToken, *testAppSecret) { + t.Errorf("expected token to be invalid") + } + dummyToken = new(Token).SetSignature([]byte("test")) + if id.VerifyToken(*dummyToken, *testAppSecret) { + t.Errorf("expected token to be invalid") + } + if invalidToken := id.GenerateToken(*testAppSecret, nil); invalidToken != nil { + t.Fatalf("expected nil, got %v", invalidToken) + } + }) userID := new(Email).SetString("test@email.com") - token := id.GenerateToken(*testAppSecret, *userID) - if token == nil { - t.Fatalf("error creating token") - } - if !id.VerifyToken(token, *testAppSecret) { - t.Errorf("expected token to be valid") - } - time.Sleep(app.SessionDuration + time.Second) - if id.VerifyToken(token, *testAppSecret) { - t.Errorf("expected token to be invalid") - } - if id.VerifyToken(nil, *testAppSecret) { - t.Errorf("expected token to be invalid") - } - exp := new(Expiration).SetDuration(minDuration) - if id.VerifyToken(exp.Marshal(), *testAppSecret) { - t.Errorf("expected token to be invalid") - } + t.Run("valid token expiration", func(t *testing.T) { + token := id.GenerateToken(*testAppSecret, *userID) + if token == nil { + t.Fatalf("error creating token") + } + if !id.VerifyToken(token, *testAppSecret) { + t.Errorf("expected token to be valid") + } + time.Sleep(app.SessionDuration + time.Second) + if id.VerifyToken(token, *testAppSecret) { + t.Errorf("expected token to be invalid") + } + }) + + t.Run("invalid verify inputs", func(t *testing.T) { + if id.VerifyToken(nil, *testAppSecret) { + t.Errorf("expected token to be invalid") + } + exp := new(Expiration).SetDuration(minDuration) + if id.VerifyToken(exp.Marshal(), *testAppSecret) { + t.Errorf("expected token to be invalid") + } + + token := id.GenerateToken(*testAppSecret, *userID) + if token == nil { + t.Fatalf("error creating token") + } + token.SetEmail(nil) + if id.VerifyToken(token, *testAppSecret) { + t.Fatalf("expected token to be invalid") + } + }) } func TestTokenModificationRejected(t *testing.T) { @@ -206,7 +229,7 @@ func TestTokenModificationRejected(t *testing.T) { if id == nil { t.Fatalf("error decoding app ID") } - + userID := new(Email).SetString("test@email.com") token := id.GenerateToken(*secret, *userID) if token == nil { diff --git a/token/secret.go b/token/secret.go index 868eefb..70e713e 100644 --- a/token/secret.go +++ b/token/secret.go @@ -1,6 +1,9 @@ package token -import "crypto/sha256" +import ( + "bytes" + "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 @@ -8,6 +11,11 @@ import "crypto/sha256" // The hash is used to sign and verify tokens, and to create the app ID and it is part of it. const secretHashSize = 12 +// minSecretParts is the minimum number of parts that a valid secret should +// have. The minimun number of required parts is 2 to ensure that the ownership +// of the secret is distributed into at least two parties. +const minSecretParts = 2 + // Secret represents a secret that is used to sign and verify tokens. It is // a wrapper around a byte slice that provides additional methods for setting // and getting the secret. It should have at least 2 parts, each hashed to a @@ -25,7 +33,8 @@ func (s *Secret) SetParts(raw ...[]byte) *Secret { } // hash each part to a sha256 size and concatenate them newParts := []byte{} - for _, part := range raw { + for _, rawPart := range raw { + part := bytes.TrimSpace(rawPart) if len(part) == 0 { continue } @@ -33,7 +42,7 @@ func (s *Secret) SetParts(raw ...[]byte) *Secret { newParts = append(newParts, hsecret[:]...) } // if there are new parts, append them to the secret - if len(newParts) != 0 { + if len(newParts) > 0 { *s = append(*s, newParts...) } return s @@ -66,5 +75,8 @@ func (s *Secret) Valid() bool { } // secret is valid if it has more than 1 part, and each part is hashed // to a sha256 size - return len(*s)%sha256.Size == 0 && len(*s) > sha256.Size + lenSecret := len(*s) + validSize := lenSecret%sha256.Size == 0 + validNumOfParts := lenSecret/sha256.Size >= minSecretParts + return validSize && validNumOfParts } diff --git a/token/secret_test.go b/token/secret_test.go index 981819f..11bd981 100644 --- a/token/secret_test.go +++ b/token/secret_test.go @@ -33,23 +33,29 @@ func TestSetPartsSecret(t *testing.T) { } func TestValidSecret(t *testing.T) { - var nilSecret *Secret - if valid := nilSecret.Valid(); valid { - t.Errorf("expected false, got %v", valid) - } - if valid := new(Secret).Valid(); valid { - t.Errorf("expected false, got %v", valid) - } - servicePart := []byte("service-secret") - singlePart := new(Secret).SetParts(servicePart) - if valid := singlePart.Valid(); valid { - t.Errorf("expected false, got %v", valid) - } + t.Run("nil secret", func(t *testing.T) { + var nilSecret *Secret + if valid := nilSecret.Valid(); valid { + t.Errorf("expected false, got %v", valid) + } + if valid := new(Secret).Valid(); valid { + t.Errorf("expected false, got %v", valid) + } + }) + serverPart := []byte("server-secret") appPart := []byte("app-secret") - valid := new(Secret).SetParts(servicePart, appPart) - if !valid.Valid() { - t.Errorf("expected true, got false") - } + t.Run("invalid number of parts", func(t *testing.T) { + singlePart := new(Secret).SetParts(serverPart) + if valid := singlePart.Valid(); valid { + t.Error("expected false, got true") + } + }) + t.Run("multiple parts", func(t *testing.T) { + valid := new(Secret).SetParts(serverPart, appPart) + if !valid.Valid() { + t.Errorf("expected true, got false") + } + }) } func TestSecretHash(t *testing.T) { diff --git a/token/token.go b/token/token.go index 43a3554..ab51627 100644 --- a/token/token.go +++ b/token/token.go @@ -2,16 +2,37 @@ package token import "bytes" +// numOfTokensParts const defines the number of parts that a Token has encoded. +// This number is used decode a encoded token into its multiple parts, or +// encode valid parts into a encoded token. const numOfTokenParts = 3 +// emptyToken is a helper var used by String() of Token struct to check if the +// a token is empty. var emypyToken = bytes.Join(make([][]byte, numOfTokenParts), []byte{tokenSeparator}) +// Signature wraps a byte slice to be used in signature operations. +type Signature []byte + +// Empty method returns true if the current signature is empty (lenght 0). +func (s Signature) Empty() bool { + return len(s) == 0 +} + // Token is a type that represents a user token. It is a wrapper around a byte // slice that provides additional methods for setting and getting the token. It -// should have 2 parts, the first part is the expiration time, and the second -// part is the signature. +// should have 3 parts: +// - The token expiration time (encoded). +// - The token signature, generated by the server using the secret over the +// expiration and the email of the user to generate the signature. +// - The email of the user who attempts to be authenticated. type Token []byte +// Valid method returns a boolean indicating if the current Token is valid. A +// A valid token has three valid parts: +// - The expiration of the token. +// - The token signature. +// - A valid user email. func (t *Token) Valid() bool { if t == nil { return false @@ -20,7 +41,11 @@ func (t *Token) Valid() bool { switch { case !ok: return false - case t.Expiration() == nil || t.Signature() == nil || t.Email() == nil: + case t.Expiration().Empty(): + return false + case t.Signature().Empty(): + return false + case !t.Email().Valid(): return false default: return true @@ -111,18 +136,21 @@ func (t *Token) Expiration() *Expiration { // time with the new expiration time. It checks that the expiration time is // valid before setting it. func (t *Token) SetExpiration(exp Expiration) *Token { - return t.join([][]byte{ + return t.join( exp.Marshal(), t.Signature(), t.Email().Marshal(), - }) + ) } // Signature method returns the token's signature. If the token is nil, nil is // returned. It internally calls the parts method to get the signature part as // byte slices. -func (t *Token) Signature() []byte { +func (t *Token) Signature() Signature { _, sig, _, _ := t.split() + if len(sig) == 0 { + return nil + } return sig } @@ -130,28 +158,28 @@ func (t *Token) Signature() []byte { // new token is created. If the signature is nil, the token is not set. It // internally calls the parts method to replace the token's signature with // the new signature. -func (t *Token) SetSignature(sig []byte) *Token { - return t.join([][]byte{ +func (t *Token) SetSignature(sig Signature) *Token { + return t.join( t.Expiration().Marshal(), sig, t.Email().Marshal(), - }) + ) } func (t *Token) Email() *Email { _, _, rawEmail, ok := t.split() - if rawEmail == nil || !ok { + if len(rawEmail) == 0 || !ok { return nil } return new(Email).Unmarshal(rawEmail) } func (t *Token) SetEmail(email Email) *Token { - return t.join([][]byte{ + return t.join( t.Expiration().Marshal(), t.Signature(), email.Marshal(), - }) + ) } // split private method returns the token's expiration time and signature as @@ -170,7 +198,7 @@ func (t *Token) split() ([]byte, []byte, []byte, bool) { return p[0], p[1], p[2], true } -func (t *Token) join(parts [][]byte) *Token { +func (t *Token) join(parts ...[]byte) *Token { // if no token is provided, create a new one if t == nil { t = new(Token) diff --git a/token/token_test.go b/token/token_test.go index 2d1dbe5..91091bb 100644 --- a/token/token_test.go +++ b/token/token_test.go @@ -6,6 +6,59 @@ import ( "time" ) +func TestValid(t *testing.T) { + t.Run("nil token", func(t *testing.T) { + var nilToken *Token + if nilToken.Valid() { + t.Fatalf("expected invalid token, got valid one") + } + }) + + t.Run("invalid parts", func(t *testing.T) { + var emptyToken Token + if emptyToken.Valid() { + t.Fatalf("expected invalid token, got valid one") + } + }) + + t.Run("no expiration", func(t *testing.T) { + token := new(Token) + token.SetSignature([]byte("abcdef1234567890")) + token.SetEmail(*new(Email).SetString("test@email.com")) + if token.Valid() { + t.Fatalf("expected invalid token, got valid one") + } + }) + + t.Run("no signature", func(t *testing.T) { + token := new(Token) + token.SetExpiration(*new(Expiration).SetDuration(minDuration)) + token.SetEmail(*new(Email).SetString("test@email.com")) + if token.Valid() { + t.Fatalf("expected invalid token, got valid one") + } + }) + + t.Run("no email", func(t *testing.T) { + token := new(Token) + token.SetSignature([]byte("abcdef1234567890")) + token.SetExpiration(*new(Expiration).SetDuration(minDuration)) + if token.Valid() { + t.Fatalf("expected invalid token, got valid one") + } + }) + + t.Run("valid token", func(t *testing.T) { + token := new(Token) + token.SetSignature([]byte("abcdef1234567890")) + token.SetExpiration(*new(Expiration).SetDuration(minDuration)) + token.SetEmail(*new(Email).SetString("test@email.com")) + if !token.Valid() { + t.Fatalf("expected valid token, got invalid one") + } + }) +} + func TestStringSetStringToken(t *testing.T) { var token *Token token.SetString("test") @@ -173,3 +226,57 @@ func Test_partsToken(t *testing.T) { t.Errorf("expected %v, got %v", []byte("test"), sign) } } + +func TestSplitJoin(t *testing.T) { + t.Run("nil token", func(t *testing.T) { + var nilToken *Token + if _, _, _, ok := nilToken.split(); ok { + t.Fatalf("expected wrong split token, got ok") + } + + if newToken := nilToken.join([]byte{}); len(newToken.Bytes()) != 0 { + t.Fatalf("expected nil token, got %x", newToken) + } + }) + + t.Run("invalid parts of token", func(t *testing.T) { + var token Token = []byte("test.token") + if _, _, _, ok := token.split(); ok { + t.Fatalf("expected wrong split token, got ok") + } + + if newToken := token.join([]byte{}); len(newToken.Bytes()) != 0 { + t.Fatalf("expected nil token, got %x", newToken) + } + }) + + t.Run("valid token", func(t *testing.T) { + expSig := []byte("abcdef1234567890") + expEmail := new(Email).SetString("test@email.com") + expExpiration := new(Expiration).SetDuration(minDuration) + + token := new(Token) + token.SetSignature(expSig) + token.SetExpiration(*expExpiration) + token.SetEmail(*expEmail) + + exp, sig, email, ok := token.split() + if !ok { + t.Fatal("expected valid token parts") + } + if !bytes.Equal(expSig, sig) { + t.Fatalf("expected signature %x, got %x", expSig, sig) + } + if !bytes.Equal(expExpiration.Marshal(), exp) { + t.Fatalf("expected expiration %x, got %x", expExpiration.Marshal(), exp) + } + if !bytes.Equal(expEmail.Marshal(), email) { + t.Fatalf("expected email %x, got %x", expEmail.Marshal(), email) + } + + newToken := new(Token).join(exp, sig, email) + if !bytes.Equal(token.Bytes(), newToken.Bytes()) { + t.Fatalf("expected token %x, got %x", token, newToken) + } + }) +} From e49f3bf22594534c36817ca18b1da0f2a9d3375e Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Tue, 25 Aug 2026 22:29:49 +0200 Subject: [PATCH 6/9] new api and api/client packages tests, documentation and minor changes --- api/api.go | 20 +++++---- api/client/client.go | 26 +++++------- api/client/client_test.go | 87 +++++++++++++++++++++++++++++---------- api/handlers.go | 54 +++++++----------------- api/handlers_test.go | 14 +++++++ api/helpers.go | 24 +++++++++++ api/routes.go | 12 +++++- api/service_test.go | 45 ++++++++++++++++++++ api/types.go | 18 +++----- 9 files changed, 200 insertions(+), 100 deletions(-) diff --git a/api/api.go b/api/api.go index 8238034..700eac2 100644 --- a/api/api.go +++ b/api/api.go @@ -11,18 +11,18 @@ // @license.name AGPL-3.0 // @license.url https://github.com/SimpleAuthLink/authapi/blob/main/LICENSE // -// @servers.url https://api.simpleauth.link -// @servers.description Production -// // @servers.url https://demo.simpleauth.link // @servers.description Demo // +// @servers.url https://api.simpleauth.link +// @servers.description Production +// // @servers.url {scheme}://{host} // @servers.description Custom // @servers.variables.enum scheme https // @servers.variables.enum scheme http -// @servers.variables.default scheme https -// @servers.variables.default host api.simpleauth.link +// @servers.variables.default scheme http +// @servers.variables.default host localhost:8080 // // @tag.name apps // @tag.description Create and manage your App @@ -35,13 +35,15 @@ // @tag.docs.description About Tokens package api -// @securityDefinitions.apikey AppID +// @securityDefinitions.apikey X-SIMPLEAUTHLINK-APPID // @in header -// @name AppID +// @name X-SIMPLEAUTHLINK-APPID +// @description Use the received App ID after registering the App (POST /apps). -// @securityDefinitions.apikey AppSecret +// @securityDefinitions.apikey X-SIMPLEAUTHLINK-SECRET // @in header -// @name AppSecret +// @name X-SIMPLEAUTHLINK-SECRET +// @description Use the same secret you provided when creating the App ID. Default: mysupersecret import ( "context" diff --git a/api/client/client.go b/api/client/client.go index f3e3998..11617b0 100644 --- a/api/client/client.go +++ b/api/client/client.go @@ -16,10 +16,7 @@ const ( DefaultClientTimeout = 30 * time.Second // DefaultAPIEndpoint is the default API endpoint for the client. It can be // overridden in the Config struct. - DefaultAPIEndpoint = "https://api.simpleauth.link" - DefaultAuthTokenHeader = "X-Auth-Token" - DefaultAuthEmailHeader = "X-Auth-User" - DefaultAuthTokenURLParam = "token" + DefaultAPIEndpoint = "https://api.simpleauth.link" ) // Config holds the configuration for the client. It includes the API endpoint, @@ -202,15 +199,15 @@ func (c *Client) SetupAppID(appID *token.AppID, appSecret string) { // RequestToken method requests a new token for the given email address. It // requires the client configuration to be valid, including the application // ID and secret. The email address must be a valid email format. -func (c *Client) RequestToken(email string) error { +func (c *Client) RequestToken(email *token.Email) error { // validate the configuration before making the request, for this operation // the app ID and secret are required if err := c.config.Validate(true); err != nil { return err } - data := &api.TokenRequest{Email: email} + data := &api.TokenRequest{Email: email.String()} // check if the email is valid - if !data.IsEmail() { + if !email.Valid() { return ErrInvalidRequestTokenInputs } // create the request with the email data @@ -233,12 +230,11 @@ func (c *Client) RequestToken(email string) error { return nil } -// VerifyToken method verifies the provided token for the given email address. -// It requires the client configuration to be valid, including the application -// ID and secret. The token must be valid, and the email address must be a -// valid email format. If the token is valid, it returns true and the -// expiration time. If the token is invalid or the email address is not valid, -// it returns false. If the request fails, it also returns an error. +// VerifyToken method verifies the provided token. It requires the client +// configuration to be valid, including the application ID and secret. If +// the token is a valid Token, it returns true and the expiration time. If +// the token is invalid or it has expired, it returns false. It also returns +// an error if the request fails. func (c *Client) VerifyToken(token *token.Token) (bool, time.Time, error) { // validate the configuration before making the request, for this operation // the app ID and secret are required @@ -289,7 +285,7 @@ func (c *Client) AuthorizedRequestURLParams(r *http.Request) (string, bool, erro return "", false, ErrMissingAuthURLParams } // get the strToken and email from the request headers - strToken := params.Get(DefaultAuthTokenURLParam) + strToken := params.Get(api.AuthTokenURLParam) // check if the token and email are valid if strToken == "" { return "", false, ErrMissingAuthURLParams @@ -314,7 +310,7 @@ func (c *Client) AuthorizedRequestHeaders(r *http.Request) (string, bool, error) return "", false, err } // get the strToken and email from the request headers - strToken := r.Header.Get(DefaultAuthTokenHeader) + strToken := r.Header.Get(api.AuthTokenHeader) // check if the token and email are valid if strToken == "" { return "", false, ErrMissingAuthHeaders diff --git a/api/client/client_test.go b/api/client/client_test.go index ca7660c..5be1143 100644 --- a/api/client/client_test.go +++ b/api/client/client_test.go @@ -79,7 +79,7 @@ func TestMain(m *testing.M) { Secret: testServerSecret, }, emailQueue) if err != nil { - log.Fatalln("ERR: error creating service:", err) + log.Fatalln("error creating service:", err) } // start the service in background go func() { @@ -112,7 +112,8 @@ func TestSuccessFlow(t *testing.T) { cli.SetupAppID(appID, testClientSecret) // request a new token for the test email testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err := cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } // wait to receive the email @@ -120,7 +121,6 @@ func TestSuccessFlow(t *testing.T) { if err != nil { t.Fatalf("failed to read token from email: %v", err) } - log.Print(testToken.String()) // verify the token valid, _, err := cli.VerifyToken(testToken) if err != nil { @@ -360,7 +360,8 @@ func TestRequestToken(t *testing.T) { } cli.config.APIEndpoint = "invalid-endpoint" testEmail := randomEmail() - err = cli.RequestToken(testEmail) + tokenEmail := new(token.Email).SetString(testEmail) + err = cli.RequestToken(tokenEmail) if err != ErrInvalidAPIEndpoint { t.Fatalf("expected ErrInvalidAPIEndpoint, got %v", err) } @@ -376,10 +377,12 @@ func TestRequestToken(t *testing.T) { t.Fatalf("failed to create app ID: %v", err) } cli.SetupAppID(appID, testClientSecret) - if err := cli.RequestToken(""); err != ErrInvalidRequestTokenInputs { + nilEmail := new(token.Email) + if err := cli.RequestToken(nilEmail); err != ErrInvalidRequestTokenInputs { t.Fatalf("expected ErrInvalidRequestTokenInputs, got %v", err) } - if err := cli.RequestToken("invalid-email"); err != ErrInvalidRequestTokenInputs { + invalidEmail := token.Email([]byte("invalid-email")) + if err := cli.RequestToken(&invalidEmail); err != ErrInvalidRequestTokenInputs { t.Fatalf("expected ErrInvalidRequestTokenInputs, got %v", err) } }) @@ -401,7 +404,9 @@ func TestRequestToken(t *testing.T) { // invalid API endpoint cli.config.APIEndpoint = srv.URL testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != ErrRequestToken { + tokenEmail := new(token.Email).SetString(testEmail) + err = cli.RequestToken(tokenEmail) + if err != ErrRequestToken { t.Fatalf("expected ErrRequestToken, got %v", err) } }) @@ -416,8 +421,10 @@ func TestRequestToken(t *testing.T) { t.Fatalf("failed to create app ID: %v", err) } cli.SetupAppID(appID, testClientSecret) + testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("expected no error, got %v", err) } }) @@ -435,7 +442,8 @@ func TestRequestToken(t *testing.T) { // Unreachable endpoint → httpClient.Do returns error → ErrAPIUnavailable cli.config.APIEndpoint = "http://nonexistent.host.issue" testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != ErrAPIUnavailable { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != ErrAPIUnavailable { t.Fatalf("expected ErrAPIUnavailable, got %v", err) } }) @@ -478,7 +486,8 @@ func TestVerifyToken(t *testing.T) { } cli.SetupAppID(appID, testClientSecret) testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } testToken, err := readTokenFromEmail(t, testEmail) @@ -502,7 +511,8 @@ func TestVerifyToken(t *testing.T) { } cli.SetupAppID(appID, testClientSecret) testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } testToken, err := readTokenFromEmail(t, testEmail) @@ -529,7 +539,8 @@ func TestVerifyToken(t *testing.T) { } cli.SetupAppID(appID, testClientSecret) testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } testToken, err := readTokenFromEmail(t, testEmail) @@ -590,7 +601,8 @@ func TestAuthorizedRequestURLParams(t *testing.T) { } t.Run("valid params in request url", func(t *testing.T) { testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } testToken, err := readTokenFromEmail(t, testEmail) @@ -599,7 +611,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { } reqURL, _ := url.Parse("http://example.com/test") reqURL.RawQuery = fmt.Sprintf("%s=%s", - DefaultAuthTokenURLParam, testToken.String()) + api.AuthTokenURLParam, testToken.String()) req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) if err != nil { @@ -627,7 +639,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { t.Run("invalid params in request url", func(t *testing.T) { invalidEmailURL, _ := url.Parse("http://example.com/test") - invalidEmailURL.RawQuery = DefaultAuthEmailHeader + "=invalid%2G" + invalidEmailURL.RawQuery = "X-Auth-Token" + "=invalid%2G" request, err := http.NewRequest(http.MethodGet, invalidEmailURL.String(), nil) if err != nil { t.Fatalf("failed to create request: %v", err) @@ -640,7 +652,8 @@ func TestAuthorizedRequestURLParams(t *testing.T) { t.Run("invalid auth in request params", func(t *testing.T) { testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } testToken, err := readTokenFromEmail(t, testEmail) @@ -650,7 +663,7 @@ func TestAuthorizedRequestURLParams(t *testing.T) { otherEmail := "other@email.com" reqURL, _ := url.Parse("http://example.com/test") reqURL.RawQuery = fmt.Sprintf("%s=%s", - DefaultAuthTokenURLParam, url.QueryEscape(testToken.String())) + api.AuthTokenURLParam, url.QueryEscape(testToken.String())) req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) if err != nil { @@ -667,6 +680,21 @@ func TestAuthorizedRequestURLParams(t *testing.T) { t.Fatalf("expected %s, got %s", email, otherEmail) } }) + + t.Run("verify token error", func(t *testing.T) { + cli.config.APIEndpoint = "http://nonexistent.host.issue" + defer func() { cli.config.APIEndpoint = testEndpoint }() + reqURL, _ := url.Parse("http://example.com/test") + reqURL.RawQuery = fmt.Sprintf("%s=%s", api.AuthTokenURLParam, "not-a-valid-token") + req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) + if err != nil { + t.Fatalf("failed to create request: %v", err) + } + _, _, err = cli.AuthorizedRequestURLParams(req) + if err != ErrAPIUnavailable { + t.Fatalf("expected ErrAPIUnavailable, got %v", err) + } + }) } func TestAuthorizedRequestHeaders(t *testing.T) { @@ -693,7 +721,8 @@ func TestAuthorizedRequestHeaders(t *testing.T) { } t.Run("valid params in request headers", func(t *testing.T) { testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } testToken, err := readTokenFromEmail(t, testEmail) @@ -704,8 +733,7 @@ func TestAuthorizedRequestHeaders(t *testing.T) { if err != nil { t.Fatalf("failed to create request: %v", err) } - req.Header.Set(DefaultAuthEmailHeader, testEmail) - req.Header.Set(DefaultAuthTokenHeader, testToken.String()) + req.Header.Set(api.AuthTokenHeader, testToken.String()) email, valid, err := cli.AuthorizedRequestHeaders(req) if err != nil { t.Fatalf("failed to get authorized request URL params: %v", err) @@ -731,7 +759,8 @@ func TestAuthorizedRequestHeaders(t *testing.T) { t.Run("invalid auth in request headers", func(t *testing.T) { testEmail := randomEmail() - if err := cli.RequestToken(testEmail); err != nil { + tokenEmail := new(token.Email).SetString(testEmail) + if err = cli.RequestToken(tokenEmail); err != nil { t.Fatalf("failed to request token: %v", err) } testToken, err := readTokenFromEmail(t, testEmail) @@ -743,7 +772,7 @@ func TestAuthorizedRequestHeaders(t *testing.T) { if err != nil { t.Fatalf("failed to create request: %v", err) } - req.Header.Set(DefaultAuthTokenHeader, testToken.String()) + req.Header.Set(api.AuthTokenHeader, testToken.String()) email, valid, err := cli.AuthorizedRequestHeaders(req) if err != nil { t.Fatalf("failed to get authorized request headers: %v", err) @@ -755,6 +784,20 @@ func TestAuthorizedRequestHeaders(t *testing.T) { t.Fatalf("expected %s, got %s", email, otherEmail) } }) + + t.Run("verify token error", func(t *testing.T) { + cli.config.APIEndpoint = "http://nonexistent.host.issue" + defer func() { cli.config.APIEndpoint = testEndpoint }() + req, err := http.NewRequest(http.MethodGet, "http://example.com/test", nil) + if err != nil { + t.Fatalf("failed to create request: %v", err) + } + req.Header.Set(api.AuthTokenHeader, "not-a-valid-token") + _, _, err = cli.AuthorizedRequestHeaders(req) + if err != ErrAPIUnavailable { + t.Fatalf("expected ErrAPIUnavailable, got %v", err) + } + }) } func Test_req(t *testing.T) { diff --git a/api/handlers.go b/api/handlers.go index b78f118..52bc749 100644 --- a/api/handlers.go +++ b/api/handlers.go @@ -22,7 +22,6 @@ import ( // @Description Create an App with a provided secret and get the AppID to // @Description be used to generate tokens for your users. // @Tags apps -// @Accept json // @Produce json // @Param request body api.AppIDRequest true "App ID Request" // @Success 200 {object} api.AppIDResponse @@ -49,27 +48,6 @@ func (s *APIService) generateAppIDHandler(w http.ResponseWriter, r *http.Request io.ResponseWith(&AppIDResponse{app.ID(app.Secret).String()}).WriteJSON(w) } -func (s *APIService) 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 { - return nil, nil, ErrInvalidAppHeaders - } - // 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() { - return nil, nil, ErrInvalidAppSecret - } - // check if the app id is valid (it should be a valid app) - if err := app.Valid(secret.Hash()); err != nil { - return nil, nil, ErrInvalidAppID - } - return app, secret, nil -} - // requestTokenHandler handles the request to request a new token for a // given user email address. It takes the AppID and the AppSecret from the // request headers, and the user email from the request body, encoded into @@ -81,20 +59,21 @@ func (s *APIService) appAndSecretFromRequest(r *http.Request) (*token.App, *toke // @Description a user using its email address. The user will receive the // @Description session token via email to that address. // @Tags tokens -// @Accept json // @Produce json -// @Security AppID || AppSecret +// @Security X-SIMPLEAUTHLINK-APPID || X-SIMPLEAUTHLINK-SECRET // @Param request body api.TokenRequest true "Token Request" // @Success 200 // @Failure 400 {object} io.APIError // @Failure 500 {object} io.APIError // @Router /tokens [post] func (s *APIService) requestTokenHandler(w http.ResponseWriter, r *http.Request) { - app, secret, err := s.appAndSecretFromRequest(r) + app, secret, err := appAndSecretFromRequest(r, []byte(s.cfg.Secret)) if err != nil { err.Write(w) return } + // AppID can not be nil because the appAndSecretFromRequest checks it, so + // not nil-check is required here appID := app.ID(secret) // decode the token request from the request body req := new(io.Request[TokenRequest]) @@ -103,21 +82,17 @@ func (s *APIService) requestTokenHandler(w http.ResponseWriter, r *http.Request) return } + userEmail := new(token.Email).SetString(req.Data.Email) switch { - case req.Data.IsEmail(): - // generate user genToken - userEmail := new(token.Email).SetString(req.Data.Email) + case userEmail.Valid(): + // generate user genToken for the appID, with the secret and the given + // user email. Nil-check is not required since at this point all + // required information is valid and provided. genToken := appID.GenerateToken(*secret, *userEmail) - 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 - } + // Parse error is not reachable at this point since the app comes + // from a validated appID which requires a valid redirect URI + linkURL, _ := url.Parse(app.RedirectURI) q := linkURL.Query() q.Set("token", genToken.String()) q.Set("user", req.Data.Email) @@ -158,15 +133,14 @@ func (s *APIService) requestTokenHandler(w http.ResponseWriter, r *http.Request) // @Description Check that the provided token is valid for the AppID and // @Description secret. // @Tags tokens -// @Accept json // @Produce json -// @Security AppID || AppSecret +// @Security X-SIMPLEAUTHLINK-APPID || X-SIMPLEAUTHLINK-SECRET // @Param request body api.TokenStatusRequest true "Token Request" // @Success 200 {object} api.TokenStatusResponse // @Failure 400 {object} io.APIError // @Router /tokens [put] func (s *APIService) verifyTokenHandler(w http.ResponseWriter, r *http.Request) { - app, secret, err := s.appAndSecretFromRequest(r) + app, secret, err := appAndSecretFromRequest(r, []byte(s.cfg.Secret)) if err != nil { err.Write(w) return diff --git a/api/handlers_test.go b/api/handlers_test.go index 9d6ea2e..89204d8 100644 --- a/api/handlers_test.go +++ b/api/handlers_test.go @@ -410,6 +410,20 @@ func TestRequestTokenHandlerErrorBranches(t *testing.T) { app.SetSecret(secret) appID := app.ID(secret) + t.Run("invalid secret provided", func(t *testing.T) { + testCaseAPIHandler[TokenRequest, any]{ + name: "whitespace-only secret", + method: http.MethodPost, + endpoint: TokensPath, + header: http.Header{ + AppIDHeader: []string{appID.String()}, + AppSecretHeader: []string{"\u00a0"}, + }, + request: &TokenRequest{Email: testUserEmail}, + err: ErrInvalidAppSecret, + }.Run(t) + }) + t.Run("invalid notification channel", func(t *testing.T) { testCaseAPIHandler[TokenRequest, any]{ name: "non-email hits default", diff --git a/api/helpers.go b/api/helpers.go index 6fcbdbd..16e7023 100644 --- a/api/helpers.go +++ b/api/helpers.go @@ -3,6 +3,9 @@ package api import ( "fmt" "net/http" + + "github.com/simpleauthlink/authapi/token" + "go.k7z7z.cc/x/net/http/io" ) // appConfigFromRequest extracts the app id and app secret from the request @@ -23,3 +26,24 @@ func appConfigFromRequest(r *http.Request) (string, string, error) { } return strAppID, strAppSecret, nil } + +func appAndSecretFromRequest(r *http.Request, serviceSecret []byte) (*token.App, *token.Secret, *io.APIError) { + // get the app id from the request header + strAppID, strAppSecret, err := appConfigFromRequest(r) + if err != nil { + return nil, nil, ErrInvalidAppHeaders + } + // 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(serviceSecret, []byte(strAppSecret)) + if !secret.Valid() { + return nil, nil, ErrInvalidAppSecret + } + // check if the app id is valid (it should be a valid app) + if err := app.Valid(secret.Hash()); err != nil { + return nil, nil, ErrInvalidAppID + } + return app, secret, nil +} diff --git a/api/routes.go b/api/routes.go index 3f62f68..f0f1061 100644 --- a/api/routes.go +++ b/api/routes.go @@ -16,8 +16,16 @@ const ( const ( // AppIDHeader constant is the header of the app ID in the request. It is // used to authenticate the app making the request. - AppIDHeader = "AppID" + AppIDHeader = "X-SIMPLEAUTHLINK-APPID" // AppSecretHeader constant is the header of the app secret in the request // It is used to authenticate the app making the request. - AppSecretHeader = "AppSecret" + AppSecretHeader = "X-SIMPLEAUTHLINK-SECRET" + // AuthTokenHeader constant is the header used by API client to expose a + // helper to get the user token from the request headers and validate it + // before continue. + AuthTokenHeader = "X-SIMPLEAUTHLINK-TOKEN" + // AuthTokenURLParam constant is the header used by API client to expose a + // helper to get the user token from the URL and validate it before + // continue. + AuthTokenURLParam = "token" ) diff --git a/api/service_test.go b/api/service_test.go index 4f3e184..ae148da 100644 --- a/api/service_test.go +++ b/api/service_test.go @@ -5,7 +5,9 @@ import ( "fmt" "log" "net" + "net/http" "os" + "sync" "testing" "time" @@ -186,3 +188,46 @@ func TestServiceStop(t *testing.T) { t.Error("server should not be reachable after stop") } } + +func TestPingInvalidConfig(t *testing.T) { + srv := &APIService{cfg: &Config{Server: "invalid host"}} + if srv.Ping() { + t.Error("expected Ping to return false for an invalid server address") + } +} + +type errorOnCloseListener struct { + net.Listener + started chan struct{} + startOnce sync.Once +} + +func (l *errorOnCloseListener) Accept() (net.Conn, error) { + l.startOnce.Do(func() { close(l.started) }) + return l.Listener.Accept() +} + +func (l *errorOnCloseListener) Close() error { + _ = l.Listener.Close() + return fmt.Errorf("forced close error") +} + +func TestStopCloseError(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + errL := &errorOnCloseListener{Listener: l, started: make(chan struct{})} + ctx, cancel := context.WithCancel(context.Background()) + srv := &APIService{ + ctx: ctx, + cancel: cancel, + cfg: &Config{Server: testServerAddr}, + Server: &http.Server{}, + } + go func() { _ = srv.Server.Serve(errL) }() + <-errL.started + if err := srv.Stop(); err == nil { + t.Error("expected Stop to return the listener close error") + } +} diff --git a/api/types.go b/api/types.go index 6e52caf..fdaf0d5 100644 --- a/api/types.go +++ b/api/types.go @@ -1,17 +1,16 @@ package api import ( - "net/mail" "time" "github.com/simpleauthlink/authapi/token" ) type AppIDRequest struct { - Name string `json:"name"` - Duration string `json:"session_duration"` - RedirectURL string `json:"redirect_url"` - Secret string `json:"secret"` + Name string `json:"name" example:"MySuperMegaApp"` + Duration string `json:"session_duration" example:"30m"` + RedirectURL string `json:"redirect_url" example:"https://example.com/callback"` + Secret string `json:"secret" example:"mysupersecret"` } func (data *AppIDRequest) parseApp(secret string) (*token.App, error) { @@ -34,16 +33,11 @@ type AppIDResponse struct { } type TokenRequest struct { - Email string `json:"email"` -} - -func (tr *TokenRequest) IsEmail() bool { - _, err := mail.ParseAddress(tr.Email) - return err == nil + Email string `json:"email" example:"user@example.com"` } type TokenStatusRequest struct { - Token string `json:"token"` + Token string `json:"token" example:""` } type TokenStatusResponse struct { From 84f9a40ae76ce1dc3869d93c8ae0b8cba5ea372e Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Tue, 25 Aug 2026 22:30:11 +0200 Subject: [PATCH 7/9] new notification package tests --- notification/notification_test.go | 33 ++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/notification/notification_test.go b/notification/notification_test.go index cbfb5fa..471f29c 100644 --- a/notification/notification_test.go +++ b/notification/notification_test.go @@ -7,14 +7,17 @@ import ( "time" ) -type testConfig struct{} +type testConfig struct { + invalid bool + unsupported bool +} -func (testConfig) Valid() bool { - return true +func (t testConfig) Valid() bool { + return !t.invalid } -func (testConfig) Support(n Notification) bool { - return true +func (t testConfig) Support(n Notification) bool { + return !t.unsupported } type testNotification struct{} @@ -187,6 +190,26 @@ func TestSendInvalidConfig(t *testing.T) { } } +func TestInvalidConfig(t *testing.T) { + if _, err := NewQueue(context.Background(), 10, testConfig{invalid: true}); err == nil { + t.Fatalf("expected error, got nil") + } +} + +func TestNoSupportedConf(t *testing.T) { + queue, err := NewQueue(context.Background(), 10, testConfig{unsupported: true}) + 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() +} + func TestSendSuccess(t *testing.T) { queue, err := NewQueue(context.Background(), 10, testConfig{}) if err != nil { From e0e6dfa74f524ecc7ecd08dfe67253579ecb1912 Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Tue, 25 Aug 2026 22:31:01 +0200 Subject: [PATCH 8/9] swagger documentation for demo inbox endpoint --- cmd/demo/main.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/cmd/demo/main.go b/cmd/demo/main.go index 3f20329..2920609 100644 --- a/cmd/demo/main.go +++ b/cmd/demo/main.go @@ -84,6 +84,18 @@ func main() { log.Info("HTTP server stopped, exiting...") } +// demoInboxHandler retrieves the latest token for a demo email. +// +// @Summary Demo email inbox +// @Description Retrieves the latest token for an email sent to a demo +// @Description inbox. The stream closes once the token is delivered. +// @Description Only available in Demo environments. +// @Tags default +// @Produce text/event-stream +// @Param email query string true "Email address to get the token for" +// @Success 200 {string} string "Server-Sent Events stream; the token arrives in the data field" +// @Failure 400 {object} io.APIError +// @Router /demo/inbox [get] func demoInboxHandler(w http.ResponseWriter, r *http.Request) { // get the email from get parameters email := r.URL.Query().Get("email") @@ -113,6 +125,9 @@ func demoInboxHandler(w http.ResponseWriter, r *http.Request) { if err := rc.Flush(); err != nil { return } + // close the stream once the token is delivered so that the + // response completes and clients (like swagger-ui) can show it + return } } } From 9e2f0ca9c34c2a2768c933b747c9128d73619b42 Mon Sep 17 00:00:00 2001 From: Lucas Menendez Date: Tue, 25 Aug 2026 22:31:22 +0200 Subject: [PATCH 9/9] new makefile sections and fixes --- Makefile | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 9e5f3f8..aa9b461 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,10 @@ -.PHONY: run demo clean +.PHONY: demo api swagger-ui clean-demo clean-api demo: clean-demo @echo "Building demo image..." docker build -f docker/Dockerfile.demo -t demo-simpleauthlink . @echo "Running demo container..." - docker run --name demo-simpleauthlink --env-file demo.env -p ${PORT}:80 -d demo-simpleauthlink + @set -a; . ./.env; set +a; docker run --name demo-simpleauthlink --env-file .env -p $${PORT}:$${PORT} demo-simpleauthlink clean-demo: @echo "Cleaning up previous containers and images..." @@ -18,7 +18,7 @@ api: clean-api @echo "Building API image..." docker build -f docker/Dockerfile.prod -t simpleauthlink . @echo "Running API container..." - docker run --name simpleauthlink --env-file .env -p ${PORT}:80 simpleauthlink + @set -a; . ./.env; set +a; docker run --name simpleauthlink --env-file .env -p $${PORT}:$${PORT} simpleauthlink clean-api: @echo "Cleaning up previous containers and images..." @@ -26,4 +26,13 @@ clean-api: @echo "Containers cleaned up" @docker rmi -f simpleauthlink 2>/dev/null || true @echo "Images cleaned up" - @echo "Cleaning up done" \ No newline at end of file + @echo "Cleaning up done" + +swagger-ui: + ./scripts/generate-swagger.sh + @trap 'truncate -s 0 docs/swagger.yaml' EXIT; \ + docker run --rm \ + -p 8081:8080 \ + -e SWAGGER_JSON=/spec/swagger.yaml \ + -v "$$PWD/docs:/spec:ro" \ + docker.swagger.io/swaggerapi/swagger-ui \ No newline at end of file