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

Merge commit from fork

security: GHSA-9q82-wjpr-32jm (CRIT) require login for every API call when guests must log in
James Read 1 день назад
Родитель
Сommit
4d6f26b8ff

+ 1 - 1
docs/modules/ROOT/pages/config.adoc

@@ -94,7 +94,7 @@ All configuration options are covered in the solution sections
 | `authHttpHeaderUserGroup` | The HTTP header to use for the usergroup. | `` | Requires restart | xref:security/trusted_header.adoc[Trusted Headers]
 | `authHttpHeaderUserGroup` | The HTTP header to use for the usergroup. | `` | Requires restart | xref:security/trusted_header.adoc[Trusted Headers]
 | `authLocalUsers` | The list of local users. | `[]` | Requires restart | xref:security/local.adoc[Local Users]
 | `authLocalUsers` | The list of local users. | `[]` | Requires restart | xref:security/local.adoc[Local Users]
 | `authLoginUrl` | The URL to redirect to for login. | `` | Requires restart | xref:security/local.adoc[Login URL]
 | `authLoginUrl` | The URL to redirect to for login. | `` | Requires restart | xref:security/local.adoc[Login URL]
-| `authRequireGuestsToLogin` | Basically disables all functionality for guests. It sets all default permissions to false. | `false` | Requires restart | xref:security/acl.adoc[Access Control Lists]
+| `authRequireGuestsToLogin` | Makes guests log in before they can do anything. Guests can only call the API to log in, and get no permissions: all default permissions are set to false, and ACLs never apply to guests. See xref:security/example_login_required.adoc[Login required]. | `false` | Requires restart | xref:security/acl.adoc[Access Control Lists]
 | `defaultPermissions` | The default permissions to use. | `[]` | Requires restart | xref:security/acl.adoc[Access Control Lists]
 | `defaultPermissions` | The default permissions to use. | `[]` | Requires restart | xref:security/acl.adoc[Access Control Lists]
 | `accessControlLists` | The list of access control lists. | `[]` | Requires restart | xref:security/acl.adoc[Access Control Lists]
 | `accessControlLists` | The list of access control lists. | `[]` | Requires restart | xref:security/acl.adoc[Access Control Lists]
 | `security.headerContentSecurityPolicy` | Whether to send a `Content-Security-Policy` header from the single HTTP frontend. | `true` | Live reloadable | xref:security/content_security_policy.adoc[Content Security Policy headers]
 | `security.headerContentSecurityPolicy` | Whether to send a `Content-Security-Policy` header from the single HTTP frontend. | `true` | Live reloadable | xref:security/content_security_policy.adoc[Content Security Policy headers]

+ 5 - 2
docs/modules/ROOT/pages/security/example_login_required.adoc

