Skip to content

Commit fd41bbb

Browse files
lakhansamaniclaude
andauthored
feat(api): multi-protocol public API surface (GraphQL + gRPC + REST + MCP) (#620)
* feat(api): multi-protocol public API surface (GraphQL + gRPC + REST + MCP) Adds gRPC + grpc-gateway REST + MCP surfaces for the public GraphQL ops (no `_` prefix), driven from a single proto source of truth. GraphQL stays unchanged; admin ops stay GraphQL-only. Consolidates the previously-stacked PRs #614#615#616#617#618#619 into a single change against main. PROTO (proto/) - buf v2 module rooted at buf.build/authorizerdev/authorizer - Single AuthorizerService with 19 RPCs whose names match GraphQL ops 1:1: Signup, Login, Logout, MagicLinkLogin, VerifyEmail, ResendVerifyEmail, VerifyOtp, ResendOtp, ForgotPassword, ResetPassword, Profile, UpdateProfile, DeactivateAccount, Revoke, Session, ValidateJwtToken, ValidateSession, Meta, Permissions - common/v1: annotations (required_permissions, mcp_tool, audit_log, public), pagination, errors, shared AppData - Each RPC's response wrapped in a per-RPC message so buf STANDARD's RPC_REQUEST_RESPONSE_UNIQUE lint passes; shared inner types (AuthResponse, User, Meta) live in proto/authorizer/v1/types.proto - google.api.http annotations drive REST: GET /v1/{method} for trivially- empty queries (meta, profile, permissions, logout), POST /v1/{method} otherwise. Snake_case method paths mirror GraphQL identifiers. - buf STANDARD lint + format both enforced in CI; bufbuild/buf-action@v1 runs lint always, breaking-check on PRs, format -d --exit-code always TRANSPORT-AGNOSTIC SERVICE LAYER (internal/service/) - sideeffects.go: RequestMetadata + ResponseSideEffects + MetaFromGin / ApplyToGin / MetaFromGRPC / ApplyToGRPC bridges - provider.go: service.Provider interface - signup.go, meta.go: migrated from internal/graphql; resolvers become thin transport adapters - Supporting helpers: parsers.GetHostFromRequest/GetAppURLFromRequest, cookie.BuildSessionCookies/BuildMfaSessionCookies (existing gin wrappers now delegate to these so behaviour is byte-identical) gRPC SERVER (internal/grpcsrv/) - server.go: AuthorizerService registered, gRPC reflection (gated on --enable-grpc-reflection), gRPC health checking, graceful shutdown - interceptors: recovery (panic → codes.Internal), logging (per-code level), validate (protovalidate) - handlers/authorizer.go: Meta delegates to service.Meta; the other 18 methods inherit UnimplementedAuthorizerServiceServer and return codes.Unimplemented until their handler migrates from internal/graphql - transport/grpc_metadata.go: gRPC metadata ↔ RequestMetadata bridge (extracts cookies from grpcgateway-cookie, preserves multi-cookie Set-Cookie responses) REST GATEWAY (internal/gateway/) - mount.go: serves grpc-gateway via in-process bufconn dial — no extra TCP hop, no TLS plumbing - JSONPb marshaler: UseProtoNames=true so REST payloads match GraphQL's snake_case shape - Mounted at /v1/* under the existing gin router (shares CORS, security headers, rate limit, logger middleware automatically) - /openapi.json serves the merged swagger spec (embedded via go:embed from gen/openapi/openapi.go so it works regardless of cwd) MCP SERVER (internal/mcp/) - scanner.go: walks grpc.Server.GetServiceInfo() + protoregistry.GlobalFiles, reads the mcp_tool annotation on each method to build a tool registry - schema.go: derives JSON Schema from proto request descriptors, with cycle guard for self-recursive types (google.protobuf.Value) - server.go: registers tools dynamically on a github.com/modelcontextprotocol/ go-sdk Server; tool handlers unmarshal JSON args into a dynamicpb.Message, invoke the gRPC method via an in-process bufconn, marshal the response back to JSON. gRPC errors surface as CallToolResult{IsError:true} so the LLM gets actionable text - Today's MCP-exposed tools (from proto annotations): meta, profile, session, permissions. Credential-bearing methods stay unexposed - `authorizer mcp` subcommand (cmd/mcp.go) serves over stdio for `claude mcp add authorizer -- /path/to/authorizer mcp ...` CLI (cmd/root.go, cmd/mcp.go, internal/config/config.go) - --grpc-port (default 9091; collision-checked against --http-port and --metrics-port at startup), --enable-grpc-reflection (default true), --grpc-tls-cert / -key / -insecure (TLS plumbing placeholders; TLS implementation is a follow-up PR) - server.Run starts HTTP + metrics + gRPC + REST gateway listeners with shared graceful shutdown TESTS - internal/parsers/url_test.go GetHostFromRequest priority + spoof rejection - internal/cookie/cookie_test.go BuildSessionCookies/BuildMfaSessionCookies shape - internal/service/sideeffects_test.go MetaFromGin/ApplyToGin nil-safety + roundtrip - internal/grpcsrv/interceptors/ recovery / logging / validate - internal/grpcsrv/transport/ gRPC metadata bridge (cookies, fallbacks) - internal/mcp/schema_test.go flat scalars, nested message, cycle-safety regression - internal/integration_tests/grpc_meta_test.go AuthorizerService.Meta - internal/integration_tests/grpc_surface_test.go all 18 stubs return Unimplemented + gRPC health - internal/integration_tests/rest_meta_test.go GET /v1/meta through gateway - internal/integration_tests/rest_openapi_test.go /openapi.json serves embedded spec - internal/integration_tests/mcp_test.go tools/list + tools/call meta - internal/integration_tests/mcp_stubs_test.go stub returns CallToolResult{IsError:true} - Existing GraphQL integration suite still passes (65–70s, no behaviour drift) What's NOT in this PR (deferred) - --grpc-tls-cert / -key / -insecure are wired into config but not yet enforced; TLS implementation lands in a follow-up alongside metrics- listener TLS - 18 of the 19 gRPC methods (and their REST mirrors + MCP tools) are Unimplemented stubs; each becomes real as its op migrates from internal/graphql into internal/service in follow-up PRs. The annotation-driven MCP scanner + gateway routing means follow-ups don't need to touch the gRPC/REST/MCP scaffolding — only add the service-layer method and the handler delegation Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(api,mcp): migrate 7 stubs; security audit fixes; lock stdio-only MCP (#621) Implements 7 of the 17 stubbed AuthorizerService methods (Profile, Permissions, Logout, Revoke, ValidateJwtToken, ValidateSession, Session) following the established service-layer pattern, and addresses the security audit findings against the MCP surface. SECURITY AUDIT FIXES C1 — Session response carries access_token / refresh_token / id_token / authenticator_secret / recovery_codes. The proto annotation on Session flipped to mcp_tool.exposed = false so those credentials never land in an LLM transcript. Session remains available via gRPC + REST + GraphQL for legitimate browser/server-to-server consumers. H1 — MCP→gRPC auth propagation. New `--mcp-bearer` flag on the `authorizer mcp` subcommand; the MCP server stamps `Authorization: Bearer <token>` on every outgoing gRPC call. Identity-bearing tools (profile, permissions) now have a caller to attribute to; anonymous runs still work for the public Meta tool but identity-bearing tools surface a clean unauthorized error. H2 — Recovery interceptor redacts panic values. The recovered value is no longer dumped via `.Interface("panic", r)` (which would have logged credentials if a handler ever panicked with the request struct); only the panic type is logged for triage. Regression test included. STDIO-ONLY MCP TRANSPORT internal/mcp/server.go — explicit type-level documentation: stdio is the ONLY supported transport. The Server has no RunHTTP / RunTCP / RunSSE methods, intentionally. internal/mcp/transport_test.go — `TestServer_StdioOnly` reflects over *Server's exported methods and fails the build if anyone adds a method whose name suggests a network transport (RunHTTP, ListenTCP, ServeWS, etc.). To add a transport: implement an MCP-side auth interceptor first, then update the allow-list. cmd/mcp.go — docstring + CLI long help explicitly state "stdio only". 7 STUB MIGRATIONS internal/service: profile.go, permissions.go, logout.go, revoke.go, validate_jwt_token.go, validate_session.go, session.go, permission_check.go (shared helper). All follow the SignUp pattern: take RequestMetadata, return (result, *ResponseSideEffects, error). internal/grpcsrv/handlers: authorizer.go grows 4 real method implementations (Profile, Permissions, Logout, Revoke, ValidateJwtToken, ValidateSession, Session). project.go adds projectUser / projectAuthResponse / projectAppData / claimsToAppData / protoToModelPermissions helpers shared across methods. internal/graphql: resolvers for the seven ops become thin delegations (same pattern as Signup + Meta). internal/cookie: BuildDeleteSessionCookies added; DeleteSession now delegates to it (transport-agnostic mirror of the existing pattern). internal/service/provider.go: Dependencies grows AuthorizationProvider; the four new methods land on the Provider interface. All call sites (cmd/root, cmd/mcp, test_helper) wire it through. TESTS - TestRecovery_DoesNotLogCredentialBearingPanicValue (H2 regression) - TestServer_StdioOnly (transport lock-down) - TestMCPListAndCallMeta now expects 3 MCP tools (meta/profile/permissions); session was DROPPED per C1. - TestMCPToolErrorSurfacesAsIsErrorResult exercises anonymous call to identity-bearing tool (formerly the "stubbed tool" test). - TestAuthorizerServiceStubsReturnUnimplemented shrunk by 7 entries. - Full SQLite integration suite (67s) still green — no regression on the existing GraphQL behaviour for any of the 7 migrated ops. STILL STUBBED (10 ops, follow-up PRs) Login, MagicLinkLogin, VerifyEmail, ResendVerifyEmail, VerifyOtp, ResendOtp, ForgotPassword, ResetPassword, UpdateProfile, DeactivateAccount. Each is a substantial state machine; better as focused individual PRs than rushed in a batch. Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(api): typed errors + REST status codes, logout POST, signup gRPC, fmt/lint Addresses the multi-protocol API review findings. REST/gRPC correctness (a): introduce transport-agnostic typed errors (internal/service/errors.go, ErrorKind) and a gRPC ErrorMap interceptor so business errors map to proper codes (InvalidArgument->400, Unauthenticated->401, PermissionDenied->403, NotFound->404, FailedPrecondition->400) instead of collapsing to Unknown/500. All migrated service methods classify their client-facing errors; messages are unchanged so GraphQL behaviour is byte-identical. Logout GET->POST (b): logout mutates state and is audited, so it must not be a safe GET (RFC 9110 9.2.1, CSRF). Proto annotation + regen. REST error envelope (d): gateway WithErrorHandler emits a stable snake_case envelope {"code","message"}; WithRoutingErrorHandler keeps true HTTP statuses (e.g. 405 on method mismatch instead of 501). Signup gRPC handler (4): wire service.SignUp into the gRPC/REST/MCP surface (was a stub despite the service method existing). Fix latent nil-Request panic: MetaFromGRPC now synthesizes an *http.Request from the gRPC metadata so the gin-shim TokenProvider helpers in Profile/Permissions/Logout/Session/ValidateSession don't dereference nil over gRPC/REST. Tooling: add make fmt (fmt-go/fmt-ts) and make lint (lint-go/lint-ts) plus .golangci.yml (skips generated code). Docs: document Stripe-aligned REST conventions (snake_case paths, method-by-effect, /v1 prefix, error envelope) and correct the mapping table to the as-implemented paths. Tests: cross-protocol error-message consistency (GraphQL==gRPC==REST), REST status-code/envelope coverage, logout-is-POST, MetaFromGRPC request synthesis. project.go AppData converters de-duplicated. * feat(api): expose check_permissions/list_permissions on gRPC, REST, and MCP - typed ErrFgaNotEnabled as FailedPrecondition (gRPC FailedPrecondition, REST 400 failed_precondition) instead of an opaque internal error - FGA integration setup wires the service layer with the embedded engine - surface tests: 20-RPC assertion, fail-closed + validation coverage for both permission RPCs over gRPC and REST, MCP tool list and nested-schema coverage (check_permissions/list_permissions replace the permissions tool) - docs/grpc-rest-api-spec.md updated to the new permission surface and required_relations gates * refactor: review fixes — token-derived FGA subject, shared engine init - session/validate_session pass the token-validated claims.Subject (not the re-fetched user record ID) to enforceRequiredRelations, matching main - extract initAuthzEngine into cmd/fga_engine.go; root.go and the mcp subcommand now share one OpenFGA init path * fix(cli): mcp subcommand inherits server flags RootCmd registered its flags as local flags, which cobra does not propagate to subcommands — the documented `authorizer mcp --database-type=... --client-id=...` invocation failed with 'unknown flag'. Register them as persistent flags so the mcp subcommand shares the full server flag surface and rootArgs storage. Verified end-to-end over stdio: initialize handshake, tools/list (meta, profile, check_permissions, list_permissions), nested input schema, public meta call, and fail-closed IsError results for anonymous identity-bearing calls. * ci: skip buf breaking until main carries the proto module buf breaking diffs against main#subdir=proto, but proto/ first lands in this PR — the check can only fail before merge ('Module had no .proto files'). Gate it on the base branch actually having protos, and disable the action's PR comment which the job token lacks permission to post. * fix(gateway,mcp): propagate authorizer host so issuer validation works off-HTTP Two fixes found by live end-to-end smoke testing of the new surfaces: - REST gateway: the in-process bufconn call carries ':authority=bufconn', so the service layer resolved the host as http://bufconn and JWT issuer validation rejected every token on /v1/*. A WithMetadata annotator now forwards the original request's host via parsers.GetHostFromRequest (same spoof-hardened resolution as the gin path) as x-authorizer-url, which transport.MetaFromGRPC already reads first. - MCP: stampAuth now also stamps x-authorizer-url from the new --mcp-authorizer-url flag, so identity-bearing tools (profile, check_permissions, list_permissions) pass issuer validation when --mcp-bearer is set. Regression tests: TestRESTGatewayForwardsAuthorizerHost (REST signup must mint iss=<forwarded host>, then round-trip on /v1/profile) and TestStampAuth (both metadata keys). * test(e2e): release smoke suite for all public API surfaces make smoke builds the real binary and runs one black-box scenario across GraphQL, REST, gRPC, and MCP stdio: seed an OpenFGA model + tuple, sign a user up, then assert the identical check_permissions / list_permissions decision (allow + deny) on every surface, plus REST fail-closed/validation envelopes and the MCP handshake + tool discovery with a real bearer token. Gated behind the smoke build tag so regular test runs skip it; the release workflow runs it as a required job before the Docker image is built. --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 3fd4777 commit fd41bbb

102 files changed

Lines changed: 16301 additions & 1394 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/workflows/ci.yml

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,42 @@ jobs:
2727

2828
- name: Run tests
2929
run: make test
30+
31+
proto:
32+
name: Proto lint + breaking
33+
runs-on: ubuntu-latest
34+
steps:
35+
- uses: actions/checkout@v4
36+
with:
37+
persist-credentials: false
38+
# buf breaking needs main's history to diff against.
39+
fetch-depth: 0
40+
41+
# buf breaking can only diff against main once main actually carries
42+
# the proto module; before this PR series merges, main has no proto/
43+
# and `buf breaking` fails with "had no .proto files".
44+
- name: Check base branch has protos
45+
id: base
46+
run: |
47+
if git ls-tree -d origin/main proto | grep -q proto; then
48+
echo "has_proto=true" >> "$GITHUB_OUTPUT"
49+
else
50+
echo "has_proto=false" >> "$GITHUB_OUTPUT"
51+
fi
52+
53+
- uses: bufbuild/buf-action@v1
54+
with:
55+
input: proto
56+
lint: true
57+
# `format: true` makes the action run `buf format -d --exit-code`,
58+
# failing the job on any unformatted .proto. Catches drift before
59+
# generated code can diverge.
60+
format: true
61+
# Only run breaking on PRs (push to main has nothing to diff
62+
# against) and only once main carries the proto module.
63+
breaking: ${{ github.event_name == 'pull_request' && steps.base.outputs.has_proto == 'true' }}
64+
breaking_against: 'https://github.com/${{ github.repository }}.git#branch=main,subdir=proto'
65+
# The action's PR comment needs permissions the default
66+
# GITHUB_TOKEN of this job lacks ("Resource not accessible by
67+
# integration"); skip it.
68+
pr_comment: false

.github/workflows/release.yaml

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,26 @@ jobs:
3636
- name: Run tests
3737
run: make test
3838

39+
smoke:
40+
name: Release smoke (GraphQL + REST + gRPC + MCP)
41+
runs-on: ubuntu-latest
42+
steps:
43+
- uses: actions/checkout@v4
44+
with:
45+
persist-credentials: false
46+
- uses: actions/setup-go@v5
47+
with:
48+
go-version-file: go.mod
49+
cache: true
50+
# Black-box end-to-end pass over every public API surface against the
51+
# freshly built binary (see internal/e2e/smoke_test.go).
52+
- name: Run smoke tests
53+
run: make smoke
54+
3955
build:
4056
name: Build and push Docker image
4157
runs-on: ubuntu-latest
42-
needs: test
58+
needs: [test, smoke]
4359
steps:
4460
- uses: actions/checkout@v4
4561
- name: Set up Docker Buildx

.golangci.yml

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# golangci-lint v2 configuration.
2+
# Run via `make lint-go` (or `golangci-lint run ./...`).
3+
version: "2"
4+
5+
run:
6+
# Build tags used by the test/storage matrix so all files type-check.
7+
tests: true
8+
9+
linters:
10+
# Default linter set (errcheck, govet, ineffassign, staticcheck, unused).
11+
default: standard
12+
settings:
13+
staticcheck:
14+
checks:
15+
- all
16+
# QF1008 wants embedded-field selectors collapsed (p.Config.X -> p.X);
17+
# the codebase deliberately keeps the explicit p.Config.X form.
18+
- -QF1008
19+
exclusions:
20+
# Generated protobuf/gateway/openapi code is owned by buf, not us.
21+
generated: lax
22+
paths:
23+
- gen/
24+
- ".*\\.pb\\.go$"
25+
- ".*\\.pb\\.gw\\.go$"
26+
27+
formatters:
28+
enable:
29+
- gofmt
30+
exclusions:
31+
paths:
32+
- gen/

Makefile

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,14 @@ dev:
9292
test:
9393
go clean --testcache && TEST_DBS="sqlite" $(GO_TEST_ALL)
9494

95+
# Release smoke tests: build the real binary and exercise every public API
96+
# surface (GraphQL, REST, gRPC, MCP) end to end, including an authenticated
97+
# FGA decision on each. Gated behind the `smoke` build tag so regular test
98+
# runs skip them. CI runs this on every release.
99+
.PHONY: smoke
100+
smoke:
101+
go test -tags smoke -count=1 -v -timeout 5m ./internal/e2e/
102+
95103
test-postgres: test-cleanup-postgres
96104
docker run -d --name authorizer_postgres -p 5434:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=postgres postgres
97105
sleep 3
@@ -174,3 +182,71 @@ generate-graphql:
174182
generate-db-template:
175183
cp -rf internal/storage/db/provider_template internal/storage/db/${dbname}
176184
find internal/storage/db/${dbname} -type f -exec sed -i -e 's/provider_template/${dbname}/g' {} \;
185+
186+
# ----------------------------------------------------------------------------
187+
# Protobuf (Phase 0+): public-API source of truth under ./proto.
188+
# `buf` is installed on demand into $(GOBIN) if missing.
189+
# ----------------------------------------------------------------------------
190+
BUF ?= $(shell command -v buf 2>/dev/null)
191+
BUF_VERSION ?= v1.47.2
192+
193+
.PHONY: proto-tools proto-lint proto-breaking proto-gen
194+
195+
proto-tools:
196+
@if [ -z "$(BUF)" ]; then \
197+
echo "Installing buf $(BUF_VERSION) via go install"; \
198+
go install github.com/bufbuild/buf/cmd/buf@$(BUF_VERSION); \
199+
fi
200+
201+
proto-lint: proto-tools
202+
cd proto && buf lint
203+
204+
# Compare the working tree's proto against origin/main; fails on breaking changes.
205+
# Override BUF_BREAKING_AGAINST for local runs (e.g. "main" or a SHA).
206+
BUF_BREAKING_AGAINST ?= .git#branch=origin/main,subdir=proto
207+
proto-breaking: proto-tools
208+
cd proto && buf breaking --against '../$(BUF_BREAKING_AGAINST)'
209+
210+
proto-gen: proto-tools
211+
cd proto && buf dep update && buf generate
212+
213+
# ----------------------------------------------------------------------------
214+
# Formatting & linting (Go + TypeScript). `make fmt` before committing,
215+
# `make lint` in CI. golangci-lint is installed on demand if missing.
216+
# ----------------------------------------------------------------------------
217+
GOLANGCI_LINT ?= $(shell command -v golangci-lint 2>/dev/null)
218+
GOLANGCI_LINT_VERSION ?= v2.11.4
219+
220+
.PHONY: fmt fmt-go fmt-ts lint lint-go lint-ts lint-tools
221+
222+
# Format everything.
223+
fmt: fmt-go fmt-ts
224+
225+
# gofmt -s over all hand-written Go sources (generated protobuf output under
226+
# gen/ is excluded — it is owned by buf).
227+
fmt-go:
228+
@gofmt -s -w $(shell find . -type f -name '*.go' -not -path './gen/*')
229+
230+
# Prettier over both web apps via their configured format scripts.
231+
fmt-ts:
232+
cd web/app && npm run format
233+
cd web/dashboard && npm run format
234+
235+
# Lint everything.
236+
lint: lint-go lint-ts
237+
238+
lint-tools:
239+
@if [ -z "$(GOLANGCI_LINT)" ]; then \
240+
echo "Installing golangci-lint $(GOLANGCI_LINT_VERSION)"; \
241+
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION); \
242+
fi
243+
244+
# golangci-lint over the module. Generated code under gen/ is excluded via
245+
# .golangci.yml.
246+
lint-go: lint-tools
247+
golangci-lint run ./...
248+
249+
# Prettier in --check mode: fails (non-zero) if any web source is unformatted.
250+
lint-ts:
251+
cd web/app && npx prettier --check 'src/**/*.(ts|tsx|js|jsx)'
252+
cd web/dashboard && npx prettier --check 'src/**/*.(ts|tsx|js|jsx)'

