Skip to content

feat(database): add USAGE and CREATE schema privilege grants - #10910

Merged
leonardoce merged 21 commits into
cloudnative-pg:mainfrom
BRGOVIND:feat/schema-grants
Nov 2, 2026
Merged

leonardoce merged 21 commits into
cloudnative-pg:mainfrom
BRGOVIND:feat/schema-grants

Conversation

@BRGOVIND

@BRGOVIND BRGOVIND commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Adds a permissions field to schema entries in the Database CRD, letting users declaratively grant or revoke the USAGE and CREATE privileges on a schema, alongside the existing owner/ensure management:

schemas:
  - name: app
    owner: app
    permissions:
      usage:
        - name: public
          type: revoke

Each entry reuses the existing grant/revoke model used for FDW and foreign-server usage (name + type: grant|revoke, default: grant), so public targets the PostgreSQL PUBLIC pseudo-role as it already does elsewhere.

Closes #7872

@BRGOVIND
BRGOVIND requested a review from a team June 15, 2026 19:06
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. enhancement 🪄 New feature or request labels Jun 15, 2026
@cnpg-bot cnpg-bot added backport-requested ◀️ This pull request should be backported to all supported releases release-1.25 release-1.28 labels Jun 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❗ By default, the pull request is configured to backport to all release branches.

  • To stop backporting this pr, remove the label: backport-requested ◀️ or add the label 'do not backport'
  • To stop backporting this pr to a certain release branch, remove the specific branch label: release-x.y

@gbartolini

Copy link
Copy Markdown
Contributor

Please see my comment here: #7872 (comment)

@BRGOVIND
BRGOVIND requested a review from jsilvela as a code owner June 19, 2026 12:13
@BRGOVIND

Copy link
Copy Markdown
Contributor Author

Thanks @gbartolini — I've reworked the API to follow the proposed design.

Schema grants now use a permissions stanza keyed by privilege, reusing the existing UsageSpec {name, type: grant|revoke} model rather than the previous flat usagePrivileges/createPrivileges lists:

schemas:
  - name: myschema
    owner: app
    permissions:
      usage:
        - name: readonly
          type: grant
      create:
        - name: app
          type: grant

This keeps the surface consistent with the FDW/server usage permissions and mirrors the shape proposed for database-level grants in #10826, building on the shared applyObjectPrivilege primitive from #10829. I've regenerated the deepcopy, CRD manifests and API reference docs, and added unit tests covering grant/revoke on schema create and update (go build/go vet/go test all green locally).

On the idempotent ACL-diffing point from #10826: I kept this PR on the existing fire-and-forget applyObjectPrivilege path to stay consistent with the currently-merged FDW/server usage behaviour. Happy to follow up with a shared read-current-ACL-and-diff helper (usable by both #7872 and #10826) as a separate change if you'd prefer that to land here instead. Let me know which you'd like.

@BRGOVIND

Copy link
Copy Markdown
Contributor Author

Gentle ping on this one 🙂 — it adds explicit USAGE and CREATE schema privilege grants for the Database resource. Branch is rebased and green. Is there anything you'd like me to adjust to make it easier to review?

@Utkarsh-sharma47

Copy link
Copy Markdown
Contributor

Hi @BRGOVIND, I was looking through the validation path for the new permissions stanza and noticed a possible consistency gap.

FDW/server usage entries currently go through validateNameOptionsUsages, which prevents the same role from appearing more than once. Unless I'm missing another validation path, the new schema permissions.usage / permissions.create lists don't seem to get an equivalent check in validateSchemas.

For example, would this currently be accepted?

permissions:
usage:
- name: reader
type: grant
- name: reader
type: revoke

If so, both operations would be applied in list order. Would it make sense to reuse the existing duplicate-name validation independently for each privilege list?

Happy to help with the validation/tests if useful.

@BRGOVIND

BRGOVIND commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Hi @BRGOVIND, I was looking through the validation path for the new permissions stanza and noticed a possible consistency gap.

FDW/server usage entries currently go through validateNameOptionsUsages, which prevents the same role from appearing more than once. Unless I'm missing another validation path, the new schema permissions.usage / permissions.create lists don't seem to get an equivalent check in validateSchemas.

For example, would this currently be accepted?

permissions: usage: - name: reader type: grant - name: reader type: revoke

If so, both operations would be applied in list order. Would it make sense to reuse the existing duplicate-name validation independently for each privilege list?

Happy to help with the validation/tests if useful.

Thanks for taking a look!

Good catch. I don't believe the new schema permissions currently go through the same duplicate entry validation as the existing FDW server usage lists. I'll take a look at reusing the existing validation so duplicate role entry isrejected consistently for each privilege list, and I'll add/update the relevant tests.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Aug 2, 2026
@armru
armru force-pushed the feat/schema-grants branch from 65d786f to f135cff Compare August 11, 2026 11:56
@armru
armru requested review from a team, NiccoloFei and litaocdl as code owners August 11, 2026 11:56
@armru
armru force-pushed the feat/schema-grants branch 2 times, most recently from 4a0240c to fc34329 Compare August 11, 2026 12:07
@armru

