main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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.Handle("POST /v1/users/invite", ad.RequireRole("super_admin", "tenant_admin")(inviteHandler(ad, logger)))
  91. mux.Handle("GET /v1/users/me", ad.RequireAuth(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 — logout is allowed without a valid
  380. // token so a user with a dead access can still kill their
  381. // refresh). If no claims, audit logs "user_id=''".
  382. uid := ""
  383. if c := authd.ClaimsFromContext(r.Context()); c != nil {
  384. uid = c.UserID
  385. }
  386. if err := ad.Logout(r.Context(), req.RefreshToken, uid, clientIP(r), r.UserAgent()); err != nil {
  387. logger.Error("logout internal error", "err", err)
  388. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  389. return
  390. }
  391. writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
  392. }
  393. }
  394. // --- /v1/auth/magic -------------------------------------------------------
  395. type magicReq struct {
  396. Token string `json:"token"`
  397. NewPassword string `json:"new_password"`
  398. }
  399. func magicConsumeHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  400. return func(w http.ResponseWriter, r *http.Request) {
  401. var req magicReq
  402. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  403. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  404. return
  405. }
  406. if req.Token == "" || req.NewPassword == "" {
  407. writeErr(w, http.StatusBadRequest, "bad_request", "token and new_password required")
  408. return
  409. }
  410. if len(req.NewPassword) < 12 {
  411. writeErr(w, http.StatusBadRequest, "weak_password", "password must be at least 12 characters")
  412. return
  413. }
  414. uid, err := ad.ConsumeMagicLink(r.Context(), req.Token, clientIP(r), r.UserAgent())
  415. if err != nil {
  416. if errors.Is(err, authd.ErrMagicLinkInvalid) {
  417. writeErr(w, http.StatusUnauthorized, "invalid_link", "magic link invalid or expired")
  418. return
  419. }
  420. logger.Error("magic consume error", "err", err)
  421. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  422. return
  423. }
  424. if err := ad.SetPassword(r.Context(), uid, req.NewPassword); err != nil {
  425. logger.Error("set password error", "err", err)
  426. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  427. return
  428. }
  429. // Auto-login: return a session so the user lands on the
  430. // dashboard without a separate login round-trip.
  431. user, err := ad.Store().GetUserByID(r.Context(), uid)
  432. if err != nil {
  433. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  434. return
  435. }
  436. // We don't have the plaintext password to call Login(). The
  437. // simpler path: sign a session directly using a helper.
  438. // For now, return success and require the user to log in
  439. // normally — UX is one extra click, security is cleaner.
  440. _ = user
  441. writeJSON(w, http.StatusOK, map[string]any{
  442. "status": "ok",
  443. "user_id": uid,
  444. "message": "password set. Please log in.",
  445. })
  446. }
  447. }
  448. // --- /v1/users/invite -----------------------------------------------------
  449. type inviteReq struct {
  450. TenantSlug string `json:"tenant_slug"`
  451. Email string `json:"email"`
  452. Role string `json:"role"`
  453. }
  454. type inviteResp struct {
  455. UserID string `json:"user_id"`
  456. MagicLinkToken string `json:"magic_link_token"`
  457. ExpiresAt time.Time `json:"expires_at"`
  458. }
  459. func inviteHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  460. return func(w http.ResponseWriter, r *http.Request) {
  461. claims := authd.ClaimsFromContext(r.Context())
  462. if claims == nil {
  463. // Should never happen — RequireAuth/RequireRole ensured
  464. // this. Belt-and-suspenders.
  465. writeErr(w, http.StatusUnauthorized, "unauthorized", "claims missing")
  466. return
  467. }
  468. var req inviteReq
  469. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  470. writeErr(w, http.StatusBadRequest, "bad_request", "invalid json")
  471. return
  472. }
  473. if req.Email == "" || req.Role == "" {
  474. writeErr(w, http.StatusBadRequest, "bad_request", "email and role required")
  475. return
  476. }
  477. // Resolve tenant: super_admin can target any tenant by slug;
  478. // tenant_admin can only target their own tenant.
  479. var (
  480. tenantID string
  481. err error
  482. )
  483. if claims.Role == "super_admin" {
  484. if req.TenantSlug == "" {
  485. writeErr(w, http.StatusBadRequest, "bad_request", "tenant_slug required for super_admin")
  486. return
  487. }
  488. tenantID, err = ad.Store().TenantIDBySlug(r.Context(), req.TenantSlug)
  489. if err != nil {
  490. writeErr(w, http.StatusBadRequest, "unknown_tenant", "tenant_slug not found")
  491. return
  492. }
  493. } else {
  494. tenantID = claims.TenantID
  495. }
  496. token, uid, err := ad.InviteUser(r.Context(), tenantID, req.Email, req.Role, claims.UserID, clientIP(r), r.UserAgent())
  497. if err != nil {
  498. logger.Error("invite error", "err", err)
  499. writeErr(w, http.StatusInternalServerError, "internal", "internal error")
  500. return
  501. }
  502. writeJSON(w, http.StatusOK, inviteResp{
  503. UserID: uid,
  504. MagicLinkToken: token,
  505. })
  506. }
  507. }
  508. // --- /v1/users/me ---------------------------------------------------------
  509. func meHandler(ad *authd.Authd, logger *slog.Logger) http.HandlerFunc {
  510. return func(w http.ResponseWriter, r *http.Request) {
  511. claims := authd.ClaimsFromContext(r.Context())
  512. if claims == nil {
  513. writeErr(w, http.StatusUnauthorized, "unauthorized", "claims missing")
  514. return
  515. }
  516. u, err := ad.Store().GetUserByID(r.Context(), claims.UserID)
  517. if err != nil {
  518. writeErr(w, http.StatusInternalServerError, "internal", "user lookup failed")
  519. return
  520. }
  521. writeJSON(w, http.StatusOK, map[string]any{
  522. "user_id": u.ID,
  523. "email": u.Email,
  524. "role": u.Role,
  525. "status": u.Status,
  526. "tenant_id": u.TenantID,
  527. "display_name": u.DisplayName,
  528. })
  529. }
  530. }