Categorygithub.com/safenetlabs/tyk
modulepackage
1.2.1
Repository: https://github.com/safenetlabs/tyk.git
Documentation: pkg.go.dev

# README

Build Status

Tyk API Gateway

Tyk is a lightweight, open source API Gateway and enables you to control who accesses your API, when they access it and how they access it. Tyk will also record detailed analytics on how your users are interacting with your API and when things go wrong.


What is an API Gateway?

An API Gateway sits in front of your application(s) and manages the heavy lifting of authorisation, access control and throughput limiting to your services. Ideally, it should mean that you can focus on creating services instead of implementing management infrastructure. For example if you have written a really awesome web service that provides geolocation data for all the cats in NYC, and you want to make it public, integrating an API gateway is a faster, more secure route that writing your own authorisation middleware.

Key Features of Tyk

Tyk offers powerful, yet lightweight features that allow fine gained control over your API ecosystem.

  • RESTFul API - Full programatic access to the internals makes it easy to manage your API users, keys and Api Configuration from within your systems
  • Multiple access protocols - Out of the box, Tyk supports Token-based, HMAC Signed, Basic Auth and Keyless access methods
  • Rate Limiting - Easily rate limit your API users, rate limiting is granular and can be applied on a per-key basis
  • Quotas - Enforce usage quotas on users to manage capacity or charge for tiered access
  • Granular Access Control - Grant api access on a version by version basis, grant keys access to multiple API's or just a single version
  • Key Expiry - Control how long keys are valid for
  • API Versioning - API Versions can be easily set and deprecated at a specific time and date
  • Blacklist/Whitelist/Ignored endpoint access - Enforce strict security models on a version-by-version basis to your access points
  • Analytics logging - Record detailed usage data on who is using your API's (raw data only)
  • Webhooks - Trigger webhooks against events such as Quota Violations and Authentication failures
  • IP Whitelisting - Block access to non-trusted IP addresses for more secure interactions
  • Zero downtime restarts - Tyk configurations can be altered dynamically and the service restarted without affecting any active request

Tyk is written in Go, which makes it fast and easy to set up. Its only dependencies are a Mongo database (for analytics) and Redis, though it can be deployed without either (not recommended).

Why?

Tyk was built because other open source API Gateways in the market come with dependencies and bloat, attempting to be too many things to too many people. tyk is focused, simple and does one thing well - protecting your API from unauthorised access.

Documentation

All the documentation can be found on our main site at http://tyk.io/about/

License

Tyk is released under the MPL v2.0 please see the LICENSE.md file for a full version of the license.

Contribute / Build

To get started contributing, clone the repo to your local go workspace, change into the new tyk directory and run go get, this should retrieve all the dependencies.

We are working to increase test coverage of features, currently the majority of auth methods and middleware are tested, however it could always be better.

Any changes that are submitted with a pull request should come with a test and be in a separate branch. Basically, use this checklist:

  • Do your changes have tests?
  • Have you run the tests?
  • Did they pass?
  • Have you written a test for your feature?
  • Does it pass after merge?

If you can answer yes to all of the above, feel free to submit a pull request :-)

Roadmap

To coordinate development and be completely transparent as to where the project is going, the version roadmap for the next version, as well as proposed features and adopted proposals can be viewed on our public Trello board:

https://trello.com/b/59d5kAZ5/tyk-api-gateway-roadmap

Any proposals can be made in the Github issue tracker, proposals that are adopted will be placed into the trello and then moved according to their status.

A note on the tests

Currently in order for tests to pass, a redis host is required. We know, this is terrible and should be handled with an interface, and it is, however in the current version there is a hard requirement for the application to have its default memory setup to use redis as part of a deployment, this is to make it easier to install the application for the end-user. Future versions will work around this, or we may drop the memory requirement.

The simplest way to get the tests to run is to install local redis, or (what I do) have a vagrant instance that is running redis, then you can just vagrant up when you need redis and kill it later. Just make sure you are forwarding the default ports 1:1.

Dev versus stable

The master branch is NOT the stable releases, check the tags for stable releases that can be patched, please se the CHANGELOG for breaking changes or to see how things stand.

Documentation is currently valid for the 1.1 release.

# Functions