armru commented Aug 11, 2026

Copy link
Copy Markdown
Member

Hello, thanks for the contribution, I pushed some changes if you could take a look

@armru

armru commented Aug 11, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

Copy link
Copy Markdown
Contributor

@cnpg-bot cnpg-bot added the ok to merge 👌 This PR can be merged label Aug 11, 2026
@BRGOVIND

Copy link
Copy Markdown
Contributor Author

Hello, thanks for the contribution, I pushed some changes if you could take a look

I did; Thanks !
i there anything more you'd like me to add ?

BRGOVIND and others added 21 commits November 2, 2026 10:46
The Database CRD SchemaSpec had no way to express privilege grants on a
schema. Users who need roles to access objects inside a schema (USAGE)
or create objects in it (CREATE) had to run raw SQL outside the
operator, which breaks the declarative model.

Add two optional fields to SchemaSpec:

  usagePrivileges: []UsageSpec   # GRANT/REVOKE USAGE ON SCHEMA
  createPrivileges: []UsageSpec  # GRANT/REVOKE CREATE ON SCHEMA

Both reuse the existing UsageSpec (name + type: grant|revoke), keeping
the API consistent with the FDW/Server privilege model.

A new updateDatabaseSchemaGrants() SQL helper drives GRANT/REVOKE via
the existing applyObjectPrivilege() primitive so no new SQL logic is
needed. Grants are applied both on schema creation and on each
reconciliation update.

Example spec:
  schemas:
    - name: analytics
      owner: app_owner
      usagePrivileges:
        - name: reporting_role
          type: grant
      createPrivileges:
        - name: app_owner
          type: grant

Fixes cloudnative-pg#7872

Signed-off-by: B R GOVIND <[email protected]>
Restructure schema-level privilege management to a permissions stanza
keyed by privilege (usage, create), each entry reusing the existing
UsageSpec {name, type: grant|revoke} model, instead of the flat
usagePrivileges/createPrivileges lists. This aligns the API with the
design proposed in cloudnative-pg#10826 and keeps the surface consistent with the
foreign data wrapper / server usage permissions, building on the shared
applyObjectPrivilege primitive from cloudnative-pg#10829.

Regenerate deepcopy, CRD manifests and the API reference docs, and add
unit tests covering grant/revoke application on schema create and update.

Signed-off-by: B R GOVIND <[email protected]>
Schema permissions.usage and permissions.create lists were not
checked for repeated role names, unlike FDW/server usage lists which
already reject duplicates via validateNameOptionsUsages. Extract that
duplicate-name check into a small validateUsageNames helper and reuse
it independently for permissions.usage and permissions.create in
validateSchemas.

Signed-off-by: BRGOVIND <[email protected]>
A failing CREATE grant returned the error from applyObjectPrivilege
unwrapped, so Database.Status.Schemas[i].Message reported the failure
without saying which schema it belonged to, while the equivalent USAGE
failure already carried the schema name.

Signed-off-by: Armando Ruocco <[email protected]>
Pin two behaviours of the schema privilege reconciler: a grantee named
public is rendered as the PUBLIC keyword rather than a quoted
identifier, and a permissions stanza with both lists empty issues no
statement at all.

Signed-off-by: Armando Ruocco <[email protected]>
Grant USAGE to PUBLIC and CREATE to the application role on the test
schema of the declarative database fixture, and assert both with
has_schema_privilege. The privileges are deliberately split between the
two grantees: a privilege held by PUBLIC satisfies has_schema_privilege
for every role, so granting the same one to both would make the
assertion on the named role pass even if that grant never ran.

Signed-off-by: Armando Ruocco <[email protected]>
Describe the permissions stanza on Database.spec.schemas, its usage and
create lists, and the PUBLIC pseudo-role. Record the reconciliation
semantics as they stand: the privileges are re-applied on every cycle,
and removing an entry does not revoke anything.

Signed-off-by: Armando Ruocco <[email protected]>
…noring it

applyObjectPrivilege's switch on grantee.Type only logged a Warning
and returned nil for any value other than the known grant/revoke
constants. This meant a reconcile could report success (Applied: true)
while a requested grant/revoke was silently never applied.

Return an error instead, so an unhandled type surfaces as a reconcile
failure rather than a silent no-op.

Assisted-by: Claude

Signed-off-by: Gabriele Bartolini <[email protected]>
updateDatabaseSchemaGrants already returns a well-contextualized error
("applying USAGE/CREATE grants for schema %q: %w"). updateDatabaseSchema
wrapped it again with "updating schema grants: %w", while
createDatabaseSchema passed the same error through unwrapped. The
redundant layer added no information and made the two call paths
report the identical failure differently.

Propagate the error as-is, matching createDatabaseSchema.

Assisted-by: Claude

Signed-off-by: Gabriele Bartolini <[email protected]>
applyUsagePermissions only curried the "USAGE" privilege into
applyObjectPrivilege, with no logic of its own. With schema grants
now also calling applyObjectPrivilege directly for CREATE, keeping
the wrapper meant USAGE and CREATE calls looked different for no
real reason.

