SPB Git

Repository Public

admin_grants.go 11.1 KB 305 lines go

1package api23import (4	"context"5	"errors"6	"slices"7	"unicode/utf8"89	"github.com/google/uuid"10	"github.com/jackc/pgx/v5"1112	"clustr.spboucher.ai/mcc/internal/audit"13	"clustr.spboucher.ai/mcc/internal/authz"14	"clustr.spboucher.ai/mcc/internal/httpx"15	"clustr.spboucher.ai/mcc/internal/ids"16)1718// ── Policy grants ──────────────────────────────────────────────────────────1920const admGrantCols = `id, subject_kind, subject, permission, resource_kind, resource_id, effect::text, created_by, created_at`2122func admScanGrant(row pgx.Row) (PolicyGrant, error) {23	var g PolicyGrant24	var kind, effect string25	err := row.Scan(&g.Id, &kind, &g.Subject, &g.Permission, &g.ResourceKind, &g.ResourceId, &effect, &g.CreatedBy, &g.CreatedAt)26	g.SubjectKind, g.Effect = GrantSubjectKind(kind), GrantEffect(effect)27	return g, err28}2930func (h *adminHandlers) ListPolicyGrants(ctx context.Context, req ListPolicyGrantsRequestObject) (ListPolicyGrantsResponseObject, error) {31	p := req.Params32	limit, err := clLimit(p.Limit)33	if err != nil {34		return nil, err35	}36	b := &clSQL{}37	if p.SubjectKind != nil {38		if *p.SubjectKind != GrantSubjectKindUser && *p.SubjectKind != GrantSubjectKindRole {39			return nil, clInvalid("subject_kind", "must be user or role")40		}41		b.and("subject_kind = " + b.arg(string(*p.SubjectKind)))42	}43	if p.Subject != nil {44		if len(*p.Subject) > 64 {45			return nil, clInvalid("subject", "must be at most 64 characters")46		}47		b.and("subject = " + b.arg(*p.Subject))48	}49	if p.Permission != nil {50		if !authz.Known(authz.Permission(*p.Permission)) {51			return nil, clInvalid("permission", "is not a known permission (see GET /permissions)")52		}53		b.and("permission = " + b.arg(*p.Permission))54	}55	cur, err := clDecodeCursor(p.Cursor, "grants", 1)56	if err != nil {57		return nil, err58	}59	if cur != nil {60		id, err := clCursorUUID(cur[0])61		if err != nil {62			return nil, err63		}64		b.and("id < " + b.arg(id))65	}66	// Ids are UUIDv7: descending id is most recent first.67	rows, err := h.Pool.Query(ctx, `select `+admGrantCols+` from policy_grants`+b.where()+` order by id desc limit `+b.arg(limit+1), b.args...)68	if err != nil {69		return nil, err70	}71	items, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (PolicyGrant, error) { return admScanGrant(r) })72	if err != nil {73		return nil, err74	}75	out := PolicyGrantList{Items: items}76	if len(items) > limit {77		out.Items = items[:limit]78		out.NextCursor = clEncodeCursor("grants", out.Items[limit-1].Id.String())79	}80	if out.Items == nil {81		out.Items = []PolicyGrant{}82	}83	return ListPolicyGrants200JSONResponse{Body: out}, nil84}8586// Permissions that are only ever checked for the whole cluster: a grant87// scoped to a node, service, site or tag would never be consulted.88var admUnscopable = []authz.Permission{authz.ClusterRead, authz.AuditRead, authz.AuditExport, authz.UsersManage,89	authz.InvitationsManage, authz.AgentsManage, authz.SettingsManage}9091// CreatePolicyGrant validates a grant so that every stored row means92// something: known permission, existing subject and resource, and no grant93// that authz.Decide would ignore or that could lock administration out.94func (h *adminHandlers) CreatePolicyGrant(ctx context.Context, req CreatePolicyGrantRequestObject) (CreatePolicyGrantResponseObject, error) {95	if req.Body == nil {96		return nil, httpx.Validation("Body required.")97	}98	body := req.Body99	actor := principalFrom(ctx).Session100	perm := authz.Permission(body.Permission)101	if !authz.Known(perm) {102		return nil, clInvalid("permission", "is not a known permission (see GET /permissions)")103	}104	if body.Effect != GrantEffectAllow && body.Effect != GrantEffectDeny {105		return nil, clInvalid("effect", "must be allow or deny")106	}107108	// Subject: a role name, or the id of an existing user.109	var subjectRole authz.Role // role the grant will be evaluated against110	subject := body.Subject111	switch body.SubjectKind {112	case GrantSubjectKindRole:113		subjectRole = authz.Role(subject)114		if !subjectRole.Valid() {115			return nil, clInvalid("subject", "must be owner, admin, operator or viewer")116		}117	case GrantSubjectKindUser:118		id, err := uuid.Parse(subject)119		if err != nil {120			return nil, clInvalid("subject", "must be a user id")121		}122		u, err := h.Identity.UserByID(ctx, id)123		if errors.Is(err, httpx.ErrNotFound) {124			return nil, clUnprocessable("unknown_subject", "No user has this id.")125		} else if err != nil {126			return nil, err127		}128		subject, subjectRole = id.String(), u.Role129	default:130		return nil, clInvalid("subject_kind", "must be user or role")131	}132133	// Resource scope.134	var resKind, resID *string135	if body.ResourceKind != nil {136		k := string(*body.ResourceKind)137		if !slices.Contains([]string{"node", "service", "site", "tag"}, k) {138			return nil, clInvalid("resource_kind", "must be node, service, site or tag")139		}140		resKind = &k141		if slices.Contains(admUnscopable, perm) {142			return nil, clUnprocessable("permission_not_scopable", "This permission applies to the whole cluster; a grant limited to a resource would never be used.")143		}144	}145	if body.ResourceId != nil && *body.ResourceId != "" {146		if resKind == nil {147			return nil, clInvalid("resource_id", "requires resource_kind")148		}149		id := *body.ResourceId150		switch *resKind {151		case "node", "service":152			rid, err := uuid.Parse(id)153			if err != nil {154				return nil, clInvalid("resource_id", "must be the id of a "+*resKind)155			}156			table := "nodes"157			if *resKind == "service" {158				table = "services"159			}160			var exists bool161			if err := h.Pool.QueryRow(ctx, `select exists (select 1 from `+table+` where id = $1)`, rid).Scan(&exists); err != nil {162				return nil, err163			}164			if !exists {165				return nil, clUnprocessable("unknown_resource", "No "+*resKind+" has this id.")166			}167			id = rid.String()168		default:169			if utf8.RuneCountInString(id) > 64 || !clPrintable(id) {170				return nil, clInvalid("resource_id", "must be at most 64 printable characters")171			}172		}173		resID = &id174	}175176	// authz.Decide ignores allow-grants beyond what a role may ever hold.177	if body.Effect == GrantEffectAllow && !authz.Grantable(subjectRole, perm) {178		return nil, clUnprocessable("grant_ineffective", "This permission cannot be granted to the "+string(subjectRole)+179			" role: the grant would be ignored.").With("permission", string(perm)).With("role", string(subjectRole))180	}181	// Denying user management to owners for every resource would leave nobody able to undo it.182	if body.Effect == GrantEffectDeny && perm == authz.UsersManage && subjectRole == authz.Owner {183		return nil, clUnprocessable("lockout", "Owners cannot be denied users.manage: nobody could remove the grant.")184	}185186	deny := func(reason string) (CreatePolicyGrantResponseObject, error) {187		h.audit(ctx, h.Pool, "policy.grant.create", "policy_grant", "", audit.Denied, reason,188			map[string]any{"subject_kind": string(body.SubjectKind), "subject": subject, "permission": string(perm), "effect": string(body.Effect)})189		return nil, httpx.ErrForbidden190	}191	// An admin can neither target an owner nor hand out a permission it does not hold.192	if actor.User.Role != authz.Owner {193		if subjectRole == authz.Owner {194			return deny("only an owner may create a grant that targets an owner")195		}196		if body.Effect == GrantEffectAllow {197			ok, err := h.can(ctx, actor, perm, authz.Resource{})198			if err != nil {199				return nil, err200			}201			if !ok {202				return deny("cannot grant a permission the actor does not hold")203			}204		}205	}206	id := ids.New()207	tx, err := h.Pool.Begin(ctx)208	if err != nil {209		return nil, err210	}211	defer tx.Rollback(ctx)212	// Serialize grant changes: the checks below and the insert must see the same rows.213	if _, err := tx.Exec(ctx, `select pg_advisory_xact_lock(7305002)`); err != nil {214		return nil, err215	}216	var same, opposite bool217	if err := tx.QueryRow(ctx, `select coalesce(bool_or(effect = $6::grant_effect), false), coalesce(bool_or(effect <> $6::grant_effect), false)218		from policy_grants where subject_kind = $1 and subject = $2 and permission = $3219			and resource_kind is not distinct from $4 and resource_id is not distinct from $5`,220		string(body.SubjectKind), subject, string(perm), resKind, resID, string(body.Effect)).Scan(&same, &opposite); err != nil {221		return nil, err222	}223	if same {224		return nil, clConflict("This grant already exists.")225	}226	if opposite {227		return nil, clConflict("The opposite grant exists for the same subject, permission and resource; delete it first.")228	}229	g, err := admScanGrant(tx.QueryRow(ctx, `insert into policy_grants(id, subject_kind, subject, permission, resource_kind, resource_id, effect, created_by)230		values ($1, $2, $3, $4, $5, $6, $7::grant_effect, $8) returning `+admGrantCols,231		id, string(body.SubjectKind), subject, string(perm), resKind, resID, string(body.Effect), actor.User.ID))232	if clUniqueViolation(err) {233		return nil, clConflict("This grant already exists.")234	} else if err != nil {235		return nil, err236	}237	params := map[string]any{"subject_kind": g.SubjectKind, "subject": g.Subject, "permission": g.Permission, "effect": g.Effect}238	if resKind != nil {239		params["resource_kind"] = *resKind240	}241	if resID != nil {242		params["resource_id"] = *resID243	}244	if err := h.audit(ctx, tx, "policy.grant.create", "policy_grant", id.String(), audit.Success, "", params); err != nil {245		return nil, err246	}247	if err := tx.Commit(ctx); err != nil {248		return nil, err249	}250	h.invalidateGrants()251	return CreatePolicyGrant201JSONResponse{Body: g}, nil252}253254func (h *adminHandlers) DeletePolicyGrant(ctx context.Context, req DeletePolicyGrantRequestObject) (DeletePolicyGrantResponseObject, error) {255	actor := principalFrom(ctx).Session256	tx, err := h.Pool.Begin(ctx)257	if err != nil {258		return nil, err259	}260	defer tx.Rollback(ctx)261	if _, err := tx.Exec(ctx, `select pg_advisory_xact_lock(7305002)`); err != nil {262		return nil, err263	}264	g, err := admScanGrant(tx.QueryRow(ctx, `select `+admGrantCols+` from policy_grants where id = $1 for update`, req.Id))265	if errors.Is(err, pgx.ErrNoRows) {266		return nil, httpx.ErrNotFound267	} else if err != nil {268		return nil, err269	}270	if actor.User.Role != authz.Owner {271		// Same rule as creation: an admin does not alter what applies to owners.272		targetsOwner := g.SubjectKind == GrantSubjectKindRole && g.Subject == string(authz.Owner)273		if g.SubjectKind == GrantSubjectKindUser {274			if id, err := uuid.Parse(g.Subject); err == nil {275				if u, err := h.Identity.UserByID(ctx, id); err == nil {276					targetsOwner = u.Role == authz.Owner277				}278			}279		}280		if targetsOwner {281			tx.Rollback(ctx)282			h.audit(ctx, h.Pool, "policy.grant.delete", "policy_grant", req.Id.String(), audit.Denied, "only an owner may delete a grant that targets an owner", nil)283			return nil, httpx.ErrForbidden284		}285	}286	if _, err := tx.Exec(ctx, `delete from policy_grants where id = $1`, req.Id); err != nil {287		return nil, err288	}289	params := map[string]any{"subject_kind": g.SubjectKind, "subject": g.Subject, "permission": g.Permission, "effect": g.Effect}290	if g.ResourceKind != nil {291		params["resource_kind"] = *g.ResourceKind292	}293	if g.ResourceId != nil {294		params["resource_id"] = *g.ResourceId295	}296	if err := h.audit(ctx, tx, "policy.grant.delete", "policy_grant", req.Id.String(), audit.Success, "", params); err != nil {297		return nil, err298	}299	if err := tx.Commit(ctx); err != nil {300		return nil, err301	}302	h.invalidateGrants()303	return DeletePolicyGrant204Response{}, nil304}305
Files main
Menu

Theme