| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package caddyauth |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "net/http" |
| 20 | |
| 21 | "go.uber.org/zap" |
| 22 | "go.uber.org/zap/zapcore" |
| 23 | |
| 24 | "github.com/caddyserver/caddy/v2" |
| 25 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 26 | ) |
| 27 | |
| 28 | func init() { |
| 29 | caddy.RegisterModule(Authentication{}) |
| 30 | } |
| 31 | |
| 32 | // Authentication is a middleware which provides user authentication. |
| 33 | // Rejects requests with HTTP 401 if the request is not authenticated. |
| 34 | // |
| 35 | // After a successful authentication, the placeholder |
| 36 | // `{http.auth.user.id}` will be set to the username, and also |
| 37 | // `{http.auth.user.*}` placeholders may be set for any authentication |
| 38 | // modules that provide user metadata. |
| 39 | // |
| 40 | // If authentication is rejected but a provider returns user information, |
| 41 | // the placeholder `{http.auth.candidate.id}` will be set to the candidate |
| 42 | // username, and also `{http.auth.candidate.*}` placeholders may be set |
| 43 | // for candidate user metadata. Candidate placeholders do not represent a |
| 44 | // successfully authenticated principal. |
| 45 | // |
| 46 | // In case of an error, the placeholder `{http.auth.<provider>.error}` |
| 47 | // will be set to the error message returned by the authentication |
| 48 | // provider. |
| 49 | // |
| 50 | // Its API is still experimental and may be subject to change. |
| 51 | type Authentication struct { |
| 52 | // A set of authentication providers. If none are specified, |
| 53 | // all requests will always be unauthenticated. |
| 54 | ProvidersRaw caddy.ModuleMap `json:"providers,omitempty" caddy:"namespace=http.authentication.providers"` |
| 55 | |
| 56 | Providers map[string]Authenticator `json:"-"` |
| 57 | |
| 58 | logger *zap.Logger |
| 59 | } |
| 60 | |
| 61 | // CaddyModule returns the Caddy module information. |
| 62 | func (Authentication) CaddyModule() caddy.ModuleInfo { |
| 63 | return caddy.ModuleInfo{ |
| 64 | ID: "http.handlers.authentication", |
| 65 | New: func() caddy.Module { return new(Authentication) }, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // Provision sets up an Authentication module by initializing its logger, |
| 70 | // loading and registering all configured authentication providers. |
| 71 | func (a *Authentication) Provision(ctx caddy.Context) error { |
| 72 | a.logger = ctx.Logger() |
| 73 | a.Providers = make(map[string]Authenticator) |
| 74 | mods, err := ctx.LoadModule(a, "ProvidersRaw") |
| 75 | if err != nil { |
| 76 | return fmt.Errorf("loading authentication providers: %v", err) |
| 77 | } |
| 78 | for modName, modIface := range mods.(map[string]any) { |
| 79 | a.Providers[modName] = modIface.(Authenticator) |
| 80 | } |
| 81 | return nil |
| 82 | } |
| 83 | |
| 84 | func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { |
| 85 | repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 86 | var user User |
| 87 | var candidate User |
| 88 | var hasCandidate bool |
| 89 | var authed bool |
| 90 | var err error |
| 91 | for provName, prov := range a.Providers { |
| 92 | user, authed, err = prov.Authenticate(w, r) |
| 93 | if err != nil { |
| 94 | if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil { |
| 95 | c.Write(zap.String("provider", provName), zap.Error(err)) |
| 96 | } |
| 97 | // Set the error from the authentication provider in a placeholder, |
| 98 | // so it can be used in the handle_errors directive. |
| 99 | repl.Set("http.auth."+provName+".error", err.Error()) |
| 100 | continue |
| 101 | } |
| 102 | if authed { |
| 103 | break |
| 104 | } |
| 105 | if userHasInfo(user) { |
| 106 | candidate = user |
| 107 | hasCandidate = true |
| 108 | } |
| 109 | } |
| 110 | if !authed { |
| 111 | if hasCandidate { |
| 112 | setAuthUserPlaceholders(repl, "http.auth.candidate", candidate) |
| 113 | } |
| 114 | return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated")) |
| 115 | } |
| 116 | |
| 117 | setAuthUserPlaceholders(repl, "http.auth.user", user) |
| 118 | |
| 119 | return next.ServeHTTP(w, r) |
| 120 | } |
| 121 | |
| 122 | func userHasInfo(user User) bool { |
| 123 | return user.ID != "" || len(user.Metadata) > 0 |
| 124 | } |
| 125 | |
| 126 | func setAuthUserPlaceholders(repl *caddy.Replacer, namespace string, user User) { |
| 127 | repl.Set(namespace+".id", user.ID) |
| 128 | for k, v := range user.Metadata { |
| 129 | repl.Set(namespace+"."+k, v) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | // Authenticator is a type which can authenticate a request. |
| 134 | // If a request was not authenticated, it returns false. An |
| 135 | // error is only returned if authenticating the request fails |
| 136 | // for a technical reason (not for bad/missing credentials). |
| 137 | type Authenticator interface { |
| 138 | Authenticate(http.ResponseWriter, *http.Request) (User, bool, error) |
| 139 | } |
| 140 | |
| 141 | // User represents an authenticated user. |
| 142 | type User struct { |
| 143 | // The ID of the authenticated user. |
| 144 | ID string |
| 145 | |
| 146 | // Any other relevant data about this |
| 147 | // user. Keys should be adhere to Caddy |
| 148 | // conventions (snake_casing), as all |
| 149 | // keys will be made available as |
| 150 | // placeholders. |
| 151 | Metadata map[string]string |
| 152 | } |
| 153 | |
| 154 | // Interface guards |
| 155 | var ( |
| 156 | _ caddy.Provisioner = (*Authentication)(nil) |
| 157 | _ caddyhttp.MiddlewareHandler = (*Authentication)(nil) |
| 158 | ) |