Giter Site home page Giter Site logo

openfga / sdk-generator Goto Github PK

View Code? Open in Web Editor NEW
14.0 12.0 32.0 2.87 MB

OpenFGA Client SDK Generator

License: Apache License 2.0

Makefile 0.34% Mustache 96.70% Shell 0.59% Go 0.97% JavaScript 0.20% Dockerfile 0.01% Python 0.42% C# 0.31% Java 0.24% Kotlin 0.23%
security authorization fga zanzibar fine-grained-authorization access-control openfga

sdk-generator's Introduction

OpenFGA

Go Reference GitHub release (latest SemVer) Docker Pulls Codecov Go Report CII Best Practices Join our community Twitter FOSSA Status Artifact HUB OpenSSF Scorecard SLSA 3

A high-performance and flexible authorization/permission engine built for developers and inspired by Google Zanzibar.

OpenFGA is designed to make it easy for developers to model their application permissions and add and integrate fine-grained authorization into their applications.

It allows in-memory data storage for quick development, as well as pluggable database modules. It currently supports PostgreSQL 14 and MySQL 8.

It offers an HTTP API and a gRPC API. It has SDKs for Java, Node.js/JavaScript, GoLang, Python and .NET. Look in our Community section for third-party SDKs and tools. It can also be used as a library (see example).

Getting Started

The following section aims to help you get started quickly. Please look at our official documentation for in-depth information.

Setup and Installation

ℹī¸ The following sections setup an OpenFGA server using the default configuration values. These are for rapid development and not for a production environment. Data written to an OpenFGA instance using the default configuration with the memory storage engine will not persist after the service is stopped.

For more information on how to configure the OpenFGA server, please take a look at our official documentation on Running in Production.

Docker

OpenFGA is available on Dockerhub, so you can quickly start it using the in-memory datastore by running the following commands:

docker pull openfga/openfga
docker run -p 8080:8080 -p 3000:3000 openfga/openfga run

Tip

The OPENFGA_HTTP_ADDR environment variable can used to configure the address at which the playground expects the OpenFGA server to be. For example, docker run -e OPENFGA_PLAYGROUND_ENABLED=true -e OPENFGA_HTTP_ADDR=0.0.0.0:4000 -p 4000:4000 -p 3000:3000 openfga/openfga run will start the OpenFGA server on port 4000, and configure the playground too.

Docker Compose

docker-compose.yaml provides an example of how to launch OpenFGA with Postgres using docker compose.

  1. First, either clone this repo or curl the docker-compose.yaml file with the following command:

    curl -LO https://openfga.dev/docker-compose.yaml
  2. Then, run the following command:

    docker compose up

Package Managers

If you are a Homebrew user, you can install OpenFGA with the following command:

brew install openfga

Pre-compiled Binaries

Download your platform's latest release and extract it. Then run the binary with the command:

./openfga run

Building from Source

There are two recommended options for building OpenFGA from source code:

Building from source with go install

Make sure you have Go 1.20 or later installed. See the Go downloads page.

You can install from source using Go modules:

  1. First, make sure $GOBIN is on your shell $PATH:

    export PATH=$PATH:$(go env GOBIN)
  2. Then use the install command:

    go install github.com/openfga/openfga/cmd/openfga
  3. Run the server with:

    ./openfga run

Building from source with go build

Alternatively you can build OpenFGA by cloning the project from this Github repo, and then building it with the go build command:

  1. Clone the repo to a local directory, and navigate to that directory:

    git clone https://github.com/openfga/openfga.git && cd openfga
  2. Then use the build command:

    go build -o ./openfga ./cmd/openfga
  3. Run the server with:

    ./openfga run

Verifying the Installation

Now that you have Set up and Installed OpenFGA, you can test your installation by creating an OpenFGA Store.

curl -X POST 'localhost:8080/stores' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name": "openfga-demo"
}'

If everything is running correctly, you should get a response with information about the newly created store, for example:

{
  "id": "01G3EMTKQRKJ93PFVDA1SJHWD2",
  "name": "openfga-demo",
  "created_at": "2022-05-19T17:11:12.888680Z",
  "updated_at": "2022-05-19T17:11:12.888680Z"
}

Playground

The Playground facilitates rapid development by allowing you to visualize and model your application's authorization model(s) and manage relationship tuples with a locally running OpenFGA instance.

To run OpenFGA with the Playground disabled, provide the --playground-enabled=false flag.

./openfga run --playground-enabled=false

Once OpenFGA is running, by default, the Playground can be accessed at http://localhost:3000/playground.

