Просмотр исходного кода

fix: stop returning the session ID from WhoAmI

The session ID is the credential held in the HttpOnly session cookie,
so returning it in the WhoAmI response let any same-origin script read
it. WhoAmI now returns a session fingerprint instead, a truncated
SHA-256 of the session ID that tells sessions apart but cannot be used
to authenticate. The sid field is reserved in the proto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread 1 день назад
Родитель
Сommit
9da5827b79

+ 3 - 1
docs/modules/ROOT/pages/api/login.adoc

@@ -24,5 +24,7 @@ You can check your current login status by using the `/WhoAmI` API call. Like al
 
 ```bash
 user@host: curl http://localhost:1337/api/WhoAmI --json '{}' -b "olivetin-sid-local=cd33aa9c-c613-473e-8581-2b742716ab8e"
-{"authenticatedUser":"admin", "usergroup":"", "provider":"local", "acls":[], "sid":""}
+{"authenticatedUser":"admin", "usergroup":"", "provider":"local", "acls":[], "sessionFingerprint":"9c1f5e2a7b3d4c60"}
 ```
+
+`WhoAmI` never returns your session ID, because the session ID is the credential in your session cookie. `sessionFingerprint` is a short value derived from the session ID. Use it to tell sessions apart, for example to check that two requests used the same session. It cannot be used to log in. If an API client needs the session cookie, take it from the `Set-Cookie` header of the login response. See xref:upgrade/upgrade_notes.adoc#whoami-session-fingerprint[Upgrade Notes].

+ 7 - 0
docs/modules/ROOT/pages/upgrade/upgrade_notes.adoc

@@ -5,6 +5,13 @@ OliveTin releases are published to GitHub, and the release notes are contained t
 
 == Next release (unreleased)
 
