# Lab — SSH keys, DigitalOcean and Cloudflare tokens and signed R2 access

**Time:** 120 minutes — 10 setup, 80 core, 20 evidence, 10 teardown. The Droplet and the two panel token creations are the long poles, so start them early. The presigned-URL proof needs a 60-second wait; do the register while it runs.

**Prerequisite:** the S1 account and SSH key, the S4 Worker sample and R2 subscription, and the lesson above. You need a terminal, a browser, and the `doctl`, `wrangler`, `aws`, `jq` and `openssl` command-line tools. The sample project lives at `course/samples/s4-worker-catalogue/` in this repository.

**You need to know:** a credential is a scoped capability — scope, clock, custody, revocation and audit. Deleting a key from an account is not revoking it on a host. A presigned URL is a bearer capability until its expiry and cannot be revoked per URL. A Worker holds its signing key in a secret store that you cannot read back. The five credential classes are SSH key pair, DigitalOcean personal access token, Cloudflare API token, R2 API key pair and Worker secret; "token" unqualified is banned.

**Safe-data acknowledgement:** I have read the lab safe-data policy. I will use only the course-supplied synthetic media, I will keep every credential out of the repository, and I will not upload real personal media to any cloud service.

## What you build

| Piece | Name | What it is for |
|---|---|---|
| Credential inventory | `data/credential-inventory.json` | Every credential S1–S7 with scope, clock, custody, revocation and audit |
| Throwaway Droplet | `course-<id>-s7` | The host used to prove what SSH revocation actually means |
| SSH key pair | `course-s7-rotate` | A second, passphrase-protected key added to the host and then revoked |
| DigitalOcean token | `course-s7-read` | `droplet:read` + `account:read`; proves a denied delete |
| R2 bucket | `course-s7-vault` | Private; holds the catalogue and the signed file |
| R2 API key pair | `course-s7-vault-read` | Object Read, bucket-scoped; signs a 60-second URL |
| Worker | `course-s7-capability` | A copy of the S4 sample holding `SIGNING_KEY` |
| Cloudflare API token | `course-s7-worker-editor` | Workers Scripts → Edit, created with Individual Workers → `course-s7-capability`; rotates the secret, refused R2, but the Worker clause was not enforced |
| Register | `data/register-template.json` | Five residual-risk rows, R01–R05 |

Work in a scratch directory outside the repository so that `node_modules` and `.dev.vars` can never be committed:

```bash
export S7_ID=<your-id>
export NAME=course-${S7_ID}-s7
```

`S7_ID` is a short identifier you invent (for example the last four digits of your student number). `NAME` is the Droplet's name; the tag on the Droplet uses the same identifier. The name is not a secret — it is how you find your own resources in a shared team.

## 1. Pre-flight: check the tools and the account

Console: **DigitalOcean → Account → API** shows your S1 token; **Cloudflare → R2 → Overview** shows the subscription S4 created. You do not need to change either one yet.

```bash
cd <path-to-repository>/course/weeks/07-security-identity
```

Start in this week's folder. Every relative path in the lab — `remote.sh`, `data/`, the sample — is resolved from here unless a step says otherwise.

```bash
doctl version
npx wrangler --version
aws --version
ssh -V
```

These four commands fail fast if a tool is missing or too old. `doctl` must be 2.4.0 or newer, Wrangler 4.69 or newer, the `aws` command-line tool v2 (the `aws s3 presign` spelling differs between v1 and v2), and OpenSSH anything from the last decade. None of them contacts a cloud service, so they cost nothing.

```bash
doctl account get
npx wrangler whoami
```

`doctl account get` proves your S1 token still works and prints the team you are spending from — check it is yours, not a classmate's. `npx wrangler whoami` prints the Cloudflare email and account id and lists the OAuth token's scopes; if it reports that you are not logged in, run `npx wrangler login` once and complete the browser flow. Copy the account id from this output into a variable so the S3 endpoint later resolves:

```bash
read -r CF_ACCOUNT_ID
export CLOUDFLARE_ACCOUNT_ID="$CF_ACCOUNT_ID"
```

`read` waits for you to paste the account id and press Enter; the export publishes it to the tools. The account id is not a secret — it appears in every request URL — but keeping it in a variable stops typos in the endpoint.

Copy the sample into a scratch directory and install its dependencies. The install is the slowest step of setup; it runs while you read the rest of the section.

```bash
cp -R ../../samples/s4-worker-catalogue "$HOME/s7-capability"
cd "$HOME/s7-capability"
npm install
```

`cp -R` copies the S4 sample without its `node_modules` (the sample's `.gitignore` excludes them). `npm install` reads `package.json` and installs Wrangler and Vitest locally, so every later `npx wrangler` uses the pinned version rather than whatever is newest.

```bash
npm test
```

The sample ships eight behaviour tests. They run offline against a fake R2 binding and must all pass; if any fail, the copy is damaged or the Node version is wrong (Node 22.12 or newer). Fix that before spending money.

```bash
sed -i.bak -e 's/^name = .*/name = "course-s7-capability"/' -e 's/^bucket_name = .*/bucket_name = "course-s7-vault"/' wrangler.toml
```

This rewrites the two identity lines of the sample's configuration: the Worker's name becomes `course-s7-capability` and its R2 binding points at the private vault you are about to create. The `.bak` suffix is the portable form of the in-place edit and leaves the original beside it. Read the result to confirm both lines changed:

```bash
grep -E '^(name|bucket_name)' wrangler.toml
```

## 2. Inventory the credentials you already hold

The first control is knowing what exists. This step finds credential-shaped strings in the repository and checks where the values actually live.

```bash
cd <path-to-repository>/course/weeks/07-security-identity
```

Return to this week's folder in the repository (the previous section left you in `$HOME/s7-capability`). The week folder holds the data files the notebook reads.

```bash
git grep -nE 'dop_v1_[A-Fa-f0-9]{32,}|(SIGNING_KEY|ACCESS_KEY|SECRET_ACCESS_KEY)[[:space:]]*=[[:space:]]*[A-Za-z0-9]{20,}' -- . ':!*.example' || echo "no credential material in tracked files"
```

`git grep` searches only files git tracks, matching two credential-shaped patterns: a DigitalOcean token-looking value, and an assignment of a long literal to a secret-named variable. The `':!*.example'` excludes template files that are supposed to contain placeholder names. The `|| echo` turns git's "no matches" exit status into a readable line; either way the evidence is the absence of a hit. A hit is not automatically a leak — `SIGNING_KEY` as a variable *name* is fine, a value is not — so read any hit before panicking.

```bash
ls -l "$HOME/Library/Application Support/doctl/config.yaml"
```

Print the permission bits and path of the file where `doctl` stored your S1 token. macOS puts it under `~/Library/Application Support/doctl/`; on Linux the same file is `~/.config/doctl/config.yaml`, so the Linux form is `ls -l ~/.config/doctl/config.yaml`. The first field must read `-rw-------` (600): only your user may read the token file. If it does not, `chmod 600` it before going further.

```bash
doctl compute ssh-key list
```

List every SSH public key registered on the DigitalOcean team, with its id, fingerprint and name. This is the account's copy of the keys, and it is *not* where a Droplet decides who may log in — that is the distinction the next step drills. Note the id of the key you created in S1 (its name is usually `course-s1-<id>`); you will pass it to the Droplet.

Open `data/credential-inventory.json` and fill in the placeholders for your own account. Do not paste secret values into it: record where each value lives (file path, environment variable, secret store), never the value. The notebook validates this file in step 7.

## 3. SSH custody: the key delete that changes nothing

This is the centrepiece of the session. You create a throwaway host, add a second key, delete that key from the DigitalOcean *account*, and discover that login still works — because the account's key list is not the host's trust store.

```bash
export S1_KEY_ID=<s1-key-id>
```

Set the id of the key you created in S1 (`doctl compute ssh-key list` shows it). This is the *provisioning* decision for the host: the key is injected into `authorized_keys` once, at Droplet creation.

Console path: **Droplets → Create Droplet**, choose Rocky Linux 10, the SGP1 region, the `s-1vcpu-1gb` size, your S1 SSH key, and the tags `course:42-05-0112`, `student:<id>`, `week:7`.

```bash
export DROPLET_ID=$(doctl compute droplet create "$NAME" --region sgp1 --image rockylinux-10-x64 --size s-1vcpu-1gb --ssh-keys "$S1_KEY_ID" --tag-names "course:42-05-0112,student:$S7_ID,week:7" --wait --format ID --no-header | tail -1)
```

The command creates one 1 GB Droplet in Singapore, installs your S1 public key into `root`'s `authorized_keys` at boot, and waits for it to become active before printing the id. `--ssh-keys "$S1_KEY_ID"` is the only credential the host will trust; `--tag-names` makes the Droplet findable and is how teardown scripts know what belongs to the course. The `$(...)` captures the printed id into `DROPLET_ID`; `tail -1` guards against a stray banner line.

```bash
export IP=$(doctl compute droplet get "$DROPLET_ID" --format PublicIPv4 --no-header)
```

```bash
ssh -i "$HOME/.ssh/do_s1" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o ConnectionAttempts=60 root@$IP 'true'
```

Wait until the host is reachable and record its key. A Droplet reports `active` when the hypervisor has it scheduled, which is often twenty to sixty seconds before `sshd` accepts connections; `ConnectTimeout` and `ConnectionAttempts` make ssh retry instead of failing on the first refusal. `StrictHostKeyChecking=accept-new` records the host fingerprint on first contact instead of prompting, so every later `ssh` and `scp` trusts it. The remote command is just `true`: this step proves reachability, not the key you meant to test.

```bash
scp -i "$HOME/.ssh/do_s1" -o StrictHostKeyChecking=accept-new remote.sh root@$IP:/root/remote.sh
```

Copy this week's `remote.sh` to the host. It is the small script that performs the three `authorized_keys` operations the drill needs; keeping them in one reviewed file means every change to the host's trust store is a named, repeatable command rather than an ad-hoc edit you might mistype.

```bash
ssh -i "$HOME/.ssh/do_s1" root@$IP 'bash /root/remote.sh identity'
```

Run the script's `identity` action: hostname, user id, and the number of lines in `authorized_keys`. It proves you reached the host and are root, and one line means exactly one key is trusted. There is no password prompt; a key-only login is the evidence.

```bash
ssh -i "$HOME/.ssh/do_s1" root@$IP 'bash /root/remote.sh list-authorized'
```

Print the key type and comment of each trusted line. The comment is the human label at the end of the public key — for the S1 key it is usually the key's name. This is your "before" picture; keep the output for the evidence bundle.

Now create the rotation key. It is a *second* key, not a replacement: the S1 key stays trusted throughout, which is what makes the revocation test meaningful.

```bash
ssh-keygen -t ed25519 -C "course-s7-rotate" -f "$HOME/.ssh/do_s7_rotate"
```

`ssh-keygen` creates an ed25519 key pair at `~/.ssh/do_s7_rotate` (private) and `~/.ssh/do_s7_rotate.pub` (public). It asks for a passphrase: use one, because the point of this key is that its private half is protected in a way the S1 key may not be. The `-C` comment is how you will recognise the line later. The command refuses to overwrite an existing file — that is a safety feature, so delete the old pair deliberately if you are repeating the lab.

```bash
chmod 600 "$HOME/.ssh/do_s7_rotate"
```

`chmod 600` makes the private key readable only by you. OpenSSH refuses to use a private key that is group- or world-readable, and a key file readable by other users on a shared laptop is a custody failure even if it never leaves the machine.

```bash
ssh-keygen -lf "$HOME/.ssh/do_s7_rotate.pub"
ssh-keygen -E md5 -lf "$HOME/.ssh/do_s7_rotate.pub"
```

Print the key's fingerprint twice: the default SHA-256 form and the legacy MD5 form. Panels and older tools still show MD5, so an operator comparing fingerprints needs both. Record both in the evidence bundle; the fingerprint is how you prove *which* key a panel row refers to without copying the key itself.

```bash
doctl compute ssh-key import course-s7-rotate --public-key-file "$HOME/.ssh/do_s7_rotate.pub"
```

Console path: **Account → Security → SSH Keys → Add SSH Key**, paste the `.pub` contents, name it `course-s7-rotate`.

Register the public key on the DigitalOcean account. This makes it available to *future* Droplets at creation time. It does **not** put the key on your running Droplet — a Droplet only reads its own `authorized_keys`, and nothing remotely edits that file for you. That gap is the whole lesson.

```bash
ssh -i "$HOME/.ssh/do_s1" root@$IP 'bash /root/remote.sh append-key' < "$HOME/.ssh/do_s7_rotate.pub"
```

Append the new public key to the running host's `authorized_keys`, feeding it over stdin so the private key never leaves the laptop and the public key never lands in a repository. This is the step that actually grants access.

```bash
ssh -i "$HOME/.ssh/do_s7_rotate" -o PreferredAuthentications=publickey root@$IP 'bash /root/remote.sh identity'
```

Log in with the new key. `PreferredAuthentications=publickey` forbids password fallback, so success proves the key itself was accepted, not some other mechanism. Keep this output: it is your "second key works" evidence.

```bash
doctl compute ssh-key list --format ID,Name --no-header | awk '$2=="course-s7-rotate"{print $1}'
```

Find the account-side id of the rotation key. The `awk` filter matches the second column (the name) and prints the first (the id); do not guess the id from another row.

```bash
export ROTATE_KEY_ID=$(doctl compute ssh-key list --format ID,Name --no-header | awk '$2=="course-s7-rotate"{print $1}')
```

Store that id in a variable, then delete the key from the account:

```bash
doctl compute ssh-key delete "$ROTATE_KEY_ID" --force
```

**False revocation.** Now try the login again, without changing anything on the host:

```bash
ssh -i "$HOME/.ssh/do_s7_rotate" -o PreferredAuthentications=publickey root@$IP 'bash /root/remote.sh identity'
```

It still works. The account delete removed the key from the *menu of keys offered at Droplet creation*; it did not reach into a running machine and delete a line from `/root/.ssh/authorized_keys`. Anyone who told you "we deleted the key, so the contractor is locked out" has not revoked anything on existing hosts. Capture this output — it is the most important screenshot of the lab.

```bash
ssh -i "$HOME/.ssh/do_s1" root@$IP 'bash /root/remote.sh remove-key course-s7-rotate'
```

**Real revocation.** Use the retained S1 key to remove every `authorized_keys` line carrying the rotation key's comment. That is the only operation that changes what the host will accept.

```bash
ssh -i "$HOME/.ssh/do_s7_rotate" -o PreferredAuthentications=publickey -o BatchMode=yes root@$IP 'bash /root/remote.sh identity'
```

Retry the rotation key's login. `BatchMode=yes` stops ssh from prompting for a passphrase or password, so a failure is a clean `Permission denied (publickey)` and exit status 255. That denial *is* the success condition here: an expected failure, not a broken lab.

```bash
ssh -i "$HOME/.ssh/do_s1" root@$IP 'bash /root/remote.sh identity'
```

Log in with the retained S1 key to prove you did not lock yourself out. If this succeeds while the rotation key fails, the revocation was surgical: one key line removed, the other untouched. Write both outputs into the evidence bundle.

## 4. A read-only token and a named denial

Console path: **Account → API → Tokens → Generate New Token**. Give it the name `course-s7-read`, choose **Custom Scopes**, tick only `droplet:read` and `account:read`, set the expiration to 30 days, and copy the token once — the panel will not show it again.

```bash
read -rs DO_READ_TOKEN
```

Read the token into a variable without echoing it to the terminal (`-s`) or adding a newline (`-r`). Nothing is written to disk, so the token's only home is this shell; closing the terminal ends it.

```bash
export DIGITALOCEAN_ACCESS_TOKEN="$DO_READ_TOKEN"
```

`doctl` reads `DIGITALOCEAN_ACCESS_TOKEN` before it reads the config file, so this export switches the CLI from your broad S1 token to the read-only one for the rest of the shell. The config file is untouched, which is why you can switch back with `unset` later.

```bash
doctl account get
```

The account read succeeds because the token carries `account:read`. Seeing the team name here is not a failure — a read-only token is supposed to be able to look.

```bash
doctl compute droplet delete "$DROPLET_ID" --force
```

This must be refused with HTTP 403 and a non-zero exit status. The token can read droplets and cannot delete them, because DigitalOcean scopes are per action: `droplet:read` does not imply `droplet:delete`. The error body names the missing scope and contains no secret, so it is safe to screenshot. Do not "fix" the denial by minting a `droplet:*` token; if a job needs a delete, mint a token that can delete only what that job names.

```bash
echo "delete exit=$?"
```

Print the exit status immediately — `$?` is overwritten by the next command, so it only means anything on this line. A non-zero value here, right after a 403, is your proof that the CLI treated the denial as failure.

```bash
doctl compute droplet list --format ID,Name
```

List the droplets with the read-only token to show the Droplet is still there. The denial changed nothing.

```bash
unset DIGITALOCEAN_ACCESS_TOKEN
```

Drop the read-only token from the environment so the next `doctl` call uses your S1 token from the config again. Also `unset DO_READ_TOKEN` when you have finished capturing evidence.

## 5. A private bucket and a 60-second capability

The bucket is private from the start: no custom domain, no `r2.dev` toggle, no public URL. Access happens only through a credential you scope to this one bucket.

```bash
npx wrangler r2 bucket create course-s7-vault
```

Console path: **R2 → Create bucket**, name `course-s7-vault`, leave the public-access options off.

Create the bucket. R2 needs the subscription checkout from S4; if the command reports that R2 is not enabled, complete that checkout in the panel first.

```bash
npx wrangler r2 object put course-s7-vault/catalogue.json --file data/catalogue.json --remote
npx wrangler r2 object put course-s7-vault/files/asset-0001.txt --file data/files/asset-0001.txt --remote --content-type text/plain
```

Upload the two objects the Worker needs: the catalogue index and the one synthetic asset file. `--remote` means the real bucket, not Wrangler's local emulation; `--content-type` sets the type the Worker will serve back. Both files are course-authored synthetic data — no client footage.

Console path: **R2 → course-s7-vault → Create R2 API Token**. Choose **Object Read**, and under **Specify bucket** pick `course-s7-vault` only. Copy the access key id and secret access key. This pair is the fourth credential class: it is not a Cloudflare API token and cannot manage the account; it can only read objects in that one bucket.

```bash
read -rs R2_ACCESS_KEY_ID
read -rs R2_SECRET_ACCESS_KEY
```

Read both values without echo. The secret is shown exactly once in the panel; if you lose it, delete the token and make another.

```bash
export AWS_ACCESS_KEY_ID="$R2_ACCESS_KEY_ID"
export AWS_SECRET_ACCESS_KEY="$R2_SECRET_ACCESS_KEY"
export AWS_DEFAULT_REGION=auto
```

The `aws` CLI speaks S3's signature protocol, and R2 implements it. These three exports point the CLI at the key pair and at R2's expected `auto` region. The values live only in this shell.

```bash
export R2_ENDPOINT="https://${CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com"
```

Build the S3-compatible endpoint from your account id, which you exported in step 1.

```bash
aws s3api head-object --bucket course-s7-vault --key files/asset-0001.txt --endpoint-url "$R2_ENDPOINT"
```

`head-object` fetches the object's metadata without the body. Success proves the bucket-scoped key can read exactly this bucket, and prints the size, ETag and content type you can compare with the upload.

```bash
URL=$(aws s3 presign s3://course-s7-vault/files/asset-0001.txt --endpoint-url "$R2_ENDPOINT" --expires-in 60)
```

Create a presigned GET URL valid for 60 seconds. Presigning is a **local** computation: the CLI signs the request with the secret key and never calls R2. That is why the signing key can produce a URL for an operation it would be denied at use time — the denial happens when the URL is fetched, not when it is made. `--expires-in 60` is the control; `aws s3 presign` produces GET only.

```bash
curl -s -o /dev/null -w 'before: %{http_code}\n' "$URL"
```

Fetch the URL immediately. `-o /dev/null` discards the body, `-w` prints only the HTTP status. Expect `before: 200`: the signature is valid and the clock has not run out.

```bash
sleep 61
```

Wait past the expiry. The extra second avoids a boundary race: the URL expires at whole-second granularity.

```bash
curl -s -o /dev/null -w 'after:  %{http_code}\n' "$URL"
```

The same URL, after expiry. Expect `after: 403`. Nothing about the object changed and the bucket is still private; only the clock passed. Note what you cannot do: there is no per-URL revocation. Deleting a URL somebody already holds is impossible, which is why a short TTL is the only control you actually have.

## 6. Rotate a Worker secret under a one-Worker token

Console path: **Workers & Pages → Create → Worker** shows the S4 sample you are copying. You do not create it here; you deploy the copy with Wrangler, then use a narrowly scoped token to rotate its secret.

```bash
OLD_KEY=$(openssl rand -hex 32)
```

Generate 32 random bytes as 64 hex characters. This is the Worker's HMAC key for the first signature; `$(...)` captures it into a shell variable so it is never printed to the terminal or written to a file.

```bash
printf '%s' "$OLD_KEY" | npx wrangler secret put SIGNING_KEY
```

Store the value as a Worker secret. `printf` avoids the trailing newline that `echo` would add — a newline would become part of the key and make every signature wrong. `secret put` encrypts the value into the Worker's secret store, creates a new version, and deploys it immediately. You cannot read the value back; `wrangler secret list` shows names only.

```bash
sleep 5
```

Wait five seconds. A secret change propagates across Cloudflare's edge in a few seconds; calling the Worker in the same instant can still hit an instance holding the previous version, which looks like a bad signature. The wait makes the next check deterministic.

```bash
WORKER_HOST=$(npx wrangler deploy 2>&1 | tee /tmp/s7-deploy.log | grep -oE 'https://[a-z0-9.-]+\.workers\.dev' | tail -1)
```

Deploy the Worker and capture its `workers.dev` hostname. `2>&1` merges Wrangler's output into the pipe, `tee` keeps a log, and the `grep` extracts the first `https://….workers.dev` URL. The Worker is public at that hostname, which is why its only access control is the signature on `/asset/:id/file` — the catalogue and health routes are deliberately readable.

```bash
sleep 5
```

Give the deployment the same few seconds to reach the edge before the health check.

```bash
curl -s "$WORKER_HOST/health"
```

Read the health route. It must report `"ok":true` and a non-zero asset count, which proves the R2 binding points at the bucket you filled and the catalogue parsed.

```bash
OLD_URL=$(SIGNING_KEY="$OLD_KEY" node scripts/sign.mjs asset-0001 "$WORKER_HOST" 60)
```

Mint a signed URL for `asset-0001` using the old key. The script computes an HMAC over the asset id and the expiry, exactly as the Worker verifies it. `SIGNING_KEY=` on the command line sets the variable for this one process only.

```bash
curl -s -o /dev/null -w 'old key: %{http_code}\n' "$OLD_URL"
```

Expect `200`: the URL and the Worker share the same secret.

Console path: **Manage Account → Account API Tokens → Create Token → Custom token**. Permissions: **Account → Workers Scripts → Edit**. Resources: **Include → Individual Workers → `course-s7-capability`**. Set a short expiry and copy the token.

```bash
read -rs CF_WORKER_TOKEN
```

Read the token and your account id. The account id is not a secret (`wrangler whoami` prints it), but keeping it in a variable makes the later API call readable.

```bash
export CLOUDFLARE_API_TOKEN="$CF_WORKER_TOKEN"
```

`wrangler` prefers `CLOUDFLARE_API_TOKEN` over its stored OAuth login, so every command now acts as the scoped token. This is the *operating* credential: one Worker, secret rotation only. The broad OAuth login you used to deploy is the *provisioning* credential, and it could do anything in the account.

```bash
NEW_KEY=$(openssl rand -hex 32)
```

Generate the replacement key.

```bash
printf '%s' "$NEW_KEY" | npx wrangler secret put SIGNING_KEY
```

Rotate the secret with the one-Worker token. This succeeds because the token is Editor on this Worker.

```bash
sleep 5
```

The same propagation wait as before, so the next check cannot be a stale instance.

```bash
npx wrangler versions list
```

List the Worker's recent versions. Each `secret put` created a version; this list is the change record, and it is more reliable than trying to find the event in another system. Note that an older version still *contains* the older secret value — rolling back to it can resurrect a key you thought you had rotated out.

```bash
curl -s -o /dev/null -w 'old url: %{http_code}\n' "$OLD_URL"
```

The URL signed with the old key must now return `401`. Rotation is effective immediately for new requests: the Worker verifies against the new secret, and the old signature no longer matches.

```bash
NEW_URL=$(SIGNING_KEY="$NEW_KEY" node scripts/sign.mjs asset-0001 "$WORKER_HOST" 60)
```

Mint a URL with the new key.

```bash
curl -s -o /dev/null -w 'new key: %{http_code}\n' "$NEW_URL"
```

Expect `200`. Old 401 and new 200 together are the rotation proof.

```bash
npx wrangler secret list
```

List the secret *names* under the scoped token. It prints `SIGNING_KEY` and no value, which is the point: the operator can rotate without ever reading the secret.

```bash
curl -s -o /dev/null -w 'r2 with worker token: %{http_code}\n' -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/r2/buckets"
```

Ask the Workers token to list R2 buckets. This must return `403`. The token carries one permission family — Workers Scripts — so an R2 call is outside its scope and refused. That is the Cloudflare half of the blast-radius proof: a leaked token can rotate secrets on Workers and cannot touch the bucket that holds the media. If this returns `200`, your token is broader than this lab's contract; delete it and recreate it with only Workers Scripts → Edit.

```bash
curl -s -o /dev/null -w 'other worker secrets: %{http_code}\n' -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/workers/scripts/course-demo-catalogue/secrets"
```

Read the secret *names* of a different Worker with the same token. Record the status; do not assume. On the verified run for this course (2026-11-13) this returned `200` even though the token was created with **Individual Workers → `course-s7-capability`**: the resource clause did not narrow the Workers Scripts permission, and script creation was not stopped either. A scope is only real when the API enforces it — the label on the token is a claim, not a boundary. If your account has no second Worker, skip this check and cite the instructor's result in your register reasoning. Either way, the answer belongs in R02: the blast radius is what the API allows, not what the panel said.

**The finding.** The design for this lab assumed a per-Worker token would be denied operations on other Workers. The API does not enforce that on this account: the token listed and wrote another Worker's secrets. Treat the token as a Workers-wide credential and record the true blast radius — that is exactly the judgement the register exists to capture.

## 7. Read both audit surfaces

Console path: **Manage Account → Audit Logs**, filter to the last hour and look for R2 bucket create/delete, token administration and Worker events. Console path: **DigitalOcean → Settings → Security → Security History**, look for token and Droplet events.

```bash
npx wrangler versions list
```

Re-read the versions list as the audit record of the rotation. Cloudflare Audit Logs document administrative events and record R2 bucket operations; token and secret events are likely present but are not enumerated in the documentation, so the lab does not claim them. Object access is not in Audit Logs at all.

Capture, for the evidence bundle:

- a Cloudflare Audit Logs extract covering the last hour, with account ids and email addresses cropped;
- a DigitalOcean Security History screenshot covering the token creation, the Droplet creation and the denied delete attempt (the denial is a *failed* event and may or may not be listed — record what you actually see, not what you expect);
- one line of the `wrangler versions list` output showing the version created by the second `secret put`.

Write down the gap for each credential in the inventory: what the provider records automatically, and what you have to capture yourself because nothing does it for you.

## 8. Complete the credential inventory and the register

```bash
cd <path-to-repository>/course/weeks/07-security-identity
```

Return to the week folder so the notebook and the data files resolve.

Open `data/credential-inventory.json` and replace every `<placeholder>` with what your own panels and machine show: your student id, the date, the expiry you actually set on the Cloudflare token, and the scopes your S1 token really carries. Keep secrets out of it — record the location, never the value.

Open `data/register-template.json` and revise R03–R05 for your own deployment; keep R01 and R02 as the worked examples unless your situation differs. Each row needs a likelihood and impact (1–5), the existing control, a residual likelihood and impact, one clause of reasoning, a treatment and an owner.

Open `notebook.ipynb` and run all cells. It validates the inventory schema, models the presign cases, walks the scope matrix, steps the secret state machine and scores the register, and writes `security_results.json`. Every assertion must pass; a failure tells you which data row is wrong, and the fix is in the data, not in the notebook.

```bash
uv run python data/check-notebook.py
```

Run the same cells without a Jupyter kernel. Use this over SSH or when you want the assertions in your terminal; it executes the notebook top to bottom and stops at the first failure, and it is the check the reference runner uses. It must end with `notebook: all code cells passed`.

Write a 150–250 word *what this proves* note: what the account-key delete changed and did not change; why the presigned URL was reusable and unrevokable; why the old Worker URL stopped working at once; and which two residual risks you would defend to the unit, with one sentence each on why.

## Evidence bundle

Submit these ten items. Each is scored 3/2/1/0 against the rubric in `PLO.md`.

1. The completed `credential-inventory.json` and the pre-lab worksheet (the four questions answered for each credential: what can it reach, when does it stop, where does it live, what proves use).
2. The S1 and rotation key fingerprints in SHA-256 and MD5; `list-authorized` before and after; the still-working login after the account delete; the denied login after the `authorized_keys` removal; the retained S1 key's successful login.
3. The `course-s7-read` scope page with the token value redacted and the expiry visible, plus the `403` and exit status from the denied delete.
4. The private bucket's settings page, the bucket-scoped R2 key page, and the presign `200`/`403` with timestamps.
5. `wrangler secret list`; `wrangler versions list` before and after rotation; the old URL's `401` and the new URL's `200`; the R2 call refused with `403`; and the other-Worker secrets check with whatever status it actually returned.
6. The Cloudflare token page showing the permission and the resource clause, plus one sentence on whether the API enforced that clause.
7. The Cloudflare Audit Logs extract and the DigitalOcean Security History screenshot, with identifiers redacted.
8. The completed five-row register and the 200-word justification of the top two residual risks.
9. `security_results.json` and your command history for the session (a `script` capture or your terminal scrollback), with every token, account id and email removed before submission.
10. The teardown log, `doctl balance get`, and the 150–250 word note.

## Failure and recovery

The deliberate failures are the two denials and the expiry: the read-only token's delete returns 403, the URL returns 403 after 60 seconds, and the removed SSH key returns `Permission denied`. They are expected outputs; capture them.

The failure that catches people is the *missing* denial. If the read-only token can delete the Droplet, its scopes are wrong — delete the token and recreate it with only `droplet:read` and `account:read`, do not proceed. If the URL still returns 200 after 61 seconds, check the system clock and whether the URL was minted with a different `--expires-in`.

If `ssh` with the rotation key is denied *before* you removed any line, the `append-key` step did not run or the key file is not the one in `authorized_keys`: list the lines and compare the fingerprint. If you lock yourself out entirely, use the DigitalOcean web console, which authenticates through the panel rather than SSH; Rocky Linux has no root password reset, so the console is the only fallback.

If `wrangler secret put` returns an authentication error, check `wrangler whoami` — the scoped token may not include the Worker, or `CLOUDFLARE_ACCOUNT_ID` may be wrong. If the Worker deploys but `/health` reports 503, the R2 binding names a bucket that does not exist or the catalogue object is missing.

## Cost ceiling

**$0.03.** One `s-1vcpu-1gb` Droplet at $0.00893/hour with a one-hour minimum charge is about one cent; deleting and recreating it a couple of times stays under three cents. R2 (under 10 GB, free egress), Workers (under 100,000 requests/day) and the Cloudflare API are free on their free plans. There is no DNS change and no custom domain. Check `doctl balance get` at teardown.

## Teardown

```bash
unset CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID
```

Drop the scoped token so the Worker deletion runs as your OAuth login — the provisioning credential is the right one for deleting what it created.

```bash
npx wrangler delete course-s7-capability
```

Delete the Worker. Its secrets go with it; this is the real revocation of `SIGNING_KEY`.

```bash
npx wrangler r2 object delete course-s7-vault/catalogue.json --remote
npx wrangler r2 object delete course-s7-vault/files/asset-0001.txt --remote
```

Empty the bucket. `bucket delete` refuses a non-empty bucket, so these two commands are not optional.

```bash
npx wrangler r2 bucket delete course-s7-vault
```

Delete the bucket itself.

Console: delete the R2 API token `course-s7-vault-read`, the Cloudflare token `course-s7-worker-editor`, and the DigitalOcean token `course-s7-read`. These have no CLI/API deletion path in the student stack; the panel is the only route. Confirm the token lists no longer show them.

```bash
doctl compute droplet delete "$DROPLET_ID" --force
```

Delete the Droplet. The rotation key is already gone from the account (the drill deleted it) and from the host (the drill removed its line); the S1 key stays.

```bash
doctl compute droplet list --format ID,Name,Region,Status
```

Confirm no course Droplet is left running. An empty table is the teardown proof.

```bash
doctl balance get
```

Read the balance and compare it with the pre-lab figure. A charge above three cents means something survived teardown or was created twice.

```bash
rm -r "$HOME/s7-capability"
rm -f "$HOME/.ssh/do_s7_rotate" "$HOME/.ssh/do_s7_rotate.pub"
```

Remove the local copy of the sample and the rotation key pair. The private key is worthless now that its `authorized_keys` line is gone, but a private key on disk is still a custody liability. Leave the S1 key alone.

Record every deletion and the balance in the teardown log.

## Fallback

- **No R2 subscription.** Use the instructor's bucket and a student-created bucket-scoped key. Skip bucket creation; the presign proof and everything else is unchanged. A fallback that changes the evidence shape is a defect — say in your note that bucket creation was omitted and why.
- **No DigitalOcean account.** Use the instructor account slot. The Droplet and the token proofs are unchanged; the tag must carry your own id.
- **SSH blocked by the network.** Use the DigitalOcean web console for the login checks and the `remote.sh` commands; the evidence is the console screenshot instead of the terminal output, and the note says so.
- **Wrangler blocked.** Use the dashboard to deploy the sample and put the secret, and do the denied-create proof with the API call through `curl` — it needs no Node.
- **Cloudflare account blocked.** Use the instructor account; the Worker and the bucket are named with your id.

## Notebook

Open [the lab notebook](notebook.ipynb); it validates the credential inventory, models the presigned-URL decisions, walks the scope matrix, steps the secret state machine and scores the five-row register before you submit. It runs offline on the Python 3.14 standard library, reads this week's `data/` files, and writes `security_results.json`.