In the event that a port other than the default port is required, the --playground-port flag can be set to change it. For example,

./openfga run --playground-enabled --playground-port 3001

Profiler (pprof)

Profiling through pprof can be enabled on the OpenFGA server by providing the --profiler-enabled flag.

./openfga run --profiler-enabled

This will start serving profiling data on port 3001. You can see that data by visiting http://localhost:3001/debug/pprof.

If you need to serve the profiler on a different address, you can do so by specifying the --profiler-addr flag. For example,

./openfga run --profiler-enabled --profiler-addr :3002

Once the OpenFGA server is running, in another window you can run the following command to generate a compressed CPU profile:

go tool pprof -proto -seconds 60 http://localhost:3001/debug/pprof/profile
# will collect data for 60 seconds and generate a file like pprof.samples.cpu.001.pb.gz

That file can be analyzed visually by running the following command and then visiting http://localhost:8084:

go tool pprof -http=localhost:8084 pprof.samples.cpu.001.pb.gz

Next Steps

Take a look at examples of how to:

Don't hesitate to browse the official Documentation, API Reference.

Limitations

MySQL Storage engine

The MySQL storage engine has a lower length limit for some properties of a tuple compared with other storage backends. For more information see the docs.

OpenFGA's MySQL Storage Adapter was contributed to OpenFGA by @twintag. Thanks!

Production Readiness

The core OpenFGA service has been in use by Okta FGA in production since December 2021.

OpenFGA's Memory Storage Adapter was built for development purposes only and is not recommended for a production environment, because it is not designed for scalable queries and has no support for persistence.

You can learn about more organizations using OpenFGA in production here. If your organization is using OpenFGA in production please consider adding it to the list.

The OpenFGA team will do its best to address all production issues with high priority.

Contributing

See CONTRIBUTING.

Community Meetings

We hold a monthly meeting to interact with the community, collaborate and receive/provide feedback. You can find more details, including the time, our agenda, and the meeting minutes here.

sdk-generator's People

Contributors

aaguiarz avatar adriantam avatar balaji-dongare avatar bketelsen avatar booniepepper avatar chgc avatar dependabot[bot] avatar designrknight avatar didier-simplecommedev avatar eddumelendez avatar evansims avatar ewanharris avatar gabrielbussolo avatar gurleensethi avatar harper avatar jimmyjames avatar jpadilla avatar le-yams avatar matt-potter avatar miparnisari avatar paulosuzart avatar rhamzeh avatar sebport0 avatar srose avatar tjtanjin avatar wonyx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdk-generator's Issues

[JS SDK] Client Credentials bearer token is not cached between requests

