### ServeOnce Function Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Demonstrates loading configuration and starting the authentication server using ServeOnce. ```go config, err := server.LoadConfig("config.yml") if err != nil { log.Fatal(err) } authServer, httpServer := ServeOnce(config, "config.yml") defer httpServer.Close() ``` -------------------------------- ### Quick Start Example Configuration Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Example `values.yaml` for enabling ingress, setting up TLS, configuring token issuer and expiration, defining static users, and setting up ACLs. This provides a comprehensive starting point for a production deployment. ```yaml # values.yaml ingress: enabled: true className: "nginx" annotations: cert-manager.io/cluster-issuer: "letsencrypt-prod" nginx.ingress.kubernetes.io/force-ssl-redirect: "true" hosts: - host: docker-auth.example.com paths: - path: / pathType: Prefix tls: - secretName: docker-auth-tls hosts: - docker-auth.example.com configmap: data: token: issuer: "docker-auth-prod" expiration: 900 users: "admin": password: "$2y$05$மையில்..." # Generate with htpasswd -Bbn admin password acl: - match: {account: "admin"} actions: ["*"] comment: "Admin has full access" - match: {account: ""} actions: ["pull"] comment: "Anonymous users can pull" ``` -------------------------------- ### Basic Helm Installation Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Installs the docker_auth Helm chart with default configurations. This is the simplest way to get started. ```bash helm install my-docker-auth cesanta/docker_auth ``` -------------------------------- ### Example Docker Auth Command Line Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Illustrates how to start the docker_auth binary with a configuration file and logging flags. ```bash docker_auth /etc/docker_auth/config.yml --v=2 --alsologtostderr ``` -------------------------------- ### Complete Docker Auth Server Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the integration of server, token, user, LDAP authentication, and ACL configurations. ```yaml server: addr: ":5001" net: "tcp" path_prefix: "" certificate: "/etc/docker_auth/server.pem" key: "/etc/docker_auth/server.key" hsts: true tls_min_version: TLS12 real_ip_header: "X-Forwarded-For" real_ip_pos: -1 token: issuer: "Docker Auth Server" expiration: 900 certificate: "/etc/docker_auth/token.pem" key: "/etc/docker_auth/token.key" users: admin: password: "$2y$05$LO.vzwpWC5LZGqThvEfznu8qhb5SGqvBSWY1J3yZ4AxtMRZ3kN5jC" labels: role: - admin ldap_auth: addr: "ldap.example.com:389" tls: "always" base: "ou=users,dc=example,dc=com" filter: "uid={0}" bind_dn: "cn=admin,dc=example,dc=com" bind_password_file: "/etc/docker_auth/ldap_password" acl: - match: account: "admin" type: "repository" name: "*" actions: ["*"] - match: type: "repository" name: "public" actions: ["pull"] ``` -------------------------------- ### Docker Auth Configuration File Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/overview.md This YAML configuration example outlines the structure for setting up the Docker Auth server. It includes sections for server settings, JWT token configuration, static user definitions, and lists of authenticators and authorizers. ```yaml server: addr: ":5001" certificate: "/etc/docker_auth/server.pem" key: "/etc/docker_auth/server.key" token: issuer: "Docker Auth" expiration: 900 users: admin: password: "$2y$05$.." [authenticators] google_auth, github_auth, ldap_auth, etc. [authorizers] acl, acl_mongo, casbin_authz, etc. ``` -------------------------------- ### Casbin Model File Example (RBAC) Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authorizers.md An example RBAC model configuration for Casbin. ```ini [request_definition] r = sub, obj, act [policy_definition] p = sub, obj, act [role_definition] g = _, _ [policy_effect] e = some(where (p.eft == allow)) [matchers] m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act ``` -------------------------------- ### Casbin Enforcer Initialization Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authorizers.md Example of initializing a Casbin enforcer and creating a Casbin authorizer. ```go enforcer, err := casbin.NewEnforcer(modelFile, policyFile) if err != nil { log.Fatal(err) } casbinAuthorizer, err := authz.NewCasbinAuthorizer(enforcer) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Casbin Policy File Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authorizers.md An example policy file for Casbin, defining permissions and roles. ```csv p, admin, repository::*, pull p, admin, repository::*, push p, user, repository::myrepo, pull p, user, repository::myrepo, push g, alice, admin g, bob, user ``` -------------------------------- ### Scope Format Examples Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/README.md Examples of resource scopes in Docker Registry. These define access permissions for repositories and registry catalogs. ```text repository:my/image:pull ``` ```text repository:my/image:push ``` ```text registry(catalog):*:* ``` -------------------------------- ### Graceful Shutdown Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Shows how to initiate a graceful shutdown of the authentication server and HTTP server in a signal handler. ```go // In signal handler authServer.Stop() httpServer.Close() glog.Exitf("Exiting") ``` -------------------------------- ### Example ACLEntry Creation Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/types.md Demonstrates how to create an ACLEntry with specific match conditions and actions, using helper functions like stringPtr. ```go entry := &ACLEntry{ Match: &MatchConditions{ Account: stringPtr("admin"), Type: stringPtr("repository"), Name: stringPtr("*"), }, Actions: &[]string{"*"}, Comment: stringPtr("Admins can do anything"), } ``` -------------------------------- ### Create and Initialize AuthServer Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-server.md Demonstrates how to load configuration and create a new AuthServer instance. This is the initial setup required before using the server. ```go config, err := server.LoadConfig("auth_config.yml") if err != nil { log.Fatal(err) } authServer, err := server.NewAuthServer(config) if err != nil { log.Fatal(err) } // Use with HTTP server httpServer := &http.Server{ Addr: config.Server.ListenAddress, Handler: authServer, } ``` -------------------------------- ### Server Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md Configures the HTTP listener, network, TLS, and request handling for the Docker Auth server. ```yaml server: addr: ":5001" net: "tcp" path_prefix: "" certificate: "/etc/docker_auth/server.pem" key: "/etc/docker_auth/server.key" hsts: true tls_min_version: TLS12 real_ip_header: "X-Forwarded-For" real_ip_pos: -1 ``` -------------------------------- ### Start Docker Auth Server with Auto-Reload Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-config.md Demonstrates how to start the Docker Auth server with automatic configuration reloading enabled. This allows changes to the configuration file to be applied without restarting the server. ```bash # Start server with auto-reload docker_auth /etc/docker_auth/config.yml # Edit config file vim /etc/docker_auth/config.yml # Server automatically reloads (check logs) docker logs ``` -------------------------------- ### Token Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md Configures JWT token generation, including issuer, expiration, and signing keys. ```yaml token: issuer: "Docker Auth Server" expiration: 900 certificate: "/etc/docker_auth/token.pem" key: "/etc/docker_auth/token.key" disable_legacy_key_id: true ``` -------------------------------- ### Helm Installation with Custom Values Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Installs the docker_auth Helm chart using a custom values file. This allows for detailed configuration of the deployment. ```bash helm install docker-auth cesanta/docker-auth -f values.yaml ``` -------------------------------- ### Static User Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md Defines static users with bcrypt-hashed passwords and optional labels for authentication. ```yaml users: admin: password: "$2y$05$LO.vzwpWC5LZGqThvEfznu8qhb5SGqvBSWY1J3yZ4AxtMRZ3kN5jC" labels: role: - admin user: password: "$2y$05$WuwBasGDAgr.QCbGIjKJaep4dhxeai9gNZdmBnQXqpKly57oNutya" labels: role: - user ``` -------------------------------- ### Let's Encrypt Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md Configures automatic certificate acquisition and renewal using Let's Encrypt. ```yaml server: letsencrypt: email: "admin@example.com" cache_dir: "/data/letsencrypt" host: "auth.example.com" ``` -------------------------------- ### Build Docker Auth Server Image Source: https://github.com/cesanta/docker_auth/blob/main/auth_server/README.md Clone the repository and build the Docker image for the auth server. Ensure you have Go and Docker installed. ```bash mkdir -p /var/tmp/go/src/github.com/cesanta cd /var/tmp/go/src/github.com/cesanta git clone https://github.com/cesanta/docker_auth.git cd docker_auth/auth_server make docker-build ``` -------------------------------- ### Run Docker Registry Authentication Server with Verbosity Source: https://github.com/cesanta/docker_auth/blob/main/README.md Example command to run the docker_auth server with increased logging verbosity. This is useful for troubleshooting. ```bash docker run ... cesanta/docker_auth:1 --v=2 --alsologtostderr /config/auth_config.yml ``` -------------------------------- ### ACL Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Defines access control list rules within the Helm chart's configuration. This example grants full access to 'admin' and pull access to anonymous users. ```yaml configmap: data: acl: - match: { account: "admin" } actions: ["*"] comment: "Admin has full access to everything." - match: { account: "" } actions: ["pull"] comment: "Anonymous users can pull" ``` -------------------------------- ### MongoDB ACL Entry Structure Example Source: https://github.com/cesanta/docker_auth/blob/main/docs/Backend_MongoDB.md An example of an ACL entry structure suitable for import into MongoDB. It includes a sequence number, match criteria, actions, and a comment. ```json {"seq": 10, "match" : {"account" : "admin"}, "actions" : ["*"], "comment" : "Admin has full access to everything."} ``` ```json {"seq": 11, "match" : {"labels": {"group": "admin"}}, "actions" : ["*"], "comment" : "Admin group members have full access to everything"} ``` ```json {"seq": 20, "match" : {"account" : "test", "name" : "test-*"}, "actions" : ["*"], "comment" : "User \"test\" has full access to test-* images but nothing else. (1)"} ``` ```json {"seq": 30, "match" : {"account" : "test"}, "actions" : [], "comment" : "User \"test\" has full access to test-* images but nothing else. (2)"} ``` ```json {"seq": 40, "match" : {"account" : "/.+/", "name" : "${account}/*"}, "actions" : ["*"], "comment" : "All logged in users can push all images that are in a namespace beginning with their name"} ``` ```json {"seq": 50, "match" : {"name" : "${labels:group}-shared/*"}, "actions" : ["push", "pull"], "comment" : "Users can pull and push to the shared namespace of any group they are in"} ``` ```json {"seq": 60, "match" : {"name" : "${labels:project}/*"}, "actions" : ["push", "pull"], "comment" : "Users can pull and push to to namespaces matching projects they are assigned to"} ``` ```json {"seq": 70, "match" : {"account" : "/.+/"}, "actions" : ["pull"], "comment" : "All logged in users can pull all images."} ``` ```json {"seq": 80, "match" : {"account" : "", "name" : "hello-world"}, "actions" : ["pull"], "comment" : "Anonymous users can pull \"hello-world\"."} ``` -------------------------------- ### Docker Compose Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md A sample Docker Compose configuration for deploying the Docker Auth service, including port mapping, volume mounts for configuration and logs, and environment variables for logging. ```yaml version: '3' services: docker_auth: image: cesanta/docker_auth:latest ports: - "5001:5001" volumes: - ./auth_config.yml:/config/auth_config.yml:ro - ./certs:/etc/docker_auth:ro - docker_auth_logs:/logs command: /config/auth_config.yml environment: - GOLOG_LOGTOSTDERR=1 - GOLOG_LEVEL=2 volumes: docker_auth_logs: ``` -------------------------------- ### User Record with Labels Source: https://github.com/cesanta/docker_auth/blob/main/docs/Labels.md Example of a user record containing multiple labels for group, project, and tier. ```json { "username" : "busy-guy", "password" : "$2y$05$B.x046DV3bvuwFgn0I42F.W/SbRU5fUoCbCGtjFl7S33aCUHNBxbq", "labels" : { "group" : [ "web", "webdev" ], "project" : [ "website", "api" ], "tier" : [ "frontend", "backend" ] } } ``` -------------------------------- ### Google Authentication Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Creates an authenticator for Google Sign-In and OAuth2. Requires a GoogleAuthConfig struct containing domain, client ID, client secret, and token storage configuration. Supports LevelDB, Google Cloud Storage, or Redis for token storage. ```Go googleConfig := &authn.GoogleAuthConfig{ Domain: "example.com", ClientId: "123456789-abc.apps.googleusercontent.com", ClientSecret: "secret", LevelTokenDB: &authn.LevelDBStoreConfig{ Path: "/data/google_tokens.ldb", }, HTTPTimeout: 10 * time.Second, } googleAuth, err := authn.NewGoogleAuth(googleConfig) if err != nil { log.Fatal(err) } ``` -------------------------------- ### ACL with Single Label Placeholder Source: https://github.com/cesanta/docker_auth/blob/main/docs/Labels.md An example ACL using a label placeholder to match projects assigned to a user. ```json { "match": { "name": "${labels:project}/*" }, "actions": [ "push", "pull" ], "comment": "Users can push to any project they are assigned to" } ``` -------------------------------- ### Authenticate User Credentials Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-server.md Example of using the Authenticate method to verify user credentials against configured authenticators. Handles success, failure, and potential errors during authentication. ```go authRequest := &authRequest{ Account: "myuser", Password: api.PasswordString("password123"), } success, labels, err := authServer.Authenticate(authRequest) if err != nil { // Handle error } if !success { // Authentication failed } ``` -------------------------------- ### GET / Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/endpoints.md Retrieves the server information, which includes HTML content with login options. The response content varies based on enabled authentication methods. ```APIDOC ## GET / ### Description Returns an HTML page with login options. The content of the page dynamically changes based on the enabled authentication providers (Google, GitHub, OIDC, GitLab). ### Method GET ### Endpoint / ### Parameters None ### Request Example None ### Response #### Success Response (200) - **Content-Type**: `text/html` - The HTML content will contain links or redirects based on enabled authentication methods. #### Response Example (HTML content) #### Redirect Response (301) - **Location**: Redirects to the appropriate login endpoint (e.g., `/github_auth`). ### Status Codes - `200` Success (HTML response) - `301` Redirect to login endpoint ``` -------------------------------- ### YAML Configuration Structure Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-config.md Example of the top-level structure for the YAML configuration file. This defines settings for the HTTP server, token generation, and various authentication/authorization providers. ```yaml # HTTP server configuration server: addr: ":5001" net: "tcp" path_prefix: "" certificate: "/path/to/cert.pem" key: "/path/to/key.pem" ``` -------------------------------- ### Server Functions Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/README.md Provides functions for creating and managing the authentication server. These include initializing a new server with configuration, loading configuration from a file, and starting the server. ```APIDOC ### Server - `NewAuthServer(c *Config) (*AuthServer, error)` - Create auth server - `LoadConfig(path string) (*Config, error)` - Load configuration - `ServeOnce(c *Config, cf string) (*AuthServer, *http.Server)` - Start server once ``` -------------------------------- ### Run Docker Registry Authentication Server Source: https://github.com/cesanta/docker_auth/blob/main/README.md Example command to run the docker_auth server using a Docker container. It maps ports, mounts configuration and log directories, and specifies the configuration file path. ```bash $ docker run \ --rm -it --name docker_auth -p 5001:5001 \ -v /path/to/config_dir:/config:ro \ -v /var/log/docker_auth:/logs \ cesanta/docker_auth:1 /config/auth_config.yml ``` -------------------------------- ### Static User Authentication Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Creates an authenticator that validates against a static user map. The map includes usernames, their passwords (as bcrypt hashes), and optional labels. Anonymous access can be configured with an empty username. ```Go users := map[string]*authn.Requirements{ "admin": { Password: (*api.PasswordString)("$2y$05$LO.vzwpWC5LZGqThvEfznu8qhb5SGqvBSWY1J3yZ4AxtMRZ3kN5jC"), Labels: api.Labels{ "role": []string{"admin"}, }, }, "user": { Password: (*api.PasswordString)("$2y$05$WuwBasGDAgr.QCbGIjKJaep4dhxeai9gNZdmBnQXqpKly57oNutya"), }, "": {}, // Anonymous access } staticAuth := authn.NewStaticUserAuth(users) ``` -------------------------------- ### Test Helm Chart Template Rendering Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Render the templates for the docker-auth Helm chart without actually installing it, useful for debugging. ```bash helm template test-release chart/docker-auth ``` -------------------------------- ### Static ACL Configuration Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md Defines static Access Control Lists (ACLs) for repository access. Use this for simple, predefined access rules. ```yaml acl: - match: account: "admin" type: "repository" name: "*" actions: ["*"] comment: "Admins can do anything" - match: type: "repository" name: "public" actions: ["pull"] comment: "Anyone can pull public repos" - match: account: "user" type: "repository" name: "user/*" actions: ["pull", "push"] ``` -------------------------------- ### Docker + Kubernetes ConfigMap Configuration Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-config.md Example of how to configure Docker Auth within a Kubernetes ConfigMap, including server, token, and LDAP settings. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: docker-auth-config data: auth_config.yml: | server: addr: ":5001" certificate: "/etc/docker_auth/certs/server.pem" key: "/etc/docker_auth/certs/server.key" token: issuer: "My Docker Auth" expiration: 900 ldap_auth: addr: "ldap.example.com:389" base: "dc=example,dc=com" bind_dn: "cn=admin,dc=example,dc=com" bind_password_file: "/etc/docker_auth/secrets/ldap_password" ``` -------------------------------- ### Get Application URL (Ingress Enabled) Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/templates/NOTES.txt If ingress is enabled, this snippet shows how to construct the application URL based on ingress hosts and paths. ```go-template {{- if .Values.ingress.enabled }} {{- range .Values.ingress.hosts }} {{- range .paths }} http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $.host }}{{ .path }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### Get Application URL (ClusterIP Service) Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/templates/NOTES.txt If the service type is ClusterIP, this command retrieves the pod name and then uses port-forwarding to access the application locally. ```bash export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "docker-auth.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") echo "Visit http://127.0.0.1:8080 to use your application" kubectl port-forward $POD_NAME 8080:80 ``` -------------------------------- ### User Record for User-Based Access Control Source: https://github.com/cesanta/docker_auth/blob/main/docs/Labels.md Example user record defining specific access rights through 'full-access' and 'read-only-access' labels. ```json { "username" : "test-user", "labels" : { "full-access" : [ "test/*" ], "read-only-access" : [ "prod/*" ] } } ``` -------------------------------- ### Add Helm Repository Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Adds the Cesanta Helm repository and updates the local repository cache. This is a prerequisite for installing the docker_auth chart. ```bash helm repo add cesanta https://cesanta.github.io/docker_auth/ helm repo update ``` -------------------------------- ### Get Application URL (NodePort Service) Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/templates/NOTES.txt When the service type is NodePort, this command exports the NodePort and then constructs the application URL using the Node IP. ```bash export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "docker-auth.fullname" . }}) export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT ``` -------------------------------- ### Get Application URL (LoadBalancer Service) Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/templates/NOTES.txt For LoadBalancer services, this snippet retrieves the LoadBalancer IP and constructs the application URL. It also provides a command to monitor the service status. ```bash NOTE: It may take a few minutes for the LoadBalancer IP to be available. You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "docker-auth.fullname" . }}' export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "docker-auth.fullname" . }} -o jsonpath='{.status.loadBalancer.ingress[0].ip}') echo http://$SERVICE_IP:{{ .Values.service.port }} ``` -------------------------------- ### JWT Payload (Claims) Example Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/overview.md Example of the payload section in a JWT token, containing claims like issuer, subject, audience, expiration, and access permissions. ```json { "iss": "Docker Auth Server", "sub": "username", "aud": "Docker registry", "exp": 1705322400, "iat": 1705321500, "nbf": 1705321490, "jti": "unique-id", "access": [ { "type": "repository", "name": "myrepo", "actions": ["pull", "push"] } ] } ``` -------------------------------- ### GET /gitlab_auth - GitLab OAuth2 Callback Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/MANIFEST.md Handles the callback from GitLab OAuth2 authentication flow. ```APIDOC ## GET /gitlab_auth - GitLab OAuth2 Callback ### Description Handles the callback from GitLab OAuth2 authentication flow. ### Method GET ### Endpoint /gitlab_auth ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from GitLab. - **state** (string) - Optional - The state parameter used to maintain state between the request and callback. ### Response #### Success Response (200) - **token** (string) - The authentication token obtained after successful OAuth. #### Response Example { "token": "generated_jwt_token" } ``` -------------------------------- ### Load Server Configuration Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-config.md Loads the server configuration from a YAML file. Use this to initialize the auth server with custom settings. ```go config, err := server.LoadConfig("/etc/docker_auth/config.yml") if err != nil { log.Fatal(err) } // Use config to create auth server authServer, err := server.NewAuthServer(config) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Load X.509 Certificate and Key Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Loads an X.509 certificate and private key pair. Ensure both cert and key files are provided, valid, and the key matches the certificate. ```go tlsConfig.Certificates[0], err = tls.LoadX509KeyPair( c.Server.CertFile, c.Server.KeyFile, ) ``` -------------------------------- ### GET /github_auth - GitHub OAuth2 Callback Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/MANIFEST.md Handles the callback from GitHub OAuth2 authentication flow. ```APIDOC ## GET /github_auth - GitHub OAuth2 Callback ### Description Handles the callback from GitHub OAuth2 authentication flow. ### Method GET ### Endpoint /github_auth ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from GitHub. - **state** (string) - Optional - The state parameter used to maintain state between the request and callback. ### Response #### Success Response (200) - **token** (string) - The authentication token obtained after successful OAuth. #### Response Example { "token": "generated_jwt_token" } ``` -------------------------------- ### GET /google_auth - Google OAuth2 Callback Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/MANIFEST.md Handles the callback from Google OAuth2 authentication flow. ```APIDOC ## GET /google_auth - Google OAuth2 Callback ### Description Handles the callback from Google OAuth2 authentication flow. ### Method GET ### Endpoint /google_auth ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from Google. - **state** (string) - Optional - The state parameter used to maintain state between the request and callback. ### Response #### Success Response (200) - **token** (string) - The authentication token obtained after successful OAuth. #### Response Example { "token": "generated_jwt_token" } ``` -------------------------------- ### GET /oidc_auth - OIDC Provider Callback Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/MANIFEST.md Handles the callback from an OpenID Connect (OIDC) provider authentication flow. ```APIDOC ## GET /oidc_auth - OIDC Provider Callback ### Description Handles the callback from an OpenID Connect (OIDC) provider authentication flow. ### Method GET ### Endpoint /oidc_auth ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from the OIDC provider. - **state** (string) - Optional - The state parameter used to maintain state between the request and callback. ### Response #### Success Response (200) - **token** (string) - The authentication token obtained after successful OIDC authentication. #### Response Example { "token": "generated_jwt_token" } ``` -------------------------------- ### Build Docker Auth with Version Information Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Builds the Docker Auth binary with custom version and build ID using Go's linker flags. ```bash go build -ldflags="-X main.Version=1.0.0 -X main.BuildID=abc123" ``` -------------------------------- ### GET / - Index Page Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/MANIFEST.md Serves the index page of the authentication service. Typically used for health checks or basic information. ```APIDOC ## GET / - Index Page ### Description Serves the index page of the authentication service. Typically used for health checks or basic information. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **message** (string) - A welcome message or status indicator. #### Response Example { "message": "Welcome to Docker Auth Service" } ``` -------------------------------- ### Configure External Program Authenticator Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Creates an authenticator that delegates to an external program. Requires an ExtAuthConfig struct specifying the program path and arguments. ```go type ExtAuthConfig struct { Program string // Path to executable Args []string // Command line arguments } ``` ```go extAuthConfig := &authn.ExtAuthConfig{ Program: "/usr/local/bin/ext_auth.sh", Args: []string{}, } extAuth := authn.NewExtAuth(extAuthConfig) ``` -------------------------------- ### Serve HTTP Requests with AuthServer Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-server.md Shows how to integrate the AuthServer with the standard Go HTTP server. This allows the server to handle incoming requests for authentication and authorization. ```go // Use with net/http http.ListenAndServe(":5001", authServer) // Or with custom server configuration server := &http.Server{ Addr: ":5001", Handler: authServer, } server.ListenAndServe() ``` -------------------------------- ### ServerConfig Structure Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/types.md Defines network and TLS settings for the authentication server. Use this to configure listening address, network type, TLS certificates, and security versions. ```go type ServerConfig struct { ListenAddress string Net string PathPrefix string RealIPHeader string RealIPPos int CertFile string KeyFile string HSTS bool TLSMinVersion string TLSCurvePreferences []string TLSCipherSuites []string LetsEncrypt LetsEncryptConfig } ``` -------------------------------- ### Package Helm Chart Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Create a versioned chart archive (.tgz) for the docker-auth Helm chart. ```bash helm package chart/docker-auth ``` -------------------------------- ### ACL with Multiple Label Placeholders Source: https://github.com/cesanta/docker_auth/blob/main/docs/Labels.md Demonstrates an ACL using multiple label placeholders to match combinations of project and group, and tier. ```json { "match": { "name": "${labels:project}/${labels:group}-${labels:tier}" }, "actions": [ "push", "pull" ], "comment": "Contrived multiple label match rule" } ``` -------------------------------- ### NewAuthServer Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-server.md Creates a new authentication and authorization server instance with the specified configuration. It requires a valid configuration object containing authenticators and authorizers. ```APIDOC ## NewAuthServer ### Description Creates a new authentication and authorization server with the specified configuration. ### Signature `NewAuthServer(c *Config) (*AuthServer, error)` ### Parameters #### Path Parameters - **c** (*Config) - Required - Server configuration containing authenticators and authorizers ### Returns - **AuthServer** (*AuthServer) - Initialized authentication server - **error** (error) - Error if initialization fails (e.g., invalid authenticator configuration) ### Example ```go config, err := server.LoadConfig("auth_config.yml") if err != nil { log.Fatal(err) } authServer, err := server.NewAuthServer(config) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### LetsEncryptConfig Structure Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/types.md Settings for integrating with Let's Encrypt for automatic TLS certificate management. Configure the host and email for certificate issuance. ```go type LetsEncryptConfig struct { Host string Email string CacheDir string } ``` -------------------------------- ### Configure XORM SQL Database Authenticator Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Creates an authenticator for validating users against SQL databases (MySQL, PostgreSQL, SQLite) using XORM. Requires an XormAuthnConfig struct with driver, connection string, and table/column details. ```go type XormAuthnConfig struct { Driver string // Database driver: "mysql", "postgres", "sqlite3" ConnectString string // Connection string UserTable string // Table name containing users IdColumn string // Column for user ID PasswordColumn string // Column for password hash } ``` -------------------------------- ### MongoDB Auth Entry Structure Source: https://github.com/cesanta/docker_auth/blob/main/docs/Backend_MongoDB.md An example of a single dictionary representing an auth entry in MongoDB. It includes username, a BCrypt hashed password, and optional labels. ```json { "username" : "admin", "password" : "$2y$05$B.x046DV3bvuwFgn0I42F.W/SbRU5fUoCbCGtjFl7S33aCUHNBxbq", "labels" : { "group" : [ "dev" ], "project": [ "website", "api" ] } } ``` -------------------------------- ### Import ACLs into MongoDB using mongoimport Source: https://github.com/cesanta/docker_auth/blob/main/docs/Backend_MongoDB.md Command to import ACL entries from a JSON file into a MongoDB collection. Ensure MongoDB is running and the mongoimport tool is installed. ```bash MONGO_IP=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' mongo-acl) mongoimport --host $MONGO_IP --db docker_auth --collection acl < reference_acl.json ``` -------------------------------- ### Authorize User Scopes Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-server.md Demonstrates how to use the Authorize method to check if a user has permissions for specific Docker resources and actions. It processes each requested scope independently. ```go ar := &authRequest{ Account: "myuser", Scopes: []authScope{ { Type: "repository", Name: "myrepo", Actions: []string{"pull", "push"}, }, }, } results, err := authServer.Authorize(ar) if err != nil { // Handle error } // results[0].autorizedActions contains allowed actions ``` -------------------------------- ### Verify Certificate Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Inspect the details of a certificate file using OpenSSL. ```bash openssl x509 -in certificate.pem -text -noout ``` -------------------------------- ### Version and Build ID Variables Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Declares global variables for storing version and build ID information. ```go var ( Version = "" BuildID = "" ) ``` -------------------------------- ### Define Access Control List (ACL) for GitHub Teams Source: https://github.com/cesanta/docker_auth/blob/main/docs/auth-methods.md Specify team-based access permissions for Docker image actions. This example grants 'pull' and 'push' actions to the 'infrastructure' team. ```yaml acl: - match: {team: "infrastructure"} actions: ["pull", "push"] comment: "Infrastructure team members can push and all images" ``` -------------------------------- ### Create LDAP Authenticator Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Use this to create an authenticator for LDAP bind. Configure server address, TLS settings, search base, filter, bind credentials, and label mappings. ```go ldapConfig := &authn.LDAPAuthConfig{ Addr: "ldap.example.com:389", TLS: "always", Base: "ou=users,dc=example,dc=com", Filter: "uid={0}", BindDN: "cn=admin,dc=example,dc=com", BindPasswordFile: "/etc/docker_auth/ldap_password.txt", LabelMaps: map[string]authn.LabelMap{ "role": { Attribute: "memberOf", ParseCN: true, }, }, } lapAuth, err := authn.NewLDAPAuth(ldapConfig) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Logging to File and Console Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Configures the Docker Auth server to log to both a specified directory and the standard error stream. ```bash docker_auth config.yml --v=2 --log_dir=/var/log/docker_auth --alsologtostderr ``` -------------------------------- ### Docker Auth HTTP Authentication Endpoint Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/overview.md This snippet shows the request and response format for the POST /auth endpoint, used to request a token with credentials. It includes example request headers, query parameters, and successful/error responses. ```http POST /auth HTTP/1.1 Host: localhost:5001 Authorization: Basic YWxhbmE6cGFzc3dvcmQ= Query: ?service=registry&scope=repository:myrepo:pull,push Response (200): { "token": "eyJ...", "access_token": "eyJ...", "expires_in": 900 } Error (401): WWW-Authenticate: Basic realm="..." ``` -------------------------------- ### Requirements Structure (Static User) Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/types.md Defines authentication requirements for static users, including password hashing and labels. Used for basic user authentication. ```go type Requirements struct { Password *api.PasswordString Labels api.Labels } ``` -------------------------------- ### Specific IP Address Binding Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Configure the server to listen on a specific IP address and port. ```yaml server: addr: "192.168.1.10:5001" ``` -------------------------------- ### Docker Registry Configuration Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/templates/NOTES.txt Configuration block for setting up a Docker registry when registry is enabled. Includes token authentication settings and realm configuration if ingress is enabled. ```yaml auth: token: autoredirect: false {{- if .Values.ingress.enabled }} {{- range .Values.ingress.hosts }} {{- range .paths }} realm: http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $.host }}{{ .path }} {{- end }} {{- end }} {{- end }} service: token-service issuer: {{ .Values.configmap.data.token.issuer }} rootcertbundle: /config/certs/{{ .Values.secret.certificateFileName }} ``` -------------------------------- ### Unix Socket Binding Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Configure the server to listen on a Unix domain socket. ```yaml server: net: "unix" addr: "/run/docker_auth.sock" ``` -------------------------------- ### LoadConfig Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-config.md Loads the server configuration from a YAML file. This function reads a YAML file from the filesystem, parses all configuration sections, validates authenticator and authorizer configurations, loads TLS certificates and signing keys, and returns a fully initialized Config structure. ```APIDOC ## LoadConfig ### Description Loads the server configuration from a YAML file. ### Function Signature `LoadConfig(path string) (*Config, error)` ### Parameters #### Path Parameters - **path** (string) - Required - Path to YAML configuration file ### Returns - **Config** (*Config) - Parsed configuration - **error** (error) - Error if file cannot be read or is invalid YAML ### Example ```go config, err := server.LoadConfig("/etc/docker_auth/config.yml") if err != nil { log.Fatal(err) } // Use config to create auth server authServer, err := server.NewAuthServer(config) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Create OpenID Connect (OIDC) Authenticator Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Use this to create an authenticator for OpenID Connect. Configure issuer URL, redirect URI, client ID, client secret, and token storage. ```go oidcConfig := &authn.OIDCAuthConfig{ Issuer: "https://auth.example.com", RedirectUrl: "https://registry.example.com/oidc_auth", ClientId: "docker-auth-client", ClientSecret: "oidc-secret", LevelTokenDB: &authn.LevelDBStoreConfig{ Path: "/data/oidc_tokens.ldb", }, HTTPTimeout: 10 * time.Second, } oidcAuth, err := authn.NewOIDCAuth(oidcConfig) if err != nil { log.Fatal(err) } ``` -------------------------------- ### NewExtAuth Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Creates an authenticator that delegates to an external program. Requires an ExtAuthConfig struct for configuration. ```APIDOC ## NewExtAuth ### Description Creates an authenticator that delegates to an external program. ### Method `NewExtAuth(c *ExtAuthConfig) api.Authenticator` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **c** (`*ExtAuthConfig`) - Required - External program configuration ### Returns - `api.Authenticator` ### ExtAuthConfig struct: - **Program** (string) - Path to executable - **Args** ([]string) - Command line arguments ### Example: ```go extAuthConfig := &authn.ExtAuthConfig{ Program: "/usr/local/bin/ext_auth.sh", Args: []string{}, } extAuth := authn.NewExtAuth(extAuthConfig) ``` ``` -------------------------------- ### Configure LDAP Authentication Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md Set up LDAP authentication by providing the server address, TLS settings, search base, and filter. Bind credentials and attribute mapping for labels can also be configured. ```yaml ldap_auth: addr: "ldap.example.com:389" tls: "always" base: "ou=users,dc=example,dc=com" filter: "uid={0}" bind_dn: "cn=admin,dc=example,dc=com" bind_password_file: "/etc/docker_auth/ldap_password" labels: role: attribute: "memberOf" parse_cn: true lower_case: true ``` -------------------------------- ### Lint Helm Chart Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Check the docker-auth Helm chart for potential issues and adherence to best practices. ```bash helm lint chart/docker-auth ``` -------------------------------- ### Autocert Manager for Let's Encrypt Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Configures an autocert manager for automatic TLS certificate acquisition and renewal via Let's Encrypt. Requires port 443 and a valid email. ```go m := &autocert.Manager{ Email: c.Server.LetsEncrypt.Email, Cache: autocert.DirCache(c.Server.LetsEncrypt.CacheDir), Prompt: autocert.AcceptTOS, } if c.Server.LetsEncrypt.Host != "" { m.HostPolicy = autocert.HostWhitelist(c.Server.LetsEncrypt.Host) } tlsConfig.GetCertificate = m.GetCertificate ``` -------------------------------- ### GoogleAuthConfig Structure Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/types.md Configuration for Google authentication. Includes client credentials, domain, and token storage options. ```go type GoogleAuthConfig struct { Domain string ClientId string ClientSecret string ClientSecretFile string LevelTokenDB *LevelDBStoreConfig GCSTokenDB *GCSStoreConfig RedisTokenDB *RedisStoreConfig HTTPTimeout time.Duration } ``` -------------------------------- ### Check Pod Logs Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Use this command to view the logs of the docker-auth pods in Kubernetes. ```bash kubectl logs -l app.kubernetes.io/name=docker-auth ``` -------------------------------- ### ExtAuthzConfig Struct Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authorizers.md Configuration for an authorizer that delegates to an external program. ```go type ExtAuthzConfig struct { Program string // Path to executable Args []string // Command line arguments } ``` -------------------------------- ### RestartableServer Struct Definition Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-main.md Defines the structure for a server that monitors configuration files and supports hot-reloading. ```go type RestartableServer struct { configFile string authServer *server.AuthServer hs *http.Server } ``` -------------------------------- ### Create GitHub Authenticator Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-authenticators.md Use this to create an authenticator for GitHub OAuth2. Configure organization, client ID, client secret, and token storage. ```go githubConfig := &authn.GitHubAuthConfig{ Organization: "myorg", ClientId: "github-client-id", ClientSecret: "github-secret", LevelTokenDB: &authn.LevelDBStoreConfig{ Path: "/data/github_tokens.ldb", }, RevalidateAfter: 1 * time.Hour, } githubAuth, err := authn.NewGitHubAuth(githubConfig) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Check Configuration Source: https://github.com/cesanta/docker_auth/blob/main/chart/docker-auth/README.md Retrieve the current configuration of the docker-auth ConfigMap in YAML format. ```bash kubectl get configmap docker-auth -o yaml ``` -------------------------------- ### XormAuthzConfig Structure Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/types.md Defines configuration parameters for Xorm-based authorization, including database driver and table names. ```go type XormAuthzConfig struct { Driver string ConnectString string AclTable string } ``` -------------------------------- ### Config Structure Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/types.md The main configuration structure for the Docker authentication service. It aggregates settings for the server, token handling, user authentication, authorization, and various external authentication providers. ```go type Config struct { Server ServerConfig Token TokenConfig Users map[string]*authn.Requirements GoogleAuth *authn.GoogleAuthConfig GitHubAuth *authn.GitHubAuthConfig OIDCAuth *authn.OIDCAuthConfig GitlabAuth *authn.GitlabAuthConfig LDAPAuth *authn.LDAPAuthConfig MongoAuth *authn.MongoAuthConfig XormAuthn *authn.XormAuthnConfig ExtAuth *authn.ExtAuthConfig PluginAuthn *authn.PluginAuthnConfig ACL authz.ACL ACLMongo *authz.ACLMongoConfig ACLXorm *authz.XormAuthzConfig ExtAuthz *authz.ExtAuthzConfig PluginAuthz *authz.PluginAuthzConfig CasbinAuthz *authz.CasbinAuthzConfig } ``` -------------------------------- ### ServeHTTP Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/api-reference-server.md Implements the http.Handler interface to handle incoming HTTP requests for various authentication and authorization endpoints. ```APIDOC ## ServeHTTP ### Description Implements the `http.Handler` interface to handle incoming HTTP requests. This method serves various authentication and authorization endpoints. ### Method `ServeHTTP(rw http.ResponseWriter, req *http.Request)` ### Parameters #### Path Parameters - **rw** (http.ResponseWriter) - Required - Response writer - **req** (*http.Request) - Required - Incoming HTTP request ### Endpoints Served - `GET /` - Index page with login links - `POST /auth` - Token authentication endpoint - `POST /auth/token` - Token authentication endpoint (alternative) - `GET /google_auth` - Google OAuth2 callback (if configured) - `GET /github_auth` - GitHub OAuth2 callback (if configured) - `GET /oidc_auth` - OIDC callback (if configured) - `GET /gitlab_auth` - GitLab OAuth2 callback (if configured) ### Example ```go http.ListenAndServe(":5001", authServer) ``` ``` -------------------------------- ### Redis Token Storage Configuration (Standalone) Source: https://github.com/cesanta/docker_auth/blob/main/_autodocs/configuration.md Configures Redis for token storage using standalone options. Specify address, database, and password. ```yaml redis_token_db: redis_options: addr: "localhost:6379" db: 0 password: "redis_password" ```