+[#whoami-session-fingerprint]
+=== `WhoAmI` no longer returns the session ID
+
+The `WhoAmI` API used to return the caller's session ID in a `sid` field. That value is the credential held in the `HttpOnly` session cookie, so it should not be readable from a response. `sid` has been removed, and `WhoAmI` now returns `sessionFingerprint` instead: a short value derived from the session ID that tells sessions apart but cannot be used to log in.
+
+This only affects API clients or scripts that read `sid` from `WhoAmI`. If you used it to get the session cookie, take the cookie from the `Set-Cookie` header of the login response instead. If you used it to identify a session, use `sessionFingerprint`. See xref:api/login.adoc[Login].
+
 [#example-config-guest-actions]
 === The example config only lets guests run harmless demo actions
 

+ 2 - 2
frontend/resources/scripts/gen/olivetin/api/v1/olivetin_pb.d.ts

@@ -1297,9 +1297,9 @@ export declare type WhoAmIResponse = Message<"olivetin.api.v1.WhoAmIResponse"> &
   acls: string[];
 
   /**
-   * @generated from field: string sid = 5;
+   * @generated from field: string session_fingerprint = 6;
    */
-  sid: string;
+  sessionFingerprint: string;
 };
 
 /**

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
frontend/resources/scripts/gen/olivetin/api/v1/olivetin_pb.js


+ 7 - 1
proto/olivetin/api/v1/olivetin.proto

@@ -303,7 +303,13 @@ message WhoAmIResponse {
 
     repeated string acls = 4;
 
-    string sid = 5;
+    // The session ID was returned here until it was replaced by
+    // session_fingerprint, because the session ID is the session's
+    // credential.
+    reserved 5;
+    reserved "sid";
+
+    string session_fingerprint = 6;
 }
 
 message ServerDiagnosticsRequest {}

+ 13 - 13
service/gen/olivetin/api/v1/olivetin.pb.go

@@ -2786,14 +2786,14 @@ func (*WhoAmIRequest) Descriptor() ([]byte, []int) {
 }
 
 type WhoAmIResponse struct {
-	state             protoimpl.MessageState `protogen:"open.v1"`
-	AuthenticatedUser string                 `protobuf:"bytes,1,opt,name=authenticated_user,json=authenticatedUser,proto3" json:"authenticated_user,omitempty"`
-	Usergroup         string                 `protobuf:"bytes,2,opt,name=usergroup,proto3" json:"usergroup,omitempty"`
-	Provider          string                 `protobuf:"bytes,3,opt,name=provider,proto3" json:"provider,omitempty"`
-	Acls              []string               `protobuf:"bytes,4,rep,name=acls,proto3" json:"acls,omitempty"`
-	Sid               string                 `protobuf:"bytes,5,opt,name=sid,proto3" json:"sid,omitempty"`
-	unknownFields     protoimpl.UnknownFields
-	sizeCache         protoimpl.SizeCache
+	state              protoimpl.MessageState `protogen:"open.v1"`
+	AuthenticatedUser  string                 `protobuf:"bytes,1,opt,name=authenticated_user,json=authenticatedUser,proto3" json:"authenticated_user,omitempty"`
+	Usergroup          string                 `protobuf:"bytes,2,opt,name=usergroup,proto3" json:"usergroup,omitempty"`
+	Provider           string                 `protobuf:"bytes,3,opt,name=provider,proto3" json:"provider,omitempty"`
+	Acls               []string               `protobuf:"bytes,4,rep,name=acls,proto3" json:"acls,omitempty"`
+	SessionFingerprint string                 `protobuf:"bytes,6,opt,name=session_fingerprint,json=sessionFingerprint,proto3" json:"session_fingerprint,omitempty"`
+	unknownFields      protoimpl.UnknownFields
+	sizeCache          protoimpl.SizeCache
 }
 
 func (x *WhoAmIResponse) Reset() {
@@ -2854,9 +2854,9 @@ func (x *WhoAmIResponse) GetAcls() []string {
 	return nil
 }
 
-func (x *WhoAmIResponse) GetSid() string {
+func (x *WhoAmIResponse) GetSessionFingerprint() string {
 	if x != nil {
-		return x.Sid
+		return x.SessionFingerprint
 	}
 	return ""
 }
@@ -5399,13 +5399,13 @@ const file_olivetin_api_v1_olivetin_proto_rawDesc = "" +
 	"\x17ExecutionStatusResponse\x126\n" +
 	"\tlog_entry\x18\x01 \x01(\v2\x19.olivetin.api.v1.LogEntryR\blogEntry\x12X\n" +
 	"\x12back_to_dashboards\x18\x02 \x03(\v2*.olivetin.api.v1.DashboardNavigationTargetR\x10backToDashboards\"\x0f\n" +
-	"\rWhoAmIRequest\"\x9f\x01\n" +
+	"\rWhoAmIRequest\"\xc9\x01\n" +
 	"\x0eWhoAmIResponse\x12-\n" +
 	"\x12authenticated_user\x18\x01 \x01(\tR\x11authenticatedUser\x12\x1c\n" +
 	"\tusergroup\x18\x02 \x01(\tR\tusergroup\x12\x1a\n" +
 	"\bprovider\x18\x03 \x01(\tR\bprovider\x12\x12\n" +
-	"\x04acls\x18\x04 \x03(\tR\x04acls\x12\x10\n" +
-	"\x03sid\x18\x05 \x01(\tR\x03sid\"\x1a\n" +
+	"\x04acls\x18\x04 \x03(\tR\x04acls\x12/\n" +
+	"\x13session_fingerprint\x18\x06 \x01(\tR\x12sessionFingerprintJ\x04\b\x05\x10\x06R\x03sid\"\x1a\n" +
 	"\x18ServerDiagnosticsRequest\"1\n" +
 	"\x19ServerDiagnosticsResponse\x12\x14\n" +
 	"\x05alert\x18\x01 \x01(\tR\x05alert\"\x11\n" +

+ 5 - 5
service/internal/api/api.go

@@ -1029,11 +1029,11 @@ func (api *oliveTinAPI) WhoAmI(ctx ctx.Context, req *connect.Request[apiv1.WhoAm
 	}
 
 	res := &apiv1.WhoAmIResponse{
-		AuthenticatedUser: user.Username,
-		Usergroup:         user.UsergroupLine,
-		Provider:          user.Provider,
-		Sid:               user.SID,
-		Acls:              user.Acls,
+		AuthenticatedUser:  user.Username,
+		Usergroup:          user.UsergroupLine,
+		Provider:           user.Provider,
+		Acls:               user.Acls,
+		SessionFingerprint: user.SessionFingerprint(),
 	}
 
 	return connect.NewResponse(res), nil

+ 78 - 0
service/internal/api/whoami_session_test.go

@@ -0,0 +1,78 @@
+package api
+
+import (
+	"context"
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+
+	"connectrpc.com/connect"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
+	apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
+	config "github.com/OliveTin/OliveTin/internal/config"
+)
+
+func loginLocalUserForSessionCookie(t *testing.T, client apiv1connect.OliveTinApiServiceClient) *http.Cookie {
+	t.Helper()
+
+	resp, err := client.LocalUserLogin(context.Background(), connect.NewRequest(&apiv1.LocalUserLoginRequest{
+		Username: "alice",
+		Password: "correct horse",
+	}))
+	require.NoError(t, err)
+	require.True(t, resp.Msg.GetSuccess())
+
+	header := http.Header{"Set-Cookie": resp.Header().Values("Set-Cookie")}
+	for _, cookie := range (&http.Response{Header: header}).Cookies() {
+		if cookie.Name == "olivetin-sid-local" && cookie.Value != "" {
+			return cookie
+		}
+	}
+
+	t.Fatal("login did not set the olivetin-sid-local cookie")
+	return nil
+}
+
+func postWhoAmI(t *testing.T, baseURL string, cookie *http.Cookie) string {
+	t.Helper()
+
+	req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, baseURL+"/api/WhoAmI", strings.NewReader("{}"))
+	require.NoError(t, err)
+	req.Header.Set("Content-Type", "application/json")
+	req.AddCookie(cookie)
+
+	resp, err := http.DefaultClient.Do(req)
+	require.NoError(t, err)
+	defer func() { assert.NoError(t, resp.Body.Close()) }()
+
+	body, err := io.ReadAll(resp.Body)
+	require.NoError(t, err)
+	require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
+
+	return string(body)
+}
+
+func TestWhoAmINeverReturnsSessionID(t *testing.T) {
+	hash, err := createHash("correct horse")
+	require.NoError(t, err)
+
+	cfg := config.DefaultConfig()
+	cfg.SetDir(t.TempDir())
+	cfg.AuthLocalUsers.Enabled = true
+	cfg.AuthLocalUsers.Users = []*config.LocalUser{{Username: "alice", Password: hash}}
+
+	ts, client := getNewTestServerAndClient(cfg)
+	defer ts.Close()
+
+	cookie := loginLocalUserForSessionCookie(t, client)
+	body := postWhoAmI(t, ts.URL, cookie)
+
+	assert.Contains(t, body, `"authenticatedUser":"alice"`)
+	assert.NotContains(t, body, cookie.Value, "WhoAmI must not return the session cookie value")
+	assert.NotContains(t, body, `"sid"`)
+	assert.Contains(t, body, `"sessionFingerprint":"`)
+}

+ 17 - 0
service/internal/auth/authpublic/authenticateduser.go

@@ -1,6 +1,8 @@
 package authpublic
 
 import (
+	"crypto/sha256"
+	"encoding/hex"
 	"slices"
 	"strings"
 
@@ -18,6 +20,21 @@ type AuthenticatedUser struct {
 	Acls            []string
 }
 
+// The session ID is the credential held in the session cookie, so it is never
+// returned to clients. The fingerprint lets a client tell sessions apart, and
+// cannot be used to authenticate.
+const sessionFingerprintLength = 16
+
+func (u *AuthenticatedUser) SessionFingerprint() string {
+	if u.SID == "" {
+		return ""
+	}
+
+	sum := sha256.Sum256([]byte(u.SID))
+
+	return hex.EncodeToString(sum[:])[:sessionFingerprintLength]
+}
+
 func (u *AuthenticatedUser) IsGuest() bool {
 	return u.Username == "guest" && u.Provider == "system"
 }

+ 39 - 0
service/internal/auth/authpublic/session_fingerprint_test.go

@@ -0,0 +1,39 @@
+package authpublic
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestSessionFingerprintIsEmptyWithoutSession(t *testing.T) {
+	t.Parallel()
+
+	user := &AuthenticatedUser{Username: "guest"}
+
+	assert.Empty(t, user.SessionFingerprint())
+}
+
+func TestSessionFingerprintDoesNotContainSessionID(t *testing.T) {
+	t.Parallel()
+
+	sid := "3f2b1c7a-8d4e-4f1a-9b6c-2e5d7a9c1b3f"
+	user := &AuthenticatedUser{SID: sid}
+
+	fingerprint := user.SessionFingerprint()
+
+	assert.Len(t, fingerprint, sessionFingerprintLength)
+	assert.NotContains(t, sid, fingerprint)
+	assert.NotContains(t, fingerprint, sid)
+}
+
+func TestSessionFingerprintIsStablePerSession(t *testing.T) {
+	t.Parallel()
+
+	first := &AuthenticatedUser{SID: "session-a"}
+	again := &AuthenticatedUser{SID: "session-a"}
+	other := &AuthenticatedUser{SID: "session-b"}
+
+	assert.Equal(t, first.SessionFingerprint(), again.SessionFingerprint())
+	assert.NotEqual(t, first.SessionFingerprint(), other.SessionFingerprint())
+}

Некоторые файлы не были показаны из-за большого количества измененных файлов