cmd/fga_engine.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package cmd
2+
3+
import (
4+
"strings"
5+
6+
"github.com/rs/zerolog"
7+
8+
"github.com/authorizerdev/authorizer/internal/authorization/engine"
9+
fgaengine "github.com/authorizerdev/authorizer/internal/authorization/engine/openfga"
10+
"github.com/authorizerdev/authorizer/internal/config"
11+
)
12+
13+
// initAuthzEngine initializes the embedded OpenFGA authorization engine from
14+
// the --fga-store / --fga-store-url config, shared by the server (root) and
15+
// the MCP subcommand. OpenFGA migrations run on boot for SQL stores
16+
// (idempotent); the in-memory store needs none.
17+
//
18+
// Engine-init failure is deliberately NON-fatal: FGA is an optional
19+
// subsystem, so a failure here (e.g. the DB user lacks DDL rights for the
20+
// OpenFGA tables) logs loudly and returns a nil engine — fga_* and the
21+
// permission APIs fail closed while core authentication keeps serving.
22+
//
23+
// The returned cleanup func is always non-nil and safe to defer; it closes
24+
// the engine when one was created.
25+
func initAuthzEngine(cfg *config.Config, log *zerolog.Logger) (engine.AuthorizationEngine, func()) {
26+
cleanup := func() {}
27+
fgaStore, fgaStoreURL, fgaEnabled := cfg.FGAStoreConfig()
28+
if !fgaEnabled {
29+
return nil, cleanup
30+
}
31+
runMigrations := !strings.EqualFold(fgaStore, fgaengine.StoreMemory)
32+
fgaEngine, err := fgaengine.New(
33+
&fgaengine.Config{
34+
Store: fgaStore,
35+
StoreURL: fgaStoreURL,
36+
StoreName: cfg.OrganizationName,
37+
RunMigrations: runMigrations,
38+
},
39+
&fgaengine.Dependencies{Log: log},
40+
)
41+
if err != nil {
42+
log.Error().Err(err).
43+
Str("fga_store", fgaStore).
44+
Msg("failed to initialize OpenFGA authorization engine; fine-grained authorization is DISABLED (fail-closed) — core auth continues")
45+
return nil, cleanup
46+
}
47+
if closer, ok := fgaEngine.(interface{ Close() }); ok {
48+
cleanup = closer.Close
49+
}
50+
log.Info().
51+
Str("fga_store", fgaStore).
52+
Bool("reused_main_db", strings.TrimSpace(cfg.FGAStore) == "").
53+
Msg("OpenFGA authorization engine initialized (embedded)")
54+
return fgaEngine, cleanup
55+
}

0 commit comments

Comments
 (0)