main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. package main
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "math/rand"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/distribution/context"
  12. "github.com/docker/distribution/registry/api/errcode"
  13. "github.com/docker/distribution/registry/auth"
  14. _ "github.com/docker/distribution/registry/auth/htpasswd"
  15. "github.com/docker/libtrust"
  16. "github.com/gorilla/mux"
  17. )
  18. func main() {
  19. var (
  20. issuer = &TokenIssuer{}
  21. pkFile string
  22. addr string
  23. debug bool
  24. err error
  25. passwdFile string
  26. realm string
  27. cert string
  28. certKey string
  29. )
  30. flag.StringVar(&issuer.Issuer, "issuer", "distribution-token-server", "Issuer string for token")
  31. flag.StringVar(&pkFile, "key", "", "Private key file")
  32. flag.StringVar(&addr, "addr", "localhost:8080", "Address to listen on")
  33. flag.BoolVar(&debug, "debug", false, "Debug mode")
  34. flag.StringVar(&passwdFile, "passwd", ".htpasswd", "Passwd file")
  35. flag.StringVar(&realm, "realm", "", "Authentication realm")
  36. flag.StringVar(&cert, "tlscert", "", "Certificate file for TLS")
  37. flag.StringVar(&certKey, "tlskey", "", "Certificate key for TLS")
  38. flag.Parse()
  39. if debug {
  40. logrus.SetLevel(logrus.DebugLevel)
  41. }
  42. if pkFile == "" {
  43. issuer.SigningKey, err = libtrust.GenerateECP256PrivateKey()
  44. if err != nil {
  45. logrus.Fatalf("Error generating private key: %v", err)
  46. }
  47. logrus.Debugf("Using newly generated key with id %s", issuer.SigningKey.KeyID())
  48. } else {
  49. issuer.SigningKey, err = libtrust.LoadKeyFile(pkFile)
  50. if err != nil {
  51. logrus.Fatalf("Error loading key file %s: %v", pkFile, err)
  52. }
  53. logrus.Debugf("Loaded private key with id %s", issuer.SigningKey.KeyID())
  54. }
  55. if realm == "" {
  56. logrus.Fatalf("Must provide realm")
  57. }
  58. ac, err := auth.GetAccessController("htpasswd", map[string]interface{}{
  59. "realm": realm,
  60. "path": passwdFile,
  61. })
  62. if err != nil {
  63. logrus.Fatalf("Error initializing access controller: %v", err)
  64. }
  65. // TODO: Make configurable
  66. issuer.Expiration = 15 * time.Minute
  67. ctx := context.Background()
  68. ts := &tokenServer{
  69. issuer: issuer,
  70. accessController: ac,
  71. refreshCache: map[string]refreshToken{},
  72. }
  73. router := mux.NewRouter()
  74. router.Path("/token/").Methods("GET").Handler(handlerWithContext(ctx, ts.getToken))
  75. router.Path("/token/").Methods("POST").Handler(handlerWithContext(ctx, ts.postToken))
  76. if cert == "" {
  77. err = http.ListenAndServe(addr, router)
  78. } else if certKey == "" {
  79. logrus.Fatalf("Must provide certficate (-tlscert) and key (-tlskey)")
  80. } else {
  81. err = http.ListenAndServeTLS(addr, cert, certKey, router)
  82. }
  83. if err != nil {
  84. logrus.Infof("Error serving: %v", err)
  85. }
  86. }
  87. // handlerWithContext wraps the given context-aware handler by setting up the
  88. // request context from a base context.
  89. func handlerWithContext(ctx context.Context, handler func(context.Context, http.ResponseWriter, *http.Request)) http.Handler {
  90. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  91. ctx := context.WithRequest(ctx, r)
  92. logger := context.GetRequestLogger(ctx)
  93. ctx = context.WithLogger(ctx, logger)
  94. handler(ctx, w, r)
  95. })
  96. }
  97. func handleError(ctx context.Context, err error, w http.ResponseWriter) {
  98. ctx, w = context.WithResponseWriter(ctx, w)
  99. if serveErr := errcode.ServeJSON(w, err); serveErr != nil {
  100. context.GetResponseLogger(ctx).Errorf("error sending error response: %v", serveErr)
  101. return
  102. }
  103. context.GetResponseLogger(ctx).Info("application error")
  104. }
  105. var refreshCharacters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  106. const refreshTokenLength = 15
  107. func newRefreshToken() string {
  108. s := make([]rune, refreshTokenLength)
  109. for i := range s {
  110. s[i] = refreshCharacters[rand.Intn(len(refreshCharacters))]
  111. }
  112. return string(s)
  113. }
  114. type refreshToken struct {
  115. subject string
  116. service string
  117. }
  118. type tokenServer struct {
  119. issuer *TokenIssuer
  120. accessController auth.AccessController
  121. refreshCache map[string]refreshToken
  122. }
  123. type tokenResponse struct {
  124. Token string `json:"access_token"`
  125. RefreshToken string `json:"refresh_token,omitempty"`
  126. ExpiresIn int `json:"expires_in,omitempty"`
  127. }
  128. func filterAccessList(ctx context.Context, scope string, requestedAccessList []auth.Access) []auth.Access {
  129. if !strings.HasSuffix(scope, "/") {
  130. scope = scope + "/"
  131. }
  132. grantedAccessList := make([]auth.Access, 0, len(requestedAccessList))
  133. for _, access := range requestedAccessList {
  134. if access.Type == "repository" {
  135. if !strings.HasPrefix(access.Name, scope) {
  136. context.GetLogger(ctx).Debugf("Resource scope not allowed: %s", access.Name)
  137. continue
  138. }
  139. } else if access.Type == "registry" {
  140. if access.Name != "catalog" {
  141. context.GetLogger(ctx).Debugf("Unknown registry resource: %s", access.Name)
  142. continue
  143. }
  144. // TODO: Limit some actions to "admin" users
  145. } else {
  146. context.GetLogger(ctx).Debugf("Skipping unsupported resource type: %s", access.Type)
  147. continue
  148. }
  149. grantedAccessList = append(grantedAccessList, access)
  150. }
  151. return grantedAccessList
  152. }
  153. // getToken handles authenticating the request and authorizing access to the
  154. // requested scopes.
  155. func (ts *tokenServer) getToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  156. context.GetLogger(ctx).Info("getToken")
  157. params := r.URL.Query()
  158. service := params.Get("service")
  159. scopeSpecifiers := params["scope"]
  160. var offline bool
  161. if offlineStr := params.Get("offline_token"); offlineStr != "" {
  162. var err error
  163. offline, err = strconv.ParseBool(offlineStr)
  164. if err != nil {
  165. handleError(ctx, ErrorBadTokenOption.WithDetail(err), w)
  166. return
  167. }
  168. }
  169. requestedAccessList := ResolveScopeSpecifiers(ctx, scopeSpecifiers)
  170. authorizedCtx, err := ts.accessController.Authorized(ctx, requestedAccessList...)
  171. if err != nil {
  172. challenge, ok := err.(auth.Challenge)
  173. if !ok {
  174. handleError(ctx, err, w)
  175. return
  176. }
  177. // Get response context.
  178. ctx, w = context.WithResponseWriter(ctx, w)
  179. challenge.SetHeaders(w)
  180. handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail(challenge.Error()), w)
  181. context.GetResponseLogger(ctx).Info("get token authentication challenge")
  182. return
  183. }
  184. ctx = authorizedCtx
  185. username := context.GetStringValue(ctx, "auth.user.name")
  186. ctx = context.WithValue(ctx, "acctSubject", username)
  187. ctx = context.WithLogger(ctx, context.GetLogger(ctx, "acctSubject"))
  188. context.GetLogger(ctx).Info("authenticated client")
  189. ctx = context.WithValue(ctx, "requestedAccess", requestedAccessList)
  190. ctx = context.WithLogger(ctx, context.GetLogger(ctx, "requestedAccess"))
  191. grantedAccessList := filterAccessList(ctx, username, requestedAccessList)
  192. ctx = context.WithValue(ctx, "grantedAccess", grantedAccessList)
  193. ctx = context.WithLogger(ctx, context.GetLogger(ctx, "grantedAccess"))
  194. token, err := ts.issuer.CreateJWT(username, service, grantedAccessList)
  195. if err != nil {
  196. handleError(ctx, err, w)
  197. return
  198. }
  199. context.GetLogger(ctx).Info("authorized client")
  200. response := tokenResponse{
  201. Token: token,
  202. ExpiresIn: int(ts.issuer.Expiration.Seconds()),
  203. }
  204. if offline {
  205. response.RefreshToken = newRefreshToken()
  206. ts.refreshCache[response.RefreshToken] = refreshToken{
  207. subject: username,
  208. service: service,
  209. }
  210. }
  211. ctx, w = context.WithResponseWriter(ctx, w)
  212. w.Header().Set("Content-Type", "application/json")
  213. json.NewEncoder(w).Encode(response)
  214. context.GetResponseLogger(ctx).Info("get token complete")
  215. }
  216. type postTokenResponse struct {
  217. Token string `json:"access_token"`
  218. Scope string `json:"scope,omitempty"`
  219. ExpiresIn int `json:"expires_in,omitempty"`
  220. IssuedAt string `json:"issued_at,omitempty"`
  221. RefreshToken string `json:"refresh_token,omitempty"`
  222. }
  223. // postToken handles authenticating the request and authorizing access to the
  224. // requested scopes.
  225. func (ts *tokenServer) postToken(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  226. grantType := r.PostFormValue("grant_type")
  227. if grantType == "" {
  228. handleError(ctx, ErrorMissingRequiredField.WithDetail("missing grant_type value"), w)
  229. return
  230. }
  231. service := r.PostFormValue("service")
  232. if service == "" {
  233. handleError(ctx, ErrorMissingRequiredField.WithDetail("missing service value"), w)
  234. return
  235. }
  236. clientID := r.PostFormValue("client_id")
  237. if clientID == "" {
  238. handleError(ctx, ErrorMissingRequiredField.WithDetail("missing client_id value"), w)
  239. return
  240. }
  241. var offline bool
  242. switch r.PostFormValue("access_type") {
  243. case "", "online":
  244. case "offline":
  245. offline = true
  246. default:
  247. handleError(ctx, ErrorUnsupportedValue.WithDetail("unknown access_type value"), w)
  248. return
  249. }
  250. requestedAccessList := ResolveScopeList(ctx, r.PostFormValue("scope"))
  251. var subject string
  252. var rToken string
  253. switch grantType {
  254. case "refresh_token":
  255. rToken = r.PostFormValue("refresh_token")
  256. if rToken == "" {
  257. handleError(ctx, ErrorUnsupportedValue.WithDetail("missing refresh_token value"), w)
  258. return
  259. }
  260. rt, ok := ts.refreshCache[rToken]
  261. if !ok || rt.service != service {
  262. handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail("invalid refresh token"), w)
  263. return
  264. }
  265. subject = rt.subject
  266. case "password":
  267. ca, ok := ts.accessController.(auth.CredentialAuthenticator)
  268. if !ok {
  269. handleError(ctx, ErrorUnsupportedValue.WithDetail("password grant type not supported"), w)
  270. return
  271. }
  272. subject = r.PostFormValue("username")
  273. if subject == "" {
  274. handleError(ctx, ErrorUnsupportedValue.WithDetail("missing username value"), w)
  275. return
  276. }
  277. password := r.PostFormValue("password")
  278. if password == "" {
  279. handleError(ctx, ErrorUnsupportedValue.WithDetail("missing password value"), w)
  280. return
  281. }
  282. if err := ca.AuthenticateUser(subject, password); err != nil {
  283. handleError(ctx, errcode.ErrorCodeUnauthorized.WithDetail("invalid credentials"), w)
  284. return
  285. }
  286. default:
  287. handleError(ctx, ErrorUnsupportedValue.WithDetail("unknown grant_type value"), w)
  288. return
  289. }
  290. ctx = context.WithValue(ctx, "acctSubject", subject)
  291. ctx = context.WithLogger(ctx, context.GetLogger(ctx, "acctSubject"))
  292. context.GetLogger(ctx).Info("authenticated client")
  293. ctx = context.WithValue(ctx, "requestedAccess", requestedAccessList)
  294. ctx = context.WithLogger(ctx, context.GetLogger(ctx, "requestedAccess"))
  295. grantedAccessList := filterAccessList(ctx, subject, requestedAccessList)
  296. ctx = context.WithValue(ctx, "grantedAccess", grantedAccessList)
  297. ctx = context.WithLogger(ctx, context.GetLogger(ctx, "grantedAccess"))
  298. token, err := ts.issuer.CreateJWT(subject, service, grantedAccessList)
  299. if err != nil {
  300. handleError(ctx, err, w)
  301. return
  302. }
  303. context.GetLogger(ctx).Info("authorized client")
  304. response := postTokenResponse{
  305. Token: token,
  306. ExpiresIn: int(ts.issuer.Expiration.Seconds()),
  307. IssuedAt: time.Now().UTC().Format(time.RFC3339),
  308. Scope: ToScopeList(grantedAccessList),
  309. }
  310. if offline {
  311. rToken = newRefreshToken()
  312. ts.refreshCache[rToken] = refreshToken{
  313. subject: subject,
  314. service: service,
  315. }
  316. }
  317. if rToken != "" {
  318. response.RefreshToken = rToken
  319. }
  320. ctx, w = context.WithResponseWriter(ctx, w)
  321. w.Header().Set("Content-Type", "application/json")
  322. json.NewEncoder(w).Encode(response)
  323. context.GetResponseLogger(ctx).Info("post token complete")
  324. }