authorizerd

package module
v5.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2022 License: Apache-2.0 Imports: 19 Imported by: 0

README

Athenz authorizer

GitHub release (latest by date) CircleCI codecov Go Report Card GolangCI Codacy Badge GoDoc Contributor Covenant

What is Athenz authorizer

Athenz authorizer is a library to cache the policies of Athenz to authorizer authentication and authorization check of user request.

Overview

Usage

To initialize authorizer.

package main

import (
    "context"
    "crypto/x509"
    "encoding/pem"
    "log"

    authorizerd "github.com/wfen/athenz-authorizer/v5"
)

func main() {
    // Initialize authorizerd
    daemon, err := authorizerd.New(
        authorizerd.WithAthenzURL("www.athenz.io"), // set athenz URL
        authorizerd.WithAthenzDomains("domain1", "domain2", "domain N"), // set athenz domains
        authorizerd.WithPubkeyRefreshPeriod("12h"), // optional, default: 24h
        authorizerd.WithPolicyRefreshPeriod("1h"), // optional, default: 30m
    )
    if err != nil {
        // cannot initialize authorizer daemon
        log.Fatalf("daemon new error: %v", err)
    }

    // Start authorizer daemon
    ctx := context.Background() // user can control authorizer daemon lifetime using this context
    if err = daemon.Init(ctx); err != nil { // initialize internal daemons in dependency order (e.g. public keys before signed policies)
        // cannot initialize internal daemons inside authorizer
        log.Fatalf("daemon init error: %v", err)
    }
    errs := daemon.Start(ctx)
    go func() {
        for err := range errs {
            // user should handle errors return from the daemon
            log.Printf("daemon start error: %v", err)
        }
    }()

    act := "action"
    res := "resource"

    // Authorize with access token
    at := "<certificate bound access token>"
    certPEM := "<binding certificate>"
    block, _ := pem.Decode([]byte(certPEM))
    if block == nil {
        log.Fatalln("failed to parse certificate PEM")
    }
    cert, err := x509.ParseCertificate(block.Bytes)
    if err != nil {
        log.Fatalf("invalid x509 certificate: %v", err)
    }
    atp, err := daemon.AuthorizeAccessToken(ctx, at, act, res, cert)
    if err != nil {
        // NOT authorized, please take appropriate action
        log.Fatalf("access token not authorized: %v", err)
    }
    log.Printf("authorized principal in access token: %#v", atp)

    // Authorize with role token
    rt := "<role token>"
    rtp, err := daemon.AuthorizeRoleToken(ctx, rt, act, res)
    if err != nil {
        // NOT authorized, please take appropriate action
        log.Fatalf("role token not authorized: %v", err)
    }
    log.Printf("authorized principal in role token: %#v", rtp)
}

How it works

To do the authentication and authorization check, the user needs to specify which domain data to be cache. The authorizer will periodically refresh the policies and Athenz public key data to verify and decode the domain data. The verified domain data will cache into the memory, and use for authentication and authorization check.

The authorizer contains two sub-module, Athenz public key daemon (pubkeyd) and Athenz policy daemon (policyd).

Athenz public key daemon

Athenz public key daemon (pubkeyd) is responsible for periodically update the Athenz public key data from Athenz server to verify the policy data received from Athenz policy daemon and verify the role token.

Athenz policy daemon

Athenz policy daemon (policyd) is responsible for periodically update the policy data of specified Athenz domain from Athenz server. The received policy data will be verified using the public key got from pubkeyd, and cache into memory. Whenever user requesting for the access check, the verification check will be used instead of asking Athenz server every time.

Configuration

The authorizer uses functional options pattern to initialize the instance. All the options are defined here.