Inline it at all three call sites (FDW, ForeignServer, Schema) and
drop the wrapper, so every privilege-application call site has the
same shape: applyObjectPrivilege(ctx, db, "<PRIVILEGE>", objectType,
objectName, list).

Assisted-by: Claude

Signed-off-by: Gabriele Bartolini <[email protected]>
…loop

The two privilege blocks in updateDatabaseSchemaGrants were
copy-pasted, differing only in the privilege keyword and grantee
list. Loop over a small {privilege, grantees} slice instead, so
adding or changing a schema-level privilege only touches one place.

Assisted-by: Claude

Signed-off-by: Gabriele Bartolini <[email protected]>
Signed-off-by: Gabriele Bartolini <[email protected]>
Add a schema-permissions revoke case: PostgreSQL grants USAGE on the
public schema to PUBLIC by default, so revoking it from a Database CR
is the only USAGE/CREATE assertion against the public schema that
actually exercises the grant/revoke code path (a grant would already
be true by default, and app already has CREATE on public via
pg_database_owner membership as the database owner).

The existing assertion loop hardcoded an expectation of true for every
usage/create entry regardless of its grant/revoke type, which would
have made this new revoke case fail. Branch on usage.Type/create.Type
so a revoke entry is asserted as not granted.

Assisted-by: Claude

Signed-off-by: Gabriele Bartolini <[email protected]>
The declarative database fixture only declares a USAGE grant, so the
CREATE arm of the schema permissions never runs in the end-to-end suite
and a broken CREATE grant would go unnoticed.

Grant CREATE on test_schema to the app role. USAGE stays on the PUBLIC
pseudo-role and CREATE goes to a named one because a privilege held by
PUBLIC satisfies has_schema_privilege() for every role: granting both to
PUBLIC would make the assertion on the named role pass even if the grant
never ran.

Signed-off-by: Armando Ruocco <[email protected]>
Grantee names are emitted as quoted identifiers and are case-sensitive,
but every spelling of `public` resolves to the same PostgreSQL PUBLIC
pseudo-role. The duplicate check compared raw strings, so a usage list
naming both `public` and `PUBLIC` passed validation and produced two
statements against the same grantee, with the last one silently winning.

Fold those spellings onto a single key while leaving every other role
name compared verbatim.

Signed-off-by: Armando Ruocco <[email protected]>
The schema grant error was wrapped twice, once by the helper naming the
privilege and the schema and once by its caller. Removing the outer layer
left nothing behind to catch it coming back: the existing assertions match
the sentinel error and a substring, and both hold with either shape.

Assert the full message instead.

Signed-off-by: Armando Ruocco <[email protected]>
The warning claimed permissions are reconciled on every loop. They are
not: the database reconciler returns early while the observed generation
matches the object generation, so a successful apply is terminal and the
30 second requeue does nothing until the spec changes.

That makes the important caveat a different one. CloudNativePG never
reads the privileges back, so a grant or revoke issued directly in
PostgreSQL is not corrected. Say that, and restore the indentation the
surrounding admonitions use.

Signed-off-by: Armando Ruocco <[email protected]>
Nothing on the page says the instance manager connects as the postgres
superuser, yet it decides who ends up owning a schema or a foreign data
wrapper declared without an owner, and it is why a declared grant is
applied even when the database owner could not have issued it.

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Gabriele Bartolini <[email protected]>
Signed-off-by: Gabriele Bartolini <[email protected]>
@leonardoce leonardoce added do not backport This PR must not be backported - it will be in the next minor release and removed backport-requested ◀️ This pull request should be backported to all supported releases release-1.28 release-1.30 labels Nov 2, 2026
@leonardoce
leonardoce merged commit 8cdcb36 into cloudnative-pg:main Nov 2, 2026
cnpg-bot pushed a commit to cloudnative-pg/api that referenced this pull request Nov 2, 2026
…udnative-pg/cloudnative-pg#10910)

Adds a `permissions` field to schema entries in the `Database` CRD,
letting users declaratively grant or revoke the `USAGE` and `CREATE`
privileges on a schema, alongside the existing `owner`/`ensure`
management:

```
    schemas:
      - name: app
        owner: app
        permissions:
          usage:
            - name: public
              type: revoke
```

Each entry reuses the existing grant/revoke model used for FDW and
foreign-server usage (`name` + `type: grant|revoke`, default: `grant`),
so public targets the PostgreSQL PUBLIC pseudo-role as it already does
elsewhere.

Closes cloudnative-pg/cloudnative-pg#7872

Signed-off-by: B R GOVIND <[email protected]>
Signed-off-by: BRGOVIND <[email protected]>
Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Gabriele Bartolini <[email protected]>
Co-authored-by: Armando Ruocco <[email protected]>
Co-authored-by: Gabriele Bartolini <[email protected]>

(cherry picked from commit cloudnative-pg/cloudnative-pg@8cdcb36)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not backport This PR must not be backported - it will be in the next minor release enhancement 🪄 New feature or request lgtm This PR has been approved by a maintainer ok to merge 👌 This PR can be merged size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Support for CREATE and USAGE grants on database schemas

7 participants