feat(identity): add server sessions and audited mail recovery

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:03:46 +03:00
1 parent 20c03288d6
commit 4ee53d9a74
58 files changed
+5359 -567

No files matched your search

@@ -47,6 +47,12 @@ type Reply struct {
// Name is the Resend error name for a non-2xx answer, for example
// "daily_quota_exceeded".
Name string
// RetryAfter is copied to the response header for a rate-limit fixture.
RetryAfter string
// DropAfterAccept stores the message and closes the connection without an
// HTTP answer, like a provider accepting the request before the response
// is lost.
DropAfterAccept bool
}
// Server is the fixture. Create it with New.
@@ -61,17 +67,22 @@ type Server struct {
mu sync.Mutex
requests []Request
messages map[string]message // by idempotency key
accepted int
scripted []Reply
clock func() time.Time
}
type message struct {
id string
body string
id string
body string
acceptedAt time.Time
}
const providerIdempotencyWindow = 24 * time.Hour
// New starts the fixture on a loopback address.
func New() *Server {
server := &Server{messages: make(map[string]message)}
server := &Server{messages: make(map[string]message), clock: time.Now}
server.http = httptest.NewServer(http.HandlerFunc(server.serve))
return server
}
@@ -94,6 +105,18 @@ func (server *Server) Script(replies ...Reply) {
// test can act while a send is in flight.
func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) }
// SetClock replaces the provider clock so tests can expire idempotency keys
// without waiting in real time.
func (server *Server) SetClock(clock func() time.Time) {
server.mu.Lock()
defer server.mu.Unlock()
if clock == nil {
server.clock = time.Now
return
}
server.clock = clock
}
// Arrivals returns how many calls the fixture has received, answered or
// not yet.
func (server *Server) Arrivals() int { return int(server.arrivals.Load()) }
@@ -110,7 +133,7 @@ func (server *Server) Requests() []Request {
func (server *Server) Messages() int {
server.mu.Lock()
defer server.mu.Unlock()
return len(server.messages)
return server.accepted
}
func (server *Server) serve(response http.ResponseWriter, request *http.Request) {
@@ -118,18 +141,26 @@ func (server *Server) serve(response http.ResponseWriter, request *http.Request)
if delay := time.Duration(server.delay.Load()); delay > 0 {
time.Sleep(delay)
}
payload, record, ok := readRequest(response, request)
if !ok {
return
}
server.handleEmail(response, payload, record)
}
func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, Request, bool) {
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
writeError(response, http.StatusNotFound, "not_found")
return
return nil, Request{}, false
}
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
writeError(response, http.StatusUnauthorized, "invalid_api_key")
return
return nil, Request{}, false
}
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes))
if err != nil {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return
return nil, Request{}, false
}
var body struct {
To []string `json:"to"`
@@ -139,41 +170,78 @@ func (server *Server) serve(response http.ResponseWriter, request *http.Request)
}
if err := json.Unmarshal(payload, &body); err != nil {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return
return nil, Request{}, false
}
key := request.Header.Get("Idempotency-Key")
record := Request{IdempotencyKey: key, To: body.To, Subject: body.Subject, Text: body.Text, HTML: body.HTML}
return payload, Request{
IdempotencyKey: request.Header.Get("Idempotency-Key"),
To: body.To,
Subject: body.Subject,
Text: body.Text,
HTML: body.HTML,
}, true
}
func (server *Server) handleEmail(response http.ResponseWriter, payload []byte, record Request) {
server.mu.Lock()
defer server.mu.Unlock()
reply := Reply{}
if len(server.scripted) > 0 {
reply := server.scripted[0]
reply = server.scripted[0]
server.scripted = server.scripted[1:]
}
now := server.clock()
known, seen := server.messages[record.IdempotencyKey]
if seen && now.Sub(known.acceptedAt) >= providerIdempotencyWindow {
delete(server.messages, record.IdempotencyKey)
seen = false
}
if reply.Status != 0 {
server.requests = append(server.requests, record)
server.mu.Unlock()
if reply.RetryAfter != "" {
response.Header().Set("Retry-After", reply.RetryAfter)
}
writeError(response, reply.Status, reply.Name)
return
}
known, seen := server.messages[key]
switch {
case seen && known.body != string(payload):
// The key was used with another body: Resend refuses it.
server.requests = append(server.requests, record)
messageID, replayed, conflict := server.recordAcceptanceLocked(record.IdempotencyKey, string(payload), now, known, seen)
record.Replayed = replayed
server.requests = append(server.requests, record)
server.mu.Unlock()
if conflict {
writeError(response, http.StatusConflict, "invalid_idempotent_request")
return
case seen:
record.Replayed = true
server.requests = append(server.requests, record)
writeAccepted(response, known.id)
}
if reply.DropAfterAccept {
dropConnection(response)
return
}
accepted := message{id: uuid.NewString(), body: string(payload)}
writeAccepted(response, messageID)
}
func (server *Server) recordAcceptanceLocked(key, body string, now time.Time, known message, seen bool) (string, bool, bool) {
if seen {
if known.body != body {
return "", false, true
}
return known.id, true, false
}
accepted := message{id: uuid.NewString(), body: body, acceptedAt: now}
if key != "" {
server.messages[key] = accepted
} else {
server.messages[accepted.id] = accepted
}
server.requests = append(server.requests, record)
writeAccepted(response, accepted.id)
server.accepted++
return accepted.id, false, false
}
func dropConnection(response http.ResponseWriter) {
if hijacker, ok := response.(http.Hijacker); ok {
connection, _, err := hijacker.Hijack()
if err == nil {
_ = connection.Close()
}
}
}
func writeAccepted(response http.ResponseWriter, id string) {