No description provided by the author
CheckIsAPIOwner will ensure that the accessor of the tyk API has the correct security credentials - this is a shared secret between the client and the owner and is set in the tyk.conf file.
Generic middleware caller to make extension easier.
No description provided by the author
GetEventHandlerByName is a convenience function to get event handler instances from an API Definition.
GetRedisInterfacePointer creates a reference to a redis connection pool that can be shared across all webhook instances.
No description provided by the author
No description provided by the author
ProxyHandler Proxies requests through to their final destination, if they make it through the middleware chain.
ReloadURLStructure will create a new muxer, reload all the app configs for an instance and then replace the DefaultServeMux with the new one, this enables a reconfiguration to take place without stopping any requests from being handled.
ReturnError returns an error to the http response writer.
TykNewSingleHostReverseProxy returns a new ReverseProxy that rewrites URLs to the scheme, host, and base path provided in target.
TykOsinNewServer creates a new server instance, but uses an extended interface so we can SetClient() too.
WriteDefaultConf will create a default configuration file and set the storage type to "memory".

# Constants

These enums fix the prefix to use when storing various OAuth keys and data, since we delegate everything to the osin framework.
These enums fix the prefix to use when storing various OAuth keys and data, since we delegate everything to the osin framework.
Enums for keys to be stored in a session context - this is how gorilla expects these to be implemented and is lifted pretty much from docs.
Enums representing the various statuses for a VersionInfo Path match during a proxy request.
These enums fix the prefix to use when storing various OAuth keys and data, since we delegate everything to the osin framework.
TODO: change these to real values.
type AuthProviderCode stringtype SessionProviderCode stringtype StorageEngineCode string .
type AuthProviderCode stringtype SessionProviderCode stringtype StorageEngineCode string .
type AuthProviderCode stringtype SessionProviderCode stringtype StorageEngineCode string .
Generic system error.
The name for event handlers as defined in the API Definition JSON/BSON format.
Define the Event Handler name so we can register it.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
Register new event types here, the string is the code used to hook at the Api Deifnititon JSON/BSON level.
Register new event types here, the string is the code used to hook at the Api Deifnititon JSON/BSON level.
Register new event types here, the string is the code used to hook at the Api Deifnititon JSON/BSON level.
Register new event types here, the string is the code used to hook at the Api Deifnititon JSON/BSON level.
Register new event types here, the string is the code used to hook at the Api Deifnititon JSON/BSON level.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
No description provided by the author
Enums representing the various statuses for a VersionInfo Path match during a proxy request.
Notifcation codes for new and refresh codes.
Generic system error.
Generic system error.
Notifcation codes for new and refresh codes.
These enums fix the prefix to use when storing various OAuth keys and data, since we delegate everything to the osin framework.
Enums for keys to be stored in a session context - this is how gorilla expects these to be implemented and is lifted pretty much from docs.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
Statuses of the request, all are false-y except StatusOk and StatusOkAndIgnore.
No description provided by the author
No description provided by the author
No description provided by the author
WH_POST
No description provided by the author
No description provided by the author
Enums representing the various statuses for a VersionInfo Path match during a proxy request.

# Variables

var genericOsinStorage *RedisOsinStorageInterface.
Not Pretty, but will avoi dmillions of connections.

# Structs