Option name Description Default Value Required Example
AthenzURL The Athenz server URL athenz.io/zts/v1 Yes "athenz.io/zts/v1"
AthenzDomains Athenz domain names that contain the RBAC policies [] Yes "domName1", "domName2"
HTTPClient The HTTP client for connecting to Athenz server http.Client{ Timeout: 30 * time.Second } No http.DefaultClient
CacheExp The TTL of the success cache 1 Minute No 1 * time.Minute
Enable/DisablePubkeyd Run public key daemon or not true No
PubkeySysAuthDomain System authority domain name to retrieve Athenz public key data sys.auth No "sys.auth"
PubkeyRefreshPeriod Period to refresh the Athenz public key data 24 Hours No "24h"
PubkeyETagExpiry ETag cache TTL of Athenz public key data 168 Hours (1 Week) No "168h"
PubkeyETagPurgePeriod ETag cache purge duration 84 Hours No "84h"
PubkeyRetryDelay Delay of next retry on request failed 1 Minute No "1m"
Enable/DisablePolicyd Run policy daemon or not true No
PolicyExpiryMargin Update the policy by a margin duration before the policy actually expires 3 Hours No "3h"
PolicyRefreshPeriod Period to refresh the Athenz policies 30 Minutes No "30m"
PolicyPurgePeriod Policy cache purge duration 1 Hours No "1h"
PolicyRetryDelay Delay of next retry on request fail 1 Minute No "1m"
PolicyRetryAttempts Maximum retry attempts on request fail 2 No 2
Enable/DisableJwkd Run JWK daemon or not true No
JwkRefreshPeriod Period to refresh the Athenz JWK 24 Hours No "24h"
JwkRetryDelay Delay of next retry on request fail 1 Minute No "1m"
jwkURLs URL to get jwk other than AthenzURL [] No "http://domain1/jwks", "http://domain2/jwks"
AccessTokenParam Use access token verification, details: AccessTokenParam Same as AccessTokenParam No {}
Enable/DisableRoleToken Use role token verification or not true No
RoleAuthHeader The HTTP header to extract role token Athenz-Role-Auth No "Athenz-Role-Auth"
Enable/DisableRoleCert Use role certificate verification or not true No
RoleCertURIPrefix Extract role from role certificate athenz://role/ No "athenz://role/"
AccessTokenParam
Option name Description Default Value Required Example
enable Use access token verification or not true No true
verifyCertThumbprint Use certificate bound access token verification true No true
certBackdateDur Backdate duration of the issue time of the certificate 1 Hour No "1h"
certOffsetDur Offset window to accept access token with a mismatching certificate thumbprint 1 Hour No "1h"
verifyClientID Use authorized client ID verification false No false
authorizedClientIDs Authorized client ID to certificate common name map nil No { "atClientID": { "certCN1", "certCN2" } }

License

Copyright (C) 2018 Yahoo Japan Corporation Athenz team.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributor License Agreement

This project requires contributors to agree to a Contributor License Agreement (CLA).

Note that only for contributions to the athenz-authorizer repository on the GitHub, the contributors of them shall be deemed to have agreed to the CLA without individual written agreements.

About releases

  • Releases
    • GitHub release (latest by date)

Authors

Documentation

Overview

Package authorizerd represents the policy updater daemon.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRoleTokenInvalid "Access denied due to invalid RoleToken"
	ErrRoleTokenInvalid = role.ErrRoleTokenInvalid
	// ErrRoleTokenExpired "Access denied due to expired RoleToken"
	ErrRoleTokenExpired = role.ErrRoleTokenExpired

	// ErrDomainMismatch "Access denied due to domain mismatch between Resource and RoleToken"
	ErrDomainMismatch = policy.ErrDomainMismatch
	// ErrDomainNotFound "Access denied due to domain not found in library cache"
	ErrDomainNotFound = policy.ErrDomainNotFound
	// ErrDomainExpired "Access denied due to expired domain policy file"
	ErrDomainExpired = policy.ErrDomainExpired
	// ErrNoMatch "Access denied due to no match to any of the assertions defined in domain policy file"
	ErrNoMatch = policy.ErrNoMatch
	// ErrInvalidPolicyResource "Access denied due to invalid/empty policy resources"
	ErrInvalidPolicyResource = policy.ErrInvalidPolicyResource
	// ErrDenyByPolicy "Access Check was explicitly denied"
	ErrDenyByPolicy = policy.ErrDenyByPolicy
	// ErrFetchPolicy "Error fetching athenz policy"
	ErrFetchPolicy = policy.ErrFetchPolicy

	// ErrInvalidParameters "Access denied due to invalid/empty action/resource values"
	ErrInvalidParameters = errors.New("Access denied due to invalid/empty action/resource values")

	// ErrInvalidCredentials "Access denied due to invalid credentials"
	ErrInvalidCredentials = errors.New("Access denied due to invalid credentials")
)

