Skip to content

chore(auth): enumerate permission actions and resources, and check the TS unions against them - #1288

Draft
IAmJSD wants to merge 1 commit into
LeanerCloud:mainfrom
IAmJSD:fix/issue-166
Draft

IAmJSD wants to merge 1 commit into
LeanerCloud:mainfrom
IAmJSD:fix/issue-166

Conversation

@IAmJSD

@IAmJSD IAmJSD commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

Root cause

internal/auth declares its permission vocabulary as individual untyped consts (ActionView, ResourcePlans, ...). Go can't enumerate a const block, so nothing in Go could list the full set. The frontend's Action / Resource unions in frontend/src/permissions.ts were therefore a hand-kept mirror, and nothing detected them drifting from Go. That drift is what caused cli#1629, where the group-edit form silently dropped permissions and widened view:history to view:*.

Fix

  • internal/auth/permission_catalog.go (new file): auth.AllActions() and auth.AllResources() return the full sets in declaration order. They include admin and the * wildcard, and each call returns a fresh copy. I put them in a new file because types.go is already over 500 lines, and because this keeps the const blocks untouched.

  • Completeness doesn't depend on anyone remembering to update the list, which is the failure mode the issue warns about. TestPermissionCatalogMatchesConstDecls uses go/ast to parse every non-test .go file in internal/auth. It collects each package-level const named Action<Upper>… / Resource<Upper>…, including Go's implicit-repeat specs, and fails when:

    • a constant is declared but not enumerated
    • a value is enumerated but no constant declares it
    • a value is listed twice
    • two constants share a value
    • such a constant's value isn't a string literal (the test can't read it otherwise)

    Each failure names the constant and its position.

  • TestPermissionCatalogCoversSeededPermissions checks that every Default*Permissions() entry and every adminCarvedOuts pair uses only enumerated actions and resources.

  • Go-to-TS seam: cmd/gen-permissions/union_drift_test.go reads frontend/src/permissions.ts, parses the export type Action = … / export type Resource = … string-literal unions (comment-aware), and fails CI if either side has a value the other lacks. The frontend's existing Record<Action, true> check keeps ALL_ACTIONS equal to the union, and this test keeps the union equal to Go. Drift now fails go test ./... in CI. The test only reads the file. This PR changes nothing under frontend/.

I kept the enumeration as a listed array plus an AST exhaustiveness test. A go:generate step or restructuring the consts around a slice would have rewritten the heavily commented const blocks in types.go, and an open branch is already editing those blocks. This approach leaves types.go untouched.

Refs #166

(This is Refs, not a closing keyword, because the audit finding attached to the issue, A11-011 on permissionMatrix.ts, and the TS generation step both need frontend changes. See below.)

Verification

All evidence below is from unit tests on this branch. No DB, cloud or integration code is involved.

export PATH=$HOME/.local/go/bin:$HOME/go/bin:$HOME/.local/bin:$PATH
export AWS_CONFIG_FILE=/dev/null AWS_SHARED_CREDENTIALS_FILE=/dev/null AWS_EC2_METADATA_DISABLED=true
go build ./... && go vet ./... && go vet -tags integration ./...      # OK
go test -count=1 ./cmd/gen-permissions/                                 # ok
go test -count=1 ./internal/auth/                                       # ok
go test -count=1 ./internal/mocks/                                      # ok
golangci-lint (v2.10.1) run --allow-parallel-runners ./internal/auth/ ./cmd/gen-permissions/   # 0 issues
gocyclo -over 10 -ignore "_test\.go" internal/auth/permission_catalog.go                       # clean

Fail-before / mutation probes. Each was applied temporarily and then reverted:

  • origin/main state (permission_catalog.go removed): both test packages fail to build (undefined: AllResources / undefined: auth.AllResources). Go has no enumeration to test against.
  • New const added, not enumerated (ActionFreeze = "freeze" added to the action block): TestPermissionCatalogMatchesConstDecls FAILS with ActionFreeze = "freeze" is declared but missing from the catalog in permission_catalog.go.
  • Enumerated in Go, frontend union not updated (also added to allActions): the auth tests pass, and TestFrontendPermissionUnionsMatchGo FAILS with Action union in ../../frontend/src/permissions.ts lacks Go value(s) ["freeze"].
  • Catalog entry dropped (ResourceRIExchange removed from allResources): the const-decl test FAILS (ResourceRIExchange = "ri-exchange" is declared but missing…), the seeded-permissions test FAILS (adminCarvedOuts uses ri-exchange), and the frontend drift test FAILS (Resource union … has ["ri-exchange"]).
  • Implicit-repeat const (ResourceAllAlias with no value after ResourceAll): FAILS with ResourceAll and ResourceAllAlias both have value "*".
  • Non-literal value (ResourceComputed = ResourcePlans + "-x"): FAILS with ResourceComputed must be a string literal….

TestTSUnionMembers covers the TS parser: line comments, block comments, a /* inside a line comment, // inside a string literal, double quotes, and a missing declaration.

I also checked with git merge-tree that the branch merges cleanly with our unopened fix/issue-313 branch, which removes the Role* constants. This change doesn't reference them.

Combined-tree verification. This branch was tested together with the other queued branches on a local, never-pushed tree: queue/platform @ 936996ad = origin/main a14dc8f2 plus these heads, merged in this order:

Branch Tested head
fix/issue-337 ff3420c
fix/issue-169 7d75eb5
fix/issue-342 66b221f
fix/issue-310 5e11c21
fix/issue-326 5f0ea59
fix/issue-243 365e959
fix/issue-343 6c94036
fix/issue-312 d2848a8
fix/issue-316 acd60dd
fix/issue-339 75ea9b9
fix/issue-339-commitment-type 73bdb19
fix/issue-353 5d25fcd
fix/issue-313 3156bc4
fix/issue-357 53d9e58
fix/issue-368 0ba727d
fix/issue-419 61648c9
fix/issue-111 b04c372
fix/issue-686 0ad90b7
fix/issue-674 793095d
fix/issue-1055 4ec96f1
fix/issue-559 dfa9525
fix/issue-558 034eed4
fix/issue-874 1720539
fix/issue-666 1e120da
fix/issue-668 fb26345
fix/issue-568 ce04173
fix/issue-311 e54f250
fix/issue-177 0cbb88a
fix/issue-151 c21377c
fix/issue-166 41fb77b
fix/issue-27 2d67622
fix/issue-323 69288ae
fix/issue-59 36463e8
fix/issue-43 35e4069
fix/issue-158 6f76f8a
fix/issue-104 bb00491
fix/issue-55 971ef1b
fix/issue-361 89ac220
fix/issue-120 b458719
fix/issue-36 42bac6e
fix/issue-525 57c97dd
fix/issue-712 e5bcda0
fix/issue-72 6cc63ed

fix/issue-72 and fix/issue-312 conflict on one line in internal/api/handler_dashboard.go (both change the calculateCommitmentMetrics call). The tree used #72's side with #312's validated provider variable; whichever PR merges second takes that same resolution.

Linux, Go 1.26.9, AWS_CONFIG_FILE=/dev/null AWS_SHARED_CREDENTIALS_FILE=/dev/null AWS_EC2_METADATA_DISABLED=true; Docker Postgres via testcontainers:

  • Passed at 936996ad: go build ./..., go vet ./..., go vet -tags integration ./... and the full go test -race -short -count=1 ./....
  • Static checks at 936996ad: golangci-lint v2.10.1 found 0 issues on every changed package, with and without --build-tags integration. tests/e2e is a separate module, so it was vetted under its own e2e tag. gocyclo -over 10 is silent on the changed non-test files.
  • Integration tests, every changed package, one package at a time (-tags integration -count=1, 60-minute local timeout because the VM was shared):
    • At 936996ad, these pass: internal/server, internal/credentials, internal/scheduler, internal/database/postgres/migrations, internal/purchase and internal/api.
    • internal/config passes except TestPostgresStoreDB_ResolveStaleRIExchange_ValidatesCloudCheck, which fails the same way on unmodified main (fixed by fix(config): compare resolve checked_at at the database's microsecond precision #1252).
    • These were run on the first build of this tree (26795376, same branches at earlier heads): internal/analytics, internal/auth, internal/commitmentopts, internal/database and cmd/lambda/clear-rate-limit all pass. The later fixes don't touch those packages.
  • What the combined run caught, each fixed on its own branch before this PR opened:
    • a compile break between fix/issue-104's test and fix/issue-326's httpToLambdaRequest signature change;
    • fix/issue-316 rejecting legacy-keyed plans;
    • fix/issue-120 versus main's global-filter test.
  • Secrets: git-secrets, using the repo's scripts/setup-git-secrets.sh patterns in a fresh repo with an isolated HOME, found nothing in the changed files, and a planted fake key was flagged. scripts/test-git-secrets-allowlist.sh: 137 PASS, 0 FAIL.
  • Nothing was applied to any cloud.

Deliberately out of scope

  • Generating the TS unions with cmd/gen-permissions: that would change the committed frontend/src/permissions.generated.ts, and the UI owner owns frontend/. The drift test gets the same "CI fails on drift" result without editing the frontend. See the follow-up below.
  • No API endpoint exposing the vocabulary. The issue doesn't ask for one, so I didn't add API surface. AllActions()/AllResources() would make one trivial if it's ever wanted.
  • Constants declared outside internal/auth: the AST scan covers this package only. Handlers that pass bare string literals to permission checks elsewhere aren't covered.
  • Naming convention: the exhaustiveness check relies on the Action/Resource + upper-case prefix. A permission const named some other way wouldn't be seen, and the test docs say this.

Frontend follow-up for the UI owner

  1. Optional: generate the unions instead of hand-writing them. Extend cmd/gen-permissions to emit, for example, export const ACTIONS = [...] as const; export type Action = (typeof ACTIONS)[number]; (and the same for resources) from auth.AllActions() / auth.AllResources() into permissions.generated.ts. Then import those in permissions.ts, regenerate with go run ./cmd/gen-permissions, and commit the result. The existing permissions-codegen pre-commit hook then catches staleness, and cmd/gen-permissions/union_drift_test.go can be deleted or pointed at the generated file. Until that happens, a new verb needs updating in three places: the const in internal/auth/types.go, the list in internal/auth/permission_catalog.go, and the union plus *_EXHAUSTIVENESS_CHECK record in frontend/src/permissions.ts. The tests name whichever one was missed.
  2. A11-011: frontend/src/users/permissionMatrix.ts:11 still has its own seven-verb ACTIONS list, so the matrix shows no row for approve-any, retry-any, cancel-any, update-any, execute-any, sell-any, revoke-any or any -own verb. Fix: derive the matrix rows from ALL_ACTIONS, as groupModals.ts already does.
  3. Comment cleanup:
    • The permissions.ts header says the unions are hand-written mirrors. It could also mention that cmd/gen-permissions/union_drift_test.go now enforces them.
    • The "exactly one place to update" comment above ACTION_EXHAUSTIVENESS_CHECK holds within the frontend, but reads as repo-wide. The issue asks for it to be scoped.

Maintainer: please mirror the issue's triage labels onto this PR: impact/internal, type/chore, triaged, priority/p3, severity/low, urgency/eventually, effort/m.

🤖 Generated with Claude Code

…e TS unions against them

Go cannot enumerate a const block, so the frontend's Action and Resource
unions were a hand-maintained mirror with nothing detecting drift.

Add auth.AllActions() / auth.AllResources(). Their completeness is not left
to memory: a go/ast test parses every non-test file in internal/auth and
fails when an Action*/Resource* constant is declared without being
enumerated (or enumerated without being declared), when such a constant is
not a string literal, or when two share a value. A second test checks that
the default group permissions and admin carve-outs use only enumerated
values.

cmd/gen-permissions gains a read-only test that parses the Action and
Resource unions in frontend/src/permissions.ts and fails CI on drift in
either direction. No frontend file changes.

Refs LeanerCloud#166

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IAmJSD IAmJSD added impact/internal Team-internal only type/chore Maintenance / non-user-visible triaged Item has been triaged priority/p3 Polish / idea / may never ship severity/low Minor harm urgency/eventually No deadline effort/m Days labels Oct 23, 2026
@coderabbitai

coderabbitai Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/m Days impact/internal Team-internal only priority/p3 Polish / idea / may never ship severity/low Minor harm triaged Item has been triaged type/chore Maintenance / non-user-visible urgency/eventually No deadline

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant