Add CORS credentials, transactional endpoints, and container deployment

CORS
  cors.go never set Access-Control-Allow-Credentials, so the
  cookie-authenticated API was unreadable from any cross-origin frontend:
  the server answered correctly and the browser blocked the page from
  reading it. Set for allowlisted origins on both the preflight and the
  actual response. Three tests added.

  HTTP_COOKIE_SAMESITE (lax|none|strict, default lax) is new. CORS is only
  half of what a cross-origin browser call needs; SameSite is judged on
  registrable domain, so a frontend on an unrelated domain gets perfect CORS
  headers and still no cookie. "none" is the only value that survives that,
  and validate() refuses it without the Secure flag.

  The "*" rejection now explains itself: browsers refuse Allow-Origin "*"
  together with credentials, so it would break every authenticated call
  rather than loosen anything.

Transactional endpoints (api-contract.md 12.1)
  POST /api/v1/job-applications/{id}/hire
  POST /api/v1/job-postings/{id}/assignments

  Replaces two client-side loops that wrote several records with no
  transaction and no rollback. Each is now one endpoint and one transaction,
  built over repo.Repo so org scoping, derived columns, type casts and error
  translation are not re-derived. Authorization reuses the existing policy
  table rather than adding a parallel one: a workflow is exactly as
  privileged as the writes it performs. 13 tests, including both rollback
  paths.

Bug fix in the repository layer
  repo.bindValue handled int64/int/float64/string but not int32, which is
  what pgx returns for a PostgreSQL `int` column. Nothing previously read a
  record and wrote one of its fields elsewhere, so it never surfaced; the
  hire flow does exactly that and failed with "ai_score must be a number".
  Both KindInt and KindFloat now accept the widths pgx actually produces.

Deployment
  infrastructure/Dockerfile.api  multi-stage, cross-compiling (BUILDPLATFORM
    + GOARCH) so linux/amd64 builds from arm64 are compiled rather than
    emulated. Alpine runtime, non-root uid 10001, 22.1 MB. Ships api, seed,
    setpassword and migrate, plus the migrations, so a Kubernetes
    initContainer can apply the schema from the same image and tag as the
    API. HEALTHCHECK keys on status code, not body, so a "degraded" instance
    is not pulled from rotation during a migration window.

  infrastructure/docker-compose.yml  migrations run to completion before the
    API starts. Assumes a managed PostgreSQL; the local-db overlay adds one
    with TLS enabled so APP_ENV=production is met rather than dodged.

  scripts/drop_public_tables.go  the one-off used to clear an unrelated
    schema from krowdb on 2026-08-24, kept for the record. Build-tagged
    ignore and gated on CONFIRM_DROP=yes.

Verified against PostgreSQL: 16/16 new tests pass, and the image was built,
run and exercised end to end (login, CORS preflight, authenticated reads,
transaction rollback).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmQiGq73Uyfq7J4yR8Vxxw
This commit is contained in:
Suriyakumarvijayanayagam
2026-08-25 11:33:01 +05:30
parent 7d12ebef3d
commit 954ba9076f
17 changed files with 1868 additions and 9 deletions

View File

