-
Notifications
You must be signed in to change notification settings - Fork 1
feat: auth SIWE login service + config #353
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sadiq1971
wants to merge
1
commit into
feat/auth-jwt
Choose a base branch
from
feat/auth-service
base: feat/auth-jwt
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package auth | ||
|
|
||
| import "time" | ||
|
|
||
| // Config configures Sign-In with Ethereum (EIP-4361) login and the JWTs it issues | ||
| // for read endpoints. It is always required; read endpoints are gated by a bearer | ||
| // token. The matching public key is published at /.well-known/jwks.json so other | ||
| // services (e.g. the indexer) can validate tokens without a shared secret. | ||
| type Config struct { | ||
| // PrivateKey is the RSA signing key as a base64-encoded PEM (PKCS#1 or PKCS#8). | ||
| // Supply it via env substitution — private_key: "${JWT_PRIVATE_KEY}" — where the | ||
| // env holds `base64 < key.pem`. It is base64-encoded so the (multi-line) PEM | ||
| // survives being expanded into a single YAML scalar. | ||
| PrivateKey string `yaml:"private_key" validate:"required"` | ||
| // KeyID is the JWKS "kid" advertised for the signing key. | ||
| KeyID string `yaml:"kid" validate:"required" default:"default"` | ||
| // Issuer is the JWT "iss" claim (and the value validators check). | ||
| Issuer string `yaml:"issuer" validate:"required" default:"canton-middleware"` | ||
| // Audience is the JWT "aud" claim. | ||
| Audience string `yaml:"audience" validate:"required" default:"canton-middleware-api"` | ||
| // TokenTTL is how long an issued JWT stays valid. | ||
| TokenTTL time.Duration `yaml:"token_ttl" validate:"required,gt=0" default:"30m"` | ||
| // NonceTTL is how long a login nonce stays valid before it must be re-fetched. | ||
| NonceTTL time.Duration `yaml:"nonce_ttl" validate:"required,gt=0" default:"5m"` | ||
| // Domain is the EIP-4361 domain the SIWE message must bind to (e.g. "app.example.com"). | ||
| Domain string `yaml:"domain" validate:"required"` | ||
| // URI is the EIP-4361 uri the SIWE message must bind to (e.g. "https://app.example.com"). | ||
| URI string `yaml:"uri" validate:"required"` | ||
| // ChainID is the EIP-155 chain id the SIWE message must declare. | ||
| ChainID int `yaml:"chain_id" validate:"required,gt=0"` | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package service | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
| "strings" | ||
|
|
||
| "github.com/go-chi/chi/v5" | ||
| "go.uber.org/zap" | ||
|
|
||
| apperrors "github.com/chainsafe/canton-middleware/pkg/app/errors" | ||
| apphttp "github.com/chainsafe/canton-middleware/pkg/app/http" | ||
| "github.com/chainsafe/canton-middleware/pkg/auth" | ||
| ) | ||
|
|
||
| const maxRequestBodyBytes = 1 << 20 // 1MB | ||
|
|
||
| type httpHandler struct { | ||
| svc Service | ||
| logger *zap.Logger | ||
| } | ||
|
|
||
| // RegisterRoutes mounts the login and JWKS endpoints on r. | ||
| func RegisterRoutes(r chi.Router, svc Service, logger *zap.Logger) { | ||
| h := &httpHandler{svc: svc, logger: logger} | ||
|
|
||
| r.Get("/auth/nonce", apphttp.HandleError(h.nonce)) | ||
| r.Post("/auth/login", apphttp.HandleError(h.login)) | ||
| r.Get("/.well-known/jwks.json", apphttp.HandleError(h.jwks)) | ||
|
|
||
| logger.Info("SIWE login enabled", zap.String("path", "/auth/login")) | ||
| } | ||
|
|
||
| // nonce issues a login nonce for the caller's address (GET /auth/nonce?address=). | ||
| // The nonce is keyed by address so repeat requests reuse the same live value, which | ||
| // stops an unauthenticated caller from churning the store; the address is the one | ||
| // the client will put in its SIWE message and is not a secret. | ||
| func (h *httpHandler) nonce(w http.ResponseWriter, r *http.Request) error { | ||
| address := strings.TrimSpace(r.URL.Query().Get("address")) | ||
| if !auth.ValidateEVMAddress(address) { | ||
| return apperrors.BadRequestError(nil, "address query parameter must be a 0x-prefixed 40-hex-char EVM address") | ||
| } | ||
|
|
||
| nonce, err := h.svc.Nonce(auth.NormalizeAddress(address)) | ||
| if err != nil { | ||
| h.logger.Warn("nonce issuance rejected", zap.Error(err)) | ||
| return apperrors.GeneralError(err) | ||
| } | ||
|
|
||
| writeJSON(w, http.StatusOK, &auth.NonceResponse{Nonce: nonce}) | ||
| return nil | ||
| } | ||
|
|
||
| func (h *httpHandler) login(w http.ResponseWriter, r *http.Request) error { | ||
| var req auth.LoginRequest | ||
| if err := readJSON(r, &req); err != nil { | ||
| return err | ||
| } | ||
| if req.Message == "" || req.Signature == "" { | ||
| return apperrors.BadRequestError(nil, "message and signature are required") | ||
| } | ||
|
|
||
| res, err := h.svc.Login(r.Context(), req.Message, req.Signature) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| writeJSON(w, http.StatusOK, res) | ||
| return nil | ||
| } | ||
|
|
||
| func (h *httpHandler) jwks(w http.ResponseWriter, _ *http.Request) error { | ||
| writeJSON(w, http.StatusOK, h.svc.JWKS()) | ||
| return nil | ||
| } | ||
|
|
||
| func readJSON(r *http.Request, dst any) error { | ||
| dec := json.NewDecoder(io.LimitReader(r.Body, maxRequestBodyBytes)) | ||
| dec.DisallowUnknownFields() | ||
| if err := dec.Decode(dst); err != nil { | ||
| return apperrors.BadRequestError(err, "invalid JSON") | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func writeJSON(w http.ResponseWriter, status int, data any) { | ||
| w.Header().Set("Content-Type", "application/json") | ||
| w.WriteHeader(status) | ||
| _ = json.NewEncoder(w).Encode(data) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package service | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/go-chi/chi/v5" | ||
| "github.com/stretchr/testify/mock" | ||
| "go.uber.org/zap" | ||
|
|
||
| apperrors "github.com/chainsafe/canton-middleware/pkg/app/errors" | ||
| "github.com/chainsafe/canton-middleware/pkg/auth" | ||
| "github.com/chainsafe/canton-middleware/pkg/auth/jwt" | ||
| "github.com/chainsafe/canton-middleware/pkg/auth/service/mocks" | ||
| ) | ||
|
|
||
| func newLoginTestServer(svc Service) http.Handler { | ||
| r := chi.NewRouter() | ||
| RegisterRoutes(r, svc, zap.NewNop()) | ||
| return r | ||
| } | ||
|
|
||
| func TestNonceHTTP_ReturnsNonce(t *testing.T) { | ||
| svc := mocks.NewService(t) | ||
| svc.EXPECT().Nonce(mock.Anything).Return("the-nonce", nil) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| req := httptest.NewRequest(http.MethodGet, "/auth/nonce?address=0x0000000000000000000000000000000000000001", nil) | ||
| newLoginTestServer(svc).ServeHTTP(rec, req) | ||
|
|
||
| if rec.Code != http.StatusOK { | ||
| t.Fatalf("status = %d, want 200", rec.Code) | ||
| } | ||
| var got auth.NonceResponse | ||
| if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { | ||
| t.Fatalf("decode: %v", err) | ||
| } | ||
| if got.Nonce != "the-nonce" { | ||
| t.Fatalf("nonce = %q, want the-nonce", got.Nonce) | ||
| } | ||
| } | ||
|
|
||
| func TestNonceHTTP_MissingOrInvalidAddress_Returns400(t *testing.T) { | ||
| svc := mocks.NewService(t) // Nonce must not be called | ||
|
|
||
| for _, q := range []string{"/auth/nonce", "/auth/nonce?address=not-an-address"} { | ||
| rec := httptest.NewRecorder() | ||
| newLoginTestServer(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, q, nil)) | ||
| if rec.Code != http.StatusBadRequest { | ||
| t.Fatalf("%s: status = %d, want 400", q, rec.Code) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestLoginHTTP_Success(t *testing.T) { | ||
| svc := mocks.NewService(t) | ||
| svc.EXPECT().Login(mock.Anything, "msg", "sig"). | ||
| Return(&auth.LoginResponse{Token: "tok", ExpiresAt: 12345}, nil) | ||
|
|
||
| body, _ := json.Marshal(auth.LoginRequest{Message: "msg", Signature: "sig"}) | ||
| rec := httptest.NewRecorder() | ||
| newLoginTestServer(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(string(body)))) | ||
|
|
||
| if rec.Code != http.StatusOK { | ||
| t.Fatalf("status = %d, want 200, body = %s", rec.Code, rec.Body.String()) | ||
| } | ||
| var got auth.LoginResponse | ||
| if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { | ||
| t.Fatalf("decode: %v", err) | ||
| } | ||
| if got.Token != "tok" || got.ExpiresAt != 12345 { | ||
| t.Fatalf("response = %+v, want {tok 12345}", got) | ||
| } | ||
| } | ||
|
|
||
| func TestLoginHTTP_InvalidJSON_Returns400(t *testing.T) { | ||
| svc := mocks.NewService(t) // Login must not be called | ||
| rec := httptest.NewRecorder() | ||
| newLoginTestServer(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader("{not json"))) | ||
|
|
||
| if rec.Code != http.StatusBadRequest { | ||
| t.Fatalf("status = %d, want 400", rec.Code) | ||
| } | ||
| } | ||
|
|
||
| func TestLoginHTTP_MissingFields_Returns400(t *testing.T) { | ||
| svc := mocks.NewService(t) // Login must not be called | ||
| body, _ := json.Marshal(auth.LoginRequest{Message: "msg"}) // signature missing | ||
| rec := httptest.NewRecorder() | ||
| newLoginTestServer(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(string(body)))) | ||
|
|
||
| if rec.Code != http.StatusBadRequest { | ||
| t.Fatalf("status = %d, want 400", rec.Code) | ||
| } | ||
| } | ||
|
|
||
| func TestLoginHTTP_ServiceUnauthorized_Returns401(t *testing.T) { | ||
| svc := mocks.NewService(t) | ||
| svc.EXPECT().Login(mock.Anything, "msg", "sig"). | ||
| Return(nil, apperrors.UnAuthorizedError(nil, "invalid sign-in message or signature")) | ||
|
|
||
| body, _ := json.Marshal(auth.LoginRequest{Message: "msg", Signature: "sig"}) | ||
| rec := httptest.NewRecorder() | ||
| newLoginTestServer(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/auth/login", strings.NewReader(string(body)))) | ||
|
|
||
| if rec.Code != http.StatusUnauthorized { | ||
| t.Fatalf("status = %d, want 401", rec.Code) | ||
| } | ||
| } | ||
|
|
||
| func TestJWKSHTTP_ServesKeySet(t *testing.T) { | ||
| svc := mocks.NewService(t) | ||
| svc.EXPECT().JWKS().Return(jwt.JWKS{Keys: []jwt.JWK{{Kid: "kid-1", Kty: "RSA"}}}) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| newLoginTestServer(svc).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/.well-known/jwks.json", nil)) | ||
|
|
||
| if rec.Code != http.StatusOK { | ||
| t.Fatalf("status = %d, want 200", rec.Code) | ||
| } | ||
| var got jwt.JWKS | ||
| if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { | ||
| t.Fatalf("decode: %v", err) | ||
| } | ||
| if len(got.Keys) != 1 || got.Keys[0].Kid != "kid-1" { | ||
| t.Fatalf("jwks = %+v, want one key kid-1", got) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package service | ||
|
|
||
| import ( | ||
| "context" | ||
| "time" | ||
|
|
||
| "go.uber.org/zap" | ||
|
|
||
| "github.com/chainsafe/canton-middleware/pkg/auth" | ||
| "github.com/chainsafe/canton-middleware/pkg/auth/jwt" | ||
| ) | ||
|
|
||
| const loginServiceName = "LoginService" | ||
|
|
||
| // logService wraps Service with logging of the login call. Nonce and JWKS are | ||
| // trivial accessors and pass through unlogged; Login is the meaningful operation, | ||
| // so its entry/exit, duration, and errors are recorded (never the message or | ||
| // signature, which are sensitive). | ||
| type logService struct { | ||
| svc Service | ||
| logger *zap.Logger | ||
| } | ||
|
|
||
| // NewLog creates a logging decorator for the login Service. | ||
| func NewLog(svc Service, logger *zap.Logger) Service { | ||
| return &logService{svc: svc, logger: logger} | ||
| } | ||
|
|
||
| func (ls *logService) Nonce(address string) (string, error) { return ls.svc.Nonce(address) } | ||
|
|
||
| func (ls *logService) JWKS() jwt.JWKS { return ls.svc.JWKS() } | ||
|
|
||
| func (ls *logService) Login(ctx context.Context, message, signature string) (resp *auth.LoginResponse, err error) { | ||
| start := time.Now() | ||
|
|
||
| ls.logger.Info("Login started", | ||
| zap.String("service", loginServiceName), | ||
| zap.String("method", "Login"), | ||
| ) | ||
|
|
||
| defer func() { | ||
| duration := time.Since(start) | ||
|
|
||
| if err != nil { | ||
| ls.logger.Error("Login failed", | ||
| zap.String("service", loginServiceName), | ||
| zap.String("method", "Login"), | ||
| zap.Duration("duration", duration), | ||
| zap.Error(err), | ||
| ) | ||
| } else { | ||
| fields := []zap.Field{ | ||
| zap.String("service", loginServiceName), | ||
| zap.String("method", "Login"), | ||
| zap.Duration("duration", duration), | ||
| } | ||
| // resp is non-nil on the nil-error path, but guard defensively: this | ||
| // decorator wraps an interface any implementation could satisfy. | ||
| if resp != nil { | ||
| fields = append(fields, zap.Int64("expires_at", resp.ExpiresAt)) | ||
| } | ||
| ls.logger.Info("Login completed", fields...) | ||
| } | ||
| }() | ||
|
|
||
| return ls.svc.Login(ctx, message, signature) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.