auth.test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { afterEach, describe, expect, test } from "bun:test"
  2. import { Option, Redacted } from "effect"
  3. import { Flag } from "@kirincode-ai/core/flag/flag"
  4. import { ServerAuth } from "../../src/server/auth"
  5. const original = {
  6. KIRINCODE_SERVER_PASSWORD: Flag.KIRINCODE_SERVER_PASSWORD,
  7. KIRINCODE_SERVER_USERNAME: Flag.KIRINCODE_SERVER_USERNAME,
  8. }
  9. afterEach(() => {
  10. Flag.KIRINCODE_SERVER_PASSWORD = original.KIRINCODE_SERVER_PASSWORD
  11. Flag.KIRINCODE_SERVER_USERNAME = original.KIRINCODE_SERVER_USERNAME
  12. })
  13. describe("ServerAuth", () => {
  14. test("does not emit auth headers without a password", () => {
  15. Flag.KIRINCODE_SERVER_PASSWORD = undefined
  16. Flag.KIRINCODE_SERVER_USERNAME = "alice"
  17. expect(ServerAuth.header()).toBeUndefined()
  18. expect(ServerAuth.headers()).toBeUndefined()
  19. })
  20. test("defaults to the kirincode username", () => {
  21. Flag.KIRINCODE_SERVER_PASSWORD = "secret"
  22. Flag.KIRINCODE_SERVER_USERNAME = undefined
  23. expect(ServerAuth.headers()).toEqual({
  24. Authorization: `Basic ${Buffer.from("opencode:secret").toString("base64")}`,
  25. })
  26. })
  27. test("uses the configured username", () => {
  28. Flag.KIRINCODE_SERVER_PASSWORD = "secret"
  29. Flag.KIRINCODE_SERVER_USERNAME = "alice"
  30. expect(ServerAuth.headers()).toEqual({
  31. Authorization: `Basic ${Buffer.from("alice:secret").toString("base64")}`,
  32. })
  33. })
  34. test("prefers explicit credentials", () => {
  35. Flag.KIRINCODE_SERVER_PASSWORD = "secret"
  36. Flag.KIRINCODE_SERVER_USERNAME = "alice"
  37. expect(ServerAuth.headers({ password: "cli-secret", username: "bob" })).toEqual({
  38. Authorization: `Basic ${Buffer.from("bob:cli-secret").toString("base64")}`,
  39. })
  40. })
  41. test("validates decoded credentials against effect config", () => {
  42. const config = { password: Option.some("secret"), username: "alice" }
  43. expect(ServerAuth.required(config)).toBe(true)
  44. expect(ServerAuth.authorized({ username: "alice", password: Redacted.make("secret") }, config)).toBe(true)
  45. expect(ServerAuth.authorized({ username: "kirincode", password: Redacted.make("secret") }, config)).toBe(false)
  46. })
  47. })