@@ -42,6 +42,29 @@ const sessionCookieName = "krow_session"
// that never authenticate anything.
func (s *Server) secureCookies() bool { return s.cfg.AppEnv != "development" }
// sameSite resolves the configured SameSite mode.
//
// Lax remains the default and the recommendation. "none" exists for the one
// deployment shape that cannot work without it: a frontend on a different
// registrable domain from the API. In that case Lax withholds the cookie on
// every cross-site fetch, so the sign-in succeeds, the Set-Cookie arrives, and
// the next request carries nothing — which reads as a broken session rather
// than as a cookie policy.
//
// An unrecognised value falls back to Lax rather than to None. config.validate
// rejects those before startup, so this is only a belt-and-braces default in
// the safe direction.
func (s *Server) sameSite() http.SameSite {
switch s.cfg.HTTP.CookieSameSite {
case "none":
return http.SameSiteNoneMode
case "strict":
return http.SameSiteStrictMode
default:
return http.SameSiteLaxMode
}
}
// setSessionCookie writes the raw token to the browser.
//
// This is the only place the raw token is written to a response, and it goes
@@ -59,12 +82,14 @@ func (s *Server) setSessionCookie(w http.ResponseWriter, token string, lifetime
Path: "/",
// HttpOnly: script cannot read it.
HttpOnly: true,
// Lax, not Strict and not None. Strict would drop the cookie on any
// cross-site navigation, so following a link into the app would land on
// a login page despite a live session. None would require Secure and
// would send the cookie on cross-site POSTs, which is the CSRF hole Lax
// exists to close.
SameSite: http.SameSiteLaxMode,
// Lax by default, and Strict/None available through
// HTTP_COOKIE_SAMESITE. Strict would drop the cookie on any cross-site
// navigation, so following a link into the app would land on a login
// page despite a live session. None sends it on cross-site requests,
// which is the CSRF hole Lax exists to close — and is nonetheless the
// only workable value when the frontend is on a different registrable
// domain. See Server.sameSite.
SameSite: s.sameSite(),
Secure: s.secureCookies(),
MaxAge: int(lifetime.Seconds()),
})
@@ -82,7 +107,9 @@ func (s *Server) clearSessionCookie(w http.ResponseWriter) {
Value: "",
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
// Must match the attributes it was set with, SameSite included, or the
// browser treats this as a different cookie and leaves the original.
SameSite: s.sameSite(),
Secure: s.secureCookies(),
MaxAge: -1,
})

View File

