feat: refresh settings, sync account avatars and link account management
This commit is contained in:
1 parent
fa1832dfa7
commit
d3d164910b
22 files changed
+789
-407
No files matched your search
@@ -20,6 +20,7 @@ type userInfo struct {
|
||||
Username string `json:"username"`
|
||||
ProfileName string `json:"profileName,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Picture string `json:"picture,omitempty"`
|
||||
AceEditorTheme string `json:"aceEditorTheme"`
|
||||
}
|
||||
|
||||
|
||||
+19
-4
@@ -24,15 +24,17 @@ import (
|
||||
|
||||
type identityKey struct{}
|
||||
type sessionIdentity struct {
|
||||
ID uint
|
||||
Admin bool
|
||||
Name string
|
||||
ID uint
|
||||
Admin bool
|
||||
Name string
|
||||
Picture string
|
||||
}
|
||||
type ssoClaims struct {
|
||||
Subject string `json:"sub"`
|
||||
Username string `json:"preferred_username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Picture string `json:"picture"`
|
||||
Roles []string `json:"roles"`
|
||||
}
|
||||
type loginAttempt struct {
|
||||
@@ -267,12 +269,16 @@ func (s *SSO) callback(w http.ResponseWriter, r *http.Request) {
|
||||
if claims.Email == "" {
|
||||
claims.Email = info.Email
|
||||
}
|
||||
if claims.Picture == "" {
|
||||
claims.Picture = info.Picture
|
||||
}
|
||||
}
|
||||
identity, err := s.provisionUser(claims)
|
||||
if err != nil {
|
||||
http.Error(w, "Cannot provision SSO user", 500)
|
||||
return
|
||||
}
|
||||
identity.Picture = s.loadAvatar(ctx, claims.Picture)
|
||||
sid := randomSecret()
|
||||
key := sha256.Sum256([]byte(sid))
|
||||
s.mu.Lock()
|
||||
@@ -386,6 +392,13 @@ func (s *SSO) Wrap(next http.Handler) http.Handler {
|
||||
}
|
||||
}
|
||||
switch p {
|
||||
case "/auth/account":
|
||||
if r.Method != http.MethodGet {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, strings.TrimRight(s.issuer, "/")+"/settings", http.StatusFound)
|
||||
return
|
||||
case "/auth/login":
|
||||
s.login(w, r)
|
||||
return
|
||||
@@ -426,7 +439,9 @@ func (s *SSO) Wrap(next http.Handler) http.Handler {
|
||||
}
|
||||
applySSOIdentity(u, identity)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(ssoUserInfo(u))
|
||||
profile := ssoUserInfo(u)
|
||||
profile.Picture = identity.Picture
|
||||
_ = json.NewEncoder(w).Encode(profile)
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/image/draw"
|
||||
_ "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
// Fetch only public avatar images on the configured identity provider, without
|
||||
// credentials or redirects. Keep a small raster thumbnail in the local session.
|
||||
func (s *SSO) loadAvatar(ctx context.Context, picture string) string {
|
||||
if picture == "" {
|
||||
return ""
|
||||
}
|
||||
issuer, err := url.Parse(s.issuer)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
target, err := url.Parse(picture)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
target = issuer.ResolveReference(target)
|
||||
prefix := strings.TrimRight(issuer.Path, "/") + "/avatars/"
|
||||
if target.Scheme != issuer.Scheme || !strings.EqualFold(target.Host, issuer.Host) || target.User != nil || target.Fragment != "" || !strings.HasPrefix(path.Clean(target.Path), prefix) {
|
||||
return ""
|
||||
}
|
||||
client := &http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return ""
|
||||
}
|
||||
const limit = 256 * 1024
|
||||
raw, err := io.ReadAll(io.LimitReader(response.Body, limit+1))
|
||||
if err != nil || len(raw) > limit {
|
||||
return ""
|
||||
}
|
||||
config, format, err := image.DecodeConfig(bytes.NewReader(raw))
|
||||
if err != nil || (format != "png" && format != "jpeg" && format != "webp") || config.Width < 1 || config.Height < 1 || config.Width > 1024 || config.Height > 1024 {
|
||||
return ""
|
||||
}
|
||||
original, _, err := image.Decode(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
width, height := config.Width, config.Height
|
||||
if width > 128 || height > 128 {
|
||||
if width >= height {
|
||||
height = max(1, height*128/width)
|
||||
width = 128
|
||||
} else {
|
||||
width = max(1, width*128/height)
|
||||
height = 128
|
||||
}
|
||||
}
|
||||
thumbnail := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
draw.ApproxBiLinear.Scale(thumbnail, thumbnail.Bounds(), original, original.Bounds(), draw.Src, nil)
|
||||
var output bytes.Buffer
|
||||
if png.Encode(&output, thumbnail) != nil {
|
||||
return ""
|
||||
}
|
||||
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(output.Bytes())
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"image"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSSOAvatarUsesOnlyProviderRasterImages(t *testing.T) {
|
||||
var valid, oversized bytes.Buffer
|
||||
_ = png.Encode(&valid, image.NewRGBA(image.Rect(0, 0, 256, 128)))
|
||||
_ = png.Encode(&oversized, image.NewRGBA(image.Rect(0, 0, 1025, 1)))
|
||||
forbidden := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
|
||||
t.Error("avatar request forwarded credentials")
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/avatars/valid.png":
|
||||
_, _ = w.Write(valid.Bytes())
|
||||
case "/avatars/redirect":
|
||||
http.Redirect(w, r, "/forbidden", 302)
|
||||
case "/avatars/svg":
|
||||
_, _ = w.Write([]byte(`<svg xmlns="http://www.w3.org/2000/svg"/>`))
|
||||
case "/avatars/large":
|
||||
_, _ = w.Write(bytes.Repeat([]byte("x"), 256*1024+1))
|
||||
case "/avatars/dimensions":
|
||||
_, _ = w.Write(oversized.Bytes())
|
||||
default:
|
||||
forbidden++
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
s := &SSO{issuer: server.URL}
|
||||
avatar := s.loadAvatar(context.Background(), server.URL+"/avatars/valid.png")
|
||||
const prefix = "data:image/png;base64,"
|
||||
if !strings.HasPrefix(avatar, prefix) {
|
||||
t.Fatal("avatar not loaded")
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(avatar, prefix))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
size, err := png.DecodeConfig(bytes.NewReader(raw))
|
||||
if err != nil || size.Width != 128 || size.Height != 64 {
|
||||
t.Fatalf("invalid thumbnail: %+v %v", size, err)
|
||||
}
|
||||
for _, source := range []string{"", "https://other.example/avatars/a.png", server.URL + "/forbidden", server.URL + "/avatars/../forbidden", server.URL + "/avatars/redirect", server.URL + "/avatars/svg", server.URL + "/avatars/large", server.URL + "/avatars/dimensions"} {
|
||||
if got := s.loadAvatar(context.Background(), source); got != "" {
|
||||
t.Errorf("accepted avatar %q", source)
|
||||
}
|
||||
}
|
||||
if forbidden != 0 {
|
||||
t.Fatal("avatar loader requested a forbidden path or followed redirect")
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -1,12 +1,15 @@
|
||||
package fbhttp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"image"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
@@ -23,6 +26,10 @@ import (
|
||||
)
|
||||
|
||||
func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
var avatarPNG bytes.Buffer
|
||||
if err := png.Encode(&avatarPNG, image.NewRGBA(image.Rect(0, 0, 16, 16))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -68,7 +75,10 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
if r.Header.Get("Authorization") != "Bearer access" {
|
||||
t.Error("missing UserInfo bearer")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(ssoClaims{Subject: profileSubject, Username: "alice", Name: "Alice Example", Email: "alice@example.test", Roles: []string{"User"}})
|
||||
_ = json.NewEncoder(w).Encode(ssoClaims{Subject: profileSubject, Username: "alice", Name: "Alice Example", Email: "alice@example.test", Picture: issuer + "/avatars/alice.png", Roles: []string{"User"}})
|
||||
case "/avatars/alice.png":
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write(avatarPNG.Bytes())
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
@@ -126,6 +136,13 @@ func TestOIDCSessionLifecycle(t *testing.T) {
|
||||
if !strings.Contains(check.Body.String(), `"username":"alice"`) || !strings.Contains(check.Body.String(), `"email":"alice@example.test"`) {
|
||||
t.Fatalf("UserInfo profile not loaded: %s", check.Body.String())
|
||||
}
|
||||
if !strings.Contains(check.Body.String(), `"picture":"data:image/png;base64,`) {
|
||||
t.Fatalf("avatar missing from session: %s", check.Body.String())
|
||||
}
|
||||
account := request("GET", "/auth/account")
|
||||
if account.Code != http.StatusFound || account.Header().Get("Location") != issuer+"/settings" {
|
||||
t.Fatalf("account redirect: %d %s", account.Code, account.Header().Get("Location"))
|
||||
}
|
||||
// Repeated logins after changing preferences retain one local identity.
|
||||
var firstID uint
|
||||
for i := 0; i < 3; i++ {
|
||||
|
||||
Reference in new issue
Block a user