jwkshared.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Package authd — jwkshared.go: helper for services that only need
  2. // the JWT verifier side of authd (not the full IdP). routerd,
  3. // archiverd, deliverd-*, admind all use this to construct the
  4. // Authd from env vars without repeating the JWTSecret / Issuer
  5. // setup in each cmd/.
  6. //
  7. // Threading: NewFromEnv is safe to call once at startup; the
  8. // returned *Authd is safe for concurrent use.
  9. package authd
  10. import (
  11. "errors"
  12. "fmt"
  13. "os"
  14. "time"
  15. )
  16. // NewFromEnv constructs an Authd for use as a JWT verifier only.
  17. // It reads:
  18. //
  19. // BA_AUTHD_JWT_SECRET (required)
  20. // BA_AUTHD_ISSUER (default "broad-announce")
  21. //
  22. // AccessTokenTTL is set to 1 minute as a placeholder; this Authd
  23. // never issues tokens (no pool is set), so the TTL is unused. The
  24. // VerifyAccessToken call only needs JWTSecret + Issuer.
  25. func NewFromEnv() (*Authd, error) {
  26. secret := os.Getenv("BA_AUTHD_JWT_SECRET")
  27. if secret == "" {
  28. return nil, errors.New("authd: BA_AUTHD_JWT_SECRET is required for JWT verification")
  29. }
  30. issuer := os.Getenv("BA_AUTHD_ISSUER")
  31. if issuer == "" {
  32. issuer = "broad-announce"
  33. }
  34. cfg := Config{
  35. JWTSecret: []byte(secret),
  36. Issuer: issuer,
  37. AccessTokenTTL: 1 * time.Minute, // placeholder, not used
  38. }
  39. return New(nil, cfg)
  40. }
  41. // MustNewFromEnv is like NewFromEnv but panics on error. Use only
  42. // in main() where a config error is a fatal startup failure.
  43. func MustNewFromEnv() *Authd {
  44. a, err := NewFromEnv()
  45. if err != nil {
  46. panic(fmt.Sprintf("authd: %v", err))
  47. }
  48. return a
  49. }
  50. // EnvEnabled reports whether BA_AUTHD_JWT_SECRET is set. Services
  51. // that wire the gate conditionally use this to decide whether to
  52. // register the JWT-protected routes. When false, the original
  53. // unauthenticated routes stay as-is (backward compatible).
  54. func EnvEnabled() bool {
  55. return os.Getenv("BA_AUTHD_JWT_SECRET") != ""
  56. }