Let non-admin accounts be granted single services, starting with /receipt/
Access was admin or nothing, so letting a friend print receipts meant making them a full admin. Users now carry a list of permissions (User.Permissions, a JSON column), each a key from the registry in services/permissions.go; admins pass every check. The only key so far is `receipt`. GET /auth/validate/:permission answers like /auth/validate-admin (200/403/401, with the same refresh-token fallback, now shared) plus 404 for an unknown key, and reads the user row rather than the token, so a grant or revoke applies on the next request. On 200 it returns the username in X-Auth-User. nginx gets a permission gate beside the admin gate: a location sets $auth_permission and auth_requests /internal/auth/validate. /receipt/ moves onto it, forwarding X-Remote-User to the receipt server. 403 now goes to /no-access rather than back to the login page. The variable must not be given a server-level default: the subrequest re-runs the server rewrite phase and would blank it. The admin panel's Manage Users tab ticks permissions per user (setUserPermissions, permissionTypes). The login page is no longer admin-only in wording or destination: a non-admin lands on /account, which lists the services they can open; /no-access is the same view with a notice. /auth/validate-admin and every other admin-gated service are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -64,6 +64,16 @@ graph/ GraphQL layer
|
||||
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
|
||||
and will transparently refresh, so returning admins are recognised without a
|
||||
visible re-login.
|
||||
- `GET /auth/validate/:permission` is the same for one named permission
|
||||
(200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's
|
||||
*permission gate*, which lets a non-admin account into one service — the
|
||||
receipt printer at `/receipt/` — without making it an admin. Grantable keys
|
||||
are the registry `services.PermissionTypes` (`services/permissions.go`);
|
||||
a user's grants are `User.Permissions`, set from the admin panel's Manage
|
||||
Users tab (`setUserPermissions`). Admins pass every permission check. The
|
||||
check reads the user row, not the token, so a grant or revoke applies on
|
||||
the next request. On 200 it returns the username in `X-Auth-User`, which
|
||||
nginx forwards to the gated service as `X-Remote-User`.
|
||||
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
|
||||
is revoked server-side, and a token that has already been issued stays valid
|
||||
until it expires. The same is true of demoting an admin: it takes effect on
|
||||
|
||||
@@ -34,6 +34,10 @@ models:
|
||||
resolver: false
|
||||
deletedAt:
|
||||
resolver: false
|
||||
# Not a database model: the fixed registry in services/permissions.go.
|
||||
PermissionType:
|
||||
model:
|
||||
- adam-french.co.uk/backend/services.PermissionType
|
||||
Post:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Post
|
||||
|
||||
@@ -187,10 +187,11 @@ func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
// `spotifyNeedsReauth` is false for non-admins.
|
||||
func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"users": "admin",
|
||||
"user": "admin",
|
||||
"places": "signedIn",
|
||||
"layouts": "admin",
|
||||
"users": "admin",
|
||||
"user": "admin",
|
||||
"places": "signedIn",
|
||||
"layouts": "admin",
|
||||
"permissionTypes": "signedIn",
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, field := range schemaUnderTest().Query.Fields {
|
||||
|
||||
+454
-33
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/99designs/gqlgen/graphql/introspection"
|
||||
gqlparser "github.com/vektah/gqlparser/v2"
|
||||
@@ -132,34 +133,35 @@ type ComplexityRoot struct {
|
||||
}
|
||||
|
||||
Mutation struct {
|
||||
ApplyLayout func(childComplexity int, id int, page string, replace bool) int
|
||||
ClearBackground func(childComplexity int, page string) int
|
||||
CreateActivity func(childComplexity int, input model.CreateActivityInput) int
|
||||
CreateBookmark func(childComplexity int, input model.CreateBookmarkInput) int
|
||||
CreateBox func(childComplexity int, input model.CreateBoxInput) int
|
||||
CreateFavorite func(childComplexity int, input model.CreateFavoriteInput) int
|
||||
CreateLayout func(childComplexity int, input model.CreateLayoutInput) int
|
||||
CreatePage func(childComplexity int, input model.CreatePageInput) int
|
||||
CreatePlace func(childComplexity int, input model.CreatePlaceInput) int
|
||||
CreatePost func(childComplexity int, input model.CreatePostInput) int
|
||||
CreateUser func(childComplexity int, input model.CreateUserInput) int
|
||||
DeleteBookmark func(childComplexity int, id int) int
|
||||
DeleteBox func(childComplexity int, id int) int
|
||||
DeleteLayout func(childComplexity int, id int) int
|
||||
DeletePage func(childComplexity int, id int) int
|
||||
DeletePlace func(childComplexity int, id int) int
|
||||
DeletePost func(childComplexity int, id int) int
|
||||
DeleteUser func(childComplexity int, id int) int
|
||||
Login func(childComplexity int, input model.LoginInput) int
|
||||
Logout func(childComplexity int) int
|
||||
RefreshToken func(childComplexity int) int
|
||||
SetBackground func(childComplexity int, page string, input model.BackgroundInput) int
|
||||
SetUserAdmin func(childComplexity int, id int, admin bool) int
|
||||
UpdateBox func(childComplexity int, id int, input model.UpdateBoxInput) int
|
||||
UpdateLayout func(childComplexity int, id int, input model.UpdateLayoutInput) int
|
||||
UpdatePage func(childComplexity int, id int, input model.UpdatePageInput) int
|
||||
UpdatePlace func(childComplexity int, id int, input model.UpdatePlaceInput) int
|
||||
UpdatePost func(childComplexity int, id int, input model.UpdatePostInput) int
|
||||
ApplyLayout func(childComplexity int, id int, page string, replace bool) int
|
||||
ClearBackground func(childComplexity int, page string) int
|
||||
CreateActivity func(childComplexity int, input model.CreateActivityInput) int
|
||||
CreateBookmark func(childComplexity int, input model.CreateBookmarkInput) int
|
||||
CreateBox func(childComplexity int, input model.CreateBoxInput) int
|
||||
CreateFavorite func(childComplexity int, input model.CreateFavoriteInput) int
|
||||
CreateLayout func(childComplexity int, input model.CreateLayoutInput) int
|
||||
CreatePage func(childComplexity int, input model.CreatePageInput) int
|
||||
CreatePlace func(childComplexity int, input model.CreatePlaceInput) int
|
||||
CreatePost func(childComplexity int, input model.CreatePostInput) int
|
||||
CreateUser func(childComplexity int, input model.CreateUserInput) int
|
||||
DeleteBookmark func(childComplexity int, id int) int
|
||||
DeleteBox func(childComplexity int, id int) int
|
||||
DeleteLayout func(childComplexity int, id int) int
|
||||
DeletePage func(childComplexity int, id int) int
|
||||
DeletePlace func(childComplexity int, id int) int
|
||||
DeletePost func(childComplexity int, id int) int
|
||||
DeleteUser func(childComplexity int, id int) int
|
||||
Login func(childComplexity int, input model.LoginInput) int
|
||||
Logout func(childComplexity int) int
|
||||
RefreshToken func(childComplexity int) int
|
||||
SetBackground func(childComplexity int, page string, input model.BackgroundInput) int
|
||||
SetUserAdmin func(childComplexity int, id int, admin bool) int
|
||||
SetUserPermissions func(childComplexity int, id int, permissions []string) int
|
||||
UpdateBox func(childComplexity int, id int, input model.UpdateBoxInput) int
|
||||
UpdateLayout func(childComplexity int, id int, input model.UpdateLayoutInput) int
|
||||
UpdatePage func(childComplexity int, id int, input model.UpdatePageInput) int
|
||||
UpdatePlace func(childComplexity int, id int, input model.UpdatePlaceInput) int
|
||||
UpdatePost func(childComplexity int, id int, input model.UpdatePostInput) int
|
||||
}
|
||||
|
||||
Page struct {
|
||||
@@ -171,6 +173,12 @@ type ComplexityRoot struct {
|
||||
UpdatedAt func(childComplexity int) int
|
||||
}
|
||||
|
||||
PermissionType struct {
|
||||
Key func(childComplexity int) int
|
||||
Label func(childComplexity int) int
|
||||
Path func(childComplexity int) int
|
||||
}
|
||||
|
||||
Place struct {
|
||||
Category func(childComplexity int) int
|
||||
Cost func(childComplexity int) int
|
||||
@@ -206,6 +214,7 @@ type ComplexityRoot struct {
|
||||
Messages func(childComplexity int) int
|
||||
Page func(childComplexity int, slug string) int
|
||||
Pages func(childComplexity int) int
|
||||
PermissionTypes func(childComplexity int) int
|
||||
Places func(childComplexity int) int
|
||||
Post func(childComplexity int, id int) int
|
||||
Posts func(childComplexity int) int
|
||||
@@ -271,11 +280,12 @@ type ComplexityRoot struct {
|
||||
}
|
||||
|
||||
User struct {
|
||||
Admin func(childComplexity int) int
|
||||
CreatedAt func(childComplexity int) int
|
||||
ID func(childComplexity int) int
|
||||
UpdatedAt func(childComplexity int) int
|
||||
Username func(childComplexity int) int
|
||||
Admin func(childComplexity int) int
|
||||
CreatedAt func(childComplexity int) int
|
||||
ID func(childComplexity int) int
|
||||
Permissions func(childComplexity int) int
|
||||
UpdatedAt func(childComplexity int) int
|
||||
Username func(childComplexity int) int
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,6 +329,7 @@ type MutationResolver interface {
|
||||
CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error)
|
||||
DeleteUser(ctx context.Context, id int) (*models.User, error)
|
||||
SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error)
|
||||
SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error)
|
||||
}
|
||||
type QueryResolver interface {
|
||||
Activities(ctx context.Context) ([]*models.Activity, error)
|
||||
@@ -342,6 +353,7 @@ type QueryResolver interface {
|
||||
SteamStatus(ctx context.Context) (*model.SteamStatus, error)
|
||||
Users(ctx context.Context) ([]*models.User, error)
|
||||
User(ctx context.Context, id int) (*models.User, error)
|
||||
PermissionTypes(ctx context.Context) ([]*services.PermissionType, error)
|
||||
}
|
||||
type RowingResolver interface {
|
||||
Time(ctx context.Context, obj *models.Rowing) (int, error)
|
||||
@@ -978,6 +990,17 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.Mutation.SetUserAdmin(childComplexity, args["id"].(int), args["admin"].(bool)), true
|
||||
case "Mutation.setUserPermissions":
|
||||
if e.ComplexityRoot.Mutation.SetUserPermissions == nil {
|
||||
break
|
||||
}
|
||||
|
||||
args, err := ec.field_Mutation_setUserPermissions_args(ctx, rawArgs)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.Mutation.SetUserPermissions(childComplexity, args["id"].(int), args["permissions"].([]string)), true
|
||||
case "Mutation.updateBox":
|
||||
if e.ComplexityRoot.Mutation.UpdateBox == nil {
|
||||
break
|
||||
@@ -1071,6 +1094,25 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
|
||||
|
||||
return e.ComplexityRoot.Page.UpdatedAt(childComplexity), true
|
||||
|
||||
case "PermissionType.key":
|
||||
if e.ComplexityRoot.PermissionType.Key == nil {
|
||||
break
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.PermissionType.Key(childComplexity), true
|
||||
case "PermissionType.label":
|
||||
if e.ComplexityRoot.PermissionType.Label == nil {
|
||||
break
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.PermissionType.Label(childComplexity), true
|
||||
case "PermissionType.path":
|
||||
if e.ComplexityRoot.PermissionType.Path == nil {
|
||||
break
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.PermissionType.Path(childComplexity), true
|
||||
|
||||
case "Place.category":
|
||||
if e.ComplexityRoot.Place.Category == nil {
|
||||
break
|
||||
@@ -1257,6 +1299,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.Query.Pages(childComplexity), true
|
||||
case "Query.permissionTypes":
|
||||
if e.ComplexityRoot.Query.PermissionTypes == nil {
|
||||
break
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.Query.PermissionTypes(childComplexity), true
|
||||
case "Query.places":
|
||||
if e.ComplexityRoot.Query.Places == nil {
|
||||
break
|
||||
@@ -1505,6 +1553,12 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.User.ID(childComplexity), true
|
||||
case "User.permissions":
|
||||
if e.ComplexityRoot.User.Permissions == nil {
|
||||
break
|
||||
}
|
||||
|
||||
return e.ComplexityRoot.User.Permissions(childComplexity), true
|
||||
case "User.updatedAt":
|
||||
if e.ComplexityRoot.User.UpdatedAt == nil {
|
||||
break
|
||||
@@ -1844,6 +1898,18 @@ func (ec *executionContext) childFields_Page(ctx context.Context, field graphql.
|
||||
return nil, fmt.Errorf("no field named %q was found under type Page", field.Name)
|
||||
}
|
||||
|
||||
func (ec *executionContext) childFields_PermissionType(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
switch field.Name {
|
||||
case "key":
|
||||
return ec.fieldContext_PermissionType_key(ctx, field)
|
||||
case "label":
|
||||
return ec.fieldContext_PermissionType_label(ctx, field)
|
||||
case "path":
|
||||
return ec.fieldContext_PermissionType_path(ctx, field)
|
||||
}
|
||||
return nil, fmt.Errorf("no field named %q was found under type PermissionType", field.Name)
|
||||
}
|
||||
|
||||
func (ec *executionContext) childFields_Place(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
switch field.Name {
|
||||
case "id":
|
||||
@@ -2006,6 +2072,8 @@ func (ec *executionContext) childFields_User(ctx context.Context, field graphql.
|
||||
return ec.fieldContext_User_username(ctx, field)
|
||||
case "admin":
|
||||
return ec.fieldContext_User_admin(ctx, field)
|
||||
case "permissions":
|
||||
return ec.fieldContext_User_permissions(ctx, field)
|
||||
}
|
||||
return nil, fmt.Errorf("no field named %q was found under type User", field.Name)
|
||||
}
|
||||
@@ -2452,6 +2520,28 @@ func (ec *executionContext) field_Mutation_setUserAdmin_args(ctx context.Context
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func (ec *executionContext) field_Mutation_setUserPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) {
|
||||
var err error
|
||||
args := map[string]any{}
|
||||
arg0, err := graphql.ProcessArgField(ctx, rawArgs, "id",
|
||||
func(ctx context.Context, v any) (int, error) {
|
||||
return ec.unmarshalNID2int(ctx, v)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args["id"] = arg0
|
||||
arg1, err := graphql.ProcessArgField(ctx, rawArgs, "permissions",
|
||||
func(ctx context.Context, v any) ([]string, error) {
|
||||
return ec.unmarshalNString2ᚕstringᚄ(ctx, v)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args["permissions"] = arg1
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func (ec *executionContext) field_Mutation_updateBox_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) {
|
||||
var err error
|
||||
args := map[string]any{}
|
||||
@@ -5619,6 +5709,63 @@ func (ec *executionContext) fieldContext_Mutation_setUserAdmin(ctx context.Conte
|
||||
return fc, nil
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Mutation_setUserPermissions(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_Mutation_setUserPermissions(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
fc := graphql.GetFieldContext(ctx)
|
||||
return ec.Resolvers.Mutation().SetUserPermissions(ctx, fc.Args["id"].(int), fc.Args["permissions"].([]string))
|
||||
},
|
||||
func(ctx context.Context, next graphql.Resolver) graphql.Resolver {
|
||||
directive0 := next
|
||||
|
||||
directive1 := func(ctx context.Context) (any, error) {
|
||||
if ec.Directives.Admin == nil {
|
||||
var zeroVal *models.User
|
||||
return zeroVal, errors.New("directive admin is not implemented")
|
||||
}
|
||||
return ec.Directives.Admin(ctx, nil, directive0)
|
||||
}
|
||||
|
||||
next = directive1
|
||||
return next
|
||||
},
|
||||
func(ctx context.Context, selections ast.SelectionSet, v *models.User) graphql.Marshaler {
|
||||
return ec.marshalNUser2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐUser(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_Mutation_setUserPermissions(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
fc = &graphql.FieldContext{
|
||||
Object: "Mutation",
|
||||
Field: field,
|
||||
IsMethod: true,
|
||||
IsResolver: true,
|
||||
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.childFields_User(ctx, field)
|
||||
},
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = ec.Recover(ctx, r)
|
||||
ec.Error(ctx, err)
|
||||
}
|
||||
}()
|
||||
ctx = graphql.WithFieldContext(ctx, fc)
|
||||
if fc.Args, err = ec.field_Mutation_setUserPermissions_args(ctx, field.ArgumentMap(ec.Variables)); err != nil {
|
||||
ec.Error(ctx, err)
|
||||
return fc, err
|
||||
}
|
||||
return fc, nil
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Page_id(ctx context.Context, field graphql.CollectedField, obj *models.Page) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
@@ -5757,6 +5904,75 @@ func (ec *executionContext) fieldContext_Page_adminOnly(_ context.Context, field
|
||||
return graphql.NewScalarFieldContext("Page", field, false, false, errors.New("field of type Boolean does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _PermissionType_key(ctx context.Context, field graphql.CollectedField, obj *services.PermissionType) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_PermissionType_key(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
return obj.Key, nil
|
||||
},
|
||||
nil,
|
||||
func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler {
|
||||
return ec.marshalNString2string(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_PermissionType_key(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
return graphql.NewScalarFieldContext("PermissionType", field, false, false, errors.New("field of type String does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _PermissionType_label(ctx context.Context, field graphql.CollectedField, obj *services.PermissionType) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_PermissionType_label(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
return obj.Label, nil
|
||||
},
|
||||
nil,
|
||||
func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler {
|
||||
return ec.marshalNString2string(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_PermissionType_label(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
return graphql.NewScalarFieldContext("PermissionType", field, false, false, errors.New("field of type String does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _PermissionType_path(ctx context.Context, field graphql.CollectedField, obj *services.PermissionType) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_PermissionType_path(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
return obj.Path, nil
|
||||
},
|
||||
nil,
|
||||
func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler {
|
||||
return ec.marshalNString2string(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_PermissionType_path(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
return graphql.NewScalarFieldContext("PermissionType", field, false, false, errors.New("field of type String does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Place_id(ctx context.Context, field graphql.CollectedField, obj *models.Place) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
@@ -6932,6 +7148,51 @@ func (ec *executionContext) fieldContext_Query_user(ctx context.Context, field g
|
||||
return fc, nil
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Query_permissionTypes(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_Query_permissionTypes(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
return ec.Resolvers.Query().PermissionTypes(ctx)
|
||||
},
|
||||
func(ctx context.Context, next graphql.Resolver) graphql.Resolver {
|
||||
directive0 := next
|
||||
|
||||
directive1 := func(ctx context.Context) (any, error) {
|
||||
if ec.Directives.SignedIn == nil {
|
||||
var zeroVal []*services.PermissionType
|
||||
return zeroVal, errors.New("directive signedIn is not implemented")
|
||||
}
|
||||
return ec.Directives.SignedIn(ctx, nil, directive0)
|
||||
}
|
||||
|
||||
next = directive1
|
||||
return next
|
||||
},
|
||||
func(ctx context.Context, selections ast.SelectionSet, v []*services.PermissionType) graphql.Marshaler {
|
||||
return ec.marshalNPermissionType2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionTypeᚄ(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_Query_permissionTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
fc = &graphql.FieldContext{
|
||||
Object: "Query",
|
||||
Field: field,
|
||||
IsMethod: true,
|
||||
IsResolver: true,
|
||||
Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.childFields_PermissionType(ctx, field)
|
||||
},
|
||||
}
|
||||
return fc, nil
|
||||
}
|
||||
|
||||
func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
@@ -7752,6 +8013,29 @@ func (ec *executionContext) fieldContext_User_admin(_ context.Context, field gra
|
||||
return graphql.NewScalarFieldContext("User", field, false, false, errors.New("field of type Boolean does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) _User_permissions(ctx context.Context, field graphql.CollectedField, obj *models.User) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
ec.OperationContext,
|
||||
field,
|
||||
func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) {
|
||||
return ec.fieldContext_User_permissions(ctx, field)
|
||||
},
|
||||
func(ctx context.Context) (any, error) {
|
||||
return obj.Permissions, nil
|
||||
},
|
||||
nil,
|
||||
func(ctx context.Context, selections ast.SelectionSet, v []string) graphql.Marshaler {
|
||||
return ec.marshalNString2ᚕstringᚄ(ctx, selections, v)
|
||||
},
|
||||
true,
|
||||
true,
|
||||
)
|
||||
}
|
||||
func (ec *executionContext) fieldContext_User_permissions(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) {
|
||||
return graphql.NewScalarFieldContext("User", field, false, false, errors.New("field of type String does not have child fields"))
|
||||
}
|
||||
|
||||
func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) {
|
||||
return graphql.ResolveField(
|
||||
ctx,
|
||||
@@ -10582,6 +10866,13 @@ func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet)
|
||||
if out.Values[i] == graphql.Null {
|
||||
out.Invalids++
|
||||
}
|
||||
case "setUserPermissions":
|
||||
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
|
||||
return ec._Mutation_setUserPermissions(ctx, field)
|
||||
})
|
||||
if out.Values[i] == graphql.Null {
|
||||
out.Invalids++
|
||||
}
|
||||
default:
|
||||
panic("unknown field " + strconv.Quote(field.Name))
|
||||
}
|
||||
@@ -10666,6 +10957,54 @@ func (ec *executionContext) _Page(ctx context.Context, sel ast.SelectionSet, obj
|
||||
return out
|
||||
}
|
||||
|
||||
var permissionTypeImplementors = []string{"PermissionType"}
|
||||
|
||||
func (ec *executionContext) _PermissionType(ctx context.Context, sel ast.SelectionSet, obj *services.PermissionType) graphql.Marshaler {
|
||||
fields := graphql.CollectFields(ec.OperationContext, sel, permissionTypeImplementors)
|
||||
|
||||
out := graphql.NewFieldSet(fields)
|
||||
deferredFieldSet := graphql.NewFieldSet(nil)
|
||||
deferLabelToView := make(map[string]*graphql.FieldSetView)
|
||||
for i, field := range fields {
|
||||
switch field.Name {
|
||||
case "__typename":
|
||||
out.Values[i] = graphql.MarshalString("PermissionType")
|
||||
case "key":
|
||||
out.Values[i] = ec._PermissionType_key(ctx, field, obj)
|
||||
if out.Values[i] == graphql.Null {
|
||||
out.Invalids++
|
||||
}
|
||||
case "label":
|
||||
out.Values[i] = ec._PermissionType_label(ctx, field, obj)
|
||||
if out.Values[i] == graphql.Null {
|
||||
out.Invalids++
|
||||
}
|
||||
case "path":
|
||||
out.Values[i] = ec._PermissionType_path(ctx, field, obj)
|
||||
if out.Values[i] == graphql.Null {
|
||||
out.Invalids++
|
||||
}
|
||||
default:
|
||||
panic("unknown field " + strconv.Quote(field.Name))
|
||||
}
|
||||
}
|
||||
out.Dispatch(ctx)
|
||||
if out.Invalids > 0 {
|
||||
return graphql.Null
|
||||
}
|
||||
|
||||
atomic.AddInt32(&ec.Deferred, int32(min(len(deferLabelToView), math.MaxInt32)))
|
||||
|
||||
ec.ProcessDeferredGroup(graphql.DeferredGroup{
|
||||
Defers: deferLabelToView,
|
||||
Path: graphql.GetPath(ctx),
|
||||
FieldSet: deferredFieldSet,
|
||||
Context: ctx,
|
||||
})
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
var placeImplementors = []string{"Place"}
|
||||
|
||||
func (ec *executionContext) _Place(ctx context.Context, sel ast.SelectionSet, obj *models.Place) graphql.Marshaler {
|
||||
@@ -11298,6 +11637,28 @@ func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) gr
|
||||
func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })
|
||||
}
|
||||
|
||||
out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })
|
||||
case "permissionTypes":
|
||||
field := field
|
||||
|
||||
innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ec.Error(ctx, ec.Recover(ctx, r))
|
||||
}
|
||||
}()
|
||||
res = ec._Query_permissionTypes(ctx, field)
|
||||
if res == graphql.Null {
|
||||
atomic.AddUint32(&fs.Invalids, 1)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
rrm := func(ctx context.Context) graphql.Marshaler {
|
||||
return ec.OperationContext.RootResolverMiddleware(ctx,
|
||||
func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) })
|
||||
}
|
||||
|
||||
out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) })
|
||||
case "__type":
|
||||
out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) {
|
||||
@@ -11859,6 +12220,11 @@ func (ec *executionContext) _User(ctx context.Context, sel ast.SelectionSet, obj
|
||||
if out.Values[i] == graphql.Null {
|
||||
out.Invalids++
|
||||
}
|
||||
case "permissions":
|
||||
out.Values[i] = ec._User_permissions(ctx, field, obj)
|
||||
if out.Values[i] == graphql.Null {
|
||||
out.Invalids++
|
||||
}
|
||||
default:
|
||||
panic("unknown field " + strconv.Quote(field.Name))
|
||||
}
|
||||
@@ -12609,6 +12975,32 @@ func (ec *executionContext) marshalNPage2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋ
|
||||
return ec._Page(ctx, sel, v)
|
||||
}
|
||||
|
||||
func (ec *executionContext) marshalNPermissionType2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []*services.PermissionType) graphql.Marshaler {
|
||||
ret := graphql.MarshalSliceConcurrently(ctx, len(v), 0, false, func(ctx context.Context, i int) graphql.Marshaler {
|
||||
fc := graphql.GetFieldContext(ctx)
|
||||
fc.Result = &v[i]
|
||||
return ec.marshalNPermissionType2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionType(ctx, sel, v[i])
|
||||
})
|
||||
|
||||
for _, e := range ret {
|
||||
if e == graphql.Null {
|
||||
return graphql.Null
|
||||
}
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (ec *executionContext) marshalNPermissionType2ᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋservicesᚐPermissionType(ctx context.Context, sel ast.SelectionSet, v *services.PermissionType) graphql.Marshaler {
|
||||
if v == nil {
|
||||
if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) {
|
||||
graphql.AddErrorf(ctx, "the requested element is null which the schema does not allow")
|
||||
}
|
||||
return graphql.Null
|
||||
}
|
||||
return ec._PermissionType(ctx, sel, v)
|
||||
}
|
||||
|
||||
func (ec *executionContext) marshalNPlace2ᚕᚖadamᚑfrenchᚗcoᚗukᚋbackendᚋmodelsᚐPlaceᚄ(ctx context.Context, sel ast.SelectionSet, v []*models.Place) graphql.Marshaler {
|
||||
ret := graphql.MarshalSliceConcurrently(ctx, len(v), 0, false, func(ctx context.Context, i int) graphql.Marshaler {
|
||||
fc := graphql.GetFieldContext(ctx)
|
||||
@@ -12811,6 +13203,35 @@ func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.S
|
||||
return res
|
||||
}
|
||||
|
||||
func (ec *executionContext) unmarshalNString2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) {
|
||||
vSlice := graphql.CoerceList(v)
|
||||
var err error
|
||||
res := make([]string, len(vSlice))
|
||||
for i := range vSlice {
|
||||
ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i))
|
||||
res[i], err = ec.unmarshalNString2string(ctx, vSlice[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (ec *executionContext) marshalNString2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler {
|
||||
ret := make(graphql.Array, len(v))
|
||||
for i := range v {
|
||||
ret[i] = ec.marshalNString2string(ctx, sel, v[i])
|
||||
}
|
||||
|
||||
for _, e := range ret {
|
||||
if e == graphql.Null {
|
||||
return graphql.Null
|
||||
}
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (ec *executionContext) unmarshalNTime2timeᚐTime(ctx context.Context, v any) (time.Time, error) {
|
||||
res, err := graphql.UnmarshalTime(v)
|
||||
return res, graphql.ErrorOnPath(ctx, err)
|
||||
|
||||
@@ -4,6 +4,17 @@ type User {
|
||||
updatedAt: Time!
|
||||
username: String!
|
||||
admin: Boolean!
|
||||
# Keys of the gated services this user may use (see PermissionType). Admins
|
||||
# pass every permission check whatever this holds.
|
||||
permissions: [String!]!
|
||||
}
|
||||
|
||||
# One grantable service, from services.PermissionTypes: `key` is what is
|
||||
# stored and what nginx gates on, `label` and `path` are for display.
|
||||
type PermissionType {
|
||||
key: String!
|
||||
label: String!
|
||||
path: String!
|
||||
}
|
||||
|
||||
input CreateUserInput {
|
||||
@@ -14,10 +25,15 @@ input CreateUserInput {
|
||||
extend type Query {
|
||||
users: [User!]! @admin
|
||||
user(id: ID!): User @admin
|
||||
# @signedIn rather than @admin: /account lists a non-admin's own services
|
||||
# from it. The list itself is not a secret.
|
||||
permissionTypes: [PermissionType!]! @signedIn
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createUser(input: CreateUserInput!): User! @admin
|
||||
deleteUser(id: ID!): User! @admin
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
|
||||
# Replaces the user's whole permission list; unknown keys are rejected.
|
||||
setUserPermissions(id: ID!, permissions: [String!]!): User! @admin
|
||||
}
|
||||
|
||||
@@ -8,9 +8,11 @@ package graph
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -72,6 +74,41 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// SetUserPermissions is the resolver for the setUserPermissions field.
|
||||
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
|
||||
// The whole list is replaced, so the admin panel sends every ticked box
|
||||
// each time. An unknown key is refused rather than dropped, so a stale
|
||||
// front end cannot silently save less than it showed. The stored list is
|
||||
// rebuilt in registry order, which also drops duplicates.
|
||||
want := map[string]bool{}
|
||||
for _, key := range permissions {
|
||||
if !services.ValidPermission(key) {
|
||||
return nil, fmt.Errorf("unknown permission %q", key)
|
||||
}
|
||||
want[key] = true
|
||||
}
|
||||
granted := []string{}
|
||||
for _, p := range services.PermissionTypes {
|
||||
if want[p.Key] {
|
||||
granted = append(granted, p.Key)
|
||||
}
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
|
||||
// No token bump needed: the permission gate reads this column on every
|
||||
// request, so the change applies to the user's next one.
|
||||
user.Permissions = granted
|
||||
if err := r.Store.DB.Save(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Users is the resolver for the users field.
|
||||
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
var users []models.User
|
||||
@@ -89,3 +126,9 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// PermissionTypes is the resolver for the permissionTypes field.
|
||||
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
|
||||
// A copy, so nothing downstream can write through to the registry.
|
||||
return ptrs(slices.Clone(services.PermissionTypes)), nil
|
||||
}
|
||||
|
||||
@@ -93,51 +93,86 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
|
||||
// decide whether to show admin UI. It answers with a bare status code and no
|
||||
// body: 200 admin, 403 authenticated but not admin, 401 not authenticated.
|
||||
// decide whether to show admin UI, nginx's admin gate calls as an
|
||||
// auth_request, and the jobs container calls with the visitor's cookies. It
|
||||
// answers with a bare status code and no body: 200 admin, 403 authenticated
|
||||
// but not admin, 401 not authenticated.
|
||||
//
|
||||
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
|
||||
// new cookie pair as a side effect, so a returning admin is recognised
|
||||
// without a visible re-login.
|
||||
func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||
accessToken, err := ctx.Cookie("access_token")
|
||||
if err != nil {
|
||||
// No access token — try refreshing
|
||||
if !store.tryRefreshAndValidateAdmin(ctx) {
|
||||
ctx.Status(http.StatusUnauthorized)
|
||||
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
|
||||
// On the access-token path admin is read from the token, as
|
||||
// everywhere else; on the refresh path there is no admin claim, and
|
||||
// the row is what makes that path pick up a revoked admin flag.
|
||||
if claims == nil {
|
||||
return user.Admin
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
|
||||
if err != nil {
|
||||
// Expired, invalid or revoked access token — try refreshing
|
||||
if !store.tryRefreshAndValidateAdmin(ctx) {
|
||||
ctx.Status(http.StatusUnauthorized)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
admin, ok := (*claims)["admin"].(bool)
|
||||
if !ok || !admin {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Status(http.StatusOK)
|
||||
admin, ok := (*claims)["admin"].(bool)
|
||||
return ok && admin
|
||||
})
|
||||
}
|
||||
|
||||
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
|
||||
// ValidatePermission backs GET /auth/validate/:permission, nginx's permission
|
||||
// gate (see services/permissions.go). Same bare-status contract and refresh
|
||||
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
|
||||
// permission, 401 not signed in — plus 404 for a key that is not in
|
||||
// services.PermissionTypes, so a typo in an nginx location fails closed and
|
||||
// visibly rather than as a 403 that looks like a missing grant.
|
||||
//
|
||||
// The bool does not mean "is an admin" — it means "this function already
|
||||
// wrote the response". It returns true both for a successful admin refresh
|
||||
// (200, new cookies set) and for a valid non-admin (403), and false only when
|
||||
// it could not decide, leaving the caller to send 401. Getting this backwards
|
||||
// would send two status codes for one request.
|
||||
// The decision reads the user row, not the token, for admins as well: a
|
||||
// grant, a revoke or a demotion applies on the very next request.
|
||||
func (store *Store) ValidatePermission(ctx *gin.Context) {
|
||||
key := ctx.Param("permission")
|
||||
if !services.ValidPermission(key) {
|
||||
ctx.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
|
||||
return services.HasPermission(user, key)
|
||||
})
|
||||
}
|
||||
|
||||
// validateSession is the body shared by the two validate endpoints: identify
|
||||
// the caller from the access token, or failing that the refresh token, and
|
||||
// answer 200 / 403 / 401 according to allow.
|
||||
//
|
||||
// Admin status is re-read from the database here, which is what makes the
|
||||
// refresh path pick up a revoked admin flag.
|
||||
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
// allow receives the access token's claims, or nil when the caller was
|
||||
// identified from the refresh token (which carries no authorisation claims).
|
||||
//
|
||||
// On 200 the username goes back in X-Auth-User, which nginx can lift with
|
||||
// auth_request_set and hand to the service behind the gate, so that service
|
||||
// knows who is using it without having accounts of its own.
|
||||
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
|
||||
accessToken, err := ctx.Cookie("access_token")
|
||||
if err == nil {
|
||||
user, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
|
||||
if err == nil {
|
||||
if !allow(user, claims) {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
ctx.Header("X-Auth-User", user.Username)
|
||||
ctx.Status(http.StatusOK)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// No access token, or an expired, invalid or revoked one — try refreshing.
|
||||
if !store.tryRefreshAndValidate(ctx, allow) {
|
||||
ctx.Status(http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
// tryRefreshAndValidate re-authenticates from the refresh token.
|
||||
//
|
||||
// The bool does not mean "allowed" — it means "this function already wrote
|
||||
// the response". It returns true both for a successful refresh (200, new
|
||||
// cookies set) and for a valid but unauthorised user (403, no new cookies),
|
||||
// and false only when it could not decide, leaving the caller to send 401.
|
||||
// Getting this backwards would send two status codes for one request.
|
||||
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
|
||||
refreshToken, err := ctx.Cookie("refresh_token")
|
||||
if err != nil {
|
||||
return false
|
||||
@@ -150,7 +185,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
if !user.Admin {
|
||||
if !allow(user, nil) {
|
||||
ctx.Status(http.StatusForbidden)
|
||||
return true
|
||||
}
|
||||
@@ -162,6 +197,7 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
||||
|
||||
store.setAuthCookies(ctx, tokens)
|
||||
|
||||
ctx.Header("X-Auth-User", user.Username)
|
||||
ctx.Status(http.StatusOK)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -23,8 +23,9 @@ import (
|
||||
// handler, so only the extension allow-list it gates on is covered, as a
|
||||
// table contract below. (The site's general uploads — validation, naming,
|
||||
// storage — are services.Uploads, tested in services/uploads_test.go.)
|
||||
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
|
||||
// reach the database on the refresh path.
|
||||
// - Store.isAdminRequest, and the validate endpoints past their first
|
||||
// check: they authenticate against the database. The allow/deny rule the
|
||||
// permission gate applies is services.HasPermission, tested there.
|
||||
//
|
||||
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
|
||||
// three shared caches, the admin claim check on the upload trust boundary, and
|
||||
@@ -251,6 +252,26 @@ func TestRequestIsAdmin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Permission gate ------------------------------------------------------
|
||||
|
||||
// An unknown key must be refused before any session lookup (Store has no DB
|
||||
// or Auth here, so reaching one would panic): it is how a typo in an nginx
|
||||
// location shows up as a 404 rather than as a missing grant.
|
||||
func TestValidatePermissionUnknownKey(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
s := &Store{}
|
||||
for _, key := range []string{"no-such-service", "admin", ""} {
|
||||
rec := httptest.NewRecorder()
|
||||
ctx, _ := gin.CreateTestContext(rec)
|
||||
ctx.Params = gin.Params{{Key: "permission", Value: key}}
|
||||
ctx.Request = httptest.NewRequest("GET", "/auth/validate/"+key, nil)
|
||||
s.ValidatePermission(ctx)
|
||||
if ctx.Writer.Status() != 404 {
|
||||
t.Errorf("key %q: status %d, want 404", key, ctx.Writer.Status())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The radio allow-list is the radio upload's trust boundary. Testing it as
|
||||
// data catches the realistic failure: someone adding a non-audio or malformed
|
||||
// extension.
|
||||
|
||||
@@ -167,6 +167,7 @@ func main() {
|
||||
r.GET("/auth/check", store.CheckToken)
|
||||
r.POST("/auth/logout", store.Logout)
|
||||
r.GET("/auth/validate-admin", store.ValidateAdmin)
|
||||
r.GET("/auth/validate/:permission", store.ValidatePermission)
|
||||
|
||||
// SPOTIFY
|
||||
// The callback must be open — Spotify redirects a logged-out browser to
|
||||
|
||||
@@ -39,6 +39,14 @@ type User struct {
|
||||
// Admin gates almost every mutation. It is copied into the access token,
|
||||
// so a change here only takes effect on the user's next token refresh.
|
||||
Admin bool `json:"admin"`
|
||||
// Permissions names the gated services this non-admin user may use, one
|
||||
// key each from services.PermissionTypes (admins pass every check
|
||||
// regardless). Unlike Admin it is never copied into a token: the gate
|
||||
// reads it from the row, which services.Auth loads on every request
|
||||
// anyway, so a grant or revoke takes effect on the user's next request.
|
||||
// Stored as a JSON array in one text column; a row from before the
|
||||
// column existed reads as NULL, i.e. no permissions.
|
||||
Permissions []string `gorm:"serializer:json" json:"permissions"`
|
||||
// TokenVersion is the session generation counter. Every issued JWT
|
||||
// carries the value current at the time it was minted, and
|
||||
// services.Auth rejects a token whose value no longer matches, so
|
||||
|
||||
@@ -155,7 +155,7 @@ func tokenVersionOf(v uint) uint {
|
||||
// verifies the signature and expiry, reads the id claim, loads the row, and
|
||||
// checks the token version. Every caller that used to hand-roll this sequence
|
||||
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
|
||||
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
|
||||
// handlers.Store.tryRefreshAndValidate and the GraphQL refreshToken
|
||||
// resolver) now goes through here, so the checks cannot drift apart.
|
||||
//
|
||||
// The returned error is always one of the sentinels above, wrapped or not, so
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// Per-service permissions: how a non-admin account is let into one gated
|
||||
// service (the receipt printer, say) without being made an admin.
|
||||
//
|
||||
// A permission is a key from PermissionTypes stored in models.User.Permissions.
|
||||
// nginx gates a service on one key by asking GET /auth/validate/<key>
|
||||
// (handlers.Store.ValidatePermission); admins pass every such check, so
|
||||
// moving a service from the admin gate to a permission gate never locks an
|
||||
// admin out. Services that are not listed here stay admin-only.
|
||||
//
|
||||
// Adding a grantable service is one entry below plus swapping that location's
|
||||
// nginx gate from /internal/auth/admin-validate to the permission gate (see
|
||||
// "Permission gate" in nginx/nginx_routes.conf.template).
|
||||
|
||||
// PermissionType describes one grantable service. Key is what is stored and
|
||||
// what nginx names; Label and Path are for the admin panel's checkboxes and
|
||||
// the signed-in user's /account list of links.
|
||||
type PermissionType struct {
|
||||
Key string
|
||||
Label string
|
||||
Path string
|
||||
}
|
||||
|
||||
// PermissionTypes is the full set of grantable permissions, in display order.
|
||||
// Removing an entry leaves the key in users' rows, where it is inert: the
|
||||
// validate endpoint 404s an unknown key, so nothing can be gated on it.
|
||||
var PermissionTypes = []PermissionType{
|
||||
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
|
||||
}
|
||||
|
||||
// ValidPermission reports whether key names a permission in PermissionTypes.
|
||||
func ValidPermission(key string) bool {
|
||||
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
|
||||
return p.Key == key
|
||||
})
|
||||
}
|
||||
|
||||
// HasPermission reports whether user may use the service gated on key. It
|
||||
// reads the row, not a token, so Admin here is the current database value.
|
||||
func HasPermission(user *models.User, key string) bool {
|
||||
return user.Admin || slices.Contains(user.Permissions, key)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
func TestValidPermission(t *testing.T) {
|
||||
for _, p := range PermissionTypes {
|
||||
if !ValidPermission(p.Key) {
|
||||
t.Errorf("listed key %q reported invalid", p.Key)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"", "admin", "Receipt", "receipt "} {
|
||||
if ValidPermission(key) {
|
||||
t.Errorf("unlisted key %q reported valid", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
|
||||
func TestPermissionKeysArePathSafe(t *testing.T) {
|
||||
seen := map[string]bool{}
|
||||
for _, p := range PermissionTypes {
|
||||
if seen[p.Key] {
|
||||
t.Errorf("duplicate key %q", p.Key)
|
||||
}
|
||||
seen[p.Key] = true
|
||||
for _, r := range p.Key {
|
||||
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
|
||||
t.Errorf("key %q has %q; use lowercase letters, digits and '-'", p.Key, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasPermission(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
user models.User
|
||||
want bool
|
||||
}{
|
||||
{"admin passes without a grant", models.User{Admin: true}, true},
|
||||
{"granted user passes", models.User{Permissions: []string{"receipt"}}, true},
|
||||
{"other grant does not count", models.User{Permissions: []string{"other"}}, false},
|
||||
{"no grants (NULL column) fails", models.User{}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := HasPermission(&c.user, "receipt"); got != c.want {
|
||||
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,11 @@ var logQuietDrop = map[string]bool{
|
||||
"/auth/check": true, // front-end session check
|
||||
}
|
||||
|
||||
// logQuietDropPrefix is the permission gate's auth_request subrequest
|
||||
// (/auth/validate/<key>), dropped on 2xx for the same reason as
|
||||
// /auth/validate-admin above: it repeats on every request to a gated page.
|
||||
const logQuietDropPrefix = "/auth/validate/"
|
||||
|
||||
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
|
||||
// signature so it plugs into gin.LoggerWithFormatter.
|
||||
func TrafficLogFormatter(params gin.LogFormatterParams) string {
|
||||
@@ -63,7 +68,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
|
||||
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
|
||||
// is still interesting (an expired session raging against refresh, a
|
||||
// broken admin gate) and is kept.
|
||||
if logQuietDrop[path] && params.StatusCode < 400 {
|
||||
if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 {
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,15 @@ func TestTrafficFormatterDropsQuietHeartbeats(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrafficFormatterDropsPermissionGate(t *testing.T) {
|
||||
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 200, "172.28.0.6", time.Millisecond)); out != "" {
|
||||
t.Fatalf("permission-gate 200 should be dropped, got %q", out)
|
||||
}
|
||||
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 403, "172.28.0.6", time.Millisecond)); out == "" {
|
||||
t.Fatal("a refused permission check must stay visible")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrafficFormatterKeepsHeartbeatFailures(t *testing.T) {
|
||||
out := TrafficLogFormatter(fmtParams("GET", "/auth/validate-admin", 401, "172.28.0.6", time.Millisecond))
|
||||
if out == "" {
|
||||
|
||||
Reference in New Issue
Block a user