AccessDefinition defines which versions of an API a key has access to.
AccessRightsCheck is a midleware that will check if the key bing used to access the API has permission to access the specific version.
AccessTokenGenTyk is a modified authorization token generator that uses the same method used to generate tokens for Tyk authHandler.
AnalyticsError is an error for when writing to the storage engine fails.
AnalyticsRecord encodes the details of a request.
APIAllKeys represents a list of keys in the memory store.
APIDefinitionLoader will load an Api definition from a storage system.
APIError is generic error object returned if there is something wrong with the request.
APIErrorMessage is an object that defines when a generic error occurred.
APIModifyKeySuccess represents when a Key modification was successful.
APISpec represents a path specification for an API, to avoid enumerating multiple nested lists, a single flattened URL list is checked for matching paths and then it's status evaluated if found.
APIStatusMessage represents an API status message.
KeyExists will check if the key being used to access the API is in the request data, and then if the key is in the storage engine.
BasicAuthKeyIsValid uses a username instead of.
BatchReplyUnit encodes a request suitable for replying to a batch request.
BatchRequestHandler handles batch requests on /tyk/batch for any API Definition that has the feature enabled.
BatchRequestStructure defines a batch request order.
Config is the configuration object used by tyk to set up various parameters.
CSVPurger purges the in-memory analytics store to a CSV file as defined in the Config object.
DefaultAuthorisationManager implements AuthorisationHandler, requires a StorageHandler to interact with key store.
No description provided by the author
No description provided by the author
ErrorHandler is invoked whenever there is an issue with a proxied request, most middleware will invoke the ErrorHandler if something is wrong with the request and halt the request processing through the chain.
EVENT_AuthFailureMeta is the metadata structure for an auth failure (EVENT_AuthFailure).
EVENT_KeyExpiredMeta is the metadata structure for an auth failure (EVENT_KeyExpired).
EVENT_QuotaExceededMeta is the metadata structure for a quota exceeded event (EVENT_QuotaExceeded).
EVENT_RateLimitExceededMeta is the metadata structure for a rate limit exceeded event (EVENT_RateLimitExceeded).
EVENT_VersionFailureMeta is the metadata structure for an auth failure (EVENT_KeyExpired).
EventMessage is a standard form to send event data to handlers.
EventMetaDefault is a standard embedded struct to be used with custom event metadata types, gives an interface for easily extending event metadata objects.
HMACMiddleware will check if the request has a signature, and if the request is allowed through.
InMemoryStorageManager implements the StorageHandler interface, it uses an in-memory map to store sessions, should only be used for testing purposes.
IPWhiteListMiddleware lets you define a list of IPs to allow upstream.
KeyError is a standard error for when a key is not found in the storage engine.
KeyExpired middleware will check if the requesting key is expired or not.
LogMessageEventHandler is a sample Event Handler.
ModifiedMiddleware is a sample custom middleware component, must inherit TykMiddleware so you have access to spec and definition data.
No description provided by the author
MongoPurger will purge analytics data into a Mongo database, requires that the Mongo DB string is specified in the Config object.
NewClientRequest is an outward facing JSON object translated from osin OAuthClients.
NewOAuthNotification is a notification sent to a webhook when an access request or a refresh request comes in.
Oauth2KeyExists will check if the key being used to access the API is in the request data, and then if the key is in the storage engine.
OAuthClient is a representation within an APISpec of a client.
OAuthHandlers are the HTTP Handlers that manage the Tyk OAuth flow.
OAuthManager handles and wraps osin OAuth2 functions to handle authorise and access requests.
RateLimitAndQuotaCheck will check the incomming request and key whether it is within it's quota and within it's rate limit, it makes use of the SessionLimiter object to do this.
RedisAnalyticsHandler implements AnalyticsHandler and will record analytics data to a redis back end as defined in the Config object.
TODO: Refactor this to move prefix handling into a checker method, then it can be an unexported setting in the struct.
RedisStorageManager is a storage manager that uses the redis database.
RequestDefinition defines a batch request.
SessionLimiter is the rate limiter for the API, use ForwardMessage() to check if a message should pass through or not.
SessionState objects represent a current API session, mainly used for rate limiting.
SuccessHandler represents the final ServeHTTP() request for a proxied API request.
TykMiddleware wraps up the ApiSpec and Proxy objects to be included in a middleware handler, this can probably be handled better.
TykOsinServer subclasses osin.Server so we can add the SetClient method without wrecking the lbrary.
URLSpec represents a flattened specification for URLs, used to check if a proxy URL path is on any of the white, plack or ignored lists.
VersionCheck will check whether the version of the requested API the request is accessing has any restrictions on URL endpoints.
WebHookHandler is an event handler that triggers web hooks.
No description provided by the author

# Interfaces

AnalyticsHandler is an interface to record analytics data to a writer.
AuthorisationHandler is used to validate a session key, implementing IsKeyAuthorised() to validate if a key exists or is valid in any way (e.g.
No description provided by the author
No description provided by the author
Purger is an interface that will define how the in-memory store will be purged of analytics data to prevent it growing too large.
SessionHandler handles all update/create/access session functions and deals exclusively with SessionState objects, not identity.
StorageHandler is a standard interface to a storage backend, used by AuthorisationManager to read and write key values to the backend.
TykEventHandler defines an event handler, e.g.
No description provided by the author

# Type aliases

ContextKey is a key type to avoid collisions.
OAuthNotificationType const to reduce risk of colisions.
RequestStatus is a custom type to avoid collisions.
URLStatus is a custom enum type to avoid collisions.
No description provided by the author