Functions

This section is empty.

Types

type AccessTokenParam

type AccessTokenParam struct {
	// contains filtered or unexported fields
}

func NewAccessTokenParam

func NewAccessTokenParam(enable bool, verifyCertThumbprint bool, certBackdateDur, certOffsetDur string, verifyClientID bool, authorizedClientIDs map[string][]string) AccessTokenParam

NewAccessTokenParam returns a new access token parameter

type Authorizerd

type Authorizerd interface {
	// Init initializes the child daemons synchronously
	Init(ctx context.Context) error
	// Start starts the background updater of the child daemons asynchronously
	Start(ctx context.Context) <-chan error

	Verify(r *http.Request, act, res string) error
	Authorize(r *http.Request, act, res string) (Principal, error)
	VerifyAccessToken(ctx context.Context, tok, act, res string, cert *x509.Certificate) error
	AuthorizeAccessToken(ctx context.Context, tok, act, res string, cert *x509.Certificate) (Principal, error)
	VerifyRoleToken(ctx context.Context, tok, act, res string) error
	AuthorizeRoleToken(ctx context.Context, tok, act, res string) (Principal, error)
	VerifyRoleCert(ctx context.Context, peerCerts []*x509.Certificate, act, res string) error
	AuthorizeRoleCert(ctx context.Context, peerCerts []*x509.Certificate, act, res string) (Principal, error)
	GetPolicyCache(ctx context.Context) map[string]interface{}
}

Authorizerd represents a daemon for user to verify the role token

func New

func New(opts ...Option) (Authorizerd, error)

New creates the Authorizerd object with the options

type MappingRules

type MappingRules struct {
	Rules map[string][]Rule
}

MappingRules keeps the translation rules

func NewMappingRules

func NewMappingRules(rules map[string][]Rule) (*MappingRules, error)

NewMappingRules creates the MappingRules object

func (*MappingRules) Translate

func (mr *MappingRules) Translate(domain, method, path, query string) (string, string, error)

Translate the information given to the argument to action and resource

type OAuthAccessToken

type OAuthAccessToken interface {
	ClientID() string
}

OAuthAccessToken is an interface for a principal that has a OAuthAccessToken

type Option

type Option func(*authority) error

Option represents a functional option

func WithAccessTokenParam

func WithAccessTokenParam(accessTokenParam AccessTokenParam) Option

WithAccessTokenParam returns a functional option that new access token parameter

func WithAthenzDomains

func WithAthenzDomains(domains ...string) Option

WithAthenzDomains returns an AthenzDomains functional option

func WithAthenzURL

func WithAthenzURL(url string) Option

WithAthenzURL returns an AthenzURL functional option

func WithCacheExp

func WithCacheExp(exp time.Duration) Option

WithCacheExp returns a CacheExp functional option

func WithDisableJwkd

func WithDisableJwkd() Option

WithDisableJwkd returns a DisableJwkd functional option

func WithDisablePolicyd

func WithDisablePolicyd() Option

WithDisablePolicyd returns a DisablePolicyd functional option

func WithDisablePubkeyd

func WithDisablePubkeyd() Option

WithDisablePubkeyd returns a DisablePubkeyd functional option

func WithDisableRoleCert

func WithDisableRoleCert() Option

WithDisableRoleCert returns a disable rolecert functional option

func WithDisableRoleToken

func WithDisableRoleToken() Option

WithDisableRoleToken returns a disable roletoken functional option

func WithEnableJwkd

func WithEnableJwkd() Option

WithEnableJwkd returns an EnableJwkd functional option

func WithEnablePolicyd

func WithEnablePolicyd() Option

WithEnablePolicyd returns an EnablePolicyd functional option

func WithEnablePubkeyd

func WithEnablePubkeyd() Option

WithEnablePubkeyd returns an EnablePubkeyd functional option

func WithEnableRoleCert

func WithEnableRoleCert() Option

