main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. // Command authd is the in-house multi-tenant auth IdP that powers
  2. // the M13 admin UI. It exposes:
  3. //
  4. // POST /v1/auth/login — email + password → access JWT + refresh token
  5. // POST /v1/auth/refresh — refresh token → new pair
  6. // POST /v1/auth/logout — refresh token → revoke
  7. // POST /v1/auth/magic — magic-link token + new password → session
  8. // POST /v1/users/invite — super/tenant-admin → magic link (email side-effect lives in the caller)
  9. // GET /v1/users/me — current user info
  10. // GET /health, /metrics — observability
  11. //
  12. // All endpoints are unauthenticated except /v1/users/me and
  13. // /v1/users/invite (which require a valid access JWT). The auth
  14. // path is /v1/auth/* (no JWT required to log in, naturally).
  15. //
  16. // Configuration: env vars only. See authdEnv() below.
  17. package main
  18. import (
  19. "context"
  20. cryptorand "crypto/rand"
  21. "encoding/json"
  22. "errors"
  23. "log/slog"
  24. "net/http"
  25. "os"
  26. "os/signal"
  27. "strconv"
  28. "syscall"
  29. "time"
  30. "git3.techno-world.net/lrosales/broad-announce/internal/authd"
  31. "git3.techno-world.net/lrosales/broad-announce/internal/httpserver"
  32. "git3.techno-world.net/lrosales/broad-announce/internal/observability"
  33. "git3.techno-world.net/lrosales/broad-announce/internal/postgres"
  34. )
  35. func main() {
  36. logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
  37. if err := run(logger); err != nil {
  38. logger.Error("authd exited with error", "err", err)
  39. os.Exit(1)
  40. }
  41. }
  42. func run(logger *slog.Logger) error {
  43. cfg, err := authdEnv()
  44. if err != nil {
  45. return err
  46. }
  47. logger.Info("authd starting",
  48. "env", cfg.Env, "addr", cfg.HTTPAddr,
  49. "issuer", cfg.Issuer, "access_ttl", cfg.AuthdConfig.AccessTokenTTL)
  50. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
  51. defer stop()
  52. pool, err := postgres.Connect(ctx, cfg.PostgresDSN)
  53. if err != nil {
  54. return err
  55. }
  56. defer pool.Close()
  57. // Verify the migration is applied (graceful if not — first boot
  58. // may need to run `go run ./cmd/seed` first).
  59. if err := pingSchema(ctx, pool); err != nil {
  60. logger.Warn("auth schema not yet present, login will fail", "err", err)
  61. }
  62. // Generate a JWT secret if not provided. The first-run case
  63. // (no env) gets a random secret written to a file so restarts
  64. // produce the same tokens. This is dev-only behavior; in
  65. // production the secret comes from K8s sealed-secrets.
  66. if len(cfg.JWTSecret) < 32 {
  67. if !cfg.AllowGeneratedSecret {
  68. return errors.New("BA_AUTHD_JWT_SECRET must be at least 32 bytes (set in env or sealed-secret)")
  69. }
  70. sec, err := loadOrCreateSecret(cfg.SecretFile, logger)
  71. if err != nil {
  72. return err
  73. }
  74. cfg.JWTSecret = sec
  75. }
  76. ad, err := authd.New(pool, cfg.AuthdConfig)
  77. if err != nil {
  78. return err
  79. }
  80. reg, _ := observability.NewRegistry("authd")
  81. srv := httpserver.New(httpserver.Config{
  82. Addr: cfg.HTTPAddr,
  83. ServiceName: "authd",
  84. }, logger, observability.MetricsHandler(reg))
  85. mux := srv.Mux()
  86. mux.HandleFunc("POST /v1/auth/login", loginHandler(ad, logger))
  87. mux.HandleFunc("POST /v1/auth/refresh", refreshHandler(ad, logger))
  88. mux.HandleFunc("POST /v1/auth/logout", logoutHandler(ad, logger))
  89. mux.HandleFunc("POST /v1/auth/magic", magicConsumeHandler(ad, logger))
  90. mux.HandleFunc("POST /v1/users/invite", inviteHandler(ad, logger))
  91. mux.HandleFunc("GET /v1/users/me", meHandler(ad, logger))
  92. // Start in background, wait for signal, then graceful shutdown.
  93. errCh := make(chan error, 1)
  94. go func() { errCh <- srv.Start() }()
  95. select {
  96. case err := <-errCh:
  97. return err
  98. case <-ctx.Done():
  99. logger.Info("shutdown signal received")
  100. shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
  101. defer cancel()
  102. return srv.Shutdown(shutdownCtx)
  103. }
  104. }
  105. // ---------------------------------------------------------------------------
  106. // Env loading
  107. // ---------------------------------------------------------------------------
  108. type env struct {
  109. Env string
  110. HTTPAddr string
  111. Issuer string
  112. AuthdConfig authd.Config
  113. PostgresDSN string
  114. ShutdownGrace time.Duration
  115. // JWT secret
  116. JWTSecret []byte
  117. AllowGeneratedSecret bool
  118. SecretFile string
  119. }
  120. func authdEnv() (env, error) {
  121. e := env{
  122. Env: getenvDefault("BA_ENV", "dev"),
  123. HTTPAddr: getenvDefault("BA_AUTHD_HTTP_ADDR", ":8804"),
  124. Issuer: getenvDefault("BA_AUTHD_ISSUER", "broad-announce"),
  125. PostgresDSN: os.Getenv("BA_POSTGRES_DSN"),
  126. }
  127. if s := os.Getenv("BA_AUTHD_JWT_SECRET"); s != "" {
  128. e.JWTSecret = []byte(s)
  129. }
  130. e.AllowGeneratedSecret = getenvDefault("BA_AUTHD_ALLOW_GENERATED_SECRET", "") == "1" ||
  131. os.Getenv("BA_ENV") == "dev"
  132. e.SecretFile = getenvDefault("BA_AUTHD_SECRET_FILE", "/var/run/broad-announce/authd.jwt")
  133. if t := os.Getenv("BA_AUTHD_ACCESS_TTL"); t != "" {
  134. d, err := time.ParseDuration(t)
  135. if err != nil {
  136. return e, err
  137. }
  138. e.AuthdConfig.AccessTokenTTL = d
  139. }
  140. if t := os.Getenv("BA_AUTHD_REFRESH_TTL"); t != "" {
  141. d, err := time.ParseDuration(t)
  142. if err != nil {
  143. return e, err
  144. }
  145. e.AuthdConfig.RefreshTokenTTL = d
  146. }
  147. if c := os.Getenv("BA_AUTHD_BCRYPT_COST"); c != "" {
  148. n, err := strconv.Atoi(c)
  149. if err != nil {
  150. return e, err
  151. }
  152. e.AuthdConfig.BcryptCost = n
  153. }
  154. e.AuthdConfig.JWTSecret = e.JWTSecret // may be empty; New() will reject
  155. e.AuthdConfig.Issuer = e.Issuer
  156. if e.PostgresDSN == "" {
  157. return e, errors.New("BA_POSTGRES_DSN must be set")
  158. }
  159. grace := 10 * time.Second
  160. if g := os.Getenv("BA_AUTHD_SHUTDOWN_GRACE"); g != "" {
  161. d, err := time.ParseDuration(g)
  162. if err != nil {
  163. return e, err
  164. }
  165. grace = d
  166. }
  167. e.ShutdownGrace = grace
  168. return e, nil
  169. }
  170. func getenvDefault(k, def string) string {
  171. if v := os.Getenv(k); v != "" {
  172. return v
  173. }
  174. return def
  175. }
  176. // pingSchema is a best-effort check that the auth schema is migrated.
  177. // Returns nil if the audit_log table exists, an error otherwise.
  178. func pingSchema(ctx context.Context, pool *postgres.Pool) error {
  179. row := pool.QueryRow(ctx,
  180. `SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema='auth' AND table_name='users')`)
  181. var ok bool
  182. if err := row.Scan(&ok); err != nil {
  183. return err
  184. }
  185. if !ok {
  186. return errors.New("auth.users not found; run migrations first")
  187. }
  188. return nil
  189. }
  190. // loadOrCreateSecret reads the JWT secret from disk, or generates a
  191. // random one and writes it. The file is chmod 600.
  192. func loadOrCreateSecret(path string, logger *slog.Logger) ([]byte, error) {
  193. if data, err := os.ReadFile(path); err == nil && len(data) >= 32 {
  194. return data, nil
  195. }
  196. logger.Warn("generating new JWT secret (dev-only)", "file", path)
  197. if err := os.MkdirAll(parentDir(path), 0o700); err != nil {
  198. return nil, err
  199. }
  200. secret := make([]byte, 48)
  201. if _, err := readFull(secret); err != nil {
  202. return nil, err
  203. }
  204. if err := os.WriteFile(path, secret, 0o600); err != nil {
  205. return nil, err
  206. }
  207. return secret, nil
  208. }
  209. // readFull fills b with cryptographically random bytes.
  210. func readFull(b []byte) (int, error) {
  211. return randomRead(b)
  212. }
  213. func parentDir(p string) string {
  214. for i := len(p) - 1; i >= 0; i-- {
  215. if p[i] == '/' {
  216. return p[:i]
  217. }
  218. }
  219. return "."
  220. }
  221. // randomRead is split out so tests can stub it; default uses crypto/rand.
  222. var randomRead = func(b []byte) (int, error) {
  223. return cryptorand.Read(b)
  224. }
  225. // ---------------------------------------------------------------------------
  226. // HTTP handlers
  227. // ---------------------------------------------------------------------------
  228. // clientIP pulls the IP from r.RemoteAddr, respecting X-Forwarded-For
  229. // when BA_AUTHD_TRUST_FORWARDED=1. Returns the bare IP (no port)
  230. // because the audit_log columns are INET.
  231. func clientIP(r *http.Request) string {
  232. raw := r.RemoteAddr
  233. if os.Getenv("BA_AUTHD_TRUST_FORWARDED") == "1" {
  234. if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
  235. // X-Forwarded-For is a list; first is the client
  236. if i := indexByte(xff, ','); i >= 0 {
  237. raw = xff[:i]
  238. } else {
  239. raw = xff
  240. }
  241. }
  242. }
  243. // Strip :port if present (host:port)
  244. if i := lastByte(raw, ':'); i >= 0 {
  245. // Make sure it's not part of an IPv6 address
  246. if !containsByte(raw, ']') || i > indexByte(raw, ']') {
  247. raw = raw[:i]
  248. }
  249. }
  250. return raw
  251. }
  252. func indexByte(s string, c byte) int {
  253. for i := 0; i < len(s); i++ {
  254. if s[i] == c {
  255. return i
  256. }
  257. }
  258. return -1
  259. }
  260. func lastByte(s string, c byte) int {
  261. for i := len(s) - 1; i >= 0; i-- {
  262. if s[i] == c {
  263. return i
  264. }
  265. }
  266. return -1
  267. }
  268. func containsByte(s string, c byte) bool {
  269. return indexByte(s, c) >= 0
  270. }
  271. // writeJSON writes status + JSON body. Sets Content-Type.
  272. func writeJSON(w http.ResponseWriter, status int, body any) {
  273. w.Header().Set("Content-Type", "application/json")
  274. w.WriteHeader(status)
  275. _ = json.NewEncoder(w).Encode(body)
  276. }
  277. // writeErr writes a JSON error response.
  278. func writeErr(w http.ResponseWriter, status int, code, msg string) {
  279. writeJSON(w, status, map[string]string{"error": code, "message": msg})
  280. }
  281. // --- /v1/auth/login -------------------------------------------------------
  282. type loginReq struct {
  283. Email string `json:"email"`
  284. Password string `json:"password"`
  285. }
  286. type loginResp struct {
  287. AccessToken string `json:"access_token"`
  288. RefreshToken string `json:"refresh_token"`
  289. TokenType string `json:"token_type"`
  290. ExpiresAt time.Time `json:"expires_at"`
  291. UserID string `json:"user_id"`
  292. TenantID string `json:"tenant_id,omitempty"`
  293. Role string `json:"role"`
  294. }
  295. func loginHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  296. return func(w http.ResponseWriter, r *http.Request) {
  297. var req loginReq
  298. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  299. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  300. return
  301. }
  302. if req.Email == "" || req.Password == "" {
  303. writeErr(w, http.StatusBadRequest, "bad_request", "email and password required")
  304. return
  305. }
  306. res, err := ad.Login(r.Context(), req.Email, req.Password, clientIP(r), r.UserAgent())
  307. if err != nil {
  308. if errors.Is(err, authd.ErrInvalidCredentials) || errors.Is(err, authd.ErrUserDisabled) {
  309. writeErr(w, http.StatusUnauthorized, "unauthorized", "invalid credentials")
  310. return
  311. }
  312. logger.Error("login internal error", "err", err)
  313. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  314. return
  315. }
  316. writeJSON(w, http.StatusOK, loginResp{
  317. AccessToken: res.AccessToken,
  318. RefreshToken: res.RefreshToken,
  319. TokenType: "Bearer",
  320. ExpiresAt: res.ExpiresAt,
  321. UserID: res.UserID,
  322. TenantID: res.TenantID,
  323. Role: res.Role,
  324. })
  325. }
  326. }
  327. // --- /v1/auth/refresh -----------------------------------------------------
  328. type refreshReq struct {
  329. RefreshToken string `json:"refresh_token"`
  330. }
  331. func refreshHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  332. return func(w http.ResponseWriter, r *http.Request) {
  333. var req refreshReq
  334. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  335. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  336. return
  337. }
  338. if req.RefreshToken == "" {
  339. writeErr(w, http.StatusBadRequest, "bad_request", "refresh_token required")
  340. return
  341. }
  342. res, err := ad.Refresh(r.Context(), req.RefreshToken, clientIP(r), r.UserAgent())
  343. if err != nil {
  344. if errors.Is(err, authd.ErrTokenReuse) {
  345. writeErr(w, http.StatusUnauthorized, "session_killed", "refresh token re-use detected, please log in again")
  346. return
  347. }
  348. if errors.Is(err, authd.ErrUserDisabled) {
  349. writeErr(w, http.StatusUnauthorized, "unauthorized", "user disabled")
  350. return
  351. }
  352. logger.Error("refresh internal error", "err", err)
  353. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  354. return
  355. }
  356. writeJSON(w, http.StatusOK, loginResp{
  357. AccessToken: res.AccessToken,
  358. RefreshToken: res.RefreshToken,
  359. TokenType: "Bearer",
  360. ExpiresAt: res.ExpiresAt,
  361. UserID: res.UserID,
  362. TenantID: res.TenantID,
  363. Role: res.Role,
  364. })
  365. }
  366. }
  367. // --- /v1/auth/logout ------------------------------------------------------
  368. type logoutReq struct {
  369. RefreshToken string `json:"refresh_token"`
  370. }
  371. func logoutHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  372. return func(w http.ResponseWriter, r *http.Request) {
  373. var req logoutReq
  374. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  375. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  376. return
  377. }
  378. // Resolve user id from the access JWT in the Authorization
  379. // header (best effort) so we can write the audit row.
  380. uid, _ := userIDFromAuthHeader(ad, r)
  381. if err := ad.Logout(r.Context(), req.RefreshToken, uid, clientIP(r), r.UserAgent()); err != nil {
  382. logger.Error("logout internal error", "err", err)
  383. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  384. return
  385. }
  386. writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
  387. }
  388. }
  389. // --- /v1/auth/magic -------------------------------------------------------
  390. type magicReq struct {
  391. Token string `json:"token"`
  392. NewPassword string `json:"new_password"`
  393. }
  394. func magicConsumeHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  395. return func(w http.ResponseWriter, r *http.Request) {
  396. var req magicReq
  397. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  398. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  399. return
  400. }
  401. if req.Token == "" || req.NewPassword == "" {
  402. writeErr(w, http.StatusBadRequest, "bad_request", "token and new_password required")
  403. return
  404. }
  405. if len(req.NewPassword) < 12 {
  406. writeErr(w, http.StatusBadRequest, "weak_password", "password must be at least 12 characters")
  407. return
  408. }
  409. uid, err := ad.ConsumeMagicLink(r.Context(), req.Token, clientIP(r), r.UserAgent())
  410. if err != nil {
  411. if errors.Is(err, authd.ErrMagicLinkInvalid) {
  412. writeErr(w, http.StatusUnauthorized, "invalid_link", "magic link invalid or expired")
  413. return
  414. }
  415. logger.Error("magic consume error", "err", err)
  416. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  417. return
  418. }
  419. if err := ad.SetPassword(r.Context(), uid, req.NewPassword); err != nil {
  420. logger.Error("set password error", "err", err)
  421. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  422. return
  423. }
  424. // Auto-login: return a session so the user lands on the
  425. // dashboard without a separate login round-trip.
  426. user, err := ad.Store().GetUserByID(r.Context(), uid)
  427. if err != nil {
  428. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  429. return
  430. }
  431. // We don't have the plaintext password to call Login(). The
  432. // simpler path: sign a session directly using a helper.
  433. // For now, return success and require the user to log in
  434. // normally — UX is one extra click, security is cleaner.
  435. _ = user
  436. writeJSON(w, http.StatusOK, map[string]any{
  437. "status": "ok",
  438. "user_id": uid,
  439. "message": "password set. Please log in.",
  440. })
  441. }
  442. }
  443. // --- /v1/users/invite -----------------------------------------------------
  444. type inviteReq struct {
  445. TenantSlug string `json:"tenant_slug"`
  446. Email string `json:"email"`
  447. Role string `json:"role"`
  448. }
  449. type inviteResp struct {
  450. UserID string `json:"user_id"`
  451. MagicLinkToken string `json:"magic_link_token"`
  452. ExpiresAt time.Time `json:"expires_at"`
  453. }
  454. func inviteHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  455. return func(w http.ResponseWriter, r *http.Request) {
  456. claims, err := userClaimsFromAuthHeader(ad, r)
  457. if err != nil {
  458. writeErr(w, http.StatusUnauthorized, "unauthorized", "valid access token required")
  459. return
  460. }
  461. if claims.Role != "super_admin" && claims.Role != "tenant_admin" {
  462. writeErr(w, http.StatusForbidden, "forbidden", "invite requires admin role")
  463. return
  464. }
  465. var req inviteReq
  466. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  467. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  468. return
  469. }
  470. if req.Email == "" || req.Role == "" {
  471. writeErr(w, http.StatusBadRequest, "bad_request", "email and role required")
  472. return
  473. }
  474. // Resolve tenant: super_admin can target any tenant by slug;
  475. // tenant_admin can only target their own tenant.
  476. var tenantID string
  477. if claims.Role == "super_admin" {
  478. if req.TenantSlug == "" {
  479. writeErr(w, http.StatusBadRequest, "bad_request", "tenant_slug required for super_admin")
  480. return
  481. }
  482. tenantID, err = ad.Store().TenantIDBySlug(r.Context(), req.TenantSlug)
  483. if err != nil {
  484. writeErr(w, http.StatusBadRequest, "unknown_tenant", "tenant_slug not found")
  485. return
  486. }
  487. } else {
  488. tenantID = claims.TenantID
  489. }
  490. token, uid, err := ad.InviteUser(r.Context(), tenantID, req.Email, req.Role, claims.UserID, clientIP(r), r.UserAgent())
  491. if err != nil {
  492. logger.Error("invite error", "err", err)
  493. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  494. return
  495. }
  496. writeJSON(w, http.StatusOK, inviteResp{
  497. UserID: uid,
  498. MagicLinkToken: token,
  499. })
  500. }
  501. }
  502. // --- /v1/users/me ---------------------------------------------------------
  503. func meHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  504. return func(w http.ResponseWriter, r *http.Request) {
  505. claims, err := userClaimsFromAuthHeader(ad, r)
  506. if err != nil {
  507. writeErr(w, http.StatusUnauthorized, "unauthorized", "valid access token required")
  508. return
  509. }
  510. u, err := ad.Store().GetUserByID(r.Context(), claims.UserID)
  511. if err != nil {
  512. writeErr(w, http.StatusInternalServerError, "internal", "user lookup failed")
  513. return
  514. }
  515. writeJSON(w, http.StatusOK, map[string]any{
  516. "user_id": u.ID,
  517. "email": u.Email,
  518. "role": u.Role,
  519. "status": u.Status,
  520. "tenant_id": u.TenantID,
  521. "display_name": u.DisplayName,
  522. })
  523. }
  524. }
  525. // --- helpers for bearer auth ----------------------------------------------
  526. // userIDFromAuthHeader extracts the user id from the access token in
  527. // the Authorization header. Returns ("", err) if absent or invalid.
  528. func userIDFromAuthHeader(ad *authd.Authd, r *http.Request) (string, error) {
  529. tok, err := bearerFromAuthHeader(r)
  530. if err != nil {
  531. return "", err
  532. }
  533. claims, err := ad.VerifyAccessToken(tok)
  534. if err != nil {
  535. return "", err
  536. }
  537. return claims.UserID, nil
  538. }
  539. func userClaimsFromAuthHeader(ad *authd.Authd, r *http.Request) (*authd.AccessClaims, error) {
  540. tok, err := bearerFromAuthHeader(r)
  541. if err != nil {
  542. return nil, err
  543. }
  544. return ad.VerifyAccessToken(tok)
  545. }
  546. func bearerFromAuthHeader(r *http.Request) (string, error) {
  547. h := r.Header.Get("Authorization")
  548. if h == "" {
  549. return "", errors.New("missing Authorization header")
  550. }
  551. const prefix = "Bearer "
  552. if len(h) <= len(prefix) || h[:len(prefix)] != prefix {
  553. return "", errors.New("Authorization must be 'Bearer <token>'")
  554. }
  555. return h[len(prefix):], nil
  556. }