Generate the job capture token from the admin panel
Deploy with Docker Compose / deploy (push) Successful in 52s
Deploy with Docker Compose / deploy (push) Successful in 52s
The userscript's bearer token was an env var, JOB_CAPTURE_TOKEN, so rotating it meant editing .env and redeploying. It is now minted on the admin diagnostics panel instead, and the env var is gone. - services.CaptureToken keeps only a SHA-256 of the token, in backend/token/job_capture_token.json beside the OAuth tokens, so it survives rebuilds and cannot be read back. The token is shown once. - GET/POST/DELETE /admin/capture-token report, generate (replacing any existing token) and revoke it, behind the cookie-authenticated admin group. - With no token generated the capture routes still answer 503. - Userscript bumped to 1.0.1 for the changed prompt text. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -38,7 +38,6 @@ var configVars = []ConfigVar{
|
||||
{"STEAM_API_KEY", "Steam status widget", false},
|
||||
{"STEAM_ID", "Steam status widget", false},
|
||||
{"CLAUDE_API_KEY", "Email summarisation", false},
|
||||
{"JOB_CAPTURE_TOKEN", "Job capture userscript", false},
|
||||
{"EMAIL_BACKEND", "Email sync (graph/imap)", false},
|
||||
{"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false},
|
||||
@@ -82,7 +81,6 @@ func (store *Store) ConfigCheck(ctx *gin.Context) {
|
||||
"SPOTIFY_CLIENT_SECRET": true,
|
||||
"MSGRAPH_CLIENT_SECRET": true,
|
||||
"CLAUDE_API_KEY": true,
|
||||
"JOB_CAPTURE_TOKEN": true,
|
||||
"STEAM_API_KEY": true,
|
||||
"IMAP_PASSWORD": true,
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package handlers
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -56,25 +55,74 @@ const (
|
||||
// rowingReadClient for why two minutes.
|
||||
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// CaptureTokenMiddleware guards the capture routes with JOB_CAPTURE_TOKEN,
|
||||
// presented as "Authorization: Bearer <token>".
|
||||
// CaptureTokenMiddleware guards the capture routes with the token generated
|
||||
// in the admin panel (services.CaptureToken), presented as
|
||||
// "Authorization: Bearer <token>".
|
||||
//
|
||||
// An unset token turns the routes off (503) rather than leaving them open:
|
||||
// an empty env var is the stack's failure mode for a forgotten secret (see
|
||||
// .env.example), and comparing "" to "" would otherwise let everyone in.
|
||||
// Until a token has been generated the routes are off (503) rather than
|
||||
// open; "no token" must never be satisfied by a request that sends none.
|
||||
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
|
||||
if store.JobCaptureToken == "" {
|
||||
if store.CaptureToken == nil {
|
||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
|
||||
return
|
||||
}
|
||||
if set, _ := store.CaptureToken.Status(); !set {
|
||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "no capture token has been generated"})
|
||||
return
|
||||
}
|
||||
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
|
||||
if !ok || subtle.ConstantTimeCompare([]byte(presented), []byte(store.JobCaptureToken)) != 1 {
|
||||
if !ok || !store.CaptureToken.Verify(presented) {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// The three handlers below manage that token from the admin panel. They sit
|
||||
// in the cookie-authenticated admin group, not behind the token: the token
|
||||
// must not be able to replace itself.
|
||||
|
||||
func captureTokenStatus(token *services.CaptureToken) gin.H {
|
||||
set, createdAt := token.Status()
|
||||
if !set {
|
||||
return gin.H{"set": false}
|
||||
}
|
||||
return gin.H{"set": true, "createdAt": createdAt}
|
||||
}
|
||||
|
||||
// GetCaptureToken backs GET /admin/capture-token: whether a token exists and
|
||||
// when it was made. The token itself is not recoverable — only its hash is
|
||||
// stored.
|
||||
func (store *Store) GetCaptureToken(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
||||
}
|
||||
|
||||
// GenerateCaptureToken backs POST /admin/capture-token. It replaces any
|
||||
// existing token, so the userscript must be reconfigured with the new one,
|
||||
// and its response is the only time the token is ever sent anywhere.
|
||||
func (store *Store) GenerateCaptureToken(ctx *gin.Context) {
|
||||
token, createdAt, err := store.CaptureToken.Generate()
|
||||
if err != nil {
|
||||
log.Println("Generating capture token failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store the token"})
|
||||
return
|
||||
}
|
||||
// The response carries a credential; keep it out of any cache.
|
||||
ctx.Header("Cache-Control", "no-store")
|
||||
ctx.JSON(http.StatusOK, gin.H{"token": token, "createdAt": createdAt})
|
||||
}
|
||||
|
||||
// RevokeCaptureToken backs DELETE /admin/capture-token, switching the capture
|
||||
// routes off until a new token is generated.
|
||||
func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
|
||||
if err := store.CaptureToken.Revoke(); err != nil {
|
||||
log.Println("Revoking capture token failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to revoke the token"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
||||
}
|
||||
|
||||
// trackingParams are query parameters that say how the visitor arrived, not
|
||||
// which posting this is. Anything not listed is kept: ATS boards identify the
|
||||
// job in the query string often enough (gh_jid, jk, jobId) that dropping
|
||||
|
||||
@@ -6,11 +6,13 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -22,40 +24,123 @@ import (
|
||||
|
||||
func TestCaptureTokenMiddleware(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
serve := func(store *Store, header string) int {
|
||||
r := gin.New()
|
||||
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
|
||||
req := httptest.NewRequest(http.MethodGet, "/x", nil)
|
||||
if header != "" {
|
||||
req.Header.Set("Authorization", header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec.Code
|
||||
}
|
||||
newToken := func() *services.CaptureToken {
|
||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
// The case the middleware exists to get right: with no token generated,
|
||||
// a request presenting nothing (or an empty bearer) must not get in.
|
||||
t.Run("no token generated switches the routes off", func(t *testing.T) {
|
||||
store := &Store{CaptureToken: newToken()}
|
||||
for _, header := range []string{"", "Bearer ", "Bearer anything"} {
|
||||
if got := serve(store, header); got != http.StatusServiceUnavailable {
|
||||
t.Fatalf("header %q: status = %d, want 503", header, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("a store built without the token service is off too", func(t *testing.T) {
|
||||
if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", got)
|
||||
}
|
||||
})
|
||||
|
||||
store := &Store{CaptureToken: newToken()}
|
||||
token, _, err := store.CaptureToken.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
configured string
|
||||
header string
|
||||
want int
|
||||
name string
|
||||
header string
|
||||
want int
|
||||
}{
|
||||
{"the right token is let through", "s3cret", "Bearer s3cret", http.StatusOK},
|
||||
{"a wrong token is refused", "s3cret", "Bearer nope", http.StatusUnauthorized},
|
||||
{"no header is refused", "s3cret", "", http.StatusUnauthorized},
|
||||
{"the bare token without the scheme is refused", "s3cret", "s3cret", http.StatusUnauthorized},
|
||||
// The case the middleware exists to get right: an unset token must
|
||||
// not match the empty credential of an anonymous request.
|
||||
{"an unset token switches the routes off", "", "", http.StatusServiceUnavailable},
|
||||
{"an unset token is not matched by an empty bearer", "", "Bearer ", http.StatusServiceUnavailable},
|
||||
{"the generated token is let through", "Bearer " + token, http.StatusOK},
|
||||
{"a wrong token is refused", "Bearer nope", http.StatusUnauthorized},
|
||||
{"no header is refused", "", http.StatusUnauthorized},
|
||||
{"the bare token without the scheme is refused", token, http.StatusUnauthorized},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
store := &Store{JobCaptureToken: c.configured}
|
||||
r := gin.New()
|
||||
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/x", nil)
|
||||
if c.header != "" {
|
||||
req.Header.Set("Authorization", c.header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
if rec.Code != c.want {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, c.want)
|
||||
if got := serve(store, c.header); got != c.want {
|
||||
t.Fatalf("status = %d, want %d", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The admin endpoints, driven without the admin middleware (covered
|
||||
// elsewhere): generate shows the token once, status never does, and a second
|
||||
// generate or a revoke stops the first token working.
|
||||
func TestCaptureTokenAdminEndpoints(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
store := &Store{CaptureToken: tok}
|
||||
r := gin.New()
|
||||
r.GET("/t", store.GetCaptureToken)
|
||||
r.POST("/t", store.GenerateCaptureToken)
|
||||
r.DELETE("/t", store.RevokeCaptureToken)
|
||||
|
||||
call := func(method string) (map[string]any, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body)
|
||||
}
|
||||
var out map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
return out, rec
|
||||
}
|
||||
|
||||
if out, _ := call(http.MethodGet); out["set"] != false {
|
||||
t.Fatalf("fresh status = %v", out)
|
||||
}
|
||||
|
||||
out, rec := call(http.MethodPost)
|
||||
first, _ := out["token"].(string)
|
||||
if !tok.Verify(first) {
|
||||
t.Fatalf("generated token %q does not verify", first)
|
||||
}
|
||||
if rec.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("the response carrying the token must not be cacheable")
|
||||
}
|
||||
|
||||
out, _ = call(http.MethodGet)
|
||||
if out["set"] != true || out["createdAt"] == nil {
|
||||
t.Fatalf("status after generate = %v", out)
|
||||
}
|
||||
if _, leaked := out["token"]; leaked {
|
||||
t.Fatal("status must never return the token")
|
||||
}
|
||||
|
||||
call(http.MethodPost)
|
||||
if tok.Verify(first) {
|
||||
t.Fatal("regenerating must invalidate the previous token")
|
||||
}
|
||||
|
||||
if out, _ := call(http.MethodDelete); out["set"] != false {
|
||||
t.Fatalf("status after revoke = %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalJobURL(t *testing.T) {
|
||||
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
|
||||
cases := []struct {
|
||||
|
||||
@@ -39,9 +39,10 @@ type Store struct {
|
||||
// photo (handle_rowing.go) and a job posting (handle_job_capture.go).
|
||||
PythonURL string
|
||||
|
||||
// Bearer token for the browser capture routes (handle_job_capture.go).
|
||||
// Empty means those routes are switched off, not open.
|
||||
JobCaptureToken string
|
||||
// Bearer token for the browser capture routes (handle_job_capture.go),
|
||||
// generated from the admin panel. Nil, or holding no token, means those
|
||||
// routes are switched off, not open.
|
||||
CaptureToken *services.CaptureToken
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
|
||||
Reference in New Issue
Block a user