@@ -73,6 +73,19 @@ func cors(origins []string) func(http.Handler) http.Handler {
w.Header().Set("Access-Control-Allow-Origin", origin)
// Authentication is a cookie, so the browser will neither send it
// nor expose the response without this. It is set for allowlisted
// origins only, and the origin above is always a specific one —
// the pairing of Allow-Credentials with "*" is rejected outright by
// browsers, which is the second reason this middleware never echoes
// a wildcard.
//
// Both the preflight and the actual response need it: the preflight
// decides whether the browser is willing to SEND the cookie, and the
// actual response decides whether the page may READ the result.
// Setting it here, before the preflight branch, covers both.
w.Header().Set("Access-Control-Allow-Credentials", "true")
if isPreflight(r) {
w.Header().Add("Vary", "Access-Control-Request-Method")
w.Header().Add("Vary", "Access-Control-Request-Headers")

View File

@@ -133,6 +133,62 @@ func TestCORSOffByDefault(t *testing.T) {
}
}
// Authentication is a cookie, so a cross-origin frontend calling with
// `credentials: 'include'` needs Access-Control-Allow-Credentials on the actual
// response. Without it the browser blocks the page from reading a reply the
// server answered perfectly well, and the app sees an opaque network failure
// beside a 200 in the server log.
func TestCORSAllowsCredentialsOnResponse(t *testing.T) {
handler := corsAPI(t, devOrigin)
rec := send(handler, "GET", "/api/v1/job-postings", map[string]string{"Origin": devOrigin})
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", rec.Code)
}
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
t.Fatalf("Access-Control-Allow-Credentials = %q, want \"true\" — "+
"a cookie-authenticated API is unreadable cross-origin without it", got)
}
// Allow-Credentials with a wildcard origin is rejected by every browser, so
// the two must never appear together.
if got := rec.Header().Get("Access-Control-Allow-Origin"); got == "*" {
t.Fatal("Access-Control-Allow-Origin is \"*\" alongside credentials; browsers refuse that pairing")
}
}
// The preflight decides whether the browser is willing to SEND the cookie at
// all, so it needs the header too — separately from the actual response.
func TestCORSAllowsCredentialsOnPreflight(t *testing.T) {
handler := corsAPI(t, devOrigin)
rec := send(handler, "OPTIONS", "/api/v1/job-postings", map[string]string{
"Origin": devOrigin,
"Access-Control-Request-Method": "POST",
})
if rec.Code != http.StatusNoContent {
t.Fatalf("expected 204, got %d", rec.Code)
}
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
t.Fatalf("preflight Access-Control-Allow-Credentials = %q, want \"true\"", got)
}
}
// An origin that is not on the allowlist must not be handed credentials
// permission — the header is worthless on its own, but pairing it with a
// reflected origin would be the classic misconfiguration.
func TestCORSWithholdsCredentialsFromUnknownOrigin(t *testing.T) {
handler := corsAPI(t, devOrigin)
rec := send(handler, "GET", "/api/v1/job-postings",
map[string]string{"Origin": "http://evil.example"})
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "" {
t.Fatalf("an unlisted origin was granted credentials: %q", got)
}
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
t.Fatalf("an unlisted origin was echoed back: %q", got)
}
}
func contains(haystack, needle string) bool {
for i := 0; i+len(needle) <= len(haystack); i++ {
if haystack[i:i+len(needle)] == needle {

View File

@@ -37,6 +37,7 @@ type Server struct {
db *db.DB
api *service.Registry
definitions *service.DefinitionsService
workflows *service.WorkflowService
log *slog.Logger
http *http.Server
started time.Time
@@ -124,6 +125,7 @@ func New(cfg *config.Config, database *db.DB, log *slog.Logger, opts ...Option)
cfg: cfg, db: database, log: log,
api: service.NewRegistry(database.Pool),
definitions: service.NewDefinitions(database.Pool),
workflows: service.NewWorkflows(database.Pool).WithClock(o.now),
started: o.now(),
sessions: sessions,
users: users,
@@ -135,7 +137,8 @@ func New(cfg *config.Config, database *db.DB, log *slog.Logger, opts ...Option)
mux := http.NewServeMux()
mux.HandleFunc("GET /health", s.handleHealth)
s.endpoints = s.routeAuth(mux) + s.routeResources(mux) + s.routeMe(mux) + s.routeDefinitions(mux)
s.endpoints = s.routeAuth(mux) + s.routeResources(mux) + s.routeMe(mux) +
s.routeDefinitions(mux) + s.routeWorkflows(mux)
handler := jsonErrors(mux)
// Authentication sits where devOrgMiddleware used to, so every route below

View File

@@ -0,0 +1,153 @@
package httpserver
import (
"net/http"
"github.com/krow/krow-backend/go-api/internal/authctx"
"github.com/krow/krow-backend/go-api/internal/domain"
"github.com/krow/krow-backend/go-api/internal/service"
)
// The multi-record endpoints from api-contract.md §12.1.
//
// These are the first routes that are not a plain CRUD projection of a table,
// and they are shaped as verbs on the record they act on — `.../{id}/hire`,
// `.../{id}/assignments` — rather than as new collections. The action is the
// thing being requested, and it has no independent existence to GET.
//
// AUTHORIZATION REUSES THE POLICY TABLE RATHER THAN ADDING TO IT.
//
// A workflow is exactly as privileged as the writes it performs, so each one
// is gated on the operations it will actually carry out — hire needs UPDATE on
// job-applications and CREATE on staff; assign needs CREATE on assignments and
// UPDATE on job-applications. Inventing a separate `hire` permission would
// create a second place where the answer to "who may do this" lives, and the
// two would eventually disagree. Every pair below resolves to `operators`
// today, which is the intended answer: a talent user cannot hire themselves or
// place themselves on a shift.
// requirement is one (resource, operation) pair a workflow depends on.
type requirement struct {
path string
op domain.Op
}
// authorizeAll refuses unless the caller may perform every listed operation.
//
// All-or-nothing, checked before any transaction opens: a caller who may update
// an application but not create staff must not get halfway through a hire and
// be rolled back. The refusal is the same 403 a single-operation handler gives,
// and names no resource — see domain.Forbidden.
func (s *Server) authorizeAll(w http.ResponseWriter, r *http.Request,
reqs ...requirement) (authctx.Identity, bool) {
ident, err := authctx.MustFrom(r.Context())
if err != nil {
// Unreachable: the middleware refuses an unauthenticated request before
// the router sees it. A missing identity here is a wiring bug.
writeError(w, s.log, domain.Internal(err))
return authctx.Identity{}, false
}
role, known := domain.ParseRole(ident.Role)
if !known {
s.log.Warn("workflow refused: unknown role",
"user_id", ident.UserID, "role", ident.Role, "path", r.URL.Path)
writeError(w, s.log, domain.Forbidden())
return authctx.Identity{}, false
}
for _, req := range reqs {
svc, ok := s.api.Get(req.path)
if !ok {
writeError(w, s.log, domain.Internal(
errUnregisteredResource(req.path)))
return authctx.Identity{}, false
}
if !svc.Resource().Policy.Allows(req.op, role) {
s.log.Warn("workflow authorization refused",
"user_id", ident.UserID, "role", ident.Role,
"required_resource", req.path, "path", r.URL.Path)
writeError(w, s.log, domain.Forbidden())
return authctx.Identity{}, false
}
}
return ident, true
}
type unregisteredResourceError string
func (e unregisteredResourceError) Error() string {
return "httpserver: workflow depends on unregistered resource " + string(e)
}
func errUnregisteredResource(path string) error { return unregisteredResourceError(path) }
func (s *Server) routeWorkflows(mux *http.ServeMux) int {
mux.HandleFunc("POST /api/v1/job-applications/{id}/hire", s.handleHire)
mux.HandleFunc("POST /api/v1/job-postings/{id}/assignments", s.handleAssign)
return 2
}
// handleHire moves an application to `hired` and creates the staff record in
// one transaction. Replaces the two-call sequence at krowHooks.js:302-303.
func (s *Server) handleHire(w http.ResponseWriter, r *http.Request) {
ident, ok := s.authorizeAll(w, r,
requirement{"job-applications", domain.OpUpdate},
requirement{"staff", domain.OpCreate},
requirement{"user-activity", domain.OpCreate},
)
if !ok {
return
}
body, err := decodeBody(r)
if err != nil {
writeError(w, s.log, err)
return
}
result, err := s.workflows.Hire(r.Context(), ident, r.PathValue("id"), body)
if err != nil {
writeError(w, s.log, err)
return
}
s.log.Info("candidate hired", "user_id", ident.UserID,
"application_id", r.PathValue("id"), "staff_id", result.Staff["id"])
// 201: the request created a staff record. The application it also updated
// is returned alongside so the caller can render the new state without a
// second read.
writeJSON(w, http.StatusCreated, envelope{Data: result})
}
// handleAssign places workers on a posting in one transaction. Replaces the 3n
// sequential round-trips at krowHooks.js:421/449/466.
func (s *Server) handleAssign(w http.ResponseWriter, r *http.Request) {
ident, ok := s.authorizeAll(w, r,
requirement{"assignments", domain.OpCreate},
requirement{"job-applications", domain.OpUpdate},
requirement{"user-activity", domain.OpCreate},
)
if !ok {
return
}
var req service.AssignRequest
if err := decodeInto(r, &req); err != nil {
writeError(w, s.log, err)
return
}
result, err := s.workflows.Assign(r.Context(), ident, r.PathValue("id"), req)
if err != nil {
writeError(w, s.log, err)
return
}
s.log.Info("workers assigned", "user_id", ident.UserID,
"job_posting_id", r.PathValue("id"), "count", result.Count)
writeJSON(w, http.StatusCreated, envelope{Data: result})
}

View File

@@ -0,0 +1,331 @@
package httpserver_test
import (
"context"
"net/http"
"testing"
)
// The multi-record endpoints from api-contract.md §12.1.
//
// The property worth testing here is not that the happy path works — it is that
// a failure part-way through leaves NOTHING behind. Every rollback test below
// counts rows before and after, because "the request returned an error" and
// "the request changed nothing" are different claims and only the second one is
// what a transaction is for.
// applicationFor creates an application that can be hired.
func applicationFor(t *testing.T, r *rbac, posting, name, email string) string {
t.Helper()
return mustCreate(t, r, r.admin, "/api/v1/job-applications", map[string]any{
"job_posting_id": posting,
"applicant_name": name,
"email": email,
"status": "shortlisted",
"ai_score": 77,
})
}
func countRows(t *testing.T, r *rbac, table string) int {
t.Helper()
var n int
if err := r.h.Pool.QueryRow(context.Background(),
`SELECT count(*) FROM `+table+` WHERE org_id = $1::uuid`, r.orgID).Scan(&n); err != nil {
t.Fatalf("count %s: %v", table, err)
}
return n
}
/* ── Hire ───────────────────────────────────────────────────────────────── */
func TestHireCreatesStaffAndMovesApplication(t *testing.T) {
r := newRBAC(t)
app := applicationFor(t, r, r.activePosting, "Hire Me", "hire-me@example.test")
before := countRows(t, r, "staff")
got := r.as(r.admin, "POST", "/api/v1/job-applications/"+app+"/hire", map[string]any{
"role": "Event Server", "profile_tier": "Skilled",
})
if got.code != http.StatusCreated {
t.Fatalf("hire: got %d, want 201 (%v)", got.code, got.body)
}
data, _ := got.body["data"].(map[string]any)
application, _ := data["application"].(map[string]any)
staff, _ := data["staff"].(map[string]any)
if application == nil || staff == nil {
t.Fatalf("hire response is missing application or staff: %v", got.body)
}
if application["status"] != "hired" {
t.Errorf("application.status = %v, want hired", application["status"])
}
if staff["name"] != "Hire Me" {
t.Errorf("staff.name = %v, want the applicant's name", staff["name"])
}
if staff["email"] != "hire-me@example.test" {
t.Errorf("staff.email = %v, want the application's email", staff["email"])
}
// The caller's overrides win over the derived defaults.
if staff["role"] != "Event Server" {
t.Errorf("staff.role = %v, want the supplied role", staff["role"])
}
if staff["profile_tier"] != "Skilled" {
t.Errorf("staff.profile_tier = %v, want the supplied tier", staff["profile_tier"])
}
// ai_score is carried across from the application. It is an `int` column,
// so it arrives from pgx as int32 — the case repo.bindValue did not handle
// until this endpoint existed to read a record and write it elsewhere.
if score, ok := staff["ai_score"].(float64); !ok || int(score) != 77 {
t.Errorf("staff.ai_score = %v, want 77 carried from the application", staff["ai_score"])
}
if staff["application_id"] != app {
t.Errorf("staff.application_id = %v, want %s", staff["application_id"], app)
}
if after := countRows(t, r, "staff"); after != before+1 {
t.Errorf("staff rows: %d -> %d, want exactly one more", before, after)
}
}
// Hiring the same application twice would create a second employment record for
// one person, so the second attempt is a conflict rather than a repeat.
func TestHireIsNotRepeatable(t *testing.T) {
r := newRBAC(t)
app := applicationFor(t, r, r.activePosting, "Twice", "twice@example.test")
if got := r.as(r.admin, "POST", "/api/v1/job-applications/"+app+"/hire", map[string]any{}); got.code != http.StatusCreated {
t.Fatalf("first hire: got %d, want 201 (%v)", got.code, got.body)
}
before := countRows(t, r, "staff")
got := r.as(r.admin, "POST", "/api/v1/job-applications/"+app+"/hire", map[string]any{})
if got.code != http.StatusConflict {
t.Fatalf("second hire: got %d, want 409 (%v)", got.code, got.body)
}
if after := countRows(t, r, "staff"); after != before {
t.Errorf("a refused hire still wrote a staff row: %d -> %d", before, after)
}
}
// The whole point of the endpoint: the two writes succeed together or not at
// all. A staff insert that violates a constraint must leave the application
// untouched, not merely report an error.
func TestHireRollsBackTheApplicationWhenStaffFails(t *testing.T) {
r := newRBAC(t)
app := applicationFor(t, r, r.activePosting, "Rollback", "rollback@example.test")
staffBefore := countRows(t, r, "staff")
// profile_tier is a native enum; a value outside it fails the staff INSERT
// after the application UPDATE has already been issued in this transaction.
got := r.as(r.admin, "POST", "/api/v1/job-applications/"+app+"/hire", map[string]any{
"profile_tier": "NotARealTier",
})
if got.code == http.StatusCreated {
t.Fatalf("an invalid profile_tier was accepted: %v", got.body)
}
if after := countRows(t, r, "staff"); after != staffBefore {
t.Errorf("staff rows changed despite a failed hire: %d -> %d", staffBefore, after)
}
// The decisive assertion: the application must NOT be hired.
reread := r.as(r.admin, "GET", "/api/v1/job-applications?limit=500", nil)
if reread.code != http.StatusOK {
t.Fatalf("re-read applications: %d", reread.code)
}
for _, raw := range reread.body["data"].([]any) {
rec := raw.(map[string]any)
if rec["id"] == app && rec["status"] == "hired" {
t.Fatal("the application was left hired after the staff insert failed — " +
"the two writes are not in one transaction")
}
}
}
// Hiring is an operator action. A talent user must not be able to hire anyone,
// including themselves.
func TestHireIsRefusedToTalent(t *testing.T) {
r := newRBAC(t)
app := applicationFor(t, r, r.activePosting, "Self", r.talA.email)
before := countRows(t, r, "staff")
got := r.as(r.talA, "POST", "/api/v1/job-applications/"+app+"/hire", map[string]any{})
if got.code != http.StatusForbidden {
t.Fatalf("talent hire: got %d, want 403 (%v)", got.code, got.body)
}
if after := countRows(t, r, "staff"); after != before {
t.Errorf("a refused hire still wrote a staff row: %d -> %d", before, after)
}
}
func TestHireRejectsUnknownApplication(t *testing.T) {
r := newRBAC(t)
got := r.as(r.admin, "POST",
"/api/v1/job-applications/00000000-0000-0000-0000-000000000000/hire", map[string]any{})
if got.code != http.StatusNotFound {
t.Fatalf("hire unknown application: got %d, want 404 (%v)", got.code, got.body)
}
}
// Another organization's application is absent, not forbidden — the same 404 a
// nonexistent id gets, so existence does not leak across tenants.
func TestHireCannotReachAnotherOrganization(t *testing.T) {
r := newRBAC(t)
app := applicationFor(t, r, r.activePosting, "Ours", "ours@example.test")
got := r.as(r.outsider, "POST", "/api/v1/job-applications/"+app+"/hire", map[string]any{})
if got.code != http.StatusNotFound {
t.Fatalf("cross-tenant hire: got %d, want 404 (%v)", got.code, got.body)
}
}
/* ── Assign ─────────────────────────────────────────────────────────────── */
func TestAssignPlacesWorkersAndUpdatesApplications(t *testing.T) {
r := newRBAC(t)
a1 := applicationFor(t, r, r.activePosting, "Worker One", "w1@example.test")
a2 := applicationFor(t, r, r.activePosting, "Worker Two", "w2@example.test")
before := countRows(t, r, "assignments")
got := r.as(r.admin, "POST", "/api/v1/job-postings/"+r.activePosting+"/assignments", map[string]any{
"workers": []map[string]any{
{"worker_email": "w1@example.test", "worker_name": "Worker One",
"starts_at": "2026-09-01T09:00:00Z", "application_id": a1, "match_score": 91},
{"worker_email": "w2@example.test", "worker_name": "Worker Two",
"starts_at": "2026-09-01T09:00:00Z", "application_id": a2},
},
})
if got.code != http.StatusCreated {
t.Fatalf("assign: got %d, want 201 (%v)", got.code, got.body)
}
data, _ := got.body["data"].(map[string]any)
if count, ok := data["count"].(float64); !ok || int(count) != 2 {
t.Errorf("count = %v, want 2", data["count"])
}
if after := countRows(t, r, "assignments"); after != before+2 {
t.Errorf("assignment rows: %d -> %d, want two more", before, after)
}
// Both applications must now read as assigned.
list := r.as(r.admin, "GET", "/api/v1/job-applications?status=assigned", nil)
assigned := map[string]bool{}
for _, raw := range list.body["data"].([]any) {
assigned[raw.(map[string]any)["id"].(string)] = true
}
if !assigned[a1] || !assigned[a2] {
t.Errorf("applications were not moved to assigned: a1=%v a2=%v", assigned[a1], assigned[a2])
}
}
// A worker with no application is legitimate — that is what the talent pool is
// for — and must not be invented one.
func TestAssignAcceptsWorkerWithoutApplication(t *testing.T) {
r := newRBAC(t)
got := r.as(r.admin, "POST", "/api/v1/job-postings/"+r.activePosting+"/assignments", map[string]any{
"workers": []map[string]any{
{"worker_email": "pool@example.test", "worker_name": "Pool Worker",
"starts_at": "2026-09-01T09:00:00Z"},
},
})
if got.code != http.StatusCreated {
t.Fatalf("assign without application: got %d, want 201 (%v)", got.code, got.body)
}
}
// The batch is all-or-nothing. A bad reference on the SECOND worker must undo
// the first worker's assignment, not leave it stranded.
func TestAssignRollsBackTheWholeBatch(t *testing.T) {
r := newRBAC(t)
before := countRows(t, r, "assignments")
got := r.as(r.admin, "POST", "/api/v1/job-postings/"+r.activePosting+"/assignments", map[string]any{
"workers": []map[string]any{
{"worker_email": "first@example.test", "worker_name": "First",
"starts_at": "2026-09-01T09:00:00Z"},
{"worker_email": "second@example.test", "worker_name": "Second",
"starts_at": "2026-09-01T09:00:00Z",
"application_id": "00000000-0000-0000-0000-000000000000"},
},
})
if got.code == http.StatusCreated {
t.Fatalf("a batch naming a nonexistent application was accepted: %v", got.body)
}
if after := countRows(t, r, "assignments"); after != before {
t.Fatalf("the first worker survived the second's failure: %d -> %d — "+
"the batch is not one transaction", before, after)
}
}
func TestAssignIsRefusedToTalent(t *testing.T) {
r := newRBAC(t)
before := countRows(t, r, "assignments")
got := r.as(r.talA, "POST", "/api/v1/job-postings/"+r.activePosting+"/assignments", map[string]any{
"workers": []map[string]any{
{"worker_email": r.talA.email, "worker_name": "Self",
"starts_at": "2026-09-01T09:00:00Z"},
},
})
if got.code != http.StatusForbidden {
t.Fatalf("talent assign: got %d, want 403 (%v)", got.code, got.body)
}
if after := countRows(t, r, "assignments"); after != before {
t.Errorf("a refused assign still wrote a row: %d -> %d", before, after)
}
}
func TestAssignValidatesTheBatchBeforeWriting(t *testing.T) {
r := newRBAC(t)
before := countRows(t, r, "assignments")
cases := []struct {
name string
body map[string]any
}{
{"no workers", map[string]any{"workers": []map[string]any{}}},
{"missing email", map[string]any{"workers": []map[string]any{
{"worker_name": "No Email", "starts_at": "2026-09-01T09:00:00Z"}}}},
{"missing starts_at", map[string]any{"workers": []map[string]any{
{"worker_email": "x@example.test", "worker_name": "No Start"}}}},
{"malformed application_id", map[string]any{"workers": []map[string]any{
{"worker_email": "x@example.test", "starts_at": "2026-09-01T09:00:00Z",
"application_id": "not-a-uuid"}}}},
}
for _, tc := range cases {
got := r.as(r.admin, "POST", "/api/v1/job-postings/"+r.activePosting+"/assignments", tc.body)
if got.code != http.StatusUnprocessableEntity {
t.Errorf("%s: got %d, want 422 (%v)", tc.name, got.code, got.body)
}
}
if after := countRows(t, r, "assignments"); after != before {
t.Errorf("a rejected batch wrote rows: %d -> %d", before, after)
}
}
func TestAssignRejectsUnknownPosting(t *testing.T) {
r := newRBAC(t)
got := r.as(r.admin, "POST",
"/api/v1/job-postings/00000000-0000-0000-0000-000000000000/assignments", map[string]any{
"workers": []map[string]any{
{"worker_email": "x@example.test", "starts_at": "2026-09-01T09:00:00Z"},
},
})
if got.code != http.StatusNotFound {
t.Fatalf("assign to unknown posting: got %d, want 404 (%v)", got.code, got.body)
}
}
// Both endpoints are behind the session like everything else.
func TestWorkflowEndpointsRequireASession(t *testing.T) {
r := newRBAC(t)
for _, path := range []string{
"/api/v1/job-applications/00000000-0000-0000-0000-000000000000/hire",
"/api/v1/job-postings/00000000-0000-0000-0000-000000000000/assignments",
} {
if got := r.doAnon("POST", path, map[string]any{}); got.code != http.StatusUnauthorized {
t.Errorf("%s unauthenticated: got %d, want 401", path, got.code)
}
}
}