├── .chglog
├── CHANGELOG.tpl.md
└── config.yml
├── .github
└── workflows
│ ├── codeql-analysis.yml
│ ├── golangci-lint.yaml
│ └── iamci.yaml
├── .gitignore
├── .gitlint
├── .golangci.yaml
├── .gsemver.yaml
├── CHANGELOG
├── CHANGELOG-0.1.0.md
├── CHANGELOG-0.1.1.md
├── CHANGELOG-0.1.2.md
├── CHANGELOG-0.2.0.md
├── CHANGELOG-0.3.1.md
├── CHANGELOG-0.4.0.md
├── CHANGELOG-0.5.0.md
├── CHANGELOG-0.5.7-11-gb20f932.md
├── CHANGELOG-0.6.0-4-gb20f932.md
├── CHANGELOG-0.6.0.md
├── CHANGELOG-0.6.1.md
├── CHANGELOG-0.7.0.md
├── CHANGELOG-0.7.1.md
├── CHANGELOG-0.7.2.md
├── CHANGELOG-1.0.0.md
├── CHANGELOG-1.0.1.md
├── CHANGELOG-1.0.2.md
├── CHANGELOG-1.0.4.md
├── CHANGELOG-1.1.0-4-ge259267.md
├── CHANGELOG-1.1.0.md
├── CHANGELOG-1.2.0.md
├── CHANGELOG-1.4.0.md
├── CHANGELOG-1.6.0.md
├── CHANGELOG-1.6.2.md
└── CHANGELOG-1.7.0.md
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── OWNERS
├── README.md
├── SECURITY.md
├── api
├── openapi
│ └── README.md
└── swagger
│ ├── README.md
│ ├── docs
│ ├── doc.go
│ ├── policy_swagger.go
│ ├── secret_swagger.go
│ └── user_swagger.go
│ └── swagger.yaml
├── build
├── ci
│ └── .keep
├── docker
│ ├── iam-apiserver
│ │ └── Dockerfile
│ ├── iam-authz-server
│ │ └── Dockerfile
│ ├── iam-pump
│ │ └── Dockerfile
│ ├── iam-watcher
│ │ └── Dockerfile
│ └── iamctl
│ │ ├── Dockerfile
│ │ └── build.sh
└── package
│ └── .keep
├── cmd
├── gendocs
│ └── gen_iamctl_docs.go
├── geniamdocs
│ ├── gen_iam_docs.go
│ ├── gen_iam_docs_test.go
│ ├── postprocessing.go
│ └── postprocessing_test.go
├── genman
│ └── gen_iam_man.go
├── genswaggertypedocs
│ └── swagger_type_docs.go
├── genyaml
│ └── gen_iamctl_yaml.go
├── iam-apiserver
│ └── apiserver.go
├── iam-authz-server
│ └── authzserver.go
├── iam-pump
│ └── pump.go
├── iam-watcher
│ └── watcher.go
└── iamctl
│ └── iamctl.go
├── configs
├── README.md
├── access.yaml
├── cert
│ ├── iam-key.pem
│ └── iam.pem
├── ha
│ ├── 10.0.4.20
│ │ ├── iam-apiserver.conf
│ │ ├── iam-authz-server.conf
│ │ ├── keepalived.conf
│ │ └── nginx.conf
│ └── 10.0.4.21
│ │ ├── iam-apiserver.conf
│ │ ├── iam-authz-server.conf
│ │ ├── keepalived.conf
│ │ └── nginx.conf
├── iam-apiserver.yaml
├── iam-authz-server.yaml
├── iam-pump.yaml
├── iam-watcher.yaml
├── iam.sql
├── iamctl.yaml
├── values-pre-env.yaml
├── values-prod-env.yaml
├── values-test-env.yaml
└── values-with-nodeport.yaml
├── deployments
├── README.md
├── iam-v1.6.2.tar.gz
├── iam.invalid.yaml
├── iam.yaml
├── iam
│ ├── .helmignore
│ ├── Chart.yaml
│ ├── service-with-nodeport
│ │ ├── iam-apiserver-service.yaml
│ │ ├── iam-authz-server-service.yaml
│ │ ├── iam-pump-service.yaml
│ │ └── iam-watcher-service.yaml
│ ├── templates
│ │ ├── _helpers.tpl
│ │ ├── hpa.yaml
│ │ ├── iam-apiserver-deployment.yaml
│ │ ├── iam-apiserver-service.yaml
│ │ ├── iam-authz-server-deployment.yaml
│ │ ├── iam-authz-server-service.yaml
│ │ ├── iam-pump-deployment.yaml
│ │ ├── iam-pump-service.yaml
│ │ ├── iam-watcher-deployment.yaml
│ │ ├── iam-watcher-service.yaml
│ │ └── iamctl-deployment.yaml
│ └── values.yaml
└── templates
│ ├── iam-apiserver-deployment.yaml
│ ├── iam-apiserver-service.yaml
│ ├── iam-configmap.yaml
│ └── iam.yaml
├── docs
├── .generated_docs
├── README.md
├── devel
│ └── zh-CN
│ │ ├── architecture.md
│ │ ├── components.md
│ │ ├── development.md
│ │ ├── forking.md
│ │ ├── requirements.md
│ │ ├── scope.md
│ │ └── tools
│ │ ├── commitizen-go.md
│ │ ├── commitsar.md
│ │ ├── git-chglog.md
│ │ ├── go-gitlint.md
│ │ ├── gommit.md
│ │ └── mysqldump.md
├── guide
│ ├── en-US
│ │ ├── cmd
│ │ │ ├── iam-apiserver.md
│ │ │ ├── iam-authz-server.md
│ │ │ ├── iam-pump.md
│ │ │ ├── iam-watcher.md
│ │ │ └── iamctl
│ │ │ │ ├── iamctl.md
│ │ │ │ ├── iamctl_color.md
│ │ │ │ ├── iamctl_completion.md
│ │ │ │ ├── iamctl_info.md
│ │ │ │ ├── iamctl_jwt.md
│ │ │ │ ├── iamctl_jwt_show.md
│ │ │ │ ├── iamctl_jwt_sign.md
│ │ │ │ ├── iamctl_jwt_verify.md
│ │ │ │ ├── iamctl_new.md
│ │ │ │ ├── iamctl_options.md
│ │ │ │ ├── iamctl_policy.md
│ │ │ │ ├── iamctl_policy_create.md
│ │ │ │ ├── iamctl_policy_delete.md
│ │ │ │ ├── iamctl_policy_get.md
│ │ │ │ ├── iamctl_policy_list.md
│ │ │ │ ├── iamctl_policy_update.md
│ │ │ │ ├── iamctl_secret.md
│ │ │ │ ├── iamctl_secret_create.md
│ │ │ │ ├── iamctl_secret_delete.md
│ │ │ │ ├── iamctl_secret_get.md
│ │ │ │ ├── iamctl_secret_list.md
│ │ │ │ ├── iamctl_secret_update.md
│ │ │ │ ├── iamctl_set.md
│ │ │ │ ├── iamctl_user.md
│ │ │ │ ├── iamctl_user_create.md
│ │ │ │ ├── iamctl_user_delete.md
│ │ │ │ ├── iamctl_user_get.md
│ │ │ │ ├── iamctl_user_list.md
│ │ │ │ ├── iamctl_user_update.md
│ │ │ │ ├── iamctl_validate.md
│ │ │ │ └── iamctl_version.md
│ │ └── yaml
│ │ │ └── iamctl
│ │ │ ├── iamctl.yaml
│ │ │ ├── iamctl_color.yaml
│ │ │ ├── iamctl_completion.yaml
│ │ │ ├── iamctl_info.yaml
│ │ │ ├── iamctl_jwt.yaml
│ │ │ ├── iamctl_new.yaml
│ │ │ ├── iamctl_options.yaml
│ │ │ ├── iamctl_policy.yaml
│ │ │ ├── iamctl_secret.yaml
│ │ │ ├── iamctl_set.yaml
│ │ │ ├── iamctl_user.yaml
│ │ │ ├── iamctl_validate.yaml
│ │ │ └── iamctl_version.yaml
│ └── zh-CN
│ │ ├── README.md
│ │ ├── api
│ │ ├── CHANGELOG.md
│ │ ├── README.md
│ │ ├── api_specification.md
│ │ ├── authentication.md
│ │ ├── code_specification.md
│ │ ├── error_code_generated.md
│ │ ├── generic.md
│ │ ├── policy.md
│ │ ├── secret.md
│ │ ├── struct.md
│ │ └── user.md
│ │ ├── best-practice
│ │ └── authorization.md
│ │ ├── catalog.md
│ │ ├── faq
│ │ ├── iam-apiserver
│ │ │ └── .keep
│ │ └── installation
│ │ │ └── .keep
│ │ ├── geekbang
│ │ ├── .keep
│ │ └── geekbang_course_catalog.md
│ │ ├── installation
│ │ ├── 01_Linux服务器配置.md
│ │ ├── 02_Go编译环境安装和配置.md
│ │ ├── 03_Go开发IDE安装和配置.md
│ │ ├── 04_下载IAM项目代码.md
│ │ ├── 05_安装和配置数据库.md
│ │ ├── 06_安装和配置IAM系统.md
│ │ ├── README.md
│ │ ├── architecture.md
│ │ ├── iam-apiserver-deployment.yaml
│ │ ├── iam-apiserver-service.yaml
│ │ ├── installation-architecture.md
│ │ ├── installation-docker.md
│ │ ├── installation-procedures.md
│ │ ├── installation-requirement.md
│ │ ├── installation.md
│ │ ├── procedures.md
│ │ ├── 创建CA根证书和秘钥.md
│ │ ├── 创建iam-apiserver证书和私钥.md
│ │ ├── 创建iam-authz-server证书和私钥.md
│ │ ├── 创建iamctl证书和私钥.md
│ │ └── 安装和配置IAM系统.md
│ │ ├── introduction
│ │ ├── .keep
│ │ └── go_package.md
│ │ ├── operation-guide
│ │ ├── policy.md
│ │ ├── secret.md
│ │ └── user.md
│ │ ├── quickstart
│ │ └── quickstart.md
│ │ ├── sdk
│ │ └── golang.md
│ │ └── version_map.md
├── images
│ ├── IAM架构.png
│ ├── iam-apiserver-man1.png
│ ├── iamctl_user_list.png
│ ├── iamtest运行结果.png
│ ├── three-code.png
│ ├── 技术思维导图.png
│ └── 部署架构v1.png
└── man
│ └── man1
│ ├── iam-apiserver.1
│ ├── iam-authz-server.1
│ ├── iam-pump.1
│ ├── iam-watcher.1
│ ├── iamctl-color.1
│ ├── iamctl-completion.1
│ ├── iamctl-info.1
│ ├── iamctl-jwt-show.1
│ ├── iamctl-jwt-sign.1
│ ├── iamctl-jwt-verify.1
│ ├── iamctl-jwt.1
│ ├── iamctl-new.1
│ ├── iamctl-options.1
│ ├── iamctl-policy-create.1
│ ├── iamctl-policy-delete.1
│ ├── iamctl-policy-get.1
│ ├── iamctl-policy-list.1
│ ├── iamctl-policy-update.1
│ ├── iamctl-policy.1
│ ├── iamctl-secret-create.1
│ ├── iamctl-secret-delete.1
│ ├── iamctl-secret-get.1
│ ├── iamctl-secret-list.1
│ ├── iamctl-secret-update.1
│ ├── iamctl-secret.1
│ ├── iamctl-set.1
│ ├── iamctl-user-create.1
│ ├── iamctl-user-delete.1
│ ├── iamctl-user-get.1
│ ├── iamctl-user-list.1
│ ├── iamctl-user-update.1
│ ├── iamctl-user.1
│ ├── iamctl-validate.1
│ ├── iamctl-version.1
│ └── iamctl.1
├── examples
├── code
│ └── main.go
└── error
│ └── main.go
├── githooks
├── commit-msg
└── pre-commit
├── go.mod
├── go.sum
├── go.work
├── go.work.sum
├── init
├── README.md
├── iam-apiserver.service
├── iam-authz-server.service
├── iam-pump.service
└── iam-watcher.service
├── internal
├── apiserver
│ ├── app.go
│ ├── auth.go
│ ├── config
│ │ ├── config.go
│ │ └── doc.go
│ ├── controller
│ │ └── v1
│ │ │ ├── cache
│ │ │ ├── cache.go
│ │ │ └── cache_test.go
│ │ │ ├── policy
│ │ │ ├── create.go
│ │ │ ├── delete.go
│ │ │ ├── delete_collection.go
│ │ │ ├── doc.go
│ │ │ ├── get.go
│ │ │ ├── list.go
│ │ │ ├── policy.go
│ │ │ └── update.go
│ │ │ ├── secret
│ │ │ ├── create.go
│ │ │ ├── delete.go
│ │ │ ├── delete_collection.go
│ │ │ ├── doc.go
│ │ │ ├── get.go
│ │ │ ├── list.go
│ │ │ ├── secret.go
│ │ │ └── update.go
│ │ │ └── user
│ │ │ ├── change_password.go
│ │ │ ├── change_password_test.go
│ │ │ ├── create.go
│ │ │ ├── create_test.go
│ │ │ ├── delete.go
│ │ │ ├── delete_collection.go
│ │ │ ├── delete_collection_test.go
│ │ │ ├── delete_test.go
│ │ │ ├── doc.go
│ │ │ ├── get.go
│ │ │ ├── get_test.go
│ │ │ ├── list.go
│ │ │ ├── list_test.go
│ │ │ ├── update.go
│ │ │ ├── update_test.go
│ │ │ ├── user.go
│ │ │ └── user_test.go
│ ├── grpc.go
│ ├── options
│ │ ├── options.go
│ │ └── validation.go
│ ├── router.go
│ ├── run.go
│ ├── server.go
│ ├── service
│ │ └── v1
│ │ │ ├── doc.go
│ │ │ ├── mock_service.go
│ │ │ ├── policy.go
│ │ │ ├── policy_test.go
│ │ │ ├── secret.go
│ │ │ ├── secret_test.go
│ │ │ ├── service.go
│ │ │ ├── service_test.go
│ │ │ ├── user.go
│ │ │ └── user_test.go
│ ├── store
│ │ ├── doc.go
│ │ ├── etcd
│ │ │ ├── doc.go
│ │ │ ├── etcd.go
│ │ │ ├── policy.go
│ │ │ ├── policy_audit.go
│ │ │ ├── secret.go
│ │ │ └── user.go
│ │ ├── fake
│ │ │ ├── doc.go
│ │ │ ├── fake.go
│ │ │ ├── policy.go
│ │ │ ├── policy_audit.go
│ │ │ ├── secret.go
│ │ │ └── user.go
│ │ ├── mock_store.go
│ │ ├── mysql
│ │ │ ├── doc.go
│ │ │ ├── mysql.go
│ │ │ ├── policy.go
│ │ │ ├── policy_audit.go
│ │ │ ├── secret.go
│ │ │ └── user.go
│ │ ├── policy.go
│ │ ├── policy_audit.go
│ │ ├── secret.go
│ │ ├── store.go
│ │ └── user.go
│ └── testing
│ │ └── .keep
├── authzserver
│ ├── analytics
│ │ ├── analytics.go
│ │ └── analytics_options.go
│ ├── app.go
│ ├── authorization
│ │ ├── authorizer.go
│ │ ├── authorizer
│ │ │ └── authorizer.go
│ │ ├── authorizer_test.go
│ │ ├── doc.go
│ │ ├── logger.go
│ │ ├── logger_test.go
│ │ ├── manager.go
│ │ ├── manager_test.go
│ │ ├── mock_authorization.go
│ │ └── types.go
│ ├── config
│ │ ├── config.go
│ │ └── doc.go
│ ├── controller
│ │ └── v1
│ │ │ └── authorize
│ │ │ └── authorize.go
│ ├── jwt.go
│ ├── load
│ │ ├── cache
│ │ │ └── cache.go
│ │ ├── doc.go
│ │ ├── load.go
│ │ └── redis_signals.go
│ ├── options
│ │ ├── options.go
│ │ └── validation.go
│ ├── router.go
│ ├── run.go
│ ├── server.go
│ ├── store
│ │ ├── apiserver
│ │ │ ├── apiserver.go
│ │ │ ├── doc.go
│ │ │ ├── policy.go
│ │ │ └── secret.go
│ │ ├── doc.go
│ │ ├── mock_store.go
│ │ ├── policy.go
│ │ ├── secret.go
│ │ └── store.go
│ └── testing
│ │ └── .keep
├── iamctl
│ ├── cmd
│ │ ├── cmd.go
│ │ ├── color
│ │ │ └── color.go
│ │ ├── completion
│ │ │ └── completion.go
│ │ ├── info
│ │ │ └── info.go
│ │ ├── jwt
│ │ │ ├── args.go
│ │ │ ├── jwt.go
│ │ │ ├── jwt_show.go
│ │ │ ├── jwt_sign.go
│ │ │ └── jwt_verify.go
│ │ ├── new
│ │ │ └── new.go
│ │ ├── options
│ │ │ └── options.go
│ │ ├── policy
│ │ │ ├── policy.go
│ │ │ ├── policy_create.go
│ │ │ ├── policy_delete.go
│ │ │ ├── policy_get.go
│ │ │ ├── policy_list.go
│ │ │ └── policy_update.go
│ │ ├── profiling.go
│ │ ├── secret
│ │ │ ├── secret.go
│ │ │ ├── secret_create.go
│ │ │ ├── secret_delete.go
│ │ │ ├── secret_get.go
│ │ │ ├── secret_list.go
│ │ │ └── secret_update.go
│ │ ├── set
│ │ │ ├── set.go
│ │ │ └── set_db.go
│ │ ├── user
│ │ │ ├── user.go
│ │ │ ├── user_create.go
│ │ │ ├── user_delete.go
│ │ │ ├── user_get.go
│ │ │ ├── user_list.go
│ │ │ └── user_update.go
│ │ ├── util
│ │ │ ├── factory.go
│ │ │ ├── factory_client_access.go
│ │ │ ├── helpers.go
│ │ │ └── iam_match_version.go
│ │ ├── validate
│ │ │ └── validate.go
│ │ └── version
│ │ │ └── version.go
│ ├── doc.go
│ ├── iamctl.go
│ └── util
│ │ ├── interrupt
│ │ └── interrupt.go
│ │ ├── templates
│ │ ├── command_groups.go
│ │ ├── markdown.go
│ │ ├── normalizers.go
│ │ ├── templater.go
│ │ └── templates.go
│ │ └── term
│ │ ├── resize.go
│ │ ├── term.go
│ │ ├── term_writer.go
│ │ └── term_writer_test.go
├── pkg
│ ├── README.md
│ ├── code
│ │ ├── apiserver.go
│ │ ├── authzserver.go
│ │ ├── base.go
│ │ ├── code.go
│ │ └── doc.go
│ ├── logger
│ │ ├── doc.go
│ │ ├── logger.go
│ │ ├── sql.go
│ │ └── sql_test.go
│ ├── middleware
│ │ ├── auth.go
│ │ ├── auth
│ │ │ ├── auto.go
│ │ │ ├── basic.go
│ │ │ ├── cache.go
│ │ │ ├── doc.go
│ │ │ └── jwt.go
│ │ ├── context.go
│ │ ├── cors.go
│ │ ├── doc.go
│ │ ├── limit.go
│ │ ├── logger.go
│ │ ├── middleware.go
│ │ ├── publish.go
│ │ ├── requestid.go
│ │ └── user_validation.go
│ ├── options
│ │ ├── authentication.go
│ │ ├── doc.go
│ │ ├── etcd_options.go
│ │ ├── feature.go
│ │ ├── grpc.go
│ │ ├── insecure_serving.go
│ │ ├── jwt.go
│ │ ├── mysql_options.go
│ │ ├── redis_options.go
│ │ ├── secure_serving.go
│ │ └── server_run_options.go
│ ├── server
│ │ ├── config.go
│ │ ├── doc.go
│ │ ├── genericapiserver.go
│ │ ├── health.go
│ │ ├── signal.go
│ │ └── signal_posix.go
│ ├── util
│ │ ├── gormutil
│ │ │ ├── doc.go
│ │ │ ├── gorm.go
│ │ │ └── gorm_test.go
│ │ └── reflect
│ │ │ ├── doc.go
│ │ │ ├── reflect.go
│ │ │ └── reflect_test.go
│ └── validation
│ │ ├── doc.go
│ │ └── validation.go
├── pump
│ ├── analytics
│ │ ├── analytics.go
│ │ ├── analytics_filters.go
│ │ ├── analytics_filters_test.go
│ │ └── analytics_options.go
│ ├── app.go
│ ├── config
│ │ ├── config.go
│ │ ├── config_test.go
│ │ └── doc.go
│ ├── options
│ │ ├── options.go
│ │ └── validation.go
│ ├── pumps
│ │ ├── common.go
│ │ ├── csv.go
│ │ ├── doc.go
│ │ ├── dummy.go
│ │ ├── elasticsearch.go
│ │ ├── influx.go
│ │ ├── init.go
│ │ ├── kafka.go
│ │ ├── mongo.go
│ │ ├── prometheus.go
│ │ ├── pump.go
│ │ ├── pump_test.go
│ │ └── syslog.go
│ ├── run.go
│ ├── server.go
│ ├── storage
│ │ ├── redis
│ │ │ ├── redis.go
│ │ │ └── redis_test.go
│ │ └── store.go
│ └── testing
│ │ └── .keep
└── watcher
│ ├── app.go
│ ├── config
│ ├── config.go
│ ├── config_test.go
│ └── doc.go
│ ├── options
│ ├── options.go
│ └── validation.go
│ ├── run.go
│ ├── server.go
│ ├── watcher.go
│ └── watcher
│ ├── all
│ └── all.go
│ ├── clean
│ └── watcher.go
│ ├── registry.go
│ └── task
│ └── watcher.go
├── pkg
├── app
│ ├── app.go
│ ├── cmd.go
│ ├── config.go
│ ├── doc.go
│ ├── flag.go
│ ├── help.go
│ └── options.go
├── cli
│ └── genericclioptions
│ │ ├── config_flags.go
│ │ ├── doc.go
│ │ └── io_options.go
├── db
│ ├── doc.go
│ ├── mysql.go
│ └── plugin.go
├── log
│ ├── LICENSE
│ ├── README.md
│ ├── context.go
│ ├── cronlog
│ │ ├── doc.go
│ │ └── log.go
│ ├── distribution
│ │ ├── doc.go
│ │ └── logger.go
│ ├── doc.go
│ ├── encoder.go
│ ├── example
│ │ ├── context
│ │ │ ├── doc.go
│ │ │ └── main.go
│ │ ├── doc.go
│ │ ├── example.go
│ │ ├── simple
│ │ │ ├── doc.go
│ │ │ └── simple.go
│ │ └── vlevel
│ │ │ ├── doc.go
│ │ │ └── v_level.go
│ ├── go.sum
│ ├── klog
│ │ ├── doc.go
│ │ └── logger.go
│ ├── log.go
│ ├── log_test.go
│ ├── logrus
│ │ ├── doc.go
│ │ ├── hook.go
│ │ └── logger.go
│ ├── options.go
│ ├── options_test.go
│ └── types.go
├── shutdown
│ ├── .travis.yml
│ ├── LICENCE
│ ├── README.md
│ ├── doc.go
│ ├── shutdown.go
│ ├── shutdown_test.go
│ └── shutdownmanagers
│ │ └── posixsignal
│ │ ├── doc.go
│ │ ├── posixsignal.go
│ │ └── posixsignal_test.go
├── storage
│ ├── doc.go
│ ├── redis_cluster.go
│ └── storage.go
├── util
│ ├── flag
│ │ ├── doc.go
│ │ └── flag.go
│ └── genutil
│ │ ├── doc.go
│ │ ├── genutil.go
│ │ └── genutil_test.go
└── validator
│ ├── doc.go
│ └── validator.go
├── scripts
├── admin.sh
├── boilerplate.txt
├── check_nginx.sh
├── common.sh
├── coverage.awk
├── coverage.sh
├── ensure_tag.sh
├── force_release.sh
├── gen_default_config.sh
├── gencerts.sh
├── genconfig.sh
├── gendoc.sh
├── install
│ ├── common.sh
│ ├── environment.sh
│ ├── iam-apiserver.sh
│ ├── iam-authz-server.sh
│ ├── iam-pump.sh
│ ├── iam-watcher.sh
│ ├── iamctl.sh
│ ├── install.sh
│ ├── man.sh
│ ├── mariadb.sh
│ ├── mariadb_for_ubuntu.sh
│ ├── mongodb.sh
│ ├── mongodb_for_ubuntu.sh
│ ├── redis.sh
│ ├── redis_for_ubuntu.sh
│ ├── release.sh
│ ├── test.sh
│ └── vimrc
├── keepalived_notify.sh
├── lib
│ ├── color.sh
│ ├── golang.sh
│ ├── init.sh
│ ├── logging.sh
│ ├── release.sh
│ ├── util.sh
│ └── version.sh
├── make-rules
│ ├── ca.mk
│ ├── common.mk
│ ├── copyright.mk
│ ├── dependencies.mk
│ ├── deploy.mk
│ ├── gen.mk
│ ├── golang.mk
│ ├── image.mk
│ ├── release.mk
│ ├── swagger.mk
│ └── tools.mk
├── print_enable_linters.sh
├── release.sh
├── release
│ └── .keep
├── templates
│ └── project_README.md
├── update-generated-docs.sh
├── update-kubernetes-spec.sh
├── wait-for-it.sh
└── wrktest.sh
├── test
├── README.md
├── jwt
│ └── main.go
├── nginx
│ └── loadbalance.sh
└── testdata
│ └── .keep
├── third_party
└── forked
│ └── murmur3
│ ├── .gitignore
│ ├── .travis.yml
│ ├── LICENSE
│ ├── README.md
│ ├── murmur.go
│ ├── murmur128.go
│ ├── murmur32.go
│ ├── murmur32_legacy.go
│ ├── murmur64.go
│ └── murmur_test.go
└── tools
├── README.md
├── codegen
└── codegen.go
├── geniptables
├── README.md
└── main.go
├── gentoken
└── main.go
└── httptest
└── main.go
/.chglog/CHANGELOG.tpl.md:
--------------------------------------------------------------------------------
1 | {{ range .Versions }}
2 |
3 | ## {{ if .Tag.Previous }}[{{ .Tag.Name }}]({{ $.Info.RepositoryURL }}/compare/{{ .Tag.Previous.Name }}...{{ .Tag.Name }}){{ else }}{{ .Tag.Name }}{{ end }} ({{ datetime "2006-01-02" .Tag.Date }})
4 |
5 | {{ range .CommitGroups -}}
6 | ### {{ .Title }}
7 |
8 | {{ range .Commits -}}
9 | * {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }}
10 | {{ end }}
11 | {{ end -}}
12 |
13 | {{- if .RevertCommits -}}
14 | ### Reverts
15 |
16 | {{ range .RevertCommits -}}
17 | * {{ .Revert.Header }}
18 | {{ end }}
19 | {{ end -}}
20 |
21 | {{- if .NoteGroups -}}
22 | {{ range .NoteGroups -}}
23 | ### {{ .Title }}
24 |
25 | {{ range .Notes }}
26 | {{ .Body }}
27 | {{ end }}
28 | {{ end -}}
29 | {{ end -}}
30 | {{ end -}}
--------------------------------------------------------------------------------
/.chglog/config.yml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | style: github
6 | template: CHANGELOG.tpl.md
7 | info:
8 | title: CHANGELOG
9 | repository_url: https://github.com/marmotedu/iam
10 | options:
11 | commits:
12 | filters:
13 | Type:
14 | - feat
15 | - fix
16 | - perf
17 | - refactor
18 | commit_groups:
19 | title_maps:
20 | feat: Features
21 | fix: Bug Fixes
22 | perf: Performance Improvements
23 | refactor: Code Refactoring
24 | header:
25 | pattern: "^(\\w*)(?:\\(([\\w\\$\\.\\-\\*\\s]*)\\))?\\:\\s(.*)$"
26 | pattern_maps:
27 | - Type
28 | - Scope
29 | - Subject
30 | notes:
31 | keywords:
32 | - BREAKING CHANGE
33 |
--------------------------------------------------------------------------------
/.github/workflows/golangci-lint.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | name: golangci-lint
6 | on:
7 | push:
8 | branchs:
9 | - '*'
10 | pull_request:
11 | types: [opened, reopened]
12 | jobs:
13 | golangci:
14 | name: lint
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/checkout@v2
18 | - name: golangci-lint
19 | uses: golangci/golangci-lint-action@v2
20 | with:
21 | # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
22 | version: v1.41.1
23 |
24 | # Optional: working directory, useful for monorepos
25 | # working-directory: somedir
26 |
27 | # Optional: golangci-lint command line arguments.
28 | # args: --issues-exit-code=0
29 |
30 | # Optional: show only new issues if it's a pull request. The default value is `false`.
31 | # only-new-issues: true
32 |
33 | # Optional: if set to true then the action will use pre-installed Go.
34 | # skip-go-installation: true
35 |
36 | # Optional: if set to true then the action don't cache or restore ~/go/pkg.
37 | # skip-pkg-cache: true
38 |
39 | # Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
40 | # skip-build-cache: true
41 |
--------------------------------------------------------------------------------
/.gitlint:
--------------------------------------------------------------------------------
1 | --subject-regex=^((Merge branch.*)|((revert: )?(feat|fix|perf|style|refactor|test|ci|docs|chore)(\(.+\))?: [^A-Z].*[^.]$))
2 | --subject-maxlen=80
3 | --body-regex=^([^\r\n]{0,80}(\r?\n|$))*$
4 |
--------------------------------------------------------------------------------
/.gsemver.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | majorPattern: "(?m)^BREAKING CHANGE:.*$"
6 | minorPattern: "^feat(?:\(.+\))?:.*"
7 | bumpStrategies:
8 | - branchesPattern: "^(master|release/.*)$"
9 | strategy: "AUTO"
10 | preRelease: false
11 | preReleaseTemplate:
12 | preReleaseOverwrite: false
13 | buildMetadataTemplate:
14 | - branchesPattern: ".*"
15 | strategy: "AUTO"
16 | preRelease: false
17 | preReleaseTemplate:
18 | preReleaseOverwrite: false
19 | buildMetadataTemplate: "{{Commits | len}}.{{(.Commits | first).Hash.Short}}"
20 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.1.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## v0.1.0 (2020-09-29)
4 |
5 | ### Features
6 |
7 | * init commit
8 |
9 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.1.1.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.1.1](https://github.com/marmotedu/iam/compare/v0.1.0...v0.1.1) (2020-10-06)
4 |
5 | ### Bug Fixes
6 |
7 | * **apiserver:** set check url to 127.0.0.1 when bind-address is 0.0.0.0
8 | * **apiserver:** fix compile error
9 |
10 | ### Code Refactoring
11 |
12 | * **apiserver:** remove middleware and add more header to cors
13 | * **apiserver:** change the position of fs := cmd.Flags()
14 | * **apiserver:** change to cobra functions which Run with error
15 |
16 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.1.2.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.1.2](https://github.com/marmotedu/iam/compare/v0.1.1...v0.1.2) (2020-10-10)
4 |
5 | ### Bug Fixes
6 |
7 | * **apiserver:** set check url to 127.0.0.1 when bind-address is 0.0.0.0
8 | * **apiserver:** fix compile error
9 |
10 | ### Code Refactoring
11 |
12 | * **apiserver:** remove middleware and add more header to cors
13 | * **apiserver:** change the position of fs := cmd.Flags()
14 | * **apiserver:** change to cobra functions which Run with error
15 | * **pkg:** remove default middlewares and rewrite wrktest.sh
16 |
17 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.2.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.2.0](https://github.com/marmotedu/iam/compare/v0.1.2...v0.2.0) (2020-10-21)
4 |
5 | ### Bug Fixes
6 |
7 | * **pkg:** panic when start HTTP/GRPC server failed
8 | * **pkg:** fix the wrong ping path
9 |
10 | ### Code Refactoring
11 |
12 | * **apiserver:** change gorm logger
13 | * **pkg:** add dump middleware
14 | * **pkg:** add custom logger middleware
15 |
16 | ### Features
17 |
18 | * **apiserver:** change gorm v1 to v2
19 |
20 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.3.1.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.3.1](https://github.com/marmotedu/iam/compare/v0.3.0...v0.3.1) (2020-12-18)
4 |
5 | ### Bug Fixes
6 |
7 | * fix compile error
8 |
9 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.4.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.4.0](https://github.com/marmotedu/iam/compare/v0.3.1...v0.4.0) (2021-02-04)
4 |
5 | ### Bug Fixes
6 |
7 | * fix default ConfigFlags
8 |
9 | ### Code Refactoring
10 |
11 | * optimize log output
12 | * iamctl code match marmotedu-sdk-go sdk changes
13 | * optimize variable name
14 | * change encoding/json to jsoniter
15 | * create mysql/etcd storage in singleton mode
16 | * fix golangci-lint error
17 | * change datastore.go to fake.go
18 | * remove short flag `s` in generated demo command
19 | * **authzserver:** refactor authzserver storage code
20 |
21 | ### Features
22 |
23 | * add --outdir option for iamctl new command
24 |
25 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.5.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.5.0](https://github.com/marmotedu/iam/compare/v0.4.0...v0.5.0) (2021-03-02)
4 |
5 | ### Bug Fixes
6 |
7 | * fix compile error
8 | * fix the wrong information link in command long description
9 | * **authzserver:** fix context bug, cancel context in Run function
10 |
11 | ### Code Refactoring
12 |
13 | * optimize variable name Store to store
14 | * change code architecture according to go clean arch
15 | * change the way to create mysql db instance
16 | * add missing doc.go and the generate file
17 | * add context.Context parameter to some functions
18 | * optimize log output
19 | * **authzserver:** optimize log output
20 | * **makefile:** change tools install method
21 |
22 | ### Features
23 |
24 | * support graceful shutdown
25 | * add graceful shutdown
26 | * **pump:** add graceful stop for pump
27 |
28 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.5.7-11-gb20f932.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/CHANGELOG/CHANGELOG-0.5.7-11-gb20f932.md
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.6.0-4-gb20f932.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/CHANGELOG/CHANGELOG-0.6.0-4-gb20f932.md
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.6.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.6.0](https://github.com/marmotedu/iam/compare/v0.5.6...v0.6.0) (2021-03-11)
4 |
5 | ### Bug Fixes
6 |
7 | * fix name bug, have Analytics struct and function at the same time
8 | * fix initialization sequence bug
9 |
10 | ### Code Refactoring
11 |
12 | * add code comment line
13 | * change struct name `RedisAnalyticsHandler` to `Analytics`
14 | * optimize RedisAnalyticsHandler struct field order
15 | * optimize code generated file name
16 |
17 | ### Features
18 |
19 | * switch components to use application framework
20 |
21 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.6.1.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.6.1](https://github.com/marmotedu/iam/compare/v0.6.0...v0.6.1) (2021-03-11)
4 |
5 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.7.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.7.0](https://github.com/marmotedu/iam/compare/v0.6.1...v0.7.0) (2021-04-08)
4 |
5 | ### Bug Fixes
6 |
7 | * fix the wrong data directory name
8 | * fix iamctl version wrong url bug
9 | * fix generate iamctl docs error
10 |
11 | ### Code Refactoring
12 |
13 | * also print username when sync secret from iam-apiserver
14 | * optimize the output of secret list
15 | * remove shorthand `c` to avoid conflict
16 |
17 | ### Features
18 |
19 | * add automatic installation scripts
20 | * optimize gencerts.sh to allow generate common ca files
21 |
22 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.7.1.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.7.1](https://github.com/marmotedu/iam/compare/v0.7.0...v0.7.1) (2021-04-08)
4 |
5 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-0.7.2.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v0.7.2](https://github.com/marmotedu/iam/compare/v0.7.1...v0.7.2) (2021-04-10)
4 |
5 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.0.1.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.0.1](https://github.com/marmotedu/iam/compare/v1.0.0...v1.0.1) (2021-07-08)
4 |
5 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.0.2.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.0.2](https://github.com/marmotedu/iam/compare/v1.0.1...v1.0.2) (2021-07-08)
4 |
5 | ### Bug Fixes
6 |
7 | * add missing `controller` directory
8 |
9 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.0.4.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.0.4](https://github.com/marmotedu/iam/compare/v1.0.3...v1.0.4) (2021-07-08)
4 |
5 | ### Code Refactoring
6 |
7 | * change Handler to Controller, remove store from Controller
8 | * **authzserver:** change api and handler to controller
9 |
10 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.1.0-4-ge259267.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/CHANGELOG/CHANGELOG-1.1.0-4-ge259267.md
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.1.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.1.0](https://github.com/marmotedu/iam/compare/v1.0.10...v1.1.0) (2021-11-06)
4 |
5 | ### Bug Fixes
6 |
7 | * **apiserver:** fix graceful shutdown redis bug
8 |
9 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.2.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.2.0](https://github.com/marmotedu/iam/compare/v1.1.0...v1.2.0) (2021-12-18)
4 |
5 | ### Bug Fixes
6 |
7 | * use the same key type for context
8 | * fix install script cannot clone expected version
9 | * not add global flagset if options is nil
10 | * fix no usage and help template set for cmd when app options is nil
11 | * **pump:** fix iam-pump exit where get no data from redis bug
12 | * **watcher:** add missing fields in user table
13 |
14 | ### Code Refactoring
15 |
16 | * improve code reuse
17 | * improve graceful shutdown for authzserver to reduce data loss
18 | * code about apiserver
19 | * only publish redis message when request is successful
20 | * optimize the code
21 | * change param type of `NewAutoStrategy` to AuthStrategy
22 | * optimize func name `addNamedCmdTemplate` to `addCmdTemplate`
23 | * optimize the code
24 | * optimize code
25 | * return `User already exist` instead of `Database error`
26 | * **authzserver:** retry when list policy and secret failed
27 |
28 | ### Features
29 |
30 | * add /etc/iam as the configuration file query path
31 | * add iam-watcher service to do periodic works
32 | * **pump:** add distributed lock for iam-pump
33 |
34 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.4.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.4.0](https://github.com/marmotedu/iam/compare/v1.2.0...v1.4.0) (2021-12-19)
4 |
5 | ### Code Refactoring
6 |
7 | * provide `ServeHealthCheck` in genericapiserver package
8 |
9 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.6.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.6.0](https://github.com/marmotedu/iam/compare/v1.4.0...v1.6.0) (2021-12-21)
4 |
5 | ### Bug Fixes
6 |
7 | * **apiserver:** do not authenticate when creating a user
8 |
9 | ### Code Refactoring
10 |
11 | * optimize code
12 | * support coscmd and coscli tool both
13 | * optimize func name from `runPumps` to `pump`
14 |
15 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.6.2.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.6.2](https://github.com/marmotedu/iam/compare/v1.6.0...v1.6.2) (2021-12-22)
4 |
5 |
--------------------------------------------------------------------------------
/CHANGELOG/CHANGELOG-1.7.0.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## [v1.7.0](https://github.com/marmotedu/iam/compare/v1.6.2...v1.7.0) (2022-06-16)
4 |
5 | ### Bug Fixes
6 |
7 | * fix iam-pump cannot analyze and move authorization log to mongodb
8 | * fix codegen failed with go1.18
9 | * fix wrktest.sh display bug
10 | * remove jsoniter compile tag
11 | * fix some compile bugs
12 | * remove gin warning message
13 | * remove duplicated key in yaml
14 | * grammar errors
15 | * **apiserver:** deal with column 'LoginedAt'
16 | * **apiserver:** fix secrets delete collection
17 |
18 | ### Code Refactoring
19 |
20 | * remove rollinglog package
21 |
22 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Welcome to Marmotedu! If you are interested in contributing to the [Marmotedu code repo](README.md) then checkout the [Contributor's Guide](https://github.com/marmotedu/community/blob/master/CONTRIBUTING.md)
4 |
5 | The [Marmotedu community repo](https://github.com/marmotedu/community) contains information on how the community is organized and other information that is pertinent to contributing.
6 |
--------------------------------------------------------------------------------
/OWNERS:
--------------------------------------------------------------------------------
1 | # See the OWNERS docs at https://go.k8s.io/owners
2 |
3 | reviewers:
4 | - colin404
5 | approvers:
6 | - colin404
7 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Reporting security issues
2 |
3 | The Marmotedu maintainers take security seriously. If you discover a security issue, please bring it to their attention right away!
4 |
5 | ## Reporting a Vulnerability
6 |
7 | Please **DO NOT** file a public issue, instead send your report privately to 466701708@qq.com.
8 |
9 | Security reports are greatly appreciated and we will publicly thank you for it, although we keep your name confidential if you request it. We currently do not offer a paid security bounty program, but are not ruling it out in the future.
10 |
--------------------------------------------------------------------------------
/api/openapi/README.md:
--------------------------------------------------------------------------------
1 | # `openapi`
2 |
3 | OpenAPI specs.
4 |
--------------------------------------------------------------------------------
/api/swagger/README.md:
--------------------------------------------------------------------------------
1 | # `swagger`
2 |
3 | Swagger specs.
4 |
--------------------------------------------------------------------------------
/api/swagger/docs/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package docs IAM API Server API.
6 | //
7 | // Identity and Access Management System.
8 | //
9 | // Schemes: http, https
10 | // Host: iam.api.marmotedu.com
11 | // BasePath: /v1
12 | // Version: 1.0.0
13 | // License: MIT https://opensource.org/licenses/MIT
14 | // Contact: Lingfei Kong http://marmotedu.com
15 | //
16 | // Consumes:
17 | // - application/json
18 | //
19 | // Produces:
20 | // - application/json
21 | //
22 | // Security:
23 | // - basic
24 | // - api_key
25 | //
26 | // SecurityDefinitions:
27 | // basic:
28 | // type: basic
29 | // api_key:
30 | // type: apiKey
31 | // name: Authorization
32 | // in: header
33 | //
34 | // swagger:meta
35 | package docs
36 |
--------------------------------------------------------------------------------
/build/ci/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/build/ci/.keep
--------------------------------------------------------------------------------
/build/docker/iam-apiserver/Dockerfile:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | FROM BASE_IMAGE
6 | LABEL maintainer=""
7 |
8 | WORKDIR /opt/iam
9 |
10 | RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
11 | echo "Asia/Shanghai" > /etc/timezone && \
12 | mkdir -p /var/log/iam
13 |
14 | COPY iam-apiserver /opt/iam/bin/
15 |
16 | ENTRYPOINT ["/opt/iam/bin/iam-apiserver"]
17 | CMD ["-c", "/etc/iam/iam-apiserver.yaml"]
18 |
--------------------------------------------------------------------------------
/build/docker/iam-authz-server/Dockerfile:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | FROM BASE_IMAGE
6 | LABEL maintainer=""
7 |
8 | WORKDIR /opt/iam
9 |
10 | RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
11 | echo "Asia/Shanghai" > /etc/timezone && \
12 | mkdir -p /var/log/iam
13 |
14 | COPY iam-authz-server /opt/iam/bin/
15 |
16 | ENTRYPOINT ["/opt/iam/bin/iam-authz-server"]
17 | CMD ["-c", "/etc/iam/iam-authz-server.yaml"]
18 |
--------------------------------------------------------------------------------
/build/docker/iam-pump/Dockerfile:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | FROM BASE_IMAGE
6 | LABEL maintainer=""
7 |
8 | WORKDIR /opt/iam
9 |
10 | RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
11 | echo "Asia/Shanghai" > /etc/timezone && \
12 | mkdir -p /var/log/iam
13 |
14 | COPY iam-pump /opt/iam/bin/
15 |
16 | ENTRYPOINT ["/opt/iam/bin/iam-pump"]
17 | CMD ["-c", "/etc/iam/iam-pump.yaml"]
18 |
--------------------------------------------------------------------------------
/build/docker/iam-watcher/Dockerfile:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | FROM BASE_IMAGE
6 | LABEL maintainer=""
7 |
8 | WORKDIR /opt/iam
9 |
10 | RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
11 | echo "Asia/Shanghai" > /etc/timezone && \
12 | mkdir -p /var/log/iam
13 |
14 | COPY iam-watcher /opt/iam/bin/
15 |
16 | ENTRYPOINT ["/opt/iam/bin/iam-watcher"]
17 | CMD ["-c", "/etc/iam/iam-watcher.yaml"]
18 |
--------------------------------------------------------------------------------
/build/docker/iamctl/Dockerfile:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | FROM BASE_IMAGE
6 | LABEL maintainer=""
7 |
8 | WORKDIR /opt/iam/scripts/install
9 |
10 | RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
11 | echo "Asia/Shanghai" > /etc/timezone
12 |
13 | COPY iamctl /usr/bin/
14 | COPY scripts /opt/iam/scripts
15 |
16 | ENTRYPOINT ["sleep", "3600"]
17 |
--------------------------------------------------------------------------------
/build/docker/iamctl/build.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 |
8 | mkdir -p "$DST_DIR/scripts/install"
9 |
10 | cp -rv scripts/lib "$DST_DIR/scripts/"
11 | cp -v scripts/install/{common.sh,environment.sh,test.sh} "$DST_DIR/scripts/install"
12 |
--------------------------------------------------------------------------------
/build/package/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/build/package/.keep
--------------------------------------------------------------------------------
/cmd/gendocs/gen_iamctl_docs.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "io/ioutil"
10 | "os"
11 |
12 | "github.com/spf13/cobra/doc"
13 |
14 | "github.com/marmotedu/iam/internal/iamctl/cmd"
15 | "github.com/marmotedu/iam/pkg/util/genutil"
16 | )
17 |
18 | func main() {
19 | // use os.Args instead of "flags" because "flags" will mess up the man pages!
20 | path := "docs/"
21 | if len(os.Args) == 2 {
22 | path = os.Args[1]
23 | } else if len(os.Args) > 2 {
24 | _, _ = fmt.Fprintf(os.Stderr, "usage: %s [output directory]\n", os.Args[0])
25 | os.Exit(1)
26 | }
27 |
28 | outDir, err := genutil.OutDir(path)
29 | if err != nil {
30 | _, _ = fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err)
31 | os.Exit(1)
32 | }
33 |
34 | // Set environment variables used by iamctl so the output is consistent,
35 | // regardless of where we run.
36 | _ = os.Setenv("HOME", "/home/username")
37 | // TODO os.Stdin should really be something like ioutil.Discard, but a Reader
38 | iamctl := cmd.NewIAMCtlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
39 | _ = doc.GenMarkdownTree(iamctl, outDir)
40 | }
41 |
--------------------------------------------------------------------------------
/cmd/geniamdocs/gen_iam_docs_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import "testing"
8 |
9 | func Test_main(t *testing.T) {
10 | tests := []struct {
11 | name string
12 | }{
13 | // TODO: Add test cases.
14 | }
15 | for _, tt := range tests {
16 | t.Run(tt.name, func(t *testing.T) {
17 | main()
18 | })
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/cmd/genswaggertypedocs/swagger_type_docs.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | //go:generate swagger generate spec -o ../../api/swagger/swagger.yaml --scan-models
8 |
9 | import (
10 | _ "github.com/marmotedu/iam/api/swagger/docs"
11 | )
12 |
13 | func main() {
14 | }
15 |
--------------------------------------------------------------------------------
/cmd/iam-apiserver/apiserver.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // apiserver is the api server for iam-apiserver service.
6 | // it is responsible for serving the platform RESTful resource management.
7 | package main
8 |
9 | import (
10 | "math/rand"
11 | "time"
12 |
13 | _ "go.uber.org/automaxprocs"
14 |
15 | _ "go.uber.org/automaxprocs"
16 |
17 | "github.com/marmotedu/iam/internal/apiserver"
18 | )
19 |
20 | func main() {
21 | rand.Seed(time.Now().UTC().UnixNano())
22 |
23 | apiserver.NewApp("iam-apiserver").Run()
24 | }
25 |
--------------------------------------------------------------------------------
/cmd/iam-authz-server/authzserver.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // authzserver is the server for iam-authz-server.
6 | // It is responsible for serving the ladon authorization request.
7 | package main
8 |
9 | import (
10 | "math/rand"
11 | "time"
12 |
13 | "github.com/marmotedu/iam/internal/authzserver"
14 | )
15 |
16 | func main() {
17 | rand.Seed(time.Now().UTC().UnixNano())
18 |
19 | authzserver.NewApp("iam-authz-server").Run()
20 | }
21 |
--------------------------------------------------------------------------------
/cmd/iam-pump/pump.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // pump is iam analytics purger that moves the data generated by your iam-authz-server nodes to any back-end.
6 | // It is primarily used to display your analytics data in the iam operating system.
7 | package main
8 |
9 | import (
10 | "math/rand"
11 | "time"
12 |
13 | _ "go.uber.org/automaxprocs"
14 |
15 | _ "go.uber.org/automaxprocs"
16 |
17 | "github.com/marmotedu/iam/internal/pump"
18 | )
19 |
20 | func main() {
21 | rand.Seed(time.Now().UTC().UnixNano())
22 |
23 | pump.NewApp("iam-pump").Run()
24 | }
25 |
--------------------------------------------------------------------------------
/cmd/iam-watcher/watcher.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // pump is iam analytics purger that moves the data generated by your iam-authz-server nodes to any back-end.
6 | // It is primarily used to display your analytics data in the iam operating system.
7 | package main
8 |
9 | import (
10 | "math/rand"
11 | "time"
12 |
13 | _ "go.uber.org/automaxprocs"
14 |
15 | _ "go.uber.org/automaxprocs"
16 |
17 | "github.com/marmotedu/iam/internal/watcher"
18 | )
19 |
20 | func main() {
21 | rand.Seed(time.Now().UTC().UnixNano())
22 |
23 | watcher.NewApp("iam-watcher").Run()
24 | }
25 |
--------------------------------------------------------------------------------
/cmd/iamctl/iamctl.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // iamctl is the command line tool for iam platform.
6 | package main
7 |
8 | import (
9 | "os"
10 |
11 | "github.com/marmotedu/iam/internal/iamctl/cmd"
12 | )
13 |
14 | func main() {
15 | command := cmd.NewDefaultIAMCtlCommand()
16 | if err := command.Execute(); err != nil {
17 | os.Exit(1)
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/configs/README.md:
--------------------------------------------------------------------------------
1 | # `configs`
2 |
3 | iam 组件配置模板:
4 |
5 | + iam-apiserver.yaml: iam-apiserver 配置文件
6 | + iam-authz-server.yaml: iam-authz-server 配置文件
7 | + config: marmotedu-sdk-go 和 iamctl 配置文件
8 |
9 | 一些配置项因为不需要被注释掉了,如有需要可自行打开。
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/configs/access.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | # 允许登录SSH节点的来源IP,可以是固定IP(例如10.0.4.2),也可以是个网段,0.0.0.0/0代表不限制来源IP
6 | ssh-source: 10.0.4.0/24
7 |
8 | # IAM应用节点列表(来源IP)
9 | hosts:
10 | - 10.0.4.20
11 | - 10.0.4.21
12 |
13 | # 来源IP可以访问的应用端口列表(iam-apiserver, iam-authz-server, iam-pump, iam-watcher对外暴露的的端口)
14 | ports:
15 | - 8080
16 | - 8443
17 | - 9090
18 | - 9443
19 | - 7070
20 | - 5050
21 |
22 | # 来源IP可以访问的数据库端口列表(Redis, MariaDB, MongoDB)
23 | dbports:
24 | - 3306
25 | - 6379
26 | - 27017
27 |
--------------------------------------------------------------------------------
/configs/ha/10.0.4.20/iam-apiserver.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 80;
3 | server_name iam.api.marmotedu.com;
4 | root /usr/share/nginx/html;
5 | location / {
6 | proxy_set_header X-Forwarded-Host $http_host;
7 | proxy_set_header X-Real-IP $remote_addr;
8 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
9 | proxy_pass http://iam.api.marmotedu.com/;
10 | client_max_body_size 5m;
11 | }
12 |
13 | error_page 404 /404.html;
14 | location = /40x.html {
15 | }
16 |
17 | error_page 500 502 503 504 /50x.html;
18 | location = /50x.html {
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/configs/ha/10.0.4.20/iam-authz-server.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 80;
3 | server_name iam.authz.marmotedu.com;
4 | root /usr/share/nginx/html;
5 | location / {
6 | proxy_set_header X-Forwarded-Host $http_host;
7 | proxy_set_header X-Real-IP $remote_addr;
8 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
9 | proxy_pass http://iam.authz.marmotedu.com/;
10 | client_max_body_size 5m;
11 | }
12 |
13 | error_page 404 /404.html;
14 | location = /40x.html {
15 | }
16 |
17 | error_page 500 502 503 504 /50x.html;
18 | location = /50x.html {
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/configs/ha/10.0.4.21/iam-apiserver.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 80;
3 | server_name iam.api.marmotedu.com;
4 | root /usr/share/nginx/html;
5 | location / {
6 | proxy_set_header X-Forwarded-Host $http_host;
7 | proxy_set_header X-Real-IP $remote_addr;
8 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
9 | proxy_pass http://iam.api.marmotedu.com/;
10 | client_max_body_size 5m;
11 | }
12 |
13 | error_page 404 /404.html;
14 | location = /40x.html {
15 | }
16 |
17 | error_page 500 502 503 504 /50x.html;
18 | location = /50x.html {
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/configs/ha/10.0.4.21/iam-authz-server.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 80;
3 | server_name iam.authz.marmotedu.com;
4 | root /usr/share/nginx/html;
5 | location / {
6 | proxy_set_header X-Forwarded-Host $http_host;
7 | proxy_set_header X-Real-IP $remote_addr;
8 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
9 | proxy_pass http://iam.authz.marmotedu.com/;
10 | client_max_body_size 5m;
11 | }
12 |
13 | error_page 404 /404.html;
14 | location = /40x.html {
15 | }
16 |
17 | error_page 500 502 503 504 /50x.html;
18 | location = /50x.html {
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/configs/iamctl.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | user:
7 | #token: # JWT Token
8 | username: ${CONFIG_USER_USERNAME} # iam 用户名
9 | password: ${CONFIG_USER_PASSWORD} # iam 密码
10 | #secret-id: # 密钥 ID
11 | #secret-key: # 密钥 Key
12 | client-certificate: ${CONFIG_USER_CLIENT_CERTIFICATE} # 用于 TLS 的客户端证书文件路径
13 | client-key: ${CONFIG_USER_CLIENT_KEY} # 用于 TLS 的客户端 key 文件路径
14 | #client-certificate-data:
15 | #client-key-data:
16 |
17 | server:
18 | address: https://${CONFIG_SERVER_ADDRESS} # iam api-server 地址
19 | timeout: 10s # 请求 api-server 超时时间
20 | #max-retries: # 最大重试次数,默认为 0
21 | #retry-interval: # 重试间隔,默认为 1s
22 | #tls-server-name: # TLS 服务器名称
23 | #insecure-skip-tls-verify: # 设置为 true 表示跳过 TLS 安全验证模式,将使得 HTTPS 连接不安全
24 | certificate-authority: ${CONFIG_SERVER_CERTIFICATE_AUTHORITY} # 用于 CA 授权的 cert 文件路径
25 | #certificate-authority-data:
26 |
--------------------------------------------------------------------------------
/deployments/iam-v1.6.2.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/deployments/iam-v1.6.2.tar.gz
--------------------------------------------------------------------------------
/deployments/iam/.helmignore:
--------------------------------------------------------------------------------
1 | # Patterns to ignore when building packages.
2 | # This supports shell glob matching, relative path matching, and
3 | # negation (prefixed with !). Only one pattern per line.
4 | .DS_Store
5 | # Common VCS dirs
6 | .git/
7 | .gitignore
8 | .bzr/
9 | .bzrignore
10 | .hg/
11 | .hgignore
12 | .svn/
13 | # Common backup files
14 | *.swp
15 | *.bak
16 | *.tmp
17 | *.orig
18 | *~
19 | # Various IDEs
20 | .project
21 | .idea/
22 | *.tmproj
23 | .vscode/
24 |
--------------------------------------------------------------------------------
/deployments/iam/Chart.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v2
6 | name: iam
7 | description: A Helm chart for iam
8 |
9 | # A chart can be either an 'application' or a 'library' chart.
10 | #
11 | # Application charts are a collection of templates that can be packaged into versioned archives
12 | # to be deployed.
13 | #
14 | # Library charts provide useful utilities or functions for the chart developer. They're included as
15 | # a dependency of application charts to inject those utilities and functions into the rendering
16 | # pipeline. Library charts do not define any templates and therefore cannot be deployed.
17 | type: application
18 |
19 | # This is the chart version. This version number should be incremented each time you make changes
20 | # to the chart and its templates, including the app version.
21 | # Versions are expected to follow Semantic Versioning (https://semver.org/)
22 | version: 0.1.0
23 |
24 | # This is the version number of the application being deployed. This version number should be
25 | # incremented each time you make changes to the application. Versions are not expected to
26 | # follow Semantic Versioning. They should reflect the version the application is using.
27 | # It is recommended to use it with quotes.
28 | appVersion: "0.1.0"
29 |
30 | icon: https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png
31 |
--------------------------------------------------------------------------------
/deployments/iam/service-with-nodeport/iam-apiserver-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.apiServer.name }}
10 | name: {{ .Values.apiServer.name }}
11 | spec:
12 | ports:
13 | - name: https
14 | protocol: TCP
15 | {{- toYaml .Values.apiServer.service.https| nindent 4 }}
16 | - name: http
17 | protocol: TCP
18 | {{- toYaml .Values.apiServer.service.http| nindent 4 }}
19 | - name: rpc
20 | protocol: TCP
21 | {{- toYaml .Values.apiServer.service.rpc| nindent 4 }}
22 | selector:
23 | app: {{ .Values.apiServer.name }}
24 | sessionAffinity: None
25 | type: NodePort
26 |
--------------------------------------------------------------------------------
/deployments/iam/service-with-nodeport/iam-authz-server-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.authzServer.name }}
10 | name: {{ .Values.authzServer.name }}
11 | spec:
12 | ports:
13 | - name: https
14 | protocol: TCP
15 | {{- toYaml .Values.authzServer.service.https| nindent 4 }}
16 | - name: http
17 | protocol: TCP
18 | {{- toYaml .Values.authzServer.service.http| nindent 4 }}
19 | selector:
20 | app: {{ .Values.authzServer.name }}
21 | sessionAffinity: None
22 | type: NodePort
23 |
--------------------------------------------------------------------------------
/deployments/iam/service-with-nodeport/iam-pump-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.pump.name }}
10 | name: {{ .Values.pump.name }}
11 | spec:
12 | ports:
13 | - name: http
14 | protocol: TCP
15 | {{- toYaml .Values.pump.service.http| nindent 4 }}
16 | selector:
17 | app: {{ .Values.pump.name }}
18 | sessionAffinity: None
19 | type: NodePort
20 |
--------------------------------------------------------------------------------
/deployments/iam/service-with-nodeport/iam-watcher-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.watcher.name }}
10 | name: {{ .Values.watcher.name }}
11 | spec:
12 | ports:
13 | - name: http
14 | protocol: TCP
15 | {{- toYaml .Values.watcher.service.http| nindent 4 }}
16 | selector:
17 | app: {{ .Values.watcher.name }}
18 | sessionAffinity: None
19 | type: NodePort
20 |
--------------------------------------------------------------------------------
/deployments/iam/templates/hpa.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | {{- if .Values.autoscaling.enabled }}
6 | apiVersion: autoscaling/v2beta1
7 | kind: HorizontalPodAutoscaler
8 | metadata:
9 | name: {{ include "iam.fullname" . }}
10 | labels:
11 | {{- include "iam.labels" . | nindent 4 }}
12 | spec:
13 | scaleTargetRef:
14 | apiVersion: apps/v1
15 | kind: Deployment
16 | name: {{ include "iam.fullname" . }}
17 | minReplicas: {{ .Values.autoscaling.minReplicas }}
18 | maxReplicas: {{ .Values.autoscaling.maxReplicas }}
19 | metrics:
20 | {{- if .Values.autoscaling.targetCPUUtilizationPercentage }}
21 | - type: Resource
22 | resource:
23 | name: cpu
24 | targetAverageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
25 | {{- end }}
26 | {{- if .Values.autoscaling.targetMemoryUtilizationPercentage }}
27 | - type: Resource
28 | resource:
29 | name: memory
30 | targetAverageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }}
31 | {{- end }}
32 | {{- end }}
33 |
--------------------------------------------------------------------------------
/deployments/iam/templates/iam-apiserver-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.apiServer.name }}
10 | name: {{ .Values.apiServer.name }}
11 | spec:
12 | ports:
13 | - name: https
14 | protocol: TCP
15 | {{- toYaml .Values.apiServer.service.https| nindent 4 }}
16 | - name: http
17 | protocol: TCP
18 | {{- toYaml .Values.apiServer.service.http| nindent 4 }}
19 | - name: rpc
20 | protocol: TCP
21 | {{- toYaml .Values.apiServer.service.rpc| nindent 4 }}
22 | selector:
23 | app: {{ .Values.apiServer.name }}
24 | sessionAffinity: None
25 | type: {{ .Values.serviceType }}
26 |
--------------------------------------------------------------------------------
/deployments/iam/templates/iam-authz-server-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.authzServer.name }}
10 | name: {{ .Values.authzServer.name }}
11 | spec:
12 | ports:
13 | - name: https
14 | protocol: TCP
15 | {{- toYaml .Values.authzServer.service.https| nindent 4 }}
16 | - name: http
17 | protocol: TCP
18 | {{- toYaml .Values.authzServer.service.http| nindent 4 }}
19 | selector:
20 | app: {{ .Values.authzServer.name }}
21 | sessionAffinity: None
22 | type: {{ .Values.serviceType }}
23 |
--------------------------------------------------------------------------------
/deployments/iam/templates/iam-pump-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.pump.name }}
10 | name: {{ .Values.pump.name }}
11 | spec:
12 | ports:
13 | - name: http
14 | protocol: TCP
15 | {{- toYaml .Values.pump.service.http| nindent 4 }}
16 | selector:
17 | app: {{ .Values.pump.name }}
18 | sessionAffinity: None
19 | type: {{ .Values.serviceType }}
20 |
--------------------------------------------------------------------------------
/deployments/iam/templates/iam-watcher-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: {{ .Values.watcher.name }}
10 | name: {{ .Values.watcher.name }}
11 | spec:
12 | ports:
13 | - name: http
14 | protocol: TCP
15 | {{- toYaml .Values.watcher.service.http| nindent 4 }}
16 | selector:
17 | app: {{ .Values.watcher.name }}
18 | sessionAffinity: None
19 | type: {{ .Values.serviceType }}
20 |
--------------------------------------------------------------------------------
/deployments/templates/iam-apiserver-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: iam-apiserver
10 | name: iam-apiserver
11 | spec:
12 | ports:
13 | - name: https
14 | protocol: TCP
15 | port: 8443
16 | targetPort: 8443
17 | - name: http
18 | protocol: TCP
19 | port: 8080
20 | targetPort: 8080
21 | - name: rpc
22 | protocol: TCP
23 | port: 8081
24 | targetPort: 8081
25 | selector:
26 | app: iam-apiserver
27 | sessionAffinity: None
28 | type: ClusterIP
29 |
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # AUTH Documentation
2 |
3 | - [Quick Start](quickstart.md) - Read me first!
4 | - [Source Structure](source-structure.md) - TenC source structure
5 | - [Architecture](architecture.md) - Overview of the Helm/Tiller design
6 | - [Project Introduction](project.md) - Project Introduction
7 | - [TenC RESTful Resources](resources.md) - TenC RESTful resources
8 | - [Related Projects](related.md) - Releated projects
9 | - [Contributing](contributing/hacking.md) - About how to contribute to this project
10 | - [History](history.md) - A brief history of the project
11 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/architecture.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/devel/zh-CN/architecture.md
--------------------------------------------------------------------------------
/docs/devel/zh-CN/components.md:
--------------------------------------------------------------------------------
1 | # IAM Components
2 |
3 | `/cmd` directory includes every IAM components and is where all binaries and container images are built. For detail about how to launch the IAM cluster see the guide [here](/docs/devel/running-locally.md).
4 |
5 | ## Overview
6 |
7 | IAM contains 12 core components belonging to 6 services, a dependency list generator and a customized installer.
8 |
9 | ## Core Components
10 | To bootstrap properly, IAM core components need to be run in the order as shown below.
11 |
12 | - [`iam-apiserver`](/cmd/iam-apiserver) integrates [dex](https://github.com/dexidp/dex) to provide an OpenID Connect server, which can provide access to third-party authentication systems, and also provides a default local identify.
13 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/development.md:
--------------------------------------------------------------------------------
1 | ## 代码贡献流程
2 |
3 | IAM 项目采用 Github Forking 工作流:[IAM 项目代码贡献流程](./forking.md)
4 |
5 | ## 开发规范
6 |
7 | 需要通过静态代码检查工具;golangci-lint & gometalinter
8 |
9 | ## 部署
10 |
11 | ## 测试
12 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/requirements.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/devel/zh-CN/requirements.md
--------------------------------------------------------------------------------
/docs/devel/zh-CN/scope.md:
--------------------------------------------------------------------------------
1 | ## IAM commit message scope
2 |
3 | | scope | description |
4 | | ----------- | -------------------------------------- |
5 | | apiserver | iam-apiserver 组件相关的变更 |
6 | | authzserver | iam-auth-server 组件相关的变更 |
7 | | pump | iam-pump 组件相关的变更 |
8 | | iamctl | iamctl 组件相关的变更 |
9 | | user | iam-apiserver 中 user 模块相关的变更 |
10 | | policy | iam-apiserver 中 policy 模块相关的变更 |
11 | | secret | iam-apiserver 中 secret 模块相关的变更 |
12 | | pkg | pkg 包的变更 |
13 | | docs | 文档类变更 |
14 | | changelog | CHANGELOG 的变更 |
15 | | makefile | Makefile 文件的变更 |
16 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/tools/commitizen-go.md:
--------------------------------------------------------------------------------
1 | # commitizen-go 使用
2 |
3 | ## 安装
4 |
5 |
6 | ## 使用指南
7 |
8 |
9 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/tools/commitsar.md:
--------------------------------------------------------------------------------
1 | # commitsar使用指南
2 |
3 | ## commitsar安装
4 |
5 | ```bash
6 | go get github.com/aevea/commitsar
7 | ```
8 |
9 | ## commitsar使用
10 |
11 | ### commitsar配置
12 |
13 | ### 运行
14 |
15 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/tools/go-gitlint.md:
--------------------------------------------------------------------------------
1 | # go-gitlint 使用指南
2 |
3 | ## 安装
4 |
5 | ```bash
6 | $ go get github.com/marmotedu/go-gitlint/cmd/go-gitlint
7 | ```
8 |
9 | ## 配置
10 |
11 | ### githook: commit-msg配置
12 |
13 | ```bash
14 | # commit-msg use go-gitlint tool, install go-gitlint via `go get github.com/llorllale/go-gitlint/cmd/go-gitlint`
15 | go-gitlint --msg-file="$1"
16 | ```
17 |
18 | ### .gitlint配置
19 |
20 | ```bash
21 | --subject-regex=^(revert: )?(feat|fix|perf|style|refactor|test|ci|docs|chore)(\(.+\))?: [^A-Z]*[^.]$
22 | --subject-maxlen=72
23 | --body-regex=.*
24 | --body-maxlen=72
25 | ```
26 |
27 | ## 运行
28 |
29 | ```bash
30 | $ cd ${IAM_ROOT}
31 | $ go-gitlint
32 | ```
33 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/tools/gommit.md:
--------------------------------------------------------------------------------
1 | # gommit 使用指南
2 |
3 |
4 | ## 安装
5 |
6 | ```bash
7 |
8 | ```
9 |
--------------------------------------------------------------------------------
/docs/devel/zh-CN/tools/mysqldump.md:
--------------------------------------------------------------------------------
1 | # mysqldump命令使用指南
2 |
3 | 参数:
4 |
5 | - `--no-data`: 只导出表结构不导出数据
6 | - `--routines`: 导出存储过程和自定义函数
7 |
8 | ## 1. 导出所有数据库
9 |
10 | ```bash
11 | mysqldump -uroot -proot --databases iam > /tmp/iam.sql
12 | ```
13 |
14 | ## 2. 导出iam数据库的所有数据
15 |
16 | ```bash
17 | mysqldump -uroot -proot --databases iam > /tmp/iam.sql
18 | ```
19 |
20 | ## 3. 导出初始化iam数据库的sql语句
21 |
22 | ```bash
23 | mysqldump -hxxx.xx.xx.xxx -uiam --databases iam -p'iam59!z$' iam --add-drop-database --add-drop-table --add-drop-trigger --add-locks --no-data > /tmp/iam.sql
24 | ```
25 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/README.md:
--------------------------------------------------------------------------------
1 | # IAM 使用手册
2 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/api/api_specification.md:
--------------------------------------------------------------------------------
1 | # IAM 系统接口文档规范
2 |
3 | 接口文档拆分为以下几个 Markdown 文件,并存放在目录 `docs/guide/zh-CN/api` 中:
4 | - [README.md](./README.md):API 接口介绍文档,会分类介绍 IAM 支持的 API 接口,并会存放相关 API 接口文档的链接,方便开发者查看。
5 | - [CHANGELOG.md](./CHANGELOG.md):API 接口文档变更历史,方便进行历史回溯,也可以使调用者决定是否进行功能更新和版本更新。
6 | - [generic.md](./generic.md):通用说明,用来说明通用的请求参数、返回参数、认证方法和请求方法等。
7 | - [struct.md](./struct.md):数据结构,用来列出接口文档中使用的数据结构。这些数据结构可能被多个 API 接口使用,会在 user.md、secret.md、policy.md 文件中被引用。
8 | - [user.md](./user.md)、[secret.md](./secret.md)、[policy.md](./policy.md):API接口文档,相同 REST 资源的接口会存放在一个文件中,以 REST 资源名命名文档名。
9 | - [error_code_generated.md](./error_code_generated.md):错误码描述,通过程序自动生成。
10 |
11 | `user.md` 文件记录了用户相关的接口,每个接口按顺序排列包含如下 5 部分:
12 | - 接口描述:描述接口实现了什么功能。
13 | - 请求方法:接口的请求方法,格式为:`HTTP方法 请求路径`,例如 `POST /v1/users`。在 **通用说明** 中的 **请求方法**部分,会说明接口的请求协议和请求地址。
14 | - 输入参数:接口的输入字段,又分为:Header 参数、Query 参数、Body 参数、Path 参数。每个字段通过:**参数名称**、**必选**、**类型** 和 **描述** 4 个属性来描述。如果参数有限制或者默认值,可以在描述部分注明。
15 | - 输出参数:接口的返回字段,每个字段通过 **参数名称**、**类型** 和 **描述** 3 个属性来描述。
16 | - 请求示例:一个真实的 API 接口请求和返回示例。
17 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/best-practice/authorization.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/best-practice/authorization.md
--------------------------------------------------------------------------------
/docs/guide/zh-CN/faq/iam-apiserver/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/faq/iam-apiserver/.keep
--------------------------------------------------------------------------------
/docs/guide/zh-CN/faq/installation/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/faq/installation/.keep
--------------------------------------------------------------------------------
/docs/guide/zh-CN/geekbang/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/geekbang/.keep
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/03_Go开发IDE安装和配置.md:
--------------------------------------------------------------------------------
1 | # 3. Go 开发 IDE 安装和配置
2 |
3 | 编译环境准备完之后,你还需要一个代码编辑器才能开始 Go 项目开发。为了提高开发效率,你还需要将这个编辑器配置成 Go IDE。
4 | 目前,GoLand、VSCode 这些 IDE 都很优秀,但它们都是 Windows 系统下的 IDE。在 Linux 系统下我们可以选择将 Vim 配置成 Go IDE。熟练 Vim IDE 操作之后,开发效率不输 GoLand 和 VSCode。有多种方法可以配置一个Vim IDE,这里我选择使用 vim-go 将 Vim 配置成一个 Go IDE。vim-go 是社区比较受欢迎的 Vim Go 开发插件,可以用来方便的将一个 Vim 配置成 Vim IDE。
5 | Vim IDE 的安装和配置分为以下两步。
6 |
7 | 1) 安装 vim-go
8 |
9 | 安装命令如下:
10 |
11 | ```bash
12 | $ rm -f $HOME/.vim; mkdir -p ~/.vim/pack/plugins/start/
13 | $ git clone --depth=1 https://github.com/fatih/vim-go.git ~/.vim/pack/plugins/start/vim-go
14 | ```
15 |
16 | 2) Go 工具安装
17 |
18 | vim-go 会用到一些 Go 工具,比如在函数跳转时会用到 `guru`、`godef` 工具,在格式化时会用到 `goimports`,所以你也需要安装这些工具。安装方式如下:
19 | 执行 `vi /tmp/test.go`,然后输入 `:GoInstallBinaries` 安装 vim-go 需要的工具。
20 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/04_下载IAM项目代码.md:
--------------------------------------------------------------------------------
1 | # 4. 下载 IAM 项目代码
2 |
3 | 因为 IAM 的安装脚本存放在 iam 代码仓库中,安装需要的二进制文件也需要通过编译iam 源码来获得,所以在安装之前,你需要先下载 iam 源码:
4 |
5 | ```bash
6 | $ mkdir -p $WORKSPACE/golang/src/github.com/marmotedu
7 | $ cd $WORKSPACE/golang/src/github.com/marmotedu
8 | $ git clone --depth=1 https://github.com/marmotedu/iam
9 | $ go work use ./iam
10 | ```
11 |
12 | 其中,`marmotedu` 和 `marmotedu/iam` 目录存放了本实战项目的代码。在学习的过程中,你需要频繁的访问这 2 个目录,为了方便访问,你可以追加以下 2 个环境变量和 2 个 alias 到`$HOME/.bashrc`文件中:
13 |
14 | ```bash
15 | # Alias for quick access
16 | export GOSRC="$WORKSPACE/golang/src"
17 | export IAM_ROOT="$GOSRC/github.com/marmotedu/iam"
18 | alias mm="cd $GOSRC/github.com/marmotedu"
19 | alias i="cd $GOSRC/github.com/marmotedu/iam"
20 | EOF
21 | $ bash
22 | ```
23 |
24 | 之后,你就可以先通过执行 alias 命令 `mm` 访问 `$GOWORK/github.com/marmotedu` 目录;通过执行 alias 命令 `i` 访问 `$GOWORK/github.com/marmotedu/iam` 目录。我也建议你将常用操作配置成 alias,方便以后操作。
25 |
26 | 在安装配置IAM系统之前需要你执行以下命令export `going` 用户的密码,这里假设密码是 `iam59!z$`:
27 |
28 | ```bash
29 | export LINUX_PASSWORD='iam59!z$'
30 | ```
31 |
32 | 在项目开发中,像密码、密钥 Key 这类敏感信息,一般不会直接硬编码在系统中,而是通过环境变量的方式来使用。现网应用的配置文件是存放在一个安全的网络环境中,并且有访问授权流程,比较安全,这种配置文件中是可以配置密码等敏感信息的。
33 |
34 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/architecture.md:
--------------------------------------------------------------------------------
1 | # 部署架构
2 |
3 | ## 总体架构
4 |
5 | 
6 |
7 | > `iam-pump` 和 `mongo` 2 个组件正在开发中
8 |
9 | ## 架构说明
10 |
11 | 架构为了能够尽可能的用到常用的 golang 开发知识点,采用了 RESTful 和 grpc 2 种通信协议,采用了 SQL 和 NoSQL 数据库,同时大量借鉴了 `kubernetes` 和 `tkestack/tke` 优秀的设计理念。
12 |
13 |
14 | ## 模块说明
15 |
16 | - **iam-apiserver:** iam 核心组件,用来进行用户、密钥和授权策略管理
17 | - **iam-authz-server:** 授权服务器,从 **iam-apiserver** 拉取密钥和授权策略,根据匹配的策略进行授权
18 | - **iamctl:** iam 系统的客户端,类似于 `kubectl`,通过 `marmotedu-sdk-go` 访问 `iam-apiserver`
19 | - **marmotedu-sdk-go:** iam 系统的 golang sdk,类似于 `client-go`
20 | - **redis:** redis 缓存, 用来存储授权审计信息,供 `iam-pump` 后期进行数据分析
21 | - **mysql:** 持久性存储用户、密钥和授权策略
22 | - **iam-pump:** 从 redis 里面拉取授权审计数据,分析后存入 mongo
23 | - **mongo:** 授权审计数据,供后期运营展示和分析
24 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/iam-apiserver-service.yaml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | apiVersion: v1
6 | kind: Service
7 | metadata:
8 | labels:
9 | app: iam-apiserver
10 | name: iam-apiserver
11 | namespace: default
12 | spec:
13 | clusterIP: 192.168.0.231 # 虚拟服务地址
14 | externalTrafficPolicy: Cluster # 表示此服务是否希望将外部流量路由到节点本地或集群范围的端点
15 | ports: # service需要暴露的端口列表
16 | - name: https #端口名称
17 | nodePort: 30443 # 当type = NodePort时,指定映射到物理机的端口号
18 | port: 8443 # 服务监听的端口号
19 | protocol: TCP # 端口协议,支持TCP和UDP,默认TCP
20 | targetPort: 8443 # 需要转发到后端Pod的端口号
21 | selector: # label selector配置,将选择具有label标签的Pod作为其后端RS
22 | app: iam-apiserver
23 | sessionAffinity: None # 是否支持session
24 | type: NodePort # service的类型,指定service的访问方式,默认为clusterIp
25 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/installation-docker.md:
--------------------------------------------------------------------------------
1 | # 安装Docker
2 |
3 | 安装命令如下:
4 |
5 | ```bash
6 | $ curl -fsSL https://get.docker.com | bash -s docker --mirror aliyun
7 | ``
8 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/installation-procedures.md:
--------------------------------------------------------------------------------
1 | # 手把手教你部署 IAM 系统
2 |
3 | 详细安装分为如下 **6** 步:
4 |
5 | 1. [Linux 服务器基本配置](./01_Linux服务器配置.md)
6 | 2. [Go 编译环境安装和配置](./02_Go编译环境安装和配置.md)
7 | 3. [Go 开发 IDE 安装和配置](./03_Go开发IDE安装和配置.md)
8 | 4. [下载 IAM 项目代码](./04_下载IAM项目代码.md)
9 | 5. [安装和配置数据库](./05_安装和配置数据库.md)
10 | 6. [安装和配置 IAM 系统](./06_安装和配置IAM系统.md)
11 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/installation-requirement.md:
--------------------------------------------------------------------------------
1 | # 部署环境要求
2 |
3 | 1. 服务器能访问外网
4 |
5 | 2. 操作系统:CentOS Linux 8.x (64-bit)
6 |
7 | > 本安装脚本基于 CentOS 8.2 安装,建议你选择 CentOS 8.x 系统。其它Linux发行版、macOS也能安装,不过需要手动安装。
8 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/installation.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/installation/installation.md
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/procedures.md:
--------------------------------------------------------------------------------
1 | # 安装步骤
2 |
3 | [部署架构](./architecture.md)
4 |
5 | ## 1. 需求检查 & 依赖安装
6 |
7 | 请参考:[需求检查](./requirement.md)
8 |
9 | ## 2. 代码包下载
10 |
11 | ```bash
12 | git clone https://github.com/marmotedu/iam
13 | ```
14 |
15 | ## 3. 编译
16 |
17 | ```bash
18 | cd iam
19 | make
20 | ```
21 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/创建iam-apiserver证书和私钥.md:
--------------------------------------------------------------------------------
1 | # 创建iam-apiserver证书和私钥
2 |
3 | ## 创建 iam-apiserver 证书和私钥
4 |
5 | 创建证书签名请求:
6 |
7 | ``` bash
8 | $ cd $HOME/marmotedu/work
9 | $ source $HOME/marmotedu/work/environment.sh
10 | $ cat > iam-csr.json <>> ${node_ip}"
54 | ssh root@${node_ip} "mkdir -p /etc/iam/cert"
55 | scp iam-apiserverf*.pem root@${node_ip}:/etc/iam/cert/
56 | done
57 | ```
58 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/installation/创建iam-authz-server证书和私钥.md:
--------------------------------------------------------------------------------
1 | # 创建 iam-authz-server 证书和私钥
2 |
3 | 创建证书签名请求:
4 |
5 | ``` bash
6 | $ cd $HOME/marmotedu/work
7 | $ cat > iam-authz-server-csr.json <>> ${node_ip}"
52 | scp iam-authz-server*.pem root@${node_ip}:/etc/kubernetes/cert/
53 | done
54 | ```
55 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/introduction/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/introduction/.keep
--------------------------------------------------------------------------------
/docs/guide/zh-CN/introduction/go_package.md:
--------------------------------------------------------------------------------
1 | # IAM 项目推荐使用的 Go 包
2 | - 参数校验:github.com/asaskevich/govalidator
3 |
--------------------------------------------------------------------------------
/docs/guide/zh-CN/operation-guide/policy.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/operation-guide/policy.md
--------------------------------------------------------------------------------
/docs/guide/zh-CN/operation-guide/secret.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/operation-guide/secret.md
--------------------------------------------------------------------------------
/docs/guide/zh-CN/operation-guide/user.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/operation-guide/user.md
--------------------------------------------------------------------------------
/docs/guide/zh-CN/quickstart/quickstart.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/quickstart/quickstart.md
--------------------------------------------------------------------------------
/docs/guide/zh-CN/sdk/golang.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/guide/zh-CN/sdk/golang.md
--------------------------------------------------------------------------------
/docs/guide/zh-CN/version_map.md:
--------------------------------------------------------------------------------
1 | # 版本映射
2 |
3 | 为了方便对照代码学习,这里整理了一份版本映射供你参考。在学习的时候注意参照对应版本的代码看,否则可能会出现专栏/书中的代码跟所看代码(可能拿的是master分支的代码)不一致的情况。
4 |
5 | ## 极客时间《Go 语言项目开发实战》
6 |
7 | | 组件 | 版本(Tag) |
8 | | ---------------- | --------- |
9 | | component-base | v1.0.1 |
10 | | api | v1.0.2 |
11 | | marmotedu-sdk-go | v1.0.3 |
12 | | medu-sdk-go | v1.0.0 |
13 | | iam | v1.1.0 |
14 | | log | v0.0.1 |
15 | | errors | v1.0.2 |
16 | | gopractise-demo | v1.0.0 |
17 | | sample-code | v1.0.0 |
18 |
19 | ## 《从零构建企业级 Go 项目》
20 |
21 | | 组件 | 版本(Tag) |
22 | | ---------------- | --------- |
23 | | component-base | v1.6.2 |
24 | | api | v1.6.2 |
25 | | marmotedu-sdk-go | v1.6.2 |
26 | | medu-sdk-go | v1.6.2 |
27 | | iam | v1.6.2 |
28 | | log | v0.0.1 |
29 | | errors | v1.0.2 |
30 | | gopractise-demo | v1.0.0 |
31 | | sample-code | v1.0.0 |
32 |
--------------------------------------------------------------------------------
/docs/images/IAM架构.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/images/IAM架构.png
--------------------------------------------------------------------------------
/docs/images/iam-apiserver-man1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/images/iam-apiserver-man1.png
--------------------------------------------------------------------------------
/docs/images/iamctl_user_list.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/images/iamctl_user_list.png
--------------------------------------------------------------------------------
/docs/images/iamtest运行结果.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/images/iamtest运行结果.png
--------------------------------------------------------------------------------
/docs/images/three-code.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/images/three-code.png
--------------------------------------------------------------------------------
/docs/images/技术思维导图.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/images/技术思维导图.png
--------------------------------------------------------------------------------
/docs/images/部署架构v1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/docs/images/部署架构v1.png
--------------------------------------------------------------------------------
/examples/code/main.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Usage:
6 | // go run main.go
7 | // curl http://127.0.0.1:7070/user/foo
8 |
9 | package main
10 |
11 | import (
12 | "github.com/gin-gonic/gin"
13 | "github.com/marmotedu/component-base/pkg/core"
14 | "github.com/marmotedu/errors"
15 |
16 | "github.com/marmotedu/iam/internal/pkg/code"
17 | )
18 |
19 | func main() {
20 | r := gin.Default()
21 |
22 | r.GET("/user/:name", func(c *gin.Context) {
23 | name := c.Params.ByName("name")
24 | if err := getUser(name); err != nil {
25 | core.WriteResponse(c, err, nil)
26 | return
27 | }
28 |
29 | core.WriteResponse(c, nil, map[string]string{"email": name + "@foxmail.com"})
30 | })
31 |
32 | r.Run(":7070")
33 | }
34 |
35 | func getUser(name string) error {
36 | if err := queryDatabase(name); err != nil {
37 | return errors.Wrap(err, "get user failed.")
38 | }
39 |
40 | return nil
41 | }
42 |
43 | func queryDatabase(name string) error {
44 | return errors.WithCode(code.ErrDatabase, "user '%s' not found.", name)
45 | }
46 |
--------------------------------------------------------------------------------
/githooks/commit-msg:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # Store this file as .git/hooks/commit-msg in your repository in order to
8 | # enforce checking for proper commit message format before actual commits. You
9 | # may need to make the script executable by 'chmod +x .git/hooks/commit-msg'.
10 |
11 | # commit-msg use go-gitlint tool, install go-gitlint via `go get github.com/llorllale/go-gitlint/cmd/go-gitlint`
12 | go-gitlint --msg-file="$1"
13 |
--------------------------------------------------------------------------------
/githooks/pre-commit:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | LC_ALL=C
3 |
4 | local_branch="$(git rev-parse --abbrev-ref HEAD)"
5 |
6 | valid_branch_regex="^(master|develop)$|(feature|release|hotfix)\/[a-z0-9._-]+$|^HEAD$"
7 |
8 | message="There is something wrong with your branch name. Branch names in this project must adhere to this contract: $valid_branch_regex.
9 | Your commit will be rejected. You should rename your branch to a valid name and try again."
10 |
11 | if [[ ! $local_branch =~ $valid_branch_regex ]]
12 | then
13 | echo "$message"
14 | exit 1
15 | fi
16 |
17 | exit 0
18 |
--------------------------------------------------------------------------------
/go.work:
--------------------------------------------------------------------------------
1 | go 1.21.4
2 |
3 | use .
4 |
--------------------------------------------------------------------------------
/go.work.sum:
--------------------------------------------------------------------------------
1 | github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
2 | github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7 h1:u9SHYsPQNyt5tgDm3YN7+9dYrpK96E5wFilTFWIDZOM=
3 | github.com/golang-jwt/jwt v3.2.1+incompatible h1:73Z+4BJcrTC+KczS6WvTPvRGOp1WmfEP4Q1lOd9Z/+c=
4 | github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
5 | go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738 h1:VcrIfasaLFkyjk6KNlXQSzO+B0fZcnECiDrKJsfxka0=
6 |
--------------------------------------------------------------------------------
/init/iam-apiserver.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=IAM APIServer
3 | Documentation=https://github.com/marmotedu/iam/blob/master/init/README.md
4 |
5 | [Service]
6 | WorkingDirectory=${IAM_DATA_DIR}/iam-apiserver
7 | ExecStartPre=/usr/bin/mkdir -p ${IAM_DATA_DIR}/iam-apiserver
8 | ExecStartPre=/usr/bin/mkdir -p ${IAM_LOG_DIR}
9 | ExecStart=${IAM_INSTALL_DIR}/bin/iam-apiserver --config=${IAM_CONFIG_DIR}/iam-apiserver.yaml
10 | Restart=always
11 | RestartSec=5
12 | StartLimitInterval=0
13 |
14 | [Install]
15 | WantedBy=multi-user.target
16 |
--------------------------------------------------------------------------------
/init/iam-authz-server.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=IAM AuthzServer
3 | Documentation=https://github.com/marmotedu/iam/blob/master/init/README.md
4 |
5 | [Service]
6 | WorkingDirectory=${IAM_DATA_DIR}/iam-authz-server
7 | ExecStartPre=/usr/bin/mkdir -p ${IAM_DATA_DIR}/iam-authz-server
8 | ExecStartPre=/usr/bin/mkdir -p ${IAM_LOG_DIR}
9 | ExecStart=${IAM_INSTALL_DIR}/bin/iam-authz-server --config=${IAM_CONFIG_DIR}/iam-authz-server.yaml
10 | Restart=always
11 | RestartSec=5
12 | StartLimitInterval=0
13 |
14 | [Install]
15 | WantedBy=multi-user.target
16 |
--------------------------------------------------------------------------------
/init/iam-pump.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=IAM Pump Server
3 | Documentation=https://github.com/marmotedu/iam/blob/master/init/README.md
4 |
5 | [Service]
6 | WorkingDirectory=${IAM_DATA_DIR}/iam-pump
7 | ExecStartPre=/usr/bin/mkdir -p ${IAM_DATA_DIR}/iam-pump
8 | ExecStartPre=/usr/bin/mkdir -p ${IAM_LOG_DIR}
9 | ExecStart=${IAM_INSTALL_DIR}/bin/iam-pump --config=${IAM_CONFIG_DIR}/iam-pump.yaml
10 | Restart=always
11 | RestartSec=5
12 | StartLimitInterval=0
13 |
14 | [Install]
15 | WantedBy=multi-user.target
16 |
--------------------------------------------------------------------------------
/init/iam-watcher.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=IAM Watcher Server
3 | Documentation=https://github.com/marmotedu/iam/blob/master/init/README.md
4 |
5 | [Service]
6 | WorkingDirectory=${IAM_DATA_DIR}/iam-watcher
7 | ExecStartPre=/usr/bin/mkdir -p ${IAM_DATA_DIR}/iam-watcher
8 | ExecStartPre=/usr/bin/mkdir -p ${IAM_LOG_DIR}
9 | ExecStart=${IAM_INSTALL_DIR}/bin/iam-watcher --config=${IAM_CONFIG_DIR}/iam-watcher.yaml
10 | Restart=always
11 | RestartSec=5
12 | StartLimitInterval=0
13 |
14 | [Install]
15 | WantedBy=multi-user.target
16 |
--------------------------------------------------------------------------------
/internal/apiserver/config/config.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package config
6 |
7 | import "github.com/marmotedu/iam/internal/apiserver/options"
8 |
9 | // Config is the running configuration structure of the IAM pump service.
10 | type Config struct {
11 | *options.Options
12 | }
13 |
14 | // CreateConfigFromOptions creates a running configuration instance based
15 | // on a given IAM pump command line or configuration file option.
16 | func CreateConfigFromOptions(opts *options.Options) (*Config, error) {
17 | return &Config{opts}, nil
18 | }
19 |
--------------------------------------------------------------------------------
/internal/apiserver/config/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package config defines configuration for iam-apiserver.
6 | package config
7 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/policy/create.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package policy
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | v1 "github.com/marmotedu/api/apiserver/v1"
10 | "github.com/marmotedu/component-base/pkg/core"
11 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
12 | "github.com/marmotedu/errors"
13 |
14 | "github.com/marmotedu/iam/internal/pkg/code"
15 | "github.com/marmotedu/iam/internal/pkg/middleware"
16 | "github.com/marmotedu/iam/pkg/log"
17 | )
18 |
19 | // Create creates a new ladon policy.
20 | // It will convert the policy to string and store it in the storage.
21 | func (p *PolicyController) Create(c *gin.Context) {
22 | log.L(c).Info("create policy function called.")
23 |
24 | var r v1.Policy
25 | if err := c.ShouldBindJSON(&r); err != nil {
26 | core.WriteResponse(c, errors.WithCode(code.ErrBind, err.Error()), nil)
27 |
28 | return
29 | }
30 |
31 | if errs := r.Validate(); len(errs) != 0 {
32 | core.WriteResponse(c, errors.WithCode(code.ErrValidation, errs.ToAggregate().Error()), nil)
33 |
34 | return
35 | }
36 |
37 | r.Username = c.GetString(middleware.UsernameKey)
38 |
39 | if err := p.srv.Policies().Create(c, &r, metav1.CreateOptions{}); err != nil {
40 | core.WriteResponse(c, err, nil)
41 |
42 | return
43 | }
44 |
45 | core.WriteResponse(c, nil, r)
46 | }
47 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/policy/delete.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package policy
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/internal/pkg/middleware"
13 | "github.com/marmotedu/iam/pkg/log"
14 | )
15 |
16 | // Delete deletes the policy by the policy identifier.
17 | func (p *PolicyController) Delete(c *gin.Context) {
18 | log.L(c).Info("delete policy function called.")
19 |
20 | if err := p.srv.Policies().Delete(c, c.GetString(middleware.UsernameKey), c.Param("name"),
21 | metav1.DeleteOptions{}); err != nil {
22 | core.WriteResponse(c, err, nil)
23 |
24 | return
25 | }
26 |
27 | core.WriteResponse(c, nil, nil)
28 | }
29 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/policy/delete_collection.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package policy
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/internal/pkg/middleware"
13 | "github.com/marmotedu/iam/pkg/log"
14 | )
15 |
16 | // DeleteCollection delete policies by policy names.
17 | func (p *PolicyController) DeleteCollection(c *gin.Context) {
18 | log.L(c).Info("batch delete policy function called.")
19 |
20 | if err := p.srv.Policies().DeleteCollection(c, c.GetString(middleware.UsernameKey),
21 | c.QueryArray("name"), metav1.DeleteOptions{}); err != nil {
22 | core.WriteResponse(c, err, nil)
23 |
24 | return
25 | }
26 |
27 | core.WriteResponse(c, nil, nil)
28 | }
29 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/policy/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package policy implements the policy handlers.
6 | package policy
7 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/policy/get.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package policy
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/internal/pkg/middleware"
13 | "github.com/marmotedu/iam/pkg/log"
14 | )
15 |
16 | // Get return policy by the policy identifier.
17 | func (p *PolicyController) Get(c *gin.Context) {
18 | log.L(c).Info("get policy function called.")
19 |
20 | pol, err := p.srv.Policies().Get(c, c.GetString(middleware.UsernameKey), c.Param("name"), metav1.GetOptions{})
21 | if err != nil {
22 | core.WriteResponse(c, err, nil)
23 |
24 | return
25 | }
26 |
27 | core.WriteResponse(c, nil, pol)
28 | }
29 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/policy/list.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package policy
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 | "github.com/marmotedu/errors"
12 |
13 | "github.com/marmotedu/iam/internal/pkg/code"
14 | "github.com/marmotedu/iam/internal/pkg/middleware"
15 | "github.com/marmotedu/iam/pkg/log"
16 | )
17 |
18 | // List return all policies.
19 | func (p *PolicyController) List(c *gin.Context) {
20 | log.L(c).Info("list policy function called.")
21 |
22 | var r metav1.ListOptions
23 | if err := c.ShouldBindQuery(&r); err != nil {
24 | core.WriteResponse(c, errors.WithCode(code.ErrBind, err.Error()), nil)
25 |
26 | return
27 | }
28 |
29 | policies, err := p.srv.Policies().List(c, c.GetString(middleware.UsernameKey), r)
30 | if err != nil {
31 | core.WriteResponse(c, err, nil)
32 |
33 | return
34 | }
35 |
36 | core.WriteResponse(c, nil, policies)
37 | }
38 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/policy/policy.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package policy
6 |
7 | import (
8 | srvv1 "github.com/marmotedu/iam/internal/apiserver/service/v1"
9 | "github.com/marmotedu/iam/internal/apiserver/store"
10 | )
11 |
12 | // PolicyController create a policy handler used to handle request for policy resource.
13 | type PolicyController struct {
14 | srv srvv1.Service
15 | }
16 |
17 | // NewPolicyController creates a policy handler.
18 | func NewPolicyController(store store.Factory) *PolicyController {
19 | return &PolicyController{
20 | srv: srvv1.NewService(store),
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/secret/delete.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package secret
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/internal/pkg/middleware"
13 | "github.com/marmotedu/iam/pkg/log"
14 | )
15 |
16 | // Delete delete a secret by the secret identifier.
17 | func (s *SecretController) Delete(c *gin.Context) {
18 | log.L(c).Info("delete secret function called.")
19 | opts := metav1.DeleteOptions{Unscoped: true}
20 | if err := s.srv.Secrets().Delete(c, c.GetString(middleware.UsernameKey), c.Param("name"), opts); err != nil {
21 | core.WriteResponse(c, err, nil)
22 |
23 | return
24 | }
25 |
26 | core.WriteResponse(c, nil, nil)
27 | }
28 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/secret/delete_collection.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package secret
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/internal/pkg/middleware"
13 | "github.com/marmotedu/iam/pkg/log"
14 | )
15 |
16 | // DeleteCollection delete secrets by secret names.
17 | func (s *SecretController) DeleteCollection(c *gin.Context) {
18 | log.L(c).Info("batch delete policy function called.")
19 |
20 | if err := s.srv.Secrets().DeleteCollection(
21 | c,
22 | c.GetString(middleware.UsernameKey),
23 | c.QueryArray("name"),
24 | metav1.DeleteOptions{},
25 | ); err != nil {
26 | core.WriteResponse(c, err, nil)
27 |
28 | return
29 | }
30 |
31 | core.WriteResponse(c, nil, nil)
32 | }
33 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/secret/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package secret implements the secret handlers.
6 | package secret
7 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/secret/get.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package secret
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/internal/pkg/middleware"
13 | "github.com/marmotedu/iam/pkg/log"
14 | )
15 |
16 | // Get get an policy by the secret identifier.
17 | func (s *SecretController) Get(c *gin.Context) {
18 | log.L(c).Info("get secret function called.")
19 |
20 | secret, err := s.srv.Secrets().Get(c, c.GetString(middleware.UsernameKey), c.Param("name"), metav1.GetOptions{})
21 | if err != nil {
22 | core.WriteResponse(c, err, nil)
23 |
24 | return
25 | }
26 |
27 | core.WriteResponse(c, nil, secret)
28 | }
29 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/secret/list.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package secret
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 | "github.com/marmotedu/errors"
12 |
13 | "github.com/marmotedu/iam/internal/pkg/code"
14 | "github.com/marmotedu/iam/internal/pkg/middleware"
15 | "github.com/marmotedu/iam/pkg/log"
16 | )
17 |
18 | // List list all the secrets.
19 | func (s *SecretController) List(c *gin.Context) {
20 | log.L(c).Info("list secret function called.")
21 | var r metav1.ListOptions
22 | if err := c.ShouldBindQuery(&r); err != nil {
23 | core.WriteResponse(c, errors.WithCode(code.ErrBind, err.Error()), nil)
24 |
25 | return
26 | }
27 |
28 | secrets, err := s.srv.Secrets().List(c, c.GetString(middleware.UsernameKey), r)
29 | if err != nil {
30 | core.WriteResponse(c, err, nil)
31 |
32 | return
33 | }
34 |
35 | core.WriteResponse(c, nil, secrets)
36 | }
37 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/secret/secret.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package secret
6 |
7 | import (
8 | srvv1 "github.com/marmotedu/iam/internal/apiserver/service/v1"
9 | "github.com/marmotedu/iam/internal/apiserver/store"
10 | )
11 |
12 | // SecretController create a secret handler used to handle request for secret resource.
13 | type SecretController struct {
14 | srv srvv1.Service
15 | }
16 |
17 | // NewSecretController creates a secret handler.
18 | func NewSecretController(store store.Factory) *SecretController {
19 | return &SecretController{
20 | srv: srvv1.NewService(store),
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/create.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package user
6 |
7 | import (
8 | "time"
9 |
10 | "github.com/gin-gonic/gin"
11 | v1 "github.com/marmotedu/api/apiserver/v1"
12 | "github.com/marmotedu/component-base/pkg/auth"
13 | "github.com/marmotedu/component-base/pkg/core"
14 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
15 | "github.com/marmotedu/errors"
16 |
17 | "github.com/marmotedu/iam/internal/pkg/code"
18 | "github.com/marmotedu/iam/pkg/log"
19 | )
20 |
21 | // Create add new user to the storage.
22 | func (u *UserController) Create(c *gin.Context) {
23 | log.L(c).Info("user create function called.")
24 |
25 | var r v1.User
26 |
27 | if err := c.ShouldBindJSON(&r); err != nil {
28 | core.WriteResponse(c, errors.WithCode(code.ErrBind, err.Error()), nil)
29 |
30 | return
31 | }
32 |
33 | if errs := r.Validate(); len(errs) != 0 {
34 | core.WriteResponse(c, errors.WithCode(code.ErrValidation, errs.ToAggregate().Error()), nil)
35 |
36 | return
37 | }
38 |
39 | r.Password, _ = auth.Encrypt(r.Password)
40 | r.Status = 1
41 | r.LoginedAt = time.Now()
42 |
43 | // Insert the user to the storage.
44 | if err := u.srv.Users().Create(c, &r, metav1.CreateOptions{}); err != nil {
45 | core.WriteResponse(c, err, nil)
46 |
47 | return
48 | }
49 |
50 | core.WriteResponse(c, nil, r)
51 | }
52 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/delete.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package user
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/pkg/log"
13 | )
14 |
15 | // Delete delete an user by the user identifier.
16 | // Only administrator can call this function.
17 | func (u *UserController) Delete(c *gin.Context) {
18 | log.L(c).Info("delete user function called.")
19 |
20 | if err := u.srv.Users().Delete(c, c.Param("name"), metav1.DeleteOptions{Unscoped: true}); err != nil {
21 | core.WriteResponse(c, err, nil)
22 |
23 | return
24 | }
25 |
26 | core.WriteResponse(c, nil, nil)
27 | }
28 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/delete_collection.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package user
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/pkg/log"
13 | )
14 |
15 | // DeleteCollection batch delete users by multiple usernames.
16 | // Only administrator can call this function.
17 | func (u *UserController) DeleteCollection(c *gin.Context) {
18 | log.L(c).Info("batch delete user function called.")
19 |
20 | usernames := c.QueryArray("name")
21 |
22 | if err := u.srv.Users().DeleteCollection(c, usernames, metav1.DeleteOptions{}); err != nil {
23 | core.WriteResponse(c, err, nil)
24 |
25 | return
26 | }
27 |
28 | core.WriteResponse(c, nil, nil)
29 | }
30 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package user implements the user handler.
6 | package user
7 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/get.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package user
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 |
12 | "github.com/marmotedu/iam/pkg/log"
13 | )
14 |
15 | // Get get an user by the user identifier.
16 | func (u *UserController) Get(c *gin.Context) {
17 | log.L(c).Info("get user function called.")
18 |
19 | user, err := u.srv.Users().Get(c, c.Param("name"), metav1.GetOptions{})
20 | if err != nil {
21 | core.WriteResponse(c, err, nil)
22 |
23 | return
24 | }
25 |
26 | core.WriteResponse(c, nil, user)
27 | }
28 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/list.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package user
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
11 | "github.com/marmotedu/errors"
12 |
13 | "github.com/marmotedu/iam/internal/pkg/code"
14 | "github.com/marmotedu/iam/pkg/log"
15 | )
16 |
17 | // List list the users in the storage.
18 | // Only administrator can call this function.
19 | func (u *UserController) List(c *gin.Context) {
20 | log.L(c).Info("list user function called.")
21 |
22 | var r metav1.ListOptions
23 | if err := c.ShouldBindQuery(&r); err != nil {
24 | core.WriteResponse(c, errors.WithCode(code.ErrBind, err.Error()), nil)
25 |
26 | return
27 | }
28 |
29 | users, err := u.srv.Users().List(c, r)
30 | if err != nil {
31 | core.WriteResponse(c, err, nil)
32 |
33 | return
34 | }
35 |
36 | core.WriteResponse(c, nil, users)
37 | }
38 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/user.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package user
6 |
7 | import (
8 | srvv1 "github.com/marmotedu/iam/internal/apiserver/service/v1"
9 | "github.com/marmotedu/iam/internal/apiserver/store"
10 | )
11 |
12 | // UserController create a user handler used to handle request for user resource.
13 | type UserController struct {
14 | srv srvv1.Service
15 | }
16 |
17 | // NewUserController creates a user handler.
18 | func NewUserController(store store.Factory) *UserController {
19 | return &UserController{
20 | srv: srvv1.NewService(store),
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/controller/v1/user/user_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package user
6 |
7 | import (
8 | "reflect"
9 | "testing"
10 |
11 | "github.com/golang/mock/gomock"
12 |
13 | srvv1 "github.com/marmotedu/iam/internal/apiserver/service/v1"
14 | "github.com/marmotedu/iam/internal/apiserver/store"
15 | )
16 |
17 | func TestNewUserController(t *testing.T) {
18 | ctrl := gomock.NewController(t)
19 | defer ctrl.Finish()
20 |
21 | mockFactory := store.NewMockFactory(ctrl)
22 |
23 | type args struct {
24 | store store.Factory
25 | }
26 | tests := []struct {
27 | name string
28 | args args
29 | want *UserController
30 | }{
31 | {
32 | name: "default",
33 | args: args{
34 | store: mockFactory,
35 | },
36 | want: &UserController{
37 | srv: srvv1.NewService(mockFactory),
38 | },
39 | },
40 | }
41 | for _, tt := range tests {
42 | t.Run(tt.name, func(t *testing.T) {
43 | if got := NewUserController(tt.args.store); !reflect.DeepEqual(got, tt.want) {
44 | t.Errorf("NewUserController() = %v, want %v", got, tt.want)
45 | }
46 | })
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/internal/apiserver/grpc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package apiserver
6 |
7 | import (
8 | "net"
9 |
10 | "google.golang.org/grpc"
11 |
12 | "github.com/marmotedu/iam/pkg/log"
13 | )
14 |
15 | type grpcAPIServer struct {
16 | *grpc.Server
17 | address string
18 | }
19 |
20 | func (s *grpcAPIServer) Run() {
21 | listen, err := net.Listen("tcp", s.address)
22 | if err != nil {
23 | log.Fatalf("failed to listen: %s", err.Error())
24 | }
25 |
26 | go func() {
27 | if err := s.Serve(listen); err != nil {
28 | log.Fatalf("failed to start grpc server: %s", err.Error())
29 | }
30 | }()
31 |
32 | log.Infof("start grpc server at %s", s.address)
33 | }
34 |
35 | func (s *grpcAPIServer) Close() {
36 | s.GracefulStop()
37 | log.Infof("GRPC server on %s stopped", s.address)
38 | }
39 |
--------------------------------------------------------------------------------
/internal/apiserver/options/validation.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package options
6 |
7 | // Validate checks Options and return a slice of found errs.
8 | func (o *Options) Validate() []error {
9 | var errs []error
10 |
11 | errs = append(errs, o.GenericServerRunOptions.Validate()...)
12 | errs = append(errs, o.GRPCOptions.Validate()...)
13 | errs = append(errs, o.InsecureServing.Validate()...)
14 | errs = append(errs, o.SecureServing.Validate()...)
15 | errs = append(errs, o.MySQLOptions.Validate()...)
16 | errs = append(errs, o.RedisOptions.Validate()...)
17 | errs = append(errs, o.JwtOptions.Validate()...)
18 | errs = append(errs, o.Log.Validate()...)
19 | errs = append(errs, o.FeatureOptions.Validate()...)
20 |
21 | return errs
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/run.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package apiserver
6 |
7 | import "github.com/marmotedu/iam/internal/apiserver/config"
8 |
9 | // Run runs the specified APIServer. This should never exit.
10 | func Run(cfg *config.Config) error {
11 | server, err := createAPIServer(cfg)
12 | if err != nil {
13 | return err
14 | }
15 |
16 | return server.PrepareRun().Run()
17 | }
18 |
--------------------------------------------------------------------------------
/internal/apiserver/service/v1/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package v1 is the place where you can implements more complex business logic.
6 | package v1 // import "github.com/marmotedu/iam/internal/apiserver/service/v1"
7 |
--------------------------------------------------------------------------------
/internal/apiserver/service/v1/service.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package v1
6 |
7 | //go:generate mockgen -self_package=github.com/marmotedu/iam/internal/apiserver/service/v1 -destination mock_service.go -package v1 github.com/marmotedu/iam/internal/apiserver/service/v1 Service,UserSrv,SecretSrv,PolicySrv
8 |
9 | import "github.com/marmotedu/iam/internal/apiserver/store"
10 |
11 | // Service defines functions used to return resource interface.
12 | type Service interface {
13 | Users() UserSrv
14 | Secrets() SecretSrv
15 | Policies() PolicySrv
16 | }
17 |
18 | type service struct {
19 | store store.Factory
20 | }
21 |
22 | // NewService returns Service interface.
23 | func NewService(store store.Factory) Service {
24 | return &service{
25 | store: store,
26 | }
27 | }
28 |
29 | func (s *service) Users() UserSrv {
30 | return newUsers(s)
31 | }
32 |
33 | func (s *service) Secrets() SecretSrv {
34 | return newSecrets(s)
35 | }
36 |
37 | func (s *service) Policies() PolicySrv {
38 | return newPolicies(s)
39 | }
40 |
--------------------------------------------------------------------------------
/internal/apiserver/store/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package store defines the storage interface for iam-apiserver.
6 | package store
7 |
--------------------------------------------------------------------------------
/internal/apiserver/store/etcd/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package etcd implements `github.com/marmotedu/iam/internal/apiserver/store.Store` interface.
6 | package etcd
7 |
--------------------------------------------------------------------------------
/internal/apiserver/store/etcd/policy_audit.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package etcd
6 |
7 | import (
8 | "context"
9 | )
10 |
11 | type policyAudit struct {
12 | ds *datastore
13 | }
14 |
15 | func newPolicyAudits(ds *datastore) *policyAudit {
16 | return &policyAudit{ds}
17 | }
18 |
19 | // ClearOutdated clear data older than a given days.
20 | func (p *policyAudit) ClearOutdated(ctx context.Context, maxReserveDays int) (int64, error) {
21 | return 0, nil
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/store/fake/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package fake implements `github.com/marmotedu/iam/internal/apiserver/store.Store` interface.
6 | package fake
7 |
--------------------------------------------------------------------------------
/internal/apiserver/store/fake/policy_audit.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package fake
6 |
7 | import (
8 | "context"
9 | )
10 |
11 | type policyAudit struct {
12 | ds *datastore
13 | }
14 |
15 | func newPolicyAudits(ds *datastore) *policyAudit {
16 | return &policyAudit{ds}
17 | }
18 |
19 | // ClearOutdated clear data older than a given days.
20 | func (p *policyAudit) ClearOutdated(ctx context.Context, maxReserveDays int) (int64, error) {
21 | return 0, nil
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/store/mysql/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package mysql implements `github.com/marmotedu/iam/internal/apiserver/store.Store` interface.
6 | package mysql
7 |
--------------------------------------------------------------------------------
/internal/apiserver/store/mysql/policy_audit.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package mysql
6 |
7 | import (
8 | "context"
9 | "time"
10 |
11 | "gorm.io/gorm"
12 | )
13 |
14 | type policyAudit struct {
15 | db *gorm.DB
16 | }
17 |
18 | func newPolicyAudits(ds *datastore) *policyAudit {
19 | return &policyAudit{ds.db}
20 | }
21 |
22 | // ClearOutdated clear data older than a given days.
23 | func (p *policyAudit) ClearOutdated(ctx context.Context, maxReserveDays int) (int64, error) {
24 | date := time.Now().AddDate(0, 0, -maxReserveDays).Format("2006-01-02 15:04:05")
25 |
26 | d := p.db.Exec("delete from policy_audit where deletedAt < ?", date)
27 |
28 | return d.RowsAffected, d.Error
29 | }
30 |
--------------------------------------------------------------------------------
/internal/apiserver/store/policy.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | import (
8 | "context"
9 |
10 | v1 "github.com/marmotedu/api/apiserver/v1"
11 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
12 | )
13 |
14 | // PolicyStore defines the policy storage interface.
15 | type PolicyStore interface {
16 | Create(ctx context.Context, policy *v1.Policy, opts metav1.CreateOptions) error
17 | Update(ctx context.Context, policy *v1.Policy, opts metav1.UpdateOptions) error
18 | Delete(ctx context.Context, username string, name string, opts metav1.DeleteOptions) error
19 | DeleteCollection(ctx context.Context, username string, names []string, opts metav1.DeleteOptions) error
20 | Get(ctx context.Context, username string, name string, opts metav1.GetOptions) (*v1.Policy, error)
21 | List(ctx context.Context, username string, opts metav1.ListOptions) (*v1.PolicyList, error)
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/store/policy_audit.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | import (
8 | "context"
9 | )
10 |
11 | // PolicyAuditStore defines the policy_audit storage interface.
12 | type PolicyAuditStore interface {
13 | ClearOutdated(ctx context.Context, maxReserveDays int) (int64, error)
14 | }
15 |
--------------------------------------------------------------------------------
/internal/apiserver/store/secret.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | import (
8 | "context"
9 |
10 | v1 "github.com/marmotedu/api/apiserver/v1"
11 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
12 | )
13 |
14 | // SecretStore defines the secret storage interface.
15 | type SecretStore interface {
16 | Create(ctx context.Context, secret *v1.Secret, opts metav1.CreateOptions) error
17 | Update(ctx context.Context, secret *v1.Secret, opts metav1.UpdateOptions) error
18 | Delete(ctx context.Context, username, secretID string, opts metav1.DeleteOptions) error
19 | DeleteCollection(ctx context.Context, username string, secretIDs []string, opts metav1.DeleteOptions) error
20 | Get(ctx context.Context, username, secretID string, opts metav1.GetOptions) (*v1.Secret, error)
21 | List(ctx context.Context, username string, opts metav1.ListOptions) (*v1.SecretList, error)
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/store/store.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | //go:generate mockgen -self_package=github.com/marmotedu/iam/internal/apiserver/store -destination mock_store.go -package store github.com/marmotedu/iam/internal/apiserver/store Factory,UserStore,SecretStore,PolicyStore
8 |
9 | var client Factory
10 |
11 | // Factory defines the iam platform storage interface.
12 | type Factory interface {
13 | Users() UserStore
14 | Secrets() SecretStore
15 | Policies() PolicyStore
16 | PolicyAudits() PolicyAuditStore
17 | Close() error
18 | }
19 |
20 | // Client return the store client instance.
21 | func Client() Factory {
22 | return client
23 | }
24 |
25 | // SetClient set the iam store client.
26 | func SetClient(factory Factory) {
27 | client = factory
28 | }
29 |
--------------------------------------------------------------------------------
/internal/apiserver/store/user.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | import (
8 | "context"
9 |
10 | v1 "github.com/marmotedu/api/apiserver/v1"
11 | metav1 "github.com/marmotedu/component-base/pkg/meta/v1"
12 | )
13 |
14 | // UserStore defines the user storage interface.
15 | type UserStore interface {
16 | Create(ctx context.Context, user *v1.User, opts metav1.CreateOptions) error
17 | Update(ctx context.Context, user *v1.User, opts metav1.UpdateOptions) error
18 | Delete(ctx context.Context, username string, opts metav1.DeleteOptions) error
19 | DeleteCollection(ctx context.Context, usernames []string, opts metav1.DeleteOptions) error
20 | Get(ctx context.Context, username string, opts metav1.GetOptions) (*v1.User, error)
21 | List(ctx context.Context, opts metav1.ListOptions) (*v1.UserList, error)
22 | }
23 |
--------------------------------------------------------------------------------
/internal/apiserver/testing/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/internal/apiserver/testing/.keep
--------------------------------------------------------------------------------
/internal/authzserver/authorization/authorizer.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package authorization
6 |
7 | import (
8 | authzv1 "github.com/marmotedu/api/authz/v1"
9 | "github.com/ory/ladon"
10 |
11 | "github.com/marmotedu/iam/pkg/log"
12 | )
13 |
14 | // Authorizer implement the authorize interface that use local repository to
15 | // authorize the subject access review.
16 | type Authorizer struct {
17 | warden ladon.Warden
18 | }
19 |
20 | // NewAuthorizer creates a local repository authorizer and returns it.
21 | func NewAuthorizer(authorizationClient AuthorizationInterface) *Authorizer {
22 | return &Authorizer{
23 | warden: &ladon.Ladon{
24 | Manager: NewPolicyManager(authorizationClient),
25 | AuditLogger: NewAuditLogger(authorizationClient),
26 | },
27 | }
28 | }
29 |
30 | // Authorize to determine the subject access.
31 | func (a *Authorizer) Authorize(request *ladon.Request) *authzv1.Response {
32 | log.Debug("authorize request", log.Any("request", request))
33 |
34 | if err := a.warden.IsAllowed(request); err != nil {
35 | return &authzv1.Response{
36 | Denied: true,
37 | Reason: err.Error(),
38 | }
39 | }
40 |
41 | return &authzv1.Response{
42 | Allowed: true,
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/internal/authzserver/authorization/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package authorization implement the authorize interface that use local repository to
6 | // authorize the subject access review.
7 | package authorization
8 |
--------------------------------------------------------------------------------
/internal/authzserver/authorization/logger.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package authorization
6 |
7 | import (
8 | "github.com/ory/ladon"
9 |
10 | "github.com/marmotedu/iam/pkg/log"
11 | )
12 |
13 | // AuditLogger outputs and cache information about granting or rejecting policies.
14 | type AuditLogger struct {
15 | client AuthorizationInterface
16 | }
17 |
18 | // NewAuditLogger creates a AuditLogger with default parameters.
19 | func NewAuditLogger(client AuthorizationInterface) *AuditLogger {
20 | return &AuditLogger{
21 | client: client,
22 | }
23 | }
24 |
25 | // LogRejectedAccessRequest write rejected subject access to log.
26 | func (a *AuditLogger) LogRejectedAccessRequest(r *ladon.Request, p ladon.Policies, d ladon.Policies) {
27 | a.client.LogRejectedAccessRequest(r, p, d)
28 | log.Debug("subject access review rejected", log.Any("request", r), log.Any("deciders", d))
29 | }
30 |
31 | // LogGrantedAccessRequest write granted subject access to log.
32 | func (a *AuditLogger) LogGrantedAccessRequest(r *ladon.Request, p ladon.Policies, d ladon.Policies) {
33 | a.client.LogGrantedAccessRequest(r, p, d)
34 | log.Debug("subject access review granted", log.Any("request", r), log.Any("deciders", d))
35 | }
36 |
--------------------------------------------------------------------------------
/internal/authzserver/authorization/types.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package authorization
6 |
7 | //go:generate mockgen -destination mock_authorization.go -package authorization github.com/marmotedu/iam/internal/authzserver/authorization AuthorizationInterface
8 |
9 | import (
10 | "github.com/ory/ladon"
11 | )
12 |
13 | // AuthorizationInterface defiens the CURD method for lady policy.
14 | type AuthorizationInterface interface {
15 | Create(*ladon.DefaultPolicy) error
16 | Update(*ladon.DefaultPolicy) error
17 | Delete(id string) error
18 | DeleteCollection(idList []string) error
19 | Get(id string) (*ladon.DefaultPolicy, error)
20 | List(username string) ([]*ladon.DefaultPolicy, error)
21 |
22 | // The following two functions tracks denied and granted authorizations.
23 | LogRejectedAccessRequest(request *ladon.Request, pool ladon.Policies, deciders ladon.Policies)
24 | LogGrantedAccessRequest(request *ladon.Request, pool ladon.Policies, deciders ladon.Policies)
25 | }
26 |
--------------------------------------------------------------------------------
/internal/authzserver/config/config.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package config
6 |
7 | import "github.com/marmotedu/iam/internal/authzserver/options"
8 |
9 | // Config is the running configuration structure of the IAM pump service.
10 | type Config struct {
11 | *options.Options
12 | }
13 |
14 | // CreateConfigFromOptions creates a running configuration instance based
15 | // on a given IAM pump command line or configuration file option.
16 | func CreateConfigFromOptions(opts *options.Options) (*Config, error) {
17 | return &Config{opts}, nil
18 | }
19 |
--------------------------------------------------------------------------------
/internal/authzserver/config/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package config defines iam-authz-server configuration.
6 | package config
7 |
--------------------------------------------------------------------------------
/internal/authzserver/jwt.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package authzserver
6 |
7 | import (
8 | "github.com/marmotedu/errors"
9 |
10 | "github.com/marmotedu/iam/internal/authzserver/load/cache"
11 | "github.com/marmotedu/iam/internal/pkg/middleware"
12 | "github.com/marmotedu/iam/internal/pkg/middleware/auth"
13 | )
14 |
15 | func newCacheAuth() middleware.AuthStrategy {
16 | return auth.NewCacheStrategy(getSecretFunc())
17 | }
18 |
19 | func getSecretFunc() func(string) (auth.Secret, error) {
20 | return func(kid string) (auth.Secret, error) {
21 | cli, err := cache.GetCacheInsOr(nil)
22 | if err != nil || cli == nil {
23 | return auth.Secret{}, errors.Wrap(err, "get cache instance failed")
24 | }
25 |
26 | secret, err := cli.GetSecret(kid)
27 | if err != nil {
28 | return auth.Secret{}, err
29 | }
30 |
31 | return auth.Secret{
32 | Username: secret.Username,
33 | ID: secret.SecretId,
34 | Key: secret.SecretKey,
35 | Expires: secret.Expires,
36 | }, nil
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/internal/authzserver/load/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package load loads pump plugins.
6 | package load
7 |
--------------------------------------------------------------------------------
/internal/authzserver/options/validation.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package options
6 |
7 | // Validate checks Options and return a slice of found errs.
8 | func (o *Options) Validate() []error {
9 | var errs []error
10 |
11 | errs = append(errs, o.GenericServerRunOptions.Validate()...)
12 | errs = append(errs, o.InsecureServing.Validate()...)
13 | errs = append(errs, o.SecureServing.Validate()...)
14 | errs = append(errs, o.RedisOptions.Validate()...)
15 | errs = append(errs, o.FeatureOptions.Validate()...)
16 | errs = append(errs, o.Log.Validate()...)
17 | errs = append(errs, o.AnalyticsOptions.Validate()...)
18 |
19 | return errs
20 | }
21 |
--------------------------------------------------------------------------------
/internal/authzserver/router.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package authzserver
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | "github.com/marmotedu/component-base/pkg/core"
10 | "github.com/marmotedu/errors"
11 |
12 | "github.com/marmotedu/iam/internal/authzserver/controller/v1/authorize"
13 | "github.com/marmotedu/iam/internal/authzserver/load/cache"
14 | "github.com/marmotedu/iam/internal/pkg/code"
15 | "github.com/marmotedu/iam/pkg/log"
16 | )
17 |
18 | func initRouter(g *gin.Engine) {
19 | installMiddleware(g)
20 | installController(g)
21 | }
22 |
23 | func installMiddleware(g *gin.Engine) {
24 | }
25 |
26 | func installController(g *gin.Engine) *gin.Engine {
27 | auth := newCacheAuth()
28 | g.NoRoute(auth.AuthFunc(), func(c *gin.Context) {
29 | core.WriteResponse(c, errors.WithCode(code.ErrPageNotFound, "page not found."), nil)
30 | })
31 |
32 | cacheIns, _ := cache.GetCacheInsOr(nil)
33 | if cacheIns == nil {
34 | log.Panicf("get nil cache instance")
35 | }
36 |
37 | apiv1 := g.Group("/v1", auth.AuthFunc())
38 | {
39 | authzController := authorize.NewAuthzController(cacheIns)
40 |
41 | // Router for authorization
42 | apiv1.POST("/authz", authzController.Authorize)
43 | }
44 |
45 | return g
46 | }
47 |
--------------------------------------------------------------------------------
/internal/authzserver/run.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package authzserver
6 |
7 | import (
8 | "github.com/marmotedu/iam/internal/authzserver/config"
9 | )
10 |
11 | // Run runs the specified AuthzServer. This should never exit.
12 | func Run(cfg *config.Config) error {
13 | server, err := createAuthzServer(cfg)
14 | if err != nil {
15 | return err
16 | }
17 |
18 | return server.PrepareRun().Run()
19 | }
20 |
--------------------------------------------------------------------------------
/internal/authzserver/store/apiserver/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package apiserver
6 |
--------------------------------------------------------------------------------
/internal/authzserver/store/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package store defines the storage interface for authzserver.
6 | package store
7 |
--------------------------------------------------------------------------------
/internal/authzserver/store/policy.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | import "github.com/ory/ladon"
8 |
9 | // PolicyStore defines the policy storage interface.
10 | type PolicyStore interface {
11 | List() (map[string][]*ladon.DefaultPolicy, error)
12 | }
13 |
--------------------------------------------------------------------------------
/internal/authzserver/store/secret.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | import pb "github.com/marmotedu/api/proto/apiserver/v1"
8 |
9 | // SecretStore defines the secret storage interface.
10 | type SecretStore interface {
11 | // List(ctx context.Context, username string, opts metav1.ListOptions) (*v1.SecretList, error)
12 | List() (map[string]*pb.SecretInfo, error)
13 | }
14 |
--------------------------------------------------------------------------------
/internal/authzserver/store/store.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package store
6 |
7 | //go:generate mockgen -self_package=github.com/marmotedu/iam/internal/authzserver/store -destination mock_store.go -package store github.com/marmotedu/iam/internal/authzserver/store Factory,SecretStore,PolicyStore
8 |
9 | var client Factory
10 |
11 | // Factory defines the iam platform storage interface.
12 | type Factory interface {
13 | Policies() PolicyStore
14 | Secrets() SecretStore
15 | }
16 |
17 | // Client return the store client instance.
18 | func Client() Factory {
19 | return client
20 | }
21 |
22 | // SetClient set the iam store client.
23 | func SetClient(factory Factory) {
24 | client = factory
25 | }
26 |
--------------------------------------------------------------------------------
/internal/authzserver/testing/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/internal/authzserver/testing/.keep
--------------------------------------------------------------------------------
/internal/iamctl/cmd/jwt/args.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package jwt
6 |
7 | import (
8 | "fmt"
9 | "strings"
10 |
11 | "github.com/marmotedu/component-base/pkg/json"
12 | )
13 |
14 | // ArgList defines a new pflag Value.
15 | type ArgList map[string]string
16 |
17 | // String return value of ArgList in string format.
18 | func (l ArgList) String() string {
19 | data, _ := json.Marshal(l)
20 |
21 | return string(data)
22 | }
23 |
24 | // Set sets the value of ArgList.
25 | func (l ArgList) Set(arg string) error {
26 | parts := strings.SplitN(arg, "=", 2)
27 | if len(parts) != 2 {
28 | return fmt.Errorf("invalid argument '%v'. Must use format 'key=value'. %v", arg, parts)
29 | }
30 | l[parts[0]] = parts[1]
31 |
32 | return nil
33 | }
34 |
35 | // Type returns the type name of ArgList.
36 | func (l ArgList) Type() string {
37 | return "map"
38 | }
39 |
--------------------------------------------------------------------------------
/internal/iamctl/cmd/jwt/jwt.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package jwt can be used to sign/show/verify jwt token with given secretID and secretKey.
6 | package jwt
7 |
8 | import (
9 | "github.com/spf13/cobra"
10 |
11 | cmdutil "github.com/marmotedu/iam/internal/iamctl/cmd/util"
12 | "github.com/marmotedu/iam/internal/iamctl/util/templates"
13 | "github.com/marmotedu/iam/pkg/cli/genericclioptions"
14 | )
15 |
16 | var jwtLong = templates.LongDesc(`
17 | JWT command.
18 |
19 | This commands is used to sigin/show/verify jwt token.`)
20 |
21 | // NewCmdJWT returns new initialized instance of 'jwt' sub command.
22 | func NewCmdJWT(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
23 | cmd := &cobra.Command{
24 | Use: "jwt SUBCOMMAND",
25 | DisableFlagsInUseLine: true,
26 | Short: "JWT command-line tool",
27 | Long: jwtLong,
28 | Run: cmdutil.DefaultSubCommandRun(ioStreams.ErrOut),
29 | }
30 |
31 | // add subcommands
32 | cmd.AddCommand(NewCmdSign(f, ioStreams))
33 | cmd.AddCommand(NewCmdShow(f, ioStreams))
34 | cmd.AddCommand(NewCmdVerify(f, ioStreams))
35 |
36 | return cmd
37 | }
38 |
--------------------------------------------------------------------------------
/internal/iamctl/cmd/options/options.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package options print a list of global command-line options (applies to all commands).
6 | package options
7 |
8 | import (
9 | "io"
10 |
11 | "github.com/spf13/cobra"
12 |
13 | "github.com/marmotedu/iam/internal/iamctl/util/templates"
14 | )
15 |
16 | var optionsExample = templates.Examples(`
17 | # Print flags inherited by all commands
18 | iamctl options`)
19 |
20 | // NewCmdOptions implements the options command.
21 | func NewCmdOptions(out io.Writer) *cobra.Command {
22 | cmd := &cobra.Command{
23 | Use: "options",
24 | Short: "Print the list of flags inherited by all commands",
25 | Long: "Print the list of flags inherited by all commands",
26 | Example: optionsExample,
27 | Run: func(cmd *cobra.Command, args []string) {
28 | _ = cmd.Usage()
29 | },
30 | }
31 |
32 | // The `options` command needs write its output to the `out` stream
33 | // (typically stdout). Without calling SetOutput here, the Usage()
34 | // function call will fall back to stderr.
35 | cmd.SetOutput(out)
36 |
37 | templates.UseOptionsTemplates(cmd)
38 |
39 | return cmd
40 | }
41 |
--------------------------------------------------------------------------------
/internal/iamctl/cmd/policy/policy.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package policy provides functions to manage authorization policies on iam platform.
6 | package policy
7 |
8 | import (
9 | "github.com/spf13/cobra"
10 |
11 | cmdutil "github.com/marmotedu/iam/internal/iamctl/cmd/util"
12 | "github.com/marmotedu/iam/internal/iamctl/util/templates"
13 | "github.com/marmotedu/iam/pkg/cli/genericclioptions"
14 | )
15 |
16 | var policyLong = templates.LongDesc(`
17 | Authorization policy management commands.
18 |
19 | This commands allow you to manage your authorization policy on iam platform.`)
20 |
21 | // NewCmdPolicy returns new initialized instance of 'policy' sub command.
22 | func NewCmdPolicy(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
23 | cmd := &cobra.Command{
24 | Use: "policy SUBCOMMAND",
25 | DisableFlagsInUseLine: true,
26 | Short: "Manage authorization policies on iam platform",
27 | Long: policyLong,
28 | Run: cmdutil.DefaultSubCommandRun(ioStreams.ErrOut),
29 | }
30 |
31 | cmd.AddCommand(NewCmdCreate(f, ioStreams))
32 | cmd.AddCommand(NewCmdGet(f, ioStreams))
33 | cmd.AddCommand(NewCmdList(f, ioStreams))
34 | cmd.AddCommand(NewCmdDelete(f, ioStreams))
35 | cmd.AddCommand(NewCmdUpdate(f, ioStreams))
36 |
37 | return cmd
38 | }
39 |
--------------------------------------------------------------------------------
/internal/iamctl/cmd/set/set.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package set used to set specific features on objects.
6 | package set
7 |
8 | import (
9 | "github.com/spf13/cobra"
10 |
11 | cmdutil "github.com/marmotedu/iam/internal/iamctl/cmd/util"
12 | "github.com/marmotedu/iam/internal/iamctl/util/templates"
13 | "github.com/marmotedu/iam/pkg/cli/genericclioptions"
14 | )
15 |
16 | var setLong = templates.LongDesc(`
17 | Configure objects.
18 |
19 | These commands help you make changes to existing objects.`)
20 |
21 | // NewCmdSet returns an initialized Command instance for 'set' sub command.
22 | func NewCmdSet(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
23 | cmd := &cobra.Command{
24 | Use: "set SUBCOMMAND",
25 | DisableFlagsInUseLine: true,
26 | Short: "Set specific features on objects",
27 | Long: setLong,
28 | Run: cmdutil.DefaultSubCommandRun(ioStreams.ErrOut),
29 | }
30 |
31 | // add subcommands
32 | // cmd.AddCommand(NewCmdDB(f, ioStreams))
33 |
34 | return cmd
35 | }
36 |
--------------------------------------------------------------------------------
/internal/iamctl/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package iamctl provides the functions used by the iamctl command line tool
6 | // under github.com/marmotedu/iam/cmd. The functions are kept in this package to better
7 | // support unit testing. The main() method for iamctl is only an entry point
8 | // and should contain no functionality.
9 | package iamctl // import "github.com/marmotedu/iam/internal/iamctl"
10 |
--------------------------------------------------------------------------------
/internal/iamctl/iamctl.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package iamctl
6 |
7 | const (
8 | // TableWidth defines the table width for 'github.com/olekukonko/tablewriter'.
9 | TableWidth = 50
10 | )
11 |
--------------------------------------------------------------------------------
/internal/iamctl/util/templates/command_groups.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package templates
6 |
7 | import (
8 | "github.com/spf13/cobra"
9 | )
10 |
11 | type CommandGroup struct {
12 | Message string
13 | Commands []*cobra.Command
14 | }
15 |
16 | type CommandGroups []CommandGroup
17 |
18 | func (g CommandGroups) Add(c *cobra.Command) {
19 | for _, group := range g {
20 | c.AddCommand(group.Commands...)
21 | }
22 | }
23 |
24 | func (g CommandGroups) Has(c *cobra.Command) bool {
25 | for _, group := range g {
26 | for _, command := range group.Commands {
27 | if command == c {
28 | return true
29 | }
30 | }
31 | }
32 | return false
33 | }
34 |
35 | func AddAdditionalCommands(g CommandGroups, message string, cmds []*cobra.Command) CommandGroups {
36 | group := CommandGroup{Message: message}
37 | for _, c := range cmds {
38 | // Don't show commands that have no short description
39 | if !g.Has(c) && len(c.Short) != 0 {
40 | group.Commands = append(group.Commands, c)
41 | }
42 | }
43 | if len(group.Commands) == 0 {
44 | return g
45 | }
46 | return append(g, group)
47 | }
48 |
--------------------------------------------------------------------------------
/internal/iamctl/util/term/resize.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package term
6 |
7 | import (
8 | "github.com/moby/term"
9 | )
10 |
11 | // TerminalSize represents the width and height of a terminal.
12 | type TerminalSize struct {
13 | Width uint16
14 | Height uint16
15 | }
16 |
17 | // TerminalSizeQueue is capable of returning terminal resize events as they occur.
18 | type TerminalSizeQueue interface {
19 | // Next returns the new terminal size after the terminal has been resized. It returns nil when
20 | // monitoring has been stopped.
21 | Next() *TerminalSize
22 | }
23 |
24 | // GetSize returns the current size of the user's terminal. If it isn't a terminal,
25 | // nil is returned.
26 | func (t TTY) GetSize() *TerminalSize {
27 | outFd, isTerminal := term.GetFdInfo(t.Out)
28 | if !isTerminal {
29 | return nil
30 | }
31 | return GetSize(outFd)
32 | }
33 |
34 | // GetSize returns the current size of the terminal associated with fd.
35 | func GetSize(fd uintptr) *TerminalSize {
36 | winsize, err := term.GetWinsize(fd)
37 | if err != nil {
38 | // runtime.HandleError(fmt.Errorf("unable to get terminal size: %v", err))
39 | return nil
40 | }
41 |
42 | return &TerminalSize{Width: winsize.Width, Height: winsize.Height}
43 | }
44 |
--------------------------------------------------------------------------------
/internal/iamctl/util/term/term.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package term provides structures and helper functions to work with
6 | // terminal (state, sizes).
7 | package term
8 |
9 | import (
10 | "io"
11 | )
12 |
13 | // TTY helps invoke a function and preserve the state of the terminal, even if the process is
14 | // terminated during execution. It also provides support for terminal resizing for remote command
15 | // execution/attachment.
16 | type TTY struct {
17 | // In is a reader representing stdin. It is a required field.
18 | In io.Reader
19 | // Out is a writer representing stdout. It must be set to support terminal resizing. It is an
20 | // optional field.
21 | Out io.Writer
22 | // Raw is true if the terminal should be set raw.
23 | Raw bool
24 | // TryDev indicates the TTY should try to open /dev/tty if the provided input
25 | // is not a file descriptor.
26 | TryDev bool
27 | }
28 |
--------------------------------------------------------------------------------
/internal/pkg/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/internal/pkg/README.md
--------------------------------------------------------------------------------
/internal/pkg/code/apiserver.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package code
6 |
7 | //go:generate codegen -type=int
8 |
9 | // iam-apiserver: user errors.
10 | const (
11 | // ErrUserNotFound - 404: User not found.
12 | ErrUserNotFound int = iota + 110001
13 |
14 | // ErrUserAlreadyExist - 400: User already exist.
15 | ErrUserAlreadyExist
16 | )
17 |
18 | // iam-apiserver: secret errors.
19 | const (
20 | // ErrEncrypt - 400: Secret reach the max count.
21 | ErrReachMaxCount int = iota + 110101
22 |
23 | // ErrSecretNotFound - 404: Secret not found.
24 | ErrSecretNotFound
25 | )
26 |
27 | // iam-apiserver: policy errors.
28 | const (
29 | // ErrPolicyNotFound - 404: Policy not found.
30 | ErrPolicyNotFound int = iota + 110201
31 | )
32 |
--------------------------------------------------------------------------------
/internal/pkg/code/authzserver.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package code
6 |
7 | //go:generate codegen -type=int
8 |
9 | // iam-authz-server: authorize errors.
10 | const ()
11 |
--------------------------------------------------------------------------------
/internal/pkg/code/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // iam code only allowed the following http code:
6 | // StatusOK = 200 // RFC 7231, 6.3.1
7 | // StatusBadRequest = 400 // RFC 7231, 6.5.1
8 | // StatusUnauthorized = 401 // RFC 7235, 3.1
9 | // StatusForbidden = 403 // RFC 7231, 6.5.3
10 | // StatusNotFound = 404 // RFC 7231, 6.5.4
11 | // StatusInternalServerError = 500 // RFC 7231, 6.6.1
12 |
13 | // Package code defines error codes for iam platform.
14 | package code // import "github.com/marmotedu/iam/internal/pkg/code"
15 |
--------------------------------------------------------------------------------
/internal/pkg/logger/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package logger // import "github.com/marmotedu/iam/internal/pkg/logger"
6 |
--------------------------------------------------------------------------------
/internal/pkg/middleware/auth.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package middleware
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 | )
10 |
11 | // AuthStrategy defines the set of methods used to do resource authentication.
12 | type AuthStrategy interface {
13 | AuthFunc() gin.HandlerFunc
14 | }
15 |
16 | // AuthOperator used to switch between different authentication strategy.
17 | type AuthOperator struct {
18 | strategy AuthStrategy
19 | }
20 |
21 | // SetStrategy used to set to another authentication strategy.
22 | func (operator *AuthOperator) SetStrategy(strategy AuthStrategy) {
23 | operator.strategy = strategy
24 | }
25 |
26 | // AuthFunc execute resource authentication.
27 | func (operator *AuthOperator) AuthFunc() gin.HandlerFunc {
28 | return operator.strategy.AuthFunc()
29 | }
30 |
--------------------------------------------------------------------------------
/internal/pkg/middleware/auth/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package auth defines authentication strategy like Basic, Bearer.
6 | package auth // import "github.com/marmotedu/iam/internal/pkg/middleware/auth"
7 |
--------------------------------------------------------------------------------
/internal/pkg/middleware/auth/jwt.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package auth
6 |
7 | import (
8 | ginjwt "github.com/appleboy/gin-jwt/v2"
9 | "github.com/gin-gonic/gin"
10 |
11 | "github.com/marmotedu/iam/internal/pkg/middleware"
12 | )
13 |
14 | // AuthzAudience defines the value of jwt audience field.
15 | const AuthzAudience = "iam.authz.marmotedu.com"
16 |
17 | // JWTStrategy defines jwt bearer authentication strategy.
18 | type JWTStrategy struct {
19 | ginjwt.GinJWTMiddleware
20 | }
21 |
22 | var _ middleware.AuthStrategy = &JWTStrategy{}
23 |
24 | // NewJWTStrategy create jwt bearer strategy with GinJWTMiddleware.
25 | func NewJWTStrategy(gjwt ginjwt.GinJWTMiddleware) JWTStrategy {
26 | return JWTStrategy{gjwt}
27 | }
28 |
29 | // AuthFunc defines jwt bearer strategy as the gin authentication middleware.
30 | func (j JWTStrategy) AuthFunc() gin.HandlerFunc {
31 | return j.MiddlewareFunc()
32 | }
33 |
--------------------------------------------------------------------------------
/internal/pkg/middleware/context.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package middleware
6 |
7 | import (
8 | "github.com/gin-gonic/gin"
9 |
10 | "github.com/marmotedu/iam/pkg/log"
11 | )
12 |
13 | // UsernameKey defines the key in gin context which represents the owner of the secret.
14 | const UsernameKey = "username"
15 |
16 | // Context is a middleware that injects common prefix fields to gin.Context.
17 | func Context() gin.HandlerFunc {
18 | return func(c *gin.Context) {
19 | c.Set(log.KeyRequestID, c.GetString(XRequestIDKey))
20 | c.Set(log.KeyUsername, c.GetString(UsernameKey))
21 | c.Next()
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/internal/pkg/middleware/cors.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package middleware
6 |
7 | import (
8 | "time"
9 |
10 | "github.com/gin-contrib/cors"
11 | "github.com/gin-gonic/gin"
12 | )
13 |
14 | const (
15 | maxAge = 12
16 | )
17 |
18 | // Cors add cors headers.
19 | func Cors() gin.HandlerFunc {
20 | return cors.New(cors.Config{
21 | AllowOrigins: []string{"*"},
22 | AllowMethods: []string{"PUT", "PATCH", "GET", "POST", "OPTIONS", "DELETE"},
23 | AllowHeaders: []string{"Origin", "Authorization", "Content-Type", "Accept"},
24 | ExposeHeaders: []string{"Content-Length"},
25 | AllowCredentials: true,
26 | AllowOriginFunc: func(origin string) bool {
27 | return origin == "https://github.com"
28 | },
29 | MaxAge: maxAge * time.Hour,
30 | })
31 | }
32 |
--------------------------------------------------------------------------------
/internal/pkg/middleware/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package middleware defines multiple gin middlewares
6 | package middleware
7 |
--------------------------------------------------------------------------------
/internal/pkg/middleware/limit.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package middleware
6 |
7 | import (
8 | "errors"
9 |
10 | "github.com/gin-gonic/gin"
11 | "golang.org/x/time/rate"
12 | )
13 |
14 | // ErrLimitExceeded defines Limit exceeded error.
15 | var ErrLimitExceeded = errors.New("Limit exceeded")
16 |
17 | // Limit drops (HTTP status 429) the request if the limit is reached.
18 | func Limit(maxEventsPerSec float64, maxBurstSize int) gin.HandlerFunc {
19 | limiter := rate.NewLimiter(rate.Limit(maxEventsPerSec), maxBurstSize)
20 |
21 | return func(c *gin.Context) {
22 | if limiter.Allow() {
23 | c.Next()
24 |
25 | return
26 | }
27 |
28 | // Limit reached
29 | _ = c.Error(ErrLimitExceeded)
30 | c.AbortWithStatus(429)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/internal/pkg/options/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package options is the public flags and options used by a generic api
6 | // server. It takes a minimal set of dependencies and does not reference
7 | // implementations, in order to ensure it may be reused by multiple components
8 | // (such as CLI commands that wish to generate or validate config).
9 | package options // import "github.com/marmotedu/iam/internal/pkg/options"
10 |
--------------------------------------------------------------------------------
/internal/pkg/server/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package server defines the generic apiserver used by all iam platform.
6 | package server // import "github.com/marmotedu/iam/internal/pkg/server"
7 |
--------------------------------------------------------------------------------
/internal/pkg/server/health.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package server runs a http server used to provide a api to check pump health status.
6 | package server
7 |
8 | import (
9 | "net/http"
10 |
11 | "github.com/marmotedu/iam/pkg/log"
12 | )
13 |
14 | // ServeHealthCheck runs a http server used to provide a api to check pump health status.
15 | func ServeHealthCheck(healthPath string, healthAddress string) {
16 | http.HandleFunc("/"+healthPath, func(w http.ResponseWriter, r *http.Request) {
17 | w.Header().Set("Content-type", "application/json")
18 | w.WriteHeader(http.StatusOK)
19 | _, _ = w.Write([]byte(`{"status": "ok"}`))
20 | })
21 |
22 | if err := http.ListenAndServe(healthAddress, nil); err != nil {
23 | log.Fatalf("Error serving health check endpoint: %s", err.Error())
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/internal/pkg/server/signal.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package server
6 |
7 | import (
8 | "os"
9 | "os/signal"
10 | )
11 |
12 | var onlyOneSignalHandler = make(chan struct{})
13 |
14 | var shutdownHandler chan os.Signal
15 |
16 | // SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
17 | // which is closed on one of these signals. If a second signal is caught, the program
18 | // is terminated with exit code 1.
19 | func SetupSignalHandler() <-chan struct{} {
20 | close(onlyOneSignalHandler) // panics when called twice
21 |
22 | shutdownHandler = make(chan os.Signal, 2)
23 |
24 | stop := make(chan struct{})
25 |
26 | signal.Notify(shutdownHandler, shutdownSignals...)
27 |
28 | go func() {
29 | <-shutdownHandler
30 | close(stop)
31 | <-shutdownHandler
32 | os.Exit(1) // second signal. Exit directly.
33 | }()
34 |
35 | return stop
36 | }
37 |
38 | // RequestShutdown emulates a received event that is considered as shutdown signal (SIGTERM/SIGINT)
39 | // This returns whether a handler was notified.
40 | func RequestShutdown() bool {
41 | if shutdownHandler != nil {
42 | select {
43 | case shutdownHandler <- shutdownSignals[0]:
44 | return true
45 | default:
46 | }
47 | }
48 |
49 | return false
50 | }
51 |
--------------------------------------------------------------------------------
/internal/pkg/server/signal_posix.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package server
6 |
7 | import (
8 | "os"
9 | "syscall"
10 | )
11 |
12 | var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
13 |
--------------------------------------------------------------------------------
/internal/pkg/util/gormutil/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package gormutil // import "github.com/marmotedu/iam/internal/pkg/util/gormutil"
6 |
--------------------------------------------------------------------------------
/internal/pkg/util/gormutil/gorm.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package gormutil is a util to convert offset and limit to default values.
6 | package gormutil
7 |
8 | // DefaultLimit define the default number of records to be retrieved.
9 | const DefaultLimit = 1000
10 |
11 | // LimitAndOffset contains offset and limit fields.
12 | type LimitAndOffset struct {
13 | Offset int
14 | Limit int
15 | }
16 |
17 | // Unpointer fill LimitAndOffset with default values if offset/limit is nil
18 | // or it will be filled with the passed value.
19 | func Unpointer(offset *int64, limit *int64) *LimitAndOffset {
20 | var o, l int = 0, DefaultLimit
21 |
22 | if offset != nil {
23 | o = int(*offset)
24 | }
25 |
26 | if limit != nil {
27 | l = int(*limit)
28 | }
29 |
30 | return &LimitAndOffset{
31 | Offset: o,
32 | Limit: l,
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/internal/pkg/util/reflect/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package reflect // import "github.com/marmotedu/iam/internal/pkg/util/reflect"
6 |
--------------------------------------------------------------------------------
/internal/pkg/validation/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package validation // import "github.com/marmotedu/iam/internal/pkg/validation"
6 |
--------------------------------------------------------------------------------
/internal/pkg/validation/validation.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package validation defines validate functions internal used by iam.
6 | package validation
7 |
--------------------------------------------------------------------------------
/internal/pump/analytics/analytics_filters.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package analytics
6 |
7 | // AnalyticsFilters defines the analytics options.
8 | type AnalyticsFilters struct {
9 | Usernames []string `json:"usernames"`
10 | SkippedUsernames []string `json:"skip_usernames"`
11 | }
12 |
13 | // ShouldFilter determine whether a record should to be filtered out.
14 | func (filters AnalyticsFilters) ShouldFilter(record AnalyticsRecord) bool {
15 | switch {
16 | case len(filters.SkippedUsernames) > 0 && stringInSlice(record.Username, filters.SkippedUsernames):
17 | return true
18 | case len(filters.Usernames) > 0 && !stringInSlice(record.Username, filters.Usernames):
19 | return true
20 | }
21 |
22 | return false
23 | }
24 |
25 | // HasFilter determine whether a record has a filter.
26 | func (filters AnalyticsFilters) HasFilter() bool {
27 | if len(filters.SkippedUsernames) == 0 && len(filters.Usernames) == 0 {
28 | return false
29 | }
30 |
31 | return true
32 | }
33 |
34 | func stringInSlice(a string, list []string) bool {
35 | for _, b := range list {
36 | if b == a {
37 | return true
38 | }
39 | }
40 |
41 | return false
42 | }
43 |
--------------------------------------------------------------------------------
/internal/pump/config/config.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package config
6 |
7 | import "github.com/marmotedu/iam/internal/pump/options"
8 |
9 | // Config is the running configuration structure of the IAM pump service.
10 | type Config struct {
11 | *options.Options
12 | }
13 |
14 | // CreateConfigFromOptions creates a running configuration instance based
15 | // on a given IAM pump command line or configuration file option.
16 | func CreateConfigFromOptions(opts *options.Options) (*Config, error) {
17 | return &Config{opts}, nil
18 | }
19 |
--------------------------------------------------------------------------------
/internal/pump/config/config_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package config
6 |
7 | import (
8 | "reflect"
9 | "testing"
10 |
11 | "github.com/marmotedu/iam/internal/pump/options"
12 | )
13 |
14 | func TestCreateConfigFromOptions(t *testing.T) {
15 | opts := options.NewOptions()
16 | type args struct {
17 | opts *options.Options
18 | }
19 | tests := []struct {
20 | name string
21 | args args
22 | want *Config
23 | wantErr bool
24 | }{
25 | {
26 | name: "default",
27 | args: args{
28 | opts: opts,
29 | },
30 | want: &Config{opts},
31 | wantErr: false,
32 | },
33 | }
34 | for _, tt := range tests {
35 | t.Run(tt.name, func(t *testing.T) {
36 | got, err := CreateConfigFromOptions(tt.args.opts)
37 | if (err != nil) != tt.wantErr {
38 | t.Errorf("CreateConfigFromOptions() error = %v, wantErr %v", err, tt.wantErr)
39 | return
40 | }
41 | if !reflect.DeepEqual(got, tt.want) {
42 | t.Errorf("CreateConfigFromOptions() = %v, want %v", got, tt.want)
43 | }
44 | })
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/internal/pump/config/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package config defines pump configuration.
6 | package config
7 |
--------------------------------------------------------------------------------
/internal/pump/options/validation.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package options
6 |
7 | // Validate checks Options and return a slice of found errs.
8 | func (o *Options) Validate() []error {
9 | var errs []error
10 |
11 | errs = append(errs, o.RedisOptions.Validate()...)
12 | errs = append(errs, o.Log.Validate()...)
13 |
14 | return errs
15 | }
16 |
--------------------------------------------------------------------------------
/internal/pump/pumps/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package pumps defines multiple back-end service used to persistent store iam analytics data.
6 | package pumps
7 |
--------------------------------------------------------------------------------
/internal/pump/pumps/dummy.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package pumps
6 |
7 | import (
8 | "context"
9 |
10 | "github.com/marmotedu/iam/pkg/log"
11 | )
12 |
13 | // DummyPump defines a dummy pump with dummy specific options and common options.
14 | type DummyPump struct {
15 | CommonPumpConfig
16 | }
17 |
18 | // New create a dummy pump instance.
19 | func (p *DummyPump) New() Pump {
20 | newPump := DummyPump{}
21 |
22 | return &newPump
23 | }
24 |
25 | // GetName returns the dummy pump name.
26 | func (p *DummyPump) GetName() string {
27 | return "Dummy Pump"
28 | }
29 |
30 | // Init initialize the dummy pump instance.
31 | func (p *DummyPump) Init(conf interface{}) error {
32 | log.Debug("Dummy Initialized")
33 |
34 | return nil
35 | }
36 |
37 | // WriteData write analyzed data to dummy persistent back-end storage.
38 | func (p *DummyPump) WriteData(ctx context.Context, data []interface{}) error {
39 | log.Infof("Writing %d records", len(data))
40 |
41 | return nil
42 | }
43 |
--------------------------------------------------------------------------------
/internal/pump/pumps/init.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package pumps
6 |
7 | var availablePumps map[string]Pump
8 |
9 | // nolint: gochecknoinits
10 | func init() {
11 | availablePumps = make(map[string]Pump)
12 |
13 | // Register all the storage handlers here
14 | availablePumps["csv"] = &CSVPump{}
15 | availablePumps["mongo"] = &MongoPump{}
16 | availablePumps["dummy"] = &DummyPump{}
17 | availablePumps["elasticsearch"] = &ElasticsearchPump{}
18 | availablePumps["influx"] = &InfluxPump{}
19 | availablePumps["prometheus"] = &PrometheusPump{}
20 | availablePumps["kafka"] = &KafkaPump{}
21 | availablePumps["syslog"] = &SyslogPump{}
22 | }
23 |
--------------------------------------------------------------------------------
/internal/pump/pumps/pump.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package pumps
6 |
7 | import (
8 | "context"
9 | "errors"
10 |
11 | "github.com/marmotedu/iam/internal/pump/analytics"
12 | )
13 |
14 | // Pump defines the interface for all analytics back-end.
15 | type Pump interface {
16 | GetName() string
17 | New() Pump
18 | Init(interface{}) error
19 | WriteData(context.Context, []interface{}) error
20 | SetFilters(analytics.AnalyticsFilters)
21 | GetFilters() analytics.AnalyticsFilters
22 | SetTimeout(timeout int)
23 | GetTimeout() int
24 | SetOmitDetailedRecording(bool)
25 | GetOmitDetailedRecording() bool
26 | }
27 |
28 | // GetPumpByName returns the pump instance by given name.
29 | func GetPumpByName(name string) (Pump, error) {
30 | if pump, ok := availablePumps[name]; ok && pump != nil {
31 | return pump, nil
32 | }
33 |
34 | return nil, errors.New(name + " Not found")
35 | }
36 |
--------------------------------------------------------------------------------
/internal/pump/pumps/pump_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package pumps
6 |
7 | import (
8 | "testing"
9 | )
10 |
11 | func TestGetPumpByName(t *testing.T) {
12 | name := "dummy"
13 | pmpType, err := GetPumpByName(name)
14 |
15 | if err != nil || pmpType == nil {
16 | t.Fail()
17 | }
18 |
19 | name2 := "xyz"
20 | pmpType2, err2 := GetPumpByName(name2)
21 |
22 | if err2 == nil || pmpType2 != nil {
23 | t.Fail()
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/internal/pump/run.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package pump
6 |
7 | import (
8 | genericapiserver "github.com/marmotedu/iam/internal/pkg/server"
9 | "github.com/marmotedu/iam/internal/pump/config"
10 | )
11 |
12 | // Run runs the specified pump server. This should never exit.
13 | func Run(cfg *config.Config, stopCh <-chan struct{}) error {
14 | go genericapiserver.ServeHealthCheck(cfg.HealthCheckPath, cfg.HealthCheckAddress)
15 |
16 | server, err := createPumpServer(cfg)
17 | if err != nil {
18 | return err
19 | }
20 |
21 | return server.PrepareRun().Run(stopCh)
22 | }
23 |
--------------------------------------------------------------------------------
/internal/pump/storage/store.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package storage defines storages which store the analytics data from iam-authz-server.
6 | package storage
7 |
8 | // AnalyticsStorage defines the analytics storage interface.
9 | type AnalyticsStorage interface {
10 | Init(config interface{}) error
11 | GetName() string
12 | Connect() bool
13 | GetAndDeleteSet(string) []interface{}
14 | }
15 |
16 | const (
17 | // AnalyticsKeyName defines the key name in redis which used to analytics.
18 | AnalyticsKeyName string = "iam-system-analytics"
19 | )
20 |
--------------------------------------------------------------------------------
/internal/pump/testing/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/internal/pump/testing/.keep
--------------------------------------------------------------------------------
/internal/watcher/config/config.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package config
6 |
7 | import "github.com/marmotedu/iam/internal/watcher/options"
8 |
9 | // Config is the running configuration structure of the IAM pump service.
10 | type Config struct {
11 | *options.Options
12 | }
13 |
14 | // CreateConfigFromOptions creates a running configuration instance based
15 | // on a given IAM pump command line or configuration file option.
16 | func CreateConfigFromOptions(opts *options.Options) (*Config, error) {
17 | return &Config{opts}, nil
18 | }
19 |
--------------------------------------------------------------------------------
/internal/watcher/config/config_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package config
6 |
7 | import (
8 | "reflect"
9 | "testing"
10 |
11 | "github.com/marmotedu/iam/internal/watcher/options"
12 | )
13 |
14 | func TestCreateConfigFromOptions(t *testing.T) {
15 | opts := options.NewOptions()
16 | type args struct {
17 | opts *options.Options
18 | }
19 | tests := []struct {
20 | name string
21 | args args
22 | want *Config
23 | wantErr bool
24 | }{
25 | {
26 | name: "default",
27 | args: args{
28 | opts: opts,
29 | },
30 | want: &Config{opts},
31 | wantErr: false,
32 | },
33 | }
34 | for _, tt := range tests {
35 | t.Run(tt.name, func(t *testing.T) {
36 | got, err := CreateConfigFromOptions(tt.args.opts)
37 | if (err != nil) != tt.wantErr {
38 | t.Errorf("CreateConfigFromOptions() error = %v, wantErr %v", err, tt.wantErr)
39 | return
40 | }
41 | if !reflect.DeepEqual(got, tt.want) {
42 | t.Errorf("CreateConfigFromOptions() = %v, want %v", got, tt.want)
43 | }
44 | })
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/internal/watcher/config/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package config defines pump configuration.
6 | package config
7 |
--------------------------------------------------------------------------------
/internal/watcher/options/validation.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package options
6 |
7 | // Validate checks Options and return a slice of found errs.
8 | func (o *Options) Validate() []error {
9 | var errs []error
10 |
11 | errs = append(errs, o.RedisOptions.Validate()...)
12 | errs = append(errs, o.MySQLOptions.Validate()...)
13 | errs = append(errs, o.Log.Validate()...)
14 |
15 | return errs
16 | }
17 |
--------------------------------------------------------------------------------
/internal/watcher/run.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package watcher
6 |
7 | import (
8 | genericapiserver "github.com/marmotedu/iam/internal/pkg/server"
9 | "github.com/marmotedu/iam/internal/watcher/config"
10 | )
11 |
12 | // Run runs the specified pump server. This should never exit.
13 | func Run(cfg *config.Config) error {
14 | go genericapiserver.ServeHealthCheck(cfg.HealthCheckPath, cfg.HealthCheckAddress)
15 |
16 | return createWatcherServer(cfg).PrepareRun().Run()
17 | }
18 |
--------------------------------------------------------------------------------
/internal/watcher/watcher/all/all.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package all
6 |
7 | //nolint: golint
8 | import (
9 | _ "github.com/marmotedu/iam/internal/watcher/watcher/clean"
10 | _ "github.com/marmotedu/iam/internal/watcher/watcher/task"
11 | )
12 |
--------------------------------------------------------------------------------
/pkg/app/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package app defines an application framework used to create application.
6 | package app // import "github.com/marmotedu/iam/pkg/app"
7 |
--------------------------------------------------------------------------------
/pkg/app/flag.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package app
6 |
7 | import (
8 | "strings"
9 |
10 | "github.com/spf13/pflag"
11 | )
12 |
13 | func initFlag() {
14 | pflag.CommandLine.SetNormalizeFunc(WordSepNormalizeFunc)
15 | }
16 |
17 | // WordSepNormalizeFunc changes all flags that contain "_" separators.
18 | func WordSepNormalizeFunc(_ *pflag.FlagSet, name string) pflag.NormalizedName {
19 | if strings.Contains(name, "_") {
20 | return pflag.NormalizedName(strings.Replace(name, "_", "-", -1))
21 | }
22 |
23 | return pflag.NormalizedName(name)
24 | }
25 |
--------------------------------------------------------------------------------
/pkg/app/options.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package app
6 |
7 | import (
8 | cliflag "github.com/marmotedu/component-base/pkg/cli/flag"
9 | )
10 |
11 | // CliOptions abstracts configuration options for reading parameters from the
12 | // command line.
13 | type CliOptions interface {
14 | // AddFlags adds flags to the specified FlagSet object.
15 | // AddFlags(fs *pflag.FlagSet)
16 | Flags() (fss cliflag.NamedFlagSets)
17 | Validate() []error
18 | }
19 |
20 | // ConfigurableOptions abstracts configuration options for reading parameters
21 | // from a configuration file.
22 | type ConfigurableOptions interface {
23 | // ApplyFlags parsing parameters from the command line or configuration file
24 | // to the options instance.
25 | ApplyFlags() []error
26 | }
27 |
28 | // CompleteableOptions abstracts options which can be completed.
29 | type CompleteableOptions interface {
30 | Complete() error
31 | }
32 |
33 | // PrintableOptions abstracts options which can be printed.
34 | type PrintableOptions interface {
35 | String() string
36 | }
37 |
--------------------------------------------------------------------------------
/pkg/cli/genericclioptions/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package genericclioptions contains flags which can be added to you command, bound, completed, and produce
6 | // useful helper functions.
7 | package genericclioptions // import "github.com/marmotedu/iam/pkg/cli/genericclioptions"
8 |
--------------------------------------------------------------------------------
/pkg/cli/genericclioptions/io_options.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package genericclioptions
6 |
7 | import (
8 | "bytes"
9 | "io"
10 | "io/ioutil"
11 | )
12 |
13 | // IOStreams provides the standard names for iostreams. This is useful for embedding and for unit testing.
14 | // Inconsistent and different names make it hard to read and review code.
15 | type IOStreams struct {
16 | // In think, os.Stdin
17 | In io.Reader
18 | // Out think, os.Stdout
19 | Out io.Writer
20 | // ErrOut think, os.Stderr
21 | ErrOut io.Writer
22 | }
23 |
24 | // NewTestIOStreams returns a valid IOStreams and in, out, errout buffers for unit tests.
25 | func NewTestIOStreams() (IOStreams, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer) {
26 | in := &bytes.Buffer{}
27 | out := &bytes.Buffer{}
28 | errOut := &bytes.Buffer{}
29 |
30 | return IOStreams{
31 | In: in,
32 | Out: out,
33 | ErrOut: errOut,
34 | }, in, out, errOut
35 | }
36 |
37 | // NewTestIOStreamsDiscard returns a valid IOStreams that just discards.
38 | func NewTestIOStreamsDiscard() IOStreams {
39 | in := &bytes.Buffer{}
40 |
41 | return IOStreams{
42 | In: in,
43 | Out: ioutil.Discard,
44 | ErrOut: ioutil.Discard,
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/pkg/db/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package db provide useful functions to create mysql instance.
6 | package db // import "github.com/marmotedu/iam/pkg/db"
7 |
--------------------------------------------------------------------------------
/pkg/log/LICENSE:
--------------------------------------------------------------------------------
1 | Tencent is pleased to support the open source community by making TKEStack available.
2 |
3 | Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
4 |
--------------------------------------------------------------------------------
/pkg/log/cronlog/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package cronlog // import "github.com/marmotedu/iam/pkg/log/cronlog"
6 |
--------------------------------------------------------------------------------
/pkg/log/cronlog/log.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package cronlog
6 |
7 | import (
8 | "fmt"
9 |
10 | "go.uber.org/zap"
11 | )
12 |
13 | type logger struct {
14 | zapLogger *zap.SugaredLogger
15 | }
16 |
17 | // NewLogger create a logger which implement `github.com/robfig/cron.Logger`.
18 | func NewLogger(zapLogger *zap.SugaredLogger) logger {
19 | return logger{zapLogger: zapLogger}
20 | }
21 |
22 | func (l logger) Info(msg string, args ...interface{}) {
23 | l.zapLogger.Infow(msg, args...)
24 | }
25 |
26 | func (l logger) Error(err error, msg string, args ...interface{}) {
27 | l.zapLogger.Errorw(fmt.Sprintf(msg, args...), "error", err.Error())
28 | }
29 |
30 | func (l logger) Flush() {
31 | _ = l.zapLogger.Sync()
32 | }
33 |
--------------------------------------------------------------------------------
/pkg/log/distribution/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package distribution // import "github.com/marmotedu/iam/pkg/log/distribution"
6 |
--------------------------------------------------------------------------------
/pkg/log/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package log // import "github.com/marmotedu/iam/pkg/log"
6 |
--------------------------------------------------------------------------------
/pkg/log/encoder.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Tencent is pleased to support the open source community by making TKEStack
3 | * available.
4 | *
5 | * Copyright (C) 2012-2019 Tencent. All Rights Reserved.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
8 | * this file except in compliance with the License. You may obtain a copy of the
9 | * License at
10 | *
11 | * https://opensource.org/licenses/Apache-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OF ANY KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package log
20 |
21 | import (
22 | "time"
23 |
24 | "go.uber.org/zap/zapcore"
25 | )
26 |
27 | func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
28 | enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
29 | }
30 |
31 | func milliSecondsDurationEncoder(d time.Duration, enc zapcore.PrimitiveArrayEncoder) {
32 | enc.AppendFloat64(float64(d) / float64(time.Millisecond))
33 | }
34 |
--------------------------------------------------------------------------------
/pkg/log/example/context/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main // import "github.com/marmotedu/iam/pkg/log/example/context"
6 |
--------------------------------------------------------------------------------
/pkg/log/example/context/main.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "context"
9 | "flag"
10 |
11 | "github.com/marmotedu/iam/pkg/log"
12 | )
13 |
14 | var (
15 | h bool
16 |
17 | level int
18 | format string
19 | )
20 |
21 | func main() {
22 | flag.BoolVar(&h, "h", false, "Print this help.")
23 | flag.IntVar(&level, "l", 0, "Log level.")
24 | flag.StringVar(&format, "f", "console", "log output format.")
25 |
26 | flag.Parse()
27 |
28 | if h {
29 | flag.Usage()
30 |
31 | return
32 | }
33 |
34 | // logger配置
35 | opts := &log.Options{
36 | Level: "debug",
37 | Format: "console",
38 | EnableColor: true,
39 | DisableCaller: true,
40 | OutputPaths: []string{"test.log", "stdout"},
41 | ErrorOutputPaths: []string{"error.log"},
42 | }
43 | // 初始化全局logger
44 | log.Init(opts)
45 | defer log.Flush()
46 |
47 | // WithValues使用
48 | lv := log.WithValues("X-Request-ID", "7a7b9f24-4cae-4b2a-9464-69088b45b904")
49 |
50 | // Context使用
51 | lv.Infof("Start to call pirntString function")
52 | ctx := lv.WithContext(context.Background())
53 | pirntString(ctx, "World")
54 | }
55 |
56 | func pirntString(ctx context.Context, str string) {
57 | lc := log.FromContext(ctx)
58 | lc.Infof("Hello %s", str)
59 | }
60 |
--------------------------------------------------------------------------------
/pkg/log/example/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
--------------------------------------------------------------------------------
/pkg/log/example/simple/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
--------------------------------------------------------------------------------
/pkg/log/example/simple/simple.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import "github.com/marmotedu/iam/pkg/log"
8 |
9 | func main() {
10 | log.Infof("this is a test log, message: %s", "good")
11 | }
12 |
--------------------------------------------------------------------------------
/pkg/log/example/vlevel/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
--------------------------------------------------------------------------------
/pkg/log/example/vlevel/v_level.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "github.com/marmotedu/iam/pkg/log"
9 | )
10 |
11 | func main() {
12 | defer log.Flush()
13 |
14 | log.V(0).Info("This is a V level message")
15 | log.V(0).Infow("This is a V level message with fields", "X-Request-ID", "7a7b9f24-4cae-4b2a-9464-69088b45b904")
16 | }
17 |
--------------------------------------------------------------------------------
/pkg/log/klog/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package klog // import "github.com/marmotedu/iam/pkg/log/klog"
6 |
--------------------------------------------------------------------------------
/pkg/log/logrus/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package logrus // import "github.com/marmotedu/iam/pkg/log/logrus"
6 |
--------------------------------------------------------------------------------
/pkg/log/logrus/logger.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Tencent is pleased to support the open source community by making TKEStack
3 | * available.
4 | *
5 | * Copyright (C) 2012-2019 Tencent. All Rights Reserved.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
8 | * this file except in compliance with the License. You may obtain a copy of the
9 | * License at
10 | *
11 | * https://opensource.org/licenses/Apache-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OF ANY KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | // Package logrus adds a hook to the logrus logger hooks.
20 | package logrus
21 |
22 | import (
23 | "io/ioutil"
24 |
25 | "github.com/sirupsen/logrus"
26 | "go.uber.org/zap"
27 | )
28 |
29 | // NewLogger create a logrus logger, add hook to it and return it.
30 | func NewLogger(zapLogger *zap.Logger) *logrus.Logger {
31 | logger := logrus.New()
32 | logger.SetOutput(ioutil.Discard)
33 | logger.AddHook(newHook(zapLogger))
34 |
35 | return logger
36 | }
37 |
--------------------------------------------------------------------------------
/pkg/log/options_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Tencent is pleased to support the open source community by making TKEStack
3 | * available.
4 | *
5 | * Copyright (C) 2012-2019 Tencent. All Rights Reserved.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
8 | * this file except in compliance with the License. You may obtain a copy of the
9 | * License at
10 | *
11 | * https://opensource.org/licenses/Apache-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 | * WARRANTIES OF ANY KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package log_test
20 |
21 | import (
22 | "fmt"
23 | "testing"
24 |
25 | "github.com/stretchr/testify/assert"
26 |
27 | "github.com/marmotedu/iam/pkg/log"
28 | )
29 |
30 | func Test_Options_Validate(t *testing.T) {
31 | opts := &log.Options{
32 | Level: "test",
33 | Format: "test",
34 | EnableColor: true,
35 | DisableCaller: false,
36 | OutputPaths: []string{"stdout"},
37 | ErrorOutputPaths: []string{"stderr"},
38 | }
39 |
40 | errs := opts.Validate()
41 | expected := `[unrecognized level: "test" not a valid log format: "test"]`
42 | assert.Equal(t, expected, fmt.Sprintf("%s", errs))
43 | }
44 |
--------------------------------------------------------------------------------
/pkg/shutdown/.travis.yml:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | language: go
6 |
7 | go:
8 | - 1.3
9 | - 1.4
10 | - tip
11 |
12 | branches:
13 | except:
14 | - fea_vendor
15 |
--------------------------------------------------------------------------------
/pkg/shutdown/LICENCE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Zemanta
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/pkg/shutdown/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package shutdown // import "github.com/marmotedu/iam/pkg/shutdown"
6 |
--------------------------------------------------------------------------------
/pkg/shutdown/shutdownmanagers/posixsignal/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package posixsignal // import "github.com/marmotedu/iam/pkg/shutdown/shutdownmanagers/posixsignal"
6 |
--------------------------------------------------------------------------------
/pkg/storage/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package storage // import "github.com/marmotedu/iam/pkg/storage"
6 |
--------------------------------------------------------------------------------
/pkg/util/flag/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package flag
6 |
--------------------------------------------------------------------------------
/pkg/util/genutil/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package genutil // import "github.com/marmotedu/iam/pkg/util/genutil"
6 |
--------------------------------------------------------------------------------
/pkg/util/genutil/genutil.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package genutil
6 |
7 | import (
8 | "fmt"
9 | "os"
10 | "path/filepath"
11 | )
12 |
13 | // OutDir creates the absolute path name from path and checks path exists.
14 | // Returns absolute path including trailing '/' or error if path does not exist.
15 | func OutDir(path string) (string, error) {
16 | outDir, err := filepath.Abs(path)
17 | if err != nil {
18 | return "", err
19 | }
20 |
21 | stat, err := os.Stat(outDir)
22 | if err != nil {
23 | return "", err
24 | }
25 |
26 | if !stat.IsDir() {
27 | return "", fmt.Errorf("output directory %s is not a directory", outDir)
28 | }
29 | outDir += "/"
30 | return outDir, nil
31 | }
32 |
--------------------------------------------------------------------------------
/pkg/util/genutil/genutil_test.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package genutil
6 |
7 | import (
8 | "testing"
9 | )
10 |
11 | func TestValidDir(t *testing.T) {
12 | _, err := OutDir("./")
13 | if err != nil {
14 | t.Fatal(err)
15 | }
16 | }
17 |
18 | func TestInvalidDir(t *testing.T) {
19 | _, err := OutDir("./nondir")
20 | if err == nil {
21 | t.Fatal("expected an error")
22 | }
23 | }
24 |
25 | func TestNotDir(t *testing.T) {
26 | _, err := OutDir("./genutils_test.go")
27 | if err == nil {
28 | t.Fatal("expected an error")
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/pkg/validator/doc.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package validator // import "github.com/marmotedu/iam/pkg/validator"
6 |
--------------------------------------------------------------------------------
/pkg/validator/validator.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | // Package validator defines iam custom binding validators used by gin.
6 | package validator
7 |
8 | import (
9 | "github.com/gin-gonic/gin/binding"
10 | "github.com/go-playground/validator/v10"
11 | "github.com/marmotedu/component-base/pkg/validation"
12 | )
13 |
14 | // validateUsername checks if a given username is illegal.
15 | func validateUsername(fl validator.FieldLevel) bool {
16 | username := fl.Field().String()
17 | if errs := validation.IsQualifiedName(username); len(errs) > 0 {
18 | return false
19 | }
20 |
21 | return true
22 | }
23 |
24 | // validatePassword checks if a given password is illegal.
25 | func validatePassword(fl validator.FieldLevel) bool {
26 | password := fl.Field().String()
27 | if err := validation.IsValidPassword(password); err != nil {
28 | return false
29 | }
30 |
31 | return true
32 | }
33 |
34 | func init() {
35 | if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
36 | _ = v.RegisterValidation("username", validateUsername)
37 | _ = v.RegisterValidation("password", validatePassword)
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/scripts/boilerplate.txt:
--------------------------------------------------------------------------------
1 | Copyright 2020 Lingfei Kong . All rights reserved.
2 | Use of this source code is governed by a MIT style
3 | license that can be found in the LICENSE file.
4 |
--------------------------------------------------------------------------------
/scripts/check_nginx.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | for port in 80
8 | do
9 | if echo |telnet 127.0.0.1 $port 2>&1|grep refused &>/dev/null;then
10 | exit 1
11 | fi
12 | done
13 |
--------------------------------------------------------------------------------
/scripts/coverage.awk:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env awk
2 |
3 | {
4 | print $0
5 | if (match($0, /^total:/)) {
6 | sub(/%/, "", $NF);
7 | printf("test coverage is %s%(quality gate is %s%)\n", $NF, target)
8 | if (strtonum($NF) < target) {
9 | printf("test coverage does not meet expectations: %d%, please add test cases!\n", target)
10 | exit 1;
11 | }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/scripts/coverage.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # http://stackoverflow.com/a/21142256/2055281
8 |
9 | echo "mode: atomic" > coverage.txt
10 |
11 | for d in $(find ./* -maxdepth 10 -type d); do
12 | if ls $d/*.go &> /dev/null; then
13 | go test -coverprofile=profile.out -covermode=atomic $d
14 | if [ -f profile.out ]; then
15 | cat profile.out | grep -v "mode: " >> /tmp/coverage.txt
16 | rm profile.out
17 | fi
18 | fi
19 | done
20 |
21 | echo "coverage output: /tmp/coverage.txt"
22 |
--------------------------------------------------------------------------------
/scripts/ensure_tag.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | version="${VERSION}"
8 | if [ "${version}" == "" ];then
9 | version=v`gsemver bump`
10 | fi
11 |
12 | if [ -z "`git tag -l ${version}`" ];then
13 | git tag -a -m "release version ${version}" ${version}
14 | fi
15 |
--------------------------------------------------------------------------------
/scripts/force_release.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
8 | source "${IAM_ROOT}/scripts/lib/init.sh"
9 |
10 | if [ $# -ne 1 ];then
11 | iam::log::error "Usage: force_release.sh v1.0.0"
12 | exit 1
13 | fi
14 |
15 | version="$1"
16 |
17 | set +o errexit
18 | # 1. delete old version
19 | git tag -d ${version}
20 | git push origin --delete ${version}
21 |
22 | # 2. create a new tag
23 | git tag -a ${version} -m "release ${version}"
24 | git push origin master
25 | git push origin ${version}
26 |
27 | # 3. release the new release
28 | pushd ${IAM_ROOT}
29 | # try to delete target github release if exist to avoid create error
30 | iam::log::info "delete github release with tag ${version} if exist"
31 | github-release delete \
32 | --user marmotedu\
33 | --repo iam \
34 | --tag ${version} &> /dev/null
35 |
36 | make release
37 |
--------------------------------------------------------------------------------
/scripts/gen_default_config.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
8 |
9 | source "${IAM_ROOT}/scripts/common.sh"
10 |
11 | readonly LOCAL_OUTPUT_CONFIGPATH="${LOCAL_OUTPUT_ROOT}/configs"
12 | mkdir -p ${LOCAL_OUTPUT_CONFIGPATH}
13 |
14 | cd ${IAM_ROOT}/scripts
15 |
16 | export IAM_APISERVER_INSECURE_BIND_ADDRESS=0.0.0.0
17 | export IAM_AUTHZ_SERVER_INSECURE_BIND_ADDRESS=0.0.0.0
18 |
19 | # 集群内通过kubernetes服务名访问
20 | export IAM_APISERVER_HOST=iam-apiserver
21 | export IAM_AUTHZ_SERVER_HOST=iam-authz-server
22 | export IAM_PUMP_HOST=iam-pump
23 | export IAM_WATCHER_HOST=iam-watcher
24 |
25 | # 配置CA证书路径
26 | export CONFIG_USER_CLIENT_CERTIFICATE=/etc/iam/cert/admin.pem
27 | export CONFIG_USER_CLIENT_KEY=/etc/iam/cert/admin-key.pem
28 | export CONFIG_SERVER_CERTIFICATE_AUTHORITY=/etc/iam/cert/ca.pem
29 |
30 | for comp in iam-apiserver iam-authz-server iam-pump iam-watcher iamctl
31 | do
32 | iam::log::info "generate ${LOCAL_OUTPUT_CONFIGPATH}/${comp}.yaml"
33 | ./genconfig.sh install/environment.sh ../configs/${comp}.yaml > ${LOCAL_OUTPUT_CONFIGPATH}/${comp}.yaml
34 | done
35 |
36 |
--------------------------------------------------------------------------------
/scripts/genconfig.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # 本脚本功能:根据 scripts/environment.sh 配置,生成 IAM 组件 YAML 配置文件。
8 | # 示例:genconfig.sh scripts/environment.sh configs/iam-apiserver.yaml
9 |
10 | env_file="$1"
11 | template_file="$2"
12 |
13 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
14 |
15 | source "${IAM_ROOT}/scripts/lib/init.sh"
16 |
17 | if [ $# -ne 2 ];then
18 | iam::log::error "Usage: genconfig.sh scripts/environment.sh configs/iam-apiserver.yaml"
19 | exit 1
20 | fi
21 |
22 | source "${env_file}"
23 |
24 | declare -A envs
25 |
26 | set +u
27 | for env in $(sed -n 's/^[^#].*${\(.*\)}.*/\1/p' ${template_file})
28 | do
29 | if [ -z "$(eval echo \$${env})" ];then
30 | iam::log::error "environment variable '${env}' not set"
31 | missing=true
32 | fi
33 | done
34 |
35 | if [ "${missing}" ];then
36 | iam::log::error 'You may run `source scripts/environment.sh` to set these environment'
37 | exit 1
38 | fi
39 |
40 | eval "cat << EOF
41 | $(cat ${template_file})
42 | EOF"
43 |
--------------------------------------------------------------------------------
/scripts/gendoc.sh:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | for top in pkg internal/pkg
6 | do
7 | for d in $(find $top -type d)
8 | do
9 | if [ ! -f $d/doc.go ]; then
10 | if ls $d/*.go > /dev/null 2>&1; then
11 | echo $d/doc.go
12 | echo "package $(basename $d) // import \"github.com/marmotedu/iam/$d\"" > $d/doc.go
13 | fi
14 | fi
15 | done
16 | done
17 |
--------------------------------------------------------------------------------
/scripts/install/common.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 |
8 | # Common utilities, variables and checks for all build scripts.
9 | set -o errexit
10 | set +o nounset
11 | set -o pipefail
12 |
13 | # Sourced flag
14 | COMMON_SOURCED=true
15 |
16 | # The root of the build/dist directory
17 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/../..
18 | source "${IAM_ROOT}/scripts/lib/init.sh"
19 | source "${IAM_ROOT}/scripts/install/environment.sh"
20 |
21 | # 不输入密码执行需要 root 权限的命令
22 | function iam::common::sudo {
23 | echo ${LINUX_PASSWORD} | sudo -S $1
24 | }
25 |
--------------------------------------------------------------------------------
/scripts/install/man.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 |
8 | # The root of the build/dist directory
9 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/../..
10 | [[ -z ${COMMON_SOURCED} ]] && source ${IAM_ROOT}/scripts/install/common.sh
11 |
12 | # 安装后打印必要的信息
13 | function iam::man::info() {
14 | cat << EOF
15 | use: man iam-apiserver to see iam-apiserver help
16 | EOF
17 | }
18 |
19 | # 安装
20 | function iam::man::install()
21 | {
22 | pushd ${IAM_ROOT}
23 |
24 | # 1. 生成各个组件的 man1 文件
25 | ${IAM_ROOT}/scripts/update-generated-docs.sh
26 | iam::common::sudo "cp docs/man/man1/* /usr/share/man/man1/"
27 | iam::man::status || return 1
28 | iam::man::info
29 |
30 | iam::log::info "install iam-apiserver successfully"
31 | popd
32 | }
33 |
34 | # 卸载
35 | function iam::man::uninstall()
36 | {
37 | set +o errexit
38 | iam::common::sudo "rm -f /usr/share/man/man1/iam-*"
39 | set -o errexit
40 | iam::log::info "uninstall iam man pages successfully"
41 | }
42 |
43 | # 状态检查
44 | function iam::man::status()
45 | {
46 | ls /usr/share/man/man1/iam-* &>/dev/null || {
47 | iam::log::error "iam man files not exist, maybe not installed properly"
48 | return 1
49 | }
50 | }
51 |
52 | if [[ "$*" =~ iam::man:: ]];then
53 | eval $*
54 | fi
55 |
--------------------------------------------------------------------------------
/scripts/install/release.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # Build an IAM release. This will build the binaries, create the Docker
8 | # images and other build artifacts.
9 |
10 | set -o errexit
11 | set -o nounset
12 | set -o pipefail
13 |
14 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
15 | source "${IAM_ROOT}/scripts/common.sh"
16 | source "${IAM_ROOT}/scripts/lib/release.sh"
17 |
18 | IAM_RELEASE_RUN_TESTS=${IAM_RELEASE_RUN_TESTS-y}
19 |
20 | iam::golang::setup_env
21 | iam::build::verify_prereqs
22 | iam::release::verify_prereqs
23 | #iam::build::build_image
24 | iam::build::build_command
25 | iam::release::package_tarballs
26 | iam::release::updload_tarballs
27 | iam::release::github_release
28 | iam::release::generate_changelog
29 |
--------------------------------------------------------------------------------
/scripts/keepalived_notify.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # /etc/keepalived/keepalived_notify.sh
8 | log_file=/var/log/keepalived.log
9 |
10 | iam::keepalived::mail() {
11 | # 这里可以添加email逻辑,当keepalived变动时及时告警
12 | :
13 | }
14 | iam::keepalived::log() {
15 | echo "[`date '+%Y-%m-%d %T'`] $1" >> ${log_file}
16 | }
17 |
18 | [ ! -d /var/keepalived/ ] && mkdir -p /var/keepalived/
19 |
20 | case "$1" in
21 | "MASTER" )
22 | iam::keepalived::log "notify_master"
23 | ;;
24 | "BACKUP" )
25 | iam::keepalived::log "notify_backup"
26 | ;;
27 | "FAULT" )
28 | iam::keepalived::log "notify_fault"
29 | ;;
30 | "STOP" )
31 | iam::keepalived::log "notify_stop"
32 | ;;
33 | *)
34 | iam::keepalived::log "keepalived_notify.sh: state error!"
35 | ;;
36 | esac
37 |
--------------------------------------------------------------------------------
/scripts/lib/init.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | set -o errexit
8 | set +o nounset
9 | set -o pipefail
10 |
11 | # Unset CDPATH so that path interpolation can work correctly
12 | # https://github.com/iamrnetes/iamrnetes/issues/52255
13 | unset CDPATH
14 |
15 | # Default use go modules
16 | export GO111MODULE=on
17 |
18 | # The root of the build/dist directory
19 | IAM_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
20 |
21 | source "${IAM_ROOT}/scripts/lib/util.sh"
22 | source "${IAM_ROOT}/scripts/lib/logging.sh"
23 | source "${IAM_ROOT}/scripts/lib/color.sh"
24 |
25 | iam::log::install_errexit
26 |
27 | source "${IAM_ROOT}/scripts/lib/version.sh"
28 | source "${IAM_ROOT}/scripts/lib/golang.sh"
29 |
--------------------------------------------------------------------------------
/scripts/make-rules/ca.mk:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | # ==============================================================================
6 | # Makefile helper functions for create CA files
7 | #
8 |
9 | .PHONY: ca.gen.%
10 | ca.gen.%:
11 | $(eval CA := $(word 1,$(subst ., ,$*)))
12 | @echo "===========> Generating CA files for $(CA)"
13 | @${ROOT_DIR}/scripts/gencerts.sh generate-iam-cert $(OUTPUT_DIR)/cert $(CA)
14 |
15 | .PHONY: ca.gen
16 | ca.gen: $(addprefix ca.gen., $(CERTIFICATES))
17 |
--------------------------------------------------------------------------------
/scripts/make-rules/copyright.mk:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | # ==============================================================================
6 | # Makefile helper functions for copyright
7 | #
8 | #
9 | .PHONY: copyright.verify
10 | copyright.verify: tools.verify.addlicense
11 | @echo "===========> Verifying the boilerplate headers for all files"
12 | @addlicense --check -f $(ROOT_DIR)/scripts/boilerplate.txt $(ROOT_DIR) --skip-dirs=third_party,vendor,_output
13 |
14 | .PHONY: copyright.add
15 | copyright.add: tools.verify.addlicense
16 | @addlicense -v -f $(ROOT_DIR)/scripts/boilerplate.txt $(ROOT_DIR) --skip-dirs=third_party,vendor,_output
17 |
--------------------------------------------------------------------------------
/scripts/make-rules/dependencies.mk:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | # ==============================================================================
6 | # Makefile helper functions for dependencies
7 | #
8 |
9 | .PHONY: dependencies.run
10 | dependencies.run: dependencies.packages dependencies.tools
11 |
12 | .PHONY: dependencies.packages
13 | dependencies.packages:
14 | @$(GO) mod tidy
15 |
16 | .PHONY: dependencies.tools
17 | dependencies.tools: dependencies.tools.blocker dependencies.tools.critical
18 |
19 | .PHONY: dependencies.tools.blocker
20 | dependencies.tools.blocker: go.build.verify $(addprefix tools.verify., $(BLOCKER_TOOLS))
21 |
22 | .PHONY: dependencies.tools.critical
23 | dependencies.tools.critical: $(addprefix tools.verify., $(CRITICAL_TOOLS))
24 |
25 | .PHONY: dependencies.tools.trivial
26 | dependencies.tools.trivial: $(addprefix tools.verify., $(TRIVIAL_TOOLS))
27 |
--------------------------------------------------------------------------------
/scripts/make-rules/deploy.mk:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | # ==============================================================================
6 | # Makefile helper functions for deploy to developer env
7 | #
8 |
9 | KUBECTL := kubectl
10 | NAMESPACE ?= iam
11 | CONTEXT ?= marmotedu.dev
12 |
13 | DEPLOYS=iam-apiserver iam-authz-server iam-pump iam-watcher
14 |
15 | .PHONY: deploy.run.all
16 | deploy.run.all:
17 | @echo "===========> Deploying all"
18 | @$(MAKE) deploy.run
19 |
20 | .PHONY: deploy.run
21 | deploy.run: $(addprefix deploy.run., $(DEPLOYS))
22 |
23 | .PHONY: deploy.run.%
24 | deploy.run.%:
25 | $(eval ARCH := $(word 2,$(subst _, ,$(PLATFORM))))
26 | @echo "===========> Deploying $* $(VERSION)-$(ARCH)"
27 | echo @$(KUBECTL) -n $(NAMESPACE) --context=$(CONTEXT) set image deployment/$* $*=$(REGISTRY_PREFIX)/$*-$(ARCH):$(VERSION)
28 |
--------------------------------------------------------------------------------
/scripts/make-rules/release.mk:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | # ==============================================================================
6 | # Makefile helper functions for release
7 | #
8 | #
9 |
10 | .PHONY: release.run
11 | release.run: release.verify release.ensure-tag
12 | @scripts/release.sh
13 |
14 | .PHONY: release.verify
15 | release.verify: tools.verify.git-chglog tools.verify.github-release tools.verify.coscmd
16 |
17 | .PHONY: release.tag
18 | release.tag: tools.verify.gsemver release.ensure-tag
19 | @git push origin `git describe --tags --abbrev=0`
20 |
21 | .PHONY: release.ensure-tag
22 | release.ensure-tag: tools.verify.gsemver
23 | @scripts/ensure_tag.sh
24 |
--------------------------------------------------------------------------------
/scripts/make-rules/swagger.mk:
--------------------------------------------------------------------------------
1 | # Copyright 2020 Lingfei Kong . All rights reserved.
2 | # Use of this source code is governed by a MIT style
3 | # license that can be found in the LICENSE file.
4 |
5 | # ==============================================================================
6 | # Makefile helper functions for swagger
7 | #
8 |
9 | .PHONY: swagger.run
10 | swagger.run: tools.verify.swagger
11 | @echo "===========> Generating swagger API docs"
12 | @swagger generate spec --scan-models -w $(ROOT_DIR)/cmd/genswaggertypedocs -o $(ROOT_DIR)/api/swagger/swagger.yaml
13 |
14 | .PHONY: swagger.serve
15 | swagger.serve: tools.verify.swagger
16 | @swagger serve -F=redoc --no-open --port 36666 $(ROOT_DIR)/api/swagger/swagger.yaml
17 |
--------------------------------------------------------------------------------
/scripts/print_enable_linters.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | tmpdir=$(mktemp -d)
8 |
9 | function disable_linters() {
10 | cat << EOF
11 | golint
12 | tagliatelle
13 | wrapcheck
14 | forcetypeassert
15 | goerr113
16 | gomnd
17 | wsl
18 | testpackage
19 | gochecknoglobals
20 | interfacer
21 | maligned
22 | scopelint
23 | gocritic
24 | EOF
25 | }
26 |
27 | disable_linters | sort > ${tmpdir}/disable_linters
28 | golangci-lint linters | awk -F':| ' '!match($0, /Enabled|Disabled|^$/){print $1}' | sort > ${tmpdir}/all_linters
29 |
30 | for linter in $(comm -3 ${tmpdir}/all_linters ${tmpdir}/disable_linters)
31 | do
32 | echo " - $linter"
33 | done
34 |
35 | rm -rf ${tmpdir}
36 |
--------------------------------------------------------------------------------
/scripts/release.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # Build a IAM release. This will build the binaries, create the Docker
8 | # images and other build artifacts.
9 |
10 | set -o errexit
11 | set -o nounset
12 | set -o pipefail
13 |
14 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
15 | source "${IAM_ROOT}/scripts/common.sh"
16 | source "${IAM_ROOT}/scripts/lib/release.sh"
17 |
18 | IAM_RELEASE_RUN_TESTS=${IAM_RELEASE_RUN_TESTS-y}
19 |
20 | iam::golang::setup_env
21 | iam::build::verify_prereqs
22 | iam::release::verify_prereqs
23 | #iam::build::build_image
24 | iam::build::build_command
25 | iam::release::package_tarballs
26 | iam::release::updload_tarballs
27 | git push origin ${VERSION}
28 | #iam::release::github_release
29 | #iam::release::generate_changelog
30 |
--------------------------------------------------------------------------------
/scripts/release/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/scripts/release/.keep
--------------------------------------------------------------------------------
/scripts/templates/project_README.md:
--------------------------------------------------------------------------------
1 | # Project myproject
2 |
3 |
4 |
5 | ## Features
6 |
7 |
8 |
9 | ## Getting Started
10 |
11 | ### Prerequisites
12 |
13 |
14 |
15 | ### Building
16 |
17 |
18 |
19 | ### Running
20 |
21 |
22 |
23 | ## Using
24 |
25 |
26 |
27 | ## Contributing
28 |
29 |
30 |
31 | ## Community(optional)
32 |
33 |
34 |
35 | ## Authors
36 |
37 |
38 |
39 | ## License
40 |
41 |
42 |
--------------------------------------------------------------------------------
/scripts/update-generated-docs.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # This file is not intended to be run automatically. It is meant to be run
8 | # immediately before exporting docs. We do not want to check these documents in
9 | # by default.
10 |
11 | set -o errexit
12 | set -o nounset
13 | set -o pipefail
14 |
15 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
16 | source "${IAM_ROOT}/scripts/lib/init.sh"
17 |
18 | iam::golang::setup_env
19 |
20 | BINS=(
21 | gendocs
22 | geniamdocs
23 | genman
24 | genyaml
25 | )
26 | make build -C "${IAM_ROOT}" BINS="${BINS[*]}"
27 |
28 | iam::util::ensure-temp-dir
29 |
30 | iam::util::gen-docs "${IAM_TEMP}"
31 |
32 | # remove all of the old docs
33 | iam::util::remove-gen-docs
34 |
35 | # Copy fresh docs into the repo.
36 | # the shopt is so that we get docs/.generated_docs from the glob.
37 | shopt -s dotglob
38 | cp -af "${IAM_TEMP}"/* "${IAM_ROOT}"
39 | shopt -u dotglob
40 |
--------------------------------------------------------------------------------
/scripts/update-kubernetes-spec.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | # This file is not intended to be run automatically. It is meant to be run
8 | # immediately before exporting docs. We do not want to check these documents in
9 | # by default.
10 |
11 | set -o errexit
12 | set -o nounset
13 | set -o pipefail
14 |
15 | IAM_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
16 | source "${IAM_ROOT}/scripts/lib/init.sh"
17 |
18 | COMPONENTS=(iam-apiserver iam-authz-server iam-pump iam-watcher)
19 | KINDS=(deployment service)
20 |
21 | for component in ${COMPONENTS[@]}
22 | do
23 | truncate -s 0 ${IAM_ROOT}/deployments/${component}.yaml
24 |
25 | for kind in ${KINDS[@]}
26 | do
27 | echo -e "---\n# Source: deployments/${component}-${kind}.yaml" >> ${IAM_ROOT}/deployments/${component}.yaml
28 | sed '/^#\|^$/d' ${IAM_ROOT}/deployments/${component}-${kind}.yaml >> ${IAM_ROOT}/deployments/${component}.yaml
29 | done
30 |
31 | iam::log::info "generate ${IAM_ROOT}/deployments/${component}.yaml success"
32 | done
33 |
--------------------------------------------------------------------------------
/test/README.md:
--------------------------------------------------------------------------------
1 | # `/test`
2 |
3 | Additional external test apps and test data. Feel free to structure the `/test` directory anyway you want. For bigger projects it makes sense to have a data subdirectory. For example, you can have `/test/data` or `/test/testdata` if you need Go to ignore what's in that directory. Note that Go will also ignore directories or files that begin with "." or "_", so you have more flexibility in terms of how you name your test data directory.
4 |
5 | Examples:
6 |
7 | * https://github.com/openshift/origin/tree/master/test (test data is in the `/testdata` subdirectory)
8 |
9 |
10 |
--------------------------------------------------------------------------------
/test/jwt/main.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 |
10 | "github.com/golang-jwt/jwt/v4"
11 | )
12 |
13 | func main() {
14 | rawJWT := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJpYW0uYXV0aHoubWFybW90ZWR1LmNvbSIsImV4cCI6MTYwNDEyODQwMywiaWF0IjoxNjA0MTI4NDAyLCJpc3MiOiJpYW1jdGwiLCJraWQiOiJpZDEifQ.Itr5u4C-nTeA01qbjjl7RzuPD-aSQazsJZY_Z25aGnI`
15 |
16 | // Verify the token
17 | claims := &jwt.MapClaims{}
18 | parsedT, err := jwt.ParseWithClaims(rawJWT, claims, func(token *jwt.Token) (interface{}, error) {
19 | // Validate the alg is HMAC signature
20 | if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
21 | return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
22 | }
23 |
24 | if kid, ok := token.Header["kid"].(string); ok {
25 | fmt.Println("kid", kid)
26 | }
27 |
28 | return []byte("key1"), nil
29 | })
30 |
31 | if err != nil || !parsedT.Valid {
32 | fmt.Println("token valid failed", err)
33 |
34 | return
35 | }
36 |
37 | fmt.Println("ok")
38 | }
39 |
--------------------------------------------------------------------------------
/test/nginx/loadbalance.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Copyright 2020 Lingfei Kong . All rights reserved.
4 | # Use of this source code is governed by a MIT style
5 | # license that can be found in the LICENSE file.
6 |
7 | for n in $(seq 1 1 10)
8 | do
9 | nohup curl http://iam.api.marmotedu.com/healthz &>/dev/null &
10 | done
11 |
--------------------------------------------------------------------------------
/test/testdata/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marmotedu/iam/16c723d3c1f75fe437e501ef7f22a816c48a6add/test/testdata/.keep
--------------------------------------------------------------------------------
/third_party/forked/murmur3/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled Object files, Static and Dynamic libs (Shared Objects)
2 | *.o
3 | *.a
4 | *.so
5 |
6 | # Folders
7 | _obj
8 | _test
9 |
10 | # Architecture specific extensions/prefixes
11 | *.[568vq]
12 | [568vq].out
13 |
14 | *.cgo1.go
15 | *.cgo2.c
16 | _cgo_defun.c
17 | _cgo_gotypes.go
18 | _cgo_export.*
19 |
20 | _testmain.go
21 |
22 | *.exe
23 |
--------------------------------------------------------------------------------
/third_party/forked/murmur3/.travis.yml:
--------------------------------------------------------------------------------
1 | language: go
2 |
3 | go:
4 | - 1.x
5 | - master
6 |
7 | script: go test
8 |
--------------------------------------------------------------------------------
/tools/README.md:
--------------------------------------------------------------------------------
1 | # `/tools`
2 |
3 | Supporting tools for this project. Note that these tools can import code from the `/pkg` and `/internal` directories.
4 |
5 | Examples:
6 |
7 | * https://github.com/istio/istio/tree/master/tools
8 | * https://github.com/openshift/origin/tree/master/tools
9 | * https://github.com/dapr/dapr/tree/master/tools
10 |
--------------------------------------------------------------------------------
/tools/httptest/main.go:
--------------------------------------------------------------------------------
1 | // Copyright 2020 Lingfei Kong . All rights reserved.
2 | // Use of this source code is governed by a MIT style
3 | // license that can be found in the LICENSE file.
4 |
5 | package main
6 |
7 | import (
8 | "fmt"
9 | "log"
10 | "net/http"
11 | )
12 |
13 | func main() {
14 | http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
15 | message := `{"status":"ok"}`
16 | fmt.Fprint(w, message)
17 | })
18 |
19 | addr := ":6667"
20 | fmt.Printf("Serving http service on %s\n", addr)
21 | log.Fatal(http.ListenAndServe(addr, nil))
22 | }
23 |
--------------------------------------------------------------------------------