WithEnableRoleCert returns a enable rolecert functional option

func WithEnableRoleToken

func WithEnableRoleToken() Option

WithEnableRoleToken returns a enable roletoken functional option

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient returns a HTTPClient functional option

func WithJwkRefreshPeriod

func WithJwkRefreshPeriod(t string) Option

WithJwkRefreshPeriod returns a JwkRefreshPeriod functional option

func WithJwkRetryDelay

func WithJwkRetryDelay(i string) Option

WithJwkRetryDelay returns a JwkRetryDelay functional option

func WithJwkURLs

func WithJwkURLs(urls []string) Option

WithJwkURLs returns a JwkURLs functional option

func WithPolicyExpiryMargin

func WithPolicyExpiryMargin(t string) Option

WithPolicyExpiryMargin returns a PolicyExpiryMargin functional option

func WithPolicyPurgePeriod

func WithPolicyPurgePeriod(t string) Option

WithPolicyPurgePeriod returns a PolicyPurgePeriod functional option

func WithPolicyRefreshPeriod

func WithPolicyRefreshPeriod(t string) Option

WithPolicyRefreshPeriod returns a PolicyRefreshPeriod functional option

func WithPolicyRetryAttempts

func WithPolicyRetryAttempts(c int) Option

WithPolicyRetryAttempts returns a PolicyRetryAttempts functional option

func WithPolicyRetryDelay

func WithPolicyRetryDelay(i string) Option

WithPolicyRetryDelay returns a PolicyRetryDelay functional option

func WithPubkeyETagExpiry

func WithPubkeyETagExpiry(t string) Option

WithPubkeyETagExpiry returns a PubkeyETagExpiry functional option

func WithPubkeyETagPurgePeriod

func WithPubkeyETagPurgePeriod(t string) Option

WithPubkeyETagPurgePeriod returns a PubkeyETagPurgePeriod functional option

func WithPubkeyRefreshPeriod

func WithPubkeyRefreshPeriod(t string) Option

WithPubkeyRefreshPeriod returns a PubkeyRefreshPeriod functional option

func WithPubkeyRetryDelay

func WithPubkeyRetryDelay(i string) Option

WithPubkeyRetryDelay returns a PubkeyRetryDelay functional option

func WithPubkeySysAuthDomain

func WithPubkeySysAuthDomain(domain string) Option

WithPubkeySysAuthDomain returns a PubkeySysAuthDomain functional option

func WithRoleAuthHeader

func WithRoleAuthHeader(h string) Option

WithRoleAuthHeader returns a RoleAuthHeader functional option

func WithRoleCertURIPrefix

func WithRoleCertURIPrefix(t string) Option

WithRoleCertURIPrefix returns a RoleCertURIPrefix functional option

func WithTranslator

func WithTranslator(t Translator) Option

WithTranslator returns a Translator functional option

type Principal

type Principal interface {
	Name() string
	Roles() []string
	Domain() string
	IssueTime() int64
	ExpiryTime() int64
	AuthorizedRoles() []string
}

Principal is an authenticated entity

type Rule

type Rule struct {
	Method   string `yaml:"method"`
	Path     string `yaml:"path"`
	Action   string `yaml:"action"`
	Resource string `yaml:"resource"`
	// contains filtered or unexported fields
}

Rule represents a rule for translation

type Translator

type Translator interface {
	Translate(domain, method, path, query string) (string, string, error)
}

Translator translates the information given to the argument to action and resource

Directories

Path Synopsis
Package access represents the processing logic of access token.
Package access represents the processing logic of access token.
internal
url
Package url contains the utility functions for URL processing
Package url contains the utility functions for URL processing
Package jwk represents the jwk daemon fetching logic and the interface
Package jwk represents the jwk daemon fetching logic and the interface
Package policy represents the athenz policy updater fetching and verify logic and provide an interface to verify the policy data.
Package policy represents the athenz policy updater fetching and verify logic and provide an interface to verify the policy data.
Package pubkey represents the public key updater fetching logic and the interface
Package pubkey represents the public key updater fetching logic and the interface
Package role represents the processing logic of role token.
Package role represents the processing logic of role token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL