Compare commits
2
Commits
acc6876e33
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12f253a300 | ||
|
|
179463795b |
@@ -10,11 +10,12 @@
|
|||||||
# TWO JOBS
|
# TWO JOBS
|
||||||
# test go vet + go test, and a vite build of web/. The same checks as
|
# test go vet + go test, and a vite build of web/. The same checks as
|
||||||
# `make check`.
|
# `make check`.
|
||||||
# publish main only, after test: builds the image, pushes it to this
|
# publish main only, after test: builds the image and pushes it to this
|
||||||
# Gitea's container registry as :<sha> and :latest, then pulls it
|
# Gitea's container registry as :<sha> and :latest. It does NOT
|
||||||
# into the web_server stack (its `jobs` service) and waits for it
|
# deploy: the tracker runs on stppriv, which is deployed by hand
|
||||||
# to be healthy. So a push to main goes live, as web_server's own
|
# (`docker compose pull jobs && docker compose up -d jobs` in
|
||||||
# pushes do — see "Deploying" in README.md.
|
# ~/deploy/stppriv). The runner lives on stpvm and only deploys
|
||||||
|
# stpvm.
|
||||||
#
|
#
|
||||||
# SECRETS (repo settings -> Actions -> Secrets)
|
# SECRETS (repo settings -> Actions -> Secrets)
|
||||||
# REGISTRY_USER a Gitea user that can write packages for adamf
|
# REGISTRY_USER a Gitea user that can write packages for adamf
|
||||||
@@ -118,35 +119,3 @@ jobs:
|
|||||||
if: always()
|
if: always()
|
||||||
shell: bash
|
shell: bash
|
||||||
run: rm -rf "$SRC"
|
run: rm -rf "$SRC"
|
||||||
|
|
||||||
# Put the new image live. The runner is on the same host, so this is the
|
|
||||||
# same `pull` + `up` you would type by hand in the site's deploy
|
|
||||||
# directory. Only the `jobs` service is touched (--no-deps), and
|
|
||||||
# compose recreates it only if the pulled image differs.
|
|
||||||
#
|
|
||||||
# Pinning still works: if the site's .env sets JOBS_IMAGE_TAG to a
|
|
||||||
# sha, compose pulls and runs that tag, so this step changes
|
|
||||||
# nothing until the pin is removed.
|
|
||||||
#
|
|
||||||
# flock takes .compose.lock, which web_server's deploy.yaml and
|
|
||||||
# maintenance.yaml hold while they run compose, so this cannot
|
|
||||||
# race a site deploy or the weekly rebuild.
|
|
||||||
#
|
|
||||||
# Then it waits for the image's HEALTHCHECK (process up, database
|
|
||||||
# reachable). A tracker that will not start fails the run, which is
|
|
||||||
# the signal to pin JOBS_IMAGE_TAG to the last good sha.
|
|
||||||
- name: Roll the site onto the new image
|
|
||||||
working-directory: /home/adamf/deploy/web_server
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
flock .compose.lock sh -c 'docker compose pull jobs && docker compose up -d --no-deps jobs'
|
|
||||||
for i in $(seq 1 30); do
|
|
||||||
status=$(docker inspect -f '{{.State.Health.Status}}' jobs)
|
|
||||||
echo "jobs: $status"
|
|
||||||
[ "$status" = healthy ] && exit 0
|
|
||||||
[ "$status" = unhealthy ] && break
|
|
||||||
sleep 5
|
|
||||||
done
|
|
||||||
docker logs --tail 50 jobs
|
|
||||||
exit 1
|
|
||||||
|
|||||||
@@ -44,6 +44,8 @@ There are no accounts here. `internal/auth` forwards the browser's `Cookie` head
|
|||||||
- **Caching:** a "yes" is cached for 30 seconds per cookie, so logging out takes up to 30 seconds to reach the tracker.
|
- **Caching:** a "yes" is cached for 30 seconds per cookie, so logging out takes up to 30 seconds to reach the tracker.
|
||||||
- **Lapsed session:** the SPA sends the browser to the site's `/admin/login?redirect=/jobs/...` (`web/src/session.js`).
|
- **Lapsed session:** the SPA sends the browser to the site's `/admin/login?redirect=/jobs/...` (`web/src/session.js`).
|
||||||
|
|
||||||
|
`AUTH_MODE=access` is for running behind Cloudflare Access (stppriv, `priv.<site>/jobs/`), where the site's cookie is not sent. It verifies the `Cf-Access-Jwt-Assertion` header (or the `CF_Authorization` cookie) as an RS256 JWT against `https://$ACCESS_TEAM_DOMAIN/cdn-cgi/access/certs`, with issuer `https://$ACCESS_TEAM_DOMAIN` and audience `$ACCESS_AUD`. Keys are cached for an hour. A lapsed session still sends the SPA to `/admin/login`, which stppriv serves as a "log in again" page.
|
||||||
|
|
||||||
`AUTH_MODE=dev` admits everyone, for the standalone compose. It is refused unless `DEV_MODE=true`.
|
`AUTH_MODE=dev` admits everyone, for the standalone compose. It is refused unless `DEV_MODE=true`.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
@@ -66,15 +68,13 @@ The site's `docker-compose.yml` runs the published image as service `jobs`, with
|
|||||||
|
|
||||||
### Deploying
|
### Deploying
|
||||||
|
|
||||||
A push to `main` here runs `.gitea/workflows/ci.yaml`. It tests, builds and pushes `adam-french.co.uk/adamf/job-tracker:<sha>` and `:latest`, then rolls the site onto the new image and waits for the container's healthcheck. A tracker that does not come up healthy fails the run, with its last log lines in the output.
|
A push to `main` here runs `.gitea/workflows/ci.yaml`. It tests, builds and pushes `adam-french.co.uk/adamf/job-tracker:<sha>` and `:latest`. It does not deploy: the tracker runs on stppriv (`priv.<site>/jobs/`), which is deployed by hand:
|
||||||
|
|
||||||
The roll-out is the same command you would run by hand on the host:
|
|
||||||
|
|
||||||
```
|
```
|
||||||
cd ~/deploy/web_server && docker compose pull jobs && docker compose up -d --no-deps jobs
|
cd ~/deploy/stppriv && docker compose pull jobs && docker compose up -d jobs
|
||||||
```
|
```
|
||||||
|
|
||||||
To pin a version, set `JOBS_IMAGE_TAG=<sha>` in the site's `.env`. While it is pinned, pushes here still publish but change nothing live. To roll back, pin the last good sha.
|
To pin a version, set `JOBS_IMAGE_TAG=<sha>` in stppriv's `.env`. To roll back, pin the last good sha.
|
||||||
|
|
||||||
### One-off: registry setup
|
### One-off: registry setup
|
||||||
|
|
||||||
|
|||||||
+11
-4
@@ -50,13 +50,20 @@ func main() {
|
|||||||
|
|
||||||
// AUTH
|
// AUTH
|
||||||
// Settled before anything else, so a bad mode fails fast.
|
// Settled before anything else, so a bad mode fails fast.
|
||||||
// "forward" (the default) asks the main site; "dev" admits everyone and
|
// "forward" (the default) asks the main site; "access" verifies the
|
||||||
// is refused outside DEV_MODE, so a stray setting cannot open the
|
// Cloudflare Access JWT (on stppriv, where the main site's cookie is not
|
||||||
// tracker in production.
|
// sent); "dev" admits everyone and is refused outside DEV_MODE, so a
|
||||||
|
// stray setting cannot open the tracker in production.
|
||||||
var checker auth.Checker
|
var checker auth.Checker
|
||||||
switch mode := getenv("AUTH_MODE", "forward"); mode {
|
switch mode := getenv("AUTH_MODE", "forward"); mode {
|
||||||
case "forward":
|
case "forward":
|
||||||
checker = auth.NewForward(getenv("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin"))
|
checker = auth.NewForward(getenv("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin"))
|
||||||
|
case "access":
|
||||||
|
a, err := auth.NewAccess(os.Getenv("ACCESS_TEAM_DOMAIN"), os.Getenv("ACCESS_AUD"))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("AUTH_MODE=access: %v", err)
|
||||||
|
}
|
||||||
|
checker = a
|
||||||
case "dev":
|
case "dev":
|
||||||
if !devMode {
|
if !devMode {
|
||||||
log.Fatal("AUTH_MODE=dev is only allowed with DEV_MODE=true")
|
log.Fatal("AUTH_MODE=dev is only allowed with DEV_MODE=true")
|
||||||
@@ -64,7 +71,7 @@ func main() {
|
|||||||
log.Println("[Auth] AUTH_MODE=dev: every request is treated as the admin")
|
log.Println("[Auth] AUTH_MODE=dev: every request is treated as the admin")
|
||||||
checker = auth.AllowAll{}
|
checker = auth.AllowAll{}
|
||||||
default:
|
default:
|
||||||
log.Fatalf("unknown AUTH_MODE %q (want forward or dev)", mode)
|
log.Fatalf("unknown AUTH_MODE %q (want forward, access or dev)", mode)
|
||||||
}
|
}
|
||||||
|
|
||||||
databaseURL := os.Getenv("DATABASE_URL")
|
databaseURL := os.Getenv("DATABASE_URL")
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"math/big"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Access is the "access" mode checker: the tracker sits behind Cloudflare
|
||||||
|
// Access (on stppriv), which has already logged the user in and adds a signed
|
||||||
|
// JWT to every request it lets through. A valid token for our application is
|
||||||
|
// the admin; anything else is refused. Checking it here, not only at the
|
||||||
|
// edge, means a request that reaches the container some other way (a
|
||||||
|
// misrouted tunnel, a Bypass policy that is too wide) is still refused.
|
||||||
|
//
|
||||||
|
// Only RS256 is accepted, which is what Access signs with. The signing keys
|
||||||
|
// come from https://<team>/cdn-cgi/access/certs and are cached; a token with
|
||||||
|
// an unknown key id triggers a refetch, at most once per keyRefetchGap, since
|
||||||
|
// Access rotates its keys.
|
||||||
|
type Access struct {
|
||||||
|
Issuer string // https://<team>.cloudflareaccess.com
|
||||||
|
Audience string // the Access application's AUD tag
|
||||||
|
CertsURL string
|
||||||
|
Client *http.Client
|
||||||
|
now func() time.Time
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
keys map[string]*rsa.PublicKey
|
||||||
|
fetchedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
keyCacheTTL = time.Hour
|
||||||
|
keyRefetchGap = 30 * time.Second
|
||||||
|
accessHeader = "Cf-Access-Jwt-Assertion"
|
||||||
|
accessCookie = "CF_Authorization"
|
||||||
|
clockTolerance = 30 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewAccess builds the checker for teamDomain (e.g. "me.cloudflareaccess.com",
|
||||||
|
// with or without https://) and the application's audience tag.
|
||||||
|
func NewAccess(teamDomain, audience string) (*Access, error) {
|
||||||
|
team := strings.TrimRight(strings.TrimPrefix(strings.TrimPrefix(teamDomain, "https://"), "http://"), "/")
|
||||||
|
if team == "" || audience == "" {
|
||||||
|
return nil, errors.New("ACCESS_TEAM_DOMAIN and ACCESS_AUD must both be set")
|
||||||
|
}
|
||||||
|
issuer := "https://" + team
|
||||||
|
return &Access{
|
||||||
|
Issuer: issuer,
|
||||||
|
Audience: audience,
|
||||||
|
CertsURL: issuer + "/cdn-cgi/access/certs",
|
||||||
|
Client: &http.Client{Timeout: 5 * time.Second},
|
||||||
|
now: time.Now,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Access) IsAdmin(_ http.ResponseWriter, r *http.Request) bool {
|
||||||
|
token := r.Header.Get(accessHeader)
|
||||||
|
if token == "" {
|
||||||
|
if c, err := r.Cookie(accessCookie); err == nil {
|
||||||
|
token = c.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if token == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if err := a.verify(token); err != nil {
|
||||||
|
log.Printf("[auth] access token refused: %v", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type jwtHeader struct {
|
||||||
|
Alg string `json:"alg"`
|
||||||
|
Kid string `json:"kid"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type jwtClaims struct {
|
||||||
|
Iss string `json:"iss"`
|
||||||
|
Aud json.RawMessage `json:"aud"` // a string or a list of strings
|
||||||
|
Exp int64 `json:"exp"`
|
||||||
|
Nbf int64 `json:"nbf"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Access) verify(token string) error {
|
||||||
|
parts := strings.Split(token, ".")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return errors.New("not a JWT")
|
||||||
|
}
|
||||||
|
var hdr jwtHeader
|
||||||
|
if err := decodeSegment(parts[0], &hdr); err != nil {
|
||||||
|
return fmt.Errorf("header: %w", err)
|
||||||
|
}
|
||||||
|
if hdr.Alg != "RS256" {
|
||||||
|
return fmt.Errorf("alg %q not allowed", hdr.Alg)
|
||||||
|
}
|
||||||
|
key, err := a.key(hdr.Kid)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("signature encoding: %w", err)
|
||||||
|
}
|
||||||
|
digest := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
|
||||||
|
if err := rsa.VerifyPKCS1v15(key, crypto.SHA256, digest[:], sig); err != nil {
|
||||||
|
return errors.New("bad signature")
|
||||||
|
}
|
||||||
|
|
||||||
|
var claims jwtClaims
|
||||||
|
if err := decodeSegment(parts[1], &claims); err != nil {
|
||||||
|
return fmt.Errorf("claims: %w", err)
|
||||||
|
}
|
||||||
|
if claims.Iss != a.Issuer {
|
||||||
|
return fmt.Errorf("issuer %q", claims.Iss)
|
||||||
|
}
|
||||||
|
if !audienceContains(claims.Aud, a.Audience) {
|
||||||
|
return errors.New("wrong audience")
|
||||||
|
}
|
||||||
|
now := a.now()
|
||||||
|
if claims.Exp == 0 || now.After(time.Unix(claims.Exp, 0).Add(clockTolerance)) {
|
||||||
|
return errors.New("expired")
|
||||||
|
}
|
||||||
|
if claims.Nbf != 0 && now.Add(clockTolerance).Before(time.Unix(claims.Nbf, 0)) {
|
||||||
|
return errors.New("not yet valid")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Access) key(kid string) (*rsa.PublicKey, error) {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
|
||||||
|
stale := a.now().Sub(a.fetchedAt) > keyCacheTTL
|
||||||
|
k, ok := a.keys[kid]
|
||||||
|
if ok && !stale {
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
if !stale && a.now().Sub(a.fetchedAt) < keyRefetchGap {
|
||||||
|
return nil, fmt.Errorf("unknown key id %q", kid)
|
||||||
|
}
|
||||||
|
keys, err := a.fetchKeys()
|
||||||
|
if err != nil {
|
||||||
|
if ok { // keep serving the cached key if the refresh failed
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
a.keys, a.fetchedAt = keys, a.now()
|
||||||
|
if k, ok = keys[kid]; !ok {
|
||||||
|
return nil, fmt.Errorf("unknown key id %q", kid)
|
||||||
|
}
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Access) fetchKeys() (map[string]*rsa.PublicKey, error) {
|
||||||
|
resp, err := a.Client.Get(a.CertsURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fetching access certs: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("fetching access certs: status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Keys []struct {
|
||||||
|
Kid string `json:"kid"`
|
||||||
|
Kty string `json:"kty"`
|
||||||
|
N string `json:"n"`
|
||||||
|
E string `json:"e"`
|
||||||
|
} `json:"keys"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||||
|
return nil, fmt.Errorf("decoding access certs: %w", err)
|
||||||
|
}
|
||||||
|
keys := map[string]*rsa.PublicKey{}
|
||||||
|
for _, k := range body.Keys {
|
||||||
|
if k.Kty != "RSA" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
n, err1 := base64.RawURLEncoding.DecodeString(k.N)
|
||||||
|
e, err2 := base64.RawURLEncoding.DecodeString(k.E)
|
||||||
|
if err1 != nil || err2 != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
keys[k.Kid] = &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}
|
||||||
|
}
|
||||||
|
if len(keys) == 0 {
|
||||||
|
return nil, errors.New("access certs contained no RSA keys")
|
||||||
|
}
|
||||||
|
return keys, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeSegment(seg string, v any) error {
|
||||||
|
b, err := base64.RawURLEncoding.DecodeString(seg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return json.Unmarshal(b, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func audienceContains(raw json.RawMessage, want string) bool {
|
||||||
|
var one string
|
||||||
|
if json.Unmarshal(raw, &one) == nil {
|
||||||
|
return one == want
|
||||||
|
}
|
||||||
|
var many []string
|
||||||
|
if json.Unmarshal(raw, &many) == nil {
|
||||||
|
for _, a := range many {
|
||||||
|
if a == want {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/rsa"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"math/big"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testAud = "aud-tag-123"
|
||||||
|
|
||||||
|
type accessFixture struct {
|
||||||
|
key *rsa.PrivateKey
|
||||||
|
kid string
|
||||||
|
server *httptest.Server
|
||||||
|
fetches atomic.Int32
|
||||||
|
checker *Access
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAccessFixture(t *testing.T) *accessFixture {
|
||||||
|
t.Helper()
|
||||||
|
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
f := &accessFixture{key: key, kid: "k1"}
|
||||||
|
f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.fetches.Add(1)
|
||||||
|
b64 := base64.RawURLEncoding.EncodeToString
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{{
|
||||||
|
"kid": f.kid, "kty": "RSA",
|
||||||
|
"n": b64(key.N.Bytes()),
|
||||||
|
"e": b64(big.NewInt(int64(key.E)).Bytes()),
|
||||||
|
}}})
|
||||||
|
}))
|
||||||
|
t.Cleanup(f.server.Close)
|
||||||
|
|
||||||
|
c, err := NewAccess("team.example.com", testAud)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c.CertsURL = f.server.URL
|
||||||
|
f.checker = c
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *accessFixture) sign(t *testing.T, alg, kid string, claims map[string]any) string {
|
||||||
|
t.Helper()
|
||||||
|
enc := func(v any) string {
|
||||||
|
b, _ := json.Marshal(v)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(b)
|
||||||
|
}
|
||||||
|
signing := enc(map[string]string{"alg": alg, "kid": kid}) + "." + enc(claims)
|
||||||
|
digest := sha256.Sum256([]byte(signing))
|
||||||
|
sig, err := rsa.SignPKCS1v15(rand.Reader, f.key, crypto.SHA256, digest[:])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return signing + "." + base64.RawURLEncoding.EncodeToString(sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
func goodClaims() map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"iss": "https://team.example.com",
|
||||||
|
"aud": []string{testAud},
|
||||||
|
"exp": time.Now().Add(time.Hour).Unix(),
|
||||||
|
"nbf": time.Now().Add(-time.Minute).Unix(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func reqWithHeader(token string) *http.Request {
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/jobs/", nil)
|
||||||
|
if token != "" {
|
||||||
|
r.Header.Set(accessHeader, token)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAccessAcceptsValidToken(t *testing.T) {
|
||||||
|
f := newAccessFixture(t)
|
||||||
|
if !f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(f.sign(t, "RS256", f.kid, goodClaims()))) {
|
||||||
|
t.Fatal("valid token refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAccessAcceptsCookie(t *testing.T) {
|
||||||
|
f := newAccessFixture(t)
|
||||||
|
r := reqWithHeader("")
|
||||||
|
r.AddCookie(&http.Cookie{Name: accessCookie, Value: f.sign(t, "RS256", f.kid, goodClaims())})
|
||||||
|
if !f.checker.IsAdmin(httptest.NewRecorder(), r) {
|
||||||
|
t.Fatal("valid cookie refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAccessAcceptsStringAudience(t *testing.T) {
|
||||||
|
f := newAccessFixture(t)
|
||||||
|
c := goodClaims()
|
||||||
|
c["aud"] = testAud
|
||||||
|
if !f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(f.sign(t, "RS256", f.kid, c))) {
|
||||||
|
t.Fatal("string aud refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAccessRefuses(t *testing.T) {
|
||||||
|
f := newAccessFixture(t)
|
||||||
|
other, _ := rsa.GenerateKey(rand.Reader, 2048)
|
||||||
|
|
||||||
|
cases := map[string]func() string{
|
||||||
|
"no token": func() string { return "" },
|
||||||
|
"garbage": func() string { return "a.b.c" },
|
||||||
|
"wrong audience": func() string {
|
||||||
|
c := goodClaims()
|
||||||
|
c["aud"] = []string{"someone-else"}
|
||||||
|
return f.sign(t, "RS256", f.kid, c)
|
||||||
|
},
|
||||||
|
"wrong issuer": func() string {
|
||||||
|
c := goodClaims()
|
||||||
|
c["iss"] = "https://evil.example.com"
|
||||||
|
return f.sign(t, "RS256", f.kid, c)
|
||||||
|
},
|
||||||
|
"expired": func() string {
|
||||||
|
c := goodClaims()
|
||||||
|
c["exp"] = time.Now().Add(-time.Hour).Unix()
|
||||||
|
return f.sign(t, "RS256", f.kid, c)
|
||||||
|
},
|
||||||
|
"not yet valid": func() string {
|
||||||
|
c := goodClaims()
|
||||||
|
c["nbf"] = time.Now().Add(time.Hour).Unix()
|
||||||
|
return f.sign(t, "RS256", f.kid, c)
|
||||||
|
},
|
||||||
|
"alg none": func() string { return f.sign(t, "none", f.kid, goodClaims()) },
|
||||||
|
"unknown kid": func() string { return f.sign(t, "RS256", "k2", goodClaims()) },
|
||||||
|
"wrong key": func() string {
|
||||||
|
saved := f.key
|
||||||
|
f.key = other
|
||||||
|
defer func() { f.key = saved }()
|
||||||
|
return f.sign(t, "RS256", f.kid, goodClaims())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, mk := range cases {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
if f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(mk())) {
|
||||||
|
t.Fatal("accepted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAccessCachesKeys(t *testing.T) {
|
||||||
|
f := newAccessFixture(t)
|
||||||
|
tok := f.sign(t, "RS256", f.kid, goodClaims())
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(tok))
|
||||||
|
}
|
||||||
|
// Unknown kids right after a fetch must not hammer the certs endpoint.
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
f.checker.IsAdmin(httptest.NewRecorder(), reqWithHeader(f.sign(t, "RS256", "nope", goodClaims())))
|
||||||
|
}
|
||||||
|
if n := f.fetches.Load(); n != 1 {
|
||||||
|
t.Fatalf("certs fetched %d times, want 1", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewAccessNeedsConfig(t *testing.T) {
|
||||||
|
if _, err := NewAccess("", testAud); err == nil {
|
||||||
|
t.Fatal("empty team accepted")
|
||||||
|
}
|
||||||
|
if _, err := NewAccess("team.example.com", ""); err == nil {
|
||||||
|
t.Fatal("empty aud accepted")
|
||||||
|
}
|
||||||
|
c, _ := NewAccess("https://team.example.com/", testAud)
|
||||||
|
if c.Issuer != "https://team.example.com" {
|
||||||
|
t.Fatalf("issuer %q", c.Issuer)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
// ==UserScript==
|
// ==UserScript==
|
||||||
// @name Job tracker capture
|
// @name Job tracker capture
|
||||||
// @namespace https://www.adam-french.co.uk/
|
// @namespace https://www.adam-french.co.uk/
|
||||||
// @version 2.1.0
|
// @version 2.2.0
|
||||||
// @description Add the job posting you are looking at to the tracker at /jobs/.
|
// @description Add the job posting you are looking at to the tracker at /jobs/.
|
||||||
// @match *://*/*
|
// @match *://*/*
|
||||||
// @noframes
|
// @noframes
|
||||||
@@ -10,11 +10,12 @@
|
|||||||
// @grant GM_getValue
|
// @grant GM_getValue
|
||||||
// @grant GM_setValue
|
// @grant GM_setValue
|
||||||
// @grant GM_registerMenuCommand
|
// @grant GM_registerMenuCommand
|
||||||
|
// @connect priv.adam-french.co.uk
|
||||||
// @connect www.adam-french.co.uk
|
// @connect www.adam-french.co.uk
|
||||||
// @connect adam-french.co.uk
|
// @connect adam-french.co.uk
|
||||||
// @connect localhost
|
// @connect localhost
|
||||||
// @downloadURL https://www.adam-french.co.uk/jobs/job-capture.user.js
|
// @downloadURL https://priv.adam-french.co.uk/jobs/job-capture.user.js
|
||||||
// @updateURL https://www.adam-french.co.uk/jobs/job-capture.user.js
|
// @updateURL https://priv.adam-french.co.uk/jobs/job-capture.user.js
|
||||||
// ==/UserScript==
|
// ==/UserScript==
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -49,7 +50,7 @@
|
|||||||
(function () {
|
(function () {
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
const DEFAULT_BASE = "https://www.adam-french.co.uk/jobs/api";
|
const DEFAULT_BASE = "https://priv.adam-french.co.uk/jobs/api";
|
||||||
|
|
||||||
// Hosts where the button appears unprompted. Add an ATS here when one turns
|
// Hosts where the button appears unprompted. Add an ATS here when one turns
|
||||||
// up; nothing else needs to change, because the fields are read by Claude
|
// up; nothing else needs to change, because the fields are read by Claude
|
||||||
@@ -124,8 +125,13 @@
|
|||||||
// with routes under /jobs/capture. It is now its own app at <site>/jobs/api
|
// with routes under /jobs/capture. It is now its own app at <site>/jobs/api
|
||||||
// with routes under /capture, so a base saved by an older version is moved
|
// with routes under /capture, so a base saved by an older version is moved
|
||||||
// across rather than left pointing at routes that no longer exist.
|
// across rather than left pointing at routes that no longer exist.
|
||||||
|
// From 2.2.0 the tracker is on its own host, priv.<site>, so a saved
|
||||||
|
// www/apex base is moved there too (www now only 301s, which drops a POST).
|
||||||
function migrateBase(base) {
|
function migrateBase(base) {
|
||||||
return base.replace(/\/api$/, "/jobs/api").replace(/\/jobs\/jobs\/api$/, "/jobs/api");
|
return base
|
||||||
|
.replace(/\/api$/, "/jobs/api")
|
||||||
|
.replace(/\/jobs\/jobs\/api$/, "/jobs/api")
|
||||||
|
.replace(/^https:\/\/(www\.)?adam-french\.co\.uk\/jobs\/api$/, DEFAULT_BASE);
|
||||||
}
|
}
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
|
|||||||
Reference in New Issue
Block a user