@@ -42,9 +42,12 @@ Note, to use this configuration, you will need to replace `-- your password hash
 
 
 == Important configuration option: `authRequireGuestsToLogin`
 == Important configuration option: `authRequireGuestsToLogin`
 
 
-The `authRequireGuestsToLogin` option is a helpful shortcut that sets all `defaultPermissions` to false, and makes it so that all guests are prompted to login before they can do anything with OliveTin.
+The `authRequireGuestsToLogin` option makes all guests log in before they can do anything with OliveTin. When it is enabled:
 
 
-Technically, you could achieve the same effect by setting `defaultPermissions` to `false` and setting up an ACL that allows access to the login page, but `authRequireGuestsToLogin` is a more convenient way to achieve the same effect.
+* Guests (visitors who are not logged in) can only use the API to log in, log out, check that OliveTin is ready, and generate a password hash. Every other API call is refused, including starting, restarting and killing actions, and the diagnostic API calls enabled by the `insecureAllow*` options.
+* Guests get no permissions at all. All `defaultPermissions` are set to `false`, and ACLs never apply to guests, even an ACL that matches the `guest` username or usergroup. Such an ACL still applies to logged-in users who are in the `guest` usergroup, for example OAuth2 users given that group by `addToUsergroup`.
+
+This is stronger than setting `defaultPermissions` to `false` yourself, because with that alone an ACL that matches guests would still give them access. See the xref:upgrade/upgrade_notes.adoc#require-guests-to-login-all-api-calls[Upgrade Notes].
 
 
 == Per-action ACLs, vs `addToEveryAction`
 == Per-action ACLs, vs `addToEveryAction`
 
 

+ 2 - 0
docs/modules/ROOT/pages/security/oauth2.adoc

@@ -58,6 +58,8 @@ authOAuth2Providers:
 
 
 Then ensure an ACL matches that group, for example `matchUsergroups: ["guest"]`, so those users get the intended access.
 Then ensure an ACL matches that group, for example `matchUsergroups: ["guest"]`, so those users get the intended access.
 
 
+NOTE: Visitors who are not logged in are also called `guest`. If `authRequireGuestsToLogin` is `true`, an ACL that matches the `guest` usergroup applies only to logged-in users, never to visitors who are not logged in. If it is `false`, the ACL applies to both, so consider using a different group name, such as `oauth-users`.
+
 === All users from a provider in one group
 === All users from a provider in one group
 
 
 Give every user who logs in via GitHub the group `github` so you can target them in ACLs:
 Give every user who logs in via GitHub the group `github` so you can target them in ACLs:

+ 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)
 == Next release (unreleased)
 
 
+[#require-guests-to-login-all-api-calls]
+=== `authRequireGuestsToLogin` now applies to every API call and ACL
+
+When `authRequireGuestsToLogin` is `true`, guests (visitors who are not logged in) can now only call the API to log in, log out, check that OliveTin is ready, and generate a password hash. Previously some API calls, including the ones that start, restart and kill actions, did not check this option, so guests could still use them if an ACL gave them permission. ACLs also no longer apply to guests when this option is enabled, even an ACL that matches the `guest` username or usergroup.
+
+This affects you if `authRequireGuestsToLogin` is `true` and a script or integration calls the OliveTin API without logging in, for example with `curl` and no API key or session. Those calls now fail with "permission denied". Give the integration an API key or a user account, and an ACL that matches that user. ACLs for logged-in users, including OAuth2 users in the `guest` usergroup, are not affected. See xref:security/example_login_required.adoc[Login required].
+
 [#webhook-auth-type-required]
 [#webhook-auth-type-required]
 === Webhooks need an `authType`, and `authType: none` must be set for open webhooks
 === Webhooks need an `authType`, and `authType: none` must be set for open webhooks
 
 

+ 4 - 0
service/internal/acl/acl.go

@@ -80,6 +80,10 @@ func permissionsConfigToBits(permissions config.PermissionsList) PermissionBits
 }
 }
 
 
 func aclCheck(requiredPermission PermissionBits, defaultValue bool, cfg *config.Config, aclFunction string, user *authpublic.AuthenticatedUser, resourceTitle string, resourceAcls []string, includeAddToEvery bool) bool {
 func aclCheck(requiredPermission PermissionBits, defaultValue bool, cfg *config.Config, aclFunction string, user *authpublic.AuthenticatedUser, resourceTitle string, resourceAcls []string, includeAddToEvery bool) bool {
+	if user.MustLogIn(cfg) {
+		return false
+	}
+
 	relevantAcls := getRelevantAcls(cfg, resourceAcls, user, includeAddToEvery)
 	relevantAcls := getRelevantAcls(cfg, resourceAcls, user, includeAddToEvery)
 
 
 	if cfg.LogDebugOptions.AclCheckStarted {
 	if cfg.LogDebugOptions.AclCheckStarted {

+ 79 - 0
service/internal/acl/acl_login_required_test.go

@@ -0,0 +1,79 @@
+package acl
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+
+	authpublic "github.com/OliveTin/OliveTin/internal/auth/authpublic"
+	config "github.com/OliveTin/OliveTin/internal/config"
+)
+
+func guestMatchingAclConfig(requireLogin bool) (*config.Config, *config.Action) {
+	cfg := config.DefaultConfig()
+	cfg.AuthRequireGuestsToLogin = requireLogin
+	cfg.AccessControlLists = []*config.AccessControlList{
+		{
+			Name:            "basic-users",
+			MatchUsergroups: []string{"guest"},
+			MatchUsernames:  []string{"guest"},
+			Permissions:     config.PermissionsList{View: true, Exec: true, Logs: true, Kill: true},
+		},
+	}
+	cfg.Sanitize()
+
+	action := &config.Action{ID: "restart_web_server", Title: "Restart Web Server", Acls: []string{"basic-users"}}
+
+	return cfg, action
+}
+
+func newGuest(cfg *config.Config) *authpublic.AuthenticatedUser {
+	user := &authpublic.AuthenticatedUser{Username: "guest", UsergroupLine: "guest", Provider: "system"}
+	user.BuildUserAcls(cfg)
+	return user
+}
+
+func assertAllActionPermissions(t *testing.T, cfg *config.Config, user *authpublic.AuthenticatedUser, action *config.Action, expected bool) {
+	t.Helper()
+	assert.Equal(t, expected, IsAllowedView(cfg, user, action), "view")
+	assert.Equal(t, expected, IsAllowedExec(cfg, user, action), "exec")
+	assert.Equal(t, expected, IsAllowedLogs(cfg, user, action), "logs")
+	assert.Equal(t, expected, IsAllowedKill(cfg, user, action), "kill")
+}
+
+// GHSA-9q82-wjpr-32jm: an ACL that names the guest user or usergroup must not
+// give unauthenticated visitors any permission when login is required.
+func TestGuestMatchingAclGrantsNothingWhenLoginRequired(t *testing.T) {
+	cfg, action := guestMatchingAclConfig(true)
+	guest := newGuest(cfg)
+
+	assert.Empty(t, guest.Acls)
+	assertAllActionPermissions(t, cfg, guest, action, false)
+}
+
+func TestGuestDeniedByAclCheckEvenWithAclNamesSet(t *testing.T) {
+	cfg, action := guestMatchingAclConfig(true)
+	guest := &authpublic.AuthenticatedUser{Username: "guest", UsergroupLine: "guest", Provider: "system", Acls: []string{"basic-users"}}
+
+	assertAllActionPermissions(t, cfg, guest, action, false)
+}
+
+func TestGuestMatchingAclStillAppliesWhenLoginNotRequired(t *testing.T) {
+	cfg, action := guestMatchingAclConfig(false)
+	guest := newGuest(cfg)
+
+	assert.Equal(t, []string{"basic-users"}, guest.Acls)
+	assertAllActionPermissions(t, cfg, guest, action, true)
+}
+
+// The documented OAuth2 pattern gives logged-in users with no group claim the
+// usergroup "guest". Those users are not unauthenticated visitors, so the ACL
+// must keep working for them.
+func TestLoggedInUserInGuestUsergroupKeepsAclWhenLoginRequired(t *testing.T) {
+	cfg, action := guestMatchingAclConfig(true)
+	user := &authpublic.AuthenticatedUser{Username: "alice", UsergroupLine: "guest", Provider: "oauth2"}
+	user.BuildUserAcls(cfg)
+
+	assert.Equal(t, []string{"basic-users"}, user.Acls)
+	assertAllActionPermissions(t, cfg, user, action, true)
+}

+ 6 - 50
service/internal/api/api.go

@@ -522,9 +522,6 @@ func (api *oliveTinAPI) executionStatusBackToDashboards(ile *executor.InternalLo
 
 
 func (api *oliveTinAPI) ExecutionStatus(ctx ctx.Context, req *connect.Request[apiv1.ExecutionStatusRequest]) (*connect.Response[apiv1.ExecutionStatusResponse], error) {
 func (api *oliveTinAPI) ExecutionStatus(ctx ctx.Context, req *connect.Request[apiv1.ExecutionStatusRequest]) (*connect.Response[apiv1.ExecutionStatusResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
 	ile, err := api.resolveExecutionStatusForView(req.Msg, user)
 	ile, err := api.resolveExecutionStatusForView(req.Msg, user)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
@@ -591,10 +588,6 @@ func (api *oliveTinAPI) Logout(ctx ctx.Context, req *connect.Request[apiv1.Logou
 func (api *oliveTinAPI) GetActionBinding(ctx ctx.Context, req *connect.Request[apiv1.GetActionBindingRequest]) (*connect.Response[apiv1.GetActionBindingResponse], error) {
 func (api *oliveTinAPI) GetActionBinding(ctx ctx.Context, req *connect.Request[apiv1.GetActionBindingRequest]) (*connect.Response[apiv1.GetActionBindingResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	resp, err := api.getActionBindingResponse(user, req.Msg.BindingId)
 	resp, err := api.getActionBindingResponse(user, req.Msg.BindingId)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
@@ -661,10 +654,6 @@ func (api *oliveTinAPI) errUnlessBindingEntityTypeAllowed(user *authpublic.Authe
 func (api *oliveTinAPI) GetDashboard(ctx ctx.Context, req *connect.Request[apiv1.GetDashboardRequest]) (*connect.Response[apiv1.GetDashboardResponse], error) {
 func (api *oliveTinAPI) GetDashboard(ctx ctx.Context, req *connect.Request[apiv1.GetDashboardRequest]) (*connect.Response[apiv1.GetDashboardResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	entityType := ""
 	entityType := ""
 	entityKey := ""
 	entityKey := ""
 	if req.Msg != nil {
 	if req.Msg != nil {
@@ -680,13 +669,6 @@ func (api *oliveTinAPI) GetDashboard(ctx ctx.Context, req *connect.Request[apiv1
 	return api.buildCustomDashboardResponse(dashboardRenderRequest, req.Msg.Title)
 	return api.buildCustomDashboardResponse(dashboardRenderRequest, req.Msg.Title)
 }
 }
 
 
-func (api *oliveTinAPI) checkDashboardAccess(user *authpublic.AuthenticatedUser) error {
-	if user.IsGuest() && api.cfg.AuthRequireGuestsToLogin {
-		return connect.NewError(connect.CodePermissionDenied, fmt.Errorf("guests are not allowed to access the dashboard"))
-	}
-	return nil
-}
-
 func (api *oliveTinAPI) createDashboardRenderRequest(user *authpublic.AuthenticatedUser, entityType, entityKey string) *DashboardRenderRequest {
 func (api *oliveTinAPI) createDashboardRenderRequest(user *authpublic.AuthenticatedUser, entityType, entityKey string) *DashboardRenderRequest {
 	rr := &DashboardRenderRequest{
 	rr := &DashboardRenderRequest{
 		AuthenticatedUser: user,
 		AuthenticatedUser: user,
@@ -734,10 +716,6 @@ func resolveLogsPageSize(requestPageSize, defaultPageSize int64) int64 {
 func (api *oliveTinAPI) GetLogs(ctx ctx.Context, req *connect.Request[apiv1.GetLogsRequest]) (*connect.Response[apiv1.GetLogsResponse], error) {
 func (api *oliveTinAPI) GetLogs(ctx ctx.Context, req *connect.Request[apiv1.GetLogsRequest]) (*connect.Response[apiv1.GetLogsResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	pageSize := resolveLogsPageSize(req.Msg.GetPageSize(), api.cfg.LogHistoryPageSize)
 	pageSize := resolveLogsPageSize(req.Msg.GetPageSize(), api.cfg.LogHistoryPageSize)
 	logEntries, paging, err := api.executor.GetLogTrackingIdsACL(api.cfg, user, req.Msg.StartOffset, pageSize, req.Msg.DateFilter, req.Msg.GetFilter())
 	logEntries, paging, err := api.executor.GetLogTrackingIdsACL(api.cfg, user, req.Msg.StartOffset, pageSize, req.Msg.DateFilter, req.Msg.GetFilter())
 	if err != nil {
 	if err != nil {
@@ -823,10 +801,6 @@ func (api *oliveTinAPI) buildActionLogsResponse(filtered []*executor.InternalLog
 func (api *oliveTinAPI) GetActionLogs(ctx ctx.Context, req *connect.Request[apiv1.GetActionLogsRequest]) (*connect.Response[apiv1.GetActionLogsResponse], error) {
 func (api *oliveTinAPI) GetActionLogs(ctx ctx.Context, req *connect.Request[apiv1.GetActionLogsRequest]) (*connect.Response[apiv1.GetActionLogsResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	filtered := api.filterLogsByACL(api.executor.GetLogsByBindingId(req.Msg.ActionId), user)
 	filtered := api.filterLogsByACL(api.executor.GetLogsByBindingId(req.Msg.ActionId), user)
 	page := paginate(int64(len(filtered)), api.cfg.LogHistoryPageSize, req.Msg.StartOffset)
 	page := paginate(int64(len(filtered)), api.cfg.LogHistoryPageSize, req.Msg.StartOffset)
 	if page.empty {
 	if page.empty {
@@ -912,9 +886,6 @@ func (api *oliveTinAPI) errUnlessUserMayValidateArgumentTypeForBinding(user *aut
 
 
 func (api *oliveTinAPI) ValidateArgumentType(ctx ctx.Context, req *connect.Request[apiv1.ValidateArgumentTypeRequest]) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
 func (api *oliveTinAPI) ValidateArgumentType(ctx ctx.Context, req *connect.Request[apiv1.ValidateArgumentTypeRequest]) (*connect.Response[apiv1.ValidateArgumentTypeResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
 
 
 	if err := api.validateArgumentTypeBindingAccess(user, req.Msg); err != nil {
 	if err := api.validateArgumentTypeBindingAccess(user, req.Msg); err != nil {
 		return nil, err
 		return nil, err
@@ -1011,10 +982,6 @@ func (api *oliveTinAPI) findArgumentByName(action *config.Action, name string) *
 func (api *oliveTinAPI) WhoAmI(ctx ctx.Context, req *connect.Request[apiv1.WhoAmIRequest]) (*connect.Response[apiv1.WhoAmIResponse], error) {
 func (api *oliveTinAPI) WhoAmI(ctx ctx.Context, req *connect.Request[apiv1.WhoAmIRequest]) (*connect.Response[apiv1.WhoAmIResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	res := &apiv1.WhoAmIResponse{
 	res := &apiv1.WhoAmIResponse{
 		AuthenticatedUser:  user.Username,
 		AuthenticatedUser:  user.Username,
 		Usergroup:          user.UsergroupLine,
 		Usergroup:          user.UsergroupLine,
@@ -1113,10 +1080,6 @@ func (api *oliveTinAPI) EventStream(ctx ctx.Context, req *connect.Request[apiv1.
 
 
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return err
-	}
-
 	client := &streamingClient{
 	client := &streamingClient{
 		channel:           make(chan *apiv1.EventStreamResponse, 10), // Buffered channel to hold Events
 		channel:           make(chan *apiv1.EventStreamResponse, 10), // Buffered channel to hold Events
 		AuthenticatedUser: user,
 		AuthenticatedUser: user,
@@ -1340,9 +1303,6 @@ func (api *oliveTinAPI) maybeSendExecutionFinished(client *streamingClient, ile
 
 
 func (api *oliveTinAPI) GetDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.GetDiagnosticsRequest]) (*connect.Response[apiv1.GetDiagnosticsResponse], error) {
 func (api *oliveTinAPI) GetDiagnostics(ctx ctx.Context, req *connect.Request[apiv1.GetDiagnosticsRequest]) (*connect.Response[apiv1.GetDiagnosticsResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
 	if !user.EffectivePolicy.ShowDiagnostics {
 	if !user.EffectivePolicy.ShowDiagnostics {
 		return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("diagnostics are not available for your account"))
 		return nil, connect.NewError(connect.CodePermissionDenied, fmt.Errorf("diagnostics are not available for your account"))
 	}
 	}
@@ -1360,7 +1320,7 @@ func (api *oliveTinAPI) Init(ctx ctx.Context, req *connect.Request[apiv1.InitReq
 }
 }
 
 
 func (api *oliveTinAPI) buildInitResponse(user *authpublic.AuthenticatedUser) *apiv1.InitResponse {
 func (api *oliveTinAPI) buildInitResponse(user *authpublic.AuthenticatedUser) *apiv1.InitResponse {
-	loginRequired := user.IsGuest() && api.cfg.AuthRequireGuestsToLogin
+	loginRequired := user.MustLogIn(api.cfg)
 	currentVersion, availableVersion, showNewVersions := initVersionFields(user, api.cfg)
 	currentVersion, availableVersion, showNewVersions := initVersionFields(user, api.cfg)
 	showNavigation, rootDashboardEntries := api.initNavigationFields(user, loginRequired)
 	showNavigation, rootDashboardEntries := api.initNavigationFields(user, loginRequired)
 
 
@@ -1599,10 +1559,6 @@ func (api *oliveTinAPI) maybeSendOutputChunk(client *streamingClient, entry *exe
 func (api *oliveTinAPI) GetEntities(ctx ctx.Context, req *connect.Request[apiv1.GetEntitiesRequest]) (*connect.Response[apiv1.GetEntitiesResponse], error) {
 func (api *oliveTinAPI) GetEntities(ctx ctx.Context, req *connect.Request[apiv1.GetEntitiesRequest]) (*connect.Response[apiv1.GetEntitiesResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	entityMap := entities.GetEntities()
 	entityMap := entities.GetEntities()
 	entityDefinitions := api.buildEntityDefinitionsResponse(user, req.Msg, entityMap)
 	entityDefinitions := api.buildEntityDefinitionsResponse(user, req.Msg, entityMap)
 
 
@@ -1715,10 +1671,6 @@ func searchSubcomponentsForDirectories(entityType string, contents []*config.Das
 func (api *oliveTinAPI) GetEntity(ctx ctx.Context, req *connect.Request[apiv1.GetEntityRequest]) (*connect.Response[apiv1.Entity], error) {
 func (api *oliveTinAPI) GetEntity(ctx ctx.Context, req *connect.Request[apiv1.GetEntityRequest]) (*connect.Response[apiv1.Entity], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	instances := entities.GetEntityInstances(req.Msg.Type)
 	instances := entities.GetEntityInstances(req.Msg.Type)
 	if len(instances) == 0 {
 	if len(instances) == 0 {
 		return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity type %s not found", req.Msg.Type))
 		return nil, connect.NewError(connect.CodeNotFound, fmt.Errorf("entity type %s not found", req.Msg.Type))
@@ -1985,5 +1937,9 @@ func GetNewHandler(ex *executor.Executor) (string, http.Handler) {
 		},
 		},
 	)
 	)
 
 
-	return apiv1connect.NewOliveTinApiServiceHandler(server, jsonOpt)
+	return apiv1connect.NewOliveTinApiServiceHandler(
+		server,
+		jsonOpt,
+		connect.WithInterceptors(&loginRequiredInterceptor{api: server}),
+	)
 }
 }

+ 72 - 0
service/internal/api/api_login_gate.go

@@ -0,0 +1,72 @@
+package api
+
+import (
+	ctx "context"
+	"errors"
+	"net/http"
+
+	"connectrpc.com/connect"
+
+	apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
+	auth "github.com/OliveTin/OliveTin/internal/auth"
+)
+
+// When authRequireGuestsToLogin is enabled, unauthenticated visitors may only
+// call these procedures, which are needed to log in or to check the server is
+// up. Every other procedure is refused before its handler runs, so a handler
+// cannot forget the check, and a lookup cannot reveal whether an ID exists.
+//
+// Adding a procedure here makes it public. TestEveryProcedureRequiresLoginUnlessPublic
+// lists the same procedures and fails if the two lists differ.
+var loginNotRequiredProcedures = map[string]bool{
+	apiv1connect.OliveTinApiServiceInitProcedure:           true,
+	apiv1connect.OliveTinApiServiceGetReadyzProcedure:      true,
+	apiv1connect.OliveTinApiServiceLocalUserLoginProcedure: true,
+	apiv1connect.OliveTinApiServiceLogoutProcedure:         true,
+	apiv1connect.OliveTinApiServicePasswordHashProcedure:   true,
+}
+
+var errLoginRequired = errors.New("login is required")
+
+type loginRequiredInterceptor struct {
+	api *oliveTinAPI
+}
+
+func (interceptor *loginRequiredInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
+	return func(callCtx ctx.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
+		if err := interceptor.checkLoginRequired(req.Spec().Procedure, req.Header()); err != nil {
+			return nil, err
+		}
+
+		return next(callCtx, req)
+	}
+}
+
+func (interceptor *loginRequiredInterceptor) WrapStreamingClient(next connect.StreamingClientFunc) connect.StreamingClientFunc {
+	return next
+}
+
+func (interceptor *loginRequiredInterceptor) WrapStreamingHandler(next connect.StreamingHandlerFunc) connect.StreamingHandlerFunc {
+	return func(callCtx ctx.Context, conn connect.StreamingHandlerConn) error {
+		if err := interceptor.checkLoginRequired(conn.Spec().Procedure, conn.RequestHeader()); err != nil {
+			return err
+		}
+
+		return next(callCtx, conn)
+	}
+}
+
+func (interceptor *loginRequiredInterceptor) checkLoginRequired(procedure string, header http.Header) error {
+	if loginNotRequiredProcedures[procedure] {
+		return nil
+	}
+
+	cfg := interceptor.api.cfg
+	user := auth.UserFromHeaders(header, procedure, cfg)
+
+	if user.MustLogIn(cfg) {
+		return connect.NewError(connect.CodePermissionDenied, errLoginRequired)
+	}
+
+	return nil
+}

+ 168 - 0
service/internal/api/api_login_gate_test.go

@@ -0,0 +1,168 @@
+package api
+
+import (
+	"context"
+	"net/http"
+	"testing"
+
+	"connectrpc.com/connect"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"google.golang.org/protobuf/reflect/protoreflect"
+	"google.golang.org/protobuf/types/known/emptypb"
+
+	apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
+	config "github.com/OliveTin/OliveTin/internal/config"
+	"github.com/OliveTin/OliveTin/internal/executor"
+)
+
+// The procedures that unauthenticated visitors may call when login is required.
+// This list is deliberately kept separate from loginNotRequiredProcedures, so
+// that making a procedure public needs both to be changed on purpose.
+var expectedPublicProcedures = []string{
+	"Init",
+	"GetReadyz",
+	"LocalUserLogin",
+	"Logout",
+	"PasswordHash",
+}
+
+// loginRequiredGuestAclConfig is the configuration from GHSA-9q82-wjpr-32jm:
+// login is required, and an ACL that matches the "guest" usergroup grants
+// every permission on the action.
+func loginRequiredGuestAclConfig() *config.Config {
+	cfg := config.DefaultConfig()
+	cfg.AuthRequireGuestsToLogin = true
+	cfg.AccessControlLists = []*config.AccessControlList{
+		{
+			Name:            "basic-users",
+			MatchUsergroups: []string{"guest"},
+			Permissions:     config.PermissionsList{View: true, Exec: true, Logs: true, Kill: true},
+		},
+	}
+	cfg.Actions = append(cfg.Actions, &config.Action{
+		ID:    "restart_web_server",
+		Title: "Restart Web Server",
+		Shell: "echo restarted",
+		Acls:  []string{"basic-users"},
+	})
+	cfg.Sanitize()
+
+	return cfg
+}
+
+func oliveTinServiceDescriptor() protoreflect.ServiceDescriptor {
+	return apiv1.File_olivetin_api_v1_olivetin_proto.Services().ByName("OliveTinApiService")
+}
+
+func procedureForMethod(method protoreflect.MethodDescriptor) string {
+	return "/" + string(method.Parent().FullName()) + "/" + string(method.Name())
+}
+
+// callAsGuest calls any procedure with an empty message and no credentials.
+// An empty protobuf message is valid for every request type.
+func callAsGuest(baseURL string, method protoreflect.MethodDescriptor) error {
+	client := connect.NewClient[emptypb.Empty, emptypb.Empty](http.DefaultClient, baseURL+"/api/"+string(method.Name()))
+
+	if !method.IsStreamingServer() {
+		_, err := client.CallUnary(context.Background(), connect.NewRequest(&emptypb.Empty{}))
+		return err
+	}
+
+	stream, err := client.CallServerStream(context.Background(), connect.NewRequest(&emptypb.Empty{}))
+	if err != nil {
+		return err
+	}
+	received := stream.Receive()
+	closeErr := stream.Close()
+
+	if received {
+		return closeErr
+	}
+
+	return stream.Err()
+}
+
+func TestPublicProcedureListsMatch(t *testing.T) {
+	expected := make(map[string]bool)
+	for _, name := range expectedPublicProcedures {
+		method := oliveTinServiceDescriptor().Methods().ByName(protoreflect.Name(name))
+		require.NotNil(t, method, "public procedure %s does not exist in the proto service", name)
+		expected[procedureForMethod(method)] = true
+	}
+
+	assert.Equal(t, expected, loginNotRequiredProcedures)
+}
+
+// TestEveryProcedureRequiresLoginUnlessPublic (GHSA-9q82-wjpr-32jm) calls every
+// procedure in the proto service as an unauthenticated visitor, so a procedure
+// added later is covered without anyone having to remember to add a test.
+func TestEveryProcedureRequiresLoginUnlessPublic(t *testing.T) {
+	cfg := loginRequiredGuestAclConfig()
+	ts, _ := getNewTestServerAndClient(cfg)
+	defer ts.Close()
+
+	methods := oliveTinServiceDescriptor().Methods()
+	require.Positive(t, methods.Len())
+
+	for i := 0; i < methods.Len(); i++ {
+		method := methods.Get(i)
+
+		t.Run(string(method.Name()), func(t *testing.T) {
+			err := callAsGuest(ts.URL, method)
+
+			if loginNotRequiredProcedures[procedureForMethod(method)] {
+				assert.NotEqual(t, connect.CodePermissionDenied, connect.CodeOf(err), "public procedure must be callable without logging in")
+				return
+			}
+
+			require.Error(t, err)
+			assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err), "procedure must refuse unauthenticated visitors when login is required")
+		})
+	}
+}
+
+func TestGuestCannotStartActionsWhenLoginRequired(t *testing.T) {
+	cfg := loginRequiredGuestAclConfig()
+	ex := executor.DefaultExecutor(cfg)
+	ex.RebuildActionMap()
+	ts, client := getNewTestServerAndClientWithExecutor(cfg, ex)
+	defer ts.Close()
+
+	_, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{BindingId: "restart_web_server"}))
+	assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
+
+	_, err = client.StartActionAndWait(context.Background(), connect.NewRequest(&apiv1.StartActionAndWaitRequest{ActionId: "restart_web_server"}))
+	assert.Equal(t, connect.CodePermissionDenied, connect.CodeOf(err))
+
+	binding := ex.FindBindingByID("restart_web_server")
+	require.NotNil(t, binding)
+	assert.Empty(t, ex.GetLogsByBindingId(binding.ID), "the action must not have been requested at all")
+}
+
+// Real and made-up action IDs must get the same answer, so that unauthenticated
+// visitors cannot find out which actions exist.
+func TestGuestCannotTellRealActionIdsFromFakeOnes(t *testing.T) {
+	cfg := loginRequiredGuestAclConfig()
+	ts, client := getNewTestServerAndClient(cfg)
+	defer ts.Close()
+
+	_, realErr := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{BindingId: "restart_web_server"}))
+	_, fakeErr := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{BindingId: "does_not_exist_1234"}))
+
+	require.Error(t, realErr)
+	require.Error(t, fakeErr)
+	assert.Equal(t, connect.CodeOf(realErr), connect.CodeOf(fakeErr))
+	assert.Equal(t, realErr.Error(), fakeErr.Error())
+}
+
+func TestGuestCanStillStartActionsWhenLoginNotRequired(t *testing.T) {
+	cfg := loginRequiredGuestAclConfig()
+	cfg.AuthRequireGuestsToLogin = false
+	ts, client := getNewTestServerAndClient(cfg)
+	defer ts.Close()
+
+	res, err := client.StartActionAndWait(context.Background(), connect.NewRequest(&apiv1.StartActionAndWaitRequest{ActionId: "restart_web_server"}))
+	require.NoError(t, err)
+	assert.Contains(t, res.Msg.LogEntry.Output, "restarted")
+}

+ 0 - 4
service/internal/api/api_queue.go

@@ -22,10 +22,6 @@ type executionQueueBucketKey struct {
 func (api *oliveTinAPI) GetExecutionQueue(ctx ctx.Context, req *connect.Request[apiv1.GetExecutionQueueRequest]) (*connect.Response[apiv1.GetExecutionQueueResponse], error) {
 func (api *oliveTinAPI) GetExecutionQueue(ctx ctx.Context, req *connect.Request[apiv1.GetExecutionQueueRequest]) (*connect.Response[apiv1.GetExecutionQueueResponse], error) {
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 	user := auth.UserFromApiCall(ctx, req, api.cfg)
 
 
-	if err := api.checkDashboardAccess(user); err != nil {
-		return nil, err
-	}
-
 	active := api.executor.GetActiveExecutionsACL(api.cfg, user)
 	active := api.executor.GetActiveExecutionsACL(api.cfg, user)
 	groups := buildExecutionQueueGroups(active, user, api)
 	groups := buildExecutionQueueGroups(active, user, api)
 
 

+ 9 - 10
service/internal/auth/authcheck.go

@@ -24,11 +24,11 @@ func AddAuthChainFunction(check func(*types.AuthCheckingContext) *types.Authenti
 	authChain = append(authChain, check)
 	authChain = append(authChain, check)
 }
 }
 
 
-func runAuthChain[T any](req *connect.Request[T], cfg *config.Config) *types.AuthenticatedUser {
+func runAuthChain(header http.Header, cfg *config.Config) *types.AuthenticatedUser {
 	var user *types.AuthenticatedUser
 	var user *types.AuthenticatedUser
 
 
 	authCtx := &types.AuthCheckingContext{
 	authCtx := &types.AuthCheckingContext{
-		Request: &http.Request{Header: req.Header()},
+		Request: &http.Request{Header: header},
 		Config:  cfg,
 		Config:  cfg,
 	}
 	}
 
 
@@ -44,27 +44,26 @@ func runAuthChain[T any](req *connect.Request[T], cfg *config.Config) *types.Aut
 }
 }
 
 
 func UserFromApiCall[T any](ctx context.Context, req *connect.Request[T], cfg *config.Config) *types.AuthenticatedUser {
 func UserFromApiCall[T any](ctx context.Context, req *connect.Request[T], cfg *config.Config) *types.AuthenticatedUser {
-	user := runAuthChain(req, cfg)
-
 	log.Tracef("UserFromApiCall Context: %+v", ctx)
 	log.Tracef("UserFromApiCall Context: %+v", ctx)
 
 
+	return UserFromHeaders(req.Header(), req.Spec().Procedure, cfg)
+}
+
+func UserFromHeaders(header http.Header, procedure string, cfg *config.Config) *types.AuthenticatedUser {
+	user := runAuthChain(header, cfg)
+
 	if user == nil || user.Username == "" {
 	if user == nil || user.Username == "" {
 		user = UserGuest(cfg)
 		user = UserGuest(cfg)
 	} else {
 	} else {
 		user.BuildUserAcls(cfg)
 		user.BuildUserAcls(cfg)
 	}
 	}
 
 
-	path := ""
-	if req != nil {
-		path = req.Spec().Procedure
-	}
-
 	log.WithFields(log.Fields{
 	log.WithFields(log.Fields{
 		"username":      user.Username,
 		"username":      user.Username,
 		"usergroupLine": user.UsergroupLine,
 		"usergroupLine": user.UsergroupLine,
 		"provider":      user.Provider,
 		"provider":      user.Provider,
 		"acls":          user.Acls,
 		"acls":          user.Acls,
-		"path":          path,
+		"path":          procedure,
 	}).Debugf("Authenticated API request")
 	}).Debugf("Authenticated API request")
 
 
 	return user
 	return user

+ 27 - 9
service/internal/auth/authpublic/authenticateduser.go

@@ -39,6 +39,12 @@ func (u *AuthenticatedUser) IsGuest() bool {
 	return u.Username == "guest" && u.Provider == "system"
 	return u.Username == "guest" && u.Provider == "system"
 }
 }
 
 
+// MustLogIn is true for unauthenticated visitors when authRequireGuestsToLogin
+// is enabled. Such visitors get no permissions at all, whatever the ACLs say.
+func (u *AuthenticatedUser) MustLogIn(cfg *config.Config) bool {
+	return u != nil && u.IsGuest() && cfg.AuthRequireGuestsToLogin
+}
+
 func (u *AuthenticatedUser) parseUsergroupLine(sep string) []string {
 func (u *AuthenticatedUser) parseUsergroupLine(sep string) []string {
 	ret := []string{}
 	ret := []string{}
 
 
@@ -73,19 +79,31 @@ func (u *AuthenticatedUser) MatchesUsergroupAcl(matchUsergroups []string, sep st
 }
 }
 
 
 func (u *AuthenticatedUser) BuildUserAcls(cfg *config.Config) {
 func (u *AuthenticatedUser) BuildUserAcls(cfg *config.Config) {
-	for _, acl := range cfg.AccessControlLists {
-		if slices.Contains(acl.MatchUsernames, u.Username) {
-			u.Acls = append(u.Acls, acl.Name)
-			continue
-		}
+	u.Acls = append(u.Acls, u.matchingAclNames(cfg)...)
+	u.EffectivePolicy = getEffectivePolicy(cfg, u)
+}
 
 
-		if u.MatchesUsergroupAcl(acl.MatchUsergroups, cfg.AuthHttpHeaderUserGroupSep) {
-			u.Acls = append(u.Acls, acl.Name)
-			continue
+// An ACL that names the "guest" user or usergroup is meant for logged-in users
+// (for example OAuth2 users with no group claim). When login is required it must
+// never match an unauthenticated visitor, who is also called "guest".
+func (u *AuthenticatedUser) matchingAclNames(cfg *config.Config) []string {
+	if u.MustLogIn(cfg) {
+		return nil
+	}
+
+	var names []string
+
+	for _, acl := range cfg.AccessControlLists {
+		if u.matchesAcl(acl, cfg.AuthHttpHeaderUserGroupSep) {
+			names = append(names, acl.Name)
 		}
 		}
 	}
 	}
 
 
-	u.EffectivePolicy = getEffectivePolicy(cfg, u)
+	return names
+}
+
+func (u *AuthenticatedUser) matchesAcl(acl *config.AccessControlList, usergroupSep string) bool {
+	return slices.Contains(acl.MatchUsernames, u.Username) || u.MatchesUsergroupAcl(acl.MatchUsergroups, usergroupSep)
 }
 }
 
 
 func getEffectivePolicy(cfg *config.Config, u *AuthenticatedUser) *config.ConfigurationPolicy {
 func getEffectivePolicy(cfg *config.Config, u *AuthenticatedUser) *config.ConfigurationPolicy {

+ 16 - 0
service/internal/executor/executor.go

@@ -1024,6 +1024,8 @@ func stepRequestAction(req *ExecutionRequest) bool {
 	log.WithFields(log.Fields{
 	log.WithFields(log.Fields{
 		"actionTitle": req.logEntry.ActionTitle,
 		"actionTitle": req.logEntry.ActionTitle,
 		"tags":        req.Tags,
 		"tags":        req.Tags,
+		"username":    requestUsername(req),
+		"provider":    requestProvider(req),
 	}).Infof("Action requested")
 	}).Infof("Action requested")
 
 
 	notifyListenersStarted(req)
 	notifyListenersStarted(req)
@@ -1031,6 +1033,20 @@ func stepRequestAction(req *ExecutionRequest) bool {
 	return true
 	return true
 }
 }
 
 
+func requestUsername(req *ExecutionRequest) string {
+	if req.AuthenticatedUser == nil {
+		return ""
+	}
+	return req.AuthenticatedUser.Username
+}
+
+func requestProvider(req *ExecutionRequest) string {
+	if req.AuthenticatedUser == nil {
+		return ""
+	}
+	return req.AuthenticatedUser.Provider
+}
+
 func stepRequestActionHasBinding(req *ExecutionRequest) bool {
 func stepRequestActionHasBinding(req *ExecutionRequest) bool {
 	if req.Binding == nil || req.Binding.Action == nil {
 	if req.Binding == nil || req.Binding.Action == nil {
 		log.Warnf("Action request has no binding/action; skipping execution")
 		log.Warnf("Action request has no binding/action; skipping execution")

+ 48 - 0
specs/require-guests-to-login.md

@@ -0,0 +1,48 @@
+# Spec: Requiring guests to log in
+
+This spec describes what visitors who are not logged in ("guests") may do when the installation requires guests to log in.
+
+---
+
+## 1. Scope
+
+The rules apply only when the installation is configured to require guests to log in. When it is not, guests get the default permissions and any access-control entries that match them, as usual.
+
+A guest is a visitor whose request carries no valid credentials of any kind. A logged-in user is never a guest, even if their username or usergroup is "guest".
+
+---
+
+## 2. API calls guests may make
+
+Guests may only make the API calls needed to log in and to check that the server is running:
+
+- the initial client bootstrap, which tells the client that login is required;
+- the readiness check;
+- local user login;
+- logout;
+- generating a password hash.
+
+Every other API call made by a guest is refused with "permission denied". This includes streaming calls, the calls that start, restart and kill actions, and the diagnostic calls that the installation enables with its insecure options.
+
+The refusal happens before the request is looked at. A guest gets the same answer for an action, execution or entity that exists as for one that does not, so guests cannot find out which ones exist.
+
+The list of calls guests may make is closed. Any API call added in future requires login unless it is added to this list on purpose.
+
+---
+
+## 3. Permissions
+
+Guests have no permissions at all:
+
+- all default permissions are off;
+- no access-control entry applies to a guest, even one that matches the "guest" username or usergroup.
+
+Access-control entries that match the "guest" usergroup still apply to logged-in users in that usergroup, for example users from an identity provider that gives them that group.
+
+This is enforced separately from the API call rule in section 2, so that a guest cannot start, view, or kill an action even through a path that does not go through the API.
+
+---
+
+## 4. Logging
+
+When an action is requested, the log records the username and the authentication provider of the user who requested it, at the default log level, so that actions requested by guests can be told apart from actions requested by logged-in users.