279 lines
7.9 KiB
Go
279 lines
7.9 KiB
Go
//go:build e2e
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
const (
|
|
fixtureEnabledName = "E2E_COMPANY_FIXTURE"
|
|
fixtureAuthEnvName = "E2E_COMPANY_FIXTURE_TOKEN"
|
|
fixtureListenAddr = ":8081"
|
|
fixtureEndpoint = "/company/memberships/revoke"
|
|
fixtureHealthPath = "/healthcheck"
|
|
maxRequestBody = 1024
|
|
maxFixtureRequests = 32
|
|
requestTimeout = 5 * time.Second
|
|
readHeaderTimeout = 3 * time.Second
|
|
readTimeout = 5 * time.Second
|
|
writeTimeout = 5 * time.Second
|
|
idleTimeout = 15 * time.Second
|
|
)
|
|
|
|
type membershipRevoker func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error
|
|
|
|
type fixtureHandler struct {
|
|
token string
|
|
revoke membershipRevoker
|
|
requests atomic.Uint32
|
|
}
|
|
|
|
type revokeMembershipRequest struct {
|
|
OrganizationID string `json:"organization_id"`
|
|
UserID string `json:"user_id"`
|
|
SuccessorUserID string `json:"successor_user_id"`
|
|
}
|
|
|
|
func main() {
|
|
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
|
if err := checkHealth(); err != nil {
|
|
os.Exit(1)
|
|
}
|
|
return
|
|
}
|
|
if err := serve(); err != nil {
|
|
_, _ = io.WriteString(os.Stderr, "Company fixture could not start.\n")
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
func serve() error {
|
|
if os.Getenv(fixtureEnabledName) != "1" {
|
|
return errors.New("company fixture requires the isolated e2e environment")
|
|
}
|
|
token := os.Getenv(fixtureAuthEnvName)
|
|
if !hasFixtureTokenStrength(token) {
|
|
return errors.New("company fixture token must contain at least 32 random bytes")
|
|
}
|
|
databaseURL := os.Getenv("DATABASE_URL")
|
|
if databaseURL == "" {
|
|
return errors.New("company fixture database is not configured")
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
|
|
defer cancel()
|
|
pool, err := postgres.NewSizedPool(ctx, databaseURL, 4)
|
|
if err != nil {
|
|
return errors.New("company fixture could not open its database")
|
|
}
|
|
defer pool.Close()
|
|
if err := pool.Ping(ctx); err != nil {
|
|
return errors.New("company fixture database is unavailable")
|
|
}
|
|
|
|
server := &http.Server{
|
|
Addr: fixtureListenAddr,
|
|
Handler: &fixtureHandler{
|
|
token: token,
|
|
revoke: func(ctx context.Context, organizationID, userID, successorUserID uuid.UUID) error {
|
|
return postgres.RevokeCompanyFixtureMembership(ctx, pool, organizationID, userID, successorUserID)
|
|
},
|
|
},
|
|
ReadHeaderTimeout: readHeaderTimeout,
|
|
ReadTimeout: readTimeout,
|
|
WriteTimeout: writeTimeout,
|
|
IdleTimeout: idleTimeout,
|
|
MaxHeaderBytes: 4096,
|
|
ErrorLog: log.New(io.Discard, "", 0),
|
|
}
|
|
return server.ListenAndServe()
|
|
}
|
|
|
|
func checkHealth() error {
|
|
client := http.Client{Timeout: time.Second}
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
defer cancel()
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:8081"+fixtureHealthPath, nil)
|
|
if err != nil {
|
|
return errors.New("company fixture is not healthy")
|
|
}
|
|
response, err := client.Do(request)
|
|
if err != nil {
|
|
return errors.New("company fixture is not healthy")
|
|
}
|
|
defer func() { _ = response.Body.Close() }()
|
|
if response.StatusCode != http.StatusNoContent {
|
|
return errors.New("company fixture is not healthy")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func hasFixtureTokenStrength(token string) bool {
|
|
if decoded, err := hex.DecodeString(token); err == nil && len(decoded) >= 32 {
|
|
return true
|
|
}
|
|
decoded, err := base64.RawURLEncoding.Strict().DecodeString(token)
|
|
return err == nil && len(decoded) >= 32
|
|
}
|
|
|
|
func (handler *fixtureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case fixtureHealthPath:
|
|
handler.serveHealthcheck(w, r)
|
|
case fixtureEndpoint:
|
|
handler.serveMembershipRevocation(w, r)
|
|
default:
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}
|
|
|
|
func (handler *fixtureHandler) serveHealthcheck(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
w.Header().Set("Allow", http.MethodGet)
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (handler *fixtureHandler) serveMembershipRevocation(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
if handler.requests.Add(1) > maxFixtureRequests {
|
|
w.WriteHeader(http.StatusTooManyRequests)
|
|
return
|
|
}
|
|
if !hasFixtureBearerToken(r.Header.Get("Authorization"), handler.token) {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
if !isJSONRequest(r) {
|
|
w.WriteHeader(http.StatusUnsupportedMediaType)
|
|
return
|
|
}
|
|
|
|
request, status := decodeRevokeMembershipRequest(w, r)
|
|
if status != 0 {
|
|
w.WriteHeader(status)
|
|
return
|
|
}
|
|
if handler.revoke == nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
|
|
defer cancel()
|
|
if err := handler.revoke(ctx, request.organizationID, request.userID, request.successorUserID); err != nil {
|
|
w.WriteHeader(statusForFixtureError(err))
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
type parsedRevokeMembershipRequest struct {
|
|
organizationID uuid.UUID
|
|
userID uuid.UUID
|
|
successorUserID uuid.UUID
|
|
}
|
|
|
|
func decodeRevokeMembershipRequest(w http.ResponseWriter, r *http.Request) (parsedRevokeMembershipRequest, int) {
|
|
request, status := decodeRevokeRequest(w, r)
|
|
if status != 0 {
|
|
return parsedRevokeMembershipRequest{}, status
|
|
}
|
|
organizationID, err := uuid.Parse(request.OrganizationID)
|
|
if err != nil || organizationID == uuid.Nil {
|
|
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
|
|
}
|
|
userID, err := uuid.Parse(request.UserID)
|
|
if err != nil || userID == uuid.Nil {
|
|
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
|
|
}
|
|
successorUserID, err := uuid.Parse(request.SuccessorUserID)
|
|
if err != nil || successorUserID == uuid.Nil || successorUserID == userID {
|
|
return parsedRevokeMembershipRequest{}, http.StatusBadRequest
|
|
}
|
|
return parsedRevokeMembershipRequest{
|
|
organizationID: organizationID,
|
|
userID: userID,
|
|
successorUserID: successorUserID,
|
|
}, 0
|
|
}
|
|
|
|
func isJSONRequest(r *http.Request) bool {
|
|
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
|
return err == nil && strings.EqualFold(mediaType, "application/json")
|
|
}
|
|
|
|
func decodeRevokeRequest(w http.ResponseWriter, r *http.Request) (revokeMembershipRequest, int) {
|
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBody))
|
|
decoder.DisallowUnknownFields()
|
|
var request revokeMembershipRequest
|
|
if err := decoder.Decode(&request); err != nil {
|
|
return revokeMembershipRequest{}, statusForDecodeError(err)
|
|
}
|
|
var trailing any
|
|
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
|
return revokeMembershipRequest{}, statusForDecodeError(err)
|
|
}
|
|
if request.OrganizationID == "" || request.UserID == "" {
|
|
return revokeMembershipRequest{}, http.StatusBadRequest
|
|
}
|
|
return request, 0
|
|
}
|
|
|
|
func statusForDecodeError(err error) int {
|
|
var tooLarge *http.MaxBytesError
|
|
if errors.As(err, &tooLarge) {
|
|
return http.StatusRequestEntityTooLarge
|
|
}
|
|
return http.StatusBadRequest
|
|
}
|
|
|
|
func statusForFixtureError(err error) int {
|
|
switch {
|
|
case errors.Is(err, postgres.ErrCompanyFixtureScope),
|
|
errors.Is(err, outbound.ErrUserNotFound),
|
|
errors.Is(err, outbound.ErrMembershipNotFound),
|
|
errors.Is(err, outbound.ErrOrganizationNotFound):
|
|
return http.StatusNotFound
|
|
case errors.Is(err, outbound.ErrTransactionConflict):
|
|
return http.StatusConflict
|
|
default:
|
|
return http.StatusInternalServerError
|
|
}
|
|
}
|
|
|
|
func hasFixtureBearerToken(header, token string) bool {
|
|
prefix, supplied, ok := strings.Cut(header, " ")
|
|
if !ok || prefix != "Bearer" || supplied == "" {
|
|
return false
|
|
}
|
|
expectedDigest := sha256.Sum256([]byte(token))
|
|
suppliedDigest := sha256.Sum256([]byte(supplied))
|
|
return subtle.ConstantTimeCompare(expectedDigest[:], suppliedDigest[:]) == 1
|
|
}
|