When inspecting the traces of the calls to auth0 in our system, I noticed we make a call to get a token on every request.
After looking at the JS sdk code, I noticed that the credentials are indeed cached in the BaseAPI object, but this property is not used (as far as I can tell).
Every call to `createRequestFunction does not pass the credentials object, so the class is instantiated each time and the token is not cached.

Yes, I am aware that auth0 FGA have a separate SDK, we are using the OSS one to make testing easier.

[All SDKs] Validate that the Store ID and Authorization Model ID are valid ULIDs

When providing configuration to the SDKs, the user may put any strings in most of the fields

We already validate that: apiScheme + apiHost and the apiTokenIssuer are in the appropriate format, we should do the same for StoreId and AuthorizationModelId where appropriate as we know they are in ulid format.

We should not integrate the ulid library for that, as we'd rather keep our prod dependencies to an absolute minimum, but we can use regex.

[0-7][0-9A-HJKMNP-TV-Z]{25} should work, but we have not verified it yet (source).

Tests must be added for all corresponding functionality

Clearing existing directory fails if directory is already empty during `make build-client-<foo>`

Steps taken:

  • Cloned the repo
  • Ran make setup-new-sdk
  • Filled in the config.overrides.json
  • Ran make build-client-rust, ended up with this error:
% make build-client-rust
make build-client sdk_language=rust tmpdir=/tmp/tmp.wm6Z2
make[1]: Entering directory '/home/nett/Stuff/openfga-sdk-generator'
mkdir -p "/home/nett/Stuff/openfga-sdk-generator/docs/openapi/" "/home/nett/Stuff/openfga-sdk-generator/clients/"
mkdir -p "/home/nett/Stuff/openfga-sdk-generator/docs/openapi"
curl "https://raw.githubusercontent.com/openfga/api/main/docs/openapiv2/apidocs.swagger.json" \
     -o "/home/nett/Stuff/openfga-sdk-generator/docs/openapi/openfga.openapiv2.raw.json"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 63399  100 63399    0     0   435k      0 --:--:-- --:--:-- --:--:--  439k
cat "/home/nett/Stuff/openfga-sdk-generator/docs/openapi/openfga.openapiv2.raw.json" | \
	docker run --rm -i stedolan/jq \
	 '(.. | .tags? | select(.)) |= ["OpenFga"] | (.tags? | select(.)) |= [{"name":"OpenFga"}] | del(.definitions.ReadTuplesParams, .definitions.ReadTuplesResponse, .paths."/stores/{store_id}/read-tuples", .definitions.StreamedListObjectsRequest, .definitions.StreamedListObjectsResponse, .paths."/stores/{store_id}/streamed-list-objects")' > \
	/home/nett/Stuff/openfga-sdk-generator/docs/openapi/openfga.openapiv2.json
sed -i -e 's/v1.//g' /home/nett/Stuff/openfga-sdk-generator/docs/openapi/openfga.openapiv2.json
# Build a config from common + overrides
jq -rs 'reduce .[] as $item ({}; . * $item)' "/home/nett/Stuff/openfga-sdk-generator/config/common/config.base.json" "/home/nett/Stuff/openfga-sdk-generator/config/clients/rust/config.overrides.json" > "/tmp/tmp.wm6Z2/config.json"
mkdir -p "/home/nett/Stuff/openfga-sdk-generator/clients/fga-rust-sdk"
# Initialize the temporary template directory
mkdir "/tmp/tmp.wm6Z2/template"
# Copy the shared files into temp template
cp -r "/home/nett/Stuff/openfga-sdk-generator/config/common/files/." "/tmp/tmp.wm6Z2/template/"
# Copy the template files into temp template
cp -r "/home/nett/Stuff/openfga-sdk-generator/config/clients/rust/template/." "/tmp/tmp.wm6Z2/template/"
# Copy the CHANGELOG.md file into temp template
cp "/home/nett/Stuff/openfga-sdk-generator/config/clients/rust/CHANGELOG.md.mustache" "/tmp/tmp.wm6Z2/template/"
# Clear existing directory
cd "/home/nett/Stuff/openfga-sdk-generator/clients/fga-rust-sdk" && ls -A | grep -Ev '.git|node_modules|.idea' | xargs rm -r && cd -
rm: missing operand
Try 'rm --help' for more information.
make[1]: *** [Makefile:149: build-client] Error 123
make[1]: Leaving directory '/home/nett/Stuff/openfga-sdk-generator'
make: *** [Makefile:245: build-client-rust] Error 2

This seems to be related to this SO question: https://stackoverflow.com/questions/36617999/error-rm-missing-operand-when-using-along-with-find-command
cd "/home/nett/Stuff/openfga-sdk-generator/clients/fga-rust-sdk" && ls -A | grep -Ev '.git|node_modules|.idea' returns exit code 1 as the directory is completely empty:

% ls -A clients/fga-rust-sdk
% cd "/home/nett/Stuff/openfga-sdk-generator/clients/fga-rust-sdk" && ls -A | grep -Ev '.git|node_modules|.idea'
% echo $?
1

Java SDK: Choosing an HTTP client library

Let's get the best HTTP client library that will fit OpenFGA needs:

The primary list I'm considering is the list of library options from openapi-generator:

https://github.com/OpenAPITools/openapi-generator/blob/master/docs/generators/java.md#config-options

Features

Library JDK Abstraction NIO (Non-blocking IO) HTTP2
Apache HttpClient (5) 7+ HTTP Yes Yes
Java 11 HttpClient 9+ HTTP Yes Yes
Jersey 3 7+ REST Yes Yes* ( *requires Jetty)
OkHttp 8+ HTTP No Yes
OpenFeign 8+ HTTP No Yes* (* requires JDK 11+)
Resteasy 8+ REST No No
Vert.x 8+ HTTP Yes Yes

All above support both synchronous and asynchronous execution. They also all support HTTP Header
customization, although the REST versions tend to have more abstraction.

The following HTTP libraries are supported by the Open API generator, but are
not stand-alone projects, so are not included in the table above:

Feature References:

Benchmarking

Benchmarking References:


Notes: The long-term support (LTS) versions of JDK today are 8, 11, 17. JDK 8 ended active
support in May 2022, but is widely used and will see security support until 2030. JDK 21 is
scheduled for release in Sept 2023.

JS SDK: Batch Check & List Relations

  • FGA Client Wrapper: OpenFgaClient that wraps OpenFgaApi
  • FGA Client Wrapper Tests
  • BatchCheck Method
  • BatchCheck Request Header
  • BatchCheck Tests
  • BatchCheck Configurable Parallelization
  • ListRelations Method
  • ListRelations: Validate passed relations on the authorization model
  • ListRelations: If no relations passed, get them from the authorization model
  • ListRelations Request Header
  • ListRelations Tests
  • ListRelations Configurable Parallelization
  • Update README to use OpenFgaClient instead of OpenFgaApi

[.NET SDK] ApiToken Credentials not working

The ApiToken authentication method does not seem to be working, no authorization header is passed even though it is configured.
I took a glance at the code and the BaseClient seems to be created before the Authorization headers get added to the configuration's DefaultHeaders.

ApiClient.cs

public ApiClient(Configuration.Configuration configuration, HttpClient? userHttpClient = null) {
        configuration.IsValid();
        _configuration = configuration;
        _baseClient = new BaseClient(configuration, userHttpClient);

        if (configuration.Credentials == null) {
            return;
        }

        switch (configuration.Credentials.Method) {
            case CredentialsMethod.ApiToken:
                configuration.DefaultHeaders.Add("Authorization", $"Bearer {configuration.Credentials.Config!.ApiToken}");
                break;
            case CredentialsMethod.ClientCredentials:
                _oauth2Client = new OAuth2Client(configuration.Credentials, _baseClient);
                break;
            case CredentialsMethod.None:
            default:
                break;
        }
    }

Common API BDD Test Cases

As the number of Client APIs increase, to ensure there is uniform test coverage across those APIs, it would be useful to maintain a central set of Feature Files that describe baseline tests expected by the API Maintainers.

It would be great if we could maintain one common set of feature files that can be implemented across each language. For example, you could have a feature file for authentication that looks like:

Feature: OpenFGA Client API Authentication
  Scenario: No Auth Request against No Auth Server
    Given I have a client with Authentication Disabled
    When The server has Authentication Disabled
    Then I get a valid response from the server

Then implement those tests under each of the different sdk implementations.

As I work on the Kotlin endpoint, I intend to write some base feature files, and was interested to see if it's something that could be adopted more widely across the sdk generators.

Python SDK import should be correct order

As per openfga/python-sdk#24, the python SDKs client.py library imports library in the wrong order.

As per PEP 8, the import should be in order of

  1. Standard library imports.
  2. Related third party imports.
  3. Local application/library specific imports.

Furthermore, it may be good to have clean up the import so that we only import what is needed (openfga/python-sdk#23).

The file in question is https://github.com/openfga/sdk-generator/blob/main/config/clients/python/template/client/client.mustache

Provide a better guide for SDK contributors

The process for contributing a new SDK or improving an existing one is still a bit vague, we should add documentation, and possibly a quick tutorial of what that entails.

Python SDK README should call fga_client instead of api_instance

As per openfga/python-sdk#25, the python SDK README should call fga_client instead of api_instance.

There are three places where this is not called correctly

[Python] Failure during building and testing main branch

Seems like pycodestyle v2.11.0 results in breaking autopep8. See hhatto/autopep8#689

Traceback (most recent call last):
  File "/usr/local/bin/autopep8", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 4528, in main
    results = fix_multiple_files(args.files, args, sys.stdout)
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 4423, in fix_multiple_files
    ret = _fix_file((name, options, output))
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 4393, in _fix_file
    return fix_file(*parameters)
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 3589, in fix_file
    fixed_source = fix_lines(fixed_source, options, filename=filename)
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 3569, in fix_lines
    fixed_source = fix.fix()
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 613, in fix
    self._fix_source(filter_results(source=''.join(self.source),
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 557, in _fix_source
    modified_lines = fix(result)
  File "/usr/local/lib/python3.10/site-packages/autopep8.py", line 761, in fix_e225
    pycodestyle.missing_whitespace_around_operator(fixed, ts))
AttributeError: module 'pycodestyle' has no attribute 'missing_whitespace_around_operator'. Did you mean: 'whitespace_around_operator'?

Github issues do not display template for SDKs

I expect that template for bug/feature requests be provided when creating issues for SDKs. However, no templates are seen.

Issue may be related to the fact that the SDKs have the template in .github/ISSUE_TEMPLATES instead of .github/ISSUE_TEMPLATE directory.

Screen.Recording.2023-06-09.at.9.52.40.AM.mov

[SDK Request] Rust SDK

Hello, I'd like to request you to consider adding an official SDK for the Rust language.
The openapi-generator supports Rust and generally generates sane code (including async support if the reqwest client is chosen).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤ī¸ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.