Repository navigation
feat(notifications): per-recipient mute + List-Unsubscribe (closes #297) #828
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
43b03b6
feat(notifications): per-recipient mute + List-Unsubscribe (closes #297)
cristim 5d8f459
fix(ci): add IsNotificationMuted to all config.StoreInterface mocks (…
cristim b6882d6
fix(notifications): wire per-recipient mute + List-Unsubscribe into p…
cristim ed4500d
fix(notifications): fix hardcoded MIME boundary in SMTP+List-Unsubscr…
cristim 5d143d4
fix(notifications): harden mute token + close CC unsubscribe IDOR
cristim b92ae04
fix(notifications): defer mute-sender wiring to reinitializeAfterConnect
cristim 8df363a
fix(lint): gocritic/unparam/unused + migration renumber in notificati…
cristim aef1850
fix(notifications): harden one-click unsubscribe delivery
cristim 03a7f98
fix(email): remove unused isMuted/filterMutedAddresses wrappers; name…
cristim f49cb41
fix(deps): bump brace-expansion to 1.1.16 (GHSA-3jxr-9vmj-r5cp)
cristim 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,143 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "html/template" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| "github.com/LeanerCloud/CUDly/pkg/common" | ||
| "github.com/LeanerCloud/CUDly/pkg/logging" | ||
| "github.com/aws/aws-lambda-go/events" | ||
| ) | ||
|
|
||
| // mutePageCSP is the Content-Security-Policy for the unsubscribe confirmation | ||
| // page. The page is intentionally minimal (no external scripts or styles), so | ||
| // we can lock it down tightly. | ||
| const mutePageCSP = "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'" | ||
|
|
||
| // unsubscribeConfirmTmpl is the HTML confirmation page rendered after a | ||
| // successful one-click unsubscribe. No user-supplied data is interpolated via | ||
| // {{.}} without html/template escaping, so there is no XSS vector. | ||
| var unsubscribeConfirmTmpl = template.Must(template.New("unsub").Parse(`<!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="UTF-8"> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
| <title>Unsubscribed</title> | ||
| <style> | ||
| body{font-family:sans-serif;max-width:480px;margin:80px auto;padding:0 1rem;color:#222} | ||
| h1{font-size:1.4rem} | ||
| p{line-height:1.6} | ||
| </style> | ||
| </head> | ||
| <body> | ||
| <h1>You have been unsubscribed.</h1> | ||
| <p>You will no longer receive <strong>{{.ScopeLabel}}</strong> emails at this address.</p> | ||
| <p>This preference is saved. You do not need to click again.</p> | ||
| </body> | ||
| </html> | ||
| `)) | ||
|
|
||
| // scopeLabel returns a human-readable label for a notification scope. | ||
| func scopeLabel(scope string) string { | ||
| switch scope { | ||
| case string(common.ScopePurchaseApprovals): | ||
| return "purchase approval request" | ||
| case string(common.ScopeRIExchangeApprovals): | ||
| return "RI exchange approval request" | ||
| default: | ||
| return "notification" | ||
| } | ||
| } | ||
|
|
||
| func validateOneClickUnsubscribeBody(req *events.LambdaFunctionURLRequest) error { | ||
| if req.RequestContext.HTTP.Method != "POST" { | ||
| return nil | ||
| } | ||
| values, err := url.ParseQuery(req.Body) | ||
| if err != nil || len(values) != 1 || len(values["List-Unsubscribe"]) != 1 || | ||
| values.Get("List-Unsubscribe") != "One-Click" { | ||
| return NewClientError(400, "invalid one-click unsubscribe body") | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func unsubscribeRequestParams(req *events.LambdaFunctionURLRequest) (token, email, scope string, err error) { | ||
| token = req.QueryStringParameters["token"] | ||
| email = req.QueryStringParameters["email"] | ||
| scope = req.QueryStringParameters["scope"] | ||
| if token == "" || email == "" || scope == "" { | ||
| return "", "", "", NewClientError(400, "token, email and scope are required") | ||
| } | ||
| if scope != string(common.ScopePurchaseApprovals) && scope != string(common.ScopeRIExchangeApprovals) { | ||
| return "", "", "", NewClientError(400, fmt.Sprintf("unknown notification scope: %s", scope)) | ||
| } | ||
| return token, email, scope, nil | ||
| } | ||
|
|
||
| // unsubscribeHandler handles GET and RFC 8058 POST requests to | ||
| // /api/notifications/unsubscribe. | ||
| // The URL carries a signed token that encodes (email, scope); the handler | ||
| // verifies the HMAC, upserts the mute row, and returns a confirmation page. | ||
| // | ||
| // Auth: AuthPublic (token-based, no login required — mirrors approve/cancel). | ||
| func (h *Handler) unsubscribeHandler(ctx context.Context, req *events.LambdaFunctionURLRequest, _ map[string]string) (any, error) { | ||
| if err := validateOneClickUnsubscribeBody(req); err != nil { | ||
| return nil, err | ||
| } | ||
| token, email, scope, err := unsubscribeRequestParams(req) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Resolve the HMAC key with the fail-closed policy: a missing | ||
| // NOTIFICATION_MUTE_SECRET is a server misconfiguration, not a client error, | ||
| // and must never silently verify against a well-known key. | ||
| key, err := common.ResolveMuteSecret() | ||
| if err != nil { | ||
| logging.Errorf("notifications/unsubscribe: %v", err) | ||
| return nil, fmt.Errorf("unsubscribe is not configured: %w", err) | ||
| } | ||
| if !common.VerifyMuteToken(key, email, scope, token) { | ||
| logging.Warnf("notifications/unsubscribe: invalid token for scope=%s", scope) | ||
| return nil, NewClientError(401, "invalid or expired unsubscribe token") | ||
| } | ||
|
|
||
| if err := h.config.UpsertNotificationMute(ctx, email, scope, token); err != nil { | ||
| logging.Errorf("notifications/unsubscribe: store error: %v", err) | ||
| return nil, fmt.Errorf("could not save unsubscribe preference: %w", err) | ||
| } | ||
|
|
||
| logging.Infof("notifications/unsubscribe: muted scope=%s for %s", scope, redactEmailLocal(email)) | ||
|
|
||
| var buf strings.Builder | ||
| if err := unsubscribeConfirmTmpl.Execute(&buf, struct{ ScopeLabel string }{ | ||
| ScopeLabel: scopeLabel(scope), | ||
| }); err != nil { | ||
| return nil, fmt.Errorf("render unsubscribe page: %w", err) | ||
| } | ||
|
|
||
| return &rawResponse{ | ||
| contentType: "text/html; charset=utf-8", | ||
| body: buf.String(), | ||
| csp: mutePageCSP, | ||
| }, nil | ||
| } | ||
|
|
||
| // redactEmailLocal returns just the domain part with the local masked, e.g. | ||
| // "us***@example.com". Reuses the same masking logic as email/sender.go but | ||
| // without importing that package into api (avoids a dependency cycle). | ||
| func redactEmailLocal(email string) string { | ||
| at := strings.LastIndex(email, "@") | ||
| if at < 0 { | ||
| return "***" | ||
| } | ||
| local := email[:at] | ||
| domain := email[at:] // includes '@' | ||
| if len(local) <= 2 { | ||
| return "***" + domain | ||
| } | ||
| return local[:2] + "***" + domain | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
GET-triggers-mutation bug spans handler, routing, and its own test coverage. The root cause is in
unsubscribeHandler, which mutates unconditionally regardless of HTTP method;router.goroutes both verbs to it unchanged (no fix needed there), and the test suite currently asserts the buggy behavior as correct.internal/api/handler_notifications.go#L86-L127: gateh.config.UpsertNotificationMute(and the "you have been unsubscribed" response) behind a validated POST; render a non-mutating confirmation/landing page for GET.internal/api/router.go#L323-L327: no change required — once the handler branches on method internally, the existing GET+POST routing to the same handler is fine.internal/api/handler_notifications_test.go#L28-L55: updateTestUnsubscribeHandler_Success(and add a GET-specific test) to assert GET does not callUpsertNotificationMuteand instead returns a confirmation form; keep the existing POST-based mutation assertions inTestRouter_UnsubscribePOSTRoute_MutesSignedRecipientAndScope.📍 Affects 3 files
internal/api/handler_notifications.go#L86-L127(this comment)internal/api/router.go#L323-L327internal/api/handler_notifications_test.go#L28-L55🤖 